text
stringlengths 10
2.72M
|
|---|
package prj.designpatterns.decorator.demo;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 继承FilterReader<br>
* 实现一个能过滤空白字符的输入流
*
* @author LuoXin
*
*/
public class TrimInputStream extends FilterInputStream {
protected TrimInputStream(InputStream in) {
super(in);
}
@Override
public int read() throws IOException {
int c = super.read();
if (c == -1 || !isSpaceChar(c)) {
// 如果已到EOF,或读入非空字符,正常返回
return c;
} else {
// 如果读入空白字符,返回0
return 0;
}
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int num = super.read(b, off, len);
if (num != -1) {
for (int i = 0; i < num;) {
if (isSpaceChar(b[i])) {
// 跳过空白字符(后面的字符前移)
for (int j = i, k = i + 1; k < num; j++, k++) {
b[j] = b[k];
}
num--;
} else {
i++;
}
}
// 将多余buffer清零
for (int i = num; i < b.length; i++) {
b[i] = 0;
}
}
return num;
}
/**
* 判断给定的字符是否为空白字符<br>
* 空白字符定义为空格、回车符、换行符、水平制表符、换页符
*
* @param c
* 要判断的字符
* @return 判断结果
*/
private static boolean isSpaceChar(int c) {
switch (c) {
case ' ':
case '\r':
case '\n':
case '\t':
case '\f':
return true;
default:
return false;
}
}
}
|
import java.awt.Color;
import java.awt.Graphics;
import java.io.*;
/**
* Write a description of class GamesHighScore here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class GamesHighScores {
private Graphics g;
private HighScore[] highScores = new HighScore[10];
private String name;
private int score;
private boolean shift = false;
private boolean enter = false;
private boolean ready = false;
public GamesHighScores(Graphics g) {
this.g = g;
new TextBox(this);
}
public void setName(String str) {
this.name = str;
ready = true;
}
public boolean ready() {
return ready;
}
public void highScores(int score) {
this.score = score;
load();
addHighScore(new HighScore(score, name));
save();
draw();
}
public void load() {
try {
FileInputStream fi = new FileInputStream("highScores.dat");
ObjectInputStream inzors = new ObjectInputStream(fi);
highScores = (HighScore[])inzors.readObject();
inzors.close();
}
catch(Exception e) {
}
}
public void save() {
try {
FileOutputStream fo = new FileOutputStream("highScores.dat");
ObjectOutputStream outzors = new ObjectOutputStream(fo);
outzors.writeObject(highScores);
outzors.close();
}
catch(Exception e) {
System.out.println("We have a error: " + e);
}
}
public void addHighScore(HighScore h) {
boolean found = false;
for(int i = 0; i < highScores.length && found == false; i++) {
if(highScores[i] == null) {
found = true;
highScores[i] = h;
} else if(highScores[i].compareTo(h) == -1) {
found = true;
for(int j = highScores.length - 1; j > i; j--) {
highScores[j] = highScores[j - 1];
}
highScores[i] = h;
}
}
}
public void draw() {
int h = 60;
int w = 60;
g.drawString("Highscores", h, w);
g.setColor(Color.RED);
for(int i = 0; i < highScores.length; i++) {
if(highScores[i] != null) {
h = h + 30;
g.drawString((highScores[i].getName() + " " + highScores[i].getScore()), w, h);
}
}
save();
}
}
|
package biz.dreamaker.workreport.email.ui;
import biz.dreamaker.workreport.email.application.EmailService;
import biz.dreamaker.workreport.email.dto.MailObject;
import java.util.HashMap;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmailController {
private final EmailService emailService;
public EmailController(EmailService emailService) {
this.emailService = emailService;
}
private static final Map<String, Map<String, String>> labels;
static {
labels = new HashMap<>();
//Simple email
Map<String, String> props = new HashMap<>();
props.put("headerText", "Send Simple Email");
props.put("messageLabel", "Message");
props.put("additionalInfo", "");
labels.put("send", props);
//Email with template
props = new HashMap<>();
props.put("headerText", "Send Email Using Text Template");
props.put("messageLabel", "Template Parameter");
props.put("additionalInfo",
"The parameter value will be added to the following message template:<br>" +
"<b>This is the test email template for your email:<br>'Template Parameter'</b>"
);
labels.put("sendTemplate", props);
//Email with attachment
props = new HashMap<>();
props.put("headerText", "Send Email With Attachment");
props.put("messageLabel", "Message");
props.put("additionalInfo",
"To make sure that you send an attachment with this email, change the value for the 'attachment.invoice' in the application.properties file to the path to the attachment.");
labels.put("sendAttachment", props);
}
@PreAuthorize("hasRole('ROLE_ADMIN') || hasRole('ROLE_SUPER')")
@PostMapping("/api/send")
public ResponseEntity<String> createMail(
@Valid @RequestBody MailObject mailObject
) {
emailService.sendSimpleMessage(mailObject.getTo(),
mailObject.getSubject(), mailObject.getText());
return ResponseEntity.ok().body("success");
}
@PreAuthorize("hasRole('ROLE_ADMIN') || hasRole('ROLE_SUPER')")
@PostMapping("/api/send/template")
public ResponseEntity<String> createSimpleTemplate(
@Valid @RequestBody MailObject mailObject
) {
emailService.sendSimpleMessageUsingTemplate(mailObject.getTo(),
mailObject.getSubject(), "드림메이커" , "테스트작업자" , "2020-02-10");
return ResponseEntity.ok().body("success");
}
}
|
package morris.db_ping;
import javax.swing.JOptionPane;
import java.sql.*;
/**
*
* @author Kimani
*/
public class Home_UI extends javax.swing.JFrame {
DB_Checker dbCheck = new DB_Checker();
/**
* Creates new form NewJFrame
*/
public Home_UI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
btn_Ping = new javax.swing.JButton();
txt_hostIP = new javax.swing.JTextField();
txt_DBsid = new javax.swing.JTextField();
txt_UserName = new javax.swing.JTextField();
txt_Passwd = new javax.swing.JPasswordField();
txt_Port = new javax.swing.JTextField();
txt_Dump_DIR = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("DB Ping: Test Oracle DB Availability");
setBackground(new java.awt.Color(0, 0, 255));
setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
setForeground(new java.awt.Color(0, 0, 255));
setResizable(false);
jLabel1.setFont(new java.awt.Font("Algerian", 1, 24)); // NOI18N
jLabel1.setText("DB Ping");
jLabel2.setFont(new java.awt.Font("Franklin Gothic Heavy", 0, 14)); // NOI18N
jLabel2.setText("Host IP: ");
jLabel3.setFont(new java.awt.Font("Franklin Gothic Heavy", 0, 14)); // NOI18N
jLabel3.setText("Database SID: ");
jLabel4.setFont(new java.awt.Font("Franklin Gothic Heavy", 0, 14)); // NOI18N
jLabel4.setText("Username: ");
jLabel5.setFont(new java.awt.Font("Franklin Gothic Heavy", 0, 14)); // NOI18N
jLabel5.setText("Password: ");
jLabel6.setFont(new java.awt.Font("Franklin Gothic Heavy", 0, 14)); // NOI18N
jLabel6.setText("Port: ");
btn_Ping.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
btn_Ping.setText("PING!");
btn_Ping.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_PingActionPerformed(evt);
}
});
txt_hostIP.setToolTipText("Enter DB Host IP");
txt_DBsid.setToolTipText("Enter name of the DB");
txt_UserName.setToolTipText("Your Username");
txt_Passwd.setToolTipText("Your Password");
txt_Port.setToolTipText("Database Port");
txt_Dump_DIR.setEditable(false);
jLabel7.setFont(new java.awt.Font("Franklin Gothic Heavy", 0, 14)); // NOI18N
jLabel7.setText("DUMPS DIRECTORY");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(99, 99, 99)
.addComponent(btn_Ping, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txt_Dump_DIR, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(jLabel2)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txt_hostIP)
.addComponent(txt_DBsid, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE)
.addComponent(txt_UserName, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(txt_Passwd, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_Port, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel7))))
.addContainerGap(29, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_hostIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_DBsid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_UserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_Passwd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_Port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addGap(16, 16, 16)
.addComponent(btn_Ping)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_Dump_DIR, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14))
);
jLabel1.getAccessibleContext().setAccessibleName("title_lbl");
pack();
}// </editor-fold>//GEN-END:initComponents
private void btn_PingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_PingActionPerformed
// TODO add your handling code here:
//1. Verify that the text boxes have accurate data
if (txt_DBsid.getText().length()==0 | txt_Passwd.getText().length()==0 | txt_Port.getText().length()==0 | txt_UserName.getText().length()==0 | txt_hostIP.getText().length()==0){
JOptionPane.showMessageDialog(null, "Sme fields are empty.\nPlease fill them in before proceeding", "Input Error", JOptionPane.INFORMATION_MESSAGE);
}else {
//2. Ping the database
int pingResult = dbCheck.db_check(txt_DBsid.getText(), txt_hostIP.getText(), txt_UserName.getText()+" as sysdba", txt_Passwd.getText(), txt_Port.getText());
if (pingResult == 1){
//3. Give response on the db status
JOptionPane.showMessageDialog(null, "Hey... That DB is up!\n Dump Dir = "+dbCheck.dump_dir, "Database status", JOptionPane.INFORMATION_MESSAGE);
//4. Fill in the DUMP_DIR of the db
txt_Dump_DIR.setText(dbCheck.dump_dir);
} else {
//3. Give response on the db status
JOptionPane.showMessageDialog(null, "Errors\n "+dbCheck.mashida, "Database status", JOptionPane.ERROR_MESSAGE);
//4. Fill in the DUMP_DIR of the db
txt_Dump_DIR.setText(dbCheck.dump_dir);
}//end if
}//end if
}//GEN-LAST:event_btn_PingActionPerformed
/**
* @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(Home_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Home_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Home_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Home_UI.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 Home_UI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_Ping;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JTextField txt_DBsid;
private javax.swing.JTextField txt_Dump_DIR;
private javax.swing.JPasswordField txt_Passwd;
private javax.swing.JTextField txt_Port;
private javax.swing.JTextField txt_UserName;
private javax.swing.JTextField txt_hostIP;
// End of variables declaration//GEN-END:variables
}
|
package com.jl.view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import com.jl.productSql.productService;
import com.jl.sql.commentService;
import com.jl.tools.MyTools;
import com.jl.tools.common;
public class juti_view extends JFrame implements ActionListener{
JPanel jp,jp1,jp2;
JScrollPane jsp;
JTextArea ja;
JButton jb1,jb2;
JLabel jl1;
JPanel pl,pr;
int id;
String name;
int col;
public juti_view(String str,int id,String name,int col){
this.id=id;
this.name=name;
this.col=col;
jp2=new JPanel();
jl1=new JLabel("修改信息面板",new ImageIcon("image/note.png"),0);
jl1.setFont(MyTools.f6);
jl1.setForeground(Color.WHITE);
jp2.add(jl1);
ja=new JTextArea();
ja.setFont(new Font("标楷体", Font.PLAIN, 14));
ja.setLineWrap(true);// 激活自动换行功能
ja.setWrapStyleWord(true);// 激活断行不断字功能
ja.setText(str);
ja.setEditable(false);
jsp=new JScrollPane(ja);
jb1=new JButton("添加修改");
jb1.addActionListener(this);
jb1.setActionCommand("edit");
jb2=new JButton("修改完成");
jb2.addActionListener(this);
jb2.setActionCommand("done");
jp1=new JPanel();
jp1.add(jb1);
jp1.add(jb2);
pl=new JPanel();
pl.setPreferredSize(new Dimension(30,150));
pr=new JPanel();
pr.setPreferredSize(new Dimension(30, 150));
jp=new JPanel(new BorderLayout());
jp.add(jp1,BorderLayout.SOUTH);
jp.add(jsp,BorderLayout.CENTER);
jp.add(jp2,BorderLayout.NORTH);
jp.add(pl,BorderLayout.WEST);
jp.add(pr,BorderLayout.EAST);
jp1.setBackground(new Color(89,194,230));
jp2.setBackground(new Color(89,194,230));
jp.setBackground(new Color(89,194,230));
pl.setBackground(new Color(89,194,230));
pr.setBackground(new Color(89,194,230));
this.add(jp);
this.setVisible(true);
this.setSize(400,300);
this.setBackground(new Color(89,194,230));
int x = (Toolkit.getDefaultToolkit().getScreenSize().width - this.getSize().width)/2;
int y = (Toolkit.getDefaultToolkit().getScreenSize().height - this.getSize().height)/2;
this.setLocation(x, y);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("edit")){
ja.setEditable(true);
}
if(e.getActionCommand().equals("done")){
ja.setEditable(false);
if(name.equals("product")){
System.out.println("name="+name);
//完成更新
productService ps=new productService();
String content=ja.getText();
//System.out.println("content="+content);
ps.updateProduct(id, name, content);
ps.Close();
//刷新页面
infoSummary_view info=common.infoS.get(2);
info.editFlush();
}if(name.equals("information")){
System.out.println("name="+name);
if(col==1){
commentService cs=new commentService();
String content=ja.getText();
cs.update1(id, content, name);
cs.Close();
}if(col==2){
commentService cs=new commentService();
String content=ja.getText();
cs.update2(id, content, name);
cs.Close();
}if(col==3){
commentService cs=new commentService();
String content=ja.getText();
cs.update3(id, content, name);
cs.Close();
}if(col==4){
commentService cs=new commentService();
String content=ja.getText();
cs.update4(id, content, name);
cs.Close();
}if(col==5){
commentService cs=new commentService();
String content=ja.getText();
cs.update5(id, content, name);
cs.Close();
}if(col==6){
commentService cs=new commentService();
String content=ja.getText();
cs.update6(id, content, name);
cs.Close();
}
infoCollection_view info=common.mp.get(1);
info.Flush();
}
}
}
public static void main(String[] args){
}
}
|
package com.example.gopalawasthi.movielovers;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by Gopal Awasthi on 18-04-2018.
*/
public class FavouritePagerAdapter extends FragmentPagerAdapter {
private Context context;
public FavouritePagerAdapter(FragmentManager fm,Context context) {
super(fm);
this.context = context;
}
@Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FavouriteFragment();
case 1:
return new FavouriteTvFragment();
}
return null;
}
@Override
public int getCount() {
return 2;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "movies";
}else{
return "tv";
}
}
}
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* 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.
*/
/**
* Tests for SAD (sum of absolute differences).
*
* Special case, char array that is first casted to short, forcing sign extension.
*/
public class SimdSadShort2 {
// TODO: lower precision still coming, b/64091002
private static short sadCastedChar2Short(char[] s1, char[] s2) {
int min_length = Math.min(s1.length, s2.length);
short sad = 0;
for (int i = 0; i < min_length; i++) {
sad += Math.abs(((short) s1[i]) - ((short) s2[i]));
}
return sad;
}
private static short sadCastedChar2ShortAlt(char[] s1, char[] s2) {
int min_length = Math.min(s1.length, s2.length);
short sad = 0;
for (int i = 0; i < min_length; i++) {
short s = (short) s1[i];
short p = (short) s2[i];
sad += s >= p ? s - p : p - s;
}
return sad;
}
private static short sadCastedChar2ShortAlt2(char[] s1, char[] s2) {
int min_length = Math.min(s1.length, s2.length);
short sad = 0;
for (int i = 0; i < min_length; i++) {
short s = (short) s1[i];
short p = (short) s2[i];
int x = s - p;
if (x < 0) x = -x;
sad += x;
}
return sad;
}
/// CHECK-START: int SimdSadShort2.sadCastedChar2Int(char[], char[]) instruction_simplifier (before)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Phi2:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<BC1:i\d+>> BoundsCheck [<<Phi1>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<BC2:i\d+>> BoundsCheck [<<Phi1>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:c\d+>> ArrayGet [{{l\d+}},<<BC1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get2:c\d+>> ArrayGet [{{l\d+}},<<BC2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv1:s\d+>> TypeConversion [<<Get1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv2:s\d+>> TypeConversion [<<Get2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Sub:i\d+>> Sub [<<Cnv1>>,<<Cnv2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Intrin:i\d+>> InvokeStaticOrDirect [<<Sub>>] intrinsic:MathAbsInt loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi2>>,<<Intrin>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-START: int SimdSadShort2.sadCastedChar2Int(char[], char[]) loop_optimization (before)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Phi2:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:s\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get2:s\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Sub:i\d+>> Sub [<<Get1>>,<<Get2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Intrin:i\d+>> Abs [<<Sub>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi2>>,<<Intrin>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-START-ARM64: int SimdSadShort2.sadCastedChar2Int(char[], char[]) loop_optimization (after)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons8:i\d+>> IntConstant 8 loop:none
/// CHECK-DAG: <<Set:d\d+>> VecSetScalars [<<Cons0>>] loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi2:d\d+>> Phi [<<Set>>,{{d\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Load1:d\d+>> VecLoad [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Load2:d\d+>> VecLoad [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<SAD:d\d+>> VecSADAccumulate [<<Phi2>>,<<Load1>>,<<Load2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons8>>] loop:<<Loop>> outer_loop:none
private static int sadCastedChar2Int(char[] s1, char[] s2) {
int min_length = Math.min(s1.length, s2.length);
int sad = 0;
for (int i = 0; i < min_length; i++) {
sad += Math.abs(((short) s1[i]) - ((short) s2[i]));
}
return sad;
}
/// CHECK-START: int SimdSadShort2.sadCastedChar2IntAlt(char[], char[]) instruction_simplifier (before)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Phi2:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<BC1:i\d+>> BoundsCheck [<<Phi1>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<BC2:i\d+>> BoundsCheck [<<Phi1>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:c\d+>> ArrayGet [{{l\d+}},<<BC1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get2:c\d+>> ArrayGet [{{l\d+}},<<BC2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv1:s\d+>> TypeConversion [<<Get1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv2:s\d+>> TypeConversion [<<Get2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Sub1:i\d+>> Sub [<<Cnv2>>,<<Cnv1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Sub2:i\d+>> Sub [<<Cnv1>>,<<Cnv2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Phi3:i\d+>> Phi [<<Sub2>>,<<Sub1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi2>>,<<Phi3>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-START: int SimdSadShort2.sadCastedChar2IntAlt(char[], char[]) loop_optimization (before)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Phi2:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:s\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get2:s\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Sub:i\d+>> Sub [<<Get2>>,<<Get1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Intrin:i\d+>> Abs [<<Sub>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi2>>,<<Intrin>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-START-ARM64: int SimdSadShort2.sadCastedChar2IntAlt(char[], char[]) loop_optimization (after)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons8:i\d+>> IntConstant 8 loop:none
/// CHECK-DAG: <<Set:d\d+>> VecSetScalars [<<Cons0>>] loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi2:d\d+>> Phi [<<Set>>,{{d\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Load1:d\d+>> VecLoad [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Load2:d\d+>> VecLoad [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<SAD:d\d+>> VecSADAccumulate [<<Phi2>>,<<Load2>>,<<Load1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons8>>] loop:<<Loop>> outer_loop:none
private static int sadCastedChar2IntAlt(char[] s1, char[] s2) {
int min_length = Math.min(s1.length, s2.length);
int sad = 0;
for (int i = 0; i < min_length; i++) {
short s = (short) s1[i];
short p = (short) s2[i];
sad += s >= p ? s - p : p - s;
}
return sad;
}
/// CHECK-START: int SimdSadShort2.sadCastedChar2IntAlt2(char[], char[]) instruction_simplifier (before)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Phi2:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<BC1:\i\d+>> BoundsCheck [<<Phi1>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<BC2:\i\d+>> BoundsCheck [<<Phi1>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:c\d+>> ArrayGet [{{l\d+}},<<BC1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get2:c\d+>> ArrayGet [{{l\d+}},<<BC2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv1:s\d+>> TypeConversion [<<Get1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv2:s\d+>> TypeConversion [<<Get2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Sub:i\d+>> Sub [<<Cnv1>>,<<Cnv2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Neg:i\d+>> Neg [<<Sub>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Phi3:i\d+>> Phi [<<Sub>>,<<Neg>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi2>>,<<Phi3>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-START: int SimdSadShort2.sadCastedChar2IntAlt2(char[], char[]) loop_optimization (before)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<Phi2:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:s\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get2:s\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Sub:i\d+>> Sub [<<Get1>>,<<Get2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Intrin:i\d+>> Abs [<<Sub>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi2>>,<<Intrin>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-START-ARM64: int SimdSadShort2.sadCastedChar2IntAlt2(char[], char[]) loop_optimization (after)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons8:i\d+>> IntConstant 8 loop:none
/// CHECK-DAG: <<Set:d\d+>> VecSetScalars [<<Cons0>>] loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi2:d\d+>> Phi [<<Set>>,{{d\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Load1:d\d+>> VecLoad [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Load2:d\d+>> VecLoad [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<SAD:d\d+>> VecSADAccumulate [<<Phi2>>,<<Load1>>,<<Load2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons8>>] loop:<<Loop>> outer_loop:none
private static int sadCastedChar2IntAlt2(char[] s1, char[] s2) {
int min_length = Math.min(s1.length, s2.length);
int sad = 0;
for (int i = 0; i < min_length; i++) {
short s = (short) s1[i];
short p = (short) s2[i];
int x = s - p;
if (x < 0) x = -x;
sad += x;
}
return sad;
}
/// CHECK-START: long SimdSadShort2.sadCastedChar2Long(char[], char[]) instruction_simplifier (before)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<ConsL:j\d+>> LongConstant 0 loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi2:j\d+>> Phi [<<ConsL>>,{{j\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<BC1:\i\d+>> BoundsCheck [<<Phi1>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<BC2:\i\d+>> BoundsCheck [<<Phi1>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:c\d+>> ArrayGet [{{l\d+}},<<BC1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get2:c\d+>> ArrayGet [{{l\d+}},<<BC2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv1:s\d+>> TypeConversion [<<Get1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv2:s\d+>> TypeConversion [<<Get2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv3:j\d+>> TypeConversion [<<Cnv1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv4:j\d+>> TypeConversion [<<Cnv2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Sub:j\d+>> Sub [<<Cnv3>>,<<Cnv4>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Intrin:j\d+>> InvokeStaticOrDirect [<<Sub>>] intrinsic:MathAbsLong loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi2>>,<<Intrin>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-START: long SimdSadShort2.sadCastedChar2Long(char[], char[]) loop_optimization (before)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<ConsL:j\d+>> LongConstant 0 loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi2:j\d+>> Phi [<<ConsL>>,{{j\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:s\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get2:s\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv1:j\d+>> TypeConversion [<<Get1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv2:j\d+>> TypeConversion [<<Get2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Sub:j\d+>> Sub [<<Cnv1>>,<<Cnv2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Intrin:j\d+>> Abs [<<Sub>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi2>>,<<Intrin>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-START-ARM64: long SimdSadShort2.sadCastedChar2Long(char[], char[]) loop_optimization (after)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons8:i\d+>> IntConstant 8 loop:none
/// CHECK-DAG: <<ConsL:j\d+>> LongConstant 0 loop:none
/// CHECK-DAG: <<Set:d\d+>> VecSetScalars [<<ConsL>>] loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi2:d\d+>> Phi [<<Set>>,{{d\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Load1:d\d+>> VecLoad [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Load2:d\d+>> VecLoad [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<SAD:d\d+>> VecSADAccumulate [<<Phi2>>,<<Load1>>,<<Load2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons8>>] loop:<<Loop>> outer_loop:none
private static long sadCastedChar2Long(char[] s1, char[] s2) {
int min_length = Math.min(s1.length, s2.length);
long sad = 0;
for (int i = 0; i < min_length; i++) {
long x = (short) s1[i];
long y = (short) s2[i];
sad += Math.abs(x - y);
}
return sad;
}
/// CHECK-START: long SimdSadShort2.sadCastedChar2LongAt1(char[], char[]) instruction_simplifier (before)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<ConsL:j\d+>> LongConstant 1 loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi2:j\d+>> Phi [<<ConsL>>,{{j\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<BC1:\i\d+>> BoundsCheck [<<Phi1>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<BC2:\i\d+>> BoundsCheck [<<Phi1>>,{{i\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:c\d+>> ArrayGet [{{l\d+}},<<BC1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get2:c\d+>> ArrayGet [{{l\d+}},<<BC2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv1:s\d+>> TypeConversion [<<Get1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv2:s\d+>> TypeConversion [<<Get2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv3:j\d+>> TypeConversion [<<Cnv1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv4:j\d+>> TypeConversion [<<Cnv2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Sub:j\d+>> Sub [<<Cnv3>>,<<Cnv4>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Intrin:j\d+>> InvokeStaticOrDirect [<<Sub>>] intrinsic:MathAbsLong loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi2>>,<<Intrin>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-START: long SimdSadShort2.sadCastedChar2LongAt1(char[], char[]) loop_optimization (before)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons1:i\d+>> IntConstant 1 loop:none
/// CHECK-DAG: <<ConsL:j\d+>> LongConstant 1 loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi2:j\d+>> Phi [<<ConsL>>,{{j\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get1:s\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Get2:s\d+>> ArrayGet [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv1:j\d+>> TypeConversion [<<Get1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Cnv2:j\d+>> TypeConversion [<<Get2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Sub:j\d+>> Sub [<<Cnv1>>,<<Cnv2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Intrin:j\d+>> Abs [<<Sub>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi2>>,<<Intrin>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons1>>] loop:<<Loop>> outer_loop:none
//
/// CHECK-START-ARM64: long SimdSadShort2.sadCastedChar2LongAt1(char[], char[]) loop_optimization (after)
/// CHECK-DAG: <<Cons0:i\d+>> IntConstant 0 loop:none
/// CHECK-DAG: <<Cons8:i\d+>> IntConstant 8 loop:none
/// CHECK-DAG: <<ConsL:j\d+>> LongConstant 1 loop:none
/// CHECK-DAG: <<Set:d\d+>> VecSetScalars [<<ConsL>>] loop:none
/// CHECK-DAG: <<Phi1:i\d+>> Phi [<<Cons0>>,{{i\d+}}] loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: <<Phi2:d\d+>> Phi [<<Set>>,{{d\d+}}] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Load1:d\d+>> VecLoad [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<Load2:d\d+>> VecLoad [{{l\d+}},<<Phi1>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: <<SAD:d\d+>> VecSADAccumulate [<<Phi2>>,<<Load1>>,<<Load2>>] loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add [<<Phi1>>,<<Cons8>>] loop:<<Loop>> outer_loop:none
private static long sadCastedChar2LongAt1(char[] s1, char[] s2) {
int min_length = Math.min(s1.length, s2.length);
long sad = 1; // starts at 1
for (int i = 0; i < min_length; i++) {
long x = (short) s1[i];
long y = (short) s2[i];
sad += Math.abs(x - y);
}
return sad;
}
public static void main() {
// Cross-test the two most extreme values individually.
char[] s1 = { 0, 0x8000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
char[] s2 = { 0, 0x7fff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
expectEquals(-1, sadCastedChar2Short(s1, s2));
expectEquals(-1, sadCastedChar2Short(s2, s1));
expectEquals(-1, sadCastedChar2ShortAlt(s1, s2));
expectEquals(-1, sadCastedChar2ShortAlt(s2, s1));
expectEquals(-1, sadCastedChar2ShortAlt2(s1, s2));
expectEquals(-1, sadCastedChar2ShortAlt2(s2, s1));
expectEquals(65535, sadCastedChar2Int(s1, s2));
expectEquals(65535, sadCastedChar2Int(s2, s1));
expectEquals(65535, sadCastedChar2IntAlt(s1, s2));
expectEquals(65535, sadCastedChar2IntAlt(s2, s1));
expectEquals(65535, sadCastedChar2IntAlt2(s1, s2));
expectEquals(65535, sadCastedChar2IntAlt2(s2, s1));
expectEquals(65535L, sadCastedChar2Long(s1, s2));
expectEquals(65535L, sadCastedChar2Long(s2, s1));
expectEquals(65536L, sadCastedChar2LongAt1(s1, s2));
expectEquals(65536L, sadCastedChar2LongAt1(s2, s1));
// Use cross-values to test all cases.
char[] interesting = {
(char) 0x0000,
(char) 0x0001,
(char) 0x0002,
(char) 0x1234,
(char) 0x8000,
(char) 0x8001,
(char) 0x7fff,
(char) 0xffff
};
int n = interesting.length;
int m = n * n + 1;
s1 = new char[m];
s2 = new char[m];
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
s1[k] = interesting[i];
s2[k] = interesting[j];
k++;
}
}
s1[k] = 10;
s2[k] = 2;
expectEquals(-18932, sadCastedChar2Short(s1, s2));
expectEquals(-18932, sadCastedChar2ShortAlt(s1, s2));
expectEquals(-18932, sadCastedChar2ShortAlt2(s1, s2));
expectEquals(1291788, sadCastedChar2Int(s1, s2));
expectEquals(1291788, sadCastedChar2IntAlt(s1, s2));
expectEquals(1291788, sadCastedChar2IntAlt2(s1, s2));
expectEquals(1291788L, sadCastedChar2Long(s1, s2));
expectEquals(1291789L, sadCastedChar2LongAt1(s1, s2));
System.out.println("SimdSadShort2 passed");
}
private static void expectEquals(int expected, int result) {
if (expected != result) {
throw new Error("Expected: " + expected + ", found: " + result);
}
}
private static void expectEquals(long expected, long result) {
if (expected != result) {
throw new Error("Expected: " + expected + ", found: " + result);
}
}
}
|
package hdfcraft;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import hdfcraft.minecraft.Material;
import hdfcraft.heightMaps.NoiseHeightMap;
/**
* @author SchmitzP
*/
public class MixedMaterial implements Serializable {
/**
* Create a new "mixed material" which contains only one material.
*
* @param name The name of the mixed material.
* @param row A single row describing the material.
* @param biome The default biome associated with this mixed material, or -1
* for no default biome.
* @param colour The colour associated with this mixed material, or
* <code>null</code> for no default colour.
*/
public MixedMaterial(final String name, final Row row, final int biome, final Integer colour) {
this(name, new Row[] {row}, biome, Mode.SIMPLE, 1.0f, colour, null, 0, 0, false);
}
/**
* Create a new noisy mixed material.
*
* @param name The name of the mixed material.
* @param rows The rows describing the materials to be used together with
* their occurrences.
* @param biome The default biome associated with this mixed material, or -1
* for no default biome.
* @param colour The colour associated with this mixed material, or
* <code>null</code> for no default colour.
*/
public MixedMaterial(final String name, final Row[] rows, final int biome, final Integer colour) {
this(name, rows, biome, Mode.NOISE, 1.0f, colour, null, 0, 0, false);
}
/**
* Create a new blobby mixed material.
*
* @param name The name of the mixed material.
* @param rows The rows describing the materials to be used together with
* their occurrences.
* @param biome The default biome associated with this mixed material, or -1
* for no default biome.
* @param colour The colour associated with this mixed material, or
* <code>null</code> for no default colour.
* @param scale The scale of the blobs. <code>1.0f</code> for default size.
*/
public MixedMaterial(final String name, final Row[] rows, final int biome, final Integer colour, final float scale) {
this(name, rows, biome, Mode.BLOBS, scale, colour, null, 0, 0, false);
}
/**
* Create a new layered mixed material.
*
* @param name The name of the mixed material.
* @param rows The rows describing the materials to be used together with
* their heights.
* @param biome The default biome associated with this mixed material, or -1
* for no default biome.
* @param colour The colour associated with this mixed material, or
* <code>null</code> for no default colour.
* @param variation The variation in layer height which should be applied,
* or <code>null</code> for no variation.
* @param layerXSlope The slope of the layer for the x-axis.
* Must be zero if <code>repeat</code> is false.
* @param layerYSlope The slope of the layer for the y-axis.
* Must be zero if <code>repeat</code> is false.
* @param repeat Whether the layers should repeat vertically.
*/
public MixedMaterial(final String name, final Row[] rows, final int biome, final Integer colour, final NoiseSettings variation, final double layerXSlope, final double layerYSlope, final boolean repeat) {
this(name, rows, biome, Mode.LAYERED, 1.0f, colour, variation, layerXSlope, layerYSlope, repeat);
}
private MixedMaterial(final String name, final Row[] rows, final int biome, final Mode mode, final float scale, final Integer colour, final NoiseSettings variation, final double layerXSlope, final double layerYSlope, final boolean repeat) {
if ((mode != Mode.LAYERED) && (mode != Mode.SIMPLE)) {
int total = 0;
for (Row row: rows) {
total += row.occurrence;
}
if (total != 1000) {
throw new IllegalArgumentException("Total occurrence is not 1000");
}
}
this.name = name;
this.rows = rows;
this.biome = biome;
this.mode = mode;
this.scale = scale;
this.colour = colour;
this.variation = variation;
this.layerXSlope = layerXSlope;
this.layerYSlope = layerYSlope;
this.repeat = repeat;
init();
}
public String getName() {
return name;
}
public int getBiome() {
return biome;
}
public Mode getMode() {
return mode;
}
public float getScale() {
return scale;
}
public Integer getColour() {
return colour;
}
public NoiseSettings getVariation() {
return variation;
}
public boolean isRepeat() {
return repeat;
}
public double getLayerXSlope() {
return layerXSlope;
}
public double getLayerYSlope() {
return layerYSlope;
}
public BufferedImage getIcon(ColourScheme colourScheme) {
final BufferedImage icon = new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
// Draw the border
for (int i = 0; i < 15; i++) {
icon.setRGB( i, 0, 0);
icon.setRGB( 15, i, 0);
icon.setRGB(15 - i, 15, 0);
icon.setRGB( 0, 15 - i, 0);
}
// Draw the terrain
if (colour != null) {
for (int x = 1; x < 15; x++) {
for (int y = 1; y < 15; y++) {
icon.setRGB(x, y, colour);
}
}
} else {
for (int x = 1; x < 15; x++) {
for (int y = 1; y < 15; y++) {
icon.setRGB(x, y, colourScheme.getColour(getMaterial(0, x, 0, y)));
}
}
}
return icon;
}
public Material getMaterial(long seed, int x, int y, float z) {
switch (mode) {
case SIMPLE:
return simpleMaterial;
case NOISE:
return materials[random.nextInt(1000)];
case BLOBS:
double xx = x / Constants.TINY_BLOBS, yy = y / Constants.TINY_BLOBS, zz = z / Constants.TINY_BLOBS;
if (seed + 1 != noiseGenerators[0].getSeed()) {
for (int i = 0; i < noiseGenerators.length; i++) {
noiseGenerators[i].setSeed(seed + i + 1);
}
}
Material material = sortedRows[sortedRows.length - 1].material;
for (int i = noiseGenerators.length - 1; i >= 0; i--) {
final float rowScale = sortedRows[i].scale * this.scale;
if (noiseGenerators[i].getPerlinNoise(xx / rowScale, yy / rowScale, zz / rowScale) >= sortedRows[i].chance) {
material = sortedRows[i].material;
}
}
return material;
case LAYERED:
if (layerNoiseheightMap != null) {
if (layerNoiseheightMap.getSeed() != seed) {
layerNoiseheightMap.setSeed(seed);
}
z += layerNoiseheightMap.getValue(x, y, z) - layerNoiseOffset;
}
if (repeat) {
if (layerXSlope != 0.0) {
z += layerXSlope * x;
}
if (layerYSlope != 0.0) {
z += layerYSlope * y;
}
return materials[MathUtils.mod((int) (z + 0.5f), materials.length)];
} else {
final int iZ = (int) (z + 0.5f);
if (iZ < 0) {
return materials[0];
} else if (iZ >= materials.length) {
return materials[materials.length - 1];
} else {
return materials[iZ];
}
}
default:
throw new InternalError();
}
}
public Material getMaterial(long seed, int x, int y, int z) {
switch (mode) {
case SIMPLE:
return simpleMaterial;
case NOISE:
return materials[random.nextInt(1000)];
case BLOBS:
double xx = x / Constants.TINY_BLOBS, yy = y / Constants.TINY_BLOBS, zz = z / Constants.TINY_BLOBS;
if (seed + 1 != noiseGenerators[0].getSeed()) {
for (int i = 0; i < noiseGenerators.length; i++) {
noiseGenerators[i].setSeed(seed + i + 1);
}
}
Material material = sortedRows[sortedRows.length - 1].material;
for (int i = noiseGenerators.length - 1; i >= 0; i--) {
final float rowScale = sortedRows[i].scale * this.scale;
if (noiseGenerators[i].getPerlinNoise(xx / rowScale, yy / rowScale, zz / rowScale) >= sortedRows[i].chance) {
material = sortedRows[i].material;
}
}
return material;
case LAYERED:
float fZ = z;
if (layerNoiseheightMap != null) {
if (layerNoiseheightMap.getSeed() != seed) {
layerNoiseheightMap.setSeed(seed);
}
fZ += layerNoiseheightMap.getValue(x, y, z) - layerNoiseOffset;
}
if (repeat) {
if (layerXSlope != 0.0) {
fZ += layerXSlope * x;
}
if (layerYSlope != 0.0) {
fZ += layerYSlope * y;
}
return materials[MathUtils.mod((int) (fZ + 0.5f), materials.length)];
} else {
final int iZ = (int) (fZ + 0.5f);
if (iZ < 0) {
return materials[0];
} else if (iZ >= materials.length) {
return materials[materials.length - 1];
} else {
return materials[iZ];
}
}
default:
throw new InternalError();
}
}
public Row[] getRows() {
return Arrays.copyOf(rows, rows.length);
}
// java.lang.Object
@Override
public String toString() {
return name;
}
@Override
public int hashCode() {
int hash = 7;
hash = 19 * hash + this.biome;
hash = 19 * hash + Arrays.deepHashCode(this.rows);
hash = 19 * hash + mode.hashCode();
hash = 19 * hash + Float.floatToIntBits(this.scale);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MixedMaterial other = (MixedMaterial) obj;
if (this.biome != other.biome) {
return false;
}
if (!Arrays.deepEquals(this.rows, other.rows)) {
return false;
}
if (this.mode != other.mode) {
return false;
}
if (Float.floatToIntBits(this.scale) != Float.floatToIntBits(other.scale)) {
return false;
}
return true;
}
/**
* Utility method for creating a simple mixed material, consisting of one
* block type with data value 0.
*
* @param blockType The block type the mixed material should consist of
* @return A new mixed material with the specified block type, and the
* block type's name
*/
public static MixedMaterial create(final int blockType) {
return create(Material.get(blockType));
}
/**
* Utility method for creating a simple mixed material, consisting of one
* material.
*
* @param material The simple material the mixed material should consist of
* @return A new mixed material with the specified material and an
* appropriate name
*/
public static MixedMaterial create(final Material material) {
return new MixedMaterial(material.toString(), new Row(material, 1000, 1.0f), -1, null);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
// Legacy
if (mode == null) {
if (rows.length == 1) {
mode = Mode.SIMPLE;
} else if (noise) {
mode = Mode.NOISE;
} else {
mode = Mode.BLOBS;
}
}
init();
}
private void init() {
switch (mode) {
case SIMPLE:
if (rows.length != 1) {
throw new IllegalArgumentException("Only one row allowed for SIMPLE mode");
}
simpleMaterial = rows[0].material;
break;
case NOISE:
if (rows.length < 2) {
throw new IllegalArgumentException("Multiple rows required for NOISE mode");
}
materials = new Material[1000];
int index = 0;
for (Row row: rows) {
for (int i = 0; i < row.occurrence; i++) {
materials[index++] = row.material;
}
}
random = new Random();
break;
case BLOBS:
if (rows.length < 2) {
throw new IllegalArgumentException("Multiple rows required for BLOBS mode");
}
sortedRows = Arrays.copyOf(rows, rows.length);
Arrays.sort(sortedRows, new Comparator<Row>() {
@Override
public int compare(final Row r1, final Row r2) {
return r1.occurrence - r2.occurrence;
}
});
noiseGenerators = new PerlinNoise[rows.length - 1];
int cumulativePermillage = 0;
for (int i = 0; i < noiseGenerators.length; i++) {
noiseGenerators[i] = new PerlinNoise(0);
cumulativePermillage += sortedRows[i].occurrence * (1000 - cumulativePermillage) / 1000;
sortedRows[i].chance = PerlinNoise.getLevelForPromillage(cumulativePermillage);
}
break;
case LAYERED:
if (rows.length < 2) {
throw new IllegalArgumentException("Multiple rows required for LAYERED mode");
}
if ((! repeat) && ((layerXSlope != 0) || (layerYSlope != 0))) {
throw new IllegalArgumentException("Angle may not be non-zero if repeat is false");
}
List<Material> tmpMaterials = new ArrayList<Material>(hdfcraft.minecraft.Constants.DEFAULT_MAX_HEIGHT_2);
for (int i = rows.length - 1; i >= 0; i--) {
for (int j = 0; j < rows[i].occurrence; j++) {
tmpMaterials.add(rows[i].material);
}
}
materials = tmpMaterials.toArray(new Material[tmpMaterials.size()]);
if (variation != null) {
layerNoiseheightMap = new NoiseHeightMap(variation.getRange() * 2, variation.getScale() / 5, variation.getRoughness() + 1, NOISE_SEED_OFFSET);
layerNoiseOffset = variation.getRange();
} else {
layerNoiseheightMap = null;
layerNoiseOffset = 0;
}
break;
}
}
private final String name;
private final int biome;
private final Row[] rows;
@Deprecated
private final boolean noise = false;
private final float scale;
private final Integer colour;
private Mode mode = Mode.BLOBS;
private final NoiseSettings variation;
private final boolean repeat;
private final double layerXSlope, layerYSlope;
private transient Row[] sortedRows;
private transient PerlinNoise[] noiseGenerators;
private transient Material[] materials;
private transient Random random;
private transient Material simpleMaterial;
private transient NoiseHeightMap layerNoiseheightMap;
private transient int layerNoiseOffset;
public static class Row implements Serializable {
public Row(Material material, int occurrence, float scale) {
this.material = material;
this.occurrence = occurrence;
this.scale = scale;
}
@Override
public int hashCode() {
int hash = 5;
hash = 23 * hash + (this.material != null ? this.material.hashCode() : 0);
hash = 23 * hash + this.occurrence;
hash = 23 * hash + Float.floatToIntBits(this.scale);
hash = 23 * hash + Float.floatToIntBits(this.chance);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Row other = (Row) obj;
if (this.material != other.material && (this.material == null || !this.material.equals(other.material))) {
return false;
}
if (this.occurrence != other.occurrence) {
return false;
}
if (Float.floatToIntBits(this.scale) != Float.floatToIntBits(other.scale)) {
return false;
}
if (Float.floatToIntBits(this.chance) != Float.floatToIntBits(other.chance)) {
return false;
}
return true;
}
final Material material;
final int occurrence;
final float scale;
float chance;
private static final long serialVersionUID = 1L;
}
public enum Mode {SIMPLE, BLOBS, NOISE, LAYERED}
private static final long NOISE_SEED_OFFSET = 55904327L;
private static final long serialVersionUID = 1L;
}
|
package com.cai.seckill.dao;
import com.cai.seckill.pojo.Goods;
import com.cai.seckill.pojo.SeckillGoods;
import com.cai.seckill.vo.GoodsVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
@Mapper
public interface GoodsDao {
@Select("select g.*,mg.stock_count, mg.start_date, mg.end_date,mg.miaosha_price from miaosha_goods mg left join goods g on g.id = mg.goods_id ")
List<GoodsVo> listGoodsVo();
@Select("select g.*,mg.stock_count, mg.start_date, mg.end_date,mg.miaosha_price from miaosha_goods mg left join goods g on g.id = mg.goods_id where goods_id = #{id}")
GoodsVo getById(long id);
@Update("update miaosha_goods set stock_count = stock_count - 1 where goods_id = #{goodsId} " )
int reducestock(SeckillGoods goods);
}
|
package de.mq.phone.web.person;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.context.MessageSource;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import com.vaadin.data.fieldgroup.FieldGroup;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.TextField;
import de.mq.phone.domain.person.Contact;
import de.mq.phone.web.person.ContactEditorView.Fields;
import de.mq.phone.web.person.PersonEditModel.EventType;
import de.mq.vaadin.util.BindingResultsToFieldGroupMapper;
import de.mq.vaadin.util.Observer;
public class ContactEditorViewTest {
private final PersonEditModel personEditModel = Mockito.mock(PersonEditModel.class);
private final PersonEditController personEditController = Mockito.mock(PersonEditController.class);
private final BindingResultsToFieldGroupMapper bindingResultMapper = Mockito.mock(BindingResultsToFieldGroupMapper.class);
private final ContactMapper contactMapper = Mockito.mock(ContactMapper.class);
private final UserModel userModel = Mockito.mock(UserModel.class);
private final MessageSource messageSource = Mockito.mock(MessageSource.class);
private final ContactEditorView contactEditorView = new ContactEditorView(personEditModel, personEditController, bindingResultMapper, contactMapper, userModel,messageSource );
private final Map<String, Component> components = new HashMap<>();
Observer<UserModel.EventType> localeChangedObserver;
Observer<PersonEditModel.EventType> contactChangedObserver;
@SuppressWarnings("unchecked")
@Before
public final void setup() {
Mockito.when(userModel.getLocale()).thenReturn(Locale.GERMAN);
Mockito.when(messageSource.getMessage(ContactEditorView.I18N_EDIT_CONTACT_BUTTON, null, Locale.GERMAN)).thenReturn(ContactEditorView.I18N_EDIT_CONTACT_BUTTON);
Mockito.when(messageSource.getMessage(ContactEditorView.I18N_EDIT_CONTACT_HEADLINE, null, Locale.GERMAN)).thenReturn(ContactEditorView.I18N_EDIT_CONTACT_HEADLINE);
Mockito.when(messageSource.getMessage(ContactEditorView.I18N_DELETE_CONTACT_BUTTON, null, Locale.GERMAN)).thenReturn(ContactEditorView.I18N_DELETE_CONTACT_BUTTON);
Arrays.stream(Fields.values()).forEach(field -> Mockito.when(messageSource.getMessage( (ContactEditorView.I18N_EDIT_CONTACT_PREFIX + field.property()).toLowerCase(), null, Locale.GERMAN)).thenReturn(field.property()));
Mockito.doAnswer( invocation -> {
localeChangedObserver = (Observer<UserModel.EventType>) invocation.getArguments()[0];
return null;
} ).when(userModel).register(Mockito.any(Observer.class), Mockito.any(UserModel.EventType.class) );
Mockito.doAnswer(invocation -> {
contactChangedObserver = (Observer<PersonEditModel.EventType>) invocation.getArguments()[0];
return null;
}).when(personEditModel).register(Mockito.any(Observer.class), Mockito.any(PersonEditModel.EventType.class));
contactEditorView.init();
localeChangedObserver.process(UserModel.EventType.LocaleChanges);
components.clear();
ComponentTestHelper.components( contactEditorView, components);
}
@Test
public final void init() {
Arrays.stream(Fields.values()).forEach(field -> {
Assert.assertTrue(components.containsKey(field.property()));
Assert.assertFalse(components.get(field.property()).isVisible());
});
Assert.assertTrue(components.containsKey(ContactEditorView.I18N_EDIT_CONTACT_BUTTON));
Assert.assertTrue(components.containsKey(ContactEditorView.I18N_EDIT_CONTACT_HEADLINE));
Assert.assertEquals(3 + Fields.values().length, components.size());
Assert.assertFalse(contactEditorView.isVisible());
}
@Test
public final void initPhone() {
final Map<String,Object> entryAsMap = new HashMap<>();
Arrays.stream(Fields.values()).filter( field -> Fields.Contact != field).forEach(field -> entryAsMap.put(field.property(), field.name()));
prepare(entryAsMap);
contactChangedObserver.process(EventType.PersonChanged);
Arrays.stream(Fields.values()).filter(field -> field != Fields.Contact).forEach(field -> Assert.assertTrue(components.get(field.property()).isVisible()));
Assert.assertFalse(components.get(Fields.Contact.property()).isVisible());
Arrays.stream(Fields.values()).filter( field -> Fields.Contact != field).forEach(field -> Assert.assertEquals(field.name(), ((TextField)components.get(field.property())).getValue()));
}
@Test
public final void initMail() {
final Map<String,Object> entryAsMap = new HashMap<>();
entryAsMap.put(Fields.Contact.property(), Fields.Contact.name());
prepare(entryAsMap);
contactChangedObserver.process(EventType.PersonChanged);
Arrays.stream(Fields.values()).filter(field -> field != Fields.Contact).forEach(field -> Assert.assertFalse(components.get(field.property()).isVisible()));
Assert.assertTrue(components.get(Fields.Contact.property()).isVisible());
Assert.assertEquals(Fields.Contact.name(), (((TextField)components.get(Fields.Contact.property())).getValue()));
}
@Test
public final void initNothing() {
final Map<String,Object> entryAsMap = new HashMap<>();
prepare(entryAsMap);
Mockito.when(personEditModel.isPhoneContact()).thenReturn(false);
Mockito.when(personEditModel.isMailContact()).thenReturn(false);
contactChangedObserver.process(EventType.PersonChanged);
Arrays.stream(Fields.values()).forEach(field -> Assert.assertFalse(components.get(field.property()).isVisible()));
Arrays.stream(Fields.values()).forEach(field -> Assert.assertFalse(StringUtils.hasText(((TextField)components.get(field.property())).getValue())));
}
@SuppressWarnings("unchecked")
private void prepare(Map<String,Object> entryAsMap) {
final Entry<UUID, Contact> entry = Mockito.mock(Entry.class);
Mockito.when(personEditModel.getCurrentContact()).thenReturn(entry);
final Contact contact = Mockito.mock(Contact.class);
Mockito.when(entry.getValue()).thenReturn(contact);
if( entryAsMap.containsKey(Fields.Contact.property())) {
Mockito.when(personEditModel.isMailContact()).thenReturn(true);
} else {
Mockito.when(personEditModel.isPhoneContact()).thenReturn(true);
}
Mockito.when(contactMapper.contactToMap(entry)).thenReturn(entryAsMap);
Mockito.doAnswer(invocation -> {
Assert.assertEquals(entryAsMap, invocation.getArguments()[0]);
((Map<String,?>)invocation.getArguments()[0]).keySet().forEach(fieldName -> ((TextField) ((FieldGroup) invocation.getArguments()[1]).getField(fieldName)).setValue((String) entryAsMap.get(fieldName)));
return null;
}).when(bindingResultMapper).mapInto(Mockito.anyMap(), Mockito.any(FieldGroup.class));
}
@Test
public final void change() {
final Button button = (Button) components.get(ContactEditorView.I18N_EDIT_CONTACT_BUTTON);
com.vaadin.ui.Button.ClickListener listener = (com.vaadin.ui.Button.ClickListener) button.getListeners(ClickEvent.class).iterator().next();
final ClickEvent event = Mockito.mock(ClickEvent.class);
final Map<String,Object> asMap = new HashMap<>();
ArgumentCaptor<FieldGroup> fieldGroupArgumentCaptor = ArgumentCaptor.forClass(FieldGroup.class);
Mockito.when(bindingResultMapper.convert(fieldGroupArgumentCaptor.capture())).thenReturn(asMap);
final BindingResult bindingResult = Mockito.mock(BindingResult.class);
Mockito.when( personEditController.validateAndTakeOver(asMap, personEditModel)).thenReturn(bindingResult);
listener.buttonClick(event);
Mockito.verify(bindingResultMapper, Mockito.times(1)).mapInto(bindingResult, fieldGroupArgumentCaptor.getValue());
}
@Test
public final void enumForCoverageOnly() {
Arrays.stream(ContactEditorView.Fields.values()).map(field -> field.name() ).forEach(name -> Assert.assertEquals(name, ContactEditorView.Fields.valueOf(name).name()));
}
@Test
public final void deleteContact() {
final Button button = (Button) components.get(ContactEditorView.I18N_DELETE_CONTACT_BUTTON);
final ClickListener listener = (ClickListener) button.getListeners(ClickEvent.class).iterator().next();
final ClickEvent event = Mockito.mock(ClickEvent.class);
listener.buttonClick(event);
Mockito.verify(personEditModel).notifyObservers(PersonEditModel.EventType.ContactDeleted);
}
}
|
package accountReceivable;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.sql.Date;
public class FirmDB
{
public FirmDB() throws SQLException, ClassNotFoundException, IOException
{
Connection conn = SimpleDataSource.getConnection();
Statement stat = conn.createStatement();
Statement stat5 = conn.createStatement();
try
{
try{
stat.execute("DROP TABLE InvoiceTable");}
catch(SQLException rious){
System.out.println(rious.getMessage());
}
try{
stat.execute("DROP TABLE CustomerTable");}
catch(SQLException s){
System.out.println(s.getMessage());
}
try
{
stat5.execute("CREATE TABLE CustomerTable (CustomerID INT NOT NULL PRIMARY KEY, FirstName VARCHAR(20), LastName VARCHAR(20))");
}
catch(SQLException ez)
{
System.out.println("Exception during create table sequence: "+ ez.getMessage());
}
try
{
stat.execute("CREATE TABLE InvoiceTable (InvoiceID int NOT NULL PRIMARY KEY, DateIssued DATE, DateDue DATE, AmountDue DOUBLE PRECISION, CustomerID INT) ");
}
catch(SQLException ezee)
{
System.out.println("Exception during create table sequence2: "+ ezee.getMessage());
}
int customerIDs[] = {1,2,3,4};
String firstNames[] = {"Jon","Kitten","Winter","Aragorn"};
String lastNames[] = {"Snow","Mittens","Wyvern","King of Gondor"};
int invoiceIDs[] = {1,2,3,4};//yyyy-MM-dd
Date datesDue[] = {new Date(1999,01,01), new Date(2001,05,11), new Date(1994,06,04), new Date(1776,07,04)};
Date datesIssued[] = {new Date(90,11,3), new Date(1943,06,01), new Date(1930,05,07), new Date(1812,05,10)};
System.out.println("LOL" + datesIssued[2]);
double amountsDue[] = {0.00, 99.87, 54.24, 21.61};
stat.close();
try
{
//initializing the db customer
for(int i = 0; i<customerIDs.length; i++)
{
try
{
PreparedStatement stat2 = conn.prepareStatement("INSERT INTO CustomerTable (CustomerID, FirstName, LastName) VALUES (?, ?, ?)");
stat2.setInt(1, customerIDs[i]);
stat2.setString(2, firstNames[i]);
stat2.setString(3, lastNames[i]);
stat2.execute();
stat2.close();
}
catch(SQLException eze)
{
System.out.println("initialize loop fail" + eze.getMessage());
}
}
//initializing the db invoice
for(int i = 0; i<invoiceIDs.length; i++)
{
try
{
PreparedStatement stat2 = conn.prepareStatement("INSERT INTO InvoiceTable (InvoiceID, DateIssued, DateDue, AmountDue, CustomerID ) VALUES (?, ?, ?, ?, ?)");
System.out.println(invoiceIDs[i]);
stat2.setInt(1, invoiceIDs[i]);
stat2.setDate(2, datesIssued[i]);
stat2.setDate(3, datesDue[i]);
stat2.setDouble(4, amountsDue[i]);
stat2.setInt(5, customerIDs[i]);
stat2.execute();
stat2.close();
}
catch(SQLException eze)
{
System.out.println("initialize loop fail inv" + eze.getMessage());
}
}
}
finally
{
conn.close();
}
}
finally{
System.out.println("hurray");
}
}
}
|
package pro.likada.service.serviceImpl;
import pro.likada.dao.AddressApartmentTypeDAO;
import pro.likada.model.AddressApartmentType;
import pro.likada.service.AddressApartmentTypeService;
import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.List;
/**
* Created by bumur on 05.01.2017.
*/
@Named("addressApartmentTypeService")
@Transactional
public class AddressApartmentTypeServiceImpl implements AddressApartmentTypeService, Serializable {
@Inject
private AddressApartmentTypeDAO addressApartmentTypeDAO;
@Override
public List<AddressApartmentType> getAllAddressApartmentTypes() {
return addressApartmentTypeDAO.getAllAddressApartmentTypes();
}
}
|
// The "Game_Frame" class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class Game_Frame extends JFrame implements KeyListener //, ActionListener
{
//Declaring Global variables
//Declaring all the pictures
ImageIcon road, water, player, log, log2, log3, log4, log5, grass1, grass2, grass3, grass4, fly, fly2, car, car2, car3, car4, car5, car6;
//player postion, frequency of the timers. Score, life and fly counnter
int playerX = 600, playerY = 850, freq = 1000, freq2 = 200, score = 0, lives = 3, flyCount = 0, fly2Count = 0;
//Log x values
int x = 1030, x2 = 500, x3 = 1030, x4 = 500, x5 = 1030;
//Car x values
int carX = 0, carX2 = 400, carX3 = 800, carX4 = 1130, carX5 = 800, carX6 = 400;
//Declraing Timers
Timer logTimer, carTimer, flyTimer;
//Stores players name
String nam;
public Game_Frame ()
{
super ("Game_Frame"); // Set the frame's name
Toolkit dir = Toolkit.getDefaultToolkit ();
//Assigning images to each icon
road = new ImageIcon (dir.getImage ("RoadArt.jpg"));
water = new ImageIcon (dir.getImage ("WaterArt3.jpg"));
player = new ImageIcon (dir.getImage ("PlayerFrog.png"));
//Fly Sprites
fly = new ImageIcon (dir.getImage ("pixelFly.png"));
fly2 = new ImageIcon (dir.getImage ("pixelFly.png"));
//Log Sprites
log = new ImageIcon (dir.getImage ("LogPixel.png"));
log2 = new ImageIcon (dir.getImage ("LogPixel.png"));
log3 = new ImageIcon (dir.getImage ("LogPixel.png"));
log4 = new ImageIcon (dir.getImage ("LogPixel.png"));
log5 = new ImageIcon (dir.getImage ("LogPixel.png"));
//Grass Sprites
grass1 = new ImageIcon (dir.getImage ("PixelGrass.jpg"));
grass2 = new ImageIcon (dir.getImage ("PixelGrass2.png"));
grass3 = new ImageIcon (dir.getImage ("PixelGrass2.png"));
grass4 = new ImageIcon (dir.getImage ("PixelGrass2.png"));
//Car Sprites
car = new ImageIcon (dir.getImage ("carArt.png"));
car2 = new ImageIcon (dir.getImage ("carArt.png"));
car3 = new ImageIcon (dir.getImage ("carArt.png"));
car4 = new ImageIcon (dir.getImage ("carArt2.png"));
car5 = new ImageIcon (dir.getImage ("carArt2.png"));
car6 = new ImageIcon (dir.getImage ("carArt2.png"));
// Timer moves log across the screenn
logTimer = new Timer (frequency (freq, score), new ActionListener ()
{
public void actionPerformed (ActionEvent evt)
{
//Changes the x value of the logs to move accross the screen
x -= 50;
x2 -= 50;
x3 -= 50;
x4 -= 50;
x5 -= 75;
//Redraws all of the icons
repaint ();
//Checks if the logs go past the screen
//If logs pass the edge of screen, resets position
if (x <= 0)
{
x = 1030;
}
else if (x2 <= 0)
{
x2 = 1030;
}
else if (x3 <= 0)
{
x3 = 1030;
}
else if (x4 <= 0)
{
x4 = 1030;
}
else if (x5 <= 0)
{
x5 = 1030;
}
}
}
);
logTimer.start ();
//Timer moves car accross screen
carTimer = new Timer (frequency2 (freq2, score), new ActionListener ()
{
public void actionPerformed (ActionEvent e)
{
//Changes cars x value to move it across the screen
carX += 5;
carX2 += 5;
carX3 += 5;
carX4 -= 5;
carX5 -= 5;
carX6 -= 5;
//Checks if the car passes the screen
//if the car does pass the screen reset its position
if (carX >= 1130)
{
carX = 0;
}
else if (carX2 >= 1130)
{
carX2 = 0;
}
else if (carX3 >= 1130)
{
carX3 = 0;
}
else if (carX4 <= 0)
{
carX4 = 1130;
}
else if (carX5 <= 0)
{
carX5 = 1130;
}
else if (carX6 <= 0)
{
carX6 = 1130;
}
}
}
);
carTimer.start ();
//Ask the player for their name
nam = JOptionPane.showInputDialog ("What is your name?");
JOptionPane.showMessageDialog ("Dodge cars and logs. Swim and collect as many flys as possible");
addKeyListener (this);
setSize (1280, 900); // Set the frame's size
show (); // Show the frame
} // Constructor
//-----------------------------------------------------------------------------------------
public void paint (Graphics g)
{
road.paintIcon (this, g, 0, 450);
water.paintIcon (this, g, 0, 0);
//Painting cars
car.paintIcon (this, g, carX, 750);
car2.paintIcon (this, g, carX2, 750);
car3.paintIcon (this, g, carX3, 750);
car4.paintIcon (this, g, carX4, 600);
car5.paintIcon (this, g, carX5, 600);
car6.paintIcon (this, g, carX6, 600);
//Painting grass
grass1.paintIcon (this, g, 0, 0);
grass2.paintIcon (this, g, 0, 50);
grass3.paintIcon (this, g, 500, 50);
grass4.paintIcon (this, g, 1030, 50);
//Painting logs
log.paintIcon (this, g, x, 500);
log2.paintIcon (this, g, x2, 500);
log3.paintIcon (this, g, x3, 350);
log4.paintIcon (this, g, x4, 350);
log5.paintIcon (this, g, x5, 200);
//If the player has not touched a fly then paint the fly
if (flyCount == 0)
{
fly.paintIcon (this, g, 330, 150);
}
if (fly2Count == 0)
{
fly2.paintIcon (this, g, 800, 150);
}
//Paint player last so it does not get covered by other images
player.paintIcon (this, g, playerX, playerY);
//If the player touches a fly then send player back to start and add 50 points
if (flyCollision (playerX, playerY) == true)
{
playerX = 600;
playerY = 850;
score += 50;
flyCount += 1;
}
if (flyCollision2 (playerX, playerY) == true)
{
playerX = 600;
playerY = 850;
score += 50;
fly2Count += 1;
}
//Calls the collision methods
if (logCollision (playerX, playerY, x, x2, x3, x4, x5) == true)
{
//if there is collision send player back to start
playerX = 600;
playerY = 850;
lives -= 1;
}
if (carCollision (playerX, playerY, carX, carX2, carX3, carX4, carX5, carX6) == true)
{
//if there is collision send player back to start
playerX = 600;
playerY = 850;
lives -= 1;
}
//if lives = 0 stop timers and print out highscore
if (lives == 0)
{
logTimer.stop ();
carTimer.stop ();
highscore (score, nam);
}
Font gfont = new Font ("TimesNewRoman", 1, 25);
g.setFont (gfont);
g.setColor (Color.white);
g.drawString ("Lives: " + lives, 10, 75);
g.drawString ("Score: " + score, 1130, 75);
if (flyCount >= 1 && fly2Count >= 1)
{
flyCount = 0;
fly2Count = 0;
}
} // paint method
//-----------------------------------------------------------------------------------------
//Player movement
public void keyPressed (KeyEvent e)
{
//Checks which key is pressed
if (e.getKeyCode () == KeyEvent.VK_LEFT)
{
playerX -= 50;
}
else if (e.getKeyCode () == KeyEvent.VK_RIGHT)
{
playerX += 50;
}
else if (e.getKeyCode () == KeyEvent.VK_UP)
{
playerY -= 50;
}
else if (e.getKeyCode () == KeyEvent.VK_DOWN)
{
playerY += 50;
}
this.repaint ();
}
//-----------------------------------------------------------------------------------------
//Checks if player collieds with the logs
public static boolean logCollision (int playerX, int playerY, int x, int x2, int x3, int x4, int x5)
{
//Creates the player hit box
Rectangle rectPlayer = new Rectangle (playerX, playerY, playerX + 10, playerY + 10);
//Creates log hit boxs
Rectangle rectLog = new Rectangle (x, 500, x + 250, 480);
Rectangle rectLog2 = new Rectangle (x2, 500, x2 + 250, 480);
Rectangle rectLog3 = new Rectangle (x3, 350, x3 + 250, 330);
Rectangle rectLog4 = new Rectangle (x4, 350, x4 + 250, 330);
Rectangle rectLog5 = new Rectangle (x5, 200, x5 + 250, 180);
//Puts all rectangles, x values and y values in an array
Rectangle rectArray[] = {rectLog, rectLog2, rectLog3, rectLog4, rectLog5};
int posXLog[] = {x, x2, x3, x4, x5};
int posYLog[] = {500, 500, 350, 350, 200};
//Checks if the rectangles intersect
for (int i = 0 ; i < 5 ; i++)
{
Rectangle rectColli = rectArray [i].intersection (rectPlayer);
if (playerX <= posXLog [i] + 250 && playerX > posXLog [i])
if (playerY <= posYLog [i] + 20 && playerY > posYLog [i] - 20)
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------------------
public static boolean carCollision (int playerX, int playerY, int carX, int carX2, int carX3, int carX4, int carX5, int carX6)
{
//Creates the player hit box
Rectangle rectPlayer = new Rectangle (playerX, playerY, playerX + 10, playerY + 10);
//Creates log hit boxs
Rectangle rectCar = new Rectangle (carX, 750, carX + 150, 715);
Rectangle rectCar2 = new Rectangle (carX2, 750, carX2 + 150, 715);
Rectangle rectCar3 = new Rectangle (carX3, 750, carX3 + 150, 715);
Rectangle rectCar4 = new Rectangle (carX4, 600, carX4 + 150, 565);
Rectangle rectCar5 = new Rectangle (carX5, 600, carX5 + 150, 565);
Rectangle rectCar6 = new Rectangle (carX6, 600, carX6 + 150, 565);
//Puts all rectangles, x values and y values in an array
Rectangle rectArray[] = {rectCar, rectCar2, rectCar3, rectCar4, rectCar5, rectCar6};
int posXLog[] = {carX, carX2, carX3, carX4, carX5, carX6};
int posYLog[] = {750, 750, 750, 600, 600, 600};
//Checks if the rectangles intersect
for (int i = 0 ; i < 6 ; i++)
{
Rectangle rectColli = rectArray [i].intersection (rectPlayer);
if (rectColli.width > posXLog [i] && rectColli.height >= posYLog [i] - 35)
{
if (rectColli.width < posXLog [i] + 150 && rectColli.height <= posYLog [i])
{
return true;
}
}
}
return false;
}
//-----------------------------------------------------------------------------------------
public static boolean flyCollision (int playerX, int playerY)
{
//Creates the hit boxes
Rectangle rectPlayer = new Rectangle (playerX, playerY, playerX + 5, playerY + 5);
Rectangle rectFly = new Rectangle (330, 150, 325, 145);
Rectangle rectColli = rectFly.intersection (rectPlayer);
//Checks if the boxes intersects
if (rectColli.width <= 309 && rectColli.width >= 275)
{
if (rectColli.height <= 150 && rectColli.height >= 145)
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------------------
public static boolean flyCollision2 (int playerX, int playerY)
{
//Creates the hit boxes
Rectangle rectPlayer = new Rectangle (playerX, playerY, playerX + 5, playerY + 5);
Rectangle rectFly = new Rectangle (800, 150, 795, 145);
Rectangle rectColli = rectFly.intersection (rectPlayer);
//Checks if the boxes intersects
if (rectColli.width <= 800 && rectColli.width >= 795)
{
if (rectColli.height <= 150 && rectColli.height >= 145)
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------------------
public static int frequency (int freq, int score)
{
//The higher score the player has the lower the frequency
freq = freq - score;
return freq;
}
public static int frequency2 (int freq2, int score)
{
freq2 = freq2 - (score / 2);
return freq2;
}
//-----------------------------------------------------------------------------------------
public static void highscore (int score, String nam)
{
try
{
//Creates file reader
FileReader file = new FileReader ("highscore.txt");
BufferedReader input = new BufferedReader (file);
//Creates the arrays
String names[];
int allScores[];
names = new String [10];
allScores = new int [10];
//Reads from file and stores it in an array
for (int i = 0 ; i < names.length ; i++)
{
names [i] = input.readLine ();
allScores [i] = Integer.parseInt (input.readLine ());
}
//Sorts the names and score
for (int k = 0 ; k < names.length ; k++)
{
for (int j = 0 ; j < names.length - 1 ; j++)
{
if (allScores [j] > allScores [j + 1])
{
int tempScore = allScores [j];
allScores [j] = allScores [j + 1];
allScores [j + 1] = tempScore;
String tempName = names [j];
names [j] = names [j + 1];
names [j + 1] = tempName;
}
}
}
//Checks if the player's score is in the top ten
for (int v = names.length - 1 ; v >= 0 ; v--)
{
if (score > allScores [v])
{
allScores [v] = score;
names [v] = nam;
v = -1;
}
}
//Closes file
input.close ();
//Creates file writer
FileWriter outFile = new FileWriter ("highscore.txt");
PrintWriter output = new PrintWriter (outFile);
System.out.println ("Highscore");
//Writes scores to file and prints out highscore
for (int z = names.length - 1 ; z >= 0 ; z--)
{
System.out.println (names [z] + " , " + allScores [z]);
output.println (names [z]);
output.println (allScores [z]);
}
output.close ();
outFile.close ();
//Searches to see if players are in the top ten
int count = 0;
for (int c = 0 ; c < names.length ; c++)
{
if (nam.equals (names [c]))
{
System.out.println ("\n" + "You are ranked: " + (names.length - c) + "\n" + "Good Job!");
c = names.length;
count = 1;
}
}
if (count == 0)
{
System.out.println ("\n" + "Better luck next time");
}
}
catch (Exception e)
{
}
}
//-----------------------------------------------------------------------------------------
public void keyReleased (KeyEvent e)
{
}
public void keyTyped (KeyEvent e)
{
}
//-----------------------------------------------------------------------------------------
public static void main (String[] args)
{
new Game_Frame (); // Create a Game_Frame frame
} // main method
} // Game_Frame class
|
package uk.ac.ebi.intact.view.webapp;
/**
* @author Bruno Aranda (baranda@ebi.ac.uk)
* @version $Id$
*/
public interface Constants {
String BASE_URL = "http://localhost:33444/intact";
}
|
package ShopLite.entity;
public class Product {
private int sortIndex;
private String name;
private int price;
public Product(String name, int price, int sortIndex) {
this.sortIndex = sortIndex;
this.name = name;
this.price = price;
}
public Product(int sortIndex) {
this.sortIndex = sortIndex;
}
@Override
public String toString() {
return "index: " + sortIndex + " name: " + name + " price: " + price;
}
public int getIndex() {
return sortIndex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
|
package com.moviee.moviee.services;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.moviee.moviee.ApiStrings.DatabaseStrings;
import com.moviee.moviee.Interfaces.ServiceCallback;
import com.moviee.moviee.models.ApiParameter;
import com.moviee.moviee.models.Cast;
import com.moviee.moviee.models.Genres;
import com.moviee.moviee.models.Movie;
import com.moviee.moviee.models.Scores;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class TheMovieDB extends MovieService {
private ServiceCallback callback;
private Context context;
private int indexVideoSearch = 0;
private boolean language = false;
private String currentUrl = "";
public TheMovieDB(ServiceCallback callback, Context context){
super("6a14837d062d6498be918fc82a1d2275");
this.callback = callback;
this.context = context;
}
public void SearchFilm(String name)
{
currentUrl = "https://api.themoviedb.org/3/search/movie?";
List<ApiParameter> parameterList = new ArrayList<>();
parameterList.add(new ApiParameter("query", name.replace(" ", "+")));
getServerResponse(parameterList, context, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
List<Movie> listOfMovies = new ArrayList<Movie>();
try {
JSONArray arr = new JSONObject(response.body().string()).getJSONArray("results");
for (int i = 0; i < arr.length(); i++)
{
Movie movie = getMovieInfo(arr.getJSONObject(i));
if(movie!= null)
listOfMovies.add(movie);
}
callback.onResponse(listOfMovies);
}
catch (Exception exception) { callback.onResponse(new ArrayList()); }
}
});
}
public void getMovieCast(String movieId) {
currentUrl = "https://api.themoviedb.org/3/movie/" + movieId + "/credits?";
getServerResponse(new ArrayList<ApiParameter>(), context, new Callback() {
@Override public void onFailure(Call call, IOException e) { }
@Override public void onResponse(Call call, Response response) throws IOException {
List<Cast> cast = new ArrayList<Cast>();
try {
JSONArray arr = new JSONObject(response.body().string()).getJSONArray("cast");
for(int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
String url = "https://image.tmdb.org/t/p/w300_and_h450_bestv2" + obj.getString("profile_path");
String name = obj.getString("name");
String chatacter = obj.getString("character");
cast.add(new Cast(name, chatacter, url));
}
callback.onResponse(cast);
}
catch (Exception exd) { exd.printStackTrace(); callback.onResponse(cast); }
}
});
}
public void getGenreList()
{
currentUrl = "https://api.themoviedb.org/3/genre/movie/list?";
List<ApiParameter> lan = new ArrayList<>();
lan.add(new ApiParameter("language", ""));
getServerResponse(language ? lan : new ArrayList<ApiParameter>(), context, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
List<Genres> ids = new ArrayList<>();
try {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String res = response.body().string();
prefs.edit().putString("genres", res).apply();
JSONArray arr = new JSONObject(res).getJSONArray("genres");
for (int i = 0; i < arr.length(); i++)
{
JSONObject object = arr.getJSONObject(i);
if(!object.getString("name").equals("null") || ids.size() > 0)
ids.add(new Genres(object.getString("name"), object.getString("id")));
else
{
throw new Exception();
}
}
callback.onResponse(ids);
}
catch (Exception exception) {exception.printStackTrace(); if(language) callback.onResponse(new ArrayList()); else { language = true; getGenreList();} }
}
});
}
public void getPersonId(final String name)
{
currentUrl = "https://api.themoviedb.org/3/search/person?";
List<ApiParameter> parameterList = new ArrayList<>();
parameterList.add(new ApiParameter("query", name.replace(" ", "+")));
getServerResponse(parameterList, context, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
List<String> id = new ArrayList();
try
{
JSONArray arr = new JSONObject(response.body().string()).getJSONArray("results");
if(computeLevenshteinDistance(name.toLowerCase().replace(" ", ""), arr.getJSONObject(0).getString("name").replace(" ", "")) < 3)
{
id.add(arr.getJSONObject(0).getString("id"));
}
callback.onResponse(id);
}
catch (Exception exd) { callback.onResponse(id);}
}
});
}
public void getMovieVideo(final String id, final String title)
{
currentUrl = "https://api.themoviedb.org/3/movie/" + id +"/videos?";
List<ApiParameter> parameterList = new ArrayList<>();
getServerResponse(new ArrayList<ApiParameter>(), context, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try
{
JSONArray arr = new JSONObject(response.body().string()).getJSONArray("results");
List<String> ids = new ArrayList();
if(arr.length() > 0) {
String name = arr.getJSONObject(0).getString("site");
String idVideo = arr.getJSONObject(0).getString("key");
if(name.toLowerCase().equals("youtube"))
ids.add(idVideo);
}
if(ids.size() > 0)
callback.onResponse(ids);
else
getMovieVideoGoogle(title, false);
}
catch (Exception exd) { callback.onResponse(new ArrayList());}
}
});
}
public void getMovieVideoGoogle(final String title, final boolean makeItFalseAlways)
{
final Thread thread = new Thread() {
@Override
public void run() {
try {
List<String> l = new ArrayList<>();
if(indexVideoSearch != 2) {
String url = indexVideoSearch == 0 ? "https://www.google.com/search?gfns=1&sourceid=navclient&q=" + title.replace(" ", "+") + "+youtube+site:youtube.com"
: "https://www.google.it/search?sclient=psy-ab&biw=1536&bih=777&q=" + title.replace(" ", "+") + "+youtube%20site:youtube.com&oq=" + title.replace(" ", "+") + "+youtube%20site:youtube.com&gs_l=hp.9..35i39k1j0j0i22i30k1l2.0.0.1.16694.0.0.0.0.0.0.0.0..0.0....0...1c..64.psy-ab..0.0.0.uwjBxXgDCI0&pbx=1&btnI=1";
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection.setInstanceFollowRedirects(true);
connection.connect();
connection.getInputStream();
String url1 = connection.getURL().toString();
if (url1.contains("/watch?v")) {
String idVideo = url1;
String finalO = "";
int index = idVideo.length();
while (!(idVideo.charAt(--index) + "").contains("="))
finalO = idVideo.charAt(index) + finalO;
l.add(finalO);
}
if(l.size() == 0)
throw new Exception();
callback.onResponse(l);
}
else
{
throw new Exception();
}
}
catch (Exception exd)
{
//
if(indexVideoSearch++ == 2)
{
callback.onResponse(new ArrayList());
}
}
}
};
thread.start();
}
public static String getFinalURL(String url) throws IOException {
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setInstanceFollowRedirects(false);
con.connect();
con.getInputStream();
if (con.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || con.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
String redirectUrl = con.getHeaderField("Location");
return getFinalURL(redirectUrl);
}
return url;
}
public void getMovieReview(final String id, final boolean goCallback)
{
currentUrl = "http://api.themoviedb.org/3/movie/" + id + "/reviews?";
List<ApiParameter> parameterList = new ArrayList<>();
if(goCallback)
parameterList.add(new ApiParameter("language", "no"));
getServerResponse(parameterList, context, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try
{
JSONArray arr = new JSONObject(response.body().string()).getJSONArray("results");
List<String> id = new ArrayList();
String name = arr.getJSONObject(0).getString("author");
String idVideo = arr.getJSONObject(0).getString("content");
id.add(name);
id.add(idVideo);
callback.onResponse(id);
}
catch (Exception exd) { if(goCallback) callback.onResponse(new ArrayList()); else getMovieReview(id, true);}
}
});
}
public void getSimilarFilms(String filmName)
{
filmName = filmName.replace(" ", "+");
final ServiceCallback toAdd = callback;
callback = new ServiceCallback() {
@Override
public void onResponse(List list) {
callback = toAdd;
if(list.size() == 0)
callback.onResponse(new ArrayList());
else
{
currentUrl = "https://api.themoviedb.org/3/movie/" + ((Movie)list.get(0)).id + "/similar?";
getServerResponse(new ArrayList<ApiParameter>(), context, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try
{
JSONArray arr = new JSONObject(response.body().string()).getJSONArray("results");
List<Movie> listMovies = new ArrayList<>();
for(int i = 0; i < arr.length(); i++)
{
Movie movie = getMovieInfo(arr.getJSONObject(i));
if(movie!= null)
listMovies.add(movie);
}
callback.onResponse(listMovies);
}
catch (Exception exd) {callback.onResponse(new ArrayList());}
}
});
}
}
};
this.SearchFilm(filmName);
}
public void getSimilarFilmsById(String filmID) {
currentUrl = "https://api.themoviedb.org/3/movie/" + filmID + "/similar?";
getServerResponse(new ArrayList<ApiParameter>(), context, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
JSONArray arr = new JSONObject(response.body().string()).getJSONArray("results");
List<Movie> listMovies = new ArrayList<>();
for (int i = 0; i < arr.length(); i++) {
Movie movie = getMovieInfo(arr.getJSONObject(i));
if (movie != null)
listMovies.add(movie);
}
callback.onResponse(listMovies);
} catch (Exception exd) {
callback.onResponse(new ArrayList());
}
}
});
}
public void getMovieByFilter(final LinkedHashMap<String, String> filters, final String page)
{
currentUrl = "https://api.themoviedb.org/3/discover/movie?";
final List<ApiParameter> apiParameters = new ArrayList<>();
apiParameters.add(new ApiParameter("page", page));
if(filters.containsKey(DatabaseStrings.FIELD_INITIAL_DATE)) {
apiParameters.add(new ApiParameter("primary_release_date.gte", filters.get(DatabaseStrings.FIELD_INITIAL_DATE)));
}
if(filters.containsKey(DatabaseStrings.FIELD_FINAL_DATE))
apiParameters.add(new ApiParameter("primary_release_date.lte", filters.get(DatabaseStrings.FIELD_FINAL_DATE)));
if(filters.containsKey(DatabaseStrings.FIELD_RATE)) {
apiParameters.add(new ApiParameter("vote_average.gte", ( Integer.parseInt( filters.get(DatabaseStrings.FIELD_RATE)) - 1) + ""));
}
if(filters.containsKey(DatabaseStrings.FIELD_GENRE_ID)) {
apiParameters.add(new ApiParameter("with_genres", filters.get(DatabaseStrings.FIELD_GENRE_ID)));
}
if(filters.containsKey(DatabaseStrings.FIELD_ACTOR_ID)) {
apiParameters.add(new ApiParameter("with_people", filters.get(DatabaseStrings.FIELD_ACTOR_ID)));
}
if(filters.containsKey("language"))
apiParameters.add(new ApiParameter("language", "no"));
if(filters.containsKey(DatabaseStrings.FIELD_ORDER))
apiParameters.add(new ApiParameter("sort_by", filters.get(DatabaseStrings.FIELD_ORDER)));
else
apiParameters.add(new ApiParameter("sort_by", "popularity.desc"));
getServerResponse(apiParameters, context, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final List<Movie> movies = new ArrayList<Movie>();
try {
JSONArray arr = new JSONObject(response.body().string()).getJSONArray("results");
int noOverview = 0;
for(int i = 0; i < arr.length(); i++) {
Movie movie = getMovieInfo(arr.getJSONObject(i));
if(movie!= null) {
if(movie.generalInfo.length() < 3)
noOverview++;
movies.add(movie);
}
}
final ServiceCallback thisOne = callback;
callback = new ServiceCallback() {
@Override
public void onResponse(List list) {
callback = thisOne;
if(list.size() > 0)
{
for(int i = 0; i < list.size(); i++)
{
if(movies.get(i).generalInfo.length() < 3 && movies.get(i).id.equals(((Movie) list.get(i)).id))
{
movies.get(i).generalInfo = ((Movie) list.get(i)).generalInfo;
}
}
}
if(filters.containsKey(DatabaseStrings.FIELD_SIMILAR_TO) && page.equals("1")) {
final ServiceCallback temp = callback;
callback = new ServiceCallback() {
@Override
public void onResponse(List list) {
callback = temp;
for(int i = 0; i < list.size(); i++) { // i film sono circa
// posizioni: 0, 3,
movies.add(i*3 > list.size() ? list.size() : i*3, (Movie)list.get(i));
}
callback.onResponse(movies);
}
};
getSimilarFilms(filters.get(DatabaseStrings.FIELD_SIMILAR_TO));
}
else {
callback.onResponse(movies);
}
}
};
if(noOverview > 12)
{
filters.put("language", "");
getMovieByFilter(filters, page);
}
else
callback.onResponse(new ArrayList());
}
catch (Exception exd) {callback.onResponse(new ArrayList());}
}
});
}
public void getRatings(String film)
{
currentUrl = "http://www.omdbapi.com/?t=" + film.replace(" ", "+").toLowerCase()+ "&";
List<ApiParameter> parameterList = new ArrayList<>();
getServerResponse(parameterList, context, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try
{
JSONObject obj = new JSONObject(response.body().string());
String imdb = obj.getString("imdbRating");
String meta = obj.getString("Metascore");
List<Scores> id = new ArrayList<Scores>();
id.add(new Scores(imdb, meta));
callback.onResponse(id);
}
catch (Exception exd) { callback.onResponse(new ArrayList()); }
}
});
}
public boolean existMovieInList(List<Movie> list, Movie movie)
{
for(int i = 0; i < list.size(); i++)
{
if(((Movie)list.get(i)).id.equals(movie.id))
return true;
}
return false;
}
public Movie getMovieInfo(JSONObject json)
{
try {
String name = json.getString("title");
String url = "https://image.tmdb.org/t/p/w300_and_h450_bestv2" + json.getString("poster_path");
String info = json.getString("overview");
JSONArray arr = json.getJSONArray("genre_ids");
String genre = "";
for(int i = 0; i < arr.length(); i++)
genre += json.getJSONArray("genre_ids").getString(i) + ",";
if(genre.length() > 0)
genre = genre.substring(0, genre.length() - 1);
else
genre = "no genres";
String releaseDate = json.getString("release_date");
String id = json.getString("id");
String rating = json.getString("vote_average");
Movie movie = new Movie(name, url, info, genre, releaseDate, id, rating);
return movie;
}
catch (Exception exd) {return null; }
}
@Override
String getBaseUrl() {
return currentUrl;
}
@Override
String getServiceName() {
return "TheMusicDB";
}
@Override
String getApiParameterKeyName() {
return "api_key";
}
}
|
package com.kid19911010.datavisualizetool.service;
import com.kid19911010.datavisualizetool.entity.SlowLogAnalysisReport;
import java.io.InputStream;
/**
* @Description:
* @Author 吴道亮 {dlwu2@iflytek.com}
* @Date 2018/10/25 16:13
*/
public interface AnalyseDataFileService {
SlowLogAnalysisReport analyseDataFile(InputStream in) throws Exception;
}
|
package com.gateway.client;
public class HostedSession {
private String id;
private String version;
private String successIndicator;
public HostedSession() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getSuccessIndicator() {
return successIndicator;
}
public void setSuccessIndicator(String successIndicator) {
this.successIndicator = successIndicator;
}
}
|
/*
* 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 application;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author listya
*/
public class AverageSensor implements Sensor {
private List<Sensor> lists;
private List<Integer> reads;
public AverageSensor() {
this.lists = new ArrayList<>();
this.reads = new ArrayList<>();
}
public void addSensor(Sensor toAdd) {
this.lists.add(toAdd);
}
@Override
public boolean isOn() {
for (Sensor sensor : lists) {
if (sensor.isOn()) {
return true;
}
}
return false;
}
@Override
public void setOn() {
this.lists.stream().forEach(sensor -> sensor.setOn());
}
@Override
public void setOff() {
this.lists.stream().forEach(sensor -> sensor.setOff());
}
@Override
public int read() {
if (!isOn()) {
throw new IllegalStateException("Average Sensor is off");
}
double average = 0;
int stats = this.lists.stream().map(sensor -> sensor.read())
.reduce(0,(prev,value) -> prev + value);
average = (double) stats / (double) this.lists.size();
reads.add((int)average);
return (int) average;
}
public List<Integer> readings() {
return reads;
}
}
|
package org.testing.testScript;
public class TC_3 {
// login - click on library - logout
}
|
/**
* Created with IntelliJ IDEA.
* User: dexctor
* Date: 12-11-22
* Time: 下午9:13
* To change this template use File | Settings | File Templates.
*/
public class p1_3_27 {
public static void main(String[] args)
{
Queue<Integer> queue = new Queue<Integer>();
Integer now = StdIn.readInt();
while (!now.equals(0))
{
queue.enqueue(now);
now = StdIn.readInt();
}
StdOut.println(queue.recursiveMax());
}
}
|
package com.zxt.compplatform.formengine.action;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.zxt.compplatform.formengine.constant.Constant;
import com.zxt.compplatform.formengine.dao.ComponentsDao;
import com.zxt.compplatform.formengine.entity.view.EditPage;
import com.zxt.compplatform.formengine.entity.view.Field;
import com.zxt.compplatform.formengine.entity.view.ListPage;
import com.zxt.compplatform.formengine.entity.view.PagerEntiy;
import com.zxt.compplatform.formengine.entity.view.Param;
import com.zxt.compplatform.formengine.entity.view.QueryColumn;
import com.zxt.compplatform.formengine.entity.view.QueryZone;
import com.zxt.compplatform.formengine.service.ComponentsService;
import com.zxt.compplatform.formengine.service.PageService;
import com.zxt.compplatform.formengine.service.QueryXmlDataService;
import com.zxt.compplatform.formengine.service.SystemFrameService;
import com.zxt.compplatform.formengine.util.StrTools;
import com.zxt.compplatform.formengine.util.WorkFlowDataStautsXmlUtil;
import com.zxt.compplatform.workflow.Util.WorkFlowUtil;
import com.zxt.compplatform.workflow.entity.TaskFormNodeEntity;
import com.zxt.compplatform.workflow.entity.WorkFlowDataStauts;
import com.zxt.compplatform.workflow.service.WorkFlowFrameService;
import com.zxt.framework.dictionary.entity.DataDictionary;
import com.zxt.framework.dictionary.entity.SqlObj;
import com.zxt.framework.dictionary.service.IDataDictionaryService;
import com.zxt.framework.dictionary.service.ISqlDicService;
/**
* 界面组件操作Action
* @author 007
*/
public class ComponentsAction extends ActionSupport {
private static final Logger log = Logger.getLogger(ComponentsAction.class);
private ComponentsService componentsService;
/**
* 字典操作接口 GUOWEIXIN
*/
private ISqlDicService sqlDicService;
/**
* 表单组件持久化接口 GUOWEIXIN
*/
private ComponentsDao componentsDao;
/**
* 界面业务操作接口
*/
private PageService pageService;
/**
* xml数据查询操作接口
*/
private QueryXmlDataService queryXmlDataService;
/**
* 系统业务操作接口
*/
private SystemFrameService systemFrameService;
/**
* 工作流业务操作接口
*/
private WorkFlowFrameService workFlowFrameService;
/**
* 数据字典业务操作接口
*/
private IDataDictionaryService iDataDictionaryService;
/**
* json传递数据
*/
private String json;
/**
* 表单id
*/
private String formId;
/**
* 选择列
*/
private String[] selectColumns;
public String[] getSelectColumns() {
return selectColumns;
}
public void setSelectColumns(String[] selectColumns) {
this.selectColumns = selectColumns;
}
public String getFormId() {
return formId;
}
public void setFormId(String formId) {
this.formId = formId;
}
public String execute() throws Exception {
return null;
}
/**
* 级联下拉框
*
* @return
*/
public String loadCasCadeSel() {
String dataSourceId = Request().getParameter("dataSourceId");
String querySql = Request().getParameter("querySql");
String dictionaryId = Request().getParameter("dictionaryId");
String newValue = Request().getParameter("newValue");
Object[] conditions = new Object[] {};
if (dictionaryId != null && !dictionaryId.equals("")) {
DataDictionary dictionary = iDataDictionaryService
.findById(dictionaryId);
querySql = dictionary.getExpression();
dataSourceId = dictionary.getDataSource().getId();
conditions = new Object[] { newValue };
}
// dataSourceId = "0a83565f28b013048632ca023d812125";
// querySql = "select f.id id,f.name value from LMS_D_TSK_TYPE f";
HttpServletResponse response = ServletActionContext.getResponse();
PrintWriter out = null;
try {
out = response.getWriter();
List selList = componentsService.queryByDataSource(dataSourceId,
querySql, conditions);
out.print(JSONArray.fromObject(selList).toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
return null;
}
/**
* 删除数据
*
* @return
*/
public String deleteData() {
String formId = Request().getParameter("listFormID");
ListPage listPage = null;
Map map = pageService.load_service(formId);
if (map != null) {
if (map.get("listPage") != null) {
listPage = (ListPage) map.get("listPage");
listPage.setId(formId);
componentsService.deleteData(listPage, Request());
}
}
return null;
}
/**
* 刷新列表数据 + 组合查询
*
* @return
*/
public String reshData() {
String formId = Request().getParameter("formId");
Map map = pageService.load_service(formId);
PagerEntiy pagerEntiy=null;
if (map != null) {
ListPage listPage = (ListPage) map.get("listPage");
if (listPage != null) {
List listParmer = listPage.getListPageParams();
listPage.setId(formId);
Param param = null;
String[] value = null;
boolean flag = true;
/**
* 获取 参数值
*
*/
if (listParmer != null) {
if (listParmer.size() != 0) {
String key = "";
String parmerValue = "";
value = new String[listParmer.size()];
for (int i = 0; i < value.length; i++) {
param = (Param) listParmer.get(i);
key = param.getKey().trim();
if ("SYSPARAM".equals(param.getFlagType())) {
parmerValue = Request().getSession().getAttribute(key)+"";
}else {
parmerValue = Request().getParameter(key).trim();
parmerValue = StrTools.charsetFormat(parmerValue,
"ISO8859-1", "UTF-8");
}
if ((parmerValue == null)
|| "".equals(parmerValue.trim())) {
flag = false;
}
value[i] = parmerValue;
}
}
}
Map data = new HashMap();
List formList = null;
try {
if (flag) {
pagerEntiy = queryXmlDataService.queryFormData(listPage,
value, Request());
formList=pagerEntiy.getResult();
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
if (formList != null) {
String menuId = Request().getParameter("menuId");
formList = componentsService.findMenuFilter(menuId,
formList);
String isPreview = Request().getParameter("preview");
if ("extjs".equals(isPreview)) {
data.put("success", "true");
//data.put("result", pagger(Request(), formList));
data.put("totalCounts", new Integer(formList.size()));
json = JSONObject.fromObject(data).toString();
} else {
data.put("total", pagerEntiy.getTotal());
//formList = pagger(Request(), formList);
formList = WorkFlowDataStautsXmlUtil
.transferListWorkFlowStauts(formList);
data.put("rows", formList);
json = JSONObject.fromObject(data).toString();
}
json = JSONObject.fromObject(data).toString();
} else {
json = "{total:0,rows:[]}";
}
}
} else {
json = "{total:0,rows:[]}";
}
return "json";
}
/**
* 查询人员列表
*
* @return
*/
public String queryForHumanList() {
String orgid = Request().getParameter("orgid");
String dictionaryID = Request().getParameter("dictionaryId");
String state = Request().getParameter("state");
List list = componentsService.queryForHumanList(orgid, dictionaryID,
state);
Map map = new HashMap();
if (list == null) {
list = new ArrayList();
}
map.put("rows", list);
map.put("total", new Integer(list.size()));
String json = JSONObject.fromObject(map).toString();
try {
ServletActionContext.getResponse().getWriter().write(json);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 保存编辑页数据
*
* @return
*/
public String dynamicSave() {
String savetype = Request().getParameter("type");
String method = Request().getParameter("method");
try {
EditPage editPage = null;
String formId = Request().getParameter("formId");
Map map = null;
map = pageService.load_service(formId);
if (map != null) {
if (map.get("editPage") != null) {
editPage = (EditPage) map.get("editPage");
}
}
if (editPage != null) {
editPage.setId(formId);
String opertorType = Request().getParameter("opertorType");
/**
* 0 不启用工作 -1 启动异常
*/
WorkFlowDataStauts workflowDataStauts = new WorkFlowDataStauts();
/**
* 启动流程实例 start
*/
if (savetype != null && "save".equals(savetype.trim())) {
TaskFormNodeEntity taskFormNodeEntity = workFlowFrameService
.findTaskFormNodeEntity(formId);
if (taskFormNodeEntity != null) {
HttpServletRequest req = Request();
// workFlowFrameService.startProcessInstance(taskFormNodeEntity,
// req);
workFlowFrameService.startProcessInstance(
taskFormNodeEntity, req, editPage);
/**
* 获取工作流状态信息对象 xml格式
*/
// workflowDataStauts = WorkFlowDataStautsXmlUtil
// .workFlowDataStautsToXml(WorkFlowUtil
// .findInitActivity(taskFormNodeEntity
// .getProcessInstanceID()));
/**
* 动态表单启动流程时 保存工作流状态
*/
String processInstanceID = "";
if (Request().getParameter(
Constant.CUSTOM_PROCESSDEFID_ID) != null
&& !"".equals(Request().getParameter(
Constant.CUSTOM_PROCESSDEFID_ID))) {
processInstanceID = Request().getParameter(
Constant.CUSTOM_PROCESSDEFID_ID);
} else {
processInstanceID = taskFormNodeEntity
.getProcessInstanceID();
}
workflowDataStauts = WorkFlowUtil.findInitActivity(
processInstanceID, savetype);
}
} else if (savetype != null
&& "transave".equals(savetype.trim())) {
workflowDataStauts
.setToTransferDefStauts_text(Constant.WORKFLOW_QIDONG_STATE);
}
/**
* 启动流程实例 end
*/
// 保存业务数据
if ("copy".equals(method)) {
// editPage.setId(RandomGUID.geneGuid());
}
/**
* 测试大数据量
*/
componentsService.dynamicSave(Request(), editPage,
workflowDataStauts);
//此处取数据 得到保存前SQL和保存后SQL的 ID 此处只要保存后SQL
//String beforeSqlId=editPage.getBefore_sql();
String afterSqlId=editPage.getAfter_sql();
saveAfterSql(afterSqlId);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
log.error("启用了工作流,提交数据时用户未登录");
}
try {
ServletActionContext.getResponse().getWriter().write("sucess");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 保存后SQL
* @param afterSqlId:String SQL语句/触发器/存储过程ID
*/
public void saveAfterSql(String afterSqlId){
if(!"".equals(afterSqlId) && null!=afterSqlId){
SqlObj sqlObj=sqlDicService.findSqlById(afterSqlId);
//得到其SqlObj 对象 进行执行该SQL条件语句
/*
* param1:数据源ID,param2:执行的SQL语句,param3:条件 null,null
*/
String[] conditions=null;
List listParam=new ArrayList();
listParam=sqlObj.getSqlParam();
if(listParam.size()>0){
conditions=new String[listParam.size()];
}
for(int i=0;i<listParam.size();i++){
Param param=(Param)listParam.get(i);
if("1".equals(param.getType())){//手动输入
conditions[i]= param.getValue();
}
if("3".equals(param.getType())){//变量
conditions[i]= ServletActionContext.getRequest().getParameter(param.getValue());
}
}
List list = componentsDao.queryForAfterSql(sqlObj.getSqldic_dataSourceid(),sqlObj.getSqldic_expression(), conditions, Request());
}
}
/**
* 获取 数据字典值 动态 ,静态
*
* @return
*/
public String loadDictionary() {
Map map = new HashMap();
String dictionaryID = Request().getParameter("dictionaryID");
componentsService.load_Dictionary(dictionaryID);
return null;
}
public ComponentsService getComponentsService() {
return componentsService;
}
public void setComponentsService(ComponentsService componentsService) {
this.componentsService = componentsService;
}
public HttpServletRequest Request() {
return ServletActionContext.getRequest();
}
public QueryXmlDataService getQueryXmlDataService() {
return queryXmlDataService;
}
public void setQueryXmlDataService(QueryXmlDataService queryXmlDataService) {
this.queryXmlDataService = queryXmlDataService;
}
public String getJson() {
return json;
}
public void setJson(String json) {
this.json = json;
}
public PageService getPageService() {
return pageService;
}
public void setPageService(PageService pageService) {
this.pageService = pageService;
}
public List pagger(HttpServletRequest request, List data) {
List temList = null;
try {
temList = new ArrayList();
/**
* jquery方式
*/
int pageNum = Integer.parseInt(Request().getParameter("page"));
int size = Integer.parseInt(Request().getParameter("rows"));
int end = pageNum * size;
int start = end - size;
// int size = Integer.parseInt(Request().getParameter("limit"));
// int start = Integer.parseInt(Request().getParameter("start"));
// int end = start + size;
/**
* ExtJs方式
*/
int maxSize = data.size();
if (end > maxSize) {
end = maxSize;
}
if (start < 0) {
start = 0;
}
for (int i = start; i < end; i++) {
temList.add(data.get(i));
}
} catch (Exception e) {
// TODO: handle exception
temList = data;
}
return temList;
}
/**
* 批量删除
*
* @return
*/
public String bulkDelete() {
try {
String formId = Request().getParameter("listFormID");
ListPage listPage = (ListPage) (pageService.load_service(formId)
.get("listPage"));
listPage.setId(formId);
componentsService.bulkDelete(listPage, Request());
} catch (Exception e) {
// TODO: handle exception
log.error(" bulkDelete id error and listPage id error.. ");
}
return null;
}
/**
* 导出datagrid的流
*
* @return
*/
public String exportForListPage() {
return "export";
}
/**
* 导出datagrid的流
*
* @return
*/
public InputStream getDownloadFile() {
// TODO Auto-generated method stub
ListPage listPage = null;
if(formId==null)
formId = Request().getParameter("formId");
Map map = pageService.load_service(formId);
String sql="";
if (map != null) {
listPage = (ListPage) map.get("listPage");
sql=listPage.getSql();
}
HttpServletRequest request = ServletActionContext.getRequest();
QueryZone queryZone = null;
List queryColumns = null;
QueryColumn queryColumn = null;
String orderBy = "";
String condition_fiter = "";
List queryZoneList =listPage.getQueryZone();
if (queryZoneList!=null) {
try {
for (int j = 0; j < queryZoneList.size(); j++) {
queryZone = (QueryZone) queryZoneList.get(j);
queryColumns = queryZone.getQueryColumns();
if (sql.indexOf("where")<0) {
sql=sql+" where 1=1";
}
for (int i = 0; i < queryColumns.size(); i++) {
queryColumn = (QueryColumn) queryColumns.get(i);
/*
* 构件排序方式
*/
if(!queryColumn.getListSort().equals("")){
if(orderBy.equals("")){
orderBy = " order by ";
orderBy += queryColumn.getTableName() + "." + queryColumn.getName() + " " + queryColumn.getListSort();
}else{
orderBy = orderBy + " ," + queryColumn.getTableName() + "." + queryColumn.getName() + " " + queryColumn.getListSort();
}
}
switch (queryColumn.getOperateType()) {
case 1://模糊查询
if ((request.getParameter(queryColumn.getName()) != null)
&& (!"".equals(request.getParameter(queryColumn
.getName())))) {
sql = sql + " and " + queryColumn.getName() + " = '"
+ request.getParameter(queryColumn.getName())
+ "'";
}
break;
case 2://大于
if ((request.getParameter(queryColumn.getName()) != null)
&& (!"".equals(request.getParameter(queryColumn
.getName())))) {
try {
int parmer=Integer.parseInt(request.getParameter(queryColumn.getName()));
sql = sql + " and " + queryColumn.getName() + " >"
+ parmer+" ";
} catch (Exception e) {
// TODO: handle exception
log.error("大于 操作符,控件未配置验证。。");
}
}
break;
case 3://小于
if ((request.getParameter(queryColumn.getName()) != null)
&& (!"".equals(request.getParameter(queryColumn
.getName())))) {
try {
int parmer=Integer.parseInt(request.getParameter(queryColumn.getName()));
sql = sql + " and " + queryColumn.getName() + " <"
+ parmer+" ";
} catch (Exception e) {
// TODO: handle exception
log.error("小于 操作符,控件未配置验证。。");
}
}
break;
case 4://模糊查询
if ((request.getParameter(queryColumn.getName()) != null)
&& (!"".equals(request.getParameter(queryColumn
.getName())))) {
sql = sql + " and " + queryColumn.getName() + " like '%"
+ StrTools.charsetFormat(request.getParameter(queryColumn.getName()).trim(),
"ISO8859-1", "UTF-8")
+ "%'";
}
break;
case 5://in
if ((request.getParameter(queryColumn.getName()) != null)
&& (!"".equals(request.getParameter(queryColumn
.getName())))) {
sql = sql + " and " + queryColumn.getName() + " in ('"
+ request.getParameter(queryColumn.getName())
+ "')";
}
break;
case 6://范围查询
String start=request.getParameter(queryColumn.getName()+"_st");
String end=request.getParameter(queryColumn.getName()+"_end");
if ((!"".equals(start)&&(start!=null))&&((!"".equals(end)))&&(end!=null)) {
try {
sql = sql + " and (" + queryColumn.getName() + " between '"
+ start+ "' and '"+end+"')";
} catch (Exception e) {
// TODO: handle exception
log.error("范围查询,控件未配置验证,或控件类型不对。。");
}
}else{
if (("".equals(start)&&(start==null))&&("".equals(end))&&(end==null)){
continue;
}else if((!"".equals(start)&&(start!=null))){
try {
sql = sql + " and " + queryColumn.getName() + " > '"+start+"'";
} catch (Exception e) {
// TODO: handle exception
log.error("范围查询,控件未配置验证,或控件类型不对。。");
}
}else if(!("".equals(end))&&(end!=null)){
try {
sql = sql + " and " + queryColumn.getName() + " < '"+end+"'";
} catch (Exception e) {
// TODO: handle exception
log.error("范围查询,控件未配置验证,或控件类型不对。。");
}
}
}
break;
default:
if ((request.getParameter(queryColumn.getName()) != null)
&& (!"".equals(request.getParameter(queryColumn
.getName())))) {
sql = sql + " and " + queryColumn.getName() + " like '%"
+ request.getParameter(queryColumn.getName())
+ "%'";
}
break;
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
if (sql.indexOf("where")<0) {
sql=sql+" where 1=1";
}
sql= sql +condition_fiter;
sql = sql + orderBy;
listPage.setSql(sql);
return componentsService.exportForListPage(formId, listPage, Request(),
selectColumns);
}
/**
*
* @author HouLiangWei
* @createTime Jul 9, 2011 2:43:48 PM
*
* @param
* @function 确定导出excel工作簿的名字
* @return
* @throws
*/
public String getDownloadChineseFileName() {
String downloadChineseFileName = "数据列表.xls";
try {
downloadChineseFileName = new String(downloadChineseFileName
.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return downloadChineseFileName;
}
/**
* 通过页面id获取字段
*
* @return
*/
public void findFiedsByPageId() {
// TODO Auto-generated method stub
ListPage listPage = null;
Map map = pageService.load_service(formId);
if (map != null) {
listPage = (ListPage) map.get("listPage");
}
List list = listPage.getFields();
List newlist = new ArrayList();
for (int i = 0; i < list.size(); i++) {
Field column = (Field) list.get(i);
if (!column.getVisible().equals("false")) {// 判断是否 只显示列表字段的导出
Map mapxxx = new HashMap();
mapxxx.put("column", column.getDataColumn());
mapxxx.put("name", column.getName());
newlist.add(mapxxx);
}
}
String xxx = JSONArray.fromObject(newlist).toString();
try {
ServletActionContext.getResponse().getWriter().print(xxx);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public SystemFrameService getSystemFrameService() {
return systemFrameService;
}
public void setSystemFrameService(SystemFrameService systemFrameService) {
this.systemFrameService = systemFrameService;
}
public WorkFlowFrameService getWorkFlowFrameService() {
return workFlowFrameService;
}
public void setWorkFlowFrameService(
WorkFlowFrameService workFlowFrameService) {
this.workFlowFrameService = workFlowFrameService;
}
public IDataDictionaryService getIDataDictionaryService() {
return iDataDictionaryService;
}
public void setIDataDictionaryService(
IDataDictionaryService dataDictionaryService) {
iDataDictionaryService = dataDictionaryService;
}
public ISqlDicService getSqlDicService() {
return sqlDicService;
}
public void setSqlDicService(ISqlDicService sqlDicService) {
this.sqlDicService = sqlDicService;
}
public ComponentsDao getComponentsDao() {
return componentsDao;
}
public void setComponentsDao(ComponentsDao componentsDao) {
this.componentsDao = componentsDao;
}
}
|
package com.yc.education.service.impl.check;
import com.github.pagehelper.PageHelper;
import com.yc.education.mapper.check.TimecardMapper;
import com.yc.education.model.check.Timecard;
import com.yc.education.service.check.TimecardService;
import com.yc.education.service.impl.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @ClassName TimecardServiceImpl
* @Description TODO 原始考勤资料
* @Author QuZhangJing
* @Date 2019/2/18 14:04
* @Version 1.0
*/
@Service("TimecardService")
public class TimecardServiceImpl extends BaseService<Timecard> implements TimecardService {
@Autowired
private TimecardMapper timecardMapper;
@Override
public List<Timecard> findTimecardByUserOrderAndTime(int status,String startOrder, String endOrder, String startTime, String endTime) {
try {
return timecardMapper.findTimecardByUserOrderAndTime(status,startOrder, endOrder, startTime, endTime);
}catch (Exception e){
return null;
}
}
@Override
public List<Timecard> findTimecardByUserOrderAndTime(int status,String startOrder, String endOrder, String startTime, String endTime, int pageNum, int pageSize) {
try {
PageHelper.startPage(pageNum, pageSize);
return timecardMapper.findTimecardByUserOrderAndTime(status,startOrder, endOrder, startTime, endTime);
}catch (Exception e){
return null;
}
}
}
|
package com.dihaitech.spiderstory.service.impl;
import java.util.List;
import javax.annotation.Resource;
import com.dihaitech.spiderstory.dao.IArticleColumnDAO;
import com.dihaitech.spiderstory.model.ArticleColumn;
import com.dihaitech.spiderstory.service.IArticleColumnService;
import com.dihaitech.spiderstory.util.Page;
/**
* 文章栏目 业务接口 IArticleColumnService 实现类
*
* @author cg
*
* @date 2014-08-27
*/
public class ArticleColumnServiceImpl implements IArticleColumnService {
@Resource
private IArticleColumnDAO articleColumnDAO;
/* (non-Javadoc)
* @see com.dihaitech.acomp.service.IArticleColumnService#addSave(com.dihaitech.acomp.model.ArticleColumn)
*/
public int addSave(ArticleColumn articleColumn) {
return articleColumnDAO.addSaveArticleColumn(articleColumn);
}
/* (non-Javadoc)
* @see com.dihaitech.acomp.service.IArticleColumnService#deleteByIds(java.lang.String)
*/
public int deleteByIds(String str) {
return articleColumnDAO.deleteByIds(str);
}
/* (non-Javadoc)
* @see com.dihaitech.acomp.service.IArticleColumnService#editSave(com.dihaitech.acomp.model.ArticleColumn)
*/
public int editSave(ArticleColumn articleColumn) {
return articleColumnDAO.editSaveArticleColumn(articleColumn);
}
/* (non-Javadoc)
* @see com.dihaitech.acomp.IArticleColumnService#selectAll()
*/
public List<ArticleColumn> selectAll() {
return articleColumnDAO.selectAll();
}
/* (non-Javadoc)
* @see com.dihaitech.acomp.service.IArticleColumnService#selectArticleColumn(com.dihaitech.acomp.model.ArticleColumn, int)
*/
public Page selectArticleColumn(ArticleColumn articleColumn, int pageSize) {
return new Page(articleColumnDAO.getArticleColumnCount(articleColumn), pageSize);
}
/* (non-Javadoc)
* @see com.dihaitech.acomp.service.IArticleColumnService#selectArticleColumn(com.dihaitech.acomp.model.ArticleColumn, com.dihaitech.acomp.controller.helper.Page)
*/
public List<ArticleColumn> selectArticleColumn(ArticleColumn articleColumn, Page page) {
articleColumn.setStart(page.getFirstItemPos());
articleColumn.setPageSize(page.getPageSize());
return articleColumnDAO.selectArticleColumnLike(articleColumn);
}
/* (non-Javadoc)
* @see com.dihaitech.acomp.service.IArticleColumnService#selectArticleColumnById(com.dihaitech.acomp.model.ArticleColumn)
*/
public ArticleColumn selectArticleColumnById(ArticleColumn articleColumn) {
return articleColumnDAO.selectArticleColumnById(articleColumn);
}
/* (non-Javadoc)
* @see com.dihaitech.acomp.service.IArticleColumnService#selectArticleColumnByChannelId(com.dihaitech.acomp.model.ArticleColumn)
*/
@Override
public List<ArticleColumn> selectArticleColumnByChannelId(
ArticleColumn articleColumn) {
// TODO Auto-generated method stub
return articleColumnDAO.selectArticleColumnByChannelId(articleColumn);
}
/* (non-Javadoc)
* @see com.dihaitech.acomp.service.IArticleColumnService#selectArticleColumnByIds(com.dihaitech.acomp.model.ArticleColumn)
*/
@Override
public List<ArticleColumn> selectArticleColumnByIds(
ArticleColumn articleColumn) {
// TODO Auto-generated method stub
return articleColumnDAO.selectArticleColumnByIds(articleColumn);
}
/* (non-Javadoc)
* @see com.dihaitech.acomp.service.IArticleColumnService#selectArticleColumnByCode(com.dihaitech.acomp.model.ArticleColumn)
*/
@Override
public ArticleColumn selectArticleColumnByCode(ArticleColumn articleColumn) {
// TODO Auto-generated method stub
return articleColumnDAO.selectArticleColumnByCode(articleColumn);
}
/* (non-Javadoc)
* @see com.dihaitech.acomp.service.IArticleColumnService#selectArticleColumnByCodes(com.dihaitech.acomp.model.ArticleColumn)
*/
@Override
public List<ArticleColumn> selectArticleColumnByCodes(
ArticleColumn articleColumn) {
// TODO Auto-generated method stub
return articleColumnDAO.selectArticleColumnByCodes(articleColumn);
}
}
|
package cn.mccreefei.zhihu.dao.domain;
import lombok.Builder;
import lombok.Data;
import java.util.Date;
/**
* @author MccreeFei
* @create 2018-01-19 16:36
*/
@Data
public class UserDo {
private Integer id;
private String characterUrl;
private String headUrl;
private String userName;
private String simpleDescription;
private Integer thanks;
private Integer agrees;
private Integer collects;
private Integer followers;
private Integer followees;
private Date createTime;
private Date modifyTime;
public UserDo(){}
@Builder
public UserDo(Integer id, String characterUrl, String headUrl, String userName, String simpleDescription,
Integer thanks, Integer agrees, Integer collects, Integer followers,
Integer followees, Date createTime, Date modifyTime) {
this.id = id;
this.characterUrl = characterUrl;
this.headUrl = headUrl;
this.userName = userName;
this.simpleDescription = simpleDescription;
this.thanks = thanks;
this.agrees = agrees;
this.collects = collects;
this.followers = followers;
this.followees = followees;
this.createTime = createTime;
this.modifyTime = modifyTime;
}
}
|
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class HangmanGui implements ActionListener {
private JButton checkButton; //setting up the jframe components
private JTextField letter;
private GridBagLayout gridbag = new GridBagLayout();
private JLabel hangmanPic;
private JLabel usedLetters;
private JLabel hiddenWord;
private JLabel hints;
private JLabel hints2;
private JLabel hints3;
private JLabel tries;
public int p;
private Dictionary dict; //creating dictionary object
private String word; //picking random word from dictionary
public Hangman h; //creating new hangman variable storage object
/*public static void main(String[] args) {
new HangmanMain();
}*/
public void actionPerformed(ActionEvent e) {
if (e.getSource()==checkButton) {
String temp = letter.getText();
letter.setText("");
if (p==1){ //once the game is won or lost p is set to 1, so when the player clicks the play again button the HangmanGui object closes
HangmanMain.restart();
}
if (h.getTriesLeft() > 1){//if there is more than one try left
h.checkWord(temp); //takes the string in the input and brings it to the Hangman class, where it is turned into a char and compared with each char of the word.
usedLetters.setText(h.getResponseStorage()); //what letters have been used. This is stored by the Hangman class
hiddenWord.setText(h.getUnderscoreWord());//the progress of the hidden word. This is stored by the Hangman class
tries.setText("" + (h.getTriesLeft())); //how many tries left
if (h.getWon() == true){ //if the player won. this method is on the Hangman class and is determined if the edited word is the same as the original
hints.setText("You Win!");
checkButton.setText("Play Again");
p = 1;
}
String img = e.getActionCommand();
if (h.getTriesLeft() == 6){ // different images depending on the number of tries left
ImageIcon picture = new ImageIcon("hangman.png");
hangmanPic.setIcon(picture);
} else if (h.getTriesLeft() == 5){
ImageIcon picture = new ImageIcon("hangman2.png");
hangmanPic.setIcon(picture);
} else if (h.getTriesLeft() == 4){
ImageIcon picture = new ImageIcon("hangman3.png");
hangmanPic.setIcon(picture);
} else if (h.getTriesLeft() == 3){
ImageIcon picture = new ImageIcon("hangman4.png");
hangmanPic.setIcon(picture);
} else if (h.getTriesLeft() == 2){
ImageIcon picture = new ImageIcon("hangman5.png");
hangmanPic.setIcon(picture);
} else if (h.getTriesLeft() == 1){
ImageIcon picture = new ImageIcon("hangman6.png");
hangmanPic.setIcon(picture);
} else if (h.getTriesLeft() == 0){
ImageIcon picture = new ImageIcon("hangman7.png");
hangmanPic.setIcon(picture);
}
} else {
hints.setText("You Lose! The word was:"); // if the number of tries left is one, the player loses.
checkButton.setText("Play Again");
hiddenWord.setText(h.getWord());
p = 1; //sets p to one for resetting the program
tries.setText("0");
ImageIcon picture = new ImageIcon("hangman7.png");
hangmanPic.setIcon(picture);
}
}
}
public HangmanGui() {
dict = new Dictionary();
word = dict.getWord();
h = new Hangman(word);
p = 0;
JFrame frame = new JFrame("Hangman");
frame.setPreferredSize(new Dimension(640,480));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contents = frame.getContentPane();
contents.setLayout(gridbag); //setting the layout as gridbad, a very flexible layout that is similar to gridlayout
GridBagConstraints c = new GridBagConstraints();
contents.setBackground(Color.white);
ImageIcon picture = new ImageIcon("hangman.png"); //adding the components to the jframe, specifying the location on the grid, the size, and how it is oriented
hangmanPic = new JLabel(picture);
hangmanPic.setPreferredSize(new Dimension(300,300));
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridwidth = 2;
c.gridy = 1;
gridbag.setConstraints(hangmanPic, c);
contents.add(hangmanPic);
usedLetters = new JLabel("Used Letters: ");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridwidth = 2;
c.gridy = 5;
gridbag.setConstraints(usedLetters, c);
contents.add(usedLetters);
hiddenWord = new JLabel("_______");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridwidth = 1;
c.gridy = 3;
gridbag.setConstraints(hiddenWord, c);
contents.add(hiddenWord);
hints = new JLabel("Guess the letters of the word:");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridwidth = 1;
c.gridy = 3;
gridbag.setConstraints(hints, c);
contents.add(hints);
hints2 = new JLabel("Tries Remaining:");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridwidth = 1;
c.gridy = 2;
gridbag.setConstraints(hints2, c);
contents.add(hints2);
tries = new JLabel("6");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridwidth = 1;
c.gridy = 2;
gridbag.setConstraints(tries, c);
contents.add(tries);
checkButton = new JButton("Check");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridwidth = 1;
c.gridy = 4;
gridbag.setConstraints(checkButton, c);
contents.add(checkButton);
letter = new JTextField("", 17);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridwidth = 1;
c.gridy = 4;
gridbag.setConstraints(letter, c);
contents.add(letter);
checkButton.addActionListener(this);
frame.pack();
frame.setVisible(true);
}
}
|
package net.lvcy.card.entity.gate.mid;
import net.lvcy.card.core.AbstarctCard;
import net.lvcy.card.entity.gate.MidCard;
import net.lvcy.card.eumn.CardType;
public class FiveFive extends AbstarctCard implements MidCard {
public FiveFive() {
this.type = CardType.FIVE_FIVE;
}
}
|
package com.mariusgrams.dynamicgridlib.gridItems;
import com.mariusgrams.dynamicgrid.GridItem;
public class ExampleGridItem2 extends GridItem {
public ExampleGridItem2(int row, int column) {
super(row, column);
}
public ExampleGridItem2(int row, int column, int rowSpan, int columnSpan) {
super(row, column, rowSpan, columnSpan);
}
}
|
package vision.view.test;
import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBException;
import org.junit.Test;
import vision.model.Model;
import vision.model.Position;
import vision.model.Sample;
import vision.model.Sensor;
import vision.view.HeaterPlugin;
import vision.view.View;
import vision.view.WindowPlugin;
import com.jme3.app.Application;
import com.jme3.app.state.AppStateManager;
import com.jme3.asset.DesktopAssetManager;
public class PluginTest {
@Test
public void testHeaterPluginInitialize() {
View v = new View();
Model m = Model.createModel(v);
Application app = new Application();
AppStateManager stateManager = new AppStateManager(app);
HeaterPlugin heaterPlugin = new HeaterPlugin(m, v);
heaterPlugin.initialize(stateManager, app);
assertNotNull(heaterPlugin);
}
@Test
public void testHeaterPLugin(){
Sample sample1 = new Sample("heater", "celsius", 20, 0);
Sample sample2 = new Sample("heater", "celsius", 21, 0);
View v = new View();
Model m = Model.createModel(v);
List<Sensor> list = new ArrayList<Sensor>();
List<Sample> sensor1list = new ArrayList<Sample>();
sensor1list.add(sample1);
Sensor sensor1 = new Sensor("sensor1", 0, sensor1list);
sensor1.setPosition(new Position(0, 0, 0));
List<Sample> sensor2list = new ArrayList<Sample>();
sensor2list.add(sample2);
Sensor sensor2 = new Sensor("sensor2", 0, sensor2list);
sensor2.setPosition(new Position(10, 0, 0));
list.add(sensor1);
list.add(sensor2);
m.setSensor(list);
Position sensor1pos = new Position(0, 0, 0);
sensor1.setPosition(sensor1pos);
Position sensor2pos = new Position(10, 1, 1);
sensor2.setPosition(sensor2pos);
HeaterPlugin heaterPlugin = new HeaterPlugin(m, v);
Application app = new Application();
app.setAssetManager(new DesktopAssetManager(true));
AppStateManager stateManager = new AppStateManager(app);
heaterPlugin.initialize(stateManager, app);
heaterPlugin.setDaten(m);
heaterPlugin.update(20);
Sample sample3 = new Sample("heater", "celsius", 22, 0);
list.remove(sensor1);
sensor1.addToSamples(sample3);
list.add(sensor1);
m.setSensor(list);
try {
m.getGroundplan().load();
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
heaterPlugin.stateAttached(stateManager);
heaterPlugin.update(40);
Sample sample4 = new Sample("heater", "celsius", 25, 20);
List<Sample> sensor3List = new ArrayList<Sample>();
sensor3List.add(sample4);
Sensor sensor3 = new Sensor("sensor3", 20, sensor3List);
list.add(sensor3);
m.setSensor(list);
heaterPlugin.stateDetached(stateManager);
assertNotNull(m);
assertNotNull(v);
assertNotNull(heaterPlugin);
}
@Test
public void testWindowPlugin() {
Sample sample1 = new Sample("window", "", 100, 0);
Sample sample2 = new Sample("light", "", 1, 0);
View v = new View();
Model m = Model.createModel(v);
List<Sensor> list = new ArrayList<Sensor>();
List<Sample> sensor1list = new ArrayList<Sample>();
sensor1list.add(sample1);
Sensor sensor1 = new Sensor("sensor1", 0, sensor1list);
sensor1.setPosition(new Position(0, 0, 0));
List<Sample> sensor2list = new ArrayList<Sample>();
sensor2list.add(sample2);
Sensor sensor2 = new Sensor("sensor2", 0, sensor2list);
sensor2.setPosition(new Position(10, 0, 0));
list.add(sensor1);
list.add(sensor2);
m.setSensor(list);
Position sensor1pos = new Position(0, 0, 0);
sensor1.setPosition(sensor1pos);
Position sensor2pos = new Position(10, 1, 1);
sensor2.setPosition(sensor2pos);
WindowPlugin windowPlugin = new WindowPlugin(m, v);
Application app = new Application();
app.setAssetManager(new DesktopAssetManager(true));
AppStateManager stateManager = new AppStateManager(app);
windowPlugin.initialize(stateManager, app);
windowPlugin.setDaten(m);
windowPlugin.update(20);
Sample sample3 = new Sample("heater", "celsius", 22, 0);
list.remove(sensor1);
sensor1.addToSamples(sample3);
list.add(sensor1);
m.setSensor(list);
try {
m.getGroundplan().load();
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
windowPlugin.stateAttached(stateManager);
windowPlugin.update(40);
Sample sample4 = new Sample("heater", "celsius", 25, 20);
List<Sample> sensor3List = new ArrayList<Sample>();
sensor3List.add(sample4);
Sensor sensor3 = new Sensor("sensor3", 20, sensor3List);
list.add(sensor3);
m.setSensor(list);
windowPlugin.stateDetached(stateManager);
assertNotNull(m);
assertNotNull(v);
assertNotNull(windowPlugin);
}
}
|
package com.psing.professional_streaming.repository;
import com.psing.professional_streaming.dataobject.Student;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentRepository extends JpaRepository<Student,String> {
Student findByEmail(String email);
Student findBySno(String sno);
Page<Student> findAllByMajor(String major, Pageable pageable);
}
|
import java.io.IOException;
import USJavaAPI.AvsInfo;
import USJavaAPI.ResolveData;
import USJavaAPI.USResolverHttpsPostRequest;
import USJavaAPI.USResolverReceipt;
import USJavaAPI.USResTokenizeCC;
public class TestResTokenizeCC
{
public static void main(String args[]) throws IOException
{
/********************** Request Variables ****************************/
String host = "esplusqa.moneris.com";
String store_id = "monusqa002";
String api_token = "qatoken";
String order_id = "tokenizationtest1";
String txn_number = "611485-0_10";
String phone = "55555555555";
String email = "test.user@moneris.com";
String note = "my note";
String cust_id = "customer2";
AvsInfo avsCheck = new AvsInfo();
avsCheck.setAvsStreetNumber("212");
avsCheck.setAvsStreetName("Payton Street");
avsCheck.setAvsZipcode("M1M1M1");
USResTokenizeCC usResTokenizeCC = new USResTokenizeCC (order_id, txn_number);
usResTokenizeCC.setCustId(cust_id);
usResTokenizeCC.setPhone(phone);
usResTokenizeCC.setEmail(email);
usResTokenizeCC.setNote(note);
usResTokenizeCC.setAvsInfo(avsCheck);
USResolverHttpsPostRequest mpgReq =
new USResolverHttpsPostRequest(host, store_id, api_token, usResTokenizeCC);
try
{
USResolverReceipt resreceipt = mpgReq.getResolverReceipt();
ResolveData resdata = resreceipt.getResolveData();
System.out.println("DataKey = " + resreceipt.getDataKey());
System.out.println("ResponseCode = " + resreceipt.getResponseCode());
System.out.println("Message = " + resreceipt.getMessage());
System.out.println("TransDate = " + resreceipt.getTransDate());
System.out.println("TransTime = " + resreceipt.getTransTime());
System.out.println("Complete = " + resreceipt.getComplete());
System.out.println("TimedOut = " + resreceipt.getTimedOut());
System.out.println("ResSuccess = " + resreceipt.getResSuccess());
System.out.println("PaymentType = " + resreceipt.getPaymentType() + "\n");
//Contents of ResolveData
System.out.println("Cust ID = " + resdata.getResCustId());
System.out.println("Phone = " + resdata.getResPhone());
System.out.println("Email = " + resdata.getResEmail());
System.out.println("Note = " + resdata.getResNote());
System.out.println("MaskedPan = " + resdata.getResMaskedPan());
System.out.println("Exp Date = " + resdata.getResExpDate());
System.out.println("Crypt Type = " + resdata.getResCryptType());
System.out.println("Avs Street Number = " + resdata.getResAvsStreetNumber());
System.out.println("Avs Street Name = " + resdata.getResAvsStreetName());
System.out.println("Avs Zipcode = " + resdata.getResAvsZipcode());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
|
import java.awt.geom.*;
public final class Vec2 {
public static final Vec2 add(final Point2D.Double a, final Point2D.Double b) {
return new Point2D.Double(a.x + b.x, a.y + b.y);
}
public static final Vec2 sub(final Point2D.Double a, final Point2D.Double b) {
return new Point2D.Double(a.x - b.x, a.y - b.y);
}
public static final Vec2 mul(final Point2D.Double a, final double s) {
return new Point2D.Double(a.x * s, a.y * s);
}
public static final Vec2 div(final Point2D.Double a, final double s) {
return new Point2D.Double(a.x / s, a.y / s);
}
}
|
package Arrays;
public class ReverseArr {
public static void main(String[] args) {
ArrayOperation ao = ArrayOperation.getInstance();
int[] a = ao.readElement();
System.out.println("Entered array elements: ");
ao.dispArr(a);
int[] rev = ao.reverseArr(a);
System.out.println("Array elements after reversing elements");
ao.dispArr(rev);
}
}
|
package org.peterkwan.udacity.mysupermarket.widget;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import org.peterkwan.udacity.mysupermarket.R;
import static android.appwidget.AppWidgetManager.ACTION_APPWIDGET_UPDATE;
/**
* Implementation of App Widget functionality.
*/
public class MySupermarketWidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds)
updateAppWidget(context, appWidgetManager, appWidgetId);
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent != null && ACTION_APPWIDGET_UPDATE.equals(intent.getAction())) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, MySupermarketWidgetProvider.class));
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widget_list_view);
for (int appWidgetId : appWidgetIds)
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
private static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.mysupermarket_widget);
views.setRemoteAdapter(R.id.widget_list_view, new Intent(context, MySupermarketWidgetService.class));
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
|
package tabListeners;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.example.insurance.R;
/**
* A placeholder fragment containing a simple view.
*/
public class Step1Fragment extends ListFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_step1_tab,container, false);
return rootView;
}
}
|
package Domain;
public class Airbus {
private Voo voo;
private int numeroLugares = 5;
//private ArrayList<Integer> lugares = new ArrayList(numeroLugares);
public int getNumeroLugares() {
return numeroLugares;
}
public void setNumeroLugares(int numeroLugares) {
this.numeroLugares = numeroLugares;
}
public Voo getVoo() {
return voo;
}
public void setVoo(Voo voo) {
this.voo = voo;
}
}
|
package edu.sjsu.assignment3;
import java.time.LocalDate;
import java.util.Arrays;
/**
* A driver class for appointment class.
*
*/
public class Main {
public static void main(String[] args) {
LocalDate startDate = LocalDate.parse("2021-06-01");
LocalDate endDate = LocalDate.parse("2021-08-05");
// LocalDate testDate1 = LocalDate.parse("2021-06-05");
// LocalDate testDate2 = LocalDate.parse("2021-07-01");
// LocalDate testDate3 = LocalDate.parse("2021-08-15");
//
// Appointment appointment = new OnetimeAppointment("Class starts", startDate);
// Appointment appointment = new DailyAppointment("Class", startDate, endDate);
// Appointment appointment = new MonthlyAppointment("Meeting", startDate, endDate);
// boolean a1 = appointment.occursOn(testDate1);
// System.out.println(a1);
// boolean a2 = appointment.occursOn(testDate2);
// System.out.println(a2);
// boolean a3 = appointment.occursOn(testDate3);
// System.out.println(a3);
LocalDate date = LocalDate.parse("2021-08-01");
Appointment a1 = new OnetimeAppointment("Class starts", startDate);
Appointment a2 = new OnetimeAppointment("Class ends", endDate);
Appointment a3 = new DailyAppointment("Class", startDate, endDate);
Appointment a4 = new MonthlyAppointment("Code meeting", startDate, date);
Appointment a5 = new MonthlyAppointment("Assignment", startDate, endDate);
Appointment[] appointment = {a1, a2, a3, a4, a5};
Arrays.sort(appointment);
System.out.println("Comparable: " + Arrays.toString(appointment));
Arrays.sort(appointment, new DesComparator());
System.out.println("Comparator: " + Arrays.toString(appointment));
}
}
|
package norswap.autumn.visitors;
import norswap.autumn.Parser;
import norswap.autumn.ParserVisitor;
import norswap.autumn.parsers.*;
/**
* A visitor for built-in parsers that checks if the parser entails a repetition over some nullable
* parser(s) (see {@link _VisitorNullable}). These parsers are of interest because they are able to
* loop forever, as they keep invoking the same parser that successfully matches no input.
*
* <p>In fact, this visitor should be taken as an infinite loop/recursion detector (as long as the
* infinite loop is caused by lawful semantics, not by an implementation bug).
*
* <p>The result is stored within {@link #result()}, though it is more often retrieved via the
* return value of {@link #nullable_repetition(Parser)}.
*
* <p>Invocations of the visitor <b>must</b> set this value using {@link #set_result(boolean)}, so
* that the visitor may be reused for different parsers.
*
* <p>This visitor is used by {@link WellFormednessChecker}, which invokes it on all parsers
* in a parser graph.
*
* <p>An instantiable version is available as {@link VisitorNullableRepetition}.
*/
public interface _VisitorNullableRepetition extends ParserVisitor
{
// ---------------------------------------------------------------------------------------------
/**
* Provides the necessary {@link _VisitorNullable} to check if child parsers are nullable.
*/
_VisitorNullable nullable_visitor ();
// ---------------------------------------------------------------------------------------------
/**
* Whether the visited parser is a repetition over some nullable(s).
*/
boolean result();
// ---------------------------------------------------------------------------------------------
/**
* Set the result for the visited parser.
*/
void set_result (boolean value);
// ---------------------------------------------------------------------------------------------
/**
* Visit the given parser and return the {@link #result()}.
*/
default boolean nullable_repetition (Parser parser) {
parser.accept(this);
return result();
}
// ---------------------------------------------------------------------------------------------
/**
* Shortcut for {@code nullable_visitor().nullable(parser}.
*/
default boolean nullable (Parser parser) {
return nullable_visitor().nullable(parser);
}
// ---------------------------------------------------------------------------------------------
// Can't loop over a nullable parser.
@Override default void visit (AbstractChoice parser) { set_result(false); }
@Override default void visit (AbstractForwarding parser){ set_result(false); }
@Override default void visit (AbstractPrimitive parser) { set_result(false); }
@Override default void visit (CharPredicate parser) { set_result(false); }
@Override default void visit (Choice parser) { set_result(false); }
@Override default void visit (Collect parser) { set_result(false); }
@Override default void visit (Empty parser) { set_result(false); }
@Override default void visit (Fail parser) { set_result(false); }
@Override default void visit (GuardedRecursion parser) { set_result(false); }
@Override default void visit (LazyParser parser) { set_result(false); }
@Override default void visit (Longest parser) { set_result(false); }
@Override default void visit (Lookahead parser) { set_result(false); }
@Override default void visit (Memo parser) { set_result(false); }
@Override default void visit (Not parser) { set_result(false); }
@Override default void visit (ObjectPredicate parser) { set_result(false); }
@Override default void visit (Optional parser) { set_result(false); }
@Override default void visit (Sequence parser) { set_result(false); }
@Override default void visit (StringMatch parser) { set_result(false); }
@Override default void visit (TokenChoice parser) { set_result(false); }
@Override default void visit (TokenParser parser) { set_result(false); }
// ---------------------------------------------------------------------------------------------
// Does not loop: the seed has to grow.
@Override default void visit (LeftRecursive parser) { set_result(false); }
// ---------------------------------------------------------------------------------------------
// Assume unhandled custom parsers don't loop over nullable parsers.
@Override default void visit (Parser parser) { set_result(false); }
// ---------------------------------------------------------------------------------------------
@Override default void visit (Around parser)
{
set_result(!parser.exact && nullable(parser.around) && nullable(parser.inside));
}
// ---------------------------------------------------------------------------------------------
@Override default void visit (Repeat parser)
{
set_result(!parser.exact && nullable(parser.child));
}
// ---------------------------------------------------------------------------------------------
@Override default void visit (LeftAssoc parser)
{
set_result(nullable(parser.operator) && nullable(parser.right));
}
// ---------------------------------------------------------------------------------------------
@Override default void visit (RightAssoc parser)
{
set_result(nullable(parser.operator) && nullable(parser.left));
}
// ---------------------------------------------------------------------------------------------
}
|
package com.Amazon.qa.Pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LoginPage extends BasePage {
//PageFactory
@FindBy(id="ap_email")
WebElement uname;
@FindBy(id="ap_password")
WebElement paswd;
@FindBy(id="signInSubmit")
WebElement SignInBtn;
@FindBy(xpath= "//i[@class='a-icon a-icon-logo']")
WebElement AmazonLogo;
@FindBy(id="nav-link-accountList")
WebElement hello;
@FindBy(className="nav-action-inner")
WebElement btn;
@FindBy(xpath="//a[contains(text(),'Help')]")
WebElement helpLink;
//initialising the Page objects
public LoginPage() throws InterruptedException{
PageFactory.initElements(driver, this);
Actions action = new Actions(driver);
action.moveToElement(hello).build().perform();
//Thread.sleep(3000);
btn.click();
}
public String loginPageTitle() {
return driver.getTitle();
}
public boolean loginPageLogo() {
return AmazonLogo.isDisplayed();
}
public HomePage loginInToApp(){
uname.sendKeys("gouds.85@gmail.com");
paswd.sendKeys("riya2712");
SignInBtn.click();
return new HomePage();
}
public boolean helpLink() {
return helpLink.isDisplayed();
}
}
|
package ServicesAndInfo;
public enum DinoDiet {
HERBIVORE,
CARNIVORE,
OMNIVORE
}
|
package com.example.demo.models.service.solicitud;
import com.example.demo.models.dao.DISolicitud;
import com.example.demo.models.entity.Solicitud;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SSolicitudImpl implements SISolicitud {
@Autowired
private DISolicitud solicitudDao;
@Override
public void save(Solicitud solicitud) {
solicitudDao.save(solicitud);
}
@Override
public List<Solicitud> findAll() {
return (List<Solicitud>) solicitudDao.findAll();
}
@Override
public Solicitud findOne(Long id) {
return solicitudDao.findById(id).orElse(null);
}
@Override
public List<Solicitud> findByPersonaDni(String dni) {
return null;
}
@Override
public List<Solicitud> findByPersonaNombre(String nombre) {
return null;
}
}
|
package com.yuneec.flight_settings;
import android.util.Xml;
import com.yuneec.IPCameraManager.Cameras;
import com.yuneec.database.DBOpenHelper;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;
public class PullCameraParser implements CameraParser {
public List<Cameras> parse(InputStream is) throws Exception {
List<Cameras> cameras = null;
Cameras camera = null;
XmlPullParser parser = Xml.newPullParser();
parser.setInput(is, "UTF-8");
for (int eventType = parser.getEventType(); eventType != 1; eventType = parser.next()) {
switch (eventType) {
case 0:
cameras = new ArrayList();
break;
case 2:
if (!parser.getName().equals("camera")) {
if (!parser.getName().equals("id")) {
if (!parser.getName().equals(DBOpenHelper.KEY_NAME)) {
if (!parser.getName().equals("type")) {
if (!parser.getName().equals("dr")) {
if (!parser.getName().equals("f")) {
if (!parser.getName().equals("n")) {
if (!parser.getName().equals("t1")) {
if (!parser.getName().equals("t2")) {
if (!parser.getName().equals("intervalp")) {
if (!parser.getName().equals("codep")) {
if (!parser.getName().equals("intervalv")) {
if (!parser.getName().equals("codev")) {
break;
}
eventType = parser.next();
camera.setCodev(parser.getText());
break;
}
eventType = parser.next();
camera.setIntervalv(parser.getText());
break;
}
eventType = parser.next();
camera.setCodep(parser.getText());
break;
}
eventType = parser.next();
camera.setIntervalp(parser.getText());
break;
}
eventType = parser.next();
camera.setT2(parser.getText());
break;
}
eventType = parser.next();
camera.setT1(parser.getText());
break;
}
eventType = parser.next();
camera.setN(parser.getText());
break;
}
eventType = parser.next();
camera.setF(parser.getText());
break;
}
eventType = parser.next();
camera.setDr(parser.getText());
break;
}
eventType = parser.next();
camera.setType(parser.getText());
break;
}
eventType = parser.next();
camera.setName(parser.getText());
break;
}
eventType = parser.next();
camera.setId(Integer.parseInt(parser.getText()));
break;
}
camera = new Cameras();
break;
case 3:
if (!parser.getName().equals("camera")) {
break;
}
cameras.add(camera);
camera = null;
break;
default:
break;
}
}
return cameras;
}
public String serialize(List<Cameras> cameras) throws Exception {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
serializer.setOutput(writer);
serializer.startDocument("UTF-8", Boolean.valueOf(true));
serializer.startTag("", "cameras");
for (Cameras camera : cameras) {
serializer.startTag("", "camera");
serializer.attribute("", "id", new StringBuilder(String.valueOf(camera.getId())).toString());
serializer.startTag("", DBOpenHelper.KEY_NAME);
serializer.text(camera.getName());
serializer.endTag("", DBOpenHelper.KEY_NAME);
serializer.startTag("", "type");
serializer.text(new StringBuilder(String.valueOf(camera.getType())).toString());
serializer.endTag("", "type");
serializer.startTag("", "dr");
serializer.text(new StringBuilder(String.valueOf(camera.getDr())).toString());
serializer.endTag("", "dr");
serializer.startTag("", "f");
serializer.text(new StringBuilder(String.valueOf(camera.getF())).toString());
serializer.endTag("", "f");
serializer.startTag("", "n");
serializer.text(new StringBuilder(String.valueOf(camera.getN())).toString());
serializer.endTag("", "n");
serializer.startTag("", "t1");
serializer.text(new StringBuilder(String.valueOf(camera.getT1())).toString());
serializer.endTag("", "t1");
serializer.startTag("", "t2");
serializer.text(new StringBuilder(String.valueOf(camera.getT2())).toString());
serializer.endTag("", "t2");
serializer.startTag("", "intervalp");
serializer.text(new StringBuilder(String.valueOf(camera.getIntervalp())).toString());
serializer.endTag("", "intervalp");
serializer.startTag("", "codep");
serializer.text(new StringBuilder(String.valueOf(camera.getCodep())).toString());
serializer.endTag("", "codep");
serializer.startTag("", "intervalv");
serializer.text(new StringBuilder(String.valueOf(camera.getIntervalv())).toString());
serializer.endTag("", "intervalv");
serializer.startTag("", "codev");
serializer.text(new StringBuilder(String.valueOf(camera.getCodev())).toString());
serializer.endTag("", "codev");
serializer.endTag("", "camera");
}
serializer.endTag("", "cameras");
serializer.endDocument();
return writer.toString();
}
}
|
package Utilities;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class BrowserDriver {
public static WebDriver driver;
private String browserName;
public BrowserDriver(String browserName) {
this.browserName = browserName;
}
public void initializeDriver() {
if (browserName.equals("Chrome")) {
System.setProperty("webdriver.chrome.driver", "resources\\allBrowserDrivers\\chromedriver.exe");
//System.setProperty(arg0, arg1);
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
} else if (browserName.equals("IE")) {
System.setProperty("webdriver.ie.driver", "resources\\allBrowserDrivers\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
System.out.println("IE Instance created");
}
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}
public void navigateToUrl(String url)
{
driver.get(url);
}
public void closeDriver() {
if (driver != null)
driver.quit();
}
}
|
package com.soa.command;
import com.soa.ws.hero.WSDragon;
import lombok.Getter;
import java.net.URI;
import java.net.URISyntaxException;
@Getter
public class DragonsRestCommand extends AbstractRestCommand<WSDragon> {
private String postfix = "/heroes/dragons";
public DragonsRestCommand() {
super(WSDragon.class);
}
@Override
public WSDragon[] getAll() {
try {
URI uri = new URI(BASIC_API_URI + postfix);
return restTemplate.getForObject(uri, WSDragon[].class);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return new WSDragon[]{};
}
}
|
public class LC415 {
static String addStrings(String num1, String num2) {
StringBuilder res=new StringBuilder();
int i=num1.length()-1,j=num2.length()-1;
int ca=0;
while(i>=0||j>=0){
int a=i>=0?num1.charAt(i)-'0':0;
int b=j>=0?num2.charAt(j)-'0':0;
int num=a+b+ca;
ca=num/10;int y=num%10;
res.append(y);
i--;j--;
}
if(ca==1){res.append(ca);}
return res.reverse().toString();
}
public static void main(String[] args) {
String num1="17";
String num2="116";
String num=addStrings(num1,num2);
System.out.print(num);
}
}
|
package org.wso2.carbon.identity.user.endpoint.dto;
import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.*;
import javax.validation.constraints.NotNull;
@ApiModel(description = "")
public class UserDTO {
private String username = null;
private String tenantDomain = null;
private String realm = null;
/**
**/
@ApiModelProperty(value = "")
@JsonProperty("username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
/**
**/
@ApiModelProperty(value = "")
@JsonProperty("tenant-domain")
public String getTenantDomain() {
return tenantDomain;
}
public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain;
}
/**
**/
@ApiModelProperty(value = "")
@JsonProperty("realm")
public String getRealm() {
return realm;
}
public void setRealm(String realm) {
this.realm = realm;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class UserDTO {\n");
sb.append(" username: ").append(username).append("\n");
sb.append(" tenantDomain: ").append(tenantDomain).append("\n");
sb.append(" realm: ").append(realm).append("\n");
sb.append("}\n");
return sb.toString();
}
}
|
package com.afagoal.dao.system;
import com.afagoal.dao.BaseDao;
import com.afagoal.entity.system.QSysUserRole;
import com.afagoal.entity.system.SysUserRole;
import org.springframework.stereotype.Repository;
/**
* Created by BaoCai on 17/10/25.
* Description:
*/
@Repository
public class SysUserRoleDao extends BaseDao<SysUserRole,QSysUserRole> {
public SysUserRoleDao(){
this.setQEntity(QSysUserRole.sysUserRole);
}
}
|
package com.designurway.idlidosa.a.activity;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.designurway.idlidosa.R;
import com.designurway.idlidosa.a.model.PaymentSucessfulModel;
import com.designurway.idlidosa.a.retrofit.BaseClient;
import com.designurway.idlidosa.a.retrofit.RetrofitApi;
import com.designurway.idlidosa.ui.home_page.HomePageActivity;
import org.json.JSONException;
import org.json.JSONObject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class PaymentSucessfulActivity extends AppCompatActivity {
TextView transactionID;
Button paymentSucessBtn;
String customer_id, bank_name,bank_transaction_id,currency_type,gateway,mid,order_id,payment_mode,
resp_code,resp_message,status,transaction_amount,transaction_date,transaction_id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_sucessful);
transactionID = findViewById(R.id.transactionID);
paymentSucessBtn = findViewById(R.id.paymentSucessBtn);
Bundle bundle = getIntent().getExtras();
String data = bundle.getString("dataa");
// Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
Log.d("dataa",data);
try {
JSONObject jsonObject = new JSONObject(data);
customer_id = "50 ";
bank_name = jsonObject.getString("BANKNAME");
bank_transaction_id = jsonObject.getString("BANKTXNID");
currency_type = jsonObject.getString("CURRENCY");
gateway = jsonObject.getString("GATEWAYNAME");
mid = jsonObject.getString("MID");
order_id = jsonObject.getString("ORDERID");
payment_mode = jsonObject.getString("PAYMENTMODE");
resp_code = jsonObject.getString("RESPCODE");
resp_message = jsonObject.getString("RESPMSG");
status = jsonObject.getString("STATUS");
transaction_amount = jsonObject.getString("TXNAMOUNT");
transaction_date = jsonObject.getString("TXNDATE");
transaction_id = jsonObject.getString("TXNID");
transactionID.setText(transaction_id);
// Toast.makeText(this, "BANKTXNID : "+bank_transaction_id,
// Toast.LENGTH_SHORT).show();
// transactionID.setText(bank_transaction_id);
Log.d("dataa","Json : "+bank_transaction_id);
} catch (JSONException e) {
e.printStackTrace();
Log.d("dataa","Malformed JSON : "+e.getMessage());
}
postPaymentDetails();
paymentSucessBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(PaymentSucessfulActivity.this, HomePageActivity.class);
startActivity(intent);
finish();
}
});
}
private void postPaymentDetails() {
RetrofitApi api = BaseClient.getClient().create(RetrofitApi.class);
Call<PaymentSucessfulModel> call = api.postPaymentDetails(
customer_id,bank_name,bank_transaction_id,currency_type,gateway,
mid,order_id,payment_mode,resp_code, resp_message,status,transaction_amount,
transaction_date,transaction_id);
call.enqueue(new Callback<PaymentSucessfulModel>() {
@Override
public void onResponse(Call<PaymentSucessfulModel> call, Response<PaymentSucessfulModel> response) {
PaymentSucessfulModel paymentSucessfulResponse = response.body();
if (response.isSuccessful() ){
if ( paymentSucessfulResponse.getStatus().contains("1")){
// Toast.makeText(PaymentSucessfulActivity.this, "Data Inserted Succesfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(PaymentSucessfulActivity.this, "Message : "+paymentSucessfulResponse.getMessage() +" Status : "+paymentSucessfulResponse.getStatus(), Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(PaymentSucessfulActivity.this, "failed", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<PaymentSucessfulModel> call, Throwable t) {
Toast.makeText(PaymentSucessfulActivity.this, "On Failure"+ t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
|
package cz.muni.pv239.marek.exercise5.dagger;
import android.content.Context;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import javax.inject.Singleton;
import cz.muni.pv239.marek.exercise5.api.GitHubService;
import dagger.Module;
import dagger.Provides;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
@Module
public class AppModule {
private final static String GITHUB_API_ENDPOINT = "https://api.github.com";
private final Context context;
public AppModule(Context context) {
this.context = context;
}
@Provides
Context provideContext() {
return context;
}
@Provides
@Singleton
GitHubService provideGitHubService() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(GITHUB_API_ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return retrofit.create(GitHubService.class);
}
}
|
package io.ceph.rgw.client.circuitbreaker;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import io.ceph.rgw.client.action.*;
import io.ceph.rgw.client.config.Configuration;
import io.ceph.rgw.client.config.RGWClientProperties;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.*;
import java.util.concurrent.CompletableFuture;
/**
* An {@link ActionExecutor} that wraps {@link Action} and executes as {@link HystrixCommand}
*
* @author zhuangshuo
* Created by zhuangshuo on 2020/3/10.
* @see io.ceph.rgw.client.config.RGWClientProperties#enableHystrix
* @see RGWClientProperties#getHystrixConfig()
*/
public class HystrixActionExecutor implements ActionExecutor {
private final ActionExecutor delegate;
private final HystrixCommandProperties.Setter setter;
public HystrixActionExecutor(ActionExecutor delegate, Configuration hystrixConfig) {
this.delegate = Objects.requireNonNull(delegate);
this.setter = initializeSetter(hystrixConfig);
}
private interface PropertySetter {
void set(String key);
}
private static HystrixCommandProperties.Setter initializeSetter(Configuration hystrixConfig) {
HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
.withRequestCacheEnabled(false)
.withFallbackEnabled(false);
List<Map.Entry<String, PropertySetter>> list = new LinkedList<>();
list.add(new SimpleImmutableEntry<>("execution.isolation.semaphore.maxConcurrentRequests", k -> Optional.ofNullable(hystrixConfig.getInteger(k)).ifPresent(setter::withExecutionIsolationSemaphoreMaxConcurrentRequests)));
list.add(new SimpleImmutableEntry<>("execution.isolation.thread.interruptOnTimeout", k -> Optional.ofNullable(hystrixConfig.getBoolean(k)).ifPresent(setter::withExecutionIsolationThreadInterruptOnTimeout)));
list.add(new SimpleImmutableEntry<>("execution.timeoutInMilliseconds", k -> Optional.ofNullable(hystrixConfig.getInteger(k)).ifPresent(setter::withExecutionTimeoutInMilliseconds)));
list.add(new SimpleImmutableEntry<>("circuitBreaker.enabled", k -> Optional.ofNullable(hystrixConfig.getBoolean(k)).ifPresent(setter::withCircuitBreakerEnabled)));
list.add(new SimpleImmutableEntry<>("circuitBreaker.requestVolumeThreshold", k -> Optional.ofNullable(hystrixConfig.getInteger(k)).ifPresent(setter::withCircuitBreakerRequestVolumeThreshold)));
list.add(new SimpleImmutableEntry<>("circuitBreaker.sleepWindowInMilliseconds", k -> Optional.ofNullable(hystrixConfig.getInteger(k)).ifPresent(setter::withCircuitBreakerSleepWindowInMilliseconds)));
list.add(new SimpleImmutableEntry<>("circuitBreaker.errorThresholdPercentage", k -> Optional.ofNullable(hystrixConfig.getInteger(k)).ifPresent(setter::withCircuitBreakerErrorThresholdPercentage)));
list.add(new SimpleImmutableEntry<>("circuitBreaker.forceOpen", k -> Optional.ofNullable(hystrixConfig.getBoolean(k)).ifPresent(setter::withCircuitBreakerForceOpen)));
list.add(new SimpleImmutableEntry<>("circuitBreaker.forceClosed", k -> Optional.ofNullable(hystrixConfig.getBoolean(k)).ifPresent(setter::withCircuitBreakerForceClosed)));
list.add(new SimpleImmutableEntry<>("metrics.rollingPercentile.enabled", k -> Optional.ofNullable(hystrixConfig.getBoolean(k)).ifPresent(setter::withMetricsRollingPercentileEnabled)));
list.add(new SimpleImmutableEntry<>("metrics.rollingPercentile.timeInMilliseconds", k -> Optional.ofNullable(hystrixConfig.getInteger(k)).ifPresent(setter::withMetricsRollingPercentileWindowInMilliseconds)));
list.add(new SimpleImmutableEntry<>("metrics.rollingPercentile.numBuckets", k -> Optional.ofNullable(hystrixConfig.getInteger(k)).ifPresent(setter::withMetricsRollingPercentileWindowBuckets)));
list.add(new SimpleImmutableEntry<>("metrics.rollingPercentile.bucketSize", k -> Optional.ofNullable(hystrixConfig.getInteger(k)).ifPresent(setter::withMetricsRollingPercentileBucketSize)));
list.add(new SimpleImmutableEntry<>("metrics.healthSnapshot.intervalInMilliseconds", k -> Optional.ofNullable(hystrixConfig.getInteger(k)).ifPresent(setter::withMetricsHealthSnapshotIntervalInMilliseconds)));
list.add(new SimpleImmutableEntry<>("requestLog.enabled", k -> Optional.ofNullable(hystrixConfig.getBoolean(k)).ifPresent(setter::withRequestLogEnabled)));
list.forEach(e -> e.getValue().set(e.getKey()));
return setter;
}
@Override
public <R> ActionFuture<R> execute(SyncAction<R> action) {
return delegate.execute(wrap(action, setter));
}
@Override
public <R> void execute(SyncAction<R> action, ActionListener<R> listener) {
delegate.execute(wrap(action, setter), listener);
}
@Override
public <R> R run(SyncAction<R> action) {
return delegate.run(wrap(action, setter));
}
@Override
public <R> void execute(AsyncAction<R> action, ActionListener<R> listener) {
delegate.execute(wrap(action, setter), listener);
}
@Override
public <R> SubscribeActionFuture<R> execute(SubscribeAction<R> action, ActionListener<R> listener) {
return delegate.execute(action, listener);
}
private static <R> SyncAction<R> wrap(SyncAction<R> action, HystrixCommandProperties.Setter setter) {
if (action == null || action instanceof HystrixCommandSyncAction || Boolean.FALSE.equals(setter.getCircuitBreakerEnabled())) {
return action;
}
return new HystrixCommandSyncAction<>(action, setter);
}
private static <R> AsyncAction<R> wrap(AsyncAction<R> action, HystrixCommandProperties.Setter setter) {
if (action == null || action instanceof HystrixCommandAsyncAction || Boolean.FALSE.equals(setter.getCircuitBreakerEnabled())) {
return action;
}
return new HystrixCommandAsyncAction<>(action, setter);
}
private static class HystrixCommandSyncAction<R> extends HystrixCommand<R> implements SyncAction<R> {
private final SyncAction<R> action;
private HystrixCommandSyncAction(SyncAction<R> action, HystrixCommandProperties.Setter setter) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("rgw-client"))
.andCommandKey(HystrixCommandKey.Factory.asKey(action.name()))
.andCommandPropertiesDefaults(setter));
this.action = action;
}
@Override
public R run() throws Exception {
return action.call();
}
@Override
public R call() {
return execute();
}
}
private static class HystrixCommandAsyncAction<R> extends HystrixCommand<R> implements AsyncAction<R> {
private final AsyncAction<R> action;
private HystrixCommandAsyncAction(AsyncAction<R> action, HystrixCommandProperties.Setter setter) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("rgw-client"))
.andCommandKey(HystrixCommandKey.Factory.asKey(action.name()))
.andCommandPropertiesDefaults(setter));
this.action = action;
}
@Override
public R run() throws Exception {
return action.call().get();
}
@Override
public CompletableFuture<R> call() {
return CompletableFuture.supplyAsync(this::execute);
}
}
}
|
package draughts.library.boardmodel;
public class Board {
public static final int NUMBER_OF_TILES = 100;
public static final int NUMBER_OF_ROWS = 10;
public static final int TILES_IN_ROW = 10;
}
|
package simplefactory;
/**
* Date: 2019/3/2
* Created by Liuian
*/
interface IPizza {
void rotate();
void bake();
void pack();
}
|
package vn.edu.techkids.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
public static final int DL = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) this.findViewById(R.id.button);
final EditText editText = (EditText) this.findViewById(R.id.editText);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String rs = editText.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("DU_LIEU", rs);
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("goitin", bundle);
MainActivity.this.startActivityForResult(intent, 1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
}
|
package com.estudos.microsservicos.hrworker.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.estudos.microsservicos.hrworker.entity.Worker;
public interface WorkerRepository extends JpaRepository<Worker, Long> {
}
|
package pl.coderslab.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import pl.coderslab.entity.Author;
import java.util.List;
public interface AuthorRepository extends JpaRepository<Author, Long> {
Author findByEmail(String email);
Author findByPesel(String pesel);
List<Author> findAllByLastName(String lastName);
@Query("SELECT a FROM Author a WHERE a.email LIKE ?1%")
List<Author> findByEmailStartsWith(@Param("starts") String starts);
@Query("SELECT a FROM Author a WHERE a.pesel LIKE ?1%")
List<Author> findByPeselStartsWith(@Param("starts") String starts);
}
|
package com.gsn.common.cache;
import com.gsn.utils.LogUtils;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* 多层缓存的实现
* <p />
* 使用者可以通过{@link #addLocal(int)}和{@link #addRedisUsePrimitiveKey(int)}或{@link #addRedis(int, CacheKeyConverter)}
* 来添加任意层的本地缓存和Redis缓存,缓存的结构与方法调用顺序相一致
* <p />
* {@link #build()}和{@link #build(DaoHandler)}能结束添加并使该多级缓存可用
* <p />
* <b>注意:</b>该缓存内部不会存储null值,所以有时会存在大量穿透的情况 <br />
* <b>注意:</b>本地缓存使用消息队列方式进行多端缓存同步,对应key会json化发给服务器及各端,
* 如果使用非基本类型作为key,需要谨慎实现equals()和hashCode()方法,保证相同key值间可以判断是否相等,这样才能保证同步机制有效
*
* @author GSN
*/
public class MultiCache<Key, Value extends Serializable> implements Cache<Key, Value> {
/**
* 本缓存的名字
* <p />
* <b>注意:</b>该名称将作为Redis的key的前缀,同时也会在后台输出显示,所以每个缓存名都不能重复
*/
private String cacheName;
/** 顶层缓存,存放、查询时使用 */
private NestableCache<Key, Value> topLayerCache;
/** 底层缓存,添加缓存时需要修改指向 */
private NestableCache<Key, Value> bottomLayerCache;
/** 该转换器默认直接使用Key的toString()方法进行转换 */
private final CacheKeyConverter<Key> DEFAULT_CONVERTER = new CacheKeyConverter<Key>() {
@Override
public String convertToString(Key key) {
return key.toString();
}
};
public MultiCache(String cacheName) {
this.cacheName = cacheName;
}
/**
* 该类并非定义一个实际的缓存,而是将DaoHandler包装成一个虚拟缓存,
* 保证对数据库层的查询方法能够像使用缓存一样被操作
* <p />
* 如果使用数据库层,应该将该“缓存”插入到最下层
*/
private static class DaoCache<Key, Value extends Serializable>
implements NestableCache<Key, Value> {
/** 被包装起来的数据库层查询接口 */
private DaoHandler<Key, Value> daoHandler;
public DaoCache(DaoHandler<Key, Value> daoHandler) {
this.daoHandler = daoHandler;
}
@Override
public Value get(Key key) {
try {
return this.daoHandler.load(key);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Map<Key, Value> getAll(Collection<? extends Key> keys) {
try {
return this.daoHandler.loadAll(keys);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void build(Cache<Key, Value> nextLayerCache) {}
@Override
public void putToSelf(Key key, Value value) {}
@Override
public void putAllToSelf(Map<? extends Key, ? extends Value> values) {}
@Override
public void putAll(Map<? extends Key, ? extends Value> values) {}
@Override
public void put(Key key, Value value) {}
@Override
public void invalidateAll(Collection<? extends Key> keys) {}
@Override
public void invalidate(Key key) {}
@Override
public String getCacheName() {
return "";
}
@Override
public String getCacheInfo() {
return "";
}
}
/**
* 没有任何作用的黑洞层,如果目标多层缓存不与数据库层有任何交互,
* 可以将之添加到多层缓存的底部模拟
*/
private static class BlackHoleCache<Key, Value extends Serializable>
implements NestableCache<Key, Value> {
@Override
public void putToSelf(Key key, Value value) {}
@Override
public void putAllToSelf(Map<? extends Key, ? extends Value> values) {}
@Override
public void putAll(Map<? extends Key, ? extends Value> values) {}
@Override
public void put(Key key, Value value) {}
@Override
public void invalidateAll(Collection<? extends Key> keys) {}
@Override
public void invalidate(Key key) {}
@Override
public String getCacheName() {
return "";
}
@Override
public String getCacheInfo() {
return "";
}
@Override
public Map<Key, Value> getAll(Collection<? extends Key> keys) {
return new HashMap<>();
}
@Override
public Value get(Key key) {
return null;
}
@Override
public void build(Cache<Key, Value> nextLayerCache) {}
}
/**
* 向多级缓存结构中添加一个本地缓存
* <p />
* <b>注意:</b>使用该方法时要求对应Key必须恰当实现equals()和hashCode()方法,否则可能导致匹配失败
*
* @param expireTimeInSecond 过期时间
* @return 本多级缓存对象
*/
private MultiCache<Key, Value> addLocal(int expireTimeInSecond) {
addToBottom(new LocalCache<Key, Value>(this.cacheName, expireTimeInSecond));
return this;
}
/**
* 向多级缓存结构中添加一个Redis缓存,Redis缓存内部会使用传入的转换器进行Key到String的转换
*
* @param expireTimeInSecond 过期时间
* @param converter Key到String的转换器
* @return 本多级缓存对象
*/
private MultiCache<Key, Value> addRedis(int expireTimeInSecond, CacheKeyConverter<Key> converter) {
addToBottom(new RedisCache<Key, Value>(this.cacheName, expireTimeInSecond, converter));
return this;
}
/**
* 向多级缓存结构中添加一个Redis缓存
* <p />
* <b>注意:</b>被添加的Redis缓存内部会使用Key的toString()方法进行key值的转换,可能造成一些问题和错误,
* 所以该方法仅适用于使用基本类型作为Key的情况。
*
* @param expireTimeInSecond 过期时间
* @return 本多级缓存对象
*/
private MultiCache<Key, Value> addRedisUsePrimitiveKey(int expireTimeInSecond) {
addToBottom(new RedisCache<Key, Value>(this.cacheName, expireTimeInSecond, DEFAULT_CONVERTER));
return this;
}
private void addToBottom(NestableCache<Key, Value> cache) {
if (this.topLayerCache == null) {
this.topLayerCache = cache;
}
if (this.bottomLayerCache != null) {
this.bottomLayerCache.build(cache);
}
this.bottomLayerCache = cache;
}
/**
* 结束对整个多级缓存的构建,该方法会以一个数据库层操作接口作为最底层缓存结构
*
* @param daoHandler 使用者自实现的数据库层操作接口
* @return 完整构建后的多级缓存对象
*/
public MultiCache<Key, Value> build(DaoHandler<Key, Value> daoHandler) {
addToBottom(new DaoCache<>(daoHandler));
return this;
}
/**
* 结束对整个多级缓存的构建,使用该方法构建的多级缓存的最底层为黑洞模式
*
* @return 完整构建后的多级缓存对象
*/
public MultiCache<Key, Value> build() {
addToBottom(new BlackHoleCache<Key, Value>());
return this;
}
@Override
public Value get(Key key) {
try {
return this.topLayerCache.get(key);
} catch (Exception e) {
// 主要避免NullPointerException异常
LogUtils.warn("MultiCache: " + this.cacheName + " get error! " + e.getMessage());
}
return null;
}
@Override
public Map<Key, Value> getAll(Collection<? extends Key> keys) {
try {
return this.topLayerCache.getAll(keys);
} catch (Exception e) {
LogUtils.warn("MultiCache: " + this.cacheName + " get error!", e);
}
return new HashMap<>();
}
@Override
public void put(Key key, Value value) {
this.topLayerCache.put(key, value);
}
@Override
public void putAll(Map<? extends Key, ? extends Value> values) {
this.topLayerCache.putAll(values);
}
@Override
public void putToSelf(Key key, Value value) {
this.topLayerCache.putToSelf(key, value);
}
@Override
public void putAllToSelf(Map<? extends Key, ? extends Value> values) {
this.topLayerCache.putAllToSelf(values);
}
@Override
public void invalidate(Key key) {
this.topLayerCache.invalidate(key);
}
@Override
public void invalidateAll(Collection<? extends Key> keys) {
this.topLayerCache.invalidateAll(keys);
}
@Override
public String getCacheInfo() {
return getCacheName();
}
@Override
public String getCacheName() {
return "MultiCache's name is : " + this.cacheName;
}
}
|
package br.iesb.mobile.alunoonline;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import br.iesb.mobile.alunoonline.Model.Produto;
public class Cadastro extends AppCompatActivity {
private TextView login;
private EditText editNome, editSobrenome, editSenhaCad, editEmailCad, editTelefone;
private Button btnRegistrar;
private Usuario usuario;
private List<Produto> todosProdutos= new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cadastro);
Intent it = getIntent();
todosProdutos = (ArrayList) it.getSerializableExtra("todosProdutos");
editNome = findViewById( R.id.editNome );
editSobrenome = findViewById( R.id.editSobrenome );
editSenhaCad = findViewById( R.id.editSenhaCad );
editEmailCad = findViewById( R.id.editEmailCad );
editTelefone = findViewById( R.id.editTelefone );
btnRegistrar = findViewById( R.id.btnRegistrar );
//Cadastra novo usuario
btnRegistrar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(editNome.getText().toString().isEmpty()){
editNome.setError("Nome é obrigatorio");
editNome.requestFocus();
return;
}
if(editSobrenome.getText().toString().isEmpty()){
editSobrenome.setError("Sobrenome é obrigatório");
editSobrenome.requestFocus();
return;
}
if(editEmailCad.getText().toString().isEmpty()){
editEmailCad.setError("Email é obrigatório");
editEmailCad.requestFocus();
return;
}
if(editSenhaCad.getText().toString().isEmpty()){
editSenhaCad.setError("Senha é obrigatória");
editSenhaCad.requestFocus();
return;
}
cadastrar();
}
});
}
private void cadastrar() {
FirebaseAuth cadastro = FirebaseAuth.getInstance();
final Task<AuthResult> processo = cadastro.createUserWithEmailAndPassword(editEmailCad.getText().toString(), editSenhaCad.getText().toString());
processo.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(processo.isSuccessful()){
usuario = new Usuario();
usuario.setEmail(editEmailCad.getText().toString());
Intent intent = new Intent(Cadastro.this, ListaListas.class);
intent.putExtra("todosProdutos", (Serializable) todosProdutos);
startActivity(intent);
finish();
}else{
Toast.makeText(Cadastro.this, "Cadastro inválido!", Toast.LENGTH_LONG).show();
}
}
});
}
}
|
package internet;
import java.net.*;
public class CheckConnection{
public CheckConnection() {
}
public boolean IsConnected() {
try {
URL url = new URL("http://www.google.com");
URLConnection connection = url.openConnection();
connection.connect();
return true;
} catch (Exception e) {
return false;
}
}
}
|
package com.gxtc.huchuan.ui.mine.personalhomepage;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gxtc.commlibrary.base.BaseActivity;
import com.gxtc.commlibrary.helper.ImageHelper;
import com.gxtc.commlibrary.utils.EventBusUtil;
import com.gxtc.commlibrary.utils.GotoUtil;
import com.gxtc.commlibrary.utils.RomUtils;
import com.gxtc.commlibrary.utils.ToastUtil;
import com.gxtc.huchuan.Constant;
import com.gxtc.huchuan.MyApplication;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.adapter.PersonalHomePageTopAdapter;
import com.gxtc.huchuan.adapter.PersonalPageTabAdapter;
import com.gxtc.huchuan.bean.CircleBean;
import com.gxtc.huchuan.bean.PersonalHomeDataBean;
import com.gxtc.huchuan.bean.dao.User;
import com.gxtc.huchuan.bean.event.EventFocusBean;
import com.gxtc.huchuan.bean.event.EventImgBean;
import com.gxtc.huchuan.bean.event.EventSelectFriendBean;
import com.gxtc.huchuan.bean.event.EventSelectFriendForPostCardBean;
import com.gxtc.huchuan.bean.event.EventShareMessage;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.helper.ShareHelper;
import com.gxtc.huchuan.im.ui.ConversationActivity;
import com.gxtc.huchuan.im.ui.ConversationListActivity;
import com.gxtc.huchuan.ui.circle.findCircle.CircleJoinActivity;
import com.gxtc.huchuan.ui.circle.homePage.CircleMainActivity;
import com.gxtc.huchuan.ui.im.postcard.PTMessage;
import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity;
import com.gxtc.huchuan.ui.mine.personalhomepage.Deal.PersonDealFragment;
import com.gxtc.huchuan.ui.mine.personalhomepage.article.ArticleFragment;
import com.gxtc.huchuan.ui.mine.personalhomepage.classroom.ClassRoomFragment;
import com.gxtc.huchuan.ui.mine.personalhomepage.dynamic.DynamicFragment;
import com.gxtc.huchuan.utils.DialogUtil;
import com.gxtc.huchuan.utils.ImMessageUtils;
import com.gxtc.huchuan.utils.JumpPermissionManagement;
import com.gxtc.huchuan.utils.ReLoginUtil;
import com.gxtc.huchuan.utils.RelayHelper;
import com.gxtc.huchuan.utils.TextLineUtile;
import com.gxtc.huchuan.utils.UMShareUtils;
import com.gxtc.huchuan.widget.CircleImageView;
import com.gxtc.huchuan.widget.OtherGridView;
import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jzvd.JZVideoPlayer;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import static android.os.Build.VERSION_CODES.KITKAT;
import static com.gxtc.huchuan.im.ui.ConversationActivity.REQUEST_SHARE_RELAY;
/**
* Describe:我的 > 个人主页
* Created by ALing on 2017/3/13.
*/
public class PersonalHomePageActivity extends BaseActivity implements
PersonalHomeContract.View {
private static final String TAG = PersonalHomePageActivity.class.getSimpleName();
@BindView(R.id.iv_avatar) CircleImageView mIvAvatar;
@BindView(R.id.rl_show_info) RelativeLayout mRlShowInfo;
@BindView(R.id.cb_focus) ImageView mCbFocus;
@BindView(R.id.tabLayout_main) TabLayout mTabLayoutMain;
@BindView(R.id.vp_personal) ViewPager mVpPersonal;
@BindView(R.id.tv_username) TextView mTvUsername;
@BindView(R.id.tv_introduce) TextView mTvIntroduce;
@BindView(R.id.tv_focus) TextView mTvFocus;
@BindView(R.id.tv_fans) TextView mTvFans;
@BindView(R.id.otherGridView) OtherGridView otherGridView;
@BindView(R.id.tv_all_circle) TextView mTvAllCircle;
@BindView(R.id.ll_focus_chat) LinearLayout llFocusChat;
@BindView(R.id.tv_label_circle) TextView mTvLabelCircle;
@BindView(R.id.iv_mediaLevel) ImageView mIvMediaLevel;
@BindView(R.id.iv_share) ImageView ivShare;
@BindView(R.id.iv_share_white) ImageView ivShareWhite;
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.app_bar) AppBarLayout appBarLayout;
@BindView(R.id.tv_title) TextView tvTitle;
@BindView(R.id.rl_content_top) RelativeLayout rlContentTop;
@BindView(R.id.iv_back) ImageView ivBack;
@BindView(R.id.iv_back_white) ImageView ivBackWhite;
@BindView(R.id.tv_toolbar_focus_top) TextView mTvToolBarFocus;
private UMShareUtils shareUtils;
private List<Fragment> fragments;
private String userCode;
private PersonalHomeContract.Presenter mPresenter;
private String token;
private String isFollow;
private Intent intent;
private PersonalHomePageTopAdapter adapter;
private User mUser;
private float headerBgHeight;
private AlertDialog mAlertDialog;
private DynamicFragment dynamicFragment;
@Override
public boolean isLightStatusBar() {
return false;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBusUtil.register(this);
}
@Override
public void initView() {
setContentView(R.layout.activity_personal_homepage);
ButterKnife.bind(this);
}
@Override
public void initListener() {
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
float percen = Math.abs(verticalOffset / headerBgHeight);
mTvToolBarFocus.setEnabled(true);
mTvToolBarFocus.setAlpha(percen);
tvTitle.setAlpha(percen);
ivBack.setAlpha(percen);
ivShare.setAlpha(percen);
ivBackWhite.setAlpha(1f - percen);
ivShareWhite.setAlpha(1f - percen);
}
});
}
@Override
public void initData() {
switch (RomUtils.getLightStatausBarAvailableRomType()) {
case RomUtils.AvailableRomType.MIUI:
case RomUtils.AvailableRomType.FLYME:
case RomUtils.AvailableRomType.ANDROID_NATIVE://6.0以上
setActionBarTopPadding(toolbar, true);
break;
case RomUtils.AvailableRomType.NA://6.0以下
//这里也要设置一下顶部标题栏的padding,否则会重叠的
if(Build.VERSION.SDK_INT >= KITKAT){
setActionBarTopPadding(toolbar, true);
}
break;
}
headerBgHeight = getResources().getDimension(R.dimen.px500dp) - getResources().getDimension(
R.dimen.head_view_hight);
new PersonalHomePresenter(this);
mTabLayoutMain.setupWithViewPager(mVpPersonal);
token = UserManager.getInstance().getToken();
userCode = getIntent().getStringExtra("userCode");
if (userCode != null) {
mTvToolBarFocus.setVisibility(View.VISIBLE);
llFocusChat.setVisibility(View.VISIBLE);
mTvLabelCircle.setText(getString(R.string.title_his_circle));
mCbFocus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPresenter.setUserFocus(token, "3", userCode);
}
});
mTvToolBarFocus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPresenter.setUserFocus(token, "3", userCode);
}
});
}
if(!TextUtils.isEmpty(userCode) && userCode.equals(UserManager.getInstance().getUserCode())){
mTvToolBarFocus.setVisibility(View.GONE);
llFocusChat.setVisibility(View.GONE);
}
getHomePageData();
initViewPage();
initGrideView();
}
private void initGrideView() {
if (userCode != null) {
mPresenter.getCircleListByUserCode(userCode, false);
} else {
mPresenter.getCircleListByUserCode(UserManager.getInstance().getUserCode(), false);
}
}
private void getHomePageData() {
if (userCode != null) {
mPresenter.getUserMemberByUserCode(userCode, token);
} else {
mPresenter.getUserSelfInfo(token);
}
}
private void initViewPage() {
String[] arrTabTitles = getResources().getStringArray(R.array.personal_homepage_tab);
fragments = new ArrayList<>();
//主页
//PersonalHomeFragment homePageFragment = new PersonalHomeFragment();
//推荐
// RecommendFragment recommendFragment = new RecommendFragment();
dynamicFragment = new DynamicFragment();
ArticleFragment articleFragment = new ArticleFragment();
ClassRoomFragment classRoomFragment = new ClassRoomFragment();
PersonDealFragment mPersonDealFragment = new PersonDealFragment();
Bundle bundle = new Bundle();
bundle.putString(Constant.INTENT_DATA,userCode);
mPersonDealFragment.setArguments(bundle);
fragments.add(dynamicFragment);
fragments.add(articleFragment);
fragments.add(classRoomFragment);
fragments.add(mPersonDealFragment);
mVpPersonal.setAdapter(new PersonalPageTabAdapter(getSupportFragmentManager(), fragments, arrTabTitles,userCode));
}
@OnClick({R.id.iv_back, R.id.iv_share, R.id.tv_chat, R.id.tv_all_circle, R.id.tv_toolbar_focus_top})
public void onClick(View view) {
switch (view.getId()) {
case R.id.iv_back:
finish();
break;
case R.id.iv_share:
share();
break;
case R.id.tv_all_circle:
HisCircleActivity.startActivity(this, userCode);
break;
//聊天
case R.id.tv_chat:
finish();
break;
}
}
//分享
private void share() {
String[] pers = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
performRequestPermissions(getString(R.string.txt_card_permission), pers, 2200,
new PermissionsResultListener() {
@Override
public void onPermissionGranted() {
if(mUser == null) return;
shareUtils = new UMShareUtils(PersonalHomePageActivity.this);
String uri = TextUtils.isEmpty(mUser.getHeadPic()) ? Constant.DEFUAL_SHARE_IMAGE_URI : mUser.getHeadPic();
shareUtils.sharePersonalHome(uri, TextUtils.isEmpty(mUser.getSelfMediaName()) ? mUser.getName() : mUser.getSelfMediaName(), mUser.getIntroduction(), mUser.getShareUrl());
shareUtils.setOnItemClickListener(new UMShareUtils.OnItemClickListener() {
@Override
public void onItemClick(int flag) {
//发送名片
if(flag == 0){
ConversationListActivity.startActivity(PersonalHomePageActivity.this, ConversationActivity.REQUEST_SHARE_CARD,Constant.SELECT_TYPE_CARD);
}
}
});
}
@Override
public void onPermissionDenied() {
mAlertDialog = DialogUtil.showDeportDialog(PersonalHomePageActivity.this, false, null, getString(R.string.pre_storage_notice_msg),
new View.OnClickListener() {
@Override
public void onClick(View v) {
if(v.getId() == R.id.tv_dialog_confirm){
JumpPermissionManagement.GoToSetting(PersonalHomePageActivity.this);
}
mAlertDialog.dismiss();
}
});
}
});
}
@Override
public void tokenOverdue() {
mAlertDialog = DialogUtil.showDeportDialog(PersonalHomePageActivity.this, false, null, getString(R.string.token_overdue),
new View.OnClickListener() {
@Override
public void onClick(View v) {
if(v.getId() == R.id.tv_dialog_confirm){
ReLoginUtil.ReloginTodo(PersonalHomePageActivity.this);
}
mAlertDialog.dismiss();
}
});
}
@Override
public void showHomePageSelfList(List<PersonalHomeDataBean> list) {
}
@Override
public void showHomePageUserList(List<PersonalHomeDataBean> list) {
}
@Override
public void showCircleByUserList(List<CircleBean> list) {
adapter = new PersonalHomePageTopAdapter(PersonalHomePageActivity.this, list,
R.layout.item_personalpage_top);
otherGridView.setAdapter(adapter);
otherGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CircleBean bean = (CircleBean) adapter.getItem(position);
GotoUtil.goToActivity(PersonalHomePageActivity.this, CircleMainActivity.class, 0, bean);
}
});
}
@Override
public void showCircleByUserCodeList(List<CircleBean> list) {
adapter = new PersonalHomePageTopAdapter(PersonalHomePageActivity.this, list,
R.layout.item_personalpage_top);
otherGridView.setAdapter(adapter);
otherGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CircleBean bean = adapter.getDatas().get(position);
String name = bean.getGroupName();
String joinUrl = bean.getJoinUrl();
double money = bean.getFee();
int circleId = bean.getId();
int isJoin = bean.getIsJoin(); //是否已经加入 0:未加入。1:已加入
if (0 == isJoin) {
Intent intent = new Intent(PersonalHomePageActivity.this, CircleJoinActivity.class);
intent.putExtra("url", joinUrl);
intent.putExtra("id", circleId);
intent.putExtra("name", name);
intent.putExtra("isAudit", bean.getIsAudit());
intent.putExtra(Constant.INTENT_DATA, money);
startActivityForResult(intent, 0);
} else {
GotoUtil.goToActivity(PersonalHomePageActivity.this, CircleMainActivity.class, 0, bean);
}
}
});
}
@Override
public void showRefreshFinish(List<CircleBean> datas) {
}
@Override
public void showLoadMoreList(List<CircleBean> list) {
}
@Override
public void showSelfData(User user) {
mUser = user;
ImageHelper.loadHeadIcon(this, mIvAvatar, R.drawable.person_icon_head_120,
user.getHeadPic());
ImageHelper.loadImage(this, mIvMediaLevel, user.getSelfMediaLevelPicUrl(),
R.drawable.person_grade_icon_lv1);
if (!TextUtils.isEmpty(user.getSelfMediaName())) {
mTvUsername.setText(user.getSelfMediaName());
} else {
mTvUsername.setText(user.getName());
}
if (user.getIntroduction().toString().trim().length() != 0) {
mTvIntroduce.setText("简介:" + user.getIntroduction());
} else {
mTvIntroduce.setText(getString(R.string.label_introduct));
}
mTvFocus.setText("关注" + user.getFollowCount());
mTvFans.setText("粉丝" + user.getFsCount());
}
@Override
public void showMenberData(User user) {
mUser = user;
isFollow = user.getIsFollow();
if (userCode != null) {
Log.d(TAG, "initData: " + userCode);
mCbFocus.setImageResource("0".equals(
user.getIsFollow()) ? R.drawable.live_attention_normal_white : R.drawable.live_topic_attention_selected_white);
mTvToolBarFocus.setText("0".equals(user.getIsFollow()) ? "关注" : "已关注");
}
ImageHelper.loadHeadIcon(this, mIvAvatar, R.drawable.person_icon_head_120,
user.getHeadPic());
ImageHelper.loadImage(this, mIvMediaLevel, user.getSelfMediaLevelPicUrl(),
R.drawable.person_grade_icon_lv1);
if (!TextUtils.isEmpty(user.getSelfMediaName())) {
mTvUsername.setText(user.getSelfMediaName());
} else {
mTvUsername.setText(user.getName());
}
if (user.getIntroduction().toString().trim().length() != 0) {
mTvIntroduce.setText("简介:" + user.getIntroduction());
} else {
mTvIntroduce.setText(getString(R.string.label_introduct));
}
mTvFocus.setText("关注:" + user.getFollowCount());
mTvFans.setText("粉丝:" + user.getFsCount());
}
@Override
public void showUserFocus(Object object) {
if ("0".equals(isFollow)) {
isFollow = "1";
intent = new Intent();
setResult(Constant.ResponseCode.FOCUS_RESULT_CODE, intent);
mCbFocus.setImageResource(R.drawable.live_topic_attention_selected_white);
mTvToolBarFocus.setText("已关注");
new EventBusUtil().post(new EventFocusBean(true));
} else {
isFollow = "0";
intent = new Intent();
setResult(Constant.ResponseCode.FOCUS_RESULT_CODE, intent);
mCbFocus.setImageResource(R.drawable.live_attention_normal_white);
mTvToolBarFocus.setText("关注");
new EventBusUtil().post(new EventFocusBean(true));
}
}
@Override
public void showRecommendList(List<PersonalHomeDataBean> list) {
}
@Override
public void showNoMore() {
}
@Override
public void setPresenter(PersonalHomeContract.Presenter presenter) {
this.mPresenter = presenter;
}
@Override
public void showLoad() {
}
@Override
public void showLoadFinish() {
}
@Override
public void showEmpty() {
mTvAllCircle.setVisibility(View.GONE);
mTvLabelCircle.setText("还没加入任何圈子");
}
@Override
public void showReLoad() {
getHomePageData();
}
@Override
public void showError(String info) {
ToastUtil.showShort(this, info);
}
@Override
public void showNetError() {
}
//修改圈子封面图
@Subscribe(sticky = true)
public void onEvent(EventImgBean bean) {
initGrideView();
}
//分享名片
private void sharePostCard(EventSelectFriendForPostCardBean bean){
if(mUser == null) return;
PTMessage mPTMessage = PTMessage.obtain(mUser.getUserCode(), mUser.getName(), mUser.getHeadPic());
String title = mPTMessage.getName();
String img = mPTMessage.getHeadPic();
String id = mPTMessage.getUserCode();
ImMessageUtils.sentPost(bean.targetId,bean.mType, id, title, img, new IRongCallback.ISendMessageCallback() {
@Override
public void onAttached(Message message) {}
@Override
public void onSuccess(Message message) {
ToastUtil.showShort(MyApplication.getInstance(),"发送名片成功");
}
@Override
public void onError(Message message, RongIMClient.ErrorCode errorCode) {
ToastUtil.showShort(MyApplication.getInstance(),"发送名片失败: " + message);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == ConversationActivity.REQUEST_SHARE_CARD && resultCode == RESULT_OK){
EventSelectFriendForPostCardBean bean = data.getParcelableExtra(Constant.INTENT_DATA);
sharePostCard(bean);
}
//分享视频
if(requestCode == ConversationActivity.REQUEST_SHARE_VIDEO && resultCode == RESULT_OK){
EventSelectFriendBean bean = data.getParcelableExtra(Constant.INTENT_DATA);
ShareHelper.INSTANCE.getBuilder().targetId(bean.targetId).type(bean.mType).liuyan(bean.liuyan).action(ConversationActivity.REQUEST_SHARE_VIDEO).toShare();
}
//转发消息
if(requestCode == REQUEST_SHARE_RELAY && resultCode == RESULT_OK){
dynamicFragment.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onBackPressed() {
if (!JZVideoPlayer.backPress()) {
super.onBackPressed();
}
}
@Override
public void onDestroy() {
super.onDestroy();
mPresenter.destroy();
mAlertDialog = null;
TextLineUtile.clearTextLineCache();
EventBusUtil.unregister(this);
}
public static void startActivity(Context context, String userCode) {
Intent intent = new Intent(context, PersonalHomePageActivity.class);
intent.putExtra("userCode", userCode);
context.startActivity(intent);
}
}
|
package org.example.business.menu;
import org.example.data.model.menu.Menu;
import org.example.data.service.menu.MenuDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MenuServiceImpl implements MenuService {
@Autowired
private MenuDataService menuDataService;
@Override
public Menu save(Menu menu) {
return menuDataService.save(menu);
}
@Override
public Menu findById(Long id) {
return menuDataService.findById(id).orElseGet(Menu::new);
}
@Override
public Page<Menu> findAll(Menu menu, Pageable pageable) {
return menuDataService.findAll(Example.of(menu),pageable);
}
@Override
public List<Menu> findAll() {
return menuDataService.findAll();
}
}
|
package com.example.simplebroadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class BatteryReceiver extends BroadcastReceiver {
private static final String TAG = "BatteryReceiverTAG_";
public BatteryReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive Battery: ");
String action = intent.getAction();
Toast.makeText(context, "Battery Change " + action, Toast.LENGTH_SHORT).show();
}
}
|
package me.jagar.dialogcameraviewlibrary.classes;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.camerakit.CameraKit;
import com.camerakit.CameraKitView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import me.jagar.dialogcameraviewlibrary.R;
import me.jagar.dialogcameraviewlibrary.interfaces.OnCaptureCancelled;
import me.jagar.dialogcameraviewlibrary.interfaces.OnCaptureDone;
import me.jagar.dialogcameraviewlibrary.interfaces.OnRecapturing;
public class CameraViewDialog {
Context context;
String imageTempPath;
AlertDialog.Builder alertDialog;
AlertDialog screen;
//Listners
OnCaptureDone onCaptureDone = null;
OnCaptureCancelled onCaptureCancelled = null;
OnRecapturing onRecapturing = null;
int times = 0;
public void init(Context context, String imageTempPath){
this.context = context;
this.imageTempPath = imageTempPath;
}
public void startDialog(){
//Inflating the AlertDialog
alertDialog = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View dialogView = inflater.inflate(R.layout.camera_view_dialog, null);
alertDialog.setView(dialogView);
//CameraView UI
screen = alertDialog.create();
final CameraKitView cameraKitView = dialogView.findViewById(R.id.cameraKitView);
final FloatingActionButton fabCapture = dialogView.findViewById(R.id.fabCapture);
final FloatingActionButton fabDone = dialogView.findViewById(R.id.fabDone);
final FloatingActionButton fabRepeat = dialogView.findViewById(R.id.fabRepeat);
final FloatingActionButton fabSwitch = dialogView.findViewById(R.id.fabSwitch);
final ImageView imageView = dialogView.findViewById(R.id.imgView);
//Handler
final File[] image = {null};
//We start the camera
cameraKitView.onStart();
//Capturing action
fabCapture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cameraKitView.captureImage(new CameraKitView.ImageCallback() {
@SuppressLint("RestrictedApi")
@Override
public void onImage(final CameraKitView cameraKitView, byte[] bytes) {
image[0] = new File(imageTempPath);
if (image[0].exists())
image[0].delete();
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(image[0].getPath(), false);
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(image[0].getAbsolutePath()));
cameraKitView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
fabCapture.setVisibility(View.GONE);
fabSwitch.setVisibility(View.GONE);
fabDone.setVisibility(View.VISIBLE);
fabRepeat.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
//Recapturing
fabRepeat.setOnClickListener(new View.OnClickListener() {
@SuppressLint("RestrictedApi")
@Override
public void onClick(View view) {
imageView.setVisibility(View.GONE);
cameraKitView.setVisibility(View.VISIBLE);
fabRepeat.setVisibility(View.GONE);
fabDone.setVisibility(View.GONE);
fabCapture.setVisibility(View.VISIBLE);
fabSwitch.setVisibility(View.VISIBLE);
if (onRecapturing != null){
times++;
onRecapturing.onRecapturing(times);
}
}
});
//Done, let's display it in the imageView
fabDone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (image[0] != null)
//TODO
screen.dismiss();
if (onCaptureDone != null){
onCaptureDone.onDone(imageTempPath);
}
}
});
//To let us start new capturing
screen.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
cameraKitView.stopVideo();
cameraKitView.onStop();
if (onCaptureCancelled != null && !(new File(imageTempPath).exists())){
onCaptureCancelled.OnCancelled();
}
}
});
fabSwitch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (cameraKitView.getFacing() == CameraKit.FACING_BACK){
cameraKitView.setFacing(CameraKit.FACING_FRONT);
}
else{
cameraKitView.setFacing(CameraKit.FACING_BACK);
}
}
});
//Display the dialog
screen.show();
}
public void setOnCaptureDoneListener(OnCaptureDone onCaptureDone){
this.onCaptureDone = onCaptureDone;
}
public void setOnCaptureCancelledListener(OnCaptureCancelled onCaptureCancelled){
this.onCaptureCancelled = onCaptureCancelled;
}
public void setOnRecapturingListener(OnRecapturing onRecapturing){
this.onRecapturing = onRecapturing;
}
}
|
package be.darkshark.parkshark.api.dto.parkinglot;
import be.darkshark.parkshark.api.dto.util.AddressDTO;
public class DetailedParkingLotDto {
private long id;
private String name;
private String parkingCategory;
private int capacity;
private long contactPersonId;
private AddressDTO address;
private double pricePerHour;
private long divisionId;
public DetailedParkingLotDto(long id, String name, String parkingCategory, int capacity, long contactPersonId, AddressDTO address, double pricePerHour, long divisionId) {
this.id = id;
this.name = name;
this.parkingCategory = parkingCategory;
this.capacity = capacity;
this.contactPersonId = contactPersonId;
this.address = address;
this.pricePerHour = pricePerHour;
this.divisionId = divisionId;
}
public DetailedParkingLotDto() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParkingCategory() {
return parkingCategory;
}
public void setParkingCategory(String parkingCategory) {
this.parkingCategory = parkingCategory;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public long getContactPersonId() {
return contactPersonId;
}
public void setContactPersonId(long contactPersonId) {
this.contactPersonId = contactPersonId;
}
public AddressDTO getAddress() {
return address;
}
public void setAddress(AddressDTO address) {
this.address = address;
}
public double getPricePerHour() {
return pricePerHour;
}
public void setPricePerHour(double pricePerHour) {
this.pricePerHour = pricePerHour;
}
public long getDivisionId() {
return divisionId;
}
public void setDivisionId(long divisionId) {
this.divisionId = divisionId;
}
}
|
package by.orion.onlinertasks.common.exceptions.errors;
import by.orion.onlinertasks.R;
import by.orion.onlinertasks.common.exceptions.BaseError;
public class NetworkError extends BaseError {
public NetworkError() {
super(R.string.msg_common_error_network);
}
}
|
package com.classroom.services.facade.dto.entities;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import com.classroom.services.web.dto.mappers.LocalDateTimeAdapter;
import org.joda.time.LocalDateTime;
@XmlRootElement(name="searchBatchCirculars")
public class CircularBatchSearchDTO{
private Integer eventID;
private Integer batchID;
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getEventID() {
return eventID;
}
public void setEventID(Integer eventID) {
this.eventID = eventID;
}
public Integer getBatchID() {
return batchID;
}
public void setBatchID(Integer batchID) {
this.batchID = batchID;
}
}
|
package com.next.infra.odata2.function;
import java.io.InputStream;
import org.apache.olingo.odata2.jpa.processor.api.model.JPAEdmExtension;
import org.apache.olingo.odata2.jpa.processor.api.model.JPAEdmSchemaView;
public class SalesOrderProcessingExtension implements JPAEdmExtension {
@Override
public void extendJPAEdmSchema(final JPAEdmSchemaView arg0 ){
// TODO Auto-generated method stub
}
@Override
public void extendWithOperation(final JPAEdmSchemaView view) {
view.registerOperations(SalesOrderHeaderProcessor.class, null);
}
@Override
public InputStream getJPAEdmMappingModelStream() {
// TODO Auto-generated method stub
return null;
}
}
|
//package com.springboot.demo.repository;
//
//import org.springframework.data.jpa.repository.JpaRepository;
//
//import com.springboot.demo.model.Login;
//
//public interface RegistrationRepository extends JpaRepository<Login, Integer> {
// public Login findByEmailId(String emailId);
// public Login findByEmailIdAndPassword(String emailId, String password);
//
//}
|
package com.aalto.happypolar;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class PairDeviceActivity extends ActionBarActivity {
private String TAG = "myapp";
private BluetoothAdapter mBtAdapter;
private LeDeviceListAdapter mLeDeviceListAdapter;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pair_device);
BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBtAdapter = btManager.getAdapter();
mHandler = new Handler();
mLeDeviceListAdapter = new LeDeviceListAdapter(this);
ListView lvScanResults = (ListView) findViewById(R.id.lvScanResults);
lvScanResults.setAdapter(mLeDeviceListAdapter);
lvScanResults.setOnItemClickListener(mListViewClickListener);
}
@Override
protected void onResume() {
super.onResume();
refreshScanDevices();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_pair_device, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_refresh:
refreshScanDevices();
break;
}
return true;
}
private void refreshScanDevices () {
//if BT is not turned on, ask for it.
if (mBtAdapter == null || !mBtAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBtIntent);
return;
}
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mBtAdapter.stopLeScan(mLeScanCallback);
}
}, 10000);
Toast.makeText(PairDeviceActivity.this, "Scanning...", Toast.LENGTH_SHORT).show();
mBtAdapter.startLeScan(mLeScanCallback);
}
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
}
};
private ListView.OnItemClickListener mListViewClickListener = new ListView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final BluetoothDevice btDevice = mLeDeviceListAdapter.getDevice(position);
mBtAdapter.stopLeScan(mLeScanCallback); //stop scanning as well
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(PairDeviceActivity.this);
dialogBuilder.setTitle("Connect to this device?");
dialogBuilder.setMessage(btDevice.getName() + "\n" + "Address - " + btDevice.getAddress());
dialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(PairDeviceActivity.this, "Connecting...", Toast.LENGTH_LONG).show();
HeartRateDevice.initializeInstance(getApplicationContext(), btDevice, connectionListener);
}
});
dialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Do nothing if clicked no
}
});
dialogBuilder.create().show();
}
};
private HeartRateDevice.DeviceConnectionListener connectionListener = new HeartRateDevice.DeviceConnectionListener() {
@Override
public void deviceConnected(BluetoothDevice device) {
//Toast.makeText(PairDeviceActivity.this, "Connected to: " + device.getName(), Toast.LENGTH_LONG).show();
PairDeviceActivity.this.finish();
}
};
}
|
package perdonin.renaissance.core;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.utils.I18NBundle;
public class I18n {
private I18NBundle bundle;
public I18n(AssetManager am){
bundle = am.get("i18n/strings", I18NBundle.class);
}
public String get(String key){
return bundle.get(key);
}
public String format(String key, Object... args){
return bundle.format(key, args);
}
public String random(String key){
String[] values = bundle.format(key).split("#");
return values[(int)(System.currentTimeMillis() % values.length)];
}
}
|
package slimeknights.tconstruct.plugin.jei.casting;
import com.google.common.collect.ImmutableList;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
import java.util.List;
import javax.annotation.Nonnull;
import mezz.jei.api.IGuiHelper;
import mezz.jei.api.gui.IDrawable;
import mezz.jei.api.gui.IDrawableAnimated;
import mezz.jei.api.gui.IDrawableStatic;
import mezz.jei.api.gui.IGuiFluidStackGroup;
import mezz.jei.api.gui.IGuiItemStackGroup;
import mezz.jei.api.gui.IRecipeLayout;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.recipe.IRecipeCategory;
import slimeknights.tconstruct.TConstruct;
import slimeknights.tconstruct.library.Util;
import slimeknights.tconstruct.library.materials.Material;
public class CastingRecipeCategory implements IRecipeCategory<CastingRecipeWrapper> {
public static String CATEGORY = Util.prefix("casting_table");
public static ResourceLocation background_loc = Util.getResource("textures/gui/jei/casting.png");
protected final IDrawable background;
protected final IDrawableAnimated arrow;
public final IDrawable castingTable;
public final IDrawable castingBasin;
public CastingRecipeCategory(IGuiHelper guiHelper) {
this.background = guiHelper.createDrawable(background_loc, 0, 0, 141, 61);
IDrawableStatic arrowDrawable = guiHelper.createDrawable(background_loc, 141, 32, 24, 17);
this.arrow = guiHelper.createAnimatedDrawable(arrowDrawable, 200, IDrawableAnimated.StartDirection.LEFT, false);
this.castingTable = guiHelper.createDrawable(background_loc, 141, 0, 16, 16);
this.castingBasin = guiHelper.createDrawable(background_loc, 141, 16, 16, 16);
}
@Nonnull
@Override
public String getUid() {
return CATEGORY;
}
@Nonnull
@Override
public String getTitle() {
return Util.translate("gui.jei.casting.title");
}
@Nonnull
@Override
public IDrawable getBackground() {
return this.background;
}
@Override
public void drawExtras(@Nonnull Minecraft minecraft) {
arrow.draw(minecraft, 79, 25);
}
@Override
public void setRecipe(IRecipeLayout recipeLayout, CastingRecipeWrapper recipe, IIngredients ingredients) {
IGuiItemStackGroup items = recipeLayout.getItemStacks();
IGuiFluidStackGroup fluids = recipeLayout.getFluidStacks();
List<FluidStack> input = ingredients.getInputs(FluidStack.class).get(0);
List<List<ItemStack>> castsList = ingredients.getInputs(ItemStack.class);
// if there is no cast then the size of the inputs is 0, producing an index error
List<ItemStack> casts = null;
if(castsList.size() > 0) {
casts = castsList.get(0);
}
int cap = input.get(0).amount;
items.init(0, true, 58, 25);
items.init(1, false, 113, 24);
items.set(ingredients);
fluids.init(0, true, 22, 10, 18, 32, Material.VALUE_Block, false, null);
fluids.set(ingredients);
// no cast, bigger fluid
int h = 11;
if(casts == null || casts.isEmpty()) {
h += 16;
}
fluids.init(1, true, 64, 15, 6, h, cap, false, null);
// otherwise it tries to get the second input fluidstack
fluids.set(1, input);
}
@Override
public List<String> getTooltipStrings(int mouseX, int mouseY) {
return ImmutableList.of();
}
@Override
public IDrawable getIcon() {
// use the default icon
return null;
}
@Override
public String getModName() {
return TConstruct.modName;
}
}
|
import java.util.Arrays;
/**
* 被围绕的区域
*/
public class 被围绕的区域 {
public static void main(String[] args) {
被围绕的区域 t=new 被围绕的区域();
// t.solve(new char[][]{{'X','X','X','X'},{'X','O','O','X'},{'X','X','O','X'},{'X','O','X','X'}});
t.solve(new char[][]{{'O','X','X','O','X'},{'X','O','O','X','O'},{'X','O','X','O','X'},{'O','X','O','O','O'},{'X','X','O','X','O'}});
}
public void solve(char[][] board) {
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(i==0||i==board.length-1||j==0||j==board[0].length-1){
if(board[i][j]=='O'){
dfs(board,i,j);
}
}
}
}
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(board[i][j]=='O') board[i][j]='X';
if(board[i][j]=='#') board[i][j]='O';
}
}
}
private void dfs(char[][] board, int i, int j) {
if(i<0||i>=board.length||j<0||j>=board[0].length||board[i][j]=='X'||board[i][j]=='#') return;
if(board[i][j]=='O') board[i][j]='#';
dfs(board,i,j-1);
dfs(board,i,j+1);
dfs(board,i-1,j);
dfs(board,i+1,j);
}
}
|
package com.beike.service.impl.unionpage;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.beike.dao.unionpage.UnionKWDao;
import com.beike.service.unionpage.UnionPageService;
/*
* com.beike.service.impl.unionpage.UnionPageServiceImpl.java
* @description:网站静态聚合页service实现
* @Author:xuxiaoxian
* Copyright ? 2012 All rights reserved.
* @Compony:Sinobo
*
* @date: 2012-5-17,xuxiaoxian ,create class
*
*/
@Service("unionPageService")
public class UnionPageServiceImpl implements UnionPageService{
@Autowired
private UnionKWDao unionKWDao;
/**
* @date 2012-5-17
* @description:通过关键词Id查询关键词
* @param id
* @return String
* @throws
*/
public String getKeyWordById(int id){
return unionKWDao.getKeyWordById(id);
}
/**
* @date 2012-5-18
* @description:查询所有的关键词信息,
* @return List<Map<String,Object>>
* @throws
*/
public List<Map<String,Object>> getAllKeyWordMsg(){
return unionKWDao.getAllKeyWordMsg();
}
public List<Map<String,String>> getListMsgByKeyWords(String[] keyWord,int count){
List<Map<String,String>> listMsg = new ArrayList<Map<String,String>>();
if(keyWord!=null && keyWord.length > 0){
StringBuilder sb = new StringBuilder("");
for(String KW:keyWord){
if(StringUtils.isNotEmpty(KW)){
sb.append("'").append(KW).append("',");
}
}
if(sb.length()>0){
listMsg = unionKWDao.getMsgByKeyWord(sb.substring(0, sb.length()-1),count);
}
}
return listMsg;
}
public UnionKWDao getUnionKWDao() {
return unionKWDao;
}
public void setUnionKWDao(UnionKWDao unionKWDao) {
this.unionKWDao = unionKWDao;
}
}
|
package com.neo.www.protocolPB;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import com.google.protobuf.RpcController;
import com.google.protobuf.ServiceException;
import com.neo.www.ipc.protobuf.ClientProtocol.EchoRequestProto;
import com.neo.www.ipc.protobuf.ClientProtocol.EchoResponseProto;
public class ClientProtocolServerSideTranslatorBP implements ClientProtocolBP {
public EchoResponseProto echo(RpcController controller, EchoRequestProto request) throws ServiceException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
for (int i = 0; i < 1; i++) {
try {
b.write(request.getMsg().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
return EchoResponseProto.newBuilder().setMsg(b.toString()).build();
}
}
|
package controller;
import java.util.ArrayList;
import java.util.Calendar;
import model.ReplyOrientalDTO;
public class ReplyOrientalController {
private ArrayList<ReplyOrientalDTO> list;
private int id;
public ReplyOrientalController() {
id = 1;
list = new ArrayList<>();
ReplyOrientalDTO r1 = new ReplyOrientalDTO();
r1.setId(id++);
r1.setFoodId(1);
r1.setWriterId(1);
r1.setContent("개무쓸모");
r1.setWrittenDate(Calendar.getInstance());
list.add(r1);
r1 = new ReplyOrientalDTO();
r1.setId(id++);
r1.setFoodId(2);
r1.setWriterId(2);
r1.setContent("아 배고파");
r1.setWrittenDate(Calendar.getInstance());
list.add(r1);
}
public ReplyOrientalDTO selectOne(int id) {
for (ReplyOrientalDTO r : list) {
if (r.getId() == id) {
return r;
}
}
return null;
}
// 푸드 id 받아서 해당 id 값과 일치하도록 하는 메소드
public ArrayList<ReplyOrientalDTO> selectById(int foodId) {
ArrayList<ReplyOrientalDTO> temp = new ArrayList<>();
for (ReplyOrientalDTO r : list) {
if (r.getFoodId() == foodId) {
temp.add(r);
}
}
return temp;
}
public void add(ReplyOrientalDTO r) {
r.setId(id++);
r.setWrittenDate(Calendar.getInstance());
list.add(r);
}
public void delete(ReplyOrientalDTO r) {
list.remove(r);
}
// validateUserId
public boolean validateWriterId(int writerId) {
for(ReplyOrientalDTO r : list) {
if(writerId == r.getWriterId()) {
return true;
}
}
return false;
}
}
|
package com.javasampleapproach.mysql.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "time" )
public class Time implements Serializable {
private static final long serialVersionUID = -3009157732242241606L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "time_info")
private String time_info;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTime_info() {
return time_info;
}
public void setTime_info(String time_info) {
this.time_info = time_info;
}
@Override
public String toString() {
return "Time [id=" + id + ", time_info=" + time_info + "]";
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.engine;
import java.util.HashMap;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pl.edu.icm.unity.db.generic.msgtemplate.MessageTemplateDB;
import pl.edu.icm.unity.engine.authz.AuthorizationManager;
import pl.edu.icm.unity.engine.authz.AuthzCapability;
import pl.edu.icm.unity.engine.events.InvocationEventProducer;
import pl.edu.icm.unity.engine.transactions.SqlSessionTL;
import pl.edu.icm.unity.engine.transactions.Transactional;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.exceptions.WrongArgumentException;
import pl.edu.icm.unity.msgtemplates.MessageTemplate;
import pl.edu.icm.unity.msgtemplates.MessageTemplateDefinition;
import pl.edu.icm.unity.msgtemplates.MessageTemplateValidator;
import pl.edu.icm.unity.msgtemplates.MessageTemplateValidator.IllegalVariablesException;
import pl.edu.icm.unity.msgtemplates.MessageTemplateValidator.MandatoryVariablesException;
import pl.edu.icm.unity.server.api.MessageTemplateManagement;
import pl.edu.icm.unity.server.registries.MessageTemplateConsumersRegistry;
/**
* Implementation of {@link MessageTemplateManagement}
*
* @author P. Piernik
*/
@Component
@InvocationEventProducer
public class MessageTemplateManagementImpl implements MessageTemplateManagement
{
private AuthorizationManager authz;
private MessageTemplateDB mtDB;
private MessageTemplateConsumersRegistry registry;
@Autowired
public MessageTemplateManagementImpl(AuthorizationManager authz,
MessageTemplateDB mtDB, MessageTemplateConsumersRegistry registry)
{
this.authz = authz;
this.mtDB = mtDB;
this.registry = registry;
}
@Transactional
@Override
public void addTemplate(MessageTemplate toAdd) throws EngineException
{
authz.checkAuthorization(AuthzCapability.maintenance);
validateMessageTemplate(toAdd);
SqlSession sql = SqlSessionTL.get();
mtDB.insert(toAdd.getName(), toAdd, sql);
}
@Transactional
@Override
public void removeTemplate(String name) throws EngineException
{
authz.checkAuthorization(AuthzCapability.maintenance);
SqlSession sql = SqlSessionTL.get();
mtDB.remove(name, sql);
}
@Transactional
@Override
public void updateTemplate(MessageTemplate updated) throws EngineException
{
authz.checkAuthorization(AuthzCapability.maintenance);
validateMessageTemplate(updated);
SqlSession sql = SqlSessionTL.get();
mtDB.update(updated.getName(), updated, sql);
}
@Transactional(noTransaction=true)
@Override
public Map<String, MessageTemplate> listTemplates() throws EngineException
{
authz.checkAuthorization(AuthzCapability.maintenance);
SqlSession sql = SqlSessionTL.get();
return mtDB.getAllAsMap(sql);
}
@Transactional(noTransaction=true)
@Override
public MessageTemplate getTemplate(String name) throws EngineException
{
authz.checkAuthorization(AuthzCapability.maintenance);
SqlSession sql = SqlSessionTL.get();
return mtDB.get(name, sql);
}
@Transactional(noTransaction=true)
@Override
public Map<String, MessageTemplate> getCompatibleTemplates(String templateConsumer) throws EngineException
{
authz.checkAuthorization(AuthzCapability.maintenance);
SqlSession sql = SqlSessionTL.get();
Map<String, MessageTemplate> all = mtDB.getAllAsMap(sql);
Map<String, MessageTemplate> ret = new HashMap<String, MessageTemplate>(all);
for (MessageTemplate m : all.values())
{
if (!m.getConsumer().equals(templateConsumer))
{
ret.remove(m.getName());
}
}
return ret;
}
private void validateMessageTemplate(MessageTemplate toValidate)
throws EngineException
{
MessageTemplateDefinition con = registry.getByName(toValidate.getConsumer());
try
{
MessageTemplateValidator.validateMessage(con, toValidate.getMessage());
} catch (IllegalVariablesException e)
{
throw new WrongArgumentException("The following variables are unknown: " + e.getUnknown());
} catch (MandatoryVariablesException e)
{
throw new WrongArgumentException("The following variables must be used: " + e.getMandatory());
}
}
}
|
/*package MVC.controllers;
import java.awt.BorderLayout;
import java.io.PrintStream;
import java.sql.ResultSet;
import java.util.ArrayList;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import MVC.models.addPartModel;
import MVC.models.inventoryModel;
import MVC.views.addPartsView;
import MVC.views.inventoryListView;
import MVC.views.partDetailView;
public class showInventoryController2 implements ListSelectionListener {
private inventoryListView view;
private inventoryModel model;
private ArrayList<String> partList = new ArrayList<String>();
private String[] parts;
private JList list;
private MVC.views.invDetailView invDetailView;
public showInventoryController2(inventoryListView view, inventoryModel model){
this.view = view;
this.model = model;
}
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
partList.clear();
String command = view.getSelectedValue();//gets and assigns the selected value from JList to command
partList = model.getLocationIdPartByName(command);
partList = model.getPartsL();
parts = new String[partList.size()];
parts = partList.toArray(parts);
list = new JList(parts);
list.setVisibleRowCount(5);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setFixedCellHeight(44);
list.setFixedCellWidth(100);
view.add(new JScrollPane(list),BorderLayout.CENTER);
view.setVisible(true);
list.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e2) {
if (e2.getValueIsAdjusting())
return;
String str = list.getSelectedValue().toString();
model.setCurrentInventory(str);
invDetailView = new MVC.views.invDetailView(model);
showInvListController controller1 = new showInvListController(model, view);
invDetailView.registerListeners(controller1);
invDetailView.setSize(250, 250);
invDetailView.setLocation(800, 0);
invDetailView.setVisible(true);
view.repaint();
//view.revalidate();
}
});
partList.clear();
}
}
*/
|
package io.swagger.api;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiParam;
import io.swagger.client.ApiException;
import io.swagger.client.model.PaymentDTO;
import io.swagger.model.Payment;
import io.swagger.model.PaymentOrderConsentResponse;
import io.swagger.model.PaymentOrderRequest;
import io.swagger.model.PaymentOrderResponse;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-03-05T19:08:49.617Z")
@Controller
public class PaymentOrderApiController implements PaymentOrderApi {
private static final String ERROR_PROCESS_SERVICE = "Error process service";
private static final String ERROR_SERIALIZE_RESPONSE = "Couldn't serialize response for content type application/json";
private static final Logger log = LoggerFactory.getLogger(PaymentOrderApiController.class);
private final ObjectMapper objectMapper;
private final HttpServletRequest request;
@org.springframework.beans.factory.annotation.Autowired
public PaymentOrderApiController(ObjectMapper objectMapper, HttpServletRequest request) {
this.objectMapper = objectMapper;
this.request = request;
}
public ResponseEntity<Payment> getPaymentConsent(@Pattern(regexp="^\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}$") @Size(min=36,max=36) @ApiParam(value = "Order id Number of current payment",required=true) @PathVariable("orderId") String orderId,@ApiParam(value = "The JWT Token generated from Get API Token" ) @RequestHeader(value="x-dnbapi-jwt", required=false) String xDnbapiJwt,@ApiParam(value = "The API key from your app page in DNB Developer" ) @RequestHeader(value="x-api-key", required=false) String xApiKey) {
String accept = request.getHeader("Accept");
if (accept != null && accept.contains("application/json")) {
try {
String jsonString = PaymentFacade.getPaymentConsent(orderId);
return new ResponseEntity<Payment>(objectMapper.readValue(jsonString, Payment.class), HttpStatus.OK);
} catch (IOException e) {
log.error(ERROR_SERIALIZE_RESPONSE, e);
return new ResponseEntity<Payment>(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (ApiException e) {
log.error("Service error: " + e.getMessage(), e);
return new ResponseEntity<Payment>(HttpStatus.NOT_FOUND);
}
}
return new ResponseEntity<Payment>(HttpStatus.NOT_IMPLEMENTED);
}
public ResponseEntity<Payment> getPaymentDue(@Pattern(regexp="^\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}$") @Size(min=36,max=36) @ApiParam(value = "Order id Number of current payment",required=true) @PathVariable("orderId") String orderId,@ApiParam(value = "The JWT Token generated from Get API Token" ) @RequestHeader(value="x-dnbapi-jwt", required=false) String xDnbapiJwt,@ApiParam(value = "The API key from your app page in DNB Developer" ) @RequestHeader(value="x-api-key", required=false) String xApiKey) {
String accept = request.getHeader("Accept");
if (accept != null && accept.contains("application/json")) {
try {
String jsonString = PaymentFacade.getPaymentConsent(orderId);
return new ResponseEntity<Payment>(objectMapper.readValue(jsonString, Payment.class), HttpStatus.OK);
// return new ResponseEntity<Payment>(objectMapper.readValue("{ \"debtorAccount\" : { \"identification\" : \"00100\", \"name\" : \"Santander\", \"destinationDNI\" : \"14000000\" }, \"creditorAccount\" : { \"identification\" : \"00100\", \"name\" : \"Santander\", \"destinationDNI\" : \"14000000\" }, \"instructedAmount\" : { \"amount\" : 100000.0, \"currency\" : 152.0 }, \"status\" : \"APPROVED\"}", Payment.class), HttpStatus.NOT_IMPLEMENTED);
} catch (IOException e) {
log.error(ERROR_SERIALIZE_RESPONSE, e);
return new ResponseEntity<Payment>(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (ApiException e) {
log.error("Service error: " + e.getMessage(), e);
return new ResponseEntity<Payment>(HttpStatus.NOT_FOUND);
}
}
return new ResponseEntity<Payment>(HttpStatus.NOT_IMPLEMENTED);
}
public ResponseEntity<PaymentOrderResponse> paymentOrder(@ApiParam(value = "" ,required=true ) @Valid @RequestBody PaymentOrderRequest body,@ApiParam(value = "The JWT Token generated from Get API Token" ) @RequestHeader(value="x-dnbapi-jwt", required=false) String xDnbapiJwt,@ApiParam(value = "The API key from your app page in DNB Developer" ) @RequestHeader(value="x-api-key", required=false) String xApiKey) {
String accept = request.getHeader("Accept");
if (accept != null && accept.contains("application/json")) {
try {
PaymentDTO dto = PaymentFacade.updatePaymentOrder(body);
PaymentOrderResponse response = new PaymentOrderResponse();
response.setOrderId(dto.getId());
response.setTransactionId(dto.getTransactionId());
response.setPayment(body.getPayment());
return new ResponseEntity<PaymentOrderResponse>(response, HttpStatus.OK);
// return new ResponseEntity<PaymentOrderResponse>(objectMapper.readValue("{ \"orderId\" : \"12345\", \"payment\" : { \"debtorAccount\" : { \"identification\" : \"00100\", \"name\" : \"Santander\", \"destinationDNI\" : \"14000000\" }, \"creditorAccount\" : { \"identification\" : \"00100\", \"name\" : \"Santander\", \"destinationDNI\" : \"14000000\" }, \"instructedAmount\" : { \"amount\" : 100000.0, \"currency\" : 152.0 }, \"status\" : \"APPROVED\" }, \"transactionId\" : \"000012345\"}", PaymentOrderResponse.class), HttpStatus.NOT_IMPLEMENTED);
} catch (ApiException e) {
log.error(ERROR_PROCESS_SERVICE, e);
return new ResponseEntity<PaymentOrderResponse>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
return new ResponseEntity<PaymentOrderResponse>(HttpStatus.NOT_IMPLEMENTED);
}
public ResponseEntity<PaymentOrderConsentResponse> paymentOrderConsent(@ApiParam(value = "" ,required=true ) @Valid @RequestBody PaymentOrderRequest body,@ApiParam(value = "The JWT Token generated from Get API Token" ) @RequestHeader(value="x-dnbapi-jwt", required=false) String xDnbapiJwt,@ApiParam(value = "The API key from your app page in DNB Developer" ) @RequestHeader(value="x-api-key", required=false) String xApiKey) {
String accept = request.getHeader("Accept");
if (accept != null && accept.contains("application/json")) {
try {
PaymentFacade.addPaymentOrder(body);
return new ResponseEntity<PaymentOrderConsentResponse>(objectMapper.readValue("{ \"orderId\" : \"" + body.getOrderId() + "\", \"description\" : \"Payment order consent created\"}", PaymentOrderConsentResponse.class), HttpStatus.CREATED);
} catch (IOException e) {
log.error(ERROR_SERIALIZE_RESPONSE, e);
return new ResponseEntity<PaymentOrderConsentResponse>(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (ApiException e) {
log.error(ERROR_PROCESS_SERVICE, e);
return new ResponseEntity<PaymentOrderConsentResponse>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
return new ResponseEntity<PaymentOrderConsentResponse>(HttpStatus.NOT_IMPLEMENTED);
}
}
|
package org.oatesonline.yaffle.entities.impl;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlRootElement;
import org.json.simple.JSONObject;
import org.oatesonline.yaffle.entities.IPlayer;
import org.oatesonline.yaffle.entities.dao.DAOFactory;
import org.oatesonline.yaffle.entities.dao.DAOTeam;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Cached;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Indexed;
import com.googlecode.objectify.annotation.Serialized;
@Entity
@XmlRootElement
@Cached
@PersistenceCapable
public class Player extends DTOEntity implements IPlayer , Comparable{
// Logger log = Logger.getLogger(Player.class.getName());
/**
*
*/
private static final long serialVersionUID = 6893007501145539201L;
@Id
@Element
private Long id;
@Attribute(name="name")
private String name;
@Element
@Indexed
private String email;
@Attribute(name="nickname")
private String nickname;
private String pwd;
@Element
private short pld;
@Element
private short pos;
@Element
//Previous position
private short prev;
@Element
private int gd;
@Element
private int pts;
@Persistent
private java.util.List<Key<Team>> teamKeys;
// Used for Yaffle 2015
// @Serialized
// private java.util.Map<String, Key<Team>> teamKeys;
/**
* @return the prev
*/
public short getPrev() {
return prev;
}
/**
* @param prev the prev to set
*/
public void setPrev(short prev) {
this.prev = prev;
}
/**
* @return the pld
*/
public short getPld() {
return pld;
}
/**
* @param pld the pld to set
*/
public void setPld(short pld) {
this.pld = pld;
}
/**
* @return the pos
*/
public short getPos() {
return pos;
}
/**
* @param pos the pos to set
*/
public void setPos(short pos) {
this.pos = pos;
}
/**
* @return the gd
*/
public int getGd() {
return gd;
}
/**
* @param gd the gd to set
*/
public void setGd(int gd) {
this.gd = gd;
}
/**
* @return the pts
*/
public int getPts() {
return pts;
}
/**
* @param pts the pts to set
*/
public void setPts(int pts) {
this.pts = pts;
}
private Player(){
this.name = "";
this.email = "";
this.nickname = "";
this.id = null;
this.gd=0;
this.pld=0;
this.pts=0;
this.pos=0;
teamKeys = new LinkedList<Key<Team>>();
}
public Player(String name, String email, String pin){
this();
this.name = name ;
this.email = email;
this.pwd = pin;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String toXMLString() {
Serializer ser = new Persister();
StringWriter sw = new StringWriter();
try {
ser.write(this, sw);
} catch (Exception e) {
// log.log(Level.FINE, "Error writing XML for league <" + this.name + ">");
e.printStackTrace();
}
return sw.toString();
}
@SuppressWarnings("unchecked")
@Override
public String toJSONString() {
JSONObject jObj = new JSONObject();
DAOTeam daoT = DAOFactory.getDAOTeamInstance();
jObj.put("name", this.name);
jObj.put("email", this.email);
jObj.put("id", this.id);
jObj.put("nickname", this.nickname);
jObj.put("pld", this.pld);
jObj.put("pos", this.pos);
jObj.put("gd", this.gd);
jObj.put("pts", this.pts);
List<JSONObject> teams = new LinkedList<JSONObject>();
Iterator<Key<Team>> itLeague = teamKeys.iterator();
Team t = null;
Key<Team> kTeam = null;
while (itLeague.hasNext()){
kTeam = itLeague.next();
t = daoT.getTeam(kTeam);
if (null != t){
teams.add(t.toJSONObject());
}
}
jObj.put("teams", teams);
return jObj.toJSONString();
}
@Override
public String getName() {
return this.name;
}
@Override
public String getEmail() {
return this.email;
}
@Override
public String getNickname() {
return this.nickname;
}
@Override
public List<Key<Team>> getTeamKeys() {
return teamKeys;
}
@Override
public void setEmail(String email) {
this.email = email;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public void setNickname(String nickname) {
this.nickname = nickname;
}
public void setPassword(String pwd){
this.pwd = pwd;
}
public String getPassword(){
return pwd;
}
public void addTeam(String leagueCode, Team team) {
if (team != null){
Key<Team> kTeam = new Key<Team>(Team.class, team.getName());
//TODO test leagueCode is valid. Throw exception otherwise.
this.teamKeys.add(kTeam);
}
}
@Override
public int compareTo(Object o) {
if (o instanceof Player){
Player p = (Player) o;
if (this.pts > p.pts){
return -1;
}
if (this.pts < p.pts){
return 1;
}
if (this.gd > p.gd){
return -1;
}
if (this.gd < p.gd){
return 1;
}
if (this.pld < p.pld){
return 1;
}
if (this.pld > p.pld){
return -1;
}
return this.nickname.compareToIgnoreCase(p.nickname);
}
return 0;
}
}
|
/*
* @(#) JmsInfoAction.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ims.jmsinfo.struts.action;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.esum.appcommon.resource.application.Config;
import com.esum.appcommon.session.SessionMgr;
import com.esum.appframework.exception.ApplicationException;
import com.esum.appframework.struts.action.BaseDelegateAction;
import com.esum.appframework.struts.actionform.BeanUtilForm;
import com.esum.framework.core.management.ManagementException;
import com.esum.imsutil.util.ReloadXTrusAdmin;
import com.esum.wp.ims.config.XtrusConfig;
import com.esum.wp.ims.jmsinfo.JmsInfo;
import com.esum.wp.ims.jmsinfo.service.IJmsInfoService;
import com.esum.wp.ims.tld.XtrusLangTag;
/**
*
* @author heowon@esumtech.com
* @version $Revision: 1.4 $ $Date: 2010/01/27 03:55:43 $
*/
public class JmsInfoAction extends BaseDelegateAction {
protected ActionForward doService(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
if (method.equals("other method")) {
/**
*/
return null;
} else if (method.equals("jmsInfoPageList")) {
JmsInfo jmsInfo = null;
BeanUtilForm beanUtilForm = (BeanUtilForm)form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
}else {
beanUtilForm = new BeanUtilForm();
}
int itemCountPerPage = Config.getInt("Common", "LIST.COUNT_PER_PAGE");
if(inputObject == null) {
jmsInfo = new JmsInfo();
jmsInfo.setCurrentPage(new Integer(1));
jmsInfo.setItemCountPerPage(new Integer(itemCountPerPage));
}else {
jmsInfo = (JmsInfo)inputObject;
if(jmsInfo.getCurrentPage() == null) {
jmsInfo.setCurrentPage(new Integer(1));
}
if(jmsInfo.getItemCountPerPage() == null) {
jmsInfo.setItemCountPerPage(new Integer(itemCountPerPage));
}
}
SessionMgr sessMgr = new SessionMgr(request);
jmsInfo.setDbType(sessMgr.getValue("dbType"));
if(jmsInfo.getInterfaceId() != null){
if(jmsInfo.getInterfaceId().equals("null")){
jmsInfo.setInterfaceId("");
}
}else if(jmsInfo.getInterfaceId() == null){
jmsInfo.setInterfaceId("");
}
jmsInfo.setInterfaceId(jmsInfo.getInterfaceId() + "%");
beanUtilForm.setBean(jmsInfo);
request.setAttribute("inputObject", jmsInfo);
return super.doService(mapping, beanUtilForm, request, response);
} else if (method.equals("jmsInfoDetail")) {
JmsInfo jmsInfo = null;
BeanUtilForm beanUtilForm = (BeanUtilForm)form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
}else {
beanUtilForm = new BeanUtilForm();
}
if(inputObject == null) {
jmsInfo = new JmsInfo();
}else {
jmsInfo = (JmsInfo)inputObject;
}
List jmsInfoDetailList = (List) ((IJmsInfoService)iBaseService).jmsInfoDetail(jmsInfo);
jmsInfo.setJmsInfoDetailList(jmsInfoDetailList);
beanUtilForm.setBean(jmsInfo);
request.setAttribute("inputObject", jmsInfo);
return super.doService(mapping, beanUtilForm, request, response);
} else if (method.equals("delete")) {
JmsInfo jmsInfo = null;
BeanUtilForm beanUtilForm = (BeanUtilForm)form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
}else {
beanUtilForm = new BeanUtilForm();
}
if(inputObject == null) {
jmsInfo = new JmsInfo();
}else {
jmsInfo = (JmsInfo)inputObject;
}
beanUtilForm.setBean(jmsInfo);
request.setAttribute("inputObject", jmsInfo);
ActionForward forward = super.doService(mapping, beanUtilForm, request, response);
try {
String ids[] = new String[1];
ids[0] = jmsInfo .getInterfaceId();
String configId = XtrusConfig.JMS_COMPONENT_ID;
ReloadXTrusAdmin reload = ReloadXTrusAdmin.getInstance();
reload.reloadComponent(ids, configId);
}catch (ManagementException me) {
String errorMsg =XtrusLangTag.getMessage("error.management.exception");
ApplicationException are = new ApplicationException(me);
ApplicationException ae = new ApplicationException(errorMsg);
are.printException("");
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
} catch (RuntimeException re) {
String errorMsg =XtrusLangTag.getMessage("error.runtime.exception");
ApplicationException are = new ApplicationException(re);
ApplicationException ae = new ApplicationException(errorMsg);
are.printException("");
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
}catch(Exception e){
e.printStackTrace();
ApplicationException ae = new ApplicationException(e);
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
}
return forward;
} else if (method.equals("update")) {
JmsInfo jmsInfo = null;
BeanUtilForm beanUtilForm = (BeanUtilForm)form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
}else {
beanUtilForm = new BeanUtilForm();
}
if(inputObject == null) {
jmsInfo = new JmsInfo();
}else {
jmsInfo = (JmsInfo)inputObject;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
jmsInfo.setModDate(sdf.format(new Date()));
beanUtilForm.setBean(jmsInfo);
request.setAttribute("inputObject", jmsInfo);
ActionForward forward = super.doService(mapping, beanUtilForm, request, response);
try {
String ids[] = new String[1];
ids[0] = jmsInfo .getInterfaceId();
String configId = XtrusConfig.JMS_COMPONENT_ID;
ReloadXTrusAdmin reload = ReloadXTrusAdmin.getInstance();
reload.reloadComponent(ids, configId);
}catch (ManagementException me) {
String errorMsg =XtrusLangTag.getMessage("error.management.exception");
ApplicationException are = new ApplicationException(me);
ApplicationException ae = new ApplicationException(errorMsg);
are.printException("");
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
} catch (RuntimeException re) {
String errorMsg =XtrusLangTag.getMessage("error.runtime.exception");
ApplicationException are = new ApplicationException(re);
ApplicationException ae = new ApplicationException(errorMsg);
are.printException("");
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
}catch(Exception e){
e.printStackTrace();
ApplicationException ae = new ApplicationException(e);
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
}
return forward;
} else if (method.equals("insert")) {
JmsInfo jmsInfo = null;
BeanUtilForm beanUtilForm = (BeanUtilForm)form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
}else {
beanUtilForm = new BeanUtilForm();
}
if(inputObject == null) {
jmsInfo = new JmsInfo();
}else {
jmsInfo = (JmsInfo)inputObject;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
jmsInfo.setRegDate(sdf.format(new Date()));
jmsInfo.setModDate(sdf.format(new Date()));
beanUtilForm.setBean(jmsInfo);
request.setAttribute("inputObject", jmsInfo);
ActionForward forward = super.doService(mapping, beanUtilForm, request, response);
try {
String ids[] = new String[1];
ids[0] = jmsInfo .getInterfaceId();
String configId = XtrusConfig.JMS_COMPONENT_ID;
ReloadXTrusAdmin reload = ReloadXTrusAdmin.getInstance();
reload.reloadComponent(ids, configId);
}catch (ManagementException me) {
String errorMsg =XtrusLangTag.getMessage("error.management.exception");
ApplicationException are = new ApplicationException(me);
ApplicationException ae = new ApplicationException(errorMsg);
are.printException("");
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
} catch (RuntimeException re) {
String errorMsg =XtrusLangTag.getMessage("error.runtime.exception");
ApplicationException are = new ApplicationException(re);
ApplicationException ae = new ApplicationException(errorMsg);
are.printException("");
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
}catch(Exception e){
e.printStackTrace();
ApplicationException ae = new ApplicationException(e);
request.setAttribute("servletpath", request.getServletPath());
request.setAttribute("exception", ae);
return mapping.findForward("failure");
}
return forward;
} else if(method.equals("saveJmsInfoExcel")){
JmsInfo jmsInfo = null;
BeanUtilForm beanUtilForm = (BeanUtilForm) form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
}else {
beanUtilForm = new BeanUtilForm();
}
if(inputObject == null) {
jmsInfo = new JmsInfo();
}else {
jmsInfo = (JmsInfo)inputObject;
}
SessionMgr sessMgr = new SessionMgr(request);
jmsInfo.setDbType(sessMgr.getValue("dbType"));
jmsInfo.setLangType(sessMgr.getValue("langType"));
jmsInfo.setRootPath(getServlet().getServletContext().getRealPath("/"));
IJmsInfoService service = (IJmsInfoService)iBaseService;
service.saveJmsInfoExcel(jmsInfo, request, response);
return null;
} else {
return super.doService(mapping, form, request, response);
}
}
}
|
package model;
public class Homem extends Usuario{
public Homem(String nome) {
super(nome);
}
public String saudacao() {
return "Olá Sr. "+ getNome();
}
}
|
package data;
import java.io.Serializable;
/**
* {@param enum which is a part of LabWork class
*/
public class Discipline implements Serializable {
private String name; //Поле не может быть null, Строка не может быть пустой
private Long practiceHours; //Поле не может быть null
public Discipline(String name, Long practiceHours){
this.name = name;
this.practiceHours = practiceHours;
}
public Discipline(){}
public void setName(String name){this.name =name;}
public void setPracticeHours(Long practiceHours){this.practiceHours = practiceHours; }
public String getName(){return name;}
public Long getPracticeHours(){return practiceHours;}
@Override
public String toString() {
return "Discipline{" +
"name = " + name +
", practiceHours = " + practiceHours +
'}';
}
}
|
package FT;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
class FileTracker {
static private String address;
static private int port;
static final private Queue<Socket> clientsQueue = new LinkedList<>();
static final private List<FileModel> allFiles = new LinkedList<>();
static final HashMap<String, List<FileModel>> filesMap = new HashMap<>();
private static final HashMap<String, Integer> requestsMap = new HashMap<>(), uploadsMap = new HashMap<>();
static void init(String address, int port) {
FileTracker.address = address;
FileTracker.port = port;
}
static void start() {
new Thread(FileTracker::waitForClients).start();
new Thread(FileTracker::handleClients).start();
System.out.format("FT: File Tracker has started on %s:%d\n", address, port);
}
static private void waitForClients() {
try {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("FT: Waiting for clients to arrive");
while (true) {
Socket clientSocket = serverSocket.accept();
synchronized (clientsQueue) {
clientsQueue.add(clientSocket);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
static private void handleClients() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (clientsQueue) {
if (clientsQueue.isEmpty())
continue;
Socket socket = clientsQueue.poll();
new Thread(new ClientHandler(socket)).start();
}
}
}
static void registerFiles(List<FileModel> files) {
synchronized (allFiles) {
System.out.format("FT: new files came\n");
allFiles.addAll(files);
for (FileModel file : files) {
if (!filesMap.containsKey(file.fileName))
filesMap.put(file.fileName, new LinkedList<>());
List<FileModel> list = filesMap.get(file.fileName);
list.add(file);
}
}
}
static void incNumberOfRequests(String address) {
synchronized (requestsMap) {
int oldValue = requestsMap.getOrDefault(address, 0);
requestsMap.put(address, oldValue + 1);
System.out.println(address + " requests++");
}
}
static void incNumberOfUploads(String address) {
synchronized (uploadsMap) {
int oldValue = uploadsMap.getOrDefault(address, 0);
uploadsMap.put(address, oldValue + 1);
System.out.println(address + " uploads++");
}
}
static String getRate(String address) {
int request, uploads;
synchronized (requestsMap) {
request = requestsMap.getOrDefault(address, 0);
}
synchronized (uploadsMap) {
uploads = uploadsMap.getOrDefault(address, 0);
}
if (request == 0) {
request = 1;
uploads = 0;
}
System.out.println(address + ":" + uploadsMap.get(address) + "/" + requestsMap.get(address));
System.out.println(String.format("%02d%%", 100 * uploads / request));
return String.format("%02d%%", 100 * uploads / request);
}
static void cleanup(String address) {
for(Map.Entry<String, List<FileModel>> entry : filesMap.entrySet()) {
String key = entry.getKey();
List<FileModel> value = entry.getValue();
value.removeIf(file -> file.address.equals(address));
}
}
}
|
package com.rednovo.tools.sms;
import java.util.HashMap;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.rednovo.tools.MD5;
import com.rednovo.tools.web.HttpSender;
/**
* 互亿无线
* web 登录入口 http://www.ihuyi.com/product.php?cid=33
* @author sg.z/2014年11月3日
*/
public class HywxSms {
/**
* 账号信息
*/
public static final String account = "cf_cqhn";
public static final String password = "LEduo0_48Mb";
public static final String SEND_URL = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
public static final String SEL_SUM_URL = "http://106.ihuyi.cn/webservice/sms.php?method=GetNum";
/**
* 互亿无线发送短信
*
* @param mobile
* @param content
* @return
* @author sg.z
* @since 2014年11月3日下午4:59:18
*/
public static boolean sendSms(String mobile, String content) {
// 查询余额
int num = getSelSum();
if (num > 0) {
if (StringUtils.isNotBlank(content) && content.length() < 67) {
HashMap<String, String> param = new HashMap<String, String>();
param.put("account", account);
param.put("password", MD5.md5(password));
param.put("mobile", mobile);
param.put("content", content);
String result = HttpSender.httpClientRequest(SEND_URL, param);
if (StringUtils.isNotBlank(result)) {
Document doc;
try {
doc = DocumentHelper.parseText(result);
} catch (DocumentException e) {
return false;
}
Element root = doc.getRootElement();
String code = root.elementText("code");
if (StringUtils.equals(code, "2")) {
return true;
} else {
return false;
}
}
}
}
return false;
}
/**
* 查询余额
*
* @return
* @author sg.z
* @since 2014年11月3日下午5:09:40
*/
public static int getSelSum() {
HashMap<String, String> param = new HashMap<String, String>();
param.put("account", account);
param.put("password", password);
String result = HttpSender.httpClientRequest(SEL_SUM_URL, param);
if (StringUtils.isNotBlank(result)) {
Document doc;
try {
doc = DocumentHelper.parseText(result);
} catch (DocumentException e) {
return 0;
}
Element root = doc.getRootElement();
String code = root.elementText("code");
// String msg = root.elementText("msg");
String num = root.elementText("num");
if (StringUtils.equals(code, "2")) {
return Integer.valueOf(num).intValue();
} else {
return 0;
}
}
return 0;
}
public static void main(String[] args) {
boolean str = sendSms("", "您的验证码是:888888。");
System.err.println("发送结果:" + str);
}
}
|
/*
* Created on 2004. 10. 5.
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.esum.comp.etx.util;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.comp.etx.ETXCode;
import com.esum.comp.etx.ETXException;
public class ListFileReader
{
private Logger log = LoggerFactory.getLogger(ListFileReader.class);
private List list;
public ListFileReader(String listFile) throws ETXException{
list = new ArrayList();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(listFile)));
} catch (FileNotFoundException e) {
log.error("list file not found", e);
try{
if(reader!=null)
reader.close();
}catch(Exception ex){
}
throw new ETXException(ETXCode.ERROR_TXFILE_IO, "ListFileReader()", e.toString());
}
while(true){
String line = null;
try{
line = reader.readLine();
}catch(IOException e){
log.error("list file read error", e);
try{
if(reader!=null)
reader.close();
}catch(Exception ex){
}
throw new ETXException(ETXCode.ERROR_TXFILE_IO, "ListFileReader()", e.toString());
}
if(line==null)
break;
list.add(line.trim());
}
try{
if(reader!=null)
reader.close();
}catch(Exception e){
}
}
public int getLineCount(){
return list.size();
}
public String lineAt(int idx){
return (String)list.get(idx);
}
public long getDocSizeAt(int idx) {
String line = lineAt(idx);
int i = line.lastIndexOf("|");
String value = line.substring(i+1);
if(value!=null && !value.trim().equals(""))
return Integer.parseInt(value);
return 0;
}
}
|
package com.khs.hystrix.hcommand;
import java.net.URI;
import org.apache.log4j.Logger;
import org.bjc.clindesk.server.Dispatchable;
import org.bjc.clindesk.server.ObjectDispatchable;
import com.khs.hystrix.model.SampleObject;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
public class SampleHystrixServletCommand extends AbstractHystrixCommand {
private static final Logger LOG = Logger.getLogger(SampleHystrixServletCommand.class);
private long counter;
private static final URI SAMPLE_URI = URI.create("http://localhost:8080/app/sample");
public SampleHystrixServletCommand(long counter) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GET"))
.andCommandKey(HystrixCommandKey.Factory.asKey(SAMPLE_URI.getPath()))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(60000)
.withCircuitBreakerErrorThresholdPercentage(50)));
this.counter = counter;
}
@Override
protected Dispatchable run() throws Exception {
if (counter % 10 == 0) {
causeTimeout();
} else if (counter % 5 == 0) {
causeFailure();
}
return new ObjectDispatchable(createResponseData());
}
private void causeFailure() {
throw new RuntimeException("Failure");
}
private void causeTimeout() {
try {
Thread.sleep(60000);
} catch (Exception e) {
//
}
}
private SampleObject createResponseData() {
SampleObject response = new SampleObject();
response.setOne(1);
response.setTwo("2");
response.setThree("three");
response.setFour(40);
response.setFive("fifty-five");
return response;
}
}
|
package jp.co.axiz.web.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import jp.co.axiz.web.entity.Comments;
@Repository
public class CommentDao {
public List<Comments> find(Comments comments){
return null;
}
public Comments findById(Integer id) {
return null;
}
public void register(Comments comments) {
}
public void update(Comments comments) {
}
public void delete(Integer id) {
}
}
|
package com.sapient.productservice.dao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.sapient.productservice.model.Product;
@Repository(value="mysqlDaoImp")
public class ServicedaoProductImp implements ServicedaoProduct {
@Autowired
JdbcTemplate jdbctemplate;
public Product saveProduct(Product product) {
jdbctemplate.execute("insert into P values('"+product.getName()+"','"+product.getId()+"','"+product.getPrice()+"')");
return product;
}
public List<Product> fetchAllProducts() {
List<Product> products=jdbctemplate.query("select * from P", ( rs, rowNum)-> new Product(rs.getInt(2), rs.getString(1)));
System.out.println(products);
return products;
}
public Product findById(long id) {
return jdbctemplate.queryForObject("select * from P where id="+id, ( rs, rowNum)->
{
Product product = new Product(rs.getInt(2), rs.getString(1));
product.setPrice(rs.getDouble(3));
return product;
});
}
public void deleteProduct(long id) {
jdbctemplate.execute("delete from P where id="+id);
}
public Product updateProduct1(long id,Product product)
{
jdbctemplate.execute("update P set name='"+product.getName()+"' where id="+id);
return product;
}
}
|
package cn.hrbcu.com.servlet.adminServlet;
import cn.hrbcu.com.entity.Books;
import cn.hrbcu.com.entity.Institution;
import cn.hrbcu.com.entity.Page;
import cn.hrbcu.com.service.BooksService;
import cn.hrbcu.com.service.impl.AdminServiceImpl;
import cn.hrbcu.com.service.impl.BooksServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
/**
* @author: XuYi
* @date: 2021/5/23 17:10
* @description:
*/
@WebServlet("/BooksListServlet")
public class BooksListServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*设置编码*/
req.setCharacterEncoding("utf-8");
/*获取状态参数*/
String status = req.getParameter("status");
/*获取当前页码*/
String currentPage = req.getParameter("currentPage");
/*获取总页数*/
String totalPage = req.getParameter("totalPage");
/*每页条数*/
String rows = req.getParameter("rows");
/*初始化转发路径*/
String path = null;
// if("PageList".equals(status)) {
/*边界处理*/
if (currentPage == null || "".equals(currentPage)) {
currentPage = "1";
if (currentPage == null || "".equals(currentPage)) {
currentPage = "1";
}
}
if (rows == null || "".equals(rows)) {
rows = "5";
}
if (currentPage == totalPage) {
currentPage = "1";
}
/*获取条件查询参数*/
Map<String, String[]> condition = req.getParameterMap();
/*调用服务层*/
BooksService booksService = new BooksServiceImpl();
Page<Books> pb = booksService.findBooksByPage(currentPage, rows, condition);
System.out.println(pb + "\n");
/*往request注入值*/
req.setAttribute("pb", pb);
/*将查询条件注入request*/
req.setAttribute("condition", condition);
/*设置并转发*/
path = "/books.jsp";
if("delBooks".equals(status)){
/*获取所选id*/
String[] books_id = req.getParameterValues("books_id");
/*调用服务层完成删除*/
BooksService booksService_del = new BooksServiceImpl();
booksService_del.delSelectedBooks(books_id);
/*设置跳转页面*/
resp.sendRedirect(req.getContextPath()+"/BooksListServlet");
}
req.getRequestDispatcher(path).forward(req,resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
|
package org.exoplatform.management.packaging.xml;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IMarshallingContext;
import org.exoplatform.container.xml.Component;
import org.exoplatform.container.xml.Configuration;
import org.exoplatform.container.xml.ComponentPlugin;
import org.exoplatform.container.xml.ExternalComponentPlugins;
import org.exoplatform.container.xml.InitParams;
import org.exoplatform.container.xml.ObjectParameter;
import org.exoplatform.xml.object.XMLField;
import org.exoplatform.xml.object.XMLObject;
import org.exoplatform.xml.object.XMLCollection;
import java.util.Collection;
import org.exoplatform.container.xml.ValueParam;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: gregorysebert
* Date: 12/07/12
* Time: 19:09
* To change this template use File | Settings | File Templates.
*/
public class XmlConfiguration {
private static final String KERNEL_CONFIGURATION_1_1_URI = "<configuration xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.exoplaform.org/xml/ns/kernel_1_2.xsd http://www.exoplaform.org/xml/ns/kernel_1_2.xsd\" xmlns=\"http://www.exoplaform.org/xml/ns/kernel_1_2.xsd\">";
private static final String EMPTY_FIELD_REGULAR_EXPRESSION = "<field name=\"([a-z|A-Z]*)\"/>";
public void XmlConfiguration()
{
}
public void addPortalConfiguration(FileOutputStream zos)
{
ExternalComponentPlugins externalComponentPlugins = new ExternalComponentPlugins();
externalComponentPlugins.setTargetComponent("org.exoplatform.portal.config.UserPortalConfigService");
ComponentPlugin componentPlugin = new ComponentPlugin();
componentPlugin.setName("default.portal.config.user.listener");
componentPlugin.setType("org.exoplatform.portal.config.NewPortalConfigListener");
componentPlugin.setSetMethod("initListener");
componentPlugin.setDescription("this listener init the portal configuration");
InitParams initParams = new InitParams();
ValueParam valueParam = new ValueParam();
valueParam.setName("default.portal");
valueParam.setValue("default");
valueParam.setDescription("The default portal for checking db is empty or not");
// Add portal configuration
ObjectParameter objectParamPortal = new ObjectParameter();
objectParamPortal.setName("portal.configuration");
objectParamPortal.setDescription("description");
XMLObject xmlObject = new XMLObject();
xmlObject.setType("org.exoplatform.portal.config.NewPortalConfig");
XMLCollection xmlCollection = new XMLCollection();
xmlCollection.setType("java.util.HashSet");
Collection collection = new java.util.HashSet<String>();
collection.add("default");
XMLField xmlField = new XMLField();
xmlField.setName("predefinedOwner");
xmlField.setCollection(xmlCollection);
try {
xmlField.setCollectiontValue(collection);
} catch (Exception e) {
e.printStackTrace();
}
xmlObject.addField(xmlField);
xmlField = new XMLField();
xmlField.setName("ownerType");
xmlField.setString("portal");
xmlObject.addField(xmlField);
xmlField = new XMLField();
xmlField.setName("templateLocation");
xmlField.setString("war:/conf/mop/default");
xmlObject.addField(xmlField);
try {
objectParamPortal.setXMLObject(xmlObject);
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
// Add group configuration
ObjectParameter objectParamGroup = new ObjectParameter();
objectParamGroup.setName("group.configuration");
objectParamGroup.setDescription("description");
xmlObject = new XMLObject();
xmlObject.setType("org.exoplatform.portal.config.NewPortalConfig");
xmlCollection = new XMLCollection();
xmlCollection.setType("java.util.HashSet");
collection = new java.util.HashSet<String>();
collection.add("/platform/web-contributors");
xmlField = new XMLField();
xmlField.setName("predefinedOwner");
xmlField.setCollection(xmlCollection);
try {
xmlField.setCollectiontValue(collection);
} catch (Exception e) {
e.printStackTrace();
}
xmlObject.addField(xmlField);
xmlField = new XMLField();
xmlField.setName("ownerType");
xmlField.setString("group");
xmlObject.addField(xmlField);
xmlField = new XMLField();
xmlField.setName("templateLocation");
xmlField.setString("war:/conf/mop/default");
xmlObject.addField(xmlField);
try {
objectParamGroup.setXMLObject(xmlObject);
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
initParams.addParam(valueParam);
initParams.addParam(objectParamPortal);
initParams.addParam(objectParamGroup);
componentPlugin.setInitParams(initParams);
ArrayList componentPluginsList = new ArrayList();
componentPluginsList.add(componentPlugin);
externalComponentPlugins.setComponentPlugins(componentPluginsList);
Configuration configuration = new Configuration();
configuration.addExternalComponentPlugins(externalComponentPlugins);
try{
zos.write(toXML(configuration));
zos.close();
//zos.closeEntry();
}catch (Exception e) {}
}
protected byte[] toXML(Object obj) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
IBindingFactory bfact = BindingDirectory.getFactory(obj.getClass());
IMarshallingContext mctx = bfact.createMarshallingContext();
mctx.setIndent(2);
mctx.marshalDocument(obj, "UTF-8", null, out);
String outConf = new String(out.toByteArray());
outConf = outConf.replace("<configuration>", KERNEL_CONFIGURATION_1_1_URI).replaceAll(EMPTY_FIELD_REGULAR_EXPRESSION, "");
return outConf.getBytes();
} catch (Exception ie) {
throw ie;
}
}
}
|
package pl.btbw.client;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import java.util.List;
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<RepoDto>> listRepos(@Path("user") String user);
}
|
package exercises.chapter6.ex7;
import exercises.chapter6.ex7.access.Widget;
/**
* @author Volodymyr Portianko
* @date.created 14.03.2016
*/
public class Exercise7 {
public static void main(String[] args) {
new Widget();
}
}
|
/*
* 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 UI;
import Logique.Categorie;
import Logique.Generalites;
import Logique.Model_Table;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
/**
*
* @author nahimana
*/
public class UI_Categorie extends javax.swing.JFrame {
/**
* Creates new form UI_Categorie
*/
// static Model_Table tableau;
static String [] titles={"Identifiant","Nom de la Categorie","Prix"};
public UI_Categorie() {
initComponents();
Generalites.Centrer_Fenetres(this);
adapter_Model();
}
static Categorie cat=null;
void adapter_Model(){
charger_tableau(ui_categorie_data);
bt_modifier.setEnabled(false);
ui_categorie_data.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e) {
int index_ligne=-1;
if((index_ligne=ui_categorie_data.getSelectedRow())==-1)
return;
bt_enregistrer_categorie.setEnabled(false);
bt_modifier.setEnabled(true);
ui_nom_categorie.setText(ui_categorie_data.getValueAt(index_ligne,1).toString());
ui_categorie_prix.setText(ui_categorie_data.getValueAt(index_ligne,2).toString());
if(cat==null)
cat=new Categorie();
cat.setCatID(Integer.parseInt(ui_categorie_data.getValueAt(index_ligne,0).toString()));
}
});
}
void charger_tableau(JTable tabl){
ResultSet result=db.db_Con.extraireData("select * from categorie");
int size=0,i=0;
if(result!=null)
{
try {
size=Generalites.getResultSetRowCount(result);
String [][] data=new String[size][titles.length];
while(result.next()){
data[i][0]=""+result.getInt("catID");
data[i][1]=result.getString("nom");
data[i][2]=""+result.getFloat("prix");
i++;
}
tabl.setModel(new Model_Table(data, titles));
} catch (SQLException ex) {
Logger.getLogger(UI_Categorie.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
ui_nom_categorie = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
ui_categorie_prix = new javax.swing.JTextField();
bt_enregistrer_categorie = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
ui_categorie_data = new javax.swing.JTable();
bt_modifier = new javax.swing.JButton();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Nom de Categorie");
ui_nom_categorie.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ui_nom_categorieActionPerformed(evt);
}
});
jLabel2.setText("Prix");
bt_enregistrer_categorie.setText("enregistrer les Categorie");
bt_enregistrer_categorie.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_enregistrer_categorieActionPerformed(evt);
}
});
ui_categorie_data.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane2.setViewportView(ui_categorie_data);
bt_modifier.setText("Modifier les données");
bt_modifier.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bt_modifierActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(109, 109, 109)
.addComponent(bt_enregistrer_categorie)
.addGap(26, 26, 26)
.addComponent(bt_modifier))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(38, 38, 38)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 430, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 94, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ui_nom_categorie, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ui_categorie_prix, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addContainerGap(88, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ui_nom_categorie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(ui_categorie_prix, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bt_enregistrer_categorie)
.addComponent(bt_modifier))
.addGap(28, 28, 28)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(44, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(32, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void bt_enregistrer_categorieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_enregistrer_categorieActionPerformed
// TODO add your handling code here:
Categorie categ=new Categorie();
if(!ui_nom_categorie.getText().trim().equalsIgnoreCase(""))
categ.setNom(ui_nom_categorie.getText());
else {
Generalites.Donner_info_User("Saisissez s'il vous plait le nom de la categorie");
return;
}
if(!ui_categorie_prix.getText().trim().equalsIgnoreCase(""))
try{
categ.setPrix(Float.parseFloat(ui_categorie_prix.getText()));
}catch(NumberFormatException e){
Generalites.Donner_info_User("Saisissew s'il vous plait seulement les chiffres");
return;
}
else {
Generalites.Donner_info_User("Saisissez s'il vous plait le prix de la categorie");
return;
}
if(categ.enregistrer_Cat_DB()>0)
{
charger_tableau(ui_categorie_data);
Generalites.Donner_info_User("Felicitationm votre operation a ete effectuee avec succes");
ui_nom_categorie.setText("");
ui_categorie_prix.setText("");
}
else Generalites.Donner_info_User("Desolem votre operation a echoue");
}//GEN-LAST:event_bt_enregistrer_categorieActionPerformed
private void bt_modifierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_modifierActionPerformed
// TODO add your handling code here:
if(cat==null){
Generalites.Donner_info_User("Selectionnez s'il vous plait la categorie à Modifier");
return;
}
cat.setNom(ui_nom_categorie.getText());
cat.setPrix(Float.parseFloat(ui_categorie_prix.getText()));
if(cat.Modifier_Cat_DB()>0)
{
charger_tableau(ui_categorie_data);
bt_enregistrer_categorie.setEnabled(true);
bt_modifier.setEnabled(false);
Generalites.Donner_info_User("Felicitation, la categorie a ete modifiée");
}
else Generalites.Donner_info_User("Désolé, la categorie n' a pas été modifiée");
}//GEN-LAST:event_bt_modifierActionPerformed
private void ui_nom_categorieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ui_nom_categorieActionPerformed
}//GEN-LAST:event_ui_nom_categorieActionPerformed
/**
* @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(UI_Categorie.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(UI_Categorie.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(UI_Categorie.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(UI_Categorie.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new UI_Categorie().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bt_enregistrer_categorie;
private javax.swing.JButton bt_modifier;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JTable ui_categorie_data;
private javax.swing.JTextField ui_categorie_prix;
private javax.swing.JTextField ui_nom_categorie;
// End of variables declaration//GEN-END:variables
}
|
package com.workshop.alexa;
import com.amazon.speech.slu.Slot;
import com.amazon.speech.speechlet.SpeechletResponse;
import com.amazon.speech.ui.PlainTextOutputSpeech;
import com.amazon.speech.ui.SimpleCard;
import java.util.Optional;
public class AlexaUtil {
private static final String NO_VALUE = "No value";
public static SpeechletResponse createSpeechletResponse(final String title, final String speechText) {
return SpeechletResponse.newTellResponse(createPlainTextOutputSpeech(speechText), createSimpleCard(title, speechText));
}
/**
* Gets the value of a slot. Returns a default value if it isn't set.
*
* @param slot The slot.
*/
public static String getSlotValue(final Slot slot) {
return Optional.ofNullable(slot).map(Slot::getValue).orElse(NO_VALUE);
}
/**
* Creates a visual representation of the response, in the form of a card (it's shown in the Alexa app for example).
*
* @param title The title of the card.
* @param content The content of the card
*/
private static SimpleCard createSimpleCard(final String title, final String content) {
final SimpleCard card = new SimpleCard();
card.setTitle(title);
card.setContent(content);
return card;
}
/**
* Creates a PlainTextOutputSpeech object which tells Alexa what to say.
*
* @param speechText The text Alexa has to say.
*/
private static PlainTextOutputSpeech createPlainTextOutputSpeech(final String speechText) {
final PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
speech.setText(speechText);
return speech;
}
}
|
package com.share.dao;
import com.share.template.HibernateTemplate;
public class StudentPlayerDao extends HibernateTemplate{
}
|
public enum FileType {
FILE,FOLDER
}
|
//********************************************************************
// BorderPanel.java Authors: Lewis/Loftus
//
// Represents the panel in the LayoutDemo program that demonstrates
// the border layout manager.
//********************************************************************
import java.awt.*;
import javax.swing.*;
public class BorderPanel extends JApplet
{
//-----------------------------------------------------------------
// Sets up this panel with a button in each area of a border
// layout to show how it affects their position, shape, and size.
//-----------------------------------------------------------------
public void init() {
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));
content.add(new JButton("Button 2"));
content.add(new JButton("Button 3"));
}
}
|
package ua.te.jug.concurrency.shared.vol;
public class ServiceThread extends Thread {
@Override
public void run() {
Main.state.loop();
}
}
|
package org.rest.dto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "tbl_name")
public class AnimalDto {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "animal_type")
private String type;
@Column(name = "animal_name")
private String name;
@Column(name = "animal_age")
private int age;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "AnimalDto [type=" + type + ", name=" + name + ", age=" + age + "]";
}
public AnimalDto() {
super();
// TODO Auto-generated constructor stub
}
public AnimalDto(String type, String name, int age) {
super();
this.type = type;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
|
import java.util.Arrays;
public class DoublenLastSame {
/**
* @RAKESH YADAV
* 18th February 2015
* Given an int array, return a new array with double the length where its last
* element is same as the original array, and all the other elements are 0. By
* the new array contains all 0's.
*/
public static void main(String[] args) {
int []arr = {1, 2};
int []arr2 = new int[2*arr.length];
System.out.println("Array: ");
for(int i = 0; i < arr.length; i ++){
System.out.print(arr[i] + "\t");
}
arr2 = makeLast(arr);
System.out.println("\n\nNew Array:");
for(int i = 0; i < arr2.length; i++){
System.out.print(arr2[i] + "\t");
}
}
static int []makeLast(int []arr){
int arr2[] = new int[2*arr.length];
Arrays.fill(arr2, 0);
arr2[arr2.length-1] = arr[arr.length-1];
return arr2;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.