text
stringlengths 10
2.72M
|
|---|
package stringhandling;
public class Intern {
public static void main(String args[])
{
String s="hello";
String s2=new String ("hello");
//System.out.println(s==s2);
String s1=s2.intern();
System.out.println(s1==s);
}
}
|
package gil.server.controllers;
import gil.server.http.HTTPProtocol;
import gil.server.http.Request;
import gil.server.http.Response;
import java.util.function.BiFunction;
public class ParametersController {
public static BiFunction<Request, Response, Response> get =
(request, response) -> {
String responseParameters = request.getParameters().toString();
int lengthOfStringWithNoParameters = 2;
Boolean requestHasParameters = responseParameters.length() > lengthOfStringWithNoParameters;
String body = requestHasParameters ? responseParameters : "";
response.setProtocol(HTTPProtocol.PROTOCOL);
response.setStatusCode(HTTPProtocol.STATUS_CODE_200);
response.setReasonPhrase(HTTPProtocol.REASON_PHRASE_OK);
response.addHeader(HTTPProtocol.CONTENT_TYPE,"text/html; charset=UTF-8");
response.setBody(body.getBytes());
return response;
};
}
|
/*
* 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 bioui;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/**
*
* @author Jacquelyn
*/
class QueUI extends JFrame
{
//JLabel date = new JLabel("Click to select date range");
/*
constructor
*/
QueUI()
{
//set size and default button on close
//set dimensions for size of frame
int win_WIDTH = 450;
int win_HEIGHT = 200;
setSize(win_WIDTH, win_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add listeners to the buttons
//JButton dates = new JButton("Dates"); //increment grid layout by 1 when ready to use this function
JButton cells = new JButton("Well Data");
cells.addActionListener((ActionEvent e) -> new LayoutGrid());
JButton stuName = new JButton("Student Name");
stuName.addActionListener((ActionEvent e) -> {
});
JButton semes = new JButton("Semester");
semes.addActionListener((ActionEvent e) -> {
});
//add buttons and labels to the grid
JPanel queryBox = new JPanel(new GridLayout(3, 2));
queryBox.add(stuName); //JButton
//create labels to explain button function
JLabel student = new JLabel("LSC Username");
queryBox.add(student); //JLabel
queryBox.add(semes); //JButton
JLabel semester = new JLabel("Choose a semester");
queryBox.add(semester); //JLabel
//queryBox.add(dates); //for use later
//queryBox.add(date); //for use later
queryBox.add(cells); //JButton
JLabel cell = new JLabel("Click to select specific well data");
queryBox.add(cell); //JLabel
//add pane to the frame
add(queryBox);
//make it show up
setVisible(true);
setLocationRelativeTo(null);
//create frame, pane and buttons
new JFrame();
}
}
|
package be.openclinic.archiving;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import org.apache.pdfbox.util.operator.SetHorizontalTextScaling;
import be.dpms.medwan.common.model.vo.authentication.UserVO;
import be.mxs.common.model.vo.healthrecord.TransactionVO;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.Debug;
import be.mxs.common.util.system.ScreenHelper;
import be.openclinic.common.OC_Object;
import be.openclinic.medical.RequestedLabAnalysis;
public class ArchiveDocument extends OC_Object implements Comparable {
/*
// create table arch_documents (
// arch_document_objectid int,
// arch_document_serverid int,
// arch_document_udi varchar(50),
// arch_document_title varchar(255),
// arch_document_description text,
// arch_document_category varchar(50),
// arch_document_author varchar(50),
// arch_document_date datetime,
// arch_document_destination varchar(255),
// arch_document_reference varchar(50),
// arch_document_personid int,
// arch_document_storagename varchar(255),
// arch_document_deletedate datetime,
// arch_document_tran_serverid int,
// arch_document_tran_transactionid int,
// arch_document_updatetime datetime,
// arch_document_updateid int
// )
*/
public String udi;
public String title;
public String description;
public String category;
public String author;
public java.util.Date date;
public String destination;
public String reference;
public int personId;
public int tranServerId; // link with transaction
public int tranTranId; // link with transaction
public String storageName;
public java.util.Date deleteDate;
//--- CONSTRUCTOR -----------------------------------------------------------------------------
public ArchiveDocument(){
// empty
}
//--- SAVE ------------------------------------------------------------------------------------
// return UDI (unique document id)
public static ArchiveDocument save(boolean isNewTran, TransactionVO tran, UserVO activeUser){
ArchiveDocument archDoc = new ArchiveDocument();
String sUID = "", sUDI = "";
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = null;
if(isNewTran){
//*** create record ***
String sSql = "INSERT INTO arch_documents (arch_document_serverid, arch_document_objectid, arch_document_udi,"+
" arch_document_title, arch_document_description, arch_document_category, arch_document_author,"+
" arch_document_date, arch_document_destination, arch_document_reference, arch_document_personid,"+
" arch_document_tran_serverid, arch_document_tran_transactionid, arch_document_storagename,"+
" arch_document_updatetime, arch_document_updateid, arch_document_sourceid)"+
" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try{
ps = conn.prepareStatement(sSql);
int psIdx = 1;
// IDs
int serverId = Integer.parseInt(MedwanQuery.getInstance().getConfigString("serverId")),
objectId = MedwanQuery.getInstance().getOpenclinicCounter("ARCH_DOCUMENTS");
ps.setInt(psIdx++,serverId);
ps.setInt(psIdx++,objectId);
sUID = serverId+"."+objectId;
// get UDI
sUDI = generateUDI(objectId);
ps.setString(psIdx++,sUDI);
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_TITLE"));
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_DESCRIPTION"));
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_CATEGORY"));
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_AUTHOR"));
// date
String sDate = ScreenHelper.stdDateFormat.format(tran.getUpdateTime());
if(sDate.length() > 0){
sDate = ScreenHelper.convertToEUDate(sDate);
ps.setDate(psIdx++,new java.sql.Date(ScreenHelper.parseDate(sDate).getTime()));
}
else{
ps.setNull(psIdx++,Types.NULL);
}
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_DESTINATION"));
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_REFERENCE"));
// personId
String sPersonId = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_PERSONID");
if(sPersonId.length() > 0){
ps.setInt(psIdx++,Integer.parseInt(sPersonId));
}
else{
ps.setNull(psIdx++,Types.NULL);
}
// transactions' serverId and transactionId
ps.setInt(psIdx++,tran.getServerId());
ps.setInt(psIdx++,tran.getTransactionId().intValue());
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_STORAGENAME"));
ps.setTimestamp(psIdx++,new java.sql.Timestamp(new java.util.Date().getTime())); // now
ps.setInt(psIdx++,activeUser.userId.intValue());
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_SOURCEID"));
ps.executeUpdate();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
else{
//*** update record ***
sUID = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_UID");
sUDI = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_UDI");
// do not update UDI and link to transaction
String sSql = "UPDATE arch_documents SET arch_document_title = ?, arch_document_description = ?, arch_document_category = ?,"+
" arch_document_author = ?, arch_document_date = ?, arch_document_destination = ?, arch_document_reference = ?,"+
" arch_document_personid = ?, arch_document_storagename = ?,"+
" arch_document_updatetime = ?, arch_document_updateid = ?, arch_document_tran_serverid="+(MedwanQuery.getInstance().getConfigInt("GMAOLocalServerId",-1)>0?"-1":"arch_document_tran_serverid")+
" WHERE arch_document_serverid = ? AND arch_document_objectid = ?";
try{
ps = conn.prepareStatement(sSql);
int psIdx = 1;
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_TITLE"));
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_DESCRIPTION"));
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_CATEGORY"));
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_AUTHOR"));
// date
String sDate = ScreenHelper.stdDateFormat.format(tran.getUpdateTime());
if(sDate.length() > 0){
sDate = ScreenHelper.convertToEUDate(sDate);
ps.setDate(psIdx++,new java.sql.Date(ScreenHelper.parseDate(sDate).getTime()));
}
else{
ps.setNull(psIdx++,Types.NULL);
}
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_DESTINATION"));
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_REFERENCE"));
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_PERSONID"));
ps.setString(psIdx++,tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_STORAGENAME"));
ps.setTimestamp(psIdx++,new java.sql.Timestamp(new java.util.Date().getTime())); // now
ps.setInt(psIdx++,activeUser.userId.intValue());
ps.setString(psIdx++,sUID.split("\\.")[0]);
ps.setString(psIdx++,sUID.split("\\.")[1]);
ps.executeUpdate();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
//archDoc = get(sUDI); // to much load for the purpose..
archDoc.udi = sUDI;
archDoc.setUid(sUID);
return archDoc;
}
public static ArchiveDocument saveLabDocument(boolean isNewTran, TransactionVO tran, int activeUser,String sTitle, String sDescription, String sPersonId){
ArchiveDocument archDoc = new ArchiveDocument();
String sUID = "", sUDI = "";
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = null;
if(isNewTran){
//*** create record ***
String sSql = "INSERT INTO arch_documents (arch_document_serverid, arch_document_objectid, arch_document_udi,"+
" arch_document_title, arch_document_description, arch_document_category, arch_document_author,"+
" arch_document_date, arch_document_destination, arch_document_reference, arch_document_personid,"+
" arch_document_tran_serverid, arch_document_tran_transactionid, arch_document_storagename,"+
" arch_document_updatetime, arch_document_updateid)"+
" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try{
ps = conn.prepareStatement(sSql);
int psIdx = 1;
// IDs
int serverId = Integer.parseInt(MedwanQuery.getInstance().getConfigString("serverId")),
objectId = MedwanQuery.getInstance().getOpenclinicCounter("ARCH_DOCUMENTS");
ps.setInt(psIdx++,serverId);
ps.setInt(psIdx++,objectId);
sUID = serverId+"."+objectId;
// get UDI
sUDI = generateUDI(objectId);
ps.setString(psIdx++,sUDI);
ps.setString(psIdx++,sTitle);
ps.setString(psIdx++,sDescription);
ps.setString(psIdx++,"LABDOCUMENT");
ps.setString(psIdx++,"");
// date
String sDate = ScreenHelper.stdDateFormat.format(new java.util.Date());
if(sDate.length() > 0){
sDate = ScreenHelper.convertToEUDate(sDate);
ps.setDate(psIdx++,new java.sql.Date(ScreenHelper.parseDate(sDate).getTime()));
}
else{
ps.setNull(psIdx++,Types.NULL);
}
ps.setString(psIdx++,"");
ps.setString(psIdx++,tran.getUid()+"."+sDescription);
// personId
if(sPersonId.length() > 0){
ps.setInt(psIdx++,Integer.parseInt(sPersonId));
}
else{
ps.setNull(psIdx++,Types.NULL);
}
// transactions' serverId and transactionId
ps.setInt(psIdx++,tran.getServerId());
ps.setInt(psIdx++,tran.getTransactionId().intValue());
ps.setString(psIdx++,"");
ps.setTimestamp(psIdx++,new java.sql.Timestamp(new java.util.Date().getTime())); // now
ps.setInt(psIdx++,activeUser);
ps.executeUpdate();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
archDoc.udi = sUDI;
archDoc.setUid(sUID);
return archDoc;
}
//--- GET, TRHOUGH TRANSACTIONS ----------------------------------------------------------------
public static ArchiveDocument getThroughTransactions(String sUDI, int personId) throws Exception {
ArchiveDocument archDoc = null;
Vector allArchDocs = MedwanQuery.getInstance().getTransactionsByType(personId,ScreenHelper.ITEM_PREFIX+"TRANSACTION_TYPE_ARCHIVE_DOCUMENT");
Iterator docIter = allArchDocs.iterator();
TransactionVO tran;
while(docIter.hasNext()){
tran = (TransactionVO)docIter.next();
String sTmpUDI = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_UDI");
if(sTmpUDI.equals(sUDI)){
// convert tran to archDoc
archDoc = new ArchiveDocument();
String sServerId = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_SERVERID"),
sObjectId = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_OBJECTID");
archDoc.setUid(sServerId+"."+sObjectId);
archDoc.udi = sTmpUDI;
archDoc.title = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_TITLE");
archDoc.description = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_DESCRIPTION");
archDoc.category = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_CATEGORY");
archDoc.author = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_AUTHOR");
archDoc.date = ScreenHelper.parseDate(ScreenHelper.stdDateFormat.format(tran.getUpdateTime()));
archDoc.destination = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_DESTINATION");
archDoc.reference = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_REFERENCE");
archDoc.personId = Integer.parseInt(tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_PERSONID"));
archDoc.storageName = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_STORAGENAME");
// link with transaction
archDoc.tranServerId = tran.getServerId();
archDoc.tranTranId = tran.getTransactionId().intValue();
break;
}
}
return archDoc;
}
public static ArchiveDocument getByReference(String sReference){
ArchiveDocument archDoc = null;
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String sSql = "SELECT * FROM arch_documents"+
" WHERE ARCH_DOCUMENT_REFERENCE = ?";
try{
ps = conn.prepareStatement(sSql);
ps.setString(1,sReference);
rs = ps.executeQuery();
if(rs.next()){
archDoc = new ArchiveDocument();
archDoc.setUid(rs.getInt("ARCH_DOCUMENT_SERVERID")+"."+rs.getInt("ARCH_DOCUMENT_OBJECTID"));
archDoc.udi = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_UDI"));
archDoc.title = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_TITLE"));
archDoc.description = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_DESCRIPTION"));
archDoc.category = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_CATEGORY"));
archDoc.author = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_AUTHOR"));
archDoc.date = rs.getDate("ARCH_DOCUMENT_DATE");
archDoc.destination = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_DESTINATION"));
archDoc.reference = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_REFERENCE"));
archDoc.personId = rs.getInt("ARCH_DOCUMENT_PERSONID");
archDoc.storageName = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_STORAGENAME"));
archDoc.deleteDate = rs.getDate("ARCH_DOCUMENT_DELETEDATE");
// link with transaction
archDoc.tranServerId = rs.getInt("ARCH_DOCUMENT_TRAN_SERVERID");
archDoc.tranTranId = rs.getInt("ARCH_DOCUMENT_TRAN_TRANSACTIONID");
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
return archDoc;
}
public static Vector<ArchiveDocument> getAllByReference(String sReference){
Vector docs = new Vector();
ArchiveDocument archDoc = null;
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String sSql = "SELECT * FROM arch_documents"+
" WHERE ARCH_DOCUMENT_REFERENCE = ?";
try{
ps = conn.prepareStatement(sSql);
ps.setString(1,sReference);
rs = ps.executeQuery();
while(rs.next()){
archDoc = new ArchiveDocument();
archDoc.setUid(rs.getInt("ARCH_DOCUMENT_SERVERID")+"."+rs.getInt("ARCH_DOCUMENT_OBJECTID"));
archDoc.udi = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_UDI"));
archDoc.title = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_TITLE"));
archDoc.description = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_DESCRIPTION"));
archDoc.category = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_CATEGORY"));
archDoc.author = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_AUTHOR"));
archDoc.date = rs.getDate("ARCH_DOCUMENT_DATE");
archDoc.destination = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_DESTINATION"));
archDoc.reference = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_REFERENCE"));
archDoc.personId = rs.getInt("ARCH_DOCUMENT_PERSONID");
archDoc.storageName = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_STORAGENAME"));
archDoc.deleteDate = rs.getDate("ARCH_DOCUMENT_DELETEDATE");
// link with transaction
archDoc.tranServerId = rs.getInt("ARCH_DOCUMENT_TRAN_SERVERID");
archDoc.tranTranId = rs.getInt("ARCH_DOCUMENT_TRAN_TRANSACTIONID");
docs.add(archDoc);
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
return docs;
}
//--- GET -------------------------------------------------------------------------------------
public static ArchiveDocument get(String sUDI){
return get(sUDI,false);
}
public static ArchiveDocument get(String sUDI, boolean mustHaveStorageName){
ArchiveDocument archDoc = null;
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String sSql = "SELECT * FROM arch_documents"+
" WHERE ARCH_DOCUMENT_UDI = ?";
if(mustHaveStorageName){
sSql+= " AND "+MedwanQuery.getInstance().getConfigString("lengthFunction","len")+"(ARCH_DOCUMENT_STORAGENAME) > 0";
}
try{
ps = conn.prepareStatement(sSql);
ps.setString(1,sUDI);
rs = ps.executeQuery();
if(rs.next()){
archDoc = new ArchiveDocument();
archDoc.setUid(rs.getInt("ARCH_DOCUMENT_SERVERID")+"."+rs.getInt("ARCH_DOCUMENT_OBJECTID"));
archDoc.udi = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_UDI"));
archDoc.title = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_TITLE"));
archDoc.description = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_DESCRIPTION"));
archDoc.category = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_CATEGORY"));
archDoc.author = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_AUTHOR"));
archDoc.date = rs.getDate("ARCH_DOCUMENT_DATE");
archDoc.destination = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_DESTINATION"));
archDoc.reference = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_REFERENCE"));
archDoc.personId = rs.getInt("ARCH_DOCUMENT_PERSONID");
archDoc.storageName = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_STORAGENAME"));
archDoc.deleteDate = rs.getDate("ARCH_DOCUMENT_DELETEDATE");
// link with transaction
archDoc.tranServerId = rs.getInt("ARCH_DOCUMENT_TRAN_SERVERID");
archDoc.tranTranId = rs.getInt("ARCH_DOCUMENT_TRAN_TRANSACTIONID");
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
return archDoc;
}
//--- GET BASIC -------------------------------------------------------------------------------
// for environments without MedwanQuery
public static ArchiveDocument getBasic(String sUDI, Connection conn){
return getBasic(sUDI,false,conn);
}
public static ArchiveDocument getBasic(String sUDI, boolean mustHaveStorageName, Connection conn){
ArchiveDocument archDoc = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sSql = "SELECT * FROM arch_documents"+
" WHERE ARCH_DOCUMENT_UDI = ?";
if(mustHaveStorageName){
sSql+= " AND len(ARCH_DOCUMENT_STORAGENAME) > 0";
}
try{
ps = conn.prepareStatement(sSql);
ps.setString(1,sUDI);
rs = ps.executeQuery();
if(rs.next()){
archDoc = new ArchiveDocument();
archDoc.setUid(rs.getInt("ARCH_DOCUMENT_SERVERID")+"."+rs.getInt("ARCH_DOCUMENT_OBJECTID"));
archDoc.udi = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_UDI"));
archDoc.title = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_TITLE"));
archDoc.description = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_DESCRIPTION"));
archDoc.category = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_CATEGORY"));
archDoc.author = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_AUTHOR"));
archDoc.date = rs.getDate("ARCH_DOCUMENT_DATE");
archDoc.destination = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_DESTINATION"));
archDoc.reference = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_REFERENCE"));
archDoc.personId = rs.getInt("ARCH_DOCUMENT_PERSONID");
archDoc.storageName = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_STORAGENAME"));
archDoc.deleteDate = rs.getDate("ARCH_DOCUMENT_DELETEDATE");
// link with transaction
archDoc.tranServerId = rs.getInt("ARCH_DOCUMENT_TRAN_SERVERID");
archDoc.tranTranId = rs.getInt("ARCH_DOCUMENT_TRAN_TRANSACTIONID");
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
return archDoc;
}
//--- FIND -------------------------------------------------------------------------------------
public static Vector find(int personId, String sFindTitle, String sFindCategory, String sFindBegin, String sFindEnd){
return find(personId,sFindTitle,sFindCategory,sFindBegin,sFindEnd,false,false); // only not-deleted documents
}
public static Vector find(int personId, String sFindTitle, String sFindCategory, String sFindBegin, String sFindEnd,
boolean includeDeletedDocuments, boolean onlyScannedDocuments){
Vector archDocs = new Vector();
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String sSql = "SELECT * FROM arch_documents"+
" WHERE ARCH_DOCUMENT_PERSONID = ?";
if(onlyScannedDocuments){
sSql+= " AND arch_document_storagename IS NOT NULL AND arch_document_storagename <> ''";
}
if(!includeDeletedDocuments){
sSql+= " AND ARCH_DOCUMENT_DELETEDATE IS NULL";
/*
" AND EXISTS("+
" SELECT 1 FROM transactions"+
" WHERE serverid = d.ARCH_DOCUMENT_TRAN_SERVERID"+
" AND transactionid = d.ARCH_DOCUMENT_TRAN_TRANSACTIONID"+
" )";
*/
}
if(sFindTitle.length() > 0){
sSql+= " AND ARCH_DOCUMENT_TITLE LIKE ?";
}
if(sFindCategory.length() > 0){
sSql+= " AND ARCH_DOCUMENT_CATEGORY = ?";
}
// dates
if(sFindBegin.length() > 0 && sFindEnd.length() > 0){
sSql+= " AND ARCH_DOCUMENT_DATE BETWEEN ? AND ?";
}
else if(sFindBegin.length() > 0){
sSql+= " AND ARCH_DOCUMENT_DATE >= ?";
}
else if(sFindEnd.length() > 0){
sSql+= " AND ARCH_DOCUMENT_DATE <= ?";
}
try{
Debug.println(sSql);
ps = conn.prepareStatement(sSql);
int psIdx = 1;
ps.setInt(psIdx++,personId);
if(sFindTitle.length() > 0){
ps.setString(psIdx++,"%"+sFindTitle+"%");
}
if(sFindCategory.length() > 0){
ps.setString(psIdx++,sFindCategory);
}
// dates
if(sFindBegin.length() > 0 && sFindEnd.length() > 0){
ps.setDate(psIdx++,new java.sql.Date(ScreenHelper.parseDate(sFindBegin).getTime()));
ps.setDate(psIdx++,new java.sql.Date(ScreenHelper.parseDate(sFindEnd).getTime()));
}
else if(sFindBegin.length() > 0){
ps.setDate(psIdx++,new java.sql.Date(ScreenHelper.parseDate(sFindBegin).getTime()));
}
else if(sFindEnd.length() > 0){
ps.setDate(psIdx++,new java.sql.Date(ScreenHelper.parseDate(sFindEnd).getTime()));
}
rs = ps.executeQuery();
ArchiveDocument archDoc = null;
while(rs.next()){
archDoc = new ArchiveDocument();
archDoc.setUid(rs.getInt("ARCH_DOCUMENT_SERVERID")+"."+rs.getInt("ARCH_DOCUMENT_OBJECTID"));
archDoc.udi = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_UDI"));
archDoc.title = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_TITLE"));
archDoc.description = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_DESCRIPTION"));
archDoc.category = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_CATEGORY"));
archDoc.author = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_AUTHOR"));
archDoc.date = rs.getDate("ARCH_DOCUMENT_DATE");
archDoc.destination = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_DESTINATION"));
archDoc.reference = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_REFERENCE"));
archDoc.personId = rs.getInt("ARCH_DOCUMENT_PERSONID");
archDoc.storageName = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_STORAGENAME"));
archDoc.deleteDate = rs.getDate("ARCH_DOCUMENT_DELETEDATE");
// link with transaction
archDoc.tranServerId = rs.getInt("ARCH_DOCUMENT_TRAN_SERVERID");
archDoc.tranTranId = rs.getInt("ARCH_DOCUMENT_TRAN_TRANSACTIONID");
archDocs.add(archDoc);
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
return archDocs;
}
//--- GET MOST RECENT DOCUMENTS ---------------------------------------------------------------
// search through transactions
public static Vector getMostRecentDocuments(int maxRecords, int personId, boolean onlyScannedDocuments) throws Exception {
Vector recentArchDocs = new Vector();
Vector allArchDocs = MedwanQuery.getInstance().getTransactionsByType(personId,
ScreenHelper.ITEM_PREFIX+"TRANSACTION_TYPE_ARCHIVE_DOCUMENT");
Iterator docIter = allArchDocs.iterator();
ArchiveDocument archDoc;
TransactionVO tran;
int docCount = 0;
while(docIter.hasNext() && docCount < maxRecords){
tran = (TransactionVO)docIter.next();
// convert tran to archDoc
archDoc = new ArchiveDocument();
String sServerId = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_SERVERID"),
sObjectId = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_OBJECTID");
archDoc.setUid(sServerId+"."+sObjectId);
archDoc.udi = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_UDI");
archDoc.title = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_TITLE");
archDoc.description = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_DESCRIPTION");
archDoc.category = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_CATEGORY");
archDoc.author = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_AUTHOR");
archDoc.date = ScreenHelper.parseDate(ScreenHelper.stdDateFormat.format(tran.getUpdateTime()));
archDoc.destination = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_DESTINATION");
archDoc.reference = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_REFERENCE");
archDoc.personId = Integer.parseInt(tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_PERSONID"));
archDoc.storageName = tran.getItemValue(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_STORAGENAME");
// link with transaction
archDoc.tranServerId = tran.getServerId();
archDoc.tranTranId = tran.getTransactionId().intValue();
if((onlyScannedDocuments && archDoc.storageName.length() > 0) || !onlyScannedDocuments){
recentArchDocs.add(archDoc);
}
}
return recentArchDocs;
}
//--- DELETE ----------------------------------------------------------------------------------
// --> set deletedate, when deleting a transaction
public static void delete(String sUID){
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = null;
String sSql = "UPDATE arch_documents SET ARCH_DOCUMENT_DELETEDATE = ?"+
" WHERE ARCH_DOCUMENT_SERVERID = ? AND ARCH_DOCUMENT_OBJECTID = ?";
try{
ps = conn.prepareStatement(sSql);
ps.setTimestamp(1,new java.sql.Timestamp(new java.util.Date().getTime())); // now
ps.setInt(2,Integer.parseInt(sUID.split("\\.")[0]));
ps.setInt(3,Integer.parseInt(sUID.split("\\.")[1]));
ps.executeUpdate();
Debug.println("--> Archive-document marked as deleted : "+sUID+" (UID)");
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
public static void initializeUDI(String sUDI){
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = null;
String sSql = "UPDATE arch_documents SET ARCH_DOCUMENT_STORAGENAME=''"+
" WHERE ARCH_DOCUMENT_UDI = ?";
try{
ps = conn.prepareStatement(sSql);
ps.setInt(1,Integer.parseInt(sUDI));
ps.executeUpdate();
Debug.println("--> Archive-document marked as initialized : "+sUDI+" (sUDI)");
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
//--- COMPARE TO ------------------------------------------------------------------------------
public int compareTo(Object o) {
int comp;
if(o.getClass().isInstance(this)){
comp = this.udi.compareTo(((ArchiveDocument)o).udi);
}
else {
throw new ClassCastException();
}
return comp;
}
//--- SET STORAGE NAME ------------------------------------------------------------------------
// also update linked transaction
public static void setStorageName(String sUDI, String sStorageName){
setStorageName(sUDI, sStorageName,true);
}
public static void setStorageName(String sUDI, String sStorageName, boolean bUpdateTransaction){
if(Debug.enabled){
Debug.println("\n****************** setStorageName ********************");
Debug.println("sUDI : "+sUDI);
Debug.println("sStorageName : "+sStorageName);
}
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try{
//*** 1 - update archDoc ***
String sSql = "UPDATE arch_documents SET ARCH_DOCUMENT_STORAGENAME = ?"+
" WHERE ARCH_DOCUMENT_UDI = ?";
ps = conn.prepareStatement(sSql);
ps.setString(1,sStorageName);
ps.setString(2,sUDI);
int recsUpdated = ps.executeUpdate();
ps.close();
conn.close();
//If the scanned document is linked to a LAB request, update the corresponding labrequest analyses
sSql = "SELECT ARCH_DOCUMENT_REFERENCE"+
" FROM arch_documents"+
" WHERE ARCH_DOCUMENT_UDI = ? and ARCH_DOCUMENT_CATEGORY='LABDOCUMENT'";
ps = conn.prepareStatement(sSql);
ps.setString(1,sUDI);
rs = ps.executeQuery();
if(rs.next()){
//This document is linked to a LAB request
String sReference = ScreenHelper.checkString(rs.getString("ARCH_DOCUMENT_REFERENCE"));
RequestedLabAnalysis.setScanResultForReference(sReference);
}
rs.close();
ps.close();
conn.close();
if(recsUpdated > 0 && bUpdateTransaction){
Debug.println("--> Storagename set for archive-document with UDI '"+sUDI+"' : "+sStorageName);
//*** 2 - get link with transaction ***
int serverId = -1, tranId = -1;
sSql = "SELECT ARCH_DOCUMENT_TRAN_SERVERID, ARCH_DOCUMENT_TRAN_TRANSACTIONID"+
" FROM arch_documents"+
" WHERE ARCH_DOCUMENT_UDI = ?";
ps = conn.prepareStatement(sSql);
ps.setString(1,sUDI);
rs = ps.executeQuery();
if(rs.next()){
serverId = rs.getInt(1);
tranId = rs.getInt(2);
}
rs.close();
ps.close();
conn.close();
//*** 3 - update linked transaction ***
if(serverId > -1 && tranId > -1){
sSql = "UPDATE items SET value = ?, version = version+1, versionserverid = ?"+
" WHERE serverid = ? AND transactionid = ?"+
" AND type = ?";
ps = conn.prepareStatement(sSql);
ps.setString(1,sStorageName);
ps.setInt(2,serverId); // versionserver
ps.setInt(3,serverId);
ps.setInt(4,tranId);
ps.setString(5,ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_STORAGENAME");
int updatedRecs = ps.executeUpdate();
ps.close();
conn.close();
if(updatedRecs==0){
// insert item when not found during update
sSql = "INSERT INTO Items(itemId,type,"+MedwanQuery.getInstance().getConfigString("valueColumn")+","+
MedwanQuery.getInstance().getConfigString("dateColumn")+","+
"transactionId,serverid,version,versionserverid,valuehash)"+
" VALUES(?,?,?,?,?,?,?,?,?)";
ps = conn.prepareStatement(sSql);
ps.setInt(1,new Integer(MedwanQuery.getInstance().getOpenclinicCounter("ItemID")));
ps.setString(2,ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_STORAGENAME");
ps.setString(3,sStorageName);
ps.setDate(4,new java.sql.Date(new java.util.Date().getTime()));
ps.setInt(5,tranId);
ps.setInt(6,serverId);
ps.setInt(7,1); // version
ps.setInt(8,Integer.parseInt(MedwanQuery.getInstance().getConfigString("serverId"))); // versionserverid
ps.setInt(9,(ScreenHelper.ITEM_PREFIX+"ITEM_TYPE_DOC_STORAGENAME"+sStorageName).hashCode());
ps.execute();
ps.close();
//remove transaction from cache
}
Debug.println("--> Storagename set in linked transaction '"+serverId+"."+tranId+"' to '"+sStorageName+"'");
}
else{
Debug.println("--> WARNING : Storagename NOT set in linked transaction, because no link found for archive-document with UDI '"+sUDI+"'");
}
}
else{
// recsUpdated == 0
Debug.println("--> Storagename NOT SET, because no archive-document found with UDI '"+sUDI+"'.");
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
//--- GET STORAGE NAME ------------------------------------------------------------------------
public static String getStorageName(String sUDI){
if(Debug.enabled){
Debug.println("\n****************** getStorageName ********************");
Debug.println("sUDI : "+sUDI);
}
String sStorageName = "";
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try{
String sSql = "SELECT ARCH_DOCUMENT_STORAGENAME"+
" FROM arch_documents"+
" WHERE ARCH_DOCUMENT_UDI = ?";
ps = conn.prepareStatement(sSql);
ps.setString(1,sUDI);
ps.executeQuery();
rs = ps.executeQuery();
if(rs.next()){
sStorageName = ScreenHelper.checkString(rs.getString(1));
}
Debug.println("--> storagename : "+sStorageName);
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
return sStorageName;
}
//--- GENERATE UDI ----------------------------------------------------------------------------
// checkDigits = 97 - (eerste 9 cijfers MOD 97)
// 000000001/96
// 000000002/95
// 000000003/94 ...
// --> 96 = 97 - (1/97)
// --> 96 = 97 - 1
//
// '000123472/xx'
// --> xx = 97 - (123472%97)
// --> xx = 97 - 88
// --> xx = 09
// --> 000123472/09
//
// '000123480/01'
// --> 1 = 97 - (123480%97)
// --> 1 = 97 - 96
// --> 1 = 1
public static String generateUDI(final int objectId){
String sUDI = Integer.toString(objectId);
int xx = 97 - (objectId%97);
String sXX = Integer.toString(xx);
while(sXX.length()<2) sXX = "0"+sXX;
sUDI+= sXX;
while(sUDI.length()<11) sUDI = "0"+sUDI;
Debug.println("GENERATED UDI from OBJECTID "+objectId+" : "+sUDI);
return sUDI;
}
//--- GET LINKED TRANSACTION ------------------------------------------------------------------
public TransactionVO getLinkedTransaction(){
return MedwanQuery.getInstance().loadTransaction(this.tranServerId,this.tranTranId);
}
}
|
package br.com.lucro.manager.service;
import br.com.lucro.manager.model.FileHeaderCielo;
import br.com.lucro.manager.model.FileOperationResumeOutstandingBalanceCielo;
/**
*
* @author Georjuan Taylor
*
*/
public interface FileOperationResumeOutstandingBalanceCieloService {
/**
* Read line data, format and save data into data base
* @param line
* @return
* @throws Exception
*/
public FileOperationResumeOutstandingBalanceCielo processOperation(String line, FileHeaderCielo fileHeaderCielo) throws Exception;
}
|
package fr.simplon.medecine.model;
public class Creneau {
}
|
package com.gaoshin.onsalelocal.lon.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.gaoshin.onsalelocal.lon.dao.LonDao;
import com.gaoshin.onsalelocal.lon.service.LonService;
@Service("grouponService")
@Transactional(readOnly=true)
public class LonServiceImpl extends ServiceBaseImpl implements LonService {
@Autowired private LonDao grouponDao;
@Override
@Transactional(readOnly=false, rollbackFor=Throwable.class)
public void updateTasks() {
grouponDao.updateTasks();
}
@Override
@Transactional(readOnly=false, rollbackFor=Throwable.class)
public void seedTasks() {
grouponDao.seedTasks();
}
@Override
@Transactional(readOnly=false, rollbackFor=Throwable.class)
public void seedMarkets() throws Exception {
}
@Override
@Transactional(readOnly=false, rollbackFor=Throwable.class)
public void seedMarketTasks() {
grouponDao.seedMarketTasks();
}
}
|
package com.yh;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class DrawTopBase implements Runnable, Callback ,OnTouchListener{
protected SurfaceView mSurfaceView;
protected SurfaceHolder mSurfaceHolder;
protected Context mContext;
protected Rect mSurfaceRect = new Rect(0, 0, 0, 0);
public DrawTopBase() {
setSurfaceView(HolderSurfaceView.getInstance().getSurfaceView());
}
public void setSurfaceView(SurfaceView view) {
mSurfaceView = view;
mContext = mSurfaceView.getContext();
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceRect.set(new Rect(0, 0, mSurfaceView.getWidth(), mSurfaceView
.getHeight()));
set();
}
/**
* ��ݳ��������÷�Χ
*/
public void set() {
setRect(mSurfaceRect);
}
protected Thread mThread = null;
/**
* ��ʼ��Ϊ�˱����ظ���ʼ�������̱߳���
*/
public void begin() {
if (mThread == null) {
mThread = new Thread(this);
mThread.start();
}
}
public void end() {
mStatus = DrawStatus.Ending;
}
/**
* ������
*
* @param canvas
*/
protected void doWork(Canvas canvas) {
}
/**
* ������
*/
protected void endWork() {
}
protected Paint mPaint = new Paint();
/**
* ���
*
* @param canvas
*/
protected void clear(Canvas canvas) {
mPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
canvas.drawPaint(mPaint);
mPaint.setXfermode(new PorterDuffXfermode(Mode.SRC));
}
protected void clear() {
synchronized (mSurfaceHolder) {
Canvas canvas = this.mSurfaceHolder.lockCanvas();
try {
clear(canvas);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (canvas != null)
mSurfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
protected void doChange() {
change();
}
/**
* �仯
*/
protected void change() {
}
protected Rect mRect = new Rect(0, 0, 0, 0);
public void setRect(Rect r) {
mRect.set(r);
}
public Rect getRect() {
return mRect;
}
protected DrawStatus mStatus = DrawStatus.NoWork;
/**
* ����״̬ noWork û�й��� draw ����ѭ���� end ����� destroy �������
*
* @author gary
*
*/
protected enum DrawStatus {
NoWork, Drawing, Ending, Destroyed
};
protected long mBegintime;
@Override
public void run() {
mStatus = DrawStatus.Drawing;
starttime = System.currentTimeMillis();
mBegintime = System.currentTimeMillis();
// ���������
clear();
clear();
while (mStatus == DrawStatus.Drawing) {
synchronized (mSurfaceHolder) {
Canvas canvas = this.mSurfaceHolder.lockCanvas(getRect());
try {
if (canvas != null) {
clear(canvas);
doWork(canvas);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (canvas != null)
mSurfaceHolder.unlockCanvasAndPost(canvas);
}
doChange();
}
calculatePerframe();
}
if (mStatus != DrawStatus.Destroyed)
clear();
mThread = null;
endWork();
}
protected long starttime;
// ÿ֡ʱ�� 60֡���� ��һ�μ���ǰʹ�� ����
private float perframe = 16;
private int count = 0;
// ÿ���ʱ�����һ��֡ʱ��
private int mRefreshSpeed = 12;
// �趨Ҫ��ʱ��ÿ֡ 24֡ÿ��
private float mFPS = 1000 / 12;
private float sleep = mFPS;
// ����ˢ��Ƶ��
public void setFPS(int fps) {
mFPS = 1000 / fps;
}
/**
* �ȴ�ʱ��
*/
protected void calculatePerframe() {
count++;
if (count == mRefreshSpeed) // ����ÿ֡����ή����ϷЧ�ʡ�20��50���
{
long timepass = System.currentTimeMillis();
long time = timepass - starttime;
perframe = time / mRefreshSpeed;// ÿ֡ʱ��
sleep = perframe > mFPS ? mFPS - (perframe - mFPS) / mRefreshSpeed
: mFPS;
starttime = timepass;
count = 0;
}
try {
Thread.sleep((long) (sleep));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
mSurfaceRect.set(new Rect(0, 0, width, height));
set();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mStatus = DrawStatus.Destroyed;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
|
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Graph{
public int V;
public int[] color;
public int[] d ;
public int[] pi ;
Queue<Integer> queue = new LinkedList<>();
public LinkedList<Integer> adj[];
Graph(int v){
V = v;
d = new int[v + 1];
pi = new int[v + 1];
color = new int[v + 1];
adj = new LinkedList[v + 1];
for (int i = 0; i < v + 1; i++) {
adj[i] = new LinkedList();
}
}
public void addEdge(int v, int w) {
adj[v].add(w);
}
public void Distance() {
for (int i = 1; i < V + 1; i++) {
d[i] = Integer.MAX_VALUE;
}
color[1] = 1;
d[1] = 0;
pi[1] = -10;
queue.add(1);
System.out.println("Queue.size(): " + queue.size());
while (queue.size() != 0) {
int k = queue.poll();
System.out.println("K: " + k);
Iterator<Integer> iter = adj[k].listIterator();
while (iter.hasNext()) {
int nn = iter.next();
if (color[nn] == 0) {
color[nn] = 1;
d[nn] = d[k] + 1;
queue.add(nn);
}
}
color[k] = 2;
}
}
public boolean isCycle() {
int[] indegree = new int[V + 1];
for (int i = 1; i < V + 1; i++) {
Iterator<Integer> iter = adj[i].listIterator();
while (iter.hasNext()) {
int nn = iter.next();
indegree[nn] += 1;
}
}
System.out.println("INDEGREE: " + Arrays.toString(indegree));
Queue<Integer> qc = new LinkedList<>();
for (int i = 1; i < V + 1; i++) {
if (indegree[i] == 0) {
qc.add(i);
}
}
System.out.println(qc.peek());
int countVisitedNodes = 0;
while (qc.size() != 0) {
int w = qc.poll();
countVisitedNodes += 1;
Iterator<Integer> iter = adj[w].listIterator();
while (iter.hasNext()) {
int jk = iter.next();
System.out.println("JK: " + jk);
indegree[jk] -= 1;
if (indegree[jk] == 0) {
qc.add(jk);
}
}
System.out.println(qc.peek());
}
System.out.println("countVisitedNodes: " + countVisitedNodes);
if (countVisitedNodes != V) {
return true;
}
else {
return false;
}}
public boolean isBi() {
int[] detect = new int[V + 1];
int[] c1 = new int[V + 1];
detect[1] = 1;
Queue<Integer> qb = new LinkedList<>();
qb.add(1);
while (qb.size() != 0) {
int k = qb.poll();
c1[k] = 1;
Iterator<Integer> iter = adj[k].listIterator();
while (iter.hasNext()) {
int jk = iter.next();
if (detect[k] == 1) {
if (detect[jk] != 1){detect[jk] = 2;}
else {return false;}
}
else {
if (detect[jk] != 2){detect[jk] = 1;}
else {return false;}
}
if (c1[jk] == 0) {
qb.add(jk);
}
}
}
return true;
}
}
public class isBi {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//int a = scan.nextInt();
// Graph g = new Graph(13);
// g.addEdge(1, 2);g.addEdge(1, 3);g.addEdge(1, 4);
// g.addEdge(2, 3);g.addEdge(2, 4); g.addEdge(2, 1); g.addEdge(2, 5 );
// g.addEdge(3, 1);g.addEdge(3, 2);g.addEdge(3, 4);g.addEdge(3, 6);g.addEdge(3, 7);
// g.addEdge(4, 1);g.addEdge(4, 2);g.addEdge(4, 5);g.addEdge(4, 9);g.addEdge(4, 6);g.addEdge(4, 8);g.addEdge(4, 3);g.addEdge(4, 11);
// g.addEdge(5, 2);g.addEdge(5, 4);g.addEdge(5, 9);g.addEdge(5, 10);
// g.addEdge(6, 7);g.addEdge(6, 4);g.addEdge(6, 3);
// g.addEdge(7, 12);g.addEdge(7, 8);g.addEdge(7, 6);g.addEdge(7, 11);
// g.addEdge(8, 12);g.addEdge(8, 13);g.addEdge(8, 4);g.addEdge(8, 7);g.addEdge(8, 10);
// g.addEdge(9, 4);g.addEdge(9, 5);
// g.addEdge(10, 5);g.addEdge(10, 8);
// g.addEdge(11, 4);g.addEdge(11, 7);
// g.addEdge(12, 7);g.addEdge(12, 8);g.addEdge(12, 13);
// g.addEdge(13, 12);g.addEdge(13, 8);
Graph g = new Graph(5);
//g.addEdge(, 1);
// g.addEdge(1, 2);
// g.addEdge(2, 3);
// g.addEdge(3, 4);
// g.addEdge(4, 5);
// g.addEdge(1, 4);g.addEdge(1, 2);
// g.addEdge(2, 1);g.addEdge(2, 3);
// g.addEdge(3, 2);g.addEdge(3, 4);
// g.addEdge(4, 1);g.addEdge(4, 3);
g.addEdge(1, 2);g.addEdge(2, 3);
g.addEdge(3, 4);g.addEdge(4, 5);g.addEdge(5, 1);
//g.Distance();
//System.out.println(Arrays.toString(g.d));
//System.out.println(Arrays.toString(g.color));
if (g.isBi() == true) {
System.out.println("HAS CYCLE");
}
else {
System.out.println("NO CYCLE");
}
}
}
|
package com.mastek.farmToShop.entities;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.ws.rs.FormParam;
import javax.xml.bind.annotation.XmlTransient;
@XmlRootElement
@Entity
@Table
public class Basket {
public Basket() {
}
@FormParam("basketID")
int basketID;
@FormParam("basketValue")
double basketValue;
@Id//Marking the property as primary Key for the table
@GeneratedValue(strategy=GenerationType.AUTO)
public int getBasketID() {
return basketID;
}
public void setBasketID(int basketID) {
this.basketID = basketID;
}
public double getBasketValue() {
return basketValue;
}
public void setBasketValue(double basketValue) {
this.basketValue = basketValue;
}
/////////////////////////////////////////Foreign Keys/////////////////////////////////////////
Customer linkedCustomer;
@ManyToOne
@JoinColumn(name="fk_CustomerID")
@XmlTransient
public Customer getLinkedCustomer() {
return linkedCustomer;
}
public void setLinkedCustomer(Customer linkedCustomer) {
this.linkedCustomer = linkedCustomer;
}
Transaction linkedTransactions;
@OneToOne(mappedBy="linkedBasket")
@XmlTransient
public Transaction getLinkedTransactions() {
return linkedTransactions;
}
public void setLinkedTransactions(Transaction linkedTransactions) {
this.linkedTransactions = linkedTransactions;
}
Set<AssignedProduct> basketProducts = new HashSet<AssignedProduct>();
@OneToMany (mappedBy="currentBasket", cascade=CascadeType.ALL)
@XmlTransient
@org.springframework.data.annotation.Transient
public Set<AssignedProduct> getBasketProducts() {
return basketProducts;
}
public void setBasketProducts(Set<AssignedProduct> basketProducts) {
this.basketProducts = basketProducts;
}
@Override
public String toString() {
return "Baskets [basketID=" + basketID + ", basketValue=" + basketValue + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + basketID;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Basket other = (Basket) obj;
if (basketID != other.basketID)
return false;
return true;
}
}
|
package com.framgia.fsalon.utils.formatter;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import java.util.List;
/**
* Created by THM on 8/24/2017.
*/
public class ColNameIAxisValueFormatter implements IAxisValueFormatter {
private final List<String> mLabels;
public ColNameIAxisValueFormatter(List<String> labels) {
mLabels = labels;
}
@Override
public String getFormattedValue(float value, AxisBase axis) {
return mLabels.get((int) value);
}
}
|
package org.huangfugui.ibatis.mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
/**
* Created by huangfugui on 2017/7/22.
*/
@Repository
public interface LabelRecordMapper {
/**
* 用户打标签后记录用户记录
* 暂时有无自定义输入先分开,打第一轮
* @param userId
* @param picId
* @param labelId
* @param count
* @return
*/
int insertRecord(@Param("userId") int userId,
@Param("picId") int picId,
@Param("labelId") int labelId,
@Param("count") int count);
}
|
package me.d2o.statemachine.aspects;
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import me.d2o.statemachine.annotations.EnterMachineState;
import me.d2o.statemachine.annotations.ExitMachineState;
import me.d2o.statemachine.core.MachineEvent;
@Component
@Aspect
public class MachineStateAspect {
@Around(value = "@annotation(me.d2o.statemachine.annotations.EnterMachineState)")
public Object enterMachineState(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
EnterMachineState myAnnotation = method.getAnnotation(EnterMachineState.class);
MachineEvent event = (MachineEvent) joinPoint.getArgs()[0];
if (!event.isTerminated() && event.getEnterState().equals(myAnnotation.value())){
return joinPoint.proceed();
} else {
return null;
}
}
@Around(value = "@annotation(me.d2o.statemachine.annotations.ExitMachineState)")
public Object exitMachineState(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
ExitMachineState myAnnotation = method.getAnnotation(ExitMachineState.class);
MachineEvent event = (MachineEvent) joinPoint.getArgs()[0];
if (event.getExitState().equals(myAnnotation.value())){
return joinPoint.proceed();
} else {
return null;
}
}
}
|
package com.henry.sendmail;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.mail.internet.MimeMessage;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineFactoryBean;
public class SendMailController {
private static Logger logger = LoggerFactory.getLogger(SendMailController.class);
/**
* 注意:VelocityEngine必须先这样定义,再注入
*/
private static VelocityEngine velocityEngine;
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring/sendmail.xml");
logger.info("初始化spring容器:{}",ac);
JavaMailSenderImpl sender = ac.getBean("mailSender",JavaMailSenderImpl.class);
/**
* 简单发送
*/
// SimpleMailMessage msg = ac.getBean("templateMessage",SimpleMailMessage.class);
// msg.setSubject("java发送测试");//主题
// msg.setText("---邮件内容---");
// sender.send(msg);
/**
* 复杂发送:附件(Attachments)
*/
MimeMessage message = sender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo("-----@qq.com");
helper.setFrom("---------@163.com");
helper.setText("<html><body><h2>sdfadfas<h2></body></html>",true);
// let's attach the infamous windows Sample file (this time copied to c:/)
//附件
FileSystemResource file = new FileSystemResource(new File("D:/猎豹截图.jpg"));
helper.addAttachment("CoolImage.jpg", file);
sender.send(message);
} catch (Exception e) {
e.printStackTrace();
}
/**
* 使用模版引擎:freemarker,velocity
*/
try {
// VelocityEngineFactoryBean velovity = ac.getBean("velocityEngine",VelocityEngineFactoryBean.class);
// VelocityEngineFactory velocityEngineFactory = new VelocityEngineFactory();
// VelocityEngine createVelocityEngine = velocityEngineFactory.createVelocityEngine();
MimeMessage message2 = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message2, true);
helper.setTo("-------@qq.com");
helper.setFrom("----------@163.com");
User user = new User();
user.setUserName("henry.赵");
user.setEmailAddress("----------@163.com");
Map model = new HashMap();
model.put("user", user);
// String text = VelocityEngineUtils.mergeTemplate(velovity, "htmlTep.vm", "UTF-8", model);
String text = org.springframework.ui.velocity.VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "com/henry/sendmail/htmlTep.vm","UTF-8",model);
helper.setText(text,true);
sender.send(message2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package behavioral.state;
/**
* @author Renat Kaitmazov
*/
public final class HighSpeedState implements State {
/*--------------------------------------------------------*/
/* Instance variables
/*--------------------------------------------------------*/
private final CeilingFanPullChain pullChain;
/*--------------------------------------------------------*/
/* Constructors
/*--------------------------------------------------------*/
public HighSpeedState(CeilingFanPullChain pullChain) {
this.pullChain = pullChain;
}
/*--------------------------------------------------------*/
/* State implementation
/*--------------------------------------------------------*/
@Override
public final void pull() {
final State nextState = pullChain.getOffState();
pullChain.setCurrentState(nextState);
System.out.println("Turned off");
}
}
|
package com.college.staff;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StaffController {
@Autowired
StaffService staffService;
// Method to delete staff using staff id.
@DeleteMapping("/deleteStaff/{id}")
public void deleteStaff(@PathVariable("id") int id) {
staffService.deleteStaff(id);
}
// Method to add newly or update on existing staff.
@PutMapping("/updateStaff")
public Staff updateStaff(@RequestBody Staff staff) {
return staffService.updateStaff(staff);
}
// Method to add newly or update on existing staff.
@PostMapping("/addStaff")
public Staff addStaff(@RequestBody Staff staff) {
return staffService.addStaff(staff);
}
// Getting list of staffs by specific department using department id.
@GetMapping("/department/{deptId}/staff")
public List<Staff> getStaffByDepartment(@PathVariable("deptId") int deptid) {
return staffService.getStaffByDepartment(deptid);
}
// Total salary of staff in specific department id given by this method.
@GetMapping("/department/{deptId}/totalSalary")
public Long getSalaryTotalByDepartment(@PathVariable("deptId") int deptId) {
return staffService.getSalaryTotalByDepartment(deptId);
}
// Fetch all students in database.
@GetMapping("/staff")
public List<Staff> getStuedents() {
return staffService.getStaffs();
}
}
|
import java.util.*;
class shaurya
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the string");
String s=sc.nextLine();
s=s.toLowerCase();
System.out.println("enter the number of patterns you wanna find");
int n=sc.nextInt();
String[] starr=new String[n];
int[] count=new int[n];
int x,y,z;
for(x=0;x<n;x++)
{
System.out.println("enter the pattern");
starr[x]=sc.next();
}
for(x=0;x<n;x++)
{
count[x]=0;
}
String s1="";
for(x=0;x<s.length();x++)
{
for(y=x;y<s.length();y++)
{
s1=s1+s.charAt(y);
for(z=0;z<starr.length;z++)
{
if(s1.equalsIgnoreCase(starr[z]))
count[z]++;
}
}
s1="";
}
for(x=0;x<n;x++)
System.out.println(count[x]);
}
}
|
package zad1;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
public class RUSServer {
//initialize socket and input stream
private Socket socket = null;
private Socket socketSend = null;
private ServerSocket server = null;
private DataInputStream inServer = null;
private DataInputStream inputServer = null;
private DataOutputStream outputServer = null;
private Map<String, String> mapWords = Map.of("Pies", "собака", "Dziewczyna", "девушка", "Chlopak", "мальчик", "Warszwa", "Варшава");
public void server(int port) {
try {
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
String line = "";
while (!line.equals("Over")) {
socket = server.accept();
System.out.println("Client accepted");
inServer = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
line = inServer.readUTF();
String[] splitLine = line.split(";");
//serwer staje sie klientem
socketSend = new Socket("localhost", Integer.parseInt(splitLine[1]));
inputServer = new DataInputStream(System.in);
outputServer = new DataOutputStream(socketSend.getOutputStream());
try {
outputServer.writeUTF(mapWords.get(splitLine[0]));
}catch (NullPointerException a){
outputServer.writeUTF("Slowa nie znaleziono w slowniku Rosyjskim");
}
}
System.out.println("Closing connection");
socket.close();
inServer.close();
} catch (IOException i) {
System.out.println(i);
}
}
public static void main(String args[]) {
int RUSServerPort = 5001;
RUSServer rusServer = new RUSServer();
rusServer.server(RUSServerPort);
}
}
|
package com.foodaholic.interfaces;
import com.foodaholic.items.ItemCat;
import java.util.ArrayList;
public interface CategoryListener {
void onStart();
void onEnd(String success, String message, ArrayList<ItemCat> arrayListCat);
}
|
package ProjectStarterCode.model;
public class Board {
/**
* Constitutes the Board made out of tiles
* in which the snake will move
* and which will contain the food
*/
public Tile[][] tiles;
/**
* Constructs a board with tiles with 9 rows and 9 columns
*/
public Board() {
//need to set dimensions of board
tiles = new Tile[9][9];
//creating tiles for each tile
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
tiles[i][j] = new Tile(i, j);
}
}
}
/**
* Prints what each of the tiles in the board contain
*/
public void printBoard() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(tiles[i][j].getInsideTile() + "\t");
}
System.out.println();
}
}
}
|
package notifications;
/**
* Created by David on 10/04/2017.
*/
public interface INotification {
}
|
package server.controllers;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import server.data.Exercise;
import server.data.ExerciseResponse;
import server.services.ExceptionService;
import server.services.GeneratorService;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
@CrossOrigin
@RestController
public class CreateExerciseController {
@Autowired
private GeneratorService generatorService;
@Autowired
private ExceptionService exceptionService;
@GetMapping("/generate")
public String createPrograms(@RequestParam String sourceCode, @RequestParam Integer count) {
Type type = Types.newParameterizedType(ExerciseResponse.class);
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<ExerciseResponse> adapter = moshi.adapter(type);
try {
List<Exercise> exercises = generatorService.generatePrograms(sourceCode, count);
ExerciseResponse res = new ExerciseResponse(exercises, false, "");
return adapter.toJson(res);
} catch (ParseCancellationException e) {
e.printStackTrace();
ExerciseResponse res = new ExerciseResponse(new ArrayList<>(), true, e.getMessage());
return adapter.toJson(res);
} catch (Exception e) {
ExerciseResponse res = new ExerciseResponse(new ArrayList<>(), true, exceptionService.formatException(e));
e.printStackTrace();
return adapter.toJson(res);
}
}
}
|
package com.kecode._1_basic;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
//1、要求用户输入两个数a和b,如果a能被b整除或者a加b大于1000,则输出a;否则输出b。
Scanner scanner = new Scanner(System.in);
System.out.println("请输入a: ");
int a = scanner.nextInt();
System.out.println("请输入b: ");
int b = scanner.nextInt();
if( a%b == 0 || a+b > 1000) {
System.out.println(a);
}else {
System.out.println(b);
}
//2、从键盘接收整数参数.如果该数为1-7,打印对应的星期值,否则打印“非法参数”
int day = scanner.nextInt();
// 结果arr
String[] arr = {"非法参数","星期一","星期二","星期三","星期四","星期五","星期六","星期天"};
// 非法参数转为0
day = day < 1 ? 0 : day > 7 ? 0 : day;
System.out.println(arr[day]);
}
}
|
package at.ac.tuwien.sepm.groupphase.backend.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import java.util.Objects;
@Entity
@Table(name = "tax_rate")
public class TaxRate {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Double percentage;
private Double calculationFactor;
public Double getCalculationFactor() {
return calculationFactor;
}
public void setCalculationFactor(Double calculationFactor) {
this.calculationFactor = calculationFactor;
}
public TaxRate(){}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Double getPercentage() {
return percentage;
}
public void setPercentage(Double percentage) {
this.percentage = percentage;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TaxRate)) {
return false;
}
TaxRate taxRate = (TaxRate) o;
return Objects.equals(id, taxRate.id)
&& Objects.equals(percentage, taxRate.percentage);
}
@Override
public int hashCode() {
return Objects.hash(id, percentage);
}
@Override
public String toString() {
return "TaxRate{"
+
"id=" + id
+
", percentage=" + percentage
+
'}';
}
public static final class TaxRateBuilder {
Long id;
Double percentage;
Double calculationFactor;
TaxRateBuilder(){}
public static TaxRateBuilder getTaxRateBuilder() {
return new TaxRateBuilder();
}
public TaxRateBuilder withId(Long id) {
this.id = id;
return this;
}
public TaxRateBuilder withPercentage(Double percentage) {
this.percentage = percentage;
return this;
}
public TaxRateBuilder withCalculationFactor(Double calculationFactor) {
this.calculationFactor = calculationFactor;
return this;
}
public TaxRate build() {
TaxRate taxRate = new TaxRate();
taxRate.setId(id);
taxRate.setPercentage(percentage);
taxRate.setCalculationFactor(calculationFactor);
return taxRate;
}
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet;
import jakarta.servlet.ServletException;
import org.springframework.util.Assert;
/**
* Exception to be thrown on error conditions that should forward
* to a specific view with a specific model.
*
* <p>Can be thrown at any time during handler processing.
* This includes any template methods of pre-built controllers.
* For example, a form controller might abort to a specific error page
* if certain parameters do not allow to proceed with the normal workflow.
*
* @author Juergen Hoeller
* @since 22.11.2003
*/
@SuppressWarnings("serial")
public class ModelAndViewDefiningException extends ServletException {
private final ModelAndView modelAndView;
/**
* Create new ModelAndViewDefiningException with the given ModelAndView,
* typically representing a specific error page.
* @param modelAndView the ModelAndView with view to forward to and model to expose
*/
public ModelAndViewDefiningException(ModelAndView modelAndView) {
Assert.notNull(modelAndView, "ModelAndView must not be null in ModelAndViewDefiningException");
this.modelAndView = modelAndView;
}
/**
* Return the ModelAndView that this exception contains for forwarding to.
*/
public ModelAndView getModelAndView() {
return this.modelAndView;
}
}
|
package com.zxt.compplatform.formengine.engine;
/**
* 条件工厂
*
* @author 007
*/
public class ConditionFactory {
/**
* 根据不同的字符串返回不同的表单转化器实体
*
* @param str
* @return
*/
public static IPageTransFer creator(String str) {
if (str.equals("listPage")) {
return new ListPageTransFer();
} else if (str.equals("viewPage")) {
return new ViewPageTransFer();
} else if (str.equals("editPage")) {
return new EditPageTransFer();
// gongchang
}
return null;
}
}
|
import java.util.*;
/**
* Created by Adolph on 2017/8/27.
* 班级学生成绩管理一
*/
public class chapter5_18 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("请输入学生的人数:");
int renshu = in.nextInt();
System.out.println("请输入课程的数目");
int courcsNum = in.nextInt();
String[] names = new String[renshu];
String[] courcs = new String[courcsNum];
for(int i = 0;i<courcs.length;i++){
System.out.println("请定义第"+(i+1)+"门课程的名字");
courcs[i] = in.next();
}
}
}
|
package fr.unice.polytech.isa.polyevent.cli.commands;
import fr.unice.polytech.isa.polyevent.cli.framework.Command;
import fr.unice.polytech.isa.polyevent.cli.framework.CommandBuilder;
import fr.unice.polytech.isa.polyevent.cli.framework.Context;
import fr.unice.polytech.isa.polyevent.stubs.DemandePrestataire;
import fr.unice.polytech.isa.polyevent.stubs.TypeSalle;
import fr.unice.polytech.isa.polyevent.stubs.TypeService;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class AddService implements Command
{
private static final Identifier IDENTIFIER = Identifier.ADD_SERVICE;
private final List<DemandePrestataire> demandePrestataires;
private TypeService typeService;
private XMLGregorianCalendar dateDebut;
private XMLGregorianCalendar dateFin;
AddService(List<DemandePrestataire> demandePrestataires)
{
this.demandePrestataires = demandePrestataires;
}
private static String availableRoomType()
{
return Arrays.stream(TypeService.values()).map(Enum::name).collect(Collectors.joining(", "));
}
@Override
public void load(List<String> args) throws Exception
{
if (args.size() < 3)
{
String message = String.format("%s expects 3 arguments: %s TYPE_ROOM START_DATE END_DATE", IDENTIFIER, IDENTIFIER);
throw new IllegalArgumentException(message);
}
String value = args.get(0);
try
{
typeService = TypeService.valueOf(value);
}
catch (IllegalArgumentException e)
{
throw new IllegalArgumentException(String.format("The service type \"%s\" does not exist.%n" +
"Choose one type from the following list: %s.%nType help %s for more details.",
value, availableRoomType(), IDENTIFIER));
}
try
{
DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
dateDebut = datatypeFactory.newXMLGregorianCalendar(args.get(1));
dateFin = datatypeFactory.newXMLGregorianCalendar(args.get(2));
}
catch (IllegalArgumentException e)
{
throw new IllegalArgumentException(String.format("Illegal date format: %s", e.getMessage()));
}
}
@Override
public void execute() throws Exception
{
DemandePrestataire demandePrestataire = new DemandePrestataire();
demandePrestataire.setDateDebut(dateDebut);
demandePrestataire.setDateFin(dateFin);
demandePrestataire.setTypeService(typeService);
demandePrestataires.add(demandePrestataire);
}
public static class Builder implements CommandBuilder<AddService>
{
private final List<DemandePrestataire> demandePrestataires;
public Builder(List<DemandePrestataire> demandePrestataires)
{
this.demandePrestataires = demandePrestataires;
}
@Override
public String identifier()
{
return IDENTIFIER.keyword;
}
@Override
public String describe()
{
return IDENTIFIER.description;
}
@Override
public AddService build(Context context)
{
return new AddService(demandePrestataires);
}
}
}
|
/*
* 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 com.ag.beanI;
import com.ag.model.Location;
import com.ag.model.Venue;
import com.xag.util.NoMatchFoundException;
import java.util.List;
import javax.ejb.Local;
/**
*
* @author agunga
*/
@Local
public interface LocationBeanI {
/**
* @param o is the object to be updated
* @return the added Location
*/
Location add(Location o);
/**
*
* @param o is the object to be updated
* @return the updated Location
*/
Location update(Location o);
/**
*
* @param id is the primary key
* @param o is the object to be updated
* @return the updated Location
*/
// Location update(long id, Location o);
/**
*
* @author agunga
* @return a List of Shipments
*/
List<Location> findAll();
/**
*
* @author agunga
* @param id is the primaryId
* @return a Location object
* @throws com.xag.util.NoMatchFoundException
*/
Location findById(long id) throws NoMatchFoundException;
/**
*
* @author agunga
* @param o is the primaryId
* @return true if the deletion was successful
*/
boolean delete(Location o);
/**
*
* @author agunga
* @param id is the primaryId
* @return the number of deleted records
*/
int delete(long id);
}
|
package co.sblock.events.listeners.player;
import java.util.concurrent.ThreadLocalRandom;
import co.sblock.Sblock;
import co.sblock.chat.Language;
import co.sblock.events.Events;
import co.sblock.events.listeners.SblockListener;
import co.sblock.micromodules.FreeCart;
import co.sblock.micromodules.Godule;
import co.sblock.users.UserAspect;
import co.sblock.utilities.Experience;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.scheduler.BukkitRunnable;
/**
* Listener for PlayerDeathEvents.
*
* @author Jikoo
*/
public class DeathListener extends SblockListener {
private final Events events;
private final FreeCart carts;
private final Godule godule;
private final Language lang;
private final ItemStack facts;
private final String[] messages;
public DeathListener(Sblock plugin) {
super(plugin);
this.events = plugin.getModule(Events.class);
this.carts = plugin.getModule(FreeCart.class);
this.godule = plugin.getModule(Godule.class);
this.lang = plugin.getModule(Language.class);
this.messages = lang.getValue("events.death.random").split("\n");
this.facts = new ItemStack(Material.WRITTEN_BOOK);
BookMeta meta = (BookMeta) facts.getItemMeta();
meta.setTitle("Wither Facts");
meta.setAuthor(Language.getColor("rank.denizen") + "Pete");
meta.addPage("Withers are awesome.");
this.facts.setItemMeta(meta);
}
/**
* EventHandler for PlayerDeathEvents.
*
* @param event the PlayerDeathEvent
*/
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
final Player player = event.getEntity();
// Remove free minecart if riding one
this.carts.remove(player);
Location location = player.getLocation();
String randomMessage = messages[ThreadLocalRandom.current().nextInt(messages.length)];
String locString = this.lang.getValue("events.death.message")
.replace("{X}", String.valueOf(location.getBlockX()))
.replace("{Y}", String.valueOf(location.getBlockY()))
.replace("{Z}", String.valueOf(location.getBlockZ()));
player.sendMessage(Language.getColor("bad") + locString.replaceAll("\\{WORLD\\}\\s?", "").replace("{OPTION}", randomMessage));
locString = locString.replace("{WORLD}", location.getWorld().getName()).replaceAll("\\{OPTION\\}\\s?", "");
EntityDamageEvent lastDamage = player.getLastDamageCause();
if (lastDamage != null && (lastDamage.getCause() == DamageCause.WITHER
|| (lastDamage instanceof EntityDamageByEntityEvent
&& ((EntityDamageByEntityEvent) lastDamage).getDamager().getType() == EntityType.WITHER))) {
new BukkitRunnable() {
@Override
public void run() {
if (player != null) {
player.getInventory().addItem(facts);
}
}
}.runTask(getPlugin());
}
// TODO post deaths (sans coordinates) to global chat
if (this.events.getPVPTasks().containsKey(player.getUniqueId())) {
event.setDroppedExp(Experience.getExp(player));
int dropped = Experience.getExp(player) / 10;
if (dropped > 30) {
dropped = 30;
}
event.setDroppedExp(dropped);
Experience.changeExp(player, -dropped);
event.setKeepLevel(true);
event.setKeepInventory(true);
this.events.getPVPTasks().remove(player.getUniqueId()).cancel();
Player killer = player.getKiller();
if (killer == null) {
return;
}
Bukkit.getConsoleSender().sendMessage(String.format("%s died to %s. %s",
player.getName(), killer.getName(), locString));
if (godule.isEnabled(UserAspect.BREATH)) {
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short) 3);
SkullMeta meta = (SkullMeta) skull.getItemMeta();
meta.setOwner(player.getName());
skull.setItemMeta(meta);
player.getWorld().dropItem(player.getLocation(), skull);
}
} else {
Bukkit.getConsoleSender().sendMessage(String.format("%s died to %s. %s",
player.getName(), lastDamage != null ? lastDamage.getCause().name() : "null", locString));
}
}
}
|
package name.arbitrary.y2014.qualification;
import name.arbitrary.CodeJamBase;
public class C_MinesweeperMaster extends CodeJamBase {
public C_MinesweeperMaster(String fileName) {
super(fileName);
}
public static void main(String[] args) {
new C_MinesweeperMaster(args[0]).run();
}
class ImpossibleException extends Exception {
}
@Override
protected String runCase() {
String[] parts = getLine().split(" ");
int r = Integer.parseInt(parts[0]);
int c = Integer.parseInt(parts[1]);
int m = Integer.parseInt(parts[2]);
// At least 4 columns, 3 rows:
//
// ***********
// *********..
// *********..
//
// ***********
// ********...
// ********...
//
// *********..
// ********...
// ********...
//
// ********...
// ********...
// ********...
//
// *********..
// *******....
// *******....
//
// ********...
// *******....
// *******....
//
// ********...
// ******.....
// ******.....
// etc.
//
// i.e., 8 or more with >= 3 rows and sufficiently (?) wide is soluble.
// 2 columns have to be even number.
// 1 column is obvious (?)
boolean transpose = r > c;
if (transpose) {
int tmp = r;
r = c;
c = tmp;
}
char[][] map = new char[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
map[i][j] = '*';
}
}
int toClear = r * c - m;
try {
switch (r) {
case 1:
solve1(map, toClear);
break;
case 2:
solve2(map, toClear);
break;
default:
solveN(map, toClear);
break;
}
// TODO! Actually carve out the appropriate number, throwing exception that we should catch if you can't.
} catch (ImpossibleException e) {
return "\nImpossible";
}
// Start point!
map[0][0] = 'c';
if (transpose) {
return printTransposed(map);
} else {
return printNormal(map);
}
}
private void solve1(char[][] map, int toClear) throws ImpossibleException {
if (toClear <= 0) {
throw new ImpossibleException();
}
for (int i = 0; i < toClear; i++) {
map[0][i] = '.';
}
}
private void solve2(char[][] map, int toClear) throws ImpossibleException {
if (toClear <= 0 || toClear == 2) {
throw new ImpossibleException();
}
if (toClear == 1) {
return;
}
if (toClear % 2 != 0) {
throw new ImpossibleException();
}
for (int i = 0; i < toClear/2; i++) {
map[0][i] = '.';
map[1][i] = '.';
}
}
private void solveN(char[][] map, int toClear) throws ImpossibleException {
if (toClear <= 0) {
throw new ImpossibleException();
}
if (toClear == 1) {
return;
}
int c = map[0].length;
int fullRowsCleared = toClear / c;
if (fullRowsCleared >= 3) {
solveLotsCleared(map, fullRowsCleared, toClear - fullRowsCleared * c);
} else {
solveFiddlyCase(map, toClear);
}
}
private void solveLotsCleared(char[][] map, int rows, int cols) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < map[i].length; ++j) {
map[i][j] = '.';
}
}
for (int i = 0; i < cols; ++i) {
map[rows][i] = '.';
}
// Special case
if (cols == 1) {
map[rows][1] = '.';
map[rows - 1][map[rows - 1].length - 1] = '*';
}
}
private void solveFiddlyCase(char[][] map, int toClear) throws ImpossibleException {
if (toClear < 4 || toClear == 5 || toClear == 7) {
throw new ImpossibleException();
}
map[0][0] = map[0][1] = map[1][0] = map[1][1] = '.';
if (toClear == 4) {
return;
}
map[0][2] = map[1][2] = '.';
if (toClear == 6) {
return;
}
map[2][0] = map[2][1] = '.';
toClear -= 8;
int idx = 2;
while (toClear >= 3) {
map[0][idx+1] = '.';
map[1][idx+1] = '.';
map[2][idx] = '.';
idx++;
toClear -= 3;
}
switch (toClear) {
case 2:
map[0][idx+1] = '.';
map[1][idx+1] = '.';
break;
case 1:
map[2][idx] = '.';
break;
}
}
private String printNormal(char[][] map) {
StringBuilder sb = new StringBuilder();
int r = map.length;
int c = map[0].length;
for (int i = 0; i < r; i++) {
sb.append('\n');
for (int j = 0; j < c; j++) {
sb.append(map[i][j]);
}
}
return sb.toString();
}
private String printTransposed(char[][] map) {
StringBuilder sb = new StringBuilder();
int r = map.length;
int c = map[0].length;
for (int i = 0; i < c; i++) {
sb.append('\n');
for (int j = 0; j < r; j++) {
sb.append(map[j][i]);
}
}
return sb.toString();
}
}
|
package com.openfarmanager.android.dialogs;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.openfarmanager.android.App;
import com.openfarmanager.android.R;
import com.openfarmanager.android.fragments.MainPanel;
import com.openfarmanager.android.model.FileActionEnum;
/**
* Context menu action list dialog.
*
* author: Vlad Namashko
*/
public class FileActionDialog extends Dialog {
private FileActionEnum[] mActions;
private String[] mActionNames;
private Handler mHandler;
public FileActionDialog(Context context, FileActionEnum[] actions, Handler handler) {
super(context, R.style.Action_Dialog);
mActions = actions;
mActionNames = FileActionEnum.names(actions);
mHandler = handler;
}
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
View view = View.inflate(App.sInstance.getApplicationContext(), R.layout.dialog_file_action_menu, null);
final ListView actionsList = (ListView) view.findViewById(R.id.action_list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
App.sInstance.getApplicationContext(), android.R.layout.simple_list_item_1,
android.R.id.text1, mActionNames) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View item = super.getView(position, convertView, parent);
item.setMinimumWidth(actionsList.getWidth());
((TextView) item.findViewById(android.R.id.text1)).setTextColor(item.getResources().getColor(R.color.white));
return item;
}
};
actionsList.setAdapter(adapter);
actionsList.setOnItemClickListener((adapterView, view1, i, l) -> {
dismiss();
mHandler.sendMessage(Message.obtain(mHandler, MainPanel.SELECT_ACTION, mActions[i]));
});
setContentView(view);
}
}
|
package kuntosali.test;
// Generated by ComTest BEGIN
import static org.junit.Assert.*;
import org.junit.*;
import kuntosali.*;
// Generated by ComTest END
/**
* Test class made by ComTest
* @version 2020.07.29 15:57:33 // Generated by ComTest
*
*/
@SuppressWarnings({ "all" })
public class AsiakasTest {
// Generated by ComTest BEGIN
/** testGetNimi70 */
@Test
public void testGetNimi70() { // Asiakas: 70
Asiakas asiakas = new Asiakas();
asiakas.taytaAsiakas();
{ String _l_=asiakas.getNimi(),_r_="Ismo Laitela .*"; if ( !_l_.matches(_r_) ) fail("From: Asiakas line: 73" + " does not match: ["+ _l_ + "] != [" + _r_ + "]");};
} // Generated by ComTest END
// Generated by ComTest BEGIN
/** testRekisteroi127 */
@Test
public void testRekisteroi127() { // Asiakas: 127
Asiakas testi1 = new Asiakas();
assertEquals("From: Asiakas line: 129", 0, testi1.getTunnusNro());
testi1.rekisteroi();
Asiakas testi2 = new Asiakas();
testi2.rekisteroi();
int n1 = testi1.getTunnusNro();
int n2 = testi2.getTunnusNro();
assertEquals("From: Asiakas line: 135", n2-1, n1);
} // Generated by ComTest END
// Generated by ComTest BEGIN
/** testToString158 */
@Test
public void testToString158() { // Asiakas: 158
Asiakas asiakas = new Asiakas();
asiakas.parse(" 3 | Ankka Aku | 030201-111C");
assertEquals("From: Asiakas line: 161", true, asiakas.toString().startsWith("3|Ankka Aku|030201-111C|")); // on enemmäkin kuin 3 kenttää, siksi loppu |
} // Generated by ComTest END
// Generated by ComTest BEGIN
/** testParse179 */
@Test
public void testParse179() { // Asiakas: 179
Asiakas asiakas = new Asiakas();
asiakas.parse(" 3 | Ankka Aku | 030201-111C");
assertEquals("From: Asiakas line: 182", 3, asiakas.getTunnusNro());
assertEquals("From: Asiakas line: 183", true, asiakas.toString().startsWith("3|Ankka Aku|030201-111C|")); // on enemmäkin kuin 3 kenttää, siksi loppu |
asiakas.rekisteroi();
int n = asiakas.getTunnusNro();
asiakas.parse(""+(n+20)); // Otetaan merkkijonosta vain tunnusnumero
asiakas.rekisteroi(); // ja tarkistetaan että seuraavalla kertaa tulee yhtä isompi
assertEquals("From: Asiakas line: 189", n+20+1, asiakas.getTunnusNro());
} // Generated by ComTest END
// Generated by ComTest BEGIN
/**
* testClone210
* @throws CloneNotSupportedException when error
*/
@Test
public void testClone210() throws CloneNotSupportedException { // Asiakas: 210
Asiakas asiakas = new Asiakas();
asiakas.parse(" 3 | Ankka Aku | 123");
Asiakas kopio = asiakas.clone();
assertEquals("From: Asiakas line: 215", asiakas.toString(), kopio.toString());
asiakas.parse(" 4 | Ankka Tupu | 123");
assertEquals("From: Asiakas line: 217", false, kopio.toString().equals(asiakas.toString()));
} // Generated by ComTest END
// Generated by ComTest BEGIN
/** testAseta410 */
@Test
public void testAseta410() { // Asiakas: 410
Asiakas jasen = new Asiakas();
assertEquals("From: Asiakas line: 412", null, jasen.aseta(1,"Ankka Aku"));
assertEquals("From: Asiakas line: 413", null, jasen.aseta(2,"030201-111C"));
assertEquals("From: Asiakas line: 414", null, jasen.aseta(9,"1940"));
} // Generated by ComTest END
}
|
package lesson2;
/**
* Created by Admin on 09.02.2015.
*/
public class test3 {
public static void main(String[] args) {
int x = 157;
if (x % 10 == 7) {
System.out.println("Является");
} else {
System.out.println("Не является");
}
}
}
|
package com.trump.auction.pals.api.model.alipay;
import com.cf.common.utils.ServiceResult;
import lombok.Data;
@Data
public class AlipayPayResponse extends ServiceResult {
private String payBody;
private String outTradeNo;
public AlipayPayResponse(String code) {
super(code);
}
public AlipayPayResponse(String code, String msg) {
super(code, msg);
}
public AlipayPayResponse(String code, String msg, String payBody,String outTradeNo) {
super(code, msg);
this.payBody = payBody;
this.outTradeNo = outTradeNo;
}
}
|
package Demo;
public class Session1_Polymorphism {
public static void main(String[] args) {
// TODO Auto-generated method stub
B obj = new B();
obj.m1();
}
}
class A{
void m1(){
System.out.println("In A-M1");
}
}
class B extends A{
void m1(){
System.out.println("In B-M1");
}
}
class C extends A{
void m1(){
System.out.println("In C-M1");
}
}
|
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations;
import org.giddap.dreamfactory.leetcode.commons.TreeNode;
import org.giddap.dreamfactory.leetcode.onlinejudge.FlattenBinaryTreeToLinkedList;
/**
* Recursive solution.
*
* Follow the pre-order traversal to move the left subtree to right.
*/
public class FlattenBinaryTreeToLinkedListImpl implements FlattenBinaryTreeToLinkedList {
@Override
public void flatten(TreeNode root) {
if (root == null) {
return;
}
TreeNode left = root.left;
TreeNode right = root.right;
if (left != null) {
flatten(left);
TreeNode tail = left;
while (tail != null && tail.right != null) {
tail = tail.right;
}
root.right = left;
tail.right = right;
root.left = null;
}
flatten(right);
}
}
|
package com.willcode4coffee.webservice.implementation;
import org.example.superfoodsservice.SuperFoodsService;
public class SuperFoodsServiceSOAPImpl implements SuperFoodsService {
/**
*
*/
public String getSuperFoodList(String healthQuery) {
if(healthQuery.equalsIgnoreCase("BloodPressure")){
return "GrapeSeed Extract,Hawthorn Extract";
}
else if(healthQuery.equalsIgnoreCase("liverailments")){
return "Milk Thistle,Alpha Lipoic Acid";
}
else if(healthQuery.equalsIgnoreCase("kidneys")) {
return "Aloe Vera Juice, Uva Ursi,Chlorella";
}
else if(healthQuery.equalsIgnoreCase("immunesystem")){
return "Turmeric,Vitamin D3";
}
return "Currently this Info is not available";
}
}
|
package pkgb.util;
public class Helper {
public static String doHelp(){
return "I am modb, doing something with pkg.Helper";
}
}
|
package com.stylefeng.guns.rest.order.util;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @Author: yyc
* @Date: 2019/6/9 21:29
*/
@Slf4j
@Data
@Configuration
@ConfigurationProperties("ftp")
public class Ftputil {
private String hostName = "192.168.5.71";
private Integer port=2100;
private String userName="ftp";
private String password="ftp";
private FTPClient ftpClient = null;
public void init(){
try {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("utf-8");
ftpClient.connect(hostName,port);
ftpClient.login(userName,password);
} catch (Exception e) {
e.printStackTrace();
log.error("ftp初始化失败", e);
}
}
public String getFileStrByAddr(String fileAdddress){
BufferedReader bfr = null;
StringBuffer stringBuffer = new StringBuffer();
init();
try{
bfr = new BufferedReader(new InputStreamReader(ftpClient.retrieveFileStream(fileAdddress)));
String readLine=null;
while (true){
readLine = bfr.readLine();
if (readLine==null){
break;
}
stringBuffer.append(readLine);
}
}catch (Exception e){
e.printStackTrace();
log.error("获取文件信息失败",e);
}finally {
try {
ftpClient.logout();
} catch (IOException e) {
log.error("登出失败",e);
e.printStackTrace();
}
try {
bfr.close();
} catch (IOException e) {
e.printStackTrace();
log.error("关流失败",e);
}
}
return stringBuffer.toString();
}
}
|
package com.wenyuankeji.spring.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.wenyuankeji.spring.model.BaseAdmininfoModel;
import com.wenyuankeji.spring.model.BaseCityModel;
import com.wenyuankeji.spring.model.BaseConfigModel;
import com.wenyuankeji.spring.model.BaseProvinceModel;
import com.wenyuankeji.spring.model.BaseStarinfoModel;
import com.wenyuankeji.spring.model.UserPhotoMappingModel;
import com.wenyuankeji.spring.model.UserProfessionLevelModel;
import com.wenyuankeji.spring.model.UserWalletModel;
import com.wenyuankeji.spring.model.UserinfoModel;
import com.wenyuankeji.spring.model.UsersubinfoModel;
import com.wenyuankeji.spring.model.UsersubsearchModel;
import com.wenyuankeji.spring.service.IBaseCityService;
import com.wenyuankeji.spring.service.IBaseConfigService;
import com.wenyuankeji.spring.service.IBaseProvinceService;
import com.wenyuankeji.spring.service.IBaseStarInfoService;
import com.wenyuankeji.spring.service.IUserPhotoMappingService;
import com.wenyuankeji.spring.service.IUserWalletService;
import com.wenyuankeji.spring.service.IUserinfoService;
import com.wenyuankeji.spring.service.IUsersubinfoService;
import com.wenyuankeji.spring.service.IUtilService;
import com.wenyuankeji.spring.util.BaseException;
import com.wenyuankeji.spring.util.Constant;
import com.wenyuankeji.spring.util.ShunJianMeiUtil;
@Controller
public class UsersubinfoController {
@Autowired
private IUsersubinfoService usersubinfoService;
@Autowired
private IUserinfoService userinfoService;
@Autowired
private IBaseProvinceService baseProvinceService;
@Autowired
private IBaseCityService baseCityService;
@Autowired
private IUserPhotoMappingService userPhotoMappingService;
@Autowired
private IBaseStarInfoService baseStarInfoService;
@Autowired
private IBaseConfigService baseConfigService;
@Autowired
private IUserWalletService userWalletService;
@Autowired
private IUtilService utilService;
/************ 管理端 ************/
@RequestMapping("goUsersubinfoManage")
/**
* 跳转美发店登录
*
* @param request
* @param model
* @return
*/
public String goUsersubinfoManage(HttpServletRequest request, Model model) {
HttpSession session = request.getSession();
BaseAdmininfoModel userinfo = (BaseAdmininfoModel) session.getAttribute("sessionUserinfo");
if(userinfo != null){
return "usersubinfo_manage";
}else{
return "login";
}
}
@RequestMapping("UsersubinfoManage")
/**
* 美发师管理
*
* @param request
* @param model
* @param storeid
* 店铺ID
* @param paystate
* 支付类型
* @param createtime
* 创建时间
* @param page
* 当前页
* @param rows
* 每页显示条数
* @return
*/
public @ResponseBody Map<String, Object> UsersubinfoManage(HttpServletRequest request, Model model, String cityid,
String userid, String tel, String startTime, String endTime, String checkstate, String txtNickname,String page, String rows)
throws BaseException {
// 定义map
Map<String, Object> jsonMap = new HashMap<String, Object>();
// 当前页
int intPage = Integer.parseInt((page == null || page == "0") ? "1" : page);
// 每页显示条数
int intRows = Integer.parseInt((rows == null || rows == "0") ? "10" : rows);
List<UsersubinfoModel> usersubinfoModels = usersubinfoService.searchUserinfo(cityid, userid, tel, startTime, endTime,
checkstate,txtNickname,intPage, intRows);
List<UsersubsearchModel> usersubsearchModels = new ArrayList<UsersubsearchModel>();
for (int i = 0; i < usersubinfoModels.size(); i++) {
UsersubinfoModel usersubinfoModel = usersubinfoModels.get(i);
// 重新定义页面显示的实体
UsersubsearchModel usersubsearchModel = new UsersubsearchModel();
// ID
usersubsearchModel.setUserid(usersubinfoModel.getUserid());
// 手机
usersubsearchModel.setBindphone(usersubinfoModel.getUserinfoModel().getBindphone());
// 昵称
usersubsearchModel.setNickname(usersubinfoModel.getUserinfoModel().getNickname());
// 服务等级
usersubsearchModel.setLevelid(usersubinfoModel.getLevelid());
usersubsearchModel.setLevelname(usersubinfoModel.getUserProfessionLevel().getLevelname());
// 服务星级
usersubsearchModel.setScore((int) usersubinfoModel.getScore());
// 状态
int checkState = usersubinfoModel.getCheckstate();
usersubsearchModel.setCheckstate(checkState);
// 美发师钱包余额
UserWalletModel userWallet = userWalletService.searchUserWallet(usersubinfoModel.getUserid(), 2);
String balance = "0.0";
if(userWallet != null){
balance = String.valueOf(userWallet.getBalance());
}
usersubsearchModel.setBalance(balance);
usersubsearchModel.setCreateData(ShunJianMeiUtil.dateToString(usersubinfoModel.getUserinfoModel().getCreatetime()));
usersubsearchModels.add(usersubsearchModel);
//定义职称等级
List<UserProfessionLevelModel> userProfessionLevelList= usersubinfoService.searchUserProfessionLevel();
model.addAttribute("userProfessionLevelList",userProfessionLevelList);
}
// 存放总记录数,必须的
jsonMap.put("total",
usersubinfoService.searchUserinfoCount(cityid, userid, tel, startTime, endTime, checkstate,txtNickname));
// rows键 存放每页记录 list
jsonMap.put("rows", usersubsearchModels);
return jsonMap;
}
@RequestMapping("/UsersubinfoUpdateState")
/**
* 修改用户状态
* @param model
* @return
*/
public @ResponseBody Map<String, Object> UsersubinfoUpdateState(int userid, int checkstate,
Model model, HttpSession session,HttpServletRequest request) {
Map<String, Object> editInfoMap = new HashMap<String, Object>();
// 构造实体
UsersubinfoModel usersubinfoModel = new UsersubinfoModel();
usersubinfoModel.setUserid(userid);
usersubinfoModel.setCheckstate(checkstate);
try {
if (usersubinfoService.updateUsersubinfo(usersubinfoModel, 2)) {
editInfoMap.put("editInfo", true);
editInfoMap.put("message", "审核状态修改成功!");
} else {
editInfoMap.put("editInfo", false);
editInfoMap.put("message", "审核状态修改失败!");
}
} catch (Exception e) {
editInfoMap.put("editInfo", false);
editInfoMap.put("message", "审核状态修改失败!");
// 保存异常信息
utilService.addBaseException(request.getRequestURI(), "", e.getMessage());
}
return editInfoMap;
}
@RequestMapping("goDetailUserSubInfo")
/**
* 跳转美发师详情
* @param request
* @param model
* @return
*/
public String goDetailUserSubInfo(int userId,HttpServletRequest request, Model model) {
model.addAttribute("userId", userId);
try {
//查询定级
List<UserProfessionLevelModel> UserProfessionLevelList = usersubinfoService.searchUserProfessionLevel();
model.addAttribute("UserProfessionLevelList", UserProfessionLevelList);
UsersubinfoModel o = usersubinfoService.searchUserSubInfoByUserId(userId);
//查询美发师等级
model.addAttribute("levelid", o.getLevelid());
//查询美发师状态
model.addAttribute("checkstate", o.getCheckstate());
//美发师分成
model.addAttribute("allocation", o.getAllocation());
model.addAttribute("userId", userId);
} catch (Exception e) {
// 保存异常信息
utilService.addBaseException(request.getRequestURI(), "", e.getMessage());
}
return "usersubinfo_detail";
}
@RequestMapping("/addLevelAndCheckstate")
/**
* 根据省份ID查询城市
* @param model
* @return
*/
public @ResponseBody Map<String, Object> addLevelAndCheckstate(int userid,int levelid,int checkstate,
String allocation,int isType,Model model, HttpServletRequest request){
Map<String, Object> outMap = new HashMap<String, Object>();
try {
UsersubinfoModel o = usersubinfoService.searchUserSubInfoByUserId(userid);
//职称等级
o.setLevelid(levelid);
//状态
o.setCheckstate(checkstate);
//分成
if (isType == 0) {//输入框的分成
o.setAllocation(allocation);
}else{//默认配置表中的美发师分成
BaseConfigModel baseConfigModel = usersubinfoService.searchBaseConfigByCode(Constant.CONFIGCODE_14);
if (baseConfigModel != null) {
o.setAllocation(baseConfigModel.getConfigvalue());
}else{
o.setAllocation("0");
}
}
try {
if (usersubinfoService.updateUsersubinfo(o, 0)) {
outMap.put("info", true);
}else {
outMap.put("info", false);
outMap.put("msg", "设置失败!");
}
} catch (Exception e) {
outMap.put("info", false);
outMap.put("msg", "设置失败!");
// 保存异常信息
utilService.addBaseException(request.getRequestURI(), "", e.getMessage());
}
} catch (Exception e) {
// TODO: handle exception
}
return outMap;
}
@RequestMapping("goUsersubinfo_verification")
/**
* 跳转美发师审核信息
* @param request
* @param model
* @return
*/
public String goUsersubinfo_verification(int userId,HttpServletRequest request, Model model) {
// HttpSession session = request.getSession();
// String userId = session.getAttribute("userId").toString();
try {
UserinfoModel userInfoModel = userinfoService.searchUserinfoById(userId);
UsersubinfoModel userSubInfoModel = usersubinfoService.searchUserSubInfoByUserId(userId);
model.addAttribute("userInfoModel", userInfoModel);
model.addAttribute("userSubInfoModel", userSubInfoModel);
model.addAttribute("errorMsg", "");
List<BaseProvinceModel> baseProvinceList = new ArrayList<BaseProvinceModel>();
List<BaseCityModel> baseCityModelList = new ArrayList<BaseCityModel>();
//省份
baseProvinceList = baseProvinceService.searchBaseProvince();
//省份默认
BaseProvinceModel baseProvinceModel = new BaseProvinceModel();
baseProvinceModel.setProvinceid(0);
baseProvinceModel.setProvincename("请选择");
baseProvinceList.add(0, baseProvinceModel);
//城市
if (userInfoModel.getProvinceid() == 0) {
BaseCityModel baseCityModel = new BaseCityModel();
baseCityModel.setCityid(0);
baseCityModel.setCityname("请选择");
baseCityModelList.add(0,baseCityModel);
}else {
baseCityModelList = baseCityService.searchBaseCityByProvinceId(userInfoModel.getProvinceid());
}
UserinfoModel userInfoModelSession = userinfoService.searchUserinfoById(userId);
//身份证正面
UserPhotoMappingModel userPhotoMappingModel2 = userPhotoMappingService.searchUserPhoto(userInfoModelSession.getUserid(), 2);
if(null != userPhotoMappingModel2 && userPhotoMappingModel2.getBasePicture() != null){
String path = userPhotoMappingModel2.getBasePicture().getPicturepath();
String imgName = path.substring(8);
model.addAttribute("imgFileName_zm", path);
model.addAttribute("hidfileName_zm", imgName);
}else{
model.addAttribute("imgFileName_zm", "images/defaultAvatar.png");
}
//身份证背面
UserPhotoMappingModel userPhotoMappingModel3 = userPhotoMappingService.searchUserPhoto(userInfoModelSession.getUserid(), 3);
if(null != userPhotoMappingModel3 && userPhotoMappingModel3.getBasePicture() != null){
String path = userPhotoMappingModel3.getBasePicture().getPicturepath();
String imgName = path.substring(8);
model.addAttribute("imgFileName_bm", path);
model.addAttribute("hidfileName_bm", imgName);
}else{
model.addAttribute("imgFileName_bm", "images/defaultAvatar.png");
}
//手持身份证
UserPhotoMappingModel userPhotoMappingModel4 = userPhotoMappingService.searchUserPhoto(userInfoModelSession.getUserid(), 4);
if(null != userPhotoMappingModel4 && userPhotoMappingModel4.getBasePicture() != null){
String path = userPhotoMappingModel4.getBasePicture().getPicturepath();
String imgName = path.substring(8);
model.addAttribute("imgFileName_sc", path);
model.addAttribute("hidfileName_sc", imgName);
}else{
model.addAttribute("imgFileName_sc", "images/defaultAvatar.png");
}
model.addAttribute("baseProvinceList", baseProvinceList);
model.addAttribute("baseCityModelList", baseCityModelList);
model.addAttribute("userId", userId);
} catch (BaseException e) {
// 保存异常信息
utilService.addBaseException(request.getRequestURI(), "", e.getMessage());
}
return "usersubinfo_verification";
}
@RequestMapping("doSaveUserSubInfo")
public String doSaveUserSubInfo(HttpServletRequest request, Model model, String userid, String truename, String email,
int provinceid, int cityid, String address, String household, String contact, String relationship,
String contactmobile, String idcard,int buttonFlag, String fileName_zm,String fileName_bm,String fileName_sc)
throws BaseException, IOException {
//HttpSession session = request.getSession();
int userId = 0;
if(userid != ""){
userId = Integer.parseInt(userid);
}
String result = "";
try {
//System.out.println("*****************"+truename+"*****************");
//美发师扩展信息
UsersubinfoModel userSubInfo = new UsersubinfoModel();
userSubInfo.setTruename(truename);
userSubInfo.setEmail(email);
userSubInfo.setAddress(address);
userSubInfo.setHousehold(household);
userSubInfo.setContact(contact);
userSubInfo.setContactmobile(contactmobile);
userSubInfo.setRelationship(relationship);
userSubInfo.setIdcard(idcard);
userSubInfo.setCreatetime(new Date());
userSubInfo.setLevelid(1);// 资深发型师
BaseStarinfoModel baseStarinfoModel = new BaseStarinfoModel();
baseStarinfoModel.setStarid(1);
userSubInfo.setBaseStarinfoModel(baseStarinfoModel);
userSubInfo.setStarid(1);// 摩羯座
UserinfoModel userInfoModel = new UserinfoModel();
userInfoModel.setProvinceid(provinceid);
userInfoModel.setCityid(cityid);
//判断session的用户是否为空
if (userId > 0) {
//userId = Integer.parseInt(session.getAttribute("userId").toString());
userSubInfo.setUserid(userId);
//userSubInfo.setCheckstate(0);//审核状态:未提交审核
userInfoModel.setUserid(userId);
UsersubinfoModel userSubInfoTemp = usersubinfoService.searchUserSubInfoByUserId(userId);
UserinfoModel userInfoTemp = userinfoService.searchUserinfoById(userId);
saveImage(fileName_zm,userId,2,0,request);//保存身份证正面
saveImage(fileName_bm,userId,3,0,request);//保存身份证背面
saveImage(fileName_sc,userId,4,0,request);//保存手持身份证
//判断用户是否为新增用户,否则执行修改
if (0 == userSubInfoTemp.getUserid()) {
// 信息不存在,新增美发师扩展信息
int addResult = usersubinfoService.addUserSubInfo(userSubInfo);
if (addResult > 0) {
userInfoTemp.setProvinceid(provinceid);
userInfoTemp.setCityid(cityid);
userInfoTemp.setUpdatetime(new Date());
if (userinfoService.updateUserInfoByUserId(userInfoTemp)) {
if(buttonFlag == 0){
result = "usersubinfo_verification";
}else{
result = "usersubinfo_information";
}
model.addAttribute("errorMsg", "保存成功!");
} else {
result = "usersubinfo_verification";
model.addAttribute("errorMsg", "保存失败!");
}
} else {
// 新增失败
result = "error";
model.addAttribute("errorMsg", "保存失败!");
}
} else {
// 信息存在,更新美发师扩展信息
userSubInfoTemp.setTruename(truename);
userSubInfoTemp.setEmail(email);
userSubInfoTemp.setAddress(address);
userSubInfoTemp.setHousehold(household);
userSubInfoTemp.setContact(contact);
userSubInfoTemp.setContactmobile(contactmobile);
userSubInfoTemp.setRelationship(relationship);
userSubInfoTemp.setIdcard(idcard);
/*if(userSubInfoTemp.getCheckstate() != 1 && userSubInfoTemp.getCheckstate() != 2){
userSubInfoTemp.setCheckstate(0);//审核状态:未提交审核
}*/
boolean updateResult = usersubinfoService.updateUserSubInfoByUserId(userSubInfoTemp);
if (updateResult) {
// 更新成功
// 更新userinfo表里的省市信息
userInfoTemp.setProvinceid(provinceid);
userInfoTemp.setCityid(cityid);
userInfoTemp.setUpdatetime(new Date());
if (userinfoService.updateUserInfoByUserId(userInfoTemp)) {
if(buttonFlag == 0){
result = "usersubinfo_verification";
}else{
result = "usersubinfo_information";
}
model.addAttribute("errorMsg", "保存成功!");
} else {
result = "usersubinfo_verification";
model.addAttribute("errorMsg", "保存失败!");
}
} else {
// 更新失败
result = "error";
model.addAttribute("errorMsg", "保存失败!");
}
}
if(buttonFlag == 0){
//跳转第一页
model.addAttribute("userInfoModel", userInfoTemp);
model.addAttribute("userSubInfoModel", userSubInfo);
List<BaseProvinceModel> baseProvinceList = new ArrayList<BaseProvinceModel>();
List<BaseCityModel> baseCityModelList = new ArrayList<BaseCityModel>();
//省份
baseProvinceList = baseProvinceService.searchBaseProvince();
BaseProvinceModel baseProvinceModel = new BaseProvinceModel();
baseProvinceModel.setProvinceid(0);
baseProvinceModel.setProvincename("请选择");
baseProvinceList.add(0, baseProvinceModel);
//城市
if (userInfoModel.getProvinceid() == 0) {
BaseCityModel baseCityModel = new BaseCityModel();
baseCityModel.setCityid(0);
baseCityModel.setCityname("请选择");
baseCityModelList.add(0,baseCityModel);
}else {
baseCityModelList = baseCityService.searchBaseCityByProvinceId(userInfoModel.getProvinceid());
}
model.addAttribute("baseProvinceList", baseProvinceList);
model.addAttribute("baseCityModelList", baseCityModelList);
setImageAttribute(userInfoTemp.getUserid(), 2, "imgFileName_zm","hidfileName_zm","defaultAvatar.png", model, request); //设置身份证正面到Attribute
setImageAttribute(userInfoTemp.getUserid(), 3, "imgFileName_bm","hidfileName_bm","defaultAvatar.png", model, request); //设置身份证背面到Attribute
setImageAttribute(userInfoTemp.getUserid(), 4, "imgFileName_sc","hidfileName_sc","defaultAvatar.png", model, request); //设置手持身份证到Attribute
}else{
UserinfoModel userInfoModelSession = userinfoService.searchUserinfoById(userId);
UsersubinfoModel userSubInfoModelSession = usersubinfoService.searchUserSubInfoByUserId(userId);
List<BaseStarinfoModel> baseStarInfoList = new ArrayList<BaseStarinfoModel>();
baseStarInfoList = baseStarInfoService.searchBaseStarInfo();
BaseStarinfoModel baseStarinfoModelSession = new BaseStarinfoModel();
baseStarinfoModelSession.setStarid(0);
baseStarinfoModelSession.setStarname("请选择");
baseStarInfoList.add(0, baseStarinfoModelSession);
List<BaseConfigModel> hobbyList = baseConfigService.searchBaseConfig("hobby");
List<BaseConfigModel> hairstyleList = baseConfigService.searchBaseConfig("hairstyle");
model.addAttribute("hobbyList", hobbyList);
model.addAttribute("hairstyleList", hairstyleList);
model.addAttribute("baseStarInfoList", baseStarInfoList);
model.addAttribute("userInfoModel", userInfoModelSession);
model.addAttribute("userSubInfoModel", userSubInfoModelSession);
model.addAttribute("errorMsg", "");
//页面中显示对应的图片
setImageAttribute(userInfoModelSession.getUserid(), 1, "userPhoto","hidFileName_tx", "defaultAvatar.png",model, request); //设置我的头像到Attribute
setImageAttribute(userInfoModelSession.getUserid(), 7, "userImage","hidFileName_xx","defaultAvatar.png", model, request); //设置我的形象到Attribute
setImageAttribute(userInfoModelSession.getUserid(), 6, "userWork","hidFileName_zp","defaultAvatar.png", model, request); //设置我的代表作品到Attribute
}
}
} catch (Exception e) {
// 保存异常信息
utilService.addBaseException(request.getRequestURI(), "", e.getMessage());
}
model.addAttribute("userId", userId);
return result;
}
/**
* 保存图片到数据库
* @param fileName
* @param userId
* @param type
* @param sortNum 0为单张图片,1、2、3、4为多张图片
* @param request
*/
public void saveImage(String fileName,int userId,int type,int sortNum,HttpServletRequest request){
//Date date = new Date();
if(!"".equals(fileName)){
String serverPath = request.getServletContext().getRealPath("/userImg/");
try {
userPhotoMappingService.addOrUpdImg(userId, type, sortNum,fileName, serverPath);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
/**
* 设置图片的Attribute
* @param userId
* @param type 图片类型
* @param imgFileName
* @param hidFileName
* @param defaultImagePath 默认图片路径
* @param model
* @param request
*/
public void setImageAttribute(int userId,int type,String imgFileName,String hidFileName,String defaultImagePath,Model model,HttpServletRequest request){
try {
if(type == Constant.IMAGE_TYPE_06 || type == Constant.IMAGE_TYPE_07){
List<UserPhotoMappingModel> userPhotoMappingModels = userPhotoMappingService.searchUserPhotos(userId, type);
int size = 0;
if(type == Constant.IMAGE_TYPE_07){
size = 3;//我的形象循环3次
}else{
size = 4;//我的作品循环4次
}
//有图片,设置图片;没有图片,设置默认图片
for (int i = 0; i < size; i++) {
if(null != userPhotoMappingModels){
for (int j = 0; j < userPhotoMappingModels.size(); j++) {
UserPhotoMappingModel userPhotoMappingModel = userPhotoMappingModels.get(j);
if(null != userPhotoMappingModel){
if((i+1) != userPhotoMappingModel.getSortnum()){
model.addAttribute(imgFileName+(i+1), "images/"+defaultImagePath);
}else{
if(userPhotoMappingModel.getBasePicture() != null){
String path = userPhotoMappingModel.getBasePicture().getPicturepath();
String imgName = path.substring(8);
model.addAttribute(imgFileName+(i+1), path);
model.addAttribute(hidFileName+(i+1), imgName);
break;
}
}
}
}
}else{
model.addAttribute(imgFileName+(i+1), "images/"+defaultImagePath);
}
}
}else{
UserPhotoMappingModel userPhotoMappingModel = userPhotoMappingService.searchUserPhoto(userId, type);
if(null != userPhotoMappingModel && userPhotoMappingModel.getBasePicture() != null){
String path = userPhotoMappingModel.getBasePicture().getPicturepath();
String imgName = path.substring(8);
model.addAttribute(imgFileName, path);
model.addAttribute(hidFileName, imgName);
}else{
model.addAttribute(imgFileName, "images/"+defaultImagePath);
}
}
} catch (Exception e) {
// 保存异常信息
utilService.addBaseException(request.getRequestURI(), "", e.getMessage());
}
}
@RequestMapping("goUsersubinfo_information")
/**
* 查看业务信息
* @param request
* @param model
* @return
*/
public String goUsersubinfo_information(int userId,HttpServletRequest request, Model model) {
try {
UserinfoModel userInfoModelSession = userinfoService.searchUserinfoById(userId);
UsersubinfoModel userSubInfoModelSession = usersubinfoService.searchUserSubInfoByUserId(userId);
List<BaseStarinfoModel> baseStarInfoList = new ArrayList<BaseStarinfoModel>();
baseStarInfoList = baseStarInfoService.searchBaseStarInfo();
BaseStarinfoModel baseStarinfoModelSession = new BaseStarinfoModel();
baseStarinfoModelSession.setStarid(0);
baseStarinfoModelSession.setStarname("请选择");
baseStarInfoList.add(0, baseStarinfoModelSession);
List<BaseConfigModel> hobbyList = baseConfigService.searchBaseConfig("hobby");
List<BaseConfigModel> hairstyleList = baseConfigService.searchBaseConfig("hairstyle");
model.addAttribute("hobbyList", hobbyList);
model.addAttribute("hairstyleList", hairstyleList);
model.addAttribute("baseStarInfoList", baseStarInfoList);
model.addAttribute("userInfoModel", userInfoModelSession);
model.addAttribute("userSubInfoModel", userSubInfoModelSession);
model.addAttribute("errorMsg", "");
model.addAttribute("userId", userId);
setImageAttribute(userInfoModelSession.getUserid(), 1, "userPhoto","hidFileName_tx", "defaultAvatar.png",model, request); //设置我的头像到Attribute
setImageAttribute(userInfoModelSession.getUserid(), 7, "userImage","hidFileName_xx","defaultAvatar.png", model, request); //设置我的形象到Attribute
setImageAttribute(userInfoModelSession.getUserid(), 6, "userWork","hidFileName_zp","defaultAvatar.png", model, request); //设置我的代表作品到Attribute
} catch (Exception e) {
// 保存异常信息
utilService.addBaseException(request.getRequestURI(), "", e.getMessage());
}
return "usersubinfo_information";
}
@RequestMapping("doSaveUserInfo")
/**
* 保存美发师验证信息
*
* @param request
* @param model
* @param bindphone
* @param password
* @param verificationCode
* @return
*/
public String doSaveUserInfo(HttpServletRequest request, Model model, String userid, String nickname, int starid, int workinglife,
String intro, String workhistory, String hairstyle, String hobbies,int buttonFlag,
String fileName_tx,String fileName_xx1,String fileName_xx2,String fileName_xx3,String fileName_zp1,String fileName_zp2,String fileName_zp3,String fileName_zp4) {
String result = "";
String errorMsg = "";
int userId = 0;
if(userid != ""){
userId = Integer.parseInt(userid);
}
try {
UsersubinfoModel userSubInfo = new UsersubinfoModel();
userSubInfo.setStarid(starid);
userSubInfo.setWorkinglife(workinglife);
userSubInfo.setIntro(intro);
userSubInfo.setWorkhistory(workhistory);
userSubInfo.setHairstyle(hairstyle);
userSubInfo.setHobbies(hobbies);
UserinfoModel userInfoModel = new UserinfoModel();
userInfoModel.setNickname(nickname);
//HttpSession session = request.getSession();
if (userId > 0) {
//userId = Integer.parseInt(session.getAttribute("userId").toString());
saveImage(fileName_tx,userId,1,0,request);//保存我的头像
saveImage(fileName_xx1,userId,7,1,request);//保存我的形象1
saveImage(fileName_xx2,userId,7,2,request);//保存我的形象2
saveImage(fileName_xx3,userId,7,3,request);//保存我的形象3
saveImage(fileName_zp1,userId,6,1,request);//保存我的代表作品1
saveImage(fileName_zp2,userId,6,2,request);//保存我的代表作品2
saveImage(fileName_zp3,userId,6,3,request);//保存我的代表作品3
saveImage(fileName_zp4,userId,6,4,request);//保存我的代表作品4
userSubInfo.setUserid(userId);
/*if(buttonFlag == 1){
userSubInfo.setCheckstate(1);//审核状态:审核中
}else{
userSubInfo.setCheckstate(0);//审核状态:未提交审核
}*/
userInfoModel.setUserid(userId);
UsersubinfoModel userSubInfoTemp = usersubinfoService.searchUserSubInfoByUserId(userId);
UserinfoModel userInfoTemp = userinfoService.searchUserinfoById(userId);
if (0 == userSubInfoTemp.getUserid()) {
// 信息不存在,新增美发师扩展信息
int addResult = usersubinfoService.addUserSubInfo(userSubInfo);
if (addResult > 0) {
// 新增成功
// 更新userinfo表里的昵称信息
userInfoTemp.setNickname(nickname);
if (userinfoService.updateUserInfoByUserId(userInfoTemp)) {
if(buttonFlag == 0){
errorMsg = "保存成功!";
result = "usersubinfo_information";
}else{
errorMsg = "填写完毕,请等待管理员审核。";
result = "usersubinfo_verification";
}
} else {
errorMsg = "操作失败!";
result = "usersubinfo_information";
}
} else {
// 新增失败
errorMsg = "操作失败!";
result = "usersubinfo_information";
}
} else {
// 信息存在,更新美发师扩展信息
userSubInfoTemp.setStarid(starid);
userSubInfoTemp.setWorkinglife(workinglife);
userSubInfoTemp.setIntro(intro);
userSubInfoTemp.setWorkhistory(workhistory);
userSubInfoTemp.setHairstyle(hairstyle);
userSubInfoTemp.setHobbies(hobbies);
/*if(buttonFlag == 1){
userSubInfoTemp.setCheckstate(1);//审核状态:审核中
}else{
userSubInfoTemp.setCheckstate(0);//审核状态:未提交审核
}*/
boolean updateResult = usersubinfoService.updateUserSubInfoByUserId(userSubInfoTemp);
if (updateResult) {
// 更新成功
// 更新userinfo表里的昵称信息
userInfoTemp.setNickname(nickname);
if (userinfoService.updateUserInfoByUserId(userInfoTemp)) {
if(buttonFlag == 0){
errorMsg = "保存成功!";
result = "usersubinfo_information";
}else{
errorMsg = "填写完毕,请等待管理员审核。";
result = "usersubinfo_verification";
}
} else {
errorMsg = "操作失败!";
result = "usersubinfo_information";
}
} else {
// 更新失败
errorMsg = "操作失败!";
result = "usersubinfo_information";
}
}
} else {
errorMsg = "操作失败!";
result = "usersubinfo_information";
}
if(buttonFlag == 0){
//保存操作,跳转到当前页面
UserinfoModel userInfoModelSession = userinfoService.searchUserinfoById(userId);
UsersubinfoModel userSubInfoModelSession = usersubinfoService.searchUserSubInfoByUserId(userId);
List<BaseStarinfoModel> baseStarInfoList = new ArrayList<BaseStarinfoModel>();
baseStarInfoList = baseStarInfoService.searchBaseStarInfo();
BaseStarinfoModel baseStarinfoModelSession = new BaseStarinfoModel();
baseStarinfoModelSession.setStarid(0);
baseStarinfoModelSession.setStarname("请选择");
baseStarInfoList.add(0, baseStarinfoModelSession);
List<BaseConfigModel> hobbyList = baseConfigService.searchBaseConfig("hobby");
List<BaseConfigModel> hairstyleList = baseConfigService.searchBaseConfig("hairstyle");
model.addAttribute("hobbyList", hobbyList);
model.addAttribute("hairstyleList", hairstyleList);
model.addAttribute("baseStarInfoList", baseStarInfoList);
model.addAttribute("userInfoModel", userInfoModelSession);
model.addAttribute("userSubInfoModel", userSubInfoModelSession);
setImageAttribute(userInfoModelSession.getUserid(), 1, "userPhoto","hidFileName_tx", "defaultAvatar.png",model, request); //设置我的头像到Attribute
setImageAttribute(userInfoModelSession.getUserid(), 7, "userImage","hidFileName_xx","defaultAvatar.png", model, request); //设置我的形象到Attribute
setImageAttribute(userInfoModelSession.getUserid(), 6, "userWork","hidFileName_zp","defaultAvatar.png", model, request); //设置我的代表作品到Attribute
model.addAttribute("errorMsg", errorMsg);
}else{
UserinfoModel userInfoModelSession = userinfoService.searchUserinfoById(userId);
UsersubinfoModel userSubInfoModelSession = usersubinfoService.searchUserSubInfoByUserId(userId);
model.addAttribute("userInfoModel", userInfoModelSession);
model.addAttribute("userSubInfoModel", userSubInfoModelSession);
model.addAttribute("errorMsg", "填写完毕,请等待管理员审核。");
List<BaseProvinceModel> baseProvinceList = new ArrayList<BaseProvinceModel>();
List<BaseCityModel> baseCityModelList = new ArrayList<BaseCityModel>();
//省份
baseProvinceList = baseProvinceService.searchBaseProvince();
//省份默认
BaseProvinceModel baseProvinceModel = new BaseProvinceModel();
baseProvinceModel.setProvinceid(0);
baseProvinceModel.setProvincename("请选择");
baseProvinceList.add(0, baseProvinceModel);
//城市
if (userInfoModelSession.getProvinceid() == 0) {
BaseCityModel baseCityModel = new BaseCityModel();
baseCityModel.setCityid(0);
baseCityModel.setCityname("请选择");
baseCityModelList.add(0,baseCityModel);
}else {
baseCityModelList = baseCityService.searchBaseCityByProvinceId(userInfoModelSession.getProvinceid());
}
setImageAttribute(userInfoModelSession.getUserid(), 2, "imgFileName_zm","hidfileName_zm","defaultAvatar.png", model, request); //设置身份证正面到Attribute
setImageAttribute(userInfoModelSession.getUserid(), 3, "imgFileName_bm","hidfileName_bm","defaultAvatar.png", model, request); //设置身份证背面到Attribute
setImageAttribute(userInfoModelSession.getUserid(), 4, "imgFileName_sc","hidfileName_sc","defaultAvatar.png", model, request); //设置手持身份证到Attribute
model.addAttribute("baseProvinceList", baseProvinceList);
model.addAttribute("baseCityModelList", baseCityModelList);
}
} catch (Exception e) {
// 保存异常信息
utilService.addBaseException(request.getRequestURI(), "", e.getMessage());
}
model.addAttribute("userId", userId);
return result;
}
}
|
package gui.tree;
import gui.ClipboardHelper;
import gui.ComponentTools;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Enumeration;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import utils.PrintUtil;
public class WarningTree
{
private Component parent;
private AutoTree model;
private JTree view;
private JPanel panel;
public WarningTree (final Component parent, final AutoTree warnings)
{
this.parent = parent;
this.model = warnings;
view = new JTree (model);
view.putClientProperty ("JTree.lineStyle", "Angled");
view.setShowsRootHandles (true);
view.setRootVisible (false);
view.setEditable (false);
// view.setCellRenderer (new TreeRenderer()); TBD
supportCopy();
// model.outline (System.out); // trace
}
public AutoTree getModel()
{
return model;
}
public JTree getView()
{
return view;
}
public void show (final String title)
{
if (panel == null)
{
ActionListener listener = new ButtonListener();
JButton copyButton = ComponentTools.makeButtonNarrow
("Copy", "icons/20/gui/ClipboardPaste.gif", true, listener,
"Copy the selected warnings to the clipboard");
JButton printButton = ComponentTools.makeButtonNarrow
("Print", "icons/20/objects/Printer.gif", true, listener,
"Print the tree (as it appears now)");
JPanel buttons = new JPanel();
buttons.add (copyButton);
buttons.add (printButton);
JScrollPane scroll = new JScrollPane (view);
scroll.setPreferredSize (new Dimension (500, 400));
panel = new JPanel (new BorderLayout());
panel.add (scroll, BorderLayout.CENTER);
panel.add (buttons, BorderLayout.SOUTH);
}
JOptionPane.showMessageDialog (parent, panel, title,
JOptionPane.PLAIN_MESSAGE, null);
}
@SuppressWarnings("unchecked")
private void copy()
{
StringBuilder sb = new StringBuilder();
// copy just the selected ones (if there are any)
if (view.getSelectionCount() > 0)
for (TreePath tp : view.getSelectionPaths())
{
AutoTreeNode node = (AutoTreeNode) tp.getLastPathComponent();
if (node.isLeaf() && node.getUserObject() != null)
sb.append (node.getUserObject() + "\n");
else // select all children (TBD: recurse)
for (AutoTreeNode leaf : node.getLeaves())
sb.append (leaf.getUserObject() + "\n");
}
else
{
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
Enumeration<DefaultMutableTreeNode> en = root.preorderEnumeration();
while (en.hasMoreElements())
{
DefaultMutableTreeNode node = en.nextElement();
if (node.toString() != null)
{
for (int i = 0, level = node.getLevel(); i < level; i++)
sb.append (" ");
sb.append (node.toString() + "\n");
}
}
}
ClipboardHelper.copyString (sb);
}
private void supportCopy()
{
KeyStroke controlC = KeyStroke.getKeyStroke (KeyEvent.VK_C, Event.CTRL_MASK);
view.getInputMap().put (controlC, "none"); // stop JTree from consuming
Action action = new CopyAction();
Object name = action.getValue (Action.NAME);
view.getInputMap (JComponent.WHEN_IN_FOCUSED_WINDOW).put (controlC, name);
view.getActionMap().put (name, action);
}
class CopyAction extends AbstractAction
{
public CopyAction()
{
super ("CopyAction");
}
public void actionPerformed (final ActionEvent e)
{
copy();
}
}
class ButtonListener implements ActionListener
{
public void actionPerformed (final ActionEvent e)
{
String cmd = e.getActionCommand();
if (cmd.equals ("Copy"))
copy();
else if (cmd.equals ("Print"))
PrintUtil.print (parent, getView());
else
System.err.println ("Unsupported command: " + cmd);
}
}
}
|
package FirstProject.Playground;
public class College {
private Student student;
private int basicFees;
College(Student student, int basicFees){
this.student = student;
this.basicFees = basicFees;
}
}
|
public class Myfavoritesubjects {
public static void main(String[] args) {
System.out.println("My favorite subjects are \n\t Chemistry\n\t Math\n\t Computer Programming\n\t");
}
}
|
package com.thousand.petdog.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.thousand.petdog.R;
import com.thousand.petdog.adapter.SearchAddressAdapter;
import com.thousand.petdog.bean.AddressBean;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Activity:地图
* 描述:第6小块儿:查看宠物店地图
*/
public class MapActivity extends Activity implements PoiSearch.OnPoiSearchListener, Inputtips.InputtipsListener, View.OnClickListener, LocationSource {
private Context context;
private MapView mMapView = null;
private AMap aMap;
private MyLocationStyle myLocationStyle;
private UiSettings mUiSettings;//定义一个UiSettings对象
private InputtipsQuery inputquery;
private Inputtips inputtips = null;
private PoiSearch.Query query;
private ListView lv_address;
private PoiSearch poiSearch;
private SearchAddressAdapter adapter;
private ArrayList<AddressBean> data = new ArrayList<AddressBean>();
//声明AMapLocationClient类对象
public AMapLocationClient mLocationClient = null;
//声明定位回调监听器
public AMapLocationListener mLocationListener;
//声明AMapLocationClientOption对象
public AMapLocationClientOption mLocationOption;
int page = 0;
private EditText et_search;
private Button btn_search;
//返回箭头
@BindView(R.id.tv_left_button)
Button tv_left_button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
ButterKnife.bind(this);
context = this;
initView();
setOnClick();
//获取地图控件引用
mMapView = (MapView) findViewById(R.id.map);
//在activity执行onCreate时执行mMapView.onCreate(savedInstanceState),创建地图
mMapView.onCreate(savedInstanceState);
//放大18级
mMapView.getMap().moveCamera(CameraUpdateFactory.zoomTo(18));
//--------二:定位步骤1-------------初始化地图控制器对象
if (aMap == null) {
aMap = mMapView.getMap();
}
// --------二:定位步骤(无2)3-------------实例化UiSettings类对象
mUiSettings = aMap.getUiSettings();
//初始化定位
initLocation();
//初始化地图中的手势
initMapFunction();
//输入自动提示
// inputtips.setInputtipsListener(this);
}
public void initView() {
adapter = new SearchAddressAdapter(context, data);
et_search = (EditText) findViewById(R.id.et_search);
lv_address = (ListView) findViewById(R.id.lv_address);
lv_address.setAdapter(adapter);
et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEND
|| actionId == EditorInfo.IME_ACTION_DONE
|| (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
//处理事件
Toast.makeText(getApplicationContext(), "功能正在开发中", Toast.LENGTH_SHORT);
}
return false;
}
});
}
public void initMapFunction() {
//指南针
mUiSettings.setCompassEnabled(true);
//缩放手势
mUiSettings.setZoomGesturesEnabled(true);
//滑动手势
mUiSettings.setScrollGesturesEnabled(true);
}
public void initLocation() {
// --------二:定位步骤4-------------通过aMap对象设置定位数据源的监听
aMap.setLocationSource(this);
// --------二:定位步骤5-------------显示默认的定位按钮
mUiSettings.setMyLocationButtonEnabled(true);
// --------二:定位步骤6-------------可触发定位并显示当前位置
aMap.setMyLocationEnabled(true);
// --------二:定位步骤7-------------初始化定位
mLocationClient = new AMapLocationClient(getApplicationContext());
//--------二:定位步骤8-------------设置定位回调监听
mLocationClient.setLocationListener(mLocationListener);
//声明AMapLocationClientOption对象
mLocationOption = null;
//--------二:定位步骤9-------------初始化AMapLocationClientOption对象
mLocationOption = new AMapLocationClientOption();
//--------二:定位步骤10-------------设置定位模式为AMapLocationMode.Battery_Saving,低功耗模式。
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
//--------二:定位步骤11-------------//设置是否返回地址信息(默认返回地址信息)
mLocationOption.setNeedAddress(true);
//--------二:定位步骤12-------------获取一次定位结果://该方法默认为false。
mLocationOption.setOnceLocation(true);
//--------二:定位步骤13-------------设置是否强制刷新WIFI,默认为强制刷新
mLocationOption.setWifiActiveScan(true);
//--------二:定位步骤14-------------设置是否允许模拟位置,默认为false,不允许模拟位置
mLocationOption.setMockEnable(false);
//--------二:定位步骤15-------------设置定位间隔,单位毫秒,默认为2000ms
mLocationOption.setInterval(2000);
//--------二:定位步骤16-------------给定位客户端对象设置定位参数
mLocationClient.setLocationOption(mLocationOption);
//--------二:定位步骤17-------------启动定位
mLocationClient.startLocation();
//获取最近3s内精度最高的一次定位结果:
//设置setOnceLocationLatest(boolean b)接口为true,启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true,setOnceLocation(boolean b)接口也会被设置为true,反之不会,默认为false。
mLocationOption.setOnceLocationLatest(true);
// 设置连续定位模式下的定位间隔,只在连续定位模式下生效,单次定位模式下不会生效。单位为毫秒。
// myLocationStyle.interval(2000);
//设置定位蓝点的Style
aMap.setMyLocationStyle(myLocationStyle);
//初始化定位蓝点样式类
myLocationStyle = new MyLocationStyle();
myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);
// 设置为true表示启动显示定位蓝点,false表示隐藏定位蓝点并不进行定位,默认是false。
aMap.setMyLocationEnabled(true);
// 连续定位、且将视角移动到地图中心点,定位点依照设备方向旋转,并且会跟随设备移动。(1秒1次定位)
// 如果不设置myLocationType,默认也会执行此种模式。
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//返回上级Activity
case android.R.id.home:
//销毁地图
onDestroy();
finish();
break;
}
return super.onOptionsItemSelected(item);
}
//---------------------地图生命周期
@Override
protected void onDestroy() {
super.onDestroy();
//在activity执行onDestroy时执行mMapView.onDestroy(),销毁地图
mMapView.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView.onResume (),重新绘制加载地图
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView.onPause (),暂停地图的绘制
mMapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState),保存地图当前的状态
mMapView.onSaveInstanceState(outState);
}
//- -----------------地图生命周期-结束
@OnClick(R.id.tv_left_button)
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_left_button:
finish();
break;
}
}
private void seach(String address) {
query = new PoiSearch.Query(address, "", "");
query.setPageSize(10);// 设置每页最多返回多少条poiitem
query.setPageNum(page);//设置查询页码
poiSearch = new PoiSearch(this, query);
poiSearch.searchPOIAsyn();//调用 PoiSearch 的 searchPOIAsyn() 方法发送请求。
poiSearch.setOnPoiSearchListener(this);
}
private void setOnClick() {
et_search.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String content = charSequence.toString().trim();//获取自动提示输入框的内容
inputquery = new InputtipsQuery(content, "");
inputquery.setCityLimit(true);//限制在当前城市
inputtips = new Inputtips(MapActivity.this, inputquery);//定义一个输入提示对象,传入当前上下文和搜索对象
inputtips.setInputtipsListener(MapActivity.this);//设置输入提示查询的监听,实现输入提示的监听方法onGetInputtips()
inputtips.requestInputtipsAsyn();//输入查询提示的异步接口实现
}
@Override
public void afterTextChanged(Editable editable) {
String str = et_search.getText().toString();
if (str.length() > 0) {
seach(str);
}
}
});
lv_address.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent();//ListView item点击回调
intent.putExtra("data", data.get(i));
setResult(100, intent);
finish();
}
});
}
// 通过回调接口 onGetInputtips 解析返回的结果,获取输入提示返回的信息
@Override
public void onGetInputtips(List<Tip> list, int i) {
if (i == 1000) {//如果输入提示搜索成功
}
}
//POI解析查询结果
@Override
public void onPoiSearched(PoiResult poiResult, int i) {
data.clear();
//解析result获取POI信息
if (i == 1000 && poiResult != null) {
ArrayList<PoiItem> items = poiResult.getPois();
for (PoiItem item : items) { //获取经纬度对象
LatLonPoint llp = item.getLatLonPoint();
double lon = llp.getLongitude();
double lat = llp.getLatitude();
//获取标题
String title = item.getTitle();
//获取内容
String text = item.getSnippet();
String name = item.getAdName();
String cityName = item.getCityName();
String area = item.getBusinessArea();
String provinceName = item.getProvinceName();
String addressInfo = provinceName + cityName + name + text;
data.add(new AddressBean(lon, lat, title, text, addressInfo));
}
adapter.refreshData(data);
}
}
@Override
public void onPoiItemSearched(PoiItem poiItem, int i) {
}
//定位3接口
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
@Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
}
@Override
public void deactivate() {
}
}
|
package com.sun.tools.xjc.generator.annotation.spec;
import javax.xml.bind.annotation.XmlElementRef;
import com.sun.codemodel.JAnnotationWriter;
import com.sun.codemodel.JType;
public interface XmlElementRefWriter
extends JAnnotationWriter<XmlElementRef>
{
XmlElementRefWriter name(String value);
XmlElementRefWriter type(Class value);
XmlElementRefWriter type(JType value);
XmlElementRefWriter namespace(String value);
}
|
package entity;
import java.sql.Date;
public class Corso {
private int id_corso;
private String nome_corso;
private Date data_inizio;
private Date data_fine;
private String Descr;
private int id_prof;
public int getId_prof() {
return id_prof;
}
public void setId_prof(int id_prof) {
this.id_prof = id_prof;
}
public int getId_corso() {
return id_corso;
}
public void setId_corso(int id_corso) {
this.id_corso = id_corso;
}
public String getNome_corso() {
return nome_corso;
}
public void setNome_corso(String nome_corso) {
this.nome_corso = nome_corso;
}
public Date getData_inizio() {
return data_inizio;
}
public void setData_inizio(Date data_inizio) {
this.data_inizio = data_inizio;
}
public Date getData_fine() {
return data_fine;
}
public void setData_fine(Date data_fine) {
this.data_fine = data_fine;
}
public String getDescr() {
return Descr;
}
public void setDescr(String descr) {
Descr = descr;
}
@Override
public String toString() {
return "Corso [id_corso=" + id_corso + ", nome_corso=" + nome_corso + ", data_inizio=" + data_inizio
+ ", data_fine=" + data_fine + ", Descr=" + Descr + ", id_prof=" + id_prof + "]\n";
}
}
|
package com.Game;
public class GameEngine extends AbstractGameRule{
public GameEngine()
{
}
/* This method starts the game and it gets executed till the end(result gets out)
* */
public void startGame(Player player)
{
// Play the game once
do {
player.markBox(currentPlayer); // update currentRow and currentCol
updateGame(currentPlayer, currntRow, currentCol); // update currentState
printBoard();
// Print message if game-over
if (currentState == CROSS_WON) {
System.out.println("'X' won! Bye!");
} else if (currentState == NOUGHT_WON) {
System.out.println("'O' won! Bye!");
} else if (currentState == DRAW) {
System.out.println("It's a Draw! Bye!");
}
// Switch player
currentPlayer = (currentPlayer == CROSS) ? NOUGHT : CROSS;
} while (currentState == PLAYING); // repeat if not game-over
}
}
|
package cn.edu.ncu.collegesecondhand.adapter.interf;
import cn.edu.ncu.collegesecondhand.entity.CartBean;
/**
* Created by ren lingyun on 2020/4/20 2:57
*/
public interface CartCheckListener {
void isChecked(CartBean cartBean);
void isNotChecked(CartBean cartBean);
}
|
package fudan.database.project.dao.impl;
import fudan.database.project.dao.DAO;
import fudan.database.project.dao.DailyRecordDAO;
import fudan.database.project.entity.DailyRecord;
import java.util.List;
public class DailyRecordDAOJdbcImpl extends DAO<DailyRecord> implements DailyRecordDAO {
@Override
public void save(DailyRecord dailyRecord) {
String sql = "INSERT INTO daily_record(patientId, temperature, symptom, lifeStatus, date) VALUES(?,?,?,?,?)";
update(sql, dailyRecord.getPatientId(), dailyRecord.getTemperature(), dailyRecord.getSymptom(), dailyRecord.getLifeStatus(), dailyRecord.getDate());
}
@Override
public List<DailyRecord> getLatest3Record(String patientId) {
String sql = "SELECT * FROM daily_record WHERE patientId = ? ORDER BY date DESC LIMIT 3";
return getForList(sql, patientId);
}
}
|
package com.baizhi.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.baizhi.cache.RedisCacheManager;
import com.baizhi.shiro.realm.UserRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
//创建shiroFilter
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
//配置系统公共资源
Map<String,String> map = new HashMap<>();
map.put("/index","anon");
map.put("/user/**","anon");
map.put("/register","anon");
map.put("/**","authc");
//修改默认认证界面
shiroFilterFactoryBean.setLoginUrl("/index");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
//创建web管理器
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
//给安全管理器设置realm
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
//创建自定义realm
@Bean
public Realm getRealm(){
UserRealm userRealm = new UserRealm();
//设置hashed凭证匹配器
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
//设置MD5加密
credentialsMatcher.setHashAlgorithmName("md5");
//设置散列次数
credentialsMatcher.setHashIterations(1024);
userRealm.setCredentialsMatcher(credentialsMatcher);
//开启缓存管理器
userRealm.setCacheManager(new RedisCacheManager());
userRealm.setCachingEnabled(true);
userRealm.setAuthorizationCachingEnabled(true);
userRealm.setAuthorizationCacheName("authorizationCach");
userRealm.setAuthenticationCachingEnabled(true);
userRealm.setAuthenticationCacheName("authenticationCache");
return userRealm;
}
@Bean(name = "shiroDialect")
public ShiroDialect shiroDialect(){
return new ShiroDialect();
}
}
|
package future.test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FutureGetTimeout1 {
public static void main(String[] args){
int timeout = 20;
ExecutorService executor = Executors.newSingleThreadExecutor();
Boolean result = false;
Future<Boolean> future = executor.submit(new TaskThread("发送请求"));//将任务提交给线程池
try {
result = future.get(timeout, TimeUnit.SECONDS);
// result = future.get(timeout, TimeUnit.MILLISECONDS); //1
System.out.println("发送请求任务的返回结果: "+result); //2
} catch (InterruptedException e) {
System.out.println("线程中断出错。");
future.cancel(true);// 中断执行此任务的线程
} catch (ExecutionException e) {
System.out.println("线程服务出错。");
future.cancel(true);
} catch (TimeoutException e) {// 超时异常
System.out.println("超时。");
future.cancel(true);
}finally{
System.out.println("线程服务关闭。");
executor.shutdown();
}
}
static class TaskThread implements Callable<Boolean> {
private String t;
public TaskThread(String temp){
this.t= temp;
}
public Boolean call() throws Exception{
//for用于模拟超时
for(int i=0;i<999999999;i++){
Thread.currentThread().sleep(1000);
if(i==999999998){
//throw new TimeoutException();
System.out.println(t+"成功!");
}
if (Thread.interrupted()){ //很重要
return false;
}
}
System.out.println("继续执行..........");
return true;
}
}
}
|
package com.its.dao;
import java.util.List;
import com.its.entities.Rol;
public interface RolDao {
public List<Rol> list();
}
|
//package com.union.express.web.oauth.security;
//
//import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
//import org.springframework.security.oauth2.provider.ClientDetails;
//import org.springframework.security.oauth2.provider.NoSuchClientException;
//import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
//
//import javax.sql.DataSource;
//
///**
// * @author linaz
// * @created 2016.08.24 15:25
// */
//public class ClientDetailsService extends JdbcClientDetailsService {
//
//
//
// public ClientDetailsService(DataSource dataSource) {
// super(dataSource);
// }
//
//
// @Override
// public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException {
// return super.loadClientByClientId(clientId);
// }
//
//
// @Override
// public void updateClientDetails(ClientDetails clientDetails) throws NoSuchClientException {
// super.updateClientDetails(clientDetails);
// }
//
// @Override
// public void updateClientSecret(String clientId, String secret) throws NoSuchClientException {
// super.updateClientSecret(clientId, secret);
// }
//
// @Override
// public void removeClientDetails(String clientId) throws NoSuchClientException {
// super.removeClientDetails(clientId);
// }
//}
|
package com.example.apprunner.Organizer.menu3_check_payment.Activity;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.apprunner.Login.LoginActivity;
import com.example.apprunner.Login.RegisterappActivity;
import com.example.apprunner.Organizer.menu1_home.Activity.MainActivity;
import com.example.apprunner.Organizer.menu1_home.Fragment.MainFragment;
import com.example.apprunner.OrganizerAPI;
import com.example.apprunner.R;
import com.example.apprunner.ResultQuery;
import com.squareup.picasso.Picasso;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class DetailSubmitPaymentActivity extends AppCompatActivity {
String first_name,last_name,type,name_event;
int id_user_run,id_add,id_user_organizer;
TextView edt_FName,edt_LName,edt_date,edt_time,edt_bank;
ImageView edt_Pic;
Button btn_summit,btn_cancel;
int id_reg_event,id_history_payment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_submit_payment);
id_user_organizer = getIntent().getExtras().getInt("id_user_organizer");
id_user_run = getIntent().getExtras().getInt("id_user_run");
first_name = getIntent().getExtras().getString("first_name");
last_name = getIntent().getExtras().getString("last_name");
type = getIntent().getExtras().getString("type");
name_event = getIntent().getExtras().getString("name_event");
id_add = getIntent().getExtras().getInt("id_add");
id_reg_event = getIntent().getExtras().getInt("id_reg_event");
id_history_payment = getIntent().getExtras().getInt("id_history_payment");
edt_FName = findViewById(R.id.edt_FName);
edt_LName = findViewById(R.id.edt_LName);
edt_date = findViewById(R.id.edt_date);
edt_time = findViewById(R.id.edt_time);
edt_bank = findViewById(R.id.edt_bank);
edt_Pic = findViewById(R.id.edt_Pic);
btn_summit = findViewById(R.id.btn_summit);
btn_cancel = findViewById(R.id.btn_cancel);
// Toast.makeText(DetailSubmitPaymentActivity.this, Integer.toString(id_history_payment), Toast.LENGTH_LONG).show();
setName();
setDetail_payment();
getId_reg_event();
btn_summit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showAlertDialog_submit(view);
}
});
btn_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(DetailSubmitPaymentActivity.this, DetailCancelActivity.class);
intent.putExtra("first_name", first_name);
intent.putExtra("last_name", last_name);
intent.putExtra("type", type);
intent.putExtra("id_user", id_user_organizer);
intent.putExtra("id_add", id_add);
intent.putExtra("name_event", name_event);
intent.putExtra("id_history_payment",id_history_payment);
startActivity(intent);
}
});
}
public void showAlertDialog_submit(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("ยืนยันข้อมูล");
alert.setMessage("คุณต้องการยืนยันการอนุมัติการชำระใช่หรือไม่");
alert.setPositiveButton("ใช่", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
approve_history_payment(id_history_payment,id_reg_event);
}
});
alert.setNegativeButton("ไม่", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alert.create().show();
}
// public void showAlertDialog_cancel(View view) {
// AlertDialog.Builder alert = new AlertDialog.Builder(this);
// alert.setTitle("ยืนยันข้อมูล");
// alert.setMessage("คุณต้องการยืนยันการไม่อนุมัติการชำระใช่หรือไม่");
// alert.setPositiveButton("ใช่", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialogInterface, int i) {
// cancel_history_payment(id_history_payment,id_reg_event);
// }
// });
// alert.setNegativeButton("ไม่", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialogInterface, int i) {
// }
// });
// alert.create().show();
// }
// private void cancel_payment(int id_reg_event) {
// MainFragment mainFragament = new MainFragment();
// Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(mainFragament.url)
// .addConverterFactory(GsonConverterFactory.create())
// .build();
// OrganizerAPI service = retrofit.create(OrganizerAPI.class);
// Call<ResultQuery> call = service.cancel_payment(id_reg_event);
// call.enqueue(new Callback<ResultQuery>() {
// @Override
// public void onResponse(Call<ResultQuery> call, Response<ResultQuery> response) {
// Intent intent = new Intent(DetailSubmitPaymentActivity.this, DetailCancelActivity.class);
// intent.putExtra("first_name", first_name);
// intent.putExtra("last_name", last_name);
// intent.putExtra("type", type);
// intent.putExtra("id_user", id_user_organizer);
// intent.putExtra("id_add", id_add);
// intent.putExtra("name_event", name_event);
// startActivity(intent);
// Toast.makeText(DetailSubmitPaymentActivity.this, "บันทึกข้อมูลสำเร็จ" , Toast.LENGTH_LONG).show();
// }
//
// @Override
// public void onFailure(Call<ResultQuery> call, Throwable t) {
//
// }
// });
// }
//
// private void cancel_history_payment(int id_history_payment,final int id_reg_event) {
// MainFragment mainFragament = new MainFragment();
// Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(mainFragament.url)
// .addConverterFactory(GsonConverterFactory.create())
// .build();
// OrganizerAPI service = retrofit.create(OrganizerAPI.class);
// Call<ResultQuery> call = service.cancel_history_payment(id_history_payment);
// call.enqueue(new Callback<ResultQuery>() {
// @Override
// public void onResponse(Call<ResultQuery> call, Response<ResultQuery> response) {
// cancel_payment(id_reg_event);
// }
//
// @Override
// public void onFailure(Call<ResultQuery> call, Throwable t) {
//
// }
// });
// }
private void approve_history_payment(int id_history_payment,final int id_reg_event){
MainFragment mainFragament = new MainFragment();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(mainFragament.url)
.addConverterFactory(GsonConverterFactory.create())
.build();
OrganizerAPI service = retrofit.create(OrganizerAPI.class);
Call<ResultQuery> call = service.approve_history_payment(id_history_payment);
call.enqueue(new Callback<ResultQuery>() {
@Override
public void onResponse(Call<ResultQuery> call, Response<ResultQuery> response) {
summit_payment(id_reg_event);
}
@Override
public void onFailure(Call<ResultQuery> call, Throwable t) {
}
});
}
private void summit_payment(int id_reg_event){
MainFragment mainFragament = new MainFragment();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(mainFragament.url)
.addConverterFactory(GsonConverterFactory.create())
.build();
OrganizerAPI service = retrofit.create(OrganizerAPI.class);
Call<ResultQuery> call = service.summit_payment(id_reg_event);
call.enqueue(new Callback<ResultQuery>() {
@Override
public void onResponse(Call<ResultQuery> call, Response<ResultQuery> response) {
Intent intent = new Intent(DetailSubmitPaymentActivity.this, MainActivity.class);
intent.putExtra("first_name", first_name);
intent.putExtra("last_name", last_name);
intent.putExtra("type", type);
intent.putExtra("id_user", id_user_organizer);
intent.putExtra("id_add", id_add);
intent.putExtra("name_event", name_event);
startActivity(intent);
Toast.makeText(DetailSubmitPaymentActivity.this, "บันทึกข้อมูลสำเร็จ" , Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<ResultQuery> call, Throwable t) {
}
});
}
private void setDetail_payment(){
MainFragment mainFragament = new MainFragment();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(mainFragament.url)
.addConverterFactory(GsonConverterFactory.create())
.build();
OrganizerAPI service = retrofit.create(OrganizerAPI.class);
Call<ResultQuery> call = service.show_history_user_payment(id_history_payment);
call.enqueue(new Callback<ResultQuery>() {
@Override
public void onResponse(Call<ResultQuery> call, Response<ResultQuery> response) {
ResultQuery resultQuery = (ResultQuery) response.body();
edt_date.setText(resultQuery.getDate());
edt_time.setText(resultQuery.getTime());
edt_bank.setText(resultQuery.getBank());
Picasso.with(DetailSubmitPaymentActivity.this).load(resultQuery.getImage_link()).into(edt_Pic);
}
@Override
public void onFailure(Call<ResultQuery> call, Throwable t) {
}
});
}
private void getId_reg_event(){
MainFragment mainFragament = new MainFragment();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(mainFragament.url)
.addConverterFactory(GsonConverterFactory.create())
.build();
OrganizerAPI service = retrofit.create(OrganizerAPI.class);
Call<ResultQuery> call = service.getId_reg_event(id_user_run,id_add);
call.enqueue(new Callback<ResultQuery>() {
@Override
public void onResponse(Call<ResultQuery> call, Response<ResultQuery> response) {
ResultQuery resultQuery = (ResultQuery) response.body();
id_reg_event = resultQuery.getId_reg_event();
//Toast.makeText(DetailSubmitPaymentActivity.this,Integer.toString(id_reg_event),Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<ResultQuery> call, Throwable t) {
}
});
}
private void setName(){
MainFragment mainFragament = new MainFragment();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(mainFragament.url)
.addConverterFactory(GsonConverterFactory.create())
.build();
OrganizerAPI service = retrofit.create(OrganizerAPI.class);
Call<ResultQuery> call = service.setName(id_user_run);
call.enqueue(new Callback<ResultQuery>() {
@Override
public void onResponse(Call<ResultQuery> call, Response<ResultQuery> response) {
ResultQuery resultQuery = (ResultQuery) response.body();
edt_FName.setText(resultQuery.getFirst_name());
edt_LName.setText(resultQuery.getLast_name());
}
@Override
public void onFailure(Call<ResultQuery> call, Throwable t) {
}
});
}
}
|
// LANGUAGE: Java
// AUTHOR: Gleb Ermolaev
// GITHUB: https://github.com/Ermolaeff
//
//This script takes the name of the user as an input
//and greets him after that.
import java.util.Scanner;
public class Hello_World {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
System.out.println("Hello, " + name);
}
}
|
package com.algaworks.algamoney.api.data.entity;
import lombok.*;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author jsilva on 07/11/2019
*/
@Entity
@Table(name = "permission")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@EqualsAndHashCode(of = {"id"})
public class PermissionEntity {
@Id
@Column(name = "id")
private Long id;
@Column(name = "description")
private String description;
}
|
package myMath;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.function.Predicate;
import javax.management.RuntimeErrorException;
import myMath.Monom;
/**
* This class represents a Polynom with add, multiply functionality, it also should support the following:
* 1. Riemann's Integral: https://en.wikipedia.org/wiki/Riemann_integral
* 2. Finding a numerical value between two values (currently support root only f(x)=0).
* 3. Derivative
*
* @author Boaz
*
*/
/**
*
* @author Shalhevet and Neomi
*
*/
public class Polynom implements Polynom_able{
private final Monom_Comperator compare= new Monom_Comperator();
private ArrayList<Monom> polynom;
/**
* Default constructor
* An empty polynom is a polynom equal to 0
*/
public Polynom(){
polynom = new ArrayList<Monom>();
Monom m= new Monom (0,0);
polynom.add(m);
}
/**
* Copy Constructor
* @param p
*/
public Polynom (Polynom p){
this.polynom=new ArrayList<Monom>();
Iterator<Monom> itp = p.iteretor();
while(itp.hasNext()){
Monom m1 = itp.next();
this.add(new Monom(m1));
}
}
/**
* The function accepts x value and sets it in a Monom and return sum
*/
@Override
public double f(double x){
double sum = 0;
Iterator<Monom> iter = this.iteretor();
while(iter.hasNext()){
Monom m1 = iter.next();
sum = sum + m1.f(x) ;
}
return sum;
}
/**
* string constructor
* @param s
*/
public Polynom(String s) {
this.polynom=new ArrayList<Monom>();
String m ="";
String s1 = "";
for(int i = 0 ; i<s.length(); i++ ) {
if((s.charAt(i)=='-' ) && (i!=0)) {
s1 = s1 +"+"+ s.charAt(i);}
else {
s1= s1 + s.charAt(i); }}
s = s1 + "+";
for(int i=0; i<s.length();) {
m =s.substring(0 , s.indexOf('+'));
for(int k= 0; k<m.length() ; k++) {
if(m.charAt(k) == ' ') {
m = m.substring(k+1);
}
else {
break;}}
for(int l=m.length()-1 ; l>-1 ;l-- ) {
if(m.charAt(l) == ' ') {
m = m.substring(0,l);}
else {
break; }}
s = s.substring (s.indexOf('+') + 1, s.length());
Monom m1=new Monom(m);
add(m1); }}
/**
* Add polynom able to this Polynom
*/
@Override
public void add(Polynom_able p1) {
Iterator<Monom> itrp1 = p1.iteretor();
while (itrp1.hasNext()) {
Monom m1 = itrp1.next();
add(m1);
}
}
/**
* Add Monom m1 this Polynom
*/
@Override
public void add(Monom m1) {
boolean add = false;
Iterator<Monom> iter = this.iteretor();
while(( add == false) && (iter.hasNext())) {
Monom m2 =iter.next();
if(m2.get_power()==m1.get_power()) {
m2.add(m1);
add = true;
}
if(m2.get_coefficient()==0) {
iter.remove();
}
}
if (add == false) {
polynom.add(m1);
this.polynom.sort(compare); }}
/**
* substract between this polynom to Polynom_able p1
*/
@Override
public void substract(Polynom_able p1) {
Iterator<Monom> itrp1 =p1.iteretor();
while (itrp1.hasNext()) {
Monom m2=itrp1.next();
double a = ((m2.get_coefficient())* (-1));
int b = m2.get_power();
Monom n1 = new Monom (a,b);
add(n1);
}}
/**
* multiply between this polynom with Polynom_able p1
*/
@Override
public void multiply(Polynom_able p1) {
Polynom polynomnew= new Polynom();
Iterator<Monom> itrp1 = p1.iteretor();
while (itrp1.hasNext()) {
Monom n1 = new Monom(itrp1.next());
Iterator<Monom> itr = this.iteretor();
while (itr.hasNext()) {
Monom n3= new Monom (n1);
Monom n2 = new Monom (itr.next());
n3.multiply(n2);
if (n3.get_coefficient()==0)
itr.remove();
polynomnew.add(n3);
//n1=n3;
}
}
this.polynom=polynomnew.polynom;
}
/**
* check if the this polynom is equals to Polynom_able p1
* return true or false
*/
@Override
public boolean equals(Polynom_able p1) {
Iterator<Monom> itrp1 = p1.iteretor();
Iterator<Monom> itr = polynom.iterator();
while (itrp1.hasNext()|| itr.hasNext()) {
if (itrp1.hasNext()==true && itr.hasNext()==false) {
return false;
}
if (itrp1.hasNext()==false && itr.hasNext()==true) {
return false;
}
Monom n1 = itrp1.next();
Monom n2 = itr.next();
if (n1.get_coefficient()!= n2.get_coefficient()|| n1.get_power()!=n2.get_power()) {
return false;
}
}
return true;
}
/**
* check if the polynom equals zero
* return true or false
*/
@Override
public boolean isZero() {
if (this.polynom.size()==0) {
return true;
}
return false;
}
/**
* Compute a value x' (x0<=x'<=x1) for with |f(x')| < eps
*/
@Override
public double root(double x0, double x1, double eps) {
if(f(x0)*f(x1) > 0)
throw new RuntimeException("worng input");
else
{
double x2=(x1+x0)/2;
if(0-eps<=f(x2) && 0+eps>f(x2)) {
return x2;
}
else {
if((f(x2)<0 && f(0)<0)||(f(x2)>0 && f(x0)>0)){
x0=x2;
return root(x0,x1,eps);
}
else {
return root(x0,x2,eps);
}}}}
@Override
/**
* copy the Polynom_able
*/
public Polynom_able copy() {
Polynom_able ablep1= new Polynom();
Iterator<Monom> itr = polynom.iterator();
while(itr.hasNext()) {
Monom m1= itr.next();
ablep1.add(m1);
}
return ablep1;
}
@Override
/**
* derivative of the Polynom_able
*/
public Polynom_able derivative() {
Polynom_able ablep1= new Polynom();
Iterator<Monom> itr= iteretor();
while(itr.hasNext()) {
Monom m1= new Monom(itr.next());
Monom m2= new Monom ();
m2=m1.derivative();
ablep1.add(m2);
}
return ablep1;
}
@Override
/**
* Compute Riemann's Integral over this Polynom starting from x0, till x1 using eps size steps
*/
public double area(double x0, double x1, double eps) {
if (x0>x1) {
throw new RuntimeException("worng input");
}
double area=0;
while (x0<=x1) {
if (f(x0)<0) {
x0=x0+eps;
}
else {
area= area + (f(x0)*eps);
x0=x0+eps;
}
}
return area;
}
@Override
/**
* return iteretor of the this polynom
*/
public Iterator<Monom> iteretor() {
return this.polynom.iterator();
}
/**
* function get Polynom
* Returns the ArrayList of Polynom
* @return
*/
public ArrayList<Monom> getPolynom() {
return polynom;
}
/**
* function toString
*/
public String toString(){
String ans = "";
Iterator<Monom> it = polynom.iterator();
if(!it.hasNext()) {
return "0";
}
ans= ans+it.next();
while(it.hasNext())
{
Monom m1 = it.next();
if(m1.get_coefficient()>0) {
ans= ans+" + "+m1.toString();
}
else {
ans= ans+" "+ m1.toString();
}
}
if (ans!="") {
return ans;
}
else {
return 0+"";
}
}}
|
package com.qx.wechat.comm.sdk.request.msg.action;
import java.util.List;
import com.qx.wechat.comm.sdk.request.msg.PassiveMsgType;
public class PassiveGroupCreationActionMsg extends PassiveActionMsg{
private static final long serialVersionUID = 2765534130813027698L;
public PassiveGroupCreationActionMsg() {
this.setType(PassiveMsgType.ROBOT_CREATE_GROUP_MSG.getValue());
}
private String friends;
public String getFriends() {
return friends;
}
public PassiveGroupCreationActionMsg setFriends(List<String> friends) {
this.friends = friends.toString();
return this;
}
}
|
package com.nbu.barker;
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.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class RegisterActivity extends AppCompatActivity {
EditText etEmail = null;
EditText etNames = null;
EditText etPassword = null;
EditText etUsername = null;
TextView tRegistrationErrors = null;
Button bRegister = null;
Button bCancel = null;
private String m_sResponse = "";
@Override
public void onBackPressed() {
returnToMainMenu();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etEmail = (EditText) findViewById(R.id.etEmail);
etNames = (EditText) findViewById(R.id.etNames);
etPassword = (EditText) findViewById(R.id.etPassword);
tRegistrationErrors = (TextView) findViewById(R.id.tRegisterErrors);
etUsername = findViewById(R.id.etRegisterUsername);
bRegister = (Button) findViewById(R.id.bRegisterSend);
bCancel = findViewById(R.id.bCancel);
bRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bRegister.setClickable(false);
bCancel.setClickable(false);
String sEmail = etEmail.getText().toString();
String sPassword = etPassword.getText().toString();
String sNames = etNames.getText().toString();
String sUsername = etUsername.getText().toString();
String sRegistrationErrors = Tools.validateProfileParameters( sEmail ,sUsername,sNames,sPassword);
if(!sRegistrationErrors.isEmpty()) {
Log.println(Log.ERROR,"bRegister.onClickListener", "Registration errors not empty." +
"Errors:" + sRegistrationErrors);
tRegistrationErrors.setText(sRegistrationErrors);
bRegister.setClickable(true);
bCancel.setClickable(true);
}
else
{
Log.println(Log.INFO,"bRegister.onClickListener", "Registration to be created and send");
String sPasswordHashed = Tools.hashPassword(sPassword,"SHA-256");
Log.println(Log.INFO,"bRegister.onClickListener", "Password Hashed is: " + sPasswordHashed);
String sXML = " <Barker requestType=\"register\">\r\n" +
" <register>\r\n" +
" <username>" + sUsername + "</username>\r\n"+
" <name>" + sNames + "</name>\r\n" +
" <password>" + sPasswordHashed + "</password>\r\n" +
" <email>" + sEmail + "</email>\r\n" +
" </register>\r\n" +
" </Barker>\r\n";
Log.println(Log.INFO,"bRegister.onClickListener", "XML Created is: " + sXML);
String sResponse = "";
String sStatusCode = "";
try
{
sResponse = Tools.sendRequest(sXML);
Log.println(Log.ERROR, "Response is: ", sResponse);
if(sResponse == "Error" || sResponse.isEmpty())
{
tRegistrationErrors.setText("There was an internal error while parsing your registration");
bRegister.setClickable(true);
bCancel.setClickable(true);
return;
}
Document pDoc= null;
DocumentBuilder pBuilder = null;
DocumentBuilderFactory pFactory = DocumentBuilderFactory.newInstance();
pBuilder = pFactory.newDocumentBuilder();
pDoc = pBuilder.parse( new InputSource( new StringReader(sResponse)) );
XPathFactory pXpathFactory = XPathFactory.newInstance();
XPath pXpath = pXpathFactory.newXPath();
XPathExpression pExp = null;
pExp = pXpath.compile("Barker/statusCode");
sStatusCode = (String)pExp.evaluate( pDoc, XPathConstants.STRING );
}
catch(Exception e)
{
bRegister.setClickable(true);
bCancel.setClickable(true);
Log.println(Log.ERROR,"Registration error", e.getMessage());
return;
}
//success
if(sStatusCode.equals("200"))
{
returnToMainMenu("Registration success");
}
//user already exists
else if(sStatusCode.equals("402"))
{
bRegister.setClickable(true);
bCancel.setClickable(true);
Toast.makeText(RegisterActivity.this, "User with such email already exists", Toast.LENGTH_SHORT).show();
}
//all other general types of errors
else
{
bRegister.setClickable(true);
bCancel.setClickable(true);
returnToMainMenu("There was an error with your request. Please try again later");
}
Log.println(Log.ERROR,"helloWorld", "Response is: " + sResponse);
}
}
});
bCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
returnToMainMenu();
}
});
}
private void returnToMainMenu() {
Intent pMainIntent = new Intent(this, MainActivity.class);
startActivity(pMainIntent);
}
private void returnToMainMenu(String sMessage) {
Intent pMainIntent = new Intent(this, MainActivity.class);
pMainIntent.putExtra("message", sMessage);
startActivity(pMainIntent);
}
}
|
package com.siokagami.application.mytomato.bean;
/**
* Created by siokagami on 16/12/28.
*/
public class UserProfileQuery extends BaseQuery {
public String nickname;
public int sex;
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
}
|
package com.mycompany.myapp;
import android.content.*;
import android.opengl.GLSurfaceView.*;
import com.mycompany.myapp.util.*;
import java.nio.*;
import javax.microedition.khronos.egl.*;
import javax.microedition.khronos.opengles.*;
import static android.opengl.GLES20.*;
public class AirHockeyRenderer implements Renderer {
private static final int POSITION_COMPONENT_COUNT=2;
private static final int BYTES_PER_FLOAT=4;
private static FloatBuffer vertexData;
private final Context context;
private int program;
private static final String U_COLOR = "u_Color";
private int uColorLocation;
private static final String A_POSITION = "a_Position";
private int aPositionLocation;
public AirHockeyRenderer(Context context){
this.context = context;
float[] tableVerticesWithTriangle={
0.9f, 0.9f,
-0.9f, 0.9f,
0.9f, -0.9f,
-0.9f, -0.9f,
-0.9f, 0.9f,
0.9f, -0.9f,
0.8f, 0.8f,
-0.8f, 0.8f,
0.8f, -0.8f,
-0.8f, -0.8f,
-0.8f, 0.8f,
0.8f, -0.8f,
0.7f, 0.7f,
-0.7f, 0.7f,
0.7f, -0.7f,
-0.7f, -0.7f,
-0.7f, 0.7f,
0.7f, -0.7f,
0.6f, 0.6f,
-0.6f, 0.6f,
0.6f, -0.6f,
-0.6f, -0.6f,
-0.6f, 0.6f,
0.6f, -0.6f,
0.5f, 0.5f,
-0.5f, 0.5f,
0.5f, -0.5f,
-0.5f, -0.5f,
-0.5f, 0.5f,
0.5f, -0.5f,
0.4f, 0.4f,
-0.4f, 0.4f,
0.4f, -0.4f,
-0.4f, -0.4f,
-0.4f, 0.4f,
0.4f, -0.4f,
0.3f, 0.3f,
-0.3f, 0.3f,
0.3f, -0.3f,
-0.3f, -0.3f,
-0.3f, 0.3f,
0.3f, -0.3f,
0.2f, 0.2f,
-0.2f, 0.2f,
0.2f, -0.2f,
-0.2f, -0.2f,
-0.2f, 0.2f,
0.2f, -0.2f,
0.14f, 0.14f,
-0.14f, 0.14f,
0.14f, -0.14f,
-0.14f, -0.14f,
-0.14f, 0.14f,
0.14f, -0.14f,
0.04f, 0.04f,
-0.04f, 0.04f,
0.04f, -0.04f,
-0.04f, -0.04f,
-0.04f, 0.04f,
0.04f, -0.04f,
};
vertexData=ByteBuffer
.allocateDirect(tableVerticesWithTriangle.length * BYTES_PER_FLOAT)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
vertexData.put(tableVerticesWithTriangle);
}
@Override
public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
// Set the background clear color to red. The first component is
// red, the second is green, the third is blue, and the last
// component is alpha, which we don'ta use in this lesson.
glClearColor(0.0f, 1.0f, 0.0f, 0.0f);
String vertexShaderSource = TextResourceReader
.readTextFileFromResource(context,R.raw.simple_vertex_shader);
String fragmentShaderSource = TextResourceReader
.readTextFileFromResource(context,R.raw.simple_fragment_shader);
int vertexShader = ShaderHelper.compileVertexShader(vertexShaderSource);
int fragmentShader = ShaderHelper.compileFragmentShader(fragmentShaderSource);
program = ShaderHelper.linkProgram(vertexShader,fragmentShader);
if(LoggerConfig.ON){
ShaderHelper.validateProgram(program);
}
glUseProgram(program);
uColorLocation = glGetUniformLocation(program,U_COLOR);
aPositionLocation = glGetAttribLocation(program,A_POSITION);
vertexData.position(0);
glVertexAttribPointer(aPositionLocation,POSITION_COMPONENT_COUNT,
GL_FLOAT,false,0,vertexData);
glEnableVertexAttribArray(aPositionLocation);
}
/**
* onSurfaceChanged is called whenever the surface has changed. This is
* called at least once when the surface is initialized. Keep in mind that
* Android normally restarts an Activity on rotation, and in that case, the
* renderer will be destroyed and a new one created.
*
* @param width
* The new width, in pixels.
* @param height
* The new height, in pixels.
*/
@Override
public void onSurfaceChanged(GL10 glUnused, int width, int height) {
// Set the OpenGL viewport to fill the entire surface.
glViewport(0, 0, width, height);
}
/**
* OnDrawFrame is called whenever a new frame needs to be drawn. Normally,
* this is done at the refresh rate of the screen.
*/
@Override
public void onDrawFrame(GL10 glUnused) {
// Clear the rendering surface.
glClear(GL_COLOR_BUFFER_BIT);
glUniform4f(uColorLocation, 1.f, 0.0f, 0.0f, 1.0f);
glDrawArrays(GL_TRIANGLES, 0, 6);
glUniform4f(uColorLocation, 0.5f, 0.2f, 0.3f, 1.0f);
glDrawArrays(GL_TRIANGLES, 6, 6);
glUniform4f(uColorLocation, 0.0f, 1.0f, 0.3f, 1.0f);
glDrawArrays(GL_TRIANGLES, 12, 6);
glUniform4f(uColorLocation, 1.0f, 0.0f, 0.0f, 1.0f);
glDrawArrays(GL_TRIANGLES, 18, 6);
glUniform4f(uColorLocation, 0.0f, 1.0f, 1.0f, 1.0f);
glDrawArrays(GL_TRIANGLES, 24, 6);
glUniform4f(uColorLocation, 0.0f, 1.0f, 0.0f, 1.0f);
glDrawArrays(GL_TRIANGLES, 30, 6);
glUniform4f(uColorLocation, 0.0f, 0.0f, 1.0f, 1.0f);
glDrawArrays(GL_TRIANGLES, 36, 6);
glUniform4f(uColorLocation, 0.0f, 0.7f, 0.0f, 1.0f);
glDrawArrays(GL_TRIANGLES, 42, 6);
glUniform4f(uColorLocation, 0.2f, 0.5f, 0.0f, 0.0f);
glDrawArrays(GL_TRIANGLES, 48, 6);
glUniform4f(uColorLocation, 0.0f, 0.0f, 0.0f, 1.0f);
glDrawArrays(GL_TRIANGLES, 54, 6);
}
}
|
package com.amazonaws.xray.strategy;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.amazonaws.xray.emitters.Emitter;
import com.amazonaws.xray.entities.Entity;
import com.amazonaws.xray.entities.Segment;
import com.amazonaws.xray.entities.Subsegment;
public class DefaultStreamingStrategy implements StreamingStrategy {
private static final Log logger =
LogFactory.getLog(DefaultStreamingStrategy.class);
private static final int DEFAULT_MAX_SEGMENT_SIZE = 100;
private final int maxSegmentSize;
/**
* {@inheritDoc}
*
* Constructs an instance of DefaultStreamingStrategy using the default {@code maxSegmentSize} of 100.
*
*/
public DefaultStreamingStrategy() {
this(DEFAULT_MAX_SEGMENT_SIZE);
}
/**
* {@inheritDoc}
*
* Constructs an instance of DefaultStreamingStrategy using the provided {@code maxSegmentSize}.
*
* @param maxSegmentSize
* the maximum number of subsegment nodes a segment tree may have before {@code requiresStreaming} will return true
*
* @throws IllegalArgumentException
* when {@code maxSegmentSize} is a negative integer
*
*/
public DefaultStreamingStrategy(int maxSegmentSize) {
if (maxSegmentSize < 0) {
throw new IllegalArgumentException("maxSegmentSize must be a non-negative integer.");
}
this.maxSegmentSize = maxSegmentSize;
}
/**
* {@inheritDoc}
*
* Indicates that the provided segment requires streaming when it has been marked for sampling and its tree of subsegments reaches a size greater than {@code maxSegmentSize}.
*
* @see StreamingStrategy#requiresStreaming(Segment)
*/
public boolean requiresStreaming(Segment segment) {
if (segment.isSampled() && null != segment.getTotalSize()) {
return segment.getTotalSize().intValue() > maxSegmentSize;
}
return false;
}
/**
* {@inheritDoc}
*
* Performs a depth first search to find completed subsegment subtrees. Serializes these subsegments, streams them to the daemon, and removes them from their parents.
*
* @see StreamingStrategy#streamSome(Entity,Emitter)
*/
public void streamSome(Entity entity, Emitter emitter) {
if (entity.getSubsegmentsLock().tryLock()) {
try {
//copy before traversal to avoid ConcurrentModificationExceptions
new ArrayList<Subsegment>(entity.getSubsegments()).forEach( (subsegment) -> {
if (subsegment.isInProgress() || !subsegment.getSubsegments().isEmpty()) {
streamSome(subsegment, emitter);
} else {
emitter.sendSubsegment(subsegment);
subsegment.setEmitted(true);
entity.removeSubsegment(subsegment);
}
});
} finally {
entity.getSubsegmentsLock().unlock();
}
}
}
}
|
package exercicios.aula09.q1;
import java.util.ArrayList;
public abstract class Funcionario {
protected String nome;
protected String CPF;
public Funcionario(String nome, String CPF) {
this.nome = nome;
this.CPF = CPF;
}
public abstract double getRemuneracao();
public String getNome() {
return nome;
}
public String getCPF() {
return CPF;
}
@Override
public String toString() {
return this.getClass().getSimpleName() + " [nome=" + nome + ", CPF=" + CPF
+ ", Remuneracao= " + this.getRemuneracao() + "]";
}
public static void main(String[] args) {
ArrayList<Funcionario> funcionarios = new ArrayList<Funcionario>();
Funcionario f1 = new FuncionarioSalarioFixo("Func1", "473.517.620-90", 2000);
funcionarios.add(f1);
FuncionarioHoraExtra f2 = new FuncionarioHoraExtra("Func2", "379.828.610-83", 5000);
f2.setHorasExtras(10);
funcionarios.add(f2);
FuncionarioComissionado f3 = new FuncionarioComissionado("Func3", "926.379.780-31", 0.10);
f3.setTotalVendas(50000);
funcionarios.add(f3);
FuncionarioComissionadoComSalarioBase f4 =
new FuncionarioComissionadoComSalarioBase("Func4", "380.769.650-47", 0.15, 4000);
f4.setTotalVendas(100000);
funcionarios.add(f4);
for(Funcionario funcionario : funcionarios) {
System.out.println(funcionario);
}
}
}
|
package com.dmtrdev.monsters.sprites.armors.ground;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Shape2D;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.dmtrdev.monsters.DefenderOfNature;
import com.dmtrdev.monsters.consts.ConstArmor;
import com.dmtrdev.monsters.consts.ConstEnemies;
import com.dmtrdev.monsters.consts.ConstGame;
import com.dmtrdev.monsters.screens.PlayScreen;
import com.dmtrdev.monsters.sprites.armors.Armor;
public class Stone extends Armor {
private final Vector3 vector3;
private boolean mFlag;
private final PlayScreen mPlayScreen;
public Stone(final PlayScreen pPlayScreen, final float pX, final float pY, final boolean pDirection) {
super(pPlayScreen, pX, pY, pDirection);
vector3 = new Vector3();
mFlag = false;
mPlayScreen = pPlayScreen;
setSize(2.8f, 2.8f);
textureRegion = DefenderOfNature.getArmorsAtlas().findRegion("rock_hanging");
setOriginCenter();
for (int j = 0; j < 22; j++) {
frames.add(new TextureRegion(DefenderOfNature.getEffectsAtlas().findRegion("down_explode"), 0, j * 70, 354, 70));
destroyAnimation = new Animation<TextureRegion>(ConstArmor.EFFECT_SPEED, frames);
}
frames.clear();
if (direction) {
textureRegion.flip(true, false);
}
setRegion(textureRegion);
}
@Override
public void collisionEnemy() {
}
@Override
public void collisionGround() {
setToDestroy = true;
setSize(ConstArmor.EFFECT_MEDIUM_SIZE + 2.3f, ConstArmor.EFFECT_MEDIUM_SIZE - 1.1f);
destroy = false;
}
@Override
public int getArmorDamage() {
return ConstArmor.STONE_TRAP_DAMAGE;
}
@Override
public void update(final float delta) {
if (setToDestroy && effects) {
if (!destroy) {
if (playScreen.getOptions().getSoundCheck()) {
DefenderOfNature.getBigSound().play(playScreen.getOptions().getSoundVolume());
}
setPosition(body.getPosition().x - getWidth() / 2, body.getPosition().y - 1.25f);
world.destroyBody(body);
defineStone();
time = 0;
destroy = true;
} else if (destroyAnimation.isAnimationFinished(time)) {
world.destroyBody(body);
destroyed = true;
}
setRegion(textureRegion = destroyAnimation.getKeyFrame(time));
time += delta;
} else if (setToDestroy) {
world.destroyBody(body);
destroyed = true;
} else if (mFlag) {
setPosition(body.getPosition().x - getWidth() / 2, body.getPosition().y - getHeight() / 2);
if (!destroy) {
world.destroyBody(body);
defineArmor();
destroy = true;
}
} else {
handleInput();
setPosition(body.getPosition().x - getWidth() / 2, body.getPosition().y - getHeight() / 2);
}
}
private void handleInput() {
if (Gdx.input.isTouched()) {
vector3.set(Gdx.input.getX(), Gdx.input.getY(), 0);
mPlayScreen.getCamera().unproject(vector3);
final Shape2D textureBounds = new Rectangle(getX(), getY(), getWidth(), getHeight());
if (textureBounds.contains(vector3.x, vector3.y)) {
mFlag = true;
}
}
}
@Override
protected void defineArmor() {
final BodyDef bodyDef = new BodyDef();
if (!mFlag) {
if (!direction) {
bodyDef.position.set(getX() - 2.1f, getY() + 2.5f);
} else {
bodyDef.position.set(getX() + 2.1f, getY() + 2.5f);
}
bodyDef.type = BodyDef.BodyType.StaticBody;
body = world.createBody(bodyDef);
} else {
bodyDef.position.set(getX() + 1.4f, getY() + 0.5f);
bodyDef.type = BodyDef.BodyType.DynamicBody;
body = world.createBody(bodyDef);
}
final FixtureDef fixtureDef = new FixtureDef();
final PolygonShape shape = new PolygonShape();
shape.setAsBox(ConstArmor.PLANT_BODY_WIDTH - 0.4f, 1.3f);
fixtureDef.shape = shape;
fixtureDef.filter.categoryBits = ConstGame.ARMOR_BIT;
fixtureDef.filter.maskBits = ConstGame.GROUND_BIT;
fixtureDef.density = ConstArmor.PLANT_DENSITY;
body.createFixture(fixtureDef).setUserData(this);
}
private void defineStone() {
final BodyDef bodyDef = new BodyDef();
bodyDef.position.set(getX() + 2.5f, ConstEnemies.SPAWN_HEIGHT + 0.2f);
bodyDef.type = BodyDef.BodyType.StaticBody;
body = world.createBody(bodyDef);
final FixtureDef fixtureDef = new FixtureDef();
final PolygonShape shape = new PolygonShape();
shape.setAsBox(1.8f, 0.2f);
fixtureDef.shape = shape;
fixtureDef.filter.categoryBits = ConstGame.ARMOR_BIT;
fixtureDef.filter.maskBits = ConstGame.ENEMY_BIT;
fixtureDef.density = ConstArmor.PLANT_DENSITY;
body.createFixture(fixtureDef).setUserData(this);
}
}
|
package visitor;
import controller.Game;
/**
* Visitor used to add score to a game.
* When a hittable object is hit, and therefore a score is to be added to the game,
* this class is used to communicate the value to be added, in order to maintain
* class privacy.
*
* @author Gabriel Chaperon
*/
public class AddScoreVisitor extends Visitor {
private int score;
public AddScoreVisitor(int score) {
this.score = score;
}
@Override
public void visitGame(Game game) {
game.addScore(this.score);
}
}
|
package com.tide.demo04;
import java.util.ArrayList;
public class Demo06ArrayListPrint {
public static void main(String[] args) {
ArrayList<Integer> array=new ArrayList<>();
array.add(100);
array.add(120);
array.add(50);
array.add(55);
array.add(65);
array.add(30);
array.add(10);
System.out.print("{"+" ");
for (int i=0; i<array.size();i++){
int arr=array.get(i);
System.out.print(arr+" ");
if (i==array.size()-1){
System.out.print("}");
}else {
System.out.print(","+" ");
}
}
}
}
|
package com.example.hante.newprojectsum.meterialdesign;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import com.example.hante.newprojectsum.BaseActivity;
import com.example.hante.newprojectsum.R;
import com.example.hante.newprojectsum.activitys.WebViewActivity;
import com.example.hante.newprojectsum.common.Constant;
import com.example.hante.newprojectsum.common.ProgressDialogFragment;
import com.example.hante.newprojectsum.custome.TitleBar;
import com.example.hante.newprojectsum.meterialdesign.adapter.ZhihuRecyclerViewAdapter;
import com.example.hante.newprojectsum.meterialdesign.adapter.ZhihuRecyclerViewAdapterReset;
import com.example.hante.newprojectsum.meterialdesign.bean.ZhihuArt;
import com.example.hante.newprojectsum.meterialdesign.bean.ZhihuArticle;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;
/**
* MaterialDesign
*/
public class MaterialDesignAppBarActivity extends BaseActivity {
private static final String TAG = "MaterialDesignAppBarAct";
@Bind(R.id.toolbar_MD)
TitleBar mToolbarMD;
@Bind(R.id.MD_RecyclerView)
RecyclerView mMDRecyclerView;
@Bind(R.id.activity_material_design_app_bar)
CoordinatorLayout mActivityMaterialDesignAppBar;
private ZhihuRecyclerViewAdapter mZhiHuAdapter;
private ArrayList<ZhihuArticle.TopStoriesBean> mZhiHuTopStory;
private ArrayList<ZhihuArticle.StoriesBean> mZhiHuStory;
private ZhihuArticle.StoriesBean mStoriesBean;
private ZhihuArticle.TopStoriesBean mTopStoriesBean;
private List<String> mList;
//
private ArrayList<ZhihuArt> mListZhihu;
private ZhihuArt mZhihuArt;
private ZhihuRecyclerViewAdapterReset mZhihuReset;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_material_design_app_bar);
ButterKnife.bind(this);
initUI();
}
private void initUI () {
setSupportActionBar(mToolbarMD);
if(getSupportActionBar() == null) {
return;
}
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbarMD.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View view) {
finish();
}
});
//如果可以确定每个Item的高度固定,选用这个属性可以提高性能
mMDRecyclerView.setHasFixedSize(true);
//使用默认的LayoutManager
mMDRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mZhiHuTopStory = new ArrayList<>();
mZhiHuStory = new ArrayList<>();
mListZhihu = new ArrayList<>();
loadData();
}
private void recyclerViewItemClick () {
mZhihuReset.setOnItemClickListener(new ZhihuRecyclerViewAdapterReset.onItemClickListener() {
@Override
public void onItemClick (View view, int position) {
String id = mListZhihu.get(position).getmId();
Log.d(TAG, "onItemClick: ID" + id);
String title = mListZhihu.get(position).getmTitle();
Intent intent = new Intent(getApplicationContext(),
WebViewActivity.class);
String url = Constant.ARTICELItem + id;
intent.putExtra("url",
url);
intent.putExtra("title", title);
startActivity(intent);
}
});
}
private void loadData () {
setProgress(true);
AsyncHttpClient client = new AsyncHttpClient();
client.get(Constant.ZHIHUUrl, new JsonHttpResponseHandler(){
@Override
public void onSuccess (int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.d(TAG, "onSuccess: 返回请求" + response.toString());
String backResp = response.toString();
setProgress(false);
try {
JSONObject mJsonObj = new JSONObject(backResp);
String date = mJsonObj.getString("date");// 日期
if(date != null){
mToolbarMD.setMyCenterTitle(date);
}
JSONArray storiesJA = mJsonObj.getJSONArray("stories");
JSONArray top_storiesJA = mJsonObj.getJSONArray("top_stories");
for(int i = 0;i < storiesJA.length(); i ++){
mZhihuArt = new ZhihuArt();
mStoriesBean = new ZhihuArticle.StoriesBean();
JSONObject Sto = storiesJA.getJSONObject(i);
mStoriesBean.setMTitle(Sto.getString("title"));
mZhihuArt.setmTitle(Sto.getString("title"));
mZhihuArt.setmId(Sto.getString("id"));
JSONArray imagesJB = Sto.getJSONArray("images");
mList = new ArrayList<>();
for(int j = 0;j<imagesJB.length();j++){
String string = imagesJB.getString(j);
mZhihuArt.setmImage(string);
mList.add(string);
}
mStoriesBean.setMImages(mList);
mListZhihu.add(mZhihuArt);
mZhiHuStory.add(mStoriesBean);
}
for(int e = 0; e<top_storiesJA.length(); e++){
JSONObject jsonObjectTop = top_storiesJA.getJSONObject(e);
mTopStoriesBean = new ZhihuArticle.TopStoriesBean();
mZhihuArt = new ZhihuArt();
mTopStoriesBean.setMTitle(jsonObjectTop.getString("title"));
mTopStoriesBean.setMImage(jsonObjectTop.getString("image"));
mZhihuArt.setmImage(jsonObjectTop.getString("image"));
mZhihuArt.setmTitle(jsonObjectTop.getString("title"));
mZhihuArt.setmId(jsonObjectTop.getString("id"));
mZhiHuTopStory.add(mTopStoriesBean);
mListZhihu.add(mZhihuArt);
}
// mZhiHuAdapter = new ZhihuRecyclerViewAdapter(MaterialDesignAppBarActivity.this,
// mZhiHuStory,
// mZhiHuTopStory);
mZhihuReset = new ZhihuRecyclerViewAdapterReset(getApplicationContext(),
mListZhihu);
mMDRecyclerView.setAdapter(mZhihuReset);
recyclerViewItemClick();
} catch(JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure (int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
setProgress(false);
}
});
}
/**
* ProgressDialogFragment
* @param show true/false 进度条是否显示/隐藏
*/
private void setProgress (boolean show){
ProgressDialogFragment progressDialogFragment = new ProgressDialogFragment();
if(show){
progressDialogFragment.setStyle(DialogFragment.STYLE_NO_TITLE,R.style.loading_dialog);
progressDialogFragment.setCancelable(false);
progressDialogFragment.show(getSupportFragmentManager(),"Dialog");
} else {
Fragment dialog = getSupportFragmentManager().findFragmentByTag("Dialog");
if(dialog != null){
ProgressDialogFragment pdf = (ProgressDialogFragment) dialog;
pdf.dismiss();
}
}
}
}
|
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.json.JSONArray;
import org.junit.Test;
import sun.misc.BASE64Decoder;
import java.io.Closeable;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Date;
public class JWTTest {
final static String privateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC5NI/6aKa3wg4a6g3oBCgZmBgUQxbJ1AXwPF1wsS5SicyRtwKAJX84oHZ9KAQRLBVE/UC0dO0DrTPCXQE/Nzv1cG+BDlF86dCDT3IEyy3899bFsKLd6wbJw2yx7XXQpJ0w9QHxQpL697a/JqxE3pigQPmrvlJJyIUwbOUT5PYKsC/B2FjYmLTZzyZ0qBawF1L2NOsR/0I2czdsiwVaztS2ER+CT/uht5Xm3IfDWUPlH1HZhlea0eY9SaHlDvhujXE7Smqzijn/6RVniosdvlqghuuERz3sWrWlC+OmiiDBl1j6N/FewlVJe1U6adUwr6lyIQRdy0YCn4WrNcCtyJMZAgMBAAECggEAeC9883IwJnVes+aJSbRQ1XMWxSdYRXc6t1BlDrlcJyHXSAQsMj6jFXtECSoLoZ0q3E9ASxrJqCYgvZOfOIe+eCMTqPtCtD4DGwNWKXg0isHGdRmQR1S6XfpcsgY3+0Kn41pLfWXHfed8hwUwq6yL/QrNOr9SJSFkFS3FZqihZgMdW3TXwlnCQa7CS3cjrzKLJ1hof2ftgS8oR1ZtsifCUs9zDPjxwIJ3XWrje5+k7vo/OWuoSrgx5GatSeDdClCeUYoqWX87+RAmodyl/MrQYKK3Mpjw7Gte7MaRtoOjJnV/qVK03CYVPlFBhZHU5QalCR+U9AL2EM8fkkSgE30+0QKBgQDy/9KjXFLfLspr5zN9wMTonBSF79zzwp2s3FeA8eRO3ZkWlUPQ95n2D9hCSqKQmTpZFJBCbiu8JxS8eRmBoUOe6Q2DA4816D4s1+MyW6PIKUpzzmG+F+zjwq4BZQMPb28LVK7DLFxYL6vPKXkMvZ9miKslc7PIMr9zcYoh8t2WrQKBgQDDHS3hmcJCKlv35SfkGOu40/NDKrcTtts+sQbjl2hKLXn99L8T3DbMYNkO/JYesoAaY81vbvGuLety9YUQWzXYZmBAciIrZDdCVbDk+NPa3VrqND5J59iKybhiBIfbtJIyPcPL5oxJs5qXAYEvpz+obk+2kx+oysUJIjMRJxQ3nQKBgBRrQMTvZhtQ8Dt+8wm3IBS3wNW8YSGukddLsKKqMNgbsNh/9HHjzHErxa1UXjKuXYPMwY6DeXNXCVwJBQaqiWcaCEOhEfCisk7MWVAK+UlBhvsSNY5mrkY5PqvpVAeBAqC+He1SlfPnFZXT01Mpv/I6u77q6QmCkineOZA+uzYFAoGAG4qr5lORA0v9bXGwftcxtwZcKVgHPcYrDp9ojInb09S1iq6YplIIfjMRkLcA7dZelNsPrbIodWDQAos7vEJTyHczEQXLYvqjfj6gWMHzDcr/QV4ciMwsWfL9jwB6uP21QVhMoiSqGuE6aiRxOuvN5ZWktO3xox70T0S/lqVAilUCgYBG8qPFk3Gcimg4WYBiaP/MRLRr/M3XXUOg7tn3ex9UmLWtIfbaw9lLFexMMcNSQTfDTrn3j07Ljq7W1KmatTvzHF0Hess+QohFflXq1J4FFoWaxaGVXRYTxA09FEdm+9uo3udhkF6quioUH6S8Pii1IwL+7gBC+zflJSriBWA9NQ==";
final static String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuTSP+mimt8IOGuoN6AQoGZgYFEMWydQF8DxdcLEuUonMkbcCgCV/OKB2fSgEESwVRP1AtHTtA60zwl0BPzc79XBvgQ5RfOnQg09yBMst/PfWxbCi3esGycNsse110KSdMPUB8UKS+ve2vyasRN6YoED5q75SSciFMGzlE+T2CrAvwdhY2Ji02c8mdKgWsBdS9jTrEf9CNnM3bIsFWs7UthEfgk/7obeV5tyHw1lD5R9R2YZXmtHmPUmh5Q74bo1xO0pqs4o5/+kVZ4qLHb5aoIbrhEc97Fq1pQvjpoogwZdY+jfxXsJVSXtVOmnVMK+pciEEXctGAp+FqzXArciTGQIDAQAB";
@Test
public void testSignJwt() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
BASE64Decoder decoder = new BASE64Decoder();
byte[] privatekeyDecode = decoder.decodeBuffer(privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privatekeyDecode);
X509EncodedKeySpec pKeySpec = new X509EncodedKeySpec(decoder.decodeBuffer(publicKey));
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) kf.generatePrivate(keySpec);
RSAPublicKey rsaPublicKey = (RSAPublicKey) kf.generatePublic(pKeySpec);
Algorithm algorithmRS = Algorithm.RSA256(rsaPublicKey, rsaPrivateKey);
String token = JWT.create()
.withIssuer("auth0").withClaim("ectDate", new Date().getTime()).withClaim("eprDay", 3).
withExpiresAt(DateUtils.addDays(new Date(), 5))
.sign(algorithmRS);
System.out.println(token);
}
@Test
public void testVerifyToken() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsImVjdERhdGUiOjE1MjY5Nzc2MTAxMjksImV4cCI6MTUyNzQwOTYxMCwiZXByRGF5IjozfQ.KA2FtaAarRhRE4TUr1OdOhCZa9fOEE1E1iY_cmybfoBCdHiMsSj-Aa0CExKXksrJPEzLVNmpkqDO70xECc1xAEm4xJ1LQMa7gOyF4xlJrcGX_0TwxhrPQLNHAbXeUzh_Jn79F4Y_tNdUiBAESSzbvAsaQXoxqIV1MnjuepHZgUQfCfBiaSNWwnWpxJ3uvHPHAcH9wfqU9F2QsLlh_-Nv8HHNHTib5NE60ecbSLn_PblDTwMIolVSLYw2q2QhJ_g4nPPIPHQtQCV2nETKuglPIY2ZPOq8r431BvARbZd8y-ljvuxLp5Ia24ZvmHmUgVzHZkPFF3ttze0g5_n9sffYYA";
BASE64Decoder decoder = new BASE64Decoder();
byte[] privatekeyDecode = decoder.decodeBuffer(privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privatekeyDecode);
X509EncodedKeySpec pKeySpec = new X509EncodedKeySpec(decoder.decodeBuffer(publicKey));
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) kf.generatePrivate(keySpec);
RSAPublicKey rsaPublicKey = (RSAPublicKey) kf.generatePublic(pKeySpec);
Algorithm algorithmRS = Algorithm.RSA256(rsaPublicKey, rsaPrivateKey);
try {
JWTVerifier verifier = JWT.require(algorithmRS)
.withIssuer("auth0")
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
System.out.println(jwt.getIssuer());
System.out.println(jwt.getClaim("ectDate").asDate());
System.out.println(jwt.getClaim("eprDay").asInt());
} catch (JWTVerificationException exception) {
//Invalid signature/claims
System.out.println("1ihyaoishdoiahd");
}
}
@Test
public void timezoneTest() {
long dayMillis = 1000 * 60 *60 * 24;
Instant now = Instant.now();
System.out.println(Timestamp.valueOf(now.atZone(ZoneId.of("GMT")).toLocalDateTime()));
Long timeStamp = 1528133742131l;
Long dayStart = timeStamp / dayMillis * dayMillis;
Long dayEnd = dayStart + dayMillis -1 ;
System.out.println(dayStart);
System.out.println(dayEnd);
System.out.println(new Date(dayStart).toInstant().atZone(ZoneId.of("GMT")).toString());
System.out.println(new Date(dayEnd));
}
@Test
public void testDateUtils() {
System.out.println(DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
}
@Test
public void testTry() throws Exception {
try(CloseOne x = getInt()) {
}
System.out.println("chenggong");
}
class CloseOne implements Closeable {
CloseOne() {
}
@Override
public void close() throws IOException {
}
}
private CloseOne getInt () throws Exception {
throw new Exception("222");
// return new CloseOne();
}
}
|
package Attributes;
public class Number extends Attribute {
int num;
boolean init=false;
public Number(int n) {
super(false);
init=true;
num=n;
}
public Number(){
super(true);
}
@Override
public String toString(){
if(!init){
return "<NUM>";
}
return String.valueOf(num);
}
@Override
public boolean equalsTo(Attribute input) {
if(input instanceof Number){
Number n = (Number)(input);
return num==n.num;
}
return false;
}
}
|
package car;
public class Goods extends Car {
private double goodCapacity;
public Goods(int number, String brand, double fee, double goodCapacity) {
super(number, brand, fee);
this.goodCapacity = goodCapacity;
}
public double getGoodCapacity() {
return goodCapacity;
}
public void setGoodCapacity(double goodCapacity) {
this.goodCapacity = goodCapacity;
}
public String toString(){
return number + "\t" + brand + "\t" + fee + "/Μμ\t" + goodCapacity + "ΆΦ\n";
}
}
|
package com.talleres.proyectotalleresandroid;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.squareup.picasso.Picasso;
import com.talleres.proyectotalleresandroid.Utilerias.Preference;
public class MainActivityJava extends Activity {
ImageView imguno;
TextView nombreusuario, nombrecontrasena;
String usuario,contrasena;
Preference oPreference;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oPreference = new Preference(getApplicationContext());
Intent iin= getIntent();
Bundle b = iin.getExtras();
nombreusuario = findViewById(R.id.txtNombreUsuario);
nombrecontrasena = findViewById(R.id.txtNombrePassword);
if(b!=null)
{
usuario = (String) b.get("TextoUsuario");
contrasena = (String) b.get("textoContrasena");
}
else{
usuario = oPreference.getNombre();
contrasena = oPreference.getContrasena();
}
nombreusuario.setText(usuario);
nombrecontrasena.setText(contrasena);
imguno = findViewById(R.id.imgUno);
Picasso.with(getApplicationContext()).load("https://www.logaster.com.es/blog/wp-content/uploads/sites/4/2019/01/4-min-620x350.jpg")
.into(imguno);
}
}
|
package org.reactome.web.nursa.client.details.tabs.dataset;
/**
* @author Fred Loney <loneyf@ohsu.edu>
*/
public class GseaHoveredEvent extends NursaPathwayHoveredEvent<String> {
public static Type<PathwayLoader> TYPE = new Type<PathwayLoader>();
public GseaHoveredEvent(String stId) {
super(stId);
}
@Override
public Type<PathwayLoader> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(PathwayLoader handler) {
handler.load(getKey());
}
}
|
package com.edasaki.rpg.particles;
import org.bukkit.ChatColor;
public enum CosmeticRarity {
COMMON(ChatColor.WHITE + ChatColor.ITALIC.toString() + "Common Effect"),
RARE(ChatColor.AQUA + ChatColor.ITALIC.toString() + "Rare Effect"),
EPIC(ChatColor.LIGHT_PURPLE + ChatColor.ITALIC.toString() + "Epic Effect"),
LEGENDARY(ChatColor.GOLD + ChatColor.ITALIC.toString() + "Legendary Effect"),
;
public String display;
CosmeticRarity(String display) {
this.display = display;
}
}
|
package com.turios.modules.preferences;
import com.turios.persistence.Preferences;
public class BaseModulePreferences {
protected final Preferences preferences;
public BaseModulePreferences(Preferences preferences) {
super();
this.preferences = preferences;
}
}
|
package cn.jiucaituan;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.jiucaituan.common.DateUtil;
import cn.jiucaituan.common.JdbcExecutor;
import cn.jiucaituan.common.QueueFactory;
import cn.jiucaituan.vo.Msg;
public class Test {
public Test() {
// TODO Auto-generated constructor stub
}
// 抓取某个股票从某天开始到现在的股票详情。
public void fetchStock(String date) throws Exception{
JdbcExecutor jdbcExecutor = new JdbcExecutor();
List slist = jdbcExecutor.queryForList("select * from S_STOCK ", new Object[] {});
for (int i = 0; i < slist.size(); i++) {
Map row = (Map) slist.get(i);
String stockId = row.get("ID").toString();
String sql = "insert into S_JOB(JOB_NAME,JOB_TYPE,JOB_TIME,CREATE_DATE,STATE,JOB_MAN,JOB_COMMAND)"
+ "values('StockDealFRM',1011,'" + date + "',now(),0,'ADMIN'," + stockId+"); ";
System.out.println(sql);
}
}
public void test() throws Exception{
DateUtil du = new DateUtil();
Date fd = du.getDated("2016-02-29");
Calendar rightNow = Calendar.getInstance();
for (int i = 1; i < 50; i++) {
rightNow.setTime(fd);
rightNow.add(Calendar.DAY_OF_YEAR, i);// 日期加1天
Date dt1 = rightNow.getTime();
if (!du.isWeekend(dt1)) {
String sql = "insert into S_JOB(JOB_NAME,JOB_TYPE,JOB_TIME,CREATE_DATE,STATE,JOB_MAN) "
+ "values('StockDeal',1010,'" + du.format(dt1) + "',now(),0,'ADMIN'); ";
System.out.println(sql);
}
}
}
public static void main(String[] args)throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("app.xml");
Test t = new Test();
t.fetchStock("2015-01-01");
}
}
|
package com.hm.cms;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author Merlin
* @Title: CMSApplication
* @ProjectName gradle-learning
* @Description: TODO
* @date 2020/8/2015:17
*/
@SpringBootApplication
public class HmCmsApplication {
//启动类
public static void main(String[] args) {
SpringApplication.run(HmCmsApplication.class, args);
}
}
|
package com.logicbig.example.injectingcollection.map.jconfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class MapInjectionExample {
@Bean
public TestBean testBean () {
HashMap<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
return new TestBean(map);
}
public static void main (String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
MapInjectionExample.class);
TestBean bean = context.getBean(TestBean.class);
System.out.println(bean.getMap());
}
private static class TestBean {
private final Map<String, Integer> map;
//@Autowired not required anymore, starting Spring 4.3
private TestBean (Map<String, Integer> map) {
this.map = map;
}
public Map<String, Integer> getMap () {
return map;
}
}
}
|
package com.example.mmr.medic;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.example.mmr.R;
import com.example.mmr.VolleySingleton;
import com.example.mmr.patient.Patient;
import com.example.mmr.patient.ProfileFragment;
import com.example.mmr.shared.LoadImage;
import com.example.mmr.shared.SharedModel;
import com.mikhaellopez.lazydatepicker.LazyDatePicker;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import de.hdodenhof.circleimageview.CircleImageView;
public class ProfilePatient extends AppCompatActivity {
private RequestQueue queue;
private CircleImageView imageView;
private TextView email;
private TextView name;
private LinearLayout call;
private LinearLayout message;
private LinearLayout writeNote;
private LinearLayout seeRecord;
private LinearLayout setMeet;
private String cin;
private Patient patient;
ImageButton back;
MedicSessionManager sessionManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_patient);
queue = VolleySingleton.getInstance(this).getRequestQueue();
sessionManager=new MedicSessionManager(this);
imageView = findViewById(R.id.doc_profile_img_pat);
email = findViewById(R.id.patient_email);
name = findViewById(R.id.patient_name);
call = findViewById(R.id.patient_btn_call);
message = findViewById(R.id.patient_btn_chat);
writeNote = findViewById(R.id.to_notes);
seeRecord = findViewById(R.id.to_record);
setMeet = findViewById(R.id.to_calandar);
back = findViewById(R.id.patient_btn_back);
cin=getIntent().getStringExtra("cin");
new SharedModel(this,queue).getPatientInfos(cin, new SharedModel.LoadHomeInfoCallBack() {
@Override
public void onSuccess(Vector<Object> vector) {
patient=(Patient) vector.get(0);
if (!patient.getPhoto().equals("local")){
new LoadImage(imageView,getApplicationContext()).execute(patient.getPhoto());
}
email.setText(patient.getEmail());
name.setText(patient.getNom()+" "+patient.getPrenom());
call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("tel:" + patient.getTele()));
startActivity(intent);
}
});
message.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("smsto:" + patient.getTele()));
startActivity(intent);
}
});
seeRecord.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ProfilePatient.this,MedicPatientRecord.class);
intent.putExtra("cin",patient.getCin());
startActivity(intent);
}
});
writeNote.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Map<String,String> infos=new HashMap<String,String>();
Dialog dialog = new Dialog(ProfilePatient.this);
dialog.setContentView(R.layout.dialog_add_note);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button mActionOk = dialog.findViewById(R.id.add_note);
Button mActionCancel = dialog.findViewById(R.id.cancel_note);
EditText title = dialog.findViewById(R.id.titre_note);
EditText body = dialog.findViewById(R.id.desc_note);
Spinner spinner = dialog.findViewById(R.id.note_priority_add);
dialog.show();
mActionCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
mActionOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (title.getText().toString().matches("") ||
body.getText().toString().matches("") ||
spinner.getSelectedItemPosition()==0
)
Toast.makeText(getApplicationContext(),"quelques champs sont vides",Toast.LENGTH_LONG).show();
else {
dialog.dismiss();
infos.put("cinPat",cin);
infos.put("cinMed",sessionManager.getCinMedcin());
infos.put("title",title.getText().toString());
infos.put("priority",spinner.getSelectedItemPosition()+"");
infos.put("body",body.getText().toString());
new SharedModel(ProfilePatient.this,queue).addNote(infos, new SharedModel.SignUpCallBack() {
@Override
public void onSuccess(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
@Override
public void onErr(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
});
}
}
});
}
});
setMeet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Map<String,String> infos=new HashMap<String,String>();
Dialog dialog = new Dialog(ProfilePatient.this);
dialog.setContentView(R.layout.dialog_add_rendez_vous);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button mActionOk = dialog.findViewById(R.id.add_meet);
Button mActionCancel = dialog.findViewById(R.id.cancel_meet);
LazyDatePicker picker = dialog.findViewById(R.id.lazyDatePicker);
NumberPicker hour = dialog.findViewById(R.id.pickerHours);
NumberPicker minute = dialog.findViewById(R.id.pickerMinutes);
final Boolean[] isSelected = {false};
hour.setMaxValue(23);
hour.setMinValue(0);
minute.setMaxValue(23);
minute.setMinValue(0);
picker.setOnDateSelectedListener(new LazyDatePicker.OnDateSelectedListener() {
@Override
public void onDateSelected(Boolean dateSelected) {
isSelected[0] =dateSelected;
}
});
dialog.show();
mActionCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
mActionOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (! isSelected[0])
Toast.makeText(getApplicationContext(),"quelques champs sont vides",Toast.LENGTH_LONG).show();
else {
dialog.dismiss();
infos.put("cinPat",cin);
infos.put("cinMed",sessionManager.getCinMedcin());
infos.put("date",(picker.getDate().getMonth()+1)+"/"+picker.getDate().getDate()+"/"+picker.getDate().toString().substring(picker.getDate().toString().lastIndexOf(" ")+1));
infos.put("hour",hour.getValue()+"");
infos.put("minute",minute.getValue()+"");
new SharedModel(getApplicationContext(),queue).addMeet(infos, new SharedModel.SignUpCallBack() {
@Override
public void onSuccess(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
@Override
public void onErr(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
});
}
}
});
}
});
}
@Override
public void onErr(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
});
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
|
package Keywords;
import java.util.List;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import AdditionalSetup.Objects;
import AdditionalSetup.ResultUpdation;
import Common.Information;
public class Menu implements Information{
WebDriver driver;
boolean cond=false;
Objects obj;
ResultUpdation ru;
public Menu(WebDriver driver,ExtentTest test) throws Exception{
this.driver=driver;
obj = new Objects(driver, test);
ru = new ResultUpdation(obj);
}
public String testing(Properties p,String[] record,int row, String sh, int resultRow,String[] imp ) throws Exception{
try{
cond=false;
List<WebElement> menulist=driver.findElements(obj.getLocators().getObject(p,record[OBJECTNAME], record[OBJECTTYPE]));
VALUE_STORAGE.put(record[OBJECTNAME]+VALUE_END, "false");
for(WebElement ele:menulist){
if(ele.getText().contains(record[VALUE])){
obj.getJavaScript().highlight(ele);
ele.click();
VALUE_STORAGE.put(record[OBJECTNAME]+VALUE_END, "true");
cond= true;
obj.getExcelResult().setData(cond,row,sh,resultRow,Information.PASS,imp);
obj.getExtentTest().log(LogStatus.PASS, record[STEPNUMBER],"Description: "+record[DESCRIPTION]+"\nOutput: "+record[EXPECTED_COLUMN]);
return Information.PASS;
}
}
if(!cond){
cond= false;
obj.getExcelResult().setData(cond,row,sh,resultRow,Information.FAIL,imp);
obj.getExtentTest().log(LogStatus.FAIL, record[STEPNUMBER],"Description: "+record[DESCRIPTION]+"\nOutput: "+record[EXPECTED_COLUMN]);
return Information.FAIL;
}
return Information.PASS;
}
catch(Exception ne){
ru.testing(p, record, row, sh, resultRow, Information.FAIL,imp);
ne.printStackTrace();VALUE_STORAGE.put(record[OBJECTNAME]+VALUE_END, ERROR);
return Information.FAIL;
}
}
}
|
package br.com.fatec.proximatrilha.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.security.core.GrantedAuthority;
import com.fasterxml.jackson.annotation.JsonView;
import br.com.fatec.proximatrilha.view.View;
/**
* Class Model of Authorization
*
* @author Guilherme Faria
*
*/
@Entity
@Table(name = "AUTHORIZATION")
public class Authorization implements GrantedAuthority {
private static final long serialVersionUID = -80306030346346038L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "AUTHORIZATION_ID")
@JsonView({View.User.class, View.General.class})
private Long id;
@Column(name = "AUTHORITY", unique=true, length = 20, nullable = false)
@JsonView({View.User.class, View.General.class})
private String authority;
public Long getId() {
return id;
}
@Override
public String getAuthority() {
return authority;
}
public void setAuthority(final String authority) {
this.authority = authority;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((authority == null) ? 0 : authority.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Authorization other = (Authorization) obj;
if (authority == null) {
if (other.authority != null)
return false;
} else if (!authority.equals(other.authority))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
|
package org.eclipse.wb.swt;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class QuestionNine extends JFrame {
private JPanel contentPane;
private JTextField youranswers;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
QuestionNine frame = new QuestionNine();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public QuestionNine() {
setTitle("Question 9");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("9. What does UI stand for?");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblNewLabel.setBounds(10, 23, 191, 14);
contentPane.add(lblNewLabel);
youranswers = new JTextField();
youranswers.setBounds(22, 65, 163, 20);
contentPane.add(youranswers);
youranswers.setColumns(10);
JButton btnCheck = new JButton("Next");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
QuestionTen q = new QuestionTen();
q.setVisible(true);
}
});
btnCheck.setBounds(335, 227, 89, 23);
contentPane.add(btnCheck);
JButton button = new JButton("Check!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String String;
if (youranswers.equals("user interface"))
String = "message";
String message = "Correct!";
JOptionPane.showMessageDialog (null, message);
}
});
button.setBounds(335, 188, 89, 23);
contentPane.add(button);
}
}
|
package search.binary;
public class Main {
public static void main(String[] args) {
BST bst = new BST();
bst.put("3", "헤헤");
bst.put("5", "헤헤");
bst.put("1", "헤헤");
bst.put("2", "세크스");
bst.put("0", "헤헤");
int a = bst.size();
System.out.println(a);
bst.print();
}
}
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] nums = input.split(" ");
String[] as = nums[0].split("/");
String[] bs = nums[1].split("/");
int a1 = Integer.parseInt(as[0]);
int a2 = Integer.parseInt(as[1]);
int b1 = Integer.parseInt(bs[0]);
int b2 = Integer.parseInt(bs[1]);
// int a1 = scanner.nextInt();
// int a2 = scanner.nextInt();
// int b1 = scanner.nextInt();
// int b2 = scanner.nextInt();
// System.out.println(a1+" "+a2+";"+b1+" "+b2);
// 1.假分数换算
int aBase = a1 / a2;
// int temp;
// if (!(aBase==0)) a1 = a1 - a1 % a2;
a1 = Math.abs(a1 - a2 * aBase);
int bBase = b1 / b2;
// if (!(bBase==0)) b1 = b1 - (b1 % b2) *bBase;
b1 = Math.abs(b1 - b2 *bBase);
System.out.println(aBase+" "+a1+"/"+a2);
System.out.println(bBase+" "+b1+"/"+b2);
// 2.
}
}
|
public class ProblemSets {
public long maxSets(long E, long EM, long M, long MH, long H) {
long min = 0;
long max = H + MH + 1;
while(min < max) {
long mid = (min + max)/2;
if(possible(E, EM, M, MH, H, mid)) {
min = mid + 1;
} else {
max = mid;
}
}
return min - 1;
}
private boolean possible(long E, long EM, long M, long MH, long H, long goal) {
if(E < goal) {
EM -= goal - E;
if(EM < 0) {
return false;
}
}
if(H < goal) {
MH -= goal - H;
if(MH < 0) {
return false;
}
}
return goal <= EM + M + MH;
}
}
|
public class Department
{
public static void depinfo()
{
}
}
|
package com.example.jobbay;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.DateFormat;
import java.util.Date;
import Model.Data;
import Model.jobApply;
public class applyJob extends AppCompatActivity {
TextView company_name, advert_name, contact, emailid, jobqualification, experience;
Button apply;
FirebaseAuth mAuth;
DatabaseReference mApplyJob;
private DatabaseReference mPublicDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apply_job);
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
String uId = mUser.getUid();
mApplyJob = FirebaseDatabase.getInstance().getReference().child("Apply Job").child(uId);
mPublicDatabase = FirebaseDatabase.getInstance().getReference().child("Public database");
ApplyforJob();
}
private void ApplyforJob() {
company_name = findViewById(R.id.tv_name);
contact = findViewById(R.id.tv_contact);
emailid = findViewById(R.id.tv_emailid);
advert_name = findViewById(R.id.tv_JobName);
jobqualification = findViewById(R.id.tv_jobqualification);
experience = findViewById(R.id.tv_experience);
apply = findViewById(R.id.btn_apply);
apply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String cName = company_name.getText().toString().trim();
String Ccontact = contact.getText().toString().trim();
String Cemailid = emailid.getText().toString().trim();
String Cadvert = advert_name.getText().toString().trim();
String jobqual = jobqualification.getText().toString().trim();
String jexp = experience.getText().toString().trim();
if (TextUtils.isEmpty(cName)) {
company_name.setError("Required Field!");
return;
}
if (TextUtils.isEmpty(Ccontact)) {
contact.setError("Required Field!");
return;
}
if (TextUtils.isEmpty(Cemailid)) {
emailid.setError("Required Field!");
return;
}
if (TextUtils.isEmpty(Cadvert)) {
advert_name.setError("Required Field!");
return;
}
if (TextUtils.isEmpty(jobqual)) {
jobqualification.setError("Required Field!");
return;
}
if (TextUtils.isEmpty(jexp)) {
experience.setError("Required Field!");
return;
}
String id = mApplyJob.push().getKey();
String date = DateFormat.getDateInstance().format(new Date());
jobApply data = new jobApply(cName,Ccontact,Cemailid,Cadvert,jobqual,jexp,id,date);
mApplyJob.child(id).setValue(data);
mPublicDatabase.child(id).setValue(data);
Toast.makeText(getApplicationContext(),"Application sent",Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), Home.class));
}
});
}
}
|
package step_definitions;
import BDDTest.SeleniumUtils;
import BDDTest.SeleniumUtils.FindOption;
import BDDTest.SeleniumUtils.SeleniumValidateOption;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
public class TestingImages {
private SeleniumUtils seleniumUtils;
private String startPageUrlDealer,secondPageUrlDealer,thirdPageUrlDealer;
private String startPageUrlClient,secondPageUrlClient,thirdPageUrlClient;
public TestingImages(){
this.seleniumUtils=new SeleniumUtils();
startPageUrlDealer="http://audi-a4-preview.message.ch/dealer/de/";
secondPageUrlDealer="http://audi-a4-preview.message.ch/dealer/it/";
thirdPageUrlDealer="http://audi-a4-preview.message.ch/dealer/fr/";
startPageUrlClient="http://audi-a4-preview.message.ch/client/de/";
secondPageUrlClient="http://audi-a4-preview.message.ch/client/it/";
thirdPageUrlClient="http://audi-a4-preview.message.ch/client/fr/";
}
@Given("^I am on audi DE dealer homepage$")
public void I_am_on_audi_DE_dealer_homepage(){
seleniumUtils.getToURL(startPageUrlDealer);
}
@Then("^Some Audi image should be visible$")
public void Some_Audi_image_should_be_visible(){
seleniumUtils.runValidate("", seleniumUtils.findElementOnPage(FindOption.XPATH, ".//img[@src='/media/1001/audiimage.jpg']"), SeleniumValidateOption.IS_DISPLAYED);
}
@Then("^Some Audi logo should be visible$")
public void Some_Audi_logo_should_be_visible(){
seleniumUtils.runValidate("", seleniumUtils.findElementOnPage(FindOption.XPATH, ".//img[@src='/images/logo.png']"), SeleniumValidateOption.IS_DISPLAYED);
}
@Then("^I go to IT dealer homepage$")
public void I_go_to_IT_dealer_homepage(){
seleniumUtils.getToURL(secondPageUrlDealer);
}
@Then("^Logo should be there$")
public void Logo_should_be_there(){
seleniumUtils.runValidate("", seleniumUtils.findElementOnPage(FindOption.XPATH, ".//img[@src='/images/logo.png']"), SeleniumValidateOption.IS_DISPLAYED);
}
@Then("^Image should be there$")
public void Image_should_be_there(){
seleniumUtils.runValidate("", seleniumUtils.findElementOnPage(FindOption.XPATH, ".//img[@src='/media/1001/audiimage.jpg']"), SeleniumValidateOption.IS_DISPLAYED);
}
@Then("^I go to FR dealer homepage$")
public void I_go_to_FR_dealer_homepage(){
seleniumUtils.getToURL(thirdPageUrlDealer);
}
@Then("^The logo should be visible$")
public void The_logo_should_be_visible(){
seleniumUtils.runValidate("", seleniumUtils.findElementOnPage(FindOption.XPATH, ".//img[@src='/images/logo.png']"), SeleniumValidateOption.IS_DISPLAYED);
}
@Then("^The Image should be visible$")
public void Image_should_be_visible(){
seleniumUtils.runValidate("", seleniumUtils.findElementOnPage(FindOption.XPATH, ".//img[@src='/media/1001/audiimage.jpg']"), SeleniumValidateOption.IS_DISPLAYED);
}
@Then("^I go to DE client page$")
public void I_go_to_DE_client_page(){
seleniumUtils.getToURL(startPageUrlClient);
}
@Then("^Some Audi image should be visible client DE$")
public void Some_Audi_image_should_be_visible_client_DE(){
seleniumUtils.runValidate("", seleniumUtils.findElementOnPage(FindOption.XPATH, ".//img[@src='/media/1001/audiimage.jpg']"), SeleniumValidateOption.IS_DISPLAYED);
}
@Then("^Some Audi logo should be visible client DE$")
public void Some_Audi_logo_should_be_visible_client_DE(){
seleniumUtils.runValidate("", seleniumUtils.findElementOnPage(FindOption.XPATH, ".//img[@src='/images/logo.png']"), SeleniumValidateOption.IS_DISPLAYED);
}
@Then("^I go to IT client page$")
public void I_go_to_IT_client_page(){
seleniumUtils.getToURL(secondPageUrlClient);
}
@Then("^The logo should be visible client IT$")
public void The_logo_should_be_visible_client_IT(){
seleniumUtils.runValidate("", seleniumUtils.findElementOnPage(FindOption.XPATH, ".//img[@src='/images/logo.png']"), SeleniumValidateOption.IS_DISPLAYED);
}
@Then("^The Image should be visible client IT$")
public void The_Image_should_be_visible_client_IT(){
seleniumUtils.runValidate("", seleniumUtils.findElementOnPage(FindOption.XPATH, ".//img[@src='/media/1001/audiimage.jpg']"), SeleniumValidateOption.IS_DISPLAYED);
}
@Then("^I go to FR client page$")
public void I_go_to_FR_client_page(){
seleniumUtils.getToURL(thirdPageUrlClient);
}
@Then("^The logo should be visible client FR$")
public void The_logo_should_be_visible_client_FR(){
seleniumUtils.runValidate("", seleniumUtils.findElementOnPage(FindOption.XPATH, ".//img[@src='/images/logo.png']"), SeleniumValidateOption.IS_DISPLAYED);
}
@Then("^The Image should be visible client FR$")
public void Image_should_be_visible_client_FR(){
seleniumUtils.runValidate("", seleniumUtils.findElementOnPage(FindOption.XPATH, ".//img[@src='/media/1001/audiimage.jpg']"), SeleniumValidateOption.IS_DISPLAYED);
}
}
|
package api.algorithm.selection;
import java.util.List;
import api.algorithm.Algorithm;
import api.model.individual.Individual;
public abstract class SelectionAlgorithm extends Algorithm{
private int numberOfSelected;
public SelectionAlgorithm(int numberOfSelected) {
this.numberOfSelected = numberOfSelected;
}
public abstract List<Individual> select(List<Individual> poblation);
protected int getNumberOfSelected() {
return numberOfSelected;
}
}
|
package com.cbsystematics.edu.internet_shop.repository;
import com.cbsystematics.edu.internet_shop.entity.Product;
public interface IProductRepository extends GenericRepository<Product> {
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package josteo.viewmodels;
import josteo.infrastructure.DomainBase.*;
import java.util.*;
import josteo.model.paziente.*;
import josteo.application.*;
import josteo.infrastructure.helpers.*;
/**
*
* @author cristiano
*/
public class ConsultiPresenter extends ListPresenterBase<Consulto>{
public ConsultiPresenter(){
super();
}
@Override
protected void createEmptyItem(){
this.NewItem = new Consulto();
}
public String getPaziente(){
Paziente paziente = josteo.application.ApplicationState.getInstance().getCurrentPaziente();
if(paziente!=null)
return paziente.getFullName();
return "";
}
@Override
public List<Consulto> GetList(){
Paziente paziente = josteo.application.ApplicationState.getInstance().getCurrentPaziente();
return paziente.get_Consulti();
}
@Override
public void Load(){
Paziente paziente = josteo.application.ApplicationState.getInstance().getCurrentPaziente();
if(paziente==null) return;
super.Load();
}
}
|
package ru.goodroads.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.codec.binary.Base64;
public class ZIP {
public static byte[] compress(String data, String fileName) {
if (data == null || data.length() == 0) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
try {
zos.putNextEntry(new ZipEntry(fileName));
zos.write(data.getBytes());
zos.closeEntry();
zos.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return bos.toByteArray();
}
public static String compressToString(String data, String fileName) {
return Base64.encodeBase64URLSafeString(compress(data, fileName));
}
}
|
package me.ewriter.chapter4;
import android.animation.ObjectAnimator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ScrollHideListView extends AppCompatActivity implements View.OnTouchListener, AbsListView.OnScrollListener {
private Toolbar mToolbar;
private ListView mListView;
private String[] mStr = new String[20];
private int mTouchSlop;
private float mFirstY;
private float mCurrentY;
private int direction;
private ObjectAnimator mAnimator;
private boolean mShow = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scroll_hide_list_view);
// 获得系统认为的最低滚动的距离
mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mListView = (ListView) findViewById(R.id.listview);
for (int i = 0; i < mStr.length; i++) {
mStr[i] = "Item " + i;
}
View header = new View(this);
header.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
(int) getResources().getDimension( R.dimen.abc_action_bar_default_height_material)));
mListView.addHeaderView(header);
mListView.setAdapter(new ArrayAdapter<String>(
ScrollHideListView.this,
android.R.layout.simple_expandable_list_item_1,
mStr));
mListView.setOnTouchListener(this);
// ListView的滑动监听还有OnScrollListener
mListView.setOnScrollListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mFirstY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
mCurrentY = event.getY();
// if (mCurrentY - mFirstY > mTouchSlop) {
// direction = 0; // down
// } else if (mFirstY - mCurrentY > mTouchSlop) {
// direction = 1; // up
// }
//
// if (direction == 1) {
// if (mShow) {
// toolbarAnim(1); // 显示toolbar
// mShow = !mShow;
// }
// } else if (direction == 0) {
// if (!mShow) {
// toolbarAnim(0); // 隐藏toolbar
// mShow = !mShow;
// }
// }
// 这部分代码和上面书中的代码效果一样,只是以自己理解的方式重新写了一遍
if (mCurrentY - mFirstY > mTouchSlop) {
// 手指向下,即逐渐显示item9,8,7 之类的。显示toolbar
if (!mShow) {
toolbarAnim(0);
mShow = !mShow;
}
} else if (mFirstY - mCurrentY > mTouchSlop) {
// 手指向上,即逐渐显示item8,9,10这类的。隐藏toolbar
if (mShow) {
toolbarAnim(1);
mShow = !mShow;
}
}
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
/**
* toolbar 显示动画
* @param flag flag = 0 时显示,flag = 1 时隐藏
*/
private void toolbarAnim(int flag) {
if (mAnimator != null && mAnimator.isRunning()) {
mAnimator.cancel();
}
// 坐标参考:http://leeeyou.xyz/Android-Android%E5%9D%90%E6%A0%87%E4%BD%93%E7%B3%BB
if (flag == 0) {
// 属性动画,View, 平移动画,后面的章节还会具体的介绍,这里不过多解释
// 显示toolbar
mAnimator = ObjectAnimator.ofFloat(mToolbar,
"translationY", mToolbar.getTranslationY(), 0);
} else {
// 隐藏toolbar,getTranslationY() 为0 ,需要让toolbar 移动负向的距离
mAnimator = ObjectAnimator.ofFloat(mToolbar,
"translationY", mToolbar.getTranslationY(),
-mToolbar.getHeight());
}
mAnimator.start();
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case SCROLL_STATE_FLING:
// 手指抛动时,惯性滑动的状态
break;
case SCROLL_STATE_IDLE:
// 停止滚动
break;
case SCROLL_STATE_TOUCH_SCROLL:
// 正在滚动
break;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// view, 当前能看见的第一个item id, 当前能看见的item 总数,整个listview 的item 总数
}
}
|
package com.cs.rest.status;
import com.cs.payment.devcode.DCInvalidAuthorizationCodeException;
/**
* @author Hadi Movaghar
*/
public class DCInvalidAuthorizationCodeMessage extends DevcodeErrorMessage {
private static final long serialVersionUID = 1L;
public DCInvalidAuthorizationCodeMessage(final String playerId, final String errorMessage) {
super(playerId, StatusCode.DEVCODE_INVALID_AUTHORIZATION_CODE, errorMessage);
}
public static DCInvalidAuthorizationCodeMessage of(final DCInvalidAuthorizationCodeException exception) {
return new DCInvalidAuthorizationCodeMessage(exception.getPlayerId(), exception.getMessage());
}
}
|
package com.n26.atrposki.endpoints;
/*
* @author aleksandartrposki@gmail.com
* @since 06.05.18
*
*
*/
import com.n26.atrposki.domain.AggregateStatistics;
import com.n26.atrposki.domain.Transaction;
import com.n26.atrposki.statistics.StatisticsService;
import com.n26.atrposki.transactions.TransactionDTO;
import com.n26.atrposki.transactions.TransactionsService;
import com.n26.atrposki.utils.time.ITimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static com.n26.atrposki.utils.time.ITimeService.*;
@RestController
@RequestMapping("/debug")
public class DebugController {
ITimeService timeService;
TransactionsService transactionsService;
StatisticsService statisticsService;
@Autowired
public DebugController(ITimeService timeService, TransactionsService transactionsService, StatisticsService statisticsService) {
this.timeService = timeService;
this.transactionsService = transactionsService;
this.statisticsService = statisticsService;
}
@RequestMapping("/createrandom")
public DebugResponse createRandom(){
TransactionDTO t = new TransactionDTO();
t.setAmount(Math.random()*1000);
long randomTime = new Double(MILISECONDS_IN_MINUTE*Math.random()).longValue();
t.setTimestamp(timeService.getUtcNow()-randomTime);
boolean status = transactionsService.createTransaction(t);
AggregateStatistics statistics = statisticsService.getStatistics();
return new DebugResponse(t,status? HttpStatus.CREATED:HttpStatus.NO_CONTENT,statistics);
}
@RequestMapping("/time")
public long getTime(){
return timeService.getUtcNow();
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.converter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
/**
* Implementation of {@link HttpMessageConverter} that can read and write strings.
*
* <p>By default, this converter supports all media types (<code>*/*</code>),
* and writes with a {@code Content-Type} of {@code text/plain}. This can be overridden
* by setting the {@link #setSupportedMediaTypes supportedMediaTypes} property.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0
*/
public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {
private static final MediaType APPLICATION_PLUS_JSON = new MediaType("application", "*+json");
/**
* The default charset used by the converter.
*/
public static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1;
@Nullable
private volatile List<Charset> availableCharsets;
private boolean writeAcceptCharset = false;
/**
* A default constructor that uses {@code "ISO-8859-1"} as the default charset.
* @see #StringHttpMessageConverter(Charset)
*/
public StringHttpMessageConverter() {
this(DEFAULT_CHARSET);
}
/**
* A constructor accepting a default charset to use if the requested content
* type does not specify one.
*/
public StringHttpMessageConverter(Charset defaultCharset) {
super(defaultCharset, MediaType.TEXT_PLAIN, MediaType.ALL);
}
/**
* Whether the {@code Accept-Charset} header should be written to any outgoing
* request sourced from the value of {@link Charset#availableCharsets()}.
* The behavior is suppressed if the header has already been set.
* <p>As of 5.2, by default is set to {@code false}.
*/
public void setWriteAcceptCharset(boolean writeAcceptCharset) {
this.writeAcceptCharset = writeAcceptCharset;
}
@Override
public boolean supports(Class<?> clazz) {
return String.class == clazz;
}
@Override
protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage) throws IOException {
Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());
long length = inputMessage.getHeaders().getContentLength();
byte[] bytes = (length >= 0 && length <= Integer.MAX_VALUE ?
inputMessage.getBody().readNBytes((int) length) :
inputMessage.getBody().readAllBytes());
return new String(bytes, charset);
}
@Override
protected Long getContentLength(String str, @Nullable MediaType contentType) {
Charset charset = getContentTypeCharset(contentType);
return (long) str.getBytes(charset).length;
}
@Override
protected void addDefaultHeaders(HttpHeaders headers, String s, @Nullable MediaType type) throws IOException {
if (headers.getContentType() == null ) {
if (type != null && type.isConcrete() &&
(type.isCompatibleWith(MediaType.APPLICATION_JSON) ||
type.isCompatibleWith(APPLICATION_PLUS_JSON))) {
// Prevent charset parameter for JSON..
headers.setContentType(type);
}
}
super.addDefaultHeaders(headers, s, type);
}
@Override
protected void writeInternal(String str, HttpOutputMessage outputMessage) throws IOException {
HttpHeaders headers = outputMessage.getHeaders();
if (this.writeAcceptCharset && headers.get(HttpHeaders.ACCEPT_CHARSET) == null) {
headers.setAcceptCharset(getAcceptedCharsets());
}
Charset charset = getContentTypeCharset(headers.getContentType());
StreamUtils.copy(str, charset, outputMessage.getBody());
}
/**
* Return the list of supported {@link Charset Charsets}.
* <p>By default, returns {@link Charset#availableCharsets()}.
* Can be overridden in subclasses.
* @return the list of accepted charsets
*/
protected List<Charset> getAcceptedCharsets() {
List<Charset> charsets = this.availableCharsets;
if (charsets == null) {
charsets = new ArrayList<>(Charset.availableCharsets().values());
this.availableCharsets = charsets;
}
return charsets;
}
private Charset getContentTypeCharset(@Nullable MediaType contentType) {
if (contentType != null) {
Charset charset = contentType.getCharset();
if (charset != null) {
return charset;
}
else if (contentType.isCompatibleWith(MediaType.APPLICATION_JSON) ||
contentType.isCompatibleWith(APPLICATION_PLUS_JSON)) {
// Matching to AbstractJackson2HttpMessageConverter#DEFAULT_CHARSET
return StandardCharsets.UTF_8;
}
}
Charset charset = getDefaultCharset();
Assert.state(charset != null, "No default charset");
return charset;
}
}
|
package jp.ac.hal.Model;
public class CorporationAccount
{
private String corporationAccountId;
private String corporationAccountName;
private int corporationId;
private String passwd;
public String getCorporationAccountId() {
return corporationAccountId;
}
public void setCorporationAccountId(String corporationAccountId) {
this.corporationAccountId = corporationAccountId;
}
public String getCorporationAccountName() {
return corporationAccountName;
}
public void setCorporationAccountName(String corporationAccountName) {
this.corporationAccountName = corporationAccountName;
}
public int getCorporationId() {
return corporationId;
}
public void setCorporationId(int corporationId) {
this.corporationId = corporationId;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
|
package demo.oops;
class Briyani extends Food {
@Override
public void prepare() {
System.out.println("Briyani prepared");
System.out.println("Briyani ready");
}
}
class Friedrice extends Food{
String salt;
public Friedrice(String salt){
this.salt= salt;
}
@Override
public void prepare() {
System.out.println("Friedrice preapred");
}
}
class Cheesecake extends Food{
String cheese;
public Cheesecake(String cheese) {
this.cheese= cheese;
}
public void prepare() {
System.out.println("Cheescake prepared");
}
}
|
package com.xcafe.bank.config;
import com.xcafe.bank.service.repository.AccountRepository;
import com.xcafe.bank.service.repository.MySqlAccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration
@PropertySource(value = "jdbc.properties")
@EnableTransactionManagement
public class Persistence {
@Autowired
private Environment env;
@Bean
public DataSource dataSource() {
// Simple implementation of the standard JDBC DataSource interface, configuring the plain old JDBC DriverManager
// via bean properties, and returning a new Connection from every getConnection call.
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.login"));
dataSource.setPassword(env.getProperty("jdbc.password"));
dataSource.setDriverClassName(env.getProperty("jdbc.driverClass"));
return dataSource;
}
@Bean
public AccountRepository accountRepository(DataSource dataSource) {
return new MySqlAccountRepository(dataSource);
}
}
|
/*
* 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 servicios;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import modelos.DetallePedido;
import modelos.Empleado;
import modelos.Pedido;
import util.Impresora;
import util.Impresora1;
import util.Impresora2;
/**
*
* @author Nico
*/
public class Impresion_servicio {
private static Impresion_servicio instance = null;
private final int tipoImpresora;
protected Impresion_servicio(int tipoImpresora) {
this.tipoImpresora = tipoImpresora;
}
public static Impresion_servicio getInstance() {
if (instance == null) {
instance = new Impresion_servicio(Integer.valueOf(Parametros_servicio.getInstance().recuperarValorPorCodigo("impresora")));
}
return instance;
}
private Impresora getImpresora() {
if (tipoImpresora == 1) {
return new Impresora1(null);
} else {
return new Impresora2(null);
}
}
public void imprimirPedido(Pedido pedido) {
Impresora impresora = getImpresora();
String empresa = Parametros_servicio.getInstance().recuperarValorPorCodigo("empresa");
String cliente = Parametros_servicio.getInstance().recuperarValorPorCodigo("cliente");
String quincena = Parametros_servicio.getInstance().recuperarValorPorCodigo("quincena");
Empleado empleado = pedido.getEmpleado();
Double total = pedido.getTotal();
Double acumulado = Pedidos_servicio.getInstance().recuperarTotalEmpleado(empleado.getIdEmpleado(), quincena, null);
Double totalLegajo = pedido.getTotal() - pedido.getBonificacion();
//Cabecera
if (pedido.getEliminado() == 1) {
impresora.escribir("***PEDIDO ANULADO***");
}
impresora.escribir(empresa);
impresora.escribir(cliente);
//String fecha = new SimpleDateFormat("dd/MM/yyyy HH:mm").format(Calendar.getInstance().getTime());
impresora.escribir("Fecha " + pedido.getFecha());
impresora.escribir("Ticket Nro " + pedido.getIdPedido());
impresora.escribir(empleado.getNombreEmpleado().toUpperCase());
impresora.escribir("Legajo: " + empleado.getIdEmpleado().toString());
//Items
impresora.escribir("CNT Producto Precio");
for (DetallePedido detalle : pedido.getDetallesPedido()) {
//total += detalle.getCantidad() * detalle.getPrecio();
String precio = String.format("%5s", String.valueOf(detalle.getCantidad() * detalle.getPrecio()));
String cant = String.format("%3s", detalle.getCantidad().toString());
String desc = String.format("%-16s", detalle.getProducto().getDescripcion()).substring(0, 16);
String linea = cant + " " + desc + " " + precio;
impresora.escribir(linea);
}
//Totales
impresora.escribir("* SALDOS ******");
impresora.escribir(" Total Ticket:" + String.format("%10s", total.toString()));
impresora.escribir(" Bonificacion:" + String.format("%10s", pedido.getBonificacion().toString()));
impresora.escribir(" Total Legajo:" + String.format("%10s", totalLegajo.toString()));
impresora.escribir(" Acum. del Mes:" + String.format("%10s", acumulado.toString()));
//Pie
impresora.escribir("");
impresora.escribir("**************************");
impresora.escribir("* USO INTERNO *");
impresora.escribir("* Este comprobante no es *");
impresora.escribir("* valido como factura *");
impresora.escribir("**************************");
impresora.escribir(" ");
impresora.escribir(" ");
impresora.escribir(" ");
impresora.escribir(" ");
impresora.escribir(" ");
impresora.escribir(" ");
char[] initEP = new char[]{0x1b, '@'};
char[] cutP = new char[]{0x1d, 'V', 1};
impresora.escribir(new String(initEP) + new String(cutP));
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(impresora.finalizar());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (inputStream == null) {
return;
}
DocFlavor docFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc document = new SimpleDoc(inputStream, docFormat, null);
PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();
PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
if (defaultPrintService != null) {
DocPrintJob printJob = defaultPrintService.createPrintJob();
try {
printJob.print(document, attributeSet);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.err.println("No existen impresoras instaladas");
}
try {
inputStream.close();
} catch (IOException ex) {
Logger.getLogger(Impresion_servicio.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.