text
stringlengths
10
2.72M
package io.peppermint100.server.repository; import io.peppermint100.server.entity.OrderItem; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface OrderItemRepository extends JpaRepository<OrderItem, Long> { @Query("SELECT o FROM ORDER_TABLE o WHERE user_id=" + ":userId") Optional<List<OrderItem>> getOrderByUserId(@Param("userId") Long userId); }
package com.ifli.mbcp.validator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.ifli.mbcp.util.MBCPConstants.SearchBy; import com.ifli.mbcp.vo.SearchCriteriaBean; @Component("leadSearchValidator") public class LeadSearchValidator implements Validator { private static final Logger logger = LoggerFactory.getLogger(LeadSearchValidator.class); public boolean supports(Class<?> clazz) { return SearchCriteriaBean.class.isAssignableFrom(clazz); } public void validate(Object target, Errors errors) { logger.info("Validating Search Parameters."); SearchCriteriaBean searchCriteriaBean = (SearchCriteriaBean) target; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "searchText", "NotBlank.searchText"); if (errors.hasErrors()) { return; } if (searchCriteriaBean.getSearchById() == SearchBy.LEAD_ID.getValue()) { try { Long.parseLong(searchCriteriaBean.getSearchText()); } catch (NumberFormatException e) { errors.rejectValue("searchText", "Invalid.leadID"); } } else if (searchCriteriaBean.getSearchById() == SearchBy.LEAD_ID.getValue()) { } } }
package l2_servers; import java.io.File; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javafx.util.Pair; /** * This class will act as a "garbage collector" for the cache; * once reached a certain timeout or a certain load of the cache this class wakes up, * keeps the lock of the cache and cleans all the videos outdated. * @author Andrea Bugin and Ilie Sarpe * */ public class CacheCleaner implements Runnable { private static final int VERBOSE = 50; private static final long MAX_TIME_LIMIT = 24 * 60 * 60 * 1000L; // one day private static final long MAX_SLEEP_TIME = 60 * 1000L; // one minute private HashMap<String, Pair<TupleVid, ReentrantReadWriteLock>> vidsCache = null; private Lock vcLock = null; private long time_limit; private long sleep_time = 2048L; // Milliseconds private final File root_dir = new File("/"); public CacheCleaner(HashMap<String, Pair<TupleVid, ReentrantReadWriteLock>> vidsCache, ReentrantLock vcLock, long time_limit) { this.vidsCache = vidsCache; this.vcLock = vcLock; this.time_limit = time_limit; } @Override public void run() { try { while(true) { // Problem: DRIFT we have to fix it //System.out.println("i'm going to sleep at :<" + System.currentTimeMillis() + ">"); Thread.currentThread(); Thread.sleep(sleep_time); if(VERBOSE > 100) { System.out.println("I woke up at :<" + System.currentTimeMillis() + ">"); System.out.println("Disk usage = " + root_dir.getTotalSpace()); System.out.println("Disk free = " + root_dir.getFreeSpace()); System.out.println("I slept: <" + sleep_time + ">"); System.out.println("Time limit is: <" + time_limit + ">"); } // Lock of vidsCache vcLock.lock(); try { Iterator<Map.Entry<String, Pair<TupleVid, ReentrantReadWriteLock>>> it = vidsCache.entrySet().iterator(); while(it.hasNext()) { Map.Entry<String, Pair<TupleVid, ReentrantReadWriteLock>> entry = it.next(); boolean updated = true; try { entry.getValue().getValue().writeLock().lock(); long insert_time = entry.getValue().getKey().getTimeStamp(); //System.out.println("Resource is in cache from : <" + (System.currentTimeMillis() - insert_time) + ">"); if((insert_time < System.currentTimeMillis()-time_limit)) { updated = false; File file = new File(entry.getValue().getKey().getPath()); System.out.println("Path of the resource is: <" +entry.getValue().getKey().getPath()+ ">"); file.delete(); } } finally { entry.getValue().getValue().writeLock().unlock(); } if(!updated) { System.out.println("Deleted key <" + entry.getKey() +">"); vidsCache.remove(entry.getKey()); } } double free_space_percent = ((double)root_dir.getFreeSpace() /root_dir.getTotalSpace()) * 100; if(free_space_percent > 70) { time_limit *= 1.5; sleep_time *= 1.5; } else if(free_space_percent < 30) { time_limit = (time_limit == 1)? time_limit : (time_limit/2); sleep_time = (sleep_time == 1)? sleep_time : (sleep_time/2); } } finally { vcLock.unlock(); } } } catch(InterruptedException ie) { ie.printStackTrace(); } } public synchronized long getTimeLimit() { return time_limit; } }
package foo.dbgroup.RDFstruct.datasource; import java.util.ArrayList; import java.util.List; import foo.dbgroup.mongo.entity.EndPointSparql; public class EndpointRepository { private List<EndPointSparql> lista; public EndpointRepository() { super(); lista = new ArrayList<EndPointSparql>(); //senato lista.add(new EndPointSparql("http://dati.senato.it/sparql","senato",1)); //wiktionary.dbpedia.org lista.add(new EndPointSparql("http://wiktionary.dbpedia.org/sparql","wiktionary_dbpedia_org",2)); //status endpoint lista.add(new EndPointSparql("http://labs.mondeca.com/endpoint/ends", "Endpoint Status", 3)); } public List<EndPointSparql> getLista() { return lista; } public void setLista(List<EndPointSparql> lista) { this.lista = lista; } }
package com.acms.model; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; @WebServlet("/ConUtil") public class ConUtil extends HttpServlet { private static final long serialVersionUID = 1L; @Resource(name = "jdbc/ams") private DataSource ds; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Step 1: setting up the print writer PrintWriter out = response.getWriter(); response.setContentType("text/plain"); //Step 2: Get a connection to a database Connection myConn = null; Statement myStmt = null; ResultSet myRs = null; try { myConn = ds.getConnection(); //Step 3: Create SQL Statements String sql="select * from tbl_student order by first_name"; myStmt = myConn.createStatement(); //Step 4: Execute SQL Statements myRs = myStmt.executeQuery(sql); //Step 5: Process the result set while(myRs.next()) { String f_name = myRs.getString("first_name"); String l_name = myRs.getString("last_name"); out.println(f_name + " " + l_name); } }catch(Exception ex) { ex.printStackTrace(); } finally { close(myConn,myStmt,null); } } public void close(Connection myConn, Statement myStmt, ResultSet myRs) { try { if (myRs != null) { myRs.close(); } if (myStmt != null) { myStmt.close(); } if (myConn != null) { myConn.close(); } } catch (Exception exc) { exc.printStackTrace(); } } }
package jumpingalien.part3.programs.Statements; import jumpingalien.model.LivingCreatures; import jumpingalien.part3.programs.Program; public class StopJump extends BasicStatement{ @Override public void execute(Program program) { LivingCreatures object = program.getPossessedObject(); object.endJump(); } }
package models; import javax.persistence.Entity; import play.db.jpa.Model; import java.sql.*; public class BaseModel extends Model { public Timestamp createTime; public Timestamp updateTime; public String createUser; public String updateUser; public Boolean deleted; }
package COM.JambPracPortal.BEAN; import COM.JambPracPortal.DAO.DAO; import com.sendgrid.Content; import com.sendgrid.Email; import com.sendgrid.Mail; import com.sendgrid.Method; import com.sendgrid.Request; import com.sendgrid.Response; import com.sendgrid.SendGrid; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Properties; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; @ManagedBean @SessionScoped public class certApplicationBEAN extends DAO { int counter = 0; private String emailAddress; private String username; private String cclno; private String dateApplied; private String AccounterUsername; public String getEmailAddress() { return this.emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getCclno() { return this.cclno; } public void setCclno(String cclno) { this.cclno = cclno; } public String getDateApplied() { return this.dateApplied; } public void setDateApplied(String dateApplied) { this.dateApplied = dateApplied; } public void retriveCurrentUsernameFromUI() { ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext(); this.username = (String) ec.getRequestParameterMap().get("certAppform:myusername"); System.out.println("ABCD" + this.username); } public void applyfor_certMthd() throws Exception { retriveCurrentUsernameFromUI(); this.Connector();// PreparedStatement st1 = getCn().prepareStatement("select username from cert_application where username=?"); st1.setString(1, this.username); ResultSet rs = st1.executeQuery(); PreparedStatement st2 = getCn().prepareStatement("select username from enrollment where username=?"); st2.setString(1, this.username); ResultSet rs2 = st2.executeQuery(); if (rs.next()) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Error in Cert_application. This username has already applied for a certificate in our database. Pls, check with the company staff", "thank you!")); } else if (rs2.next()) { String status = ""; try { this.Connector();// PreparedStatement st = getCn().prepareStatement("INSERT INTO cert_application values(null,?, Date(Now()), status)"); st.setString(1, this.username); st.executeUpdate(); st.close(); counter++; FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "You successfully applied for a certificate! thank you! ", "Details have been sent to your email address")); PreparedStatement st3 = getCn().prepareStatement("SELECT emailid,cclno,c.username,dateapplied FROM enrollment e inner join cert_application c ON e.username = c.username WHERE e.username=?"); st3.setString(1, this.username); ResultSet rs3 = st3.executeQuery(); while (rs3.next()) { String myemail = rs3.getString(1); this.emailAddress = myemail; System.out.println(" Testing the email ID from the while-block:" + myemail + "counter :" + this.counter + "email2: " + this.emailAddress); String mycclNo = rs3.getString(2); this.cclno = mycclNo; String myUsernamer = rs3.getString(3); this.AccounterUsername = myUsernamer; String myDate = rs3.getString(4); this.dateApplied = myDate; st3.close(); sendCertApplicationMail(); ExternalContext redcontext = FacesContext.getCurrentInstance().getExternalContext(); redcontext.redirect("successful_Cert_application.xhtml"); } } catch (Exception e) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Error in cert_application. Pls, try again ", "thank you!")); } finally { this.Close(); } } else { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Error in Cert_application. This username doe NOT exist. Pls, try again", "thank you!")); st2.close(); this.Close(); } } public void sendCertApplicationMail() throws IOException, Exception { System.out.println("Im sending to: " + emailAddress); Email from = new Email("cloudsoftconsultingltd@gmail.com"); String subject = "CLOUDSOFT CONSULTING LIMITED (CCL) Cert. Application Confirmation)"; Email toRecipient = new Email(emailAddress); Content content = new Content("text/plain", "\n\n Thank you for applying for a certficate at CCL. \n\n CCL Team will get back to you after verification. \n\n Find below the details used for the application: \nCCL No: " + this.cclno + "\n" + " Username: " + this.AccounterUsername + "\n" + "E-mail id:" + this.emailAddress + "\n" + "Date Applied: " + this.dateApplied + "\n"); Mail mail = new Mail(from, subject, toRecipient, content); SendGrid sg = new SendGrid(APIKeyClass.apiKey); Request request = new Request(); System.out.println("Testing before sending the mail"); try { request.setMethod(Method.POST); request.setEndpoint("mail/send"); request.setBody(mail.build()); Response response = sg.api(request); System.out.println(response.getStatusCode()); System.out.println(response.getBody()); System.out.println(response.getHeaders()); System.out.println("SendMail After Sending Testing message: Sendmail is SUccessful"); } catch (Exception e) { throw e; } }//end of the sendMail method public void certApproval() throws Exception { int counter2 = 0; this.Connector();// //CHECKS IF A USER HAS APPLIED FOR A CERTIFICATE PreparedStatement st1 = getCn().prepareStatement("select username from cert_application where username=?"); st1.setString(1, this.username); ResultSet rs = st1.executeQuery(); //CHECK IF CERT APPROVAL HAS BEEN GRANTED TO A USER (AFTER he HAS APPLIED FOR THE CERT) PreparedStatement st2 = getCn().prepareStatement("select username from cert_application where username=? AND status= 'Approved' "); st2.setString(1, this.username); ResultSet rs3 = st2.executeQuery(); if (rs3.next()) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Information in Cert_application. This username HAS ALREADY applied for cert. and approval is been granted", " Thank you!")); } else if (rs.next()) { try { PreparedStatement st = getCn().prepareStatement("UPDATE cert_application SET status= 'Approved' WHERE username=? "); st.setString(1, this.username); st.executeUpdate(); st.close(); counter2++; FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Cer_Approval Approval", "Your Certificate Request has been approved for " + this.username + " . Details have been sent via the user e-mail.")); if (counter2 > 0) { sendApprovalMail(); } } catch (Exception e) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Error Cert_application", "Pls, check your entries " + e)); } finally { this.Close(); } } else { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Error in Cert_application. This username has NOT applied for a certificate", " Pls, ask him/her apply now. Thank you!")); st1.close(); this.Close(); } } public void sendApprovalMail() throws IOException, Exception { System.out.println("Im sending to: " + emailAddress); Email from = new Email("cloudsoftconsultingltd@gmail.com"); String subject = "CLOUDSOFT CONSULTING LIMITED (CCL) Cert. Approval/Invitation for Collection"; Email toRecipient = new Email(emailAddress); Content content = new Content("text/plain", "\n\n Your CCL certificate has been approved. \n\n Find below the details used for the approval: \nCCL No: " + this.cclno + "\n" + " Username: " + this.AccounterUsername + "\n" + "\n" + "E-mail id:" + this.emailAddress + "\n" + "The certificate hard copy will be ready after 7-days. " + "\n" + "Regards." + "\n\n" + "CCL Team" + "\n"); Mail mail = new Mail(from, subject, toRecipient, content); SendGrid sg = new SendGrid(APIKeyClass.apiKey); Request request = new Request(); System.out.println("Testing before sending the mail"); try { request.setMethod(Method.POST); request.setEndpoint("mail/send"); request.setBody(mail.build()); Response response = sg.api(request); System.out.println(response.getStatusCode()); System.out.println(response.getBody()); System.out.println(response.getHeaders()); System.out.println("SendMail After Sending Testing message: Sendmail is SUccessful"); } catch (Exception e) { throw e; } }//end of the sendMail method }//end of the class
package geometry; import java.awt.Color; import math.Coord; import math.Point3D; import math.Vecteur3D; public class Cube extends Shape3D { /** Constructeur */ public Cube(Shape3D parent, double x, double y, double z) { super(parent, x, y, z); Point3D p1 = new Point3D(0, 0, 0); Point3D p2 = new Point3D(1, 0, 0); Point3D p3 = new Point3D(1, 1, 0); Point3D p4 = new Point3D(0, 1, 0); Point3D p5 = new Point3D(0, 0, 1); Point3D p6 = new Point3D(1, 0, 1); Point3D p7 = new Point3D(1, 1, 1); Point3D p8 = new Point3D(0, 1, 1); // z = 0 Triangle triangle1 = new Triangle(p1, p2, p3); triangle1.setNormal(new Vecteur3D(0, 0, -1)); triangle1.setColor(Color.red); triangle1.setCoord(new Coord(0.0, 0.0), new Coord(1.0, 0.0), new Coord(1.0, 1.0)); Triangle triangle2 = new Triangle(p1, p3, p4); triangle2.setNormal(new Vecteur3D(0, 0, -1)); triangle2.setColor(Color.red); triangle2.setCoord(new Coord(0.0, 0.0), new Coord(1.0, 1.0), new Coord(0.0, 1.0)); // z = 1 Triangle triangle3 = new Triangle(p5, p6, p7); triangle3.setNormal(new Vecteur3D(0, 0, 1)); triangle3.setColor(Color.blue); triangle3.setCoord(new Coord(0.0, 0.0), new Coord(1.0, 0.0), new Coord(1.0, 1.0)); Triangle triangle4 = new Triangle(p5, p7, p8); triangle4.setNormal(new Vecteur3D(0, 0, 1)); triangle4.setColor(Color.blue); triangle4.setCoord(new Coord(0.0, 0.0), new Coord(1.0, 1.0), new Coord(0.0, 1.0)); // x = 0 Triangle triangle5 = new Triangle(p1, p2, p6); triangle5.setNormal(new Vecteur3D(0, -1, 0)); triangle5.setColor(Color.green); triangle5.setCoord(new Coord(0.0, 0.0), new Coord(1.0, 0.0), new Coord(1.0, 1.0)); Triangle triangle6 = new Triangle(p1, p6, p5); triangle6.setNormal(new Vecteur3D(0, -1, 0)); triangle6.setColor(Color.green); triangle6.setCoord(new Coord(0.0, 0.0), new Coord(1.0, 1.0), new Coord(0.0, 1.0)); // x = 1 Triangle triangle7 = new Triangle(p3, p4, p8); triangle7.setNormal(new Vecteur3D(0, 1, 0)); triangle7.setColor(Color.pink); triangle7.setCoord(new Coord(0.0, 0.0), new Coord(1.0, 0.0), new Coord(1.0, 1.0)); Triangle triangle8 = new Triangle(p3, p8, p7); triangle8.setNormal(new Vecteur3D(0, 1, 0)); triangle8.setColor(Color.pink); triangle8.setCoord(new Coord(0.0, 0.0), new Coord(1.0, 1.0), new Coord(0.0, 1.0)); // y = 0 Triangle triangle9 = new Triangle(p1, p4, p8); triangle9.setNormal(new Vecteur3D(-1, 0, 0)); triangle9.setColor(Color.orange); triangle9.setCoord(new Coord(0.0, 0.0), new Coord(1.0, 0.0), new Coord(1.0, 1.0)); Triangle triangle10 = new Triangle(p1, p8, p5); triangle10.setNormal(new Vecteur3D(-1, 0, 0)); triangle10.setColor(Color.orange); triangle10.setCoord(new Coord(0.0, 0.0), new Coord(1.0, 1.0), new Coord(0.0, 1.0)); // y = 1 Triangle triangle11 = new Triangle(p2, p3, p7); triangle11.setNormal(new Vecteur3D(1, 0, 0)); triangle11.setColor(Color.cyan); triangle11.setCoord(new Coord(0.0, 0.0), new Coord(1.0, 0.0), new Coord(1.0, 1.0)); Triangle triangle12 = new Triangle(p2, p7, p6); triangle12.setNormal(new Vecteur3D(1, 0, 0)); triangle12.setColor(Color.cyan); triangle12.setCoord(new Coord(0.0, 0.0), new Coord(1.0, 1.0), new Coord(0.0, 1.0)); addTriangle(triangle1); addTriangle(triangle2); addTriangle(triangle3); addTriangle(triangle4); addTriangle(triangle5); addTriangle(triangle6); addTriangle(triangle7); addTriangle(triangle8); addTriangle(triangle9); addTriangle(triangle10); addTriangle(triangle11); addTriangle(triangle12); } }
package com.blog.system.action; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.blog.system.Dao.*; import com.blog.system.Dto.*; public class MessageServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String param = request.getParameter("param"); if (param == null) { param = "view"; } if (param == "view" || param.equals("view")) { getMessage(request, response); } else if (param == "del" || param.equals("del")) { try { String messageid = request.getParameter("messageid"); MessageDao md = new MessageDao(); md.delMessage(messageid); } catch (Exception e) { e.printStackTrace(); } getMessage(request, response); } else if (param == "singlemessage" || param.equals("singlemessage")) { String messageid = request.getParameter("messageid"); MessageDao md = new MessageDao(); MessageBean mb = md.getSingleMessage(messageid); request.setAttribute("singlemessage", mb); RequestDispatcher requestDispatcher = request .getRequestDispatcher("/system/singlecomment.jsp"); requestDispatcher.forward(request, response); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public void getMessage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { int page; if (request.getParameter("page") != null) { page = Integer.parseInt(request.getParameter("page")); } else { page = 1; } int size = 10; List<MessageBean> ret = new ArrayList<MessageBean>(); MessageDao md = new MessageDao(); try { ret = md.getSystemMessage(page, size); long count = md.getSystemMessageCount(); request.setAttribute("message", ret); request.setAttribute("count", count); request.setAttribute("page", page); request.setAttribute("size", size); RequestDispatcher requestDispatcher = request .getRequestDispatcher("/system/systemmessage.jsp"); requestDispatcher.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC5 { public static void main(String[] args) { // TODO Auto-generated method stub Connection con = null; Statement st = null; ResultSet rs = null; //1. Driver loading try { Class.forName("com.mysql.cj.jdbc.Driver"); //2. Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3305/scott?serverTimezone=UTC&useUniCode=yes&characterEncoding=UTF-8","ssafy","ssafy"); // 3. Statement create int empno = 8888; String name= "도우너"; int sal = 3000; int deptno = 30; String sql = "insert into emp(empno, ename, sal, deptno) values(?,?,?,?)"; PreparedStatement pSt = con.prepareStatement(sql); pSt.setInt(1,empno); pSt.setString(2, name); pSt.setInt(3,sal); pSt.setInt(4,deptno); // 4. SQL Execute pSt.executeUpdate(); System.out.println("입력 성공!"); } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); System.out.println("class loading fail"); }finally { // 5. close try { if(rs!=null) rs.close(); if(st!=null) st.close(); if(con!=null) con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package org.basic.comp.adapter; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.record.impl.ODocument; import org.basic.comp.abst.WidgetPrivilege; import org.basic.comp.listener.MasterInterface; import org.basic.comp.listener.WiddgetSyncInterface; import javax.swing.*; public class MasterAdapter implements MasterInterface, WidgetPrivilege, EfectWidget{ protected JPanel panel; protected boolean perspectiveDefault=true; protected WindowInterfaces window; @Override public void build(ODatabaseDocumentTx db) { // TODO Auto-generated method stub } @Override public void load(ODocument model) { // TODO Auto-generated method stub } @Override public void perspectiveDefault() { // TODO Auto-generated method stub } @Override public void perspective1() { // TODO Auto-generated method stub } @Override public void perspective2() { // TODO Auto-generated method stub } @Override public void perspective3() { // TODO Auto-generated method stub } @Override public void perspective4() { // TODO Auto-generated method stub } @Override public void changePrivilege() { // TODO Auto-generated method stub } @Override public void actionAdd() { // TODO Auto-generated method stub } @Override public void actionEdit() { // TODO Auto-generated method stub } @Override public void actionView() { // TODO Auto-generated method stub } @Override public void actionReload() { // TODO Auto-generated method stub } @Override public void actionDel() { // TODO Auto-generated method stub } @Override public void actionPrint() { // TODO Auto-generated method stub } @Override public boolean isAdd() { // TODO Auto-generated method stub return false; } @Override public boolean isDel() { // TODO Auto-generated method stub return false; } @Override public boolean isView() { // TODO Auto-generated method stub return false; } @Override public boolean isEdit() { // TODO Auto-generated method stub return false; } @Override public boolean isPrint() { // TODO Auto-generated method stub return false; } @Override public String getTitle() { // TODO Auto-generated method stub return null; } @Override public String getUrlIcon() { // TODO Auto-generated method stub return null; } // public List<ToolbarSmallAdapter> getChangeStateActions() { // return changeStateActions; // } // // public void setChangeStateActions(List<ToolbarSmallAdapter> changeStateActions) { // this.changeStateActions = changeStateActions; // } @Override public WindowInterfaces getWindow() { return window; } @Override public void setWindow(WindowInterfaces window) { this.window = window; } public JPanel getPanel() { return panel; } public void setPanel(JPanel panel) { this.panel = panel; } public boolean isPerspectiveDefault() { return perspectiveDefault; } public void setPerspectiveDefault(boolean perspectiveDefault) { this.perspectiveDefault = perspectiveDefault; } @Override public Icon getIcon16() { // TODO Auto-generated method stub return null; } @Override public Icon getIcon32() { // TODO Auto-generated method stub return null; } @Override public void actionSearch() { // TODO Auto-generated method stub } @Override public void actionPdf() { // TODO Auto-generated method stub } @Override public void actionWord() { // TODO Auto-generated method stub } @Override public void actionExcel() { // TODO Auto-generated method stub } @Override public boolean isSearch() { // TODO Auto-generated method stub return false; } @Override public boolean isPdf() { // TODO Auto-generated method stub return false; } @Override public boolean isWord() { // TODO Auto-generated method stub return false; } @Override public boolean isExcel() { // TODO Auto-generated method stub return false; } @Override public void actionPrintPreview() { // TODO Auto-generated method stub } @Override public String getTitleToolBar() { // TODO Auto-generated method stub return null; } @Override public void addSync(WiddgetSyncInterface widgetSync, int code) { // TODO Auto-generated method stub } @Override public void syncWidget(ODocument o, int code) { // TODO Auto-generated method stub } @Override public void requestDefaultSelected() { // TODO Auto-generated method stub } }
package Stack.SpecialStack; public class SpecialStack extends Stack { private Stack min; public SpecialStack() { this.min = new Stack(); } /* * SpecialStack's member method to insert an element to it. This method makes * sure that the min stack is also updated with appropriate minimum values */ @Override public boolean push(int data) { if (isEmpty()) { super.push(data); min.push(data); return true; } else { super.push(data); int x = min.pop(); min.push(x); if (data > x) { min.push(x); return true; } else { min.push(data); return true; } } } /* * SpecialStack's member method to insert an element to it. This method makes * sure that the min stack is also updated with appropriate minimum values */ @Override public int pop() { int x = super.pop(); min.pop(); return x; } /* * SpecialStack's member method to get minimum element from it. */ public int getMin() { int x = min.pop(); min.push(x); return x; } public static void main(String[] args) { SpecialStack s = new SpecialStack(); s.push(10); s.push(20); s.push(30); s.push(40); s.push(50); s.push(1); System.out.println("Minimum : " + s.getMin()); s.pop(); System.out.println("Minimum : " + s.getMin()); } }
package com.dreamcatcher.factory; import com.dreamcatcher.action.Action; import com.dreamcatcher.member.action.*; public class MemberActionFactory { private static Action memberJoinAction; private static Action memberMyInfoAction; private static Action memberModifyAction; private static Action memberLoginAction; private static Action memberLogoutAction; private static Action memberIdCheckAction; private static Action memberResetPasswordAction; private static Action memberPasswordCheckAction; private static Action memberContactAction; private static Action memberLoginWithOAuthAction; private static Action memberLoginWithTwitterAction; private static Action memberLoginWithTwitterCallbackAction; static{ memberJoinAction = new MemberJoinAction(); memberMyInfoAction = new MemberMyInfoAction(); memberModifyAction = new MemberModifyAction(); memberLoginAction = new MemberLoginAction(); memberLogoutAction = new MemberLogoutAction(); memberIdCheckAction = new MemberIdCheckAction(); memberResetPasswordAction = new MemberResetPasswordAction(); memberPasswordCheckAction = new MemberPasswordCheckAction(); memberContactAction = new MemberContactAction(); memberLoginWithOAuthAction = new MemberLoginWithOAuthAction(); memberLoginWithTwitterAction = new MemberLoginWithTwitterAction(); memberLoginWithTwitterCallbackAction = new MemberLoginWithTwitterCallbackAction(); } public static Action getMemberLoginWithTwitterCallbackAction() { return memberLoginWithTwitterCallbackAction; } public static Action getMemberLoginWithTwitterAction() { return memberLoginWithTwitterAction; } public static Action getMemberLoginWithOAuthAction() { return memberLoginWithOAuthAction; } public static Action getMemberContactAction() { return memberContactAction; } public static Action getMemberMyInfoAction() { return memberMyInfoAction; } public static Action getMemberPasswordCheckAction() { return memberPasswordCheckAction; } public static Action getMemberJoinAction() { return memberJoinAction; } public static Action getMemberModifyAction() { return memberModifyAction; } public static Action getMemberLoginAction() { return memberLoginAction; } public static Action getMemberLogoutAction() { return memberLogoutAction; } public static Action getMemberIdCheckAction() { return memberIdCheckAction; } public static Action getMemberResetPasswordAction() { return memberResetPasswordAction; } }
package ru.kappers.repository; import org.springframework.data.jpa.repository.JpaRepository; import ru.kappers.model.leonmodels.MarketLeon; import ru.kappers.model.leonmodels.OddsLeon; import ru.kappers.model.leonmodels.RunnerLeon; import java.util.List; public interface RunnerLeonRepository extends JpaRepository<RunnerLeon, Long> { List<RunnerLeon> getByMarketAndOdd(MarketLeon market, OddsLeon odd); RunnerLeon getFirstByMarketAndOddAndName(MarketLeon market, OddsLeon odd, String name); List<RunnerLeon> getByOdd(OddsLeon odd); void deleteAllByOdd(OddsLeon odd); }
package br.univel.produto; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the br.univel.produto package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _LerProduto_QNAME = new QName("http://webservices.univel.br/", "Ler_Produto"); private final static QName _CadastrarProduto_QNAME = new QName("http://webservices.univel.br/", "Cadastrar_Produto"); private final static QName _LerProdutoResponse_QNAME = new QName("http://webservices.univel.br/", "Ler_ProdutoResponse"); private final static QName _ExcluirProdutoResponse_QNAME = new QName("http://webservices.univel.br/", "Excluir_ProdutoResponse"); private final static QName _AtualizarProduto_QNAME = new QName("http://webservices.univel.br/", "Atualizar_Produto"); private final static QName _AtualizarProdutoResponse_QNAME = new QName("http://webservices.univel.br/", "Atualizar_ProdutoResponse"); private final static QName _CadastrarProdutoResponse_QNAME = new QName("http://webservices.univel.br/", "Cadastrar_ProdutoResponse"); private final static QName _ExcluirProduto_QNAME = new QName("http://webservices.univel.br/", "Excluir_Produto"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: br.univel.produto * */ public ObjectFactory() { } /** * Create an instance of {@link AtualizarProdutoResponse } * */ public AtualizarProdutoResponse createAtualizarProdutoResponse() { return new AtualizarProdutoResponse(); } /** * Create an instance of {@link CadastrarProdutoResponse } * */ public CadastrarProdutoResponse createCadastrarProdutoResponse() { return new CadastrarProdutoResponse(); } /** * Create an instance of {@link ExcluirProduto } * */ public ExcluirProduto createExcluirProduto() { return new ExcluirProduto(); } /** * Create an instance of {@link ExcluirProdutoResponse } * */ public ExcluirProdutoResponse createExcluirProdutoResponse() { return new ExcluirProdutoResponse(); } /** * Create an instance of {@link AtualizarProduto } * */ public AtualizarProduto createAtualizarProduto() { return new AtualizarProduto(); } /** * Create an instance of {@link LerProdutoResponse } * */ public LerProdutoResponse createLerProdutoResponse() { return new LerProdutoResponse(); } /** * Create an instance of {@link LerProduto } * */ public LerProduto createLerProduto() { return new LerProduto(); } /** * Create an instance of {@link CadastrarProduto } * */ public CadastrarProduto createCadastrarProduto() { return new CadastrarProduto(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link LerProduto }{@code >}} * */ @XmlElementDecl(namespace = "http://webservices.univel.br/", name = "Ler_Produto") public JAXBElement<LerProduto> createLerProduto(LerProduto value) { return new JAXBElement<LerProduto>(_LerProduto_QNAME, LerProduto.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CadastrarProduto }{@code >}} * */ @XmlElementDecl(namespace = "http://webservices.univel.br/", name = "Cadastrar_Produto") public JAXBElement<CadastrarProduto> createCadastrarProduto(CadastrarProduto value) { return new JAXBElement<CadastrarProduto>(_CadastrarProduto_QNAME, CadastrarProduto.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link LerProdutoResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://webservices.univel.br/", name = "Ler_ProdutoResponse") public JAXBElement<LerProdutoResponse> createLerProdutoResponse(LerProdutoResponse value) { return new JAXBElement<LerProdutoResponse>(_LerProdutoResponse_QNAME, LerProdutoResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ExcluirProdutoResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://webservices.univel.br/", name = "Excluir_ProdutoResponse") public JAXBElement<ExcluirProdutoResponse> createExcluirProdutoResponse(ExcluirProdutoResponse value) { return new JAXBElement<ExcluirProdutoResponse>(_ExcluirProdutoResponse_QNAME, ExcluirProdutoResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AtualizarProduto }{@code >}} * */ @XmlElementDecl(namespace = "http://webservices.univel.br/", name = "Atualizar_Produto") public JAXBElement<AtualizarProduto> createAtualizarProduto(AtualizarProduto value) { return new JAXBElement<AtualizarProduto>(_AtualizarProduto_QNAME, AtualizarProduto.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AtualizarProdutoResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://webservices.univel.br/", name = "Atualizar_ProdutoResponse") public JAXBElement<AtualizarProdutoResponse> createAtualizarProdutoResponse(AtualizarProdutoResponse value) { return new JAXBElement<AtualizarProdutoResponse>(_AtualizarProdutoResponse_QNAME, AtualizarProdutoResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CadastrarProdutoResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://webservices.univel.br/", name = "Cadastrar_ProdutoResponse") public JAXBElement<CadastrarProdutoResponse> createCadastrarProdutoResponse(CadastrarProdutoResponse value) { return new JAXBElement<CadastrarProdutoResponse>(_CadastrarProdutoResponse_QNAME, CadastrarProdutoResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ExcluirProduto }{@code >}} * */ @XmlElementDecl(namespace = "http://webservices.univel.br/", name = "Excluir_Produto") public JAXBElement<ExcluirProduto> createExcluirProduto(ExcluirProduto value) { return new JAXBElement<ExcluirProduto>(_ExcluirProduto_QNAME, ExcluirProduto.class, null, value); } }
package com.Flonx.TestEquals; /** * @Auther:Flonx * @Date:2021/1/17 - 01 - 17 - 9:36 * @Description: com.Flonx.TestEquals * @Version: 1.0 */ public class Cat { }
public class GoldenSectionRatio { public static void main(String[] args) { float mindiff = 100; float result = 0; float breakpoint = 0.618f; int answerFenzi = 0;//找到的分子 int answerFenmu = 0;//找到的分母 for (int fenzi = 1;fenzi<20;fenzi++){ for (int fenmu = 1;fenmu<20;fenmu++){ float value = (float)fenzi/fenmu; float diff = value - breakpoint; diff = diff>0?diff:0-diff; if(diff<mindiff){ mindiff = diff; answerFenzi = fenzi; answerFenmu = fenmu; result = value; } } } System.out.println("距离0.618最近的两个数相除是:"+answerFenzi+"/"+answerFenmu); System.out.println("最小的差值是:"+mindiff); System.out.println("相除的结果是:"+result); } }
/* * 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.itesm.services; import com.itesm.classes.Login; import com.itesm.classes.checkLogged; import com.vaadin.event.ItemClickEvent; import com.vaadin.server.FileResource; import com.vaadin.server.VaadinService; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.ui.Button; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Image; import com.vaadin.ui.Label; import com.vaadin.ui.Notification; import com.vaadin.ui.Tree; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.Reindeer; import java.io.File; /** * * @author emmanuelpaez */ public class Frame { private VerticalLayout content = new VerticalLayout(); public VerticalLayout iniciar(UI ui){ if(new checkLogged().validate(VaadinService.getCurrentRequest().getWrappedSession().getAttribute("valido"))){ return logged(ui); }else{ return notLogged(ui); } } public VerticalLayout logged(UI ui){ //creamos layout general final VerticalLayout layout = new VerticalLayout(); //creamos titulo final HorizontalLayout title = new HorizontalLayout(); Label titulo = new Label("Crime report"); titulo.addStyleName(Reindeer.LABEL_H1); String basepath = VaadinService.getCurrent() .getBaseDirectory().getAbsolutePath(); FileResource resource = new FileResource(new File(basepath + "/WEB-INF/images/police.png")); Image image = new Image("", resource); image.setHeight("30px"); title.setSpacing(true); title.addComponent(titulo); title.addComponent(image); layout.addComponent(title); //agregamos linea separadora layout.addComponent(new Label("<hr />",Label.CONTENT_XHTML)); //creamos layout de menu y contenido final HorizontalLayout panel = new HorizontalLayout(); //cramos menu final VerticalLayout menu = new VerticalLayout(); Tree tree = new Tree("Menú"); tree.addItem("Crimenes"); tree.addItem("Nuevo Crimen"); tree.setChildrenAllowed("Nuevo Crimen", false); tree.addItem("Buscar Crimen"); tree.setChildrenAllowed("Buscar Crimen", false); tree.setParent("Nuevo Crimen","Crimenes"); tree.setParent("Buscar Crimen","Crimenes"); tree.addItem("Reporte"); tree.addItem("Estadisticas"); tree.setChildrenAllowed("Estadisticas", false); tree.addItem("Gráficas"); tree.setChildrenAllowed("Gráficas", false); tree.setParent("Estadisticas","Reporte"); tree.setParent("Gráficas","Reporte"); tree.addItem("Sesión"); tree.addItem("Finalizar Sesión"); tree.setParent("Finalizar Sesión","Sesión"); tree.setChildrenAllowed("Finalizar Sesión", false); tree.addItem("Acerca de"); tree.setChildrenAllowed("Acerca de", false); tree.addItemClickListener( new ItemClickEvent.ItemClickListener() { public void itemClick(ItemClickEvent event) { // Pick only left mouse clicks if (event.getItemId().toString().equals("Nuevo Crimen")){ ui.getPage().setLocation("addCrime"); } if (event.getItemId().toString().equals("Buscar Crimen")){ ui.getPage().setLocation("searchCrime"); } if (event.getItemId().toString().equals("Estadisticas")){ ui.getPage().setLocation("estadisticas"); } if (event.getItemId().toString().equals("Gráficas")){ ui.getPage().setLocation("graficas"); } if (event.getItemId().toString().equals("Finalizar Sesión")){ ui.getPage().setLocation("endSession"); } if (event.getItemId().toString().equals("Acerca de")){ ui.getPage().setLocation("about"); } } }); menu.addComponent(tree); menu.setWidth("40%"); panel.addComponent(menu); this.content.setWidth("60%"); this.content.setMargin(new MarginInfo(false, true, false, true)); panel.addComponent(this.content); layout.addComponent(panel); layout.setMargin(new MarginInfo(false, true, false, true)); return layout; } public VerticalLayout notLogged(UI ui){ final VerticalLayout layout = new VerticalLayout(); Label titulo = new Label("Sesión no iniciada"); titulo.addStyleName(Reindeer.LABEL_H1); layout.addComponent(titulo); layout.addComponent(new Label("Debes iniciar sesión primero.")); Button boton = new Button("Ir"); boton.addClickListener(new Button.ClickListener() { @Override public void buttonClick(final Button.ClickEvent event) { ui.getPage().setLocation("/FinalProyecto"); } }); layout.addComponent(boton); layout.setMargin(new MarginInfo(false, true, false, true)); return layout; } public VerticalLayout getContent() { return content; } public void setContent(VerticalLayout content) { this.content = content; } }
package com.cricmania.models; import java.util.List; import java.util.regex.Pattern; import play.modules.mongodb.jackson.MongoDB; import net.vz.mongodb.jackson.JacksonDBCollection; public class Team extends Modifiable { private String name; private List<PlayerMetaData> players; private String sponsoredBy; private String contactNumber; private String contactPerson; private String email; private String logoName; private Address address; private static JacksonDBCollection<Team, String> coll = MongoDB.getCollection(Team.class.getSimpleName(), Team.class, String.class); public String getName() { return name; } public void setName(String name) { this.name = name; } public List<PlayerMetaData> getPlayers() { return players; } public void setPlayers(List<PlayerMetaData> players) { this.players = players; } public String getSponsoredBy() { return sponsoredBy; } public void setSponsoredBy(String sponsoredBy) { this.sponsoredBy = sponsoredBy; } public String getContactNumber() { return contactNumber; } public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; } public String getContactPerson() { return contactPerson; } public void setContactPerson(String contactPerson) { this.contactPerson = contactPerson; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getLogoName() { return logoName; } public void setLogoName(String logoName) { this.logoName = logoName; } public static JacksonDBCollection<Team, String> getColl() { return coll; } public static void setColl(JacksonDBCollection<Team, String> coll) { Team.coll = coll; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public void save() { this.id = "TEA" + MetaDataDocument.getGeneratedId(Team.class.getSimpleName()); coll.save(this); } public static Team findById(String id) { return coll.findOneById(id); } public void update() { coll.updateById(this.id,this); } public static List<Team> getTeamByQuery(String q) { return coll.find().regex("name", Pattern.compile("(?i).*"+q+".*")).toArray(); } }
package day09_scanner_practice; import java.util.Scanner; public class TemperatureConv { public static void main(String [] args ){ Scanner input =new Scanner(System.in); System.out.println("Change F to C "); double faren = input.nextDouble(); System.out.println("Temperature in F is " +faren+ " F"); double cel = (faren -32)*5/9; System.out.println("Temperature in Celsius is "+cel+ " C"); } }
// // Este archivo ha sido generado por la arquitectura JavaTM para la implantación de la referencia de enlace (JAXB) XML v2.2.7 // Visite <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Todas las modificaciones realizadas en este archivo se perderán si se vuelve a compilar el esquema de origen. // Generado el: 2021.04.22 a las 01:46:13 AM CDT // package org.example.ventas; import javax.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the org.example.ventas package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.example.ventas * */ public ObjectFactory() { } /** * Create an instance of {@link RealizarVentaResponse } * */ public RealizarVentaResponse createRealizarVentaResponse() { return new RealizarVentaResponse(); } /** * Create an instance of {@link ModificarVentaResponse } * */ public ModificarVentaResponse createModificarVentaResponse() { return new ModificarVentaResponse(); } /** * Create an instance of {@link RealizarVentaRequest } * */ public RealizarVentaRequest createRealizarVentaRequest() { return new RealizarVentaRequest(); } /** * Create an instance of {@link EliminarVentaResponse } * */ public EliminarVentaResponse createEliminarVentaResponse() { return new EliminarVentaResponse(); } /** * Create an instance of {@link EliminarVentaRequest } * */ public EliminarVentaRequest createEliminarVentaRequest() { return new EliminarVentaRequest(); } /** * Create an instance of {@link ModificarVentaRequest } * */ public ModificarVentaRequest createModificarVentaRequest() { return new ModificarVentaRequest(); } }
package com.hhz.springboot.service; import com.hhz.springboot.bean.Student; import java.util.List; public interface StudentService { List<Student> getAllStudent(); }
package com.xhs.property.exception; import com.alibaba.fastjson.support.spring.FastJsonJsonView; import com.xhs.property.pojo.ResultEntity; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import sun.tools.tree.NullExpression; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeoutException; public class CustomExceptionResolver implements HandlerExceptionResolver { public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { ModelAndView modelAndView = new ModelAndView(); FastJsonJsonView view = new FastJsonJsonView(); Map<String, Object> errorResult = new HashMap<String, Object>(); if (e instanceof NullPointerException) { errorResult.put("message", "空指针" + e.getMessage()); } else if (e instanceof TimeoutException) { errorResult.put("message", "超时" + e.getMessage()); } System.out.println("时间"+e.getMessage()); errorResult.put("code", 203); errorResult.put("message",e.getMessage()); view.setAttributesMap(errorResult); modelAndView.setView(view); return modelAndView; } }
package dao; import dao.impl.RoleDaoImpl; import dao.impl.UserDaoImpl; import utilities.Dependencies; import models.Role; import models.User; import org.junit.Test; import testutils.BaseTest; import static org.junit.Assert.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class RoleDaoTest extends BaseTest { @Test public void testCreateAndFindRole() { dao.RoleDao roleDao = new RoleDaoImpl(); Dependencies.setRoleDao(roleDao); Role role = new Role(); roleDao.create("newrole"); role = roleDao.findByName("newrole"); assertEquals("newrole", role.name); assertNotNull(role.id); role = roleDao.findByName("nosuchrole"); assertNull(role); role = roleDao.create("anotherrole"); assertNotNull(role.id); role = roleDao.findByName("anotherrole"); assertNotNull(role); } @Test public void testRoleAssignment() { dao.RoleDao roleDao = new RoleDaoImpl(); dao.UserDao userDao = new UserDaoImpl(); Dependencies.setUserDao(userDao); Dependencies.setRoleDao(roleDao); Role role1 = roleDao.create("newrole"); Role role2 = roleDao.create("anothernewrole"); User user = userDao.create("Hadi", "Zolfaghari", "hadi@zolfaghari.com", "thepassword"); user.assignRole(role1, false); assertTrue("User must have assigned role", user.hasRole(role1)); assertFalse("User must not have unassigned role", user.hasRole(role2)); user = userDao.findByEmail("hadi@zolfaghari.com"); assertFalse("User must not have assigned role if not commited", user.hasRole(role1)); user.assignRole(role1); user = userDao.findByEmail("hadi@zolfaghari.com"); assertTrue("User must have assigned role", user.hasRole(role1)); assertFalse("User must not have unassigned role", user.hasRole(role2)); } }
package com.yicheng.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.yicheng.common.UserType; import com.yicheng.pojo.User; import com.yicheng.service.UserService; import com.yicheng.util.GenericJsonResult; import com.yicheng.util.GenericResult; import com.yicheng.util.ResultCode; import com.yicheng.util.UserInfoStorage; import com.yicheng.util.Utils; @Controller public class IdentityController { @Autowired private UserService userService; @RequestMapping(value = { "/", "/Login" }, method = RequestMethod.GET) public ModelAndView loginView(HttpServletRequest request, HttpServletResponse response) throws IOException { return new ModelAndView("login", null); } @ResponseBody @RequestMapping(value = { "/Login" }, method = RequestMethod.POST) public GenericJsonResult<String> login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { GenericJsonResult<String> result = new GenericJsonResult<String>(); String name = request.getParameter("name"); String password = request.getParameter("password"); if (StringUtils.isBlank(name) || StringUtils.isBlank(password)) { // response.sendRedirect(request.getContextPath() + "/Login"); result.setResultCode(ResultCode.E_OTHER_ERROR); result.setMessage("username and password cannot be blank");; return result; } int userType = Utils.getRequestIntValue(request, "userType", true); name = name.trim(); password = password.trim(); GenericResult<User> userResult = userService.search( name, password, userType); if (userResult.getResultCode() == ResultCode.NORMAL) { User user = userResult.getData(); String sessionId = request.getSession(true).getId(); UserInfoStorage.putUser(sessionId, user); switch (userType) { case UserType.USER_TYPE_PROOFING: result.setData("Proofing/ClothMaterialManage"); break; case UserType.USER_TYPE_PRICING: result.setData("Pricing/ClothPriceToProcess"); break; case UserType.USER_TYPE_BUYER: result.setData("Buyer/ClothCountToProcess"); break; case UserType.USER_TYPE_MANAGER: result.setData("Manager/ClothMaterialManage"); break; default: break; } } else { result.setResultCode(userResult.getResultCode()); result.setMessage(userResult.getMessage()); } return result; } @RequestMapping(value = { "/Logout", "/logout" }) public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException { UserInfoStorage.removeUser(request.getSession(true).getId()); response.sendRedirect(request.getContextPath() + "/Login"); return; } }
package com.igitras.codegen.common.next; import com.igitras.codegen.common.next.annotations.NotNull; /** * JavaResolveResult holds additional information that is obtained * when Java references are being resolved. * <p> * Created by mason on 1/5/15. */ public interface JavaResolveResult extends ResolveResult { /** * Substitutor providing values of type parameters occurring in {@link #getElement()}. */ @NotNull CgSubstitutor getSubstitutor(); boolean isPackagePrefixPackageReference(); /** * @return true if {@link #getElement()} is accessible from reference. */ boolean isAccessible(); boolean isStaticsScopeCorrect(); /** * @return scope in the reference's file where the reference has been resolved, * {@code null} for qualified and local references. */ CgElement getCurrentFileResolveScope(); }
package kz.kbtu.auth.base; import kz.kbtu.util.CustomHasher; import java.io.Serializable; import java.util.Objects; public abstract class User extends Person implements Serializable { private String login; private String password; private String phoneNumber; private String email; { this.password = CustomHasher.getInstance().hash("Kbtu111"); // System.out.println("This password " + this.password); } protected User(String login, String firstName, String lastName) { super(firstName, lastName); this.login = login; } public String getLogin() { return login; } public void setPassword(String password) { this.password = CustomHasher.getInstance().hash(password); } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean checkCredentials(String login, String password) { String hashedPassword = CustomHasher.getInstance().hash(password); return this.login.equals(login) && this.password.equals(hashedPassword); } public void print() { System.out.println(String.format("Full name: %s [%s]", getFullName(), login)); System.out.println(String.format("Birth date: %s", getBirthDate())); System.out.println(String.format("Gender: %s", getGender())); System.out.println(String.format("Phone number: %s", phoneNumber)); System.out.println(String.format("Email: %s", email)); } @Override public String toString() { return String.format("login: %s, %s", login, super.toString()); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; if (!super.equals(o)) return false; User user = (User) o; return login.equals(user.login) && password.equals(user.password); } @Override public int hashCode() { return Objects.hash(super.hashCode(), login); } }
package cn.zhoudbw.customizer; import org.springframework.boot.web.server.ConfigurableWebServerFactory; import org.springframework.boot.web.server.ErrorPage; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; /** * @author zhoudbw * 使用WebServerFactoryCustomizer设置错误页面 * @COnfiguration 声明这是一个配置文件,需要使用这个类声明bean,代替xml文件的 */ @Configuration public class MyCustomizer { /** * 因为是配置相关的,所以泛型自然要传递配置相关的,要求<T extends WebServerFactory>,传递ConfigurableWebServerFactory */ @Bean public WebServerFactoryCustomizer<ConfigurableWebServerFactory> customizer() { return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() { @Override public void customize(ConfigurableWebServerFactory factory) { /* // 创建错误页,使用下述构造方法 public ErrorPage(HttpStatus status, String path) { this.status = status; this.exception = null; this.path = path; } status表示状态码 path表示请求路径 当status==404时,转发到/error404请求 */ ErrorPage errorPage = new ErrorPage(HttpStatus.NOT_FOUND, "/error404"); // 设置错误页 factory.addErrorPages(errorPage); } }; } }
package com.example.androidtest; import android.app.Activity; import android.os.Bundle; /** * Created by linyun on 14-5-4. */ public class LauncherActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
package com.chris.projects.fx.ftp.fix; import com.chris.projects.fx.ftp.core.OrderBookService; import quickfix.MessageCracker; import quickfix.SessionID; import quickfix.fix44.NewOrderSingle; public class FTPFixMessageReceiver extends MessageCracker { private OrderBookService orderBookService; public FTPFixMessageReceiver(OrderBookService orderBookService) { this.orderBookService = orderBookService; } @Handler public void onMessage(NewOrderSingle message, SessionID sessionID) { //handle message } }
package com.tt.miniapp; import com.tt.miniapp.util.ToolUtils; import com.tt.miniapphost.AppBrandLogger; import com.tt.miniapphost.AppbrandApplication; import com.tt.miniapphost.entity.AppInfoEntity; import com.tt.miniapphost.util.ProcessUtil; import com.tt.option.q.d; import java.util.Map; import okhttp3.ac; public class RequestInceptUtil { public static String getRequestReferer() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(AppbrandConstant.OpenApi.getInst().getRequestRefere()); if (ProcessUtil.isMiniappProcess()) { AppInfoEntity appInfoEntity = AppbrandApplication.getInst().getAppInfo(); if (appInfoEntity != null && appInfoEntity.appId != null && appInfoEntity.version != null) { stringBuilder.append("?appid="); stringBuilder.append(appInfoEntity.appId); stringBuilder.append("&version="); stringBuilder.append(appInfoEntity.version); } } return stringBuilder.toString(); } public static void inceptRequest(ac.a parama) { parama.b("User-Agent"); String str = ToolUtils.getCustomUA(); AppBrandLogger.d("tma_RequestInceptUtil", new Object[] { "custom UA = ", str }); parama.b("User-Agent", str); if (d.b()) parama.b("referer"); parama.b("referer", getRequestReferer()); } public static void interceptRequest(Map<String, String> paramMap) { for (String str1 : paramMap.keySet()) { if (str1.equalsIgnoreCase("User-Agent")) paramMap.remove(str1); if (str1.equalsIgnoreCase("referer") && d.b()) paramMap.remove(str1); } String str = ToolUtils.getCustomUA(); AppBrandLogger.d("tma_RequestInceptUtil", new Object[] { "custom UA = ", str }); paramMap.put("User-Agent", str); paramMap.put("referer", getRequestReferer()); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\RequestInceptUtil.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package boardFinder.demo.service; import boardFinder.demo.domain.Shape; import boardFinder.demo.repository.ShapeRepository; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * * @author Erik */ @Service public class ShapeService { private ShapeRepository shapeRepository; @Autowired public ShapeService(ShapeRepository shapeRepository) { this.shapeRepository = shapeRepository; } public List<Shape> getAllShapes(){ return shapeRepository.findAll(); } public Optional<Shape> getShapeById(Long id){ return shapeRepository.findById(id); } /* public Brand getBrandByName(String name){ return brandRepository.findByName(name); } */ public Shape save(Shape shape){ return shapeRepository.save(shape); } }
package twilight.bgfx; /** * * @author tmccrary * */ public class VertexDecl { /** */ private long vertexDeclPtr; /** */ private boolean buildActive; /** */ private boolean valid; private VertexDecl() { valid = false; buildActive = false; } /** * */ private void checkDeclBegin() { if (vertexDeclPtr != 0) { throw new BGFXException("VertexDecl#begin already called on vertex declaration, did you call it twice?"); } } /** * */ private void checkDecl() { if (vertexDeclPtr == 0) { throw new BGFXException("Vertex declaration has not been initialized. VertexDecl#begin must be called before other methods can be used."); } } /** * */ public void checkBuildActive() { if (!buildActive) { throw new BGFXException("Cannot call methods on vertex declaration before it has been initialized with VertexDecl#begin."); } } /** * * @return */ public boolean isValid() { return valid && !buildActive; } public static VertexDecl begin() { VertexDecl decl = new VertexDecl(); decl.intBegin(RendererType.Count); return decl; } public static VertexDecl begin(RendererType _renderer) { VertexDecl decl = new VertexDecl(); decl.intBegin(_renderer); return decl; } private void intBegin(RendererType _renderer) { checkDeclBegin(); vertexDeclPtr = this.nbegin(_renderer); buildActive = true; } public void end() { checkDecl(); this.nend(); buildActive = false; valid = true; } public void destroy() { ndestroy(); } private native void ndestroy(); private native long nbegin(RendererType type); private native void nend(); public void add(Attrib _attrib, int elements, AttribType _type, boolean _normalized, boolean _asInt) { checkDecl(); this.nAdd(_attrib.ordinal(), (short) elements, _type.ordinal(), _normalized, _asInt); } private native void nAdd(int _attrib, short _num, int _type, boolean _normalized, boolean _asInt); void skip(short _num) { checkDecl(); this.nSkip(_num); } private native void nSkip(short _num); public void decode(Attrib _attrib, int _num, AttribType _type, boolean _normalized, boolean _asInt) { checkDecl(); this.nDecode(_attrib, (short) _num, _type, _normalized, _asInt); } private native void nDecode(Attrib _attrib, short _num, AttribType _type, boolean _normalized, boolean _asInt); public boolean has(Attrib _attrib) { checkDecl(); return nHas(_attrib); } private native boolean nHas(Attrib attrib); public int getOffset(Attrib _attrib) { checkDecl(); return ngetOffset(_attrib); } private native int ngetOffset(Attrib attrib); int getStride() { checkDecl(); return ngetStride(); } private native int ngetStride(); long getSize(long _num) { checkDecl(); return ngetSize(_num); } private native long ngetSize(long num); }
/* * This Java source file was generated by the Gradle 'init' task. */ package micronaut.starter.kit; import io.micronaut.context.ApplicationContext; import org.dom4j.DocumentException; public class App { public static void main(String[] args) { ApplicationContext ctx = ApplicationContext.run(); FlowParser flowParser = ctx.getBean(FlowParser.class); ArgumentBean argument = ctx.getBean(ArgumentBean.class).build(args); PDFParser pdfParser = ctx.getBean(PDFParser.class); MarkdownProcessor markdownProcessor = ctx.getBean(MarkdownProcessor.class); try { // step 1: parse input xml file to markdown string flowParser.parse(argument.getInputFile()); // step 2: generate markdown content String markdownContent = markdownProcessor.toMarkdownFile(); //step 3 convert to pdf pdfParser.toPDF(markdownContent); } catch(DocumentException docEx){ System.out.println(docEx.getMessage()); } } }
package Vista; /** * * @author Jorge Herrera - Sergio Ruiz */ public class AcercaDe extends javax.swing.JDialog { public AcercaDe(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { ok = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); ok.setText("OK"); ok.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel1.setText("Autor:"); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel2.setText("Jorge Herrera"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel3.setText("Sergio Ruiz"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(32, 32, 32) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(jLabel3)) .addGroup(layout.createSequentialGroup() .addGap(124, 124, 124) .addComponent(ok, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(57, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(23, 23, 23) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addGap(18, 18, 18) .addComponent(ok) .addContainerGap(31, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents // Si pinchas en ok, cerramos el JDIALOG private void okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okActionPerformed dispose(); }//GEN-LAST:event_okActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JButton ok; // End of variables declaration//GEN-END:variables }
package Flowers.Decorator; import Flowers.Item; /** * Created by Yasya on 22.11.16. */ public class RibbonDecorator extends ItemDecorator { public RibbonDecorator(Item i){ super(i); } public String getDescription() { return "Bouquet is decorated with ribbon\n";// Total price:" + Double.toString(this.getPrice()); } public double price() { return this.itm.price() + 1; } public String toString() { return itm.toString() + getDescription(); } }
package com.tencent.mm.g.a; public final class gr$a { public String bPS; }
/* * 文 件 名: ApiConstant.java * 版 权: Zskj Technologies Co., Ltd. Copyright YYYY-YYYY, All rights reserved * 描 述: <描述> * 修 改 人: hewei * 修改时间: 2016年6月6日 * 跟踪单号: <跟踪单号> * 修改单号: <修改单号> * 修改内容: <修改内容> */ package com.nemo.api.services.constant; import java.util.ResourceBundle; /** * 接口结果码常量 * * @author HEWEI * @version [版本号, 2016年6月6日] * @see [相关类/方法] * @since [产品/模块版本] */ public class ApiConstantMessage { // return status public static final String MSG_STATUS = ResourceBundle.getBundle("message").getString("msg_status"); // return msg public static final String MSG_MSG = ResourceBundle.getBundle("message").getString("msg_msg"); // 返回数据结果 public static final String MSG_RESULT = ResourceBundle.getBundle("message").getString("msg_result"); // return 成功状态 public static final String MSG_SUCCESS_CODE = ResourceBundle.getBundle("message").getString("msg_success_code"); // return 成功备注 public static final String MSG_SUCCESS = ResourceBundle.getBundle("message").getString("msg_success"); // return 参数不能为空 public static final String PARAM_IS_NOT_EMPTY = ResourceBundle.getBundle("message").getString("param_is_not_empty"); // return 错误状态 public static final String MSG_ERROR_STATUS = ResourceBundle.getBundle("message").getString("msg_error_status"); // return 数据库异常 public static final String DATABASE_ERROR = ResourceBundle.getBundle("message").getString("database_error"); /** * 用户开始 */ // 用户已禁用 public static final String USER_LOGIN_ERROR_IS_DISABLE = ResourceBundle.getBundle("message").getString( "user_login_error_is_disable"); // 用户不存在 public static final String USER_LOGIN_ERROR_IS_NOT_EXIT = ResourceBundle.getBundle("message").getString( "user_login_error_is_not_exit"); // 用户不存在或者密码错误 public static final String USER_LOGIN_ERROR_IS_NOT_EXIT_PWD_ERROR = ResourceBundle.getBundle("message").getString( "user_login_error_is_not_exit_pwd_error"); // 验证码失效 public static final String USER_REGISTER_IDENTIFYINGCODE_FAILURE = ResourceBundle.getBundle("message").getString( "user_register_identifyingcode_failure"); // 验证码错误 public static final String USER_REGISTER_IDENTIFYINGCODE_ERROR = ResourceBundle.getBundle("message").getString( "user_register_identifyingcode_error"); // 手机号码错误 public static final String USER_SENDMSG_PHONE_ERROR = ResourceBundle.getBundle("message").getString( "user_sendmsg_phone_error"); // 手机号码已存在 public static final String USER_SENDMSG_PHONE_IS_EXIT = ResourceBundle.getBundle("message").getString( "user_sendmsg_phone_is_exit"); // 手机号码不存在 public static final String USER_SENDMSG_PHONE_NOT_EXIT = ResourceBundle.getBundle("message").getString( "user_sendmsg_phone_not_exit"); //2016-07-16 caokai public static final String QUICKLOGIN_NO_USER = ResourceBundle.getBundle("message").getString( "quicklogin_no_user"); public static final String MSG_QUICK_LOGIN_REGISTER_STATUS = ResourceBundle.getBundle("message").getString( "msg_quick_login_register_status"); public static final String QUICKLOGIN_REGISTER_FAIL = ResourceBundle.getBundle("message").getString( "quicklogin_register_fail"); /** * 注册短信内容 */ public static final String USER_SENDMSG_REGITER_MSG = ResourceBundle.getBundle("message").getString( "user_sendmsg_regiter_msg"); /** * 微信号绑定注册账号通知消息 */ public static final String USER_SENDMSG_WX_REGITER_MSG = ResourceBundle.getBundle("message").getString("user_sendmsg_wx_regiter_msg"); /** * 注册短信内容 */ public static final String USER_SENDMSG_FORGETPWD_MSG = ResourceBundle.getBundle("message").getString( "user_sendmsg_forgetpwd_msg"); /** * 旧密码输入错误 */ public static final String USER_UPDATEPHONE_OLDPWD_MSG = ResourceBundle.getBundle("message").getString( "user_updatephone_oldpwd_msg"); /** * 绑定旧手机号输入错误 */ public static final String USER_UPDATEPHONE_OLDPHONE_MSG = ResourceBundle.getBundle("message").getString( "user_updatephone_oldphone_msg"); /** * 验证码发送失败 */ public static final String VERIFICATION_CODE_ERROR = ResourceBundle.getBundle("message").getString( "verification_code_error"); /** * 修改手机号码 */ public static final String USER_SENDMSG_CHANGEPHONE_MSG = ResourceBundle.getBundle("message").getString( "user_sendmsg_changephone_msg"); /** * 商品已经被收藏 */ public static final String PRODUCT_IS_COLLECIONED_MSG = ResourceBundle.getBundle("message").getString( "product_is_collecioned_msg"); /** * 卡号密码错误 */ public static final String RECHARGE_ERROR_PASSWORD_CARDNUM = ResourceBundle.getBundle("message").getString( "recharge_error_password_cardnum"); /** * 充值卡过期 */ public static final String RECHARGE_ERROR_OUT_OF_DATE = ResourceBundle.getBundle("message").getString( "recharge_error_out_of_date"); /** * 用户结束 */ /***** 支付开始 ****************/ /** * 订单已支付 */ public static final String ORDER_ERROR_IS_PAY = ResourceBundle.getBundle("message").getString("order_error_is_pay"); public static final String ORDER_ERROR_SERVER_ERROR = ResourceBundle.getBundle("message").getString("order_error_server_error"); public static final String ORDER_ERROR_NOT_EXIT = ResourceBundle.getBundle("message").getString("order_error_not_exit"); public static final String ORDER_ERROR_BALANCE_NOT_SUFFICIENT_FUNDS = ResourceBundle.getBundle("message").getString("order_error_balance_not_sufficient_funds"); public static final String ORDER_ERROR_INTRAGER_NOT_SUFFICIENT_FUNDS = ResourceBundle.getBundle("message").getString("order_error_intrager_not_sufficient_funds"); /***** 支付借宿 ****************/ }
package pro.anuj.challenge.motrics; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import pro.anuj.challenge.motrics.domain.Metric; import pro.anuj.challenge.motrics.utils.StripedLockProvider; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; @Configuration public class Config { private static final Map<UUID, Metric> METRIC_CACHE = new ConcurrentHashMap<>(); private static final Map<String, UUID> NAME_CACHE = new ConcurrentHashMap<>(); @Bean public Map<UUID, Metric> metricCache() { return METRIC_CACHE; } @Bean public Map<String, UUID> nameCache() { return NAME_CACHE; } @Bean public StripedLockProvider<UUID, Metric> stripedLockProvider() { return new StripedLockProvider<>(100, TimeUnit.MILLISECONDS); } }
/******************************************************************************* * Copyright (C) 2011 Peter Brewer. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contributors: * Peter Brewer ******************************************************************************/ package org.tellervo.desktop.print; import java.awt.Color; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.DateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tellervo.desktop.core.App; import org.tellervo.desktop.gui.Startup; import org.tellervo.desktop.io.Metadata; import org.tellervo.desktop.sample.Sample; import org.tellervo.schema.TellervoRequestFormat; import org.tellervo.schema.SearchOperator; import org.tellervo.schema.SearchParameterName; import org.tellervo.schema.SearchReturnObject; import org.tellervo.schema.WSIBox; import org.tellervo.desktop.tridasv2.TridasComparator; import org.tellervo.desktop.ui.Alert; import org.tellervo.desktop.util.labels.LabBarcode; import org.tellervo.desktop.util.pdf.PrintablePDF; import org.tellervo.desktop.util.test.PrintReportFramework; import org.tellervo.desktop.wsi.tellervo.TellervoResourceAccessDialog; import org.tellervo.desktop.wsi.tellervo.TellervoResourceProperties; import org.tellervo.desktop.wsi.tellervo.SearchParameters; import org.tellervo.desktop.wsi.tellervo.resources.EntitySearchResource; import org.tridas.schema.TridasElement; import org.tridas.schema.TridasObject; import org.tridas.schema.TridasSample; import org.tridas.util.TridasObjectEx; import com.lowagie.text.Chunk; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.Image; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.Phrase; import com.lowagie.text.pdf.ColumnText; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; public class BasicBoxLabel extends ReportBase{ private ArrayList<WSIBox> boxlist = new ArrayList<WSIBox>(); private final static Logger log = LoggerFactory.getLogger(BasicBoxLabel.class); public BasicBoxLabel(Sample s){ if(s==null) { System.out.println("Error - sample is null"); return; } if (s.getMeta(Metadata.BOX, WSIBox.class)==null) { System.out.println("Error - no box associated with this series"); return; } boxlist.add(s.getMeta(Metadata.BOX, WSIBox.class)); } public BasicBoxLabel(WSIBox b){ if (b==null) { System.out.println("Error - box is null"); return; } boxlist.add(b); } public BasicBoxLabel(ArrayList<WSIBox> bl) { boxlist = bl; } public void generateBoxLabel(OutputStream output) { try { PdfWriter writer = PdfWriter.getInstance(document, output); document.setPageSize(PageSize.LETTER); document.open(); cb = writer.getDirectContent(); // Set basic metadata document.addAuthor("Tellervo"); document.addSubject("Tellervo Box Labels"); PdfPTable table = new PdfPTable(2); table.setTotalWidth(495f); table.setLockedWidth(true); for(WSIBox b : boxlist) { Paragraph p = new Paragraph(); p.add(new Chunk(b.getTitle()+Chunk.NEWLINE, labelTitleFont)); p.add(new Chunk(Chunk.NEWLINE+b.getComments()+Chunk.NEWLINE, bodyFont)); p.add(new Chunk(App.getLabName()+Chunk.NEWLINE+Chunk.NEWLINE, bodyFont)); p.add(new Chunk(this.getBarCode(b), 0, 0, true)); PdfPCell cell = new PdfPCell(p); cell.setPaddingLeft(15f); cell.setPaddingRight(15f); cell.setBorderColor(Color.LIGHT_GRAY); table.addCell(cell); } PdfPCell cell = new PdfPCell(new Paragraph()); cell.setBorderColor(Color.LIGHT_GRAY); table.addCell(cell); document.add(table); document.close(); /*float top = document.top(15); int row = 1; for(int i = 0; i< boxlist.size(); i = i+2) { log.debug("Document left : "+document.left()); log.debug("Document right: "+document.right()); log.debug("Top : "+top); // Column 1 ColumnText ct1a = new ColumnText(cb); ct1a.setSimpleColumn(document.left(), top-210, 368, top, 20, Element.ALIGN_LEFT); ColumnText ct1b = new ColumnText(cb); ct1b.setSimpleColumn(document.left(), top-70, document.left()+206, top-150, 20, Element.ALIGN_LEFT); try{ WSIBox b1 = boxlist.get(i); ct1a.addText(getTitlePDF(b1)); ct1a.go(); ct1b.addElement(getBarCode(b1)); ct1b.go(); } catch (Exception e) { log.debug("Failed writing box label in left column where i="+i); } // Column 2 ColumnText ct2a = new ColumnText(cb); ct2a.setSimpleColumn(306, top-210, document.right(), top, 20, Element.ALIGN_LEFT); ColumnText ct2b = new ColumnText(cb); ct2b.setSimpleColumn(306, top-70, 512, top-80, 20, Element.ALIGN_LEFT); try{ WSIBox b2 = boxlist.get(i+1); ct2a.addText(getTitlePDF(b2)); ct2a.go(); ct2b.addElement(getBarCode(b2)); ct2b.go(); } catch (Exception e) { log.debug("Failed writing box label in right column where i="+i); //e.printStackTrace(); } // Column 2 /* ColumnText ct2 = new ColumnText(cb); ct2.setSimpleColumn(370, //llx top-100, //lly document.right(0), //urx top+15, //ury 20, //leading Element.ALIGN_RIGHT //alignment ); try{ WSIBox b2 = boxlist.get(i+1); ct2.addText(getTitlePDF(b2)); ct2.addElement(getBarCode(b2)); ct2.go(); } catch (Exception e) { log.debug("Failed writing box label where i="+i+1); } */ /* top = top-160; if(row==5) { top = document.top(15); document.newPage(); row=1; } else { row++; } }*/ } catch (DocumentException de) { System.err.println(de.getMessage()); } // Close the document document.close(); } /** * Get an iText Paragraph for the Title * * @return Paragraph */ private Paragraph getTitlePDF(WSIBox b) { Paragraph p = new Paragraph(); p.setLeading(0f); p.setMultipliedLeading(1.2f); p.add(new Phrase(10, b.getTitle()+"\n", monsterFont)); p.add(new Phrase(10, b.getComments()+" "+App.getLabName() +"fdas dfsa fds sdfalkdsf jlasdj fkljkldsa jfdsklaj fdksaj flkdsaj lkfdsalk fjdsal fjdklaj fkldsajkldsfalkjsdf asdlkj dsajlk", bodyFont)); //p.add(new Chunk(b.getCurationLocation(), bodyFontLarge)); return p; } /** * Create a series bar code for this series * * @return Image */ private Image getBarCode(WSIBox b) { UUID uuid = UUID.fromString(b.getIdentifier().getValue()); LabBarcode barcode = new LabBarcode(LabBarcode.Type.BOX, uuid); barcode.setX(0.7f); //barcode.setN(0.5f); barcode.setSize(6f); barcode.setBaseline(8f); barcode.setBarHeight(50f); Image image = barcode.createImageWithBarcode(cb, null, null); return image; } /** * Get PdfPTable containing the samples per object * * @return PdfPTable * @throws DocumentException */ private void addTable(WSIBox b) throws DocumentException { float[] widths = {0.15f, 0.75f, 0.2f}; PdfPTable tbl = new PdfPTable(widths); PdfPCell headerCell = new PdfPCell(); tbl.setWidthPercentage(100f); // Write header cells of table headerCell.setBorderWidthBottom(headerLineWidth); headerCell.setBorderWidthTop(headerLineWidth); headerCell.setBorderWidthLeft(0); headerCell.setBorderWidthRight(0); headerCell.setPhrase(new Phrase("Object", tableHeaderFontLarge)); headerCell.setHorizontalAlignment(Element.ALIGN_LEFT); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase("Elements", tableHeaderFontLarge)); headerCell.setHorizontalAlignment(Element.ALIGN_LEFT); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase("# Samples", tableHeaderFontLarge)); headerCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tbl.addCell(headerCell); // Find all objects associated with samples in this box SearchParameters objparam = new SearchParameters(SearchReturnObject.OBJECT); objparam.addSearchConstraint(SearchParameterName.SAMPLEBOXID, SearchOperator.EQUALS, b.getIdentifier().getValue().toString()); EntitySearchResource<TridasObject> objresource = new EntitySearchResource<TridasObject>(objparam); objresource.setProperty(TellervoResourceProperties.ENTITY_REQUEST_FORMAT, TellervoRequestFormat.COMPREHENSIVE); TellervoResourceAccessDialog dialog = new TellervoResourceAccessDialog(objresource); objresource.query(); dialog.setVisible(true); if(!dialog.isSuccessful()) { System.out.println("oopsey doopsey. Error getting objects"); return; } List<TridasObject> obj = objresource.getAssociatedResult(); // Check that there are not too many objects to fit on box label if(obj.size()>10) { System.out.println("Warning this label has " + Integer.toString(obj.size()) + " objects associated with it so is unlikely to fit and may take some time to produce!"); } if(obj.size()<4) { // Not many objects so add some space to the table for prettiness sake headerCell.setBorder(0); headerCell.setPhrase(new Phrase(" ")); tbl.addCell(headerCell); tbl.addCell(headerCell); tbl.addCell(headerCell); } // Sort objects into alphabetically order based on labcode TridasComparator sorter = new TridasComparator(); Collections.sort(obj, sorter); Integer sampleCountInBox = 0; // Loop through objects List<TridasObject> objdone = new ArrayList<TridasObject>(); // Array of top level objects that have already been dealt with mainobjloop: for(TridasObject myobj : obj) { // Need to check if this object has already been done as there will be duplicate top level objects if there are samples // from more than one subobject in the box if(objdone.size()>0) { try{for(TridasObject tlo : objdone){ TridasObjectEx tloex = (TridasObjectEx) tlo; TridasObjectEx myobjex = (TridasObjectEx) myobj; if (tloex.getLabCode().compareTo(myobjex.getLabCode())==0){ // Object already been done so skip to next continue mainobjloop; } else { // Object has not been done so add to the done list and keep going objdone.add(myobj); } }} catch (Exception e){} } else { objdone.add(myobj); } // Add object code to first column PdfPCell dataCell = new PdfPCell(); dataCell.setBorderWidthBottom(0); dataCell.setBorderWidthTop(0); dataCell.setBorderWidthLeft(0); dataCell.setBorderWidthRight(0); dataCell.setHorizontalAlignment(Element.ALIGN_LEFT); String objCode = null; if(myobj instanceof TridasObjectEx) objCode = ((TridasObjectEx)myobj).getLabCode(); dataCell.setPhrase(new Phrase(objCode, bodyFontLarge)); tbl.addCell(dataCell); // Search for elements associated with this object System.out.println("Starting search for elements associated with " + myobj.getTitle().toString()); SearchParameters sp = new SearchParameters(SearchReturnObject.ELEMENT); sp.addSearchConstraint(SearchParameterName.SAMPLEBOXID, SearchOperator.EQUALS, b.getIdentifier().getValue()); sp.addSearchConstraint(SearchParameterName.ANYPARENTOBJECTID, SearchOperator.EQUALS, myobj.getIdentifier().getValue()); EntitySearchResource<TridasElement> resource = new EntitySearchResource<TridasElement>(sp); resource.setProperty(TellervoResourceProperties.ENTITY_REQUEST_FORMAT, TellervoRequestFormat.SUMMARY); TellervoResourceAccessDialog dialog2 = new TellervoResourceAccessDialog(resource); resource.query(); dialog2.setVisible(true); if(!dialog2.isSuccessful()) { System.out.println("oopsey doopsey. Error getting elements"); return; } //XMLDebugView.showDialog(); List<TridasElement> elements = resource.getAssociatedResult(); TridasComparator numSorter = new TridasComparator(TridasComparator.Type.TITLES, TridasComparator.NullBehavior.NULLS_LAST, TridasComparator.CompareBehavior.AS_NUMBERS_THEN_STRINGS); Collections.sort(elements, numSorter); // Loop through elements Integer smpCnt = 0; ArrayList<String> numlist = new ArrayList<String>(); for(TridasElement myelem : elements) { // Add element title to string if(myelem.getTitle()!=null) { String mytitle = myelem.getTitle(); numlist.add(mytitle); } // Grab associated samples and add count to running total List<TridasSample> samples = myelem.getSamples(); smpCnt += samples.size(); } // Add element names to second column dataCell.setPhrase(new Phrase(hyphenSummarize(numlist), bodyFontLarge)); tbl.addCell(dataCell); // Add sample count to third column dataCell.setPhrase(new Phrase(smpCnt.toString(), bodyFontLarge)); dataCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tbl.addCell(dataCell); sampleCountInBox += smpCnt; } if(obj.size()<4) { // Not many objects so add some space to the table for prettiness sake headerCell.setBorder(0); headerCell.setPhrase(new Phrase(" ")); tbl.addCell(headerCell); tbl.addCell(headerCell); tbl.addCell(headerCell); } headerCell.setBorderWidthBottom(headerLineWidth); headerCell.setBorderWidthTop(headerLineWidth); headerCell.setBorderWidthLeft(0); headerCell.setBorderWidthRight(0); headerCell.setPhrase(new Phrase(" ", bodyFontLarge)); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase("Grand Total", tableHeaderFontLarge)); headerCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase(sampleCountInBox.toString(), bodyFontLarge)); tbl.addCell(headerCell); // Add table to document document.add(tbl); } public String hyphenSummarize(List<String> lst) { String returnStr = ""; /* if (none==true) { for(String item : lst) { returnStr += item + ", "; } if (returnStr.length()>2) returnStr = returnStr.substring(0, returnStr.length()-2); return returnStr; }*/ Integer lastnum = null; Boolean inSeq = false; Integer numOfElements = lst.size(); Integer cnt = 0; for(String item : lst) { cnt++; if (containsOnlyNumbers(item)) { // Contains only numbers if(lastnum==null) { // Lastnum is null so just add item to return string and continue to the next in list returnStr += ", " + item; lastnum = Integer.valueOf(item); continue; } else { if(inSeq==true) { if(cnt==numOfElements) { // This is the last one in the list! returnStr += "-" + item; continue; } else if(isNextInSeq(lastnum, Integer.valueOf(item))) { // Keep going! inSeq = true; lastnum = Integer.valueOf(item); continue; } else { // returnStr += "-" + lastnum.toString() + ", " + item; inSeq = false; lastnum = Integer.valueOf(item); continue; } } else { // Not in sequence yet if(isNextInSeq(lastnum, Integer.valueOf(item))) { if(cnt==numOfElements) { // This is the last one in the list! returnStr += "-" + item; continue; } else { // Keep going! inSeq = true; lastnum = Integer.valueOf(item); continue; } } else { returnStr += ", " + item; lastnum = Integer.valueOf(item); continue; } } } } else { // Contains some chars so just add as comma delimated string to return string returnStr += ", " + item; lastnum = null; inSeq = null; } } returnStr = returnStr.substring(2, returnStr.length()); return returnStr; } private Boolean isNextInSeq(Integer seqnum, Integer curnum) { if(seqnum+1==curnum) { return true; } else { return false; } } /** * This method checks if a String contains only numbers */ public boolean containsOnlyNumbers(String str) { //It can't contain only numbers if it's null or empty... if (str == null || str.length() == 0) return false; for (int i = 0; i < str.length(); i++) { //If we find a non-digit character we return false. if (!Character.isDigit(str.charAt(i))) return false; } return true; } /** * iText paragraph containing created and lastmodified timestamps * * @return Paragraph */ private Paragraph getTimestampPDF(WSIBox b) { // Set up calendar Date createdTimestamp = b.getCreatedTimestamp().getValue() .toGregorianCalendar().getTime(); Date nowTimestamp = new Date(); DateFormat df1 = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT); Paragraph p = new Paragraph(); p.add(new Chunk("Created: ", subSubSectionFont)); p.add(new Chunk(df1.format(createdTimestamp), bodyFont)); //p.add(new Chunk("\nLast Modified: ", subSubSectionFont)); //p.add(new Chunk(df1.format(lastModifiedTimestamp), bodyFontLarge)); p.add(new Chunk("\nLabel updated: ", subSubSectionFont)); p.add(new Chunk(df1.format(nowTimestamp), bodyFont)); return p; } private Paragraph getComments(WSIBox b) throws DocumentException { Paragraph p = new Paragraph(); p.setLeading(0, 1.2f); p.add(new Chunk("Comments: \n", subSubSectionFont)); if(b.getComments()!=null){ p.add(new Chunk(b.getComments(), bodyFont)); } else{ p.add(new Chunk("No comments recorded", bodyFont)); } return(p); } /** * Function for printing or viewing series report * @param printReport Boolean * @param vmid String */ public void getLabel(Boolean printReport) { if(printReport) { ByteArrayOutputStream output = new ByteArrayOutputStream(); this.generateBoxLabel(output); try { PrintablePDF pdf = PrintablePDF.fromByteArray(output.toByteArray()); // true means show printer dialog, false means just print using the default printer pdf.print(true); } catch (Exception e) { e.printStackTrace(); Alert.error("Printing error", "An error occured during printing.\n See error log for further details."); } } else { // probably better to use a chooser dialog here... try { File outputFile = File.createTempFile("boxlabel", ".pdf"); FileOutputStream output = new FileOutputStream(outputFile); this.generateBoxLabel(output); App.platform.openFile(outputFile); } catch (IOException ioe) { ioe.printStackTrace(); Alert.error("Error", "An error occurred while generating the box label.\n See error log for further details."); return; } } } /** * Function for printing or viewing series report * @param printReport Boolean * @param vmid String */ public static void getLabel(Boolean printReport, String vmid) { String domain = App.domain; Sample samp = null; try { samp = PrintReportFramework.getCorinaSampleFromVMID(domain, vmid); } catch (IOException ioe) { ioe.printStackTrace(); } // create the box label BasicBoxLabel label = new BasicBoxLabel(samp); if(printReport) { ByteArrayOutputStream output = new ByteArrayOutputStream(); label.generateBoxLabel(output); try { PrintablePDF pdf = PrintablePDF.fromByteArray(output.toByteArray()); // true means show printer dialog, false means just print using the default printer pdf.print(true); } catch (Exception e) { e.printStackTrace(); Alert.error("Printing error", "An error occured during printing.\n See error log for further details."); } } else { // probably better to use a chooser dialog here... try { File outputFile = File.createTempFile("boxlabel", ".pdf"); FileOutputStream output = new FileOutputStream(outputFile); label.generateBoxLabel(output); App.platform.openFile(outputFile); } catch (IOException ioe) { ioe.printStackTrace(); Alert.error("Error", "An error occurred while generating the box label.\n See error log for further details."); return; } } } }
package com.omnicuris; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(scanBasePackages={"com.omnicuris"}) public class CartOrderRestApiApplication { public static void main(String[] args) { SpringApplication.run(CartOrderRestApiApplication.class, args); } }
package com.involves.json; import java.util.ArrayList; import java.util.List; public class JSONArray implements JSONable { private String key; private List<Object> values; public JSONArray(String key) { this.key = key; this.values = new ArrayList<>(); } public JSONArray(String key, List<Object> values) { this.key = key; this.values = values; } public List<Object> getJsonValues() { return this.values; } public boolean add(Object object) { return this.values.add(object); } @Override public String getKey() { return this.key; } }
package com.example.rikvanbelle.drinksafe; import android.arch.persistence.room.Room; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.RadioButton; import android.widget.Toast; import com.example.rikvanbelle.drinksafe.db.AppDatabase; import com.example.rikvanbelle.drinksafe.models.User; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; public class PersonalSettingsActivity extends AppCompatActivity { EditText first_name; EditText last_name; EditText email; EditText password; EditText dateOfBirth; EditText weight; EditText length; char gender = 'M'; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_personal_settings); AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "DrinkSafe").build(); Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar); setSupportActionBar(myToolbar); first_name = findViewById(R.id.first_name); last_name = findViewById(R.id.last_name); email = findViewById(R.id.email); password = findViewById(R.id.password); dateOfBirth = findViewById(R.id.dateOfBirth); weight = findViewById(R.id.weight); length = findViewById(R.id.length); List<User> users = AppDatabase.getAppDatabase(getApplicationContext()).userDAO().getAll(); if(users.size() > 0){ initiateFields(users.get(0)); } } private void initiateFields(User user){ first_name.setText(user.getFirst_name()); last_name.setText(user.getLast_name()); email.setText(user.geteMail()); password.setText(user.getPassword()); dateOfBirth.setText(user.getDateOfBirth().toString()); weight.setText(Double.toString(user.getWeight())); length.setText(Double.toString(user.getLength())); } public void onRadioButtonClicked(View view) { // Is the button now checked? boolean checked = ((RadioButton) view).isChecked(); // Check which radio button was clicked if(view.getId() == R.id.woman){ gender = 'V'; } } public void onConfirm(View v){ Date birth = new Date(); Double weightD = Double.parseDouble(weight.getText().toString()); Double lengthD = Double.parseDouble(length.getText().toString()); try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); birth = format.parse(dateOfBirth.getText().toString()); } catch (ParseException exc){ Log.d("ERROR", exc.getMessage()); } User user = new User(first_name.getText().toString(), last_name.getText().toString(), email.getText().toString(), password.getText().toString(), birth, weightD, lengthD,gender); AppDatabase.getAppDatabase(getApplicationContext()).userDAO().insertAll(user); Toast.makeText(this, getString(R.string.UserIsAdded), Toast.LENGTH_SHORT).show(); finish(); } }
package br.com.casadocodigo.loja.infra; import java.io.IOException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; @Component public class FileSaver { @Autowired private AmazonS3 amazonS3; private static final String BUCKET="casadocodigo-rafaelsilvanercessian"; public String write(MultipartFile file) { try { amazonS3.putObject(new PutObjectRequest(BUCKET, file.getOriginalFilename(), file.getInputStream(),null) .withCannedAcl(CannedAccessControlList.PublicRead)); return "http://s3.amazonaws.com/"+BUCKET+"/"+file.getOriginalFilename(); } catch (IllegalStateException | IOException e) { throw new RuntimeException(e); } } }
package com.kh.efp.alarm.model.vo; import java.sql.Date; public class Alarm implements java.io.Serializable{ private String nType; private Date alarm_Date; private String bContent; private String bName; private String mName; private int boardId; private int nid; private int ref_Bid; public Alarm() {} public Alarm(String nType, Date alarm_Date, String bContent, String bName, String mName, int boardId, int nid, int ref_Bid) { super(); this.nType = nType; this.alarm_Date = alarm_Date; this.bContent = bContent; this.bName = bName; this.mName = mName; this.boardId = boardId; this.nid = nid; this.ref_Bid = ref_Bid; } public int getRef_Bid() { return ref_Bid; } public void setRef_Bid(int ref_Bid) { this.ref_Bid = ref_Bid; } public String getnType() { return nType; } public void setnType(String nType) { this.nType = nType; } public int getBoardId() { return boardId; } public int getNid() { return nid; } public void setNid(int nid) { this.nid = nid; } public void setBoardId(int boardId) { this.boardId = boardId; } public Date getAlarm_Date() { return alarm_Date; } public void setAlarm_Date(Date alarm_Date) { this.alarm_Date = alarm_Date; } public String getbContent() { return bContent; } public void setbContent(String bContent) { this.bContent = bContent; } public String getbName() { return bName; } public void setbName(String bName) { this.bName = bName; } public String getmName() { return mName; } public void setmName(String mName) { this.mName = mName; } @Override public String toString() { return "Alarm [nType=" + nType + ", alarm_Date=" + alarm_Date + ", bContent=" + bContent + ", bName=" + bName + ", mName=" + mName + ", bid=" + boardId + "]"; } }
package ga.islandcrawl.other; /** * Created by Ga on 12/18/2015. */ public class Timer { private int time; private int max; public Timer(int max){ set(max); } public Timer(int now, int max){ this(max); time = now; } public void set(int max){ this.max = max; this.time = 0; } public boolean isTime(int p){ return time == p; } public boolean update(){ if (++time >= max){ time = 0; return true; } return false; } }
package xin.altitude.lock.service; import lombok.SneakyThrows; import lombok.Synchronized; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import xin.altitude.lock.entity.Goods; import xin.altitude.lock.entity.Order; import xin.altitude.lock.mappeer.GoodsMapper; import xin.altitude.lock.mappeer.OrderMapper; /** * @author explore * @date 2020/11/02 13:52 */ @Service public class OrderService { @Autowired private GoodsMapper goodsMapper; @Autowired private OrderMapper orderMapper; @Autowired private CuratorFramework curatorFramework; @Autowired private RedissonClient redissonClient; /** * 生成订单 * @param goodsId 商品ID * @param num 下单数量 * @return */ @Transactional public Boolean genOrder(Long goodsId,int num){ Goods goods = goodsMapper.selectById(goodsId); if (goods.getStock()>=num) { goods.setStock(goods.getStock()-num); //减库存(基于乐观锁实现减库存) boolean bl = goodsMapper.updateById(goods) > 0; if (bl) { Order order = new Order(goodsId, num); orderMapper.insert(order); return true; } return false; } return false; } /** * 使用zk分布式锁,解决并发问题,将压力挡在数据库访问之前 * @param goodsId * @param num * @return */ @SneakyThrows @Transactional public Boolean genOrderWithZk(Long goodsId,int num){ InterProcessMutex lock = new InterProcessMutex(curatorFramework,"/lock"); //加锁(分布式) lock.acquire(); Goods goods = goodsMapper.selectById(goodsId); if (goods.getStock()>=num) { goods.setStock(goods.getStock()-num); //减库存(基于乐观锁实现减库存) boolean bl = goodsMapper.updateById(goods) > 0; if (bl) { Order order = new Order(goodsId, num); orderMapper.insert(order); lock.release(); return true; } } //释放锁 lock.release(); return false; } @Transactional public Boolean genOrderWithRedis(Long goodsId,int num){ String key = "dec_store_lock_" + goodsId; RLock lock = redissonClient.getLock(key); //加锁(分布式) lock.lock(); Goods goods = goodsMapper.selectById(goodsId); if (goods.getStock()>=num) { goods.setStock(goods.getStock()-num); //减库存(基于乐观锁实现减库存) boolean bl = goodsMapper.updateById(goods) > 0; if (bl) { Order order = new Order(goodsId, num); orderMapper.insert(order); //释放锁 lock.unlock(); return true; } } //释放锁 lock.unlock(); return false; } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngrinder.recorder.ui.component; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JPopupMenu; import javax.swing.JToggleButton; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; /** * DropDown Button. * * This button supports the sub menu binding. * * @author JunHo Yoon (modified by) * @since 1.0 * @see https * ://code.google.com/p/link-collector/source/browse/ver2/trunk/common/util/src/ru/kc/util/ * swing/button/DropDownButton.java?spec=svn414&r=414 */ public class DropDownButton extends JToggleButton { private static final long serialVersionUID = 2857744715416733620L; private JPopupMenu menu; /** * Constructor. * * @param text * text */ public DropDownButton(String text) { super(text); init(); } private void init() { addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (menu == null) { return; } boolean isSelected = e.getStateChange() == ItemEvent.SELECTED; if (isSelected) { menu.show(DropDownButton.this, 0, getHeight()); } } }); } public JPopupMenu getMenu() { return menu; } /** * Attach the given menu on this button. * * @param menu * menu to be attached. */ public void setMenu(JPopupMenu menu) { this.menu = menu; initMenu(); } private void initMenu() { menu.addPopupMenuListener(new PopupMenuListener() { public void popupMenuWillBecomeVisible(PopupMenuEvent e) { } public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { deselectButtonRequest(); } public void popupMenuCanceled(PopupMenuEvent e) { deselectButtonRequest(); } }); } private void deselectButtonRequest() { setSelected(false); } }
package facing; /** * @author admin * @version 1.0.0 * @ClassName wanggeMinPath.java * @Description * * 给定一个包含非负整数的 m x n 网格 grid ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。 * * 说明:每次只能向下或者向右移动一步。 * 由于路径的方向只能是向下或向右,因此网格的第一行的每个元素只能从左上角元素开始向右移动到达, * 网格的第一列的每个元素只能从左上角元素开始向下移动到达,此时的路径是唯一的, * 因此每个元素对应的最小路径和即为对应的路径上的数字总和。 * * 对于不在第一行和第一列的元素,可以从其上方相邻元素向下移动一步到达, * 或者从其左方相邻元素向右移动一步到达,元 * 素对应的最小路径和等于其上方相邻元素与其左方相邻元素两者对应的最小路径和中的最小值加上当前元素的值。 * 由于每个元素对应的最小路径和与其相邻元素对应的最小路径和有关,因此可以使用动态规划求解。 * * 创建二维数组 dp,与原始网格的大小相同,dp[i][j]表示从左上角出发到 (i,j)(i,j) 位置的最小路径和。 * 显然,dp[0][0]=grid[0][0]。对于 dp 中的其余元素,通过以下状态转移方程计算元素值。 * * 当 i>0i>0 且 j=0j=0 时,dp[i][0]=dp[i-1][0]+grid[i][0]dp[i][0] * * 当 i=0i=0 且 j>0j>0 时,dp[0][j]=dp[0][j-1]+grid[0][j]dp[0][j] * * 当 i>0i>0 且 j>0j>0 时,dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i][j] * * 最后得到dp[m-1][n-1]dp[m−1][n−1] 的值即为从网格左上角到网格右下角的最小路径和。 * @createTime 2021年03月07日 20:46:00 */ public class wanggeMinPath { public int minGridPathSum(int[][] grid){ if (grid == null || grid.length == 0 || grid[0].length == 0){ return 0; } int rows = grid.length; int column = grid[0].length; int[][] dp = new int[rows][column]; dp[0][0] = grid[0][0];//左上角开始 for (int i = 1; i < rows; i++) { dp[i][0] = dp[i-1][0] + grid[i][0]; } for (int j = 1; j <column ; j++) { dp[0][j] = dp[0][j - 1] + grid[0][j]; } for (int i = 1; i <rows ; i++) { for (int j = 1; j <column ; j++) { dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; } } return dp[rows - 1][column - 1];//返回最右下角 } }
package com.takshine.wxcrm.message.sugar; import java.util.List; /** * 查询日程接口 从sugar响应回来的参数 * @author liulin * */ public class UsersResp extends BaseCrm{ /** * 调用sugar接口传递的参数 */ private String count ;//数字 private List<UserAdd> users ;//任务列表 public String getCount() { return count; } public void setCount(String count) { this.count = count; } public List<UserAdd> getUsers() { return users; } public void setUsers(List<UserAdd> users) { this.users = users; } }
import java.util.Scanner; class RemoveDuplicateFromArray { public static void main(String args[]) { Scanner scan = new Scanner(System.in); System.out.print("Enter the size of array : "); int size = scan.nextInt(); int arr[] = new int[size]; System.out.println(); System.out.println("Enter the elements in array : "); for(int i = 0 ; i < size ; i++ ) { arr[i] = scan.nextInt(); } for(int i = 0 ; i < size ; i++ ) { for(int j = 0 ; j < size - 1 ; j++ ) { if(arr[j] > arr[j+1]) { arr[j] = arr[j]+arr[j+1]; arr[j+1] = arr[j]-arr[j+1]; arr[j] = arr[j]-arr[j+1]; } } } for(int i = 0 ; i < size ; i++ ) { System.out.print(arr[i] + " "); } System.out.println(); for(int i = 0 ; i < size-1 ; i++ ) { if(arr[i]==arr[i+1]){ continue; } System.out.print(arr[i] + " "); } System.out.println(arr[size-1]); scan.close(); } }
package com.zhouyi.business.controller; import com.zhouyi.business.core.common.ReturnCode; import com.zhouyi.business.core.model.PageData; import com.zhouyi.business.core.model.Response; import com.zhouyi.business.dto.SysDataLogConditionsDto; import com.zhouyi.business.core.model.SysLogData; import com.zhouyi.business.core.service.SysLogDataService; import com.zhouyi.business.core.utils.MapUtils; import com.zhouyi.business.core.utils.ResponseUtil; import io.swagger.annotations.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * @author 李秸康 * @ClassNmae: SysLogDataController * @Description: 数据日志控制器 * @date 2019/6/21 10:47 * @Version 1.0 **/ @RestController @RequestMapping(value="/api/sysDataLog") @Api(description = "数据日志API") public class SysLogDataController { @Autowired private SysLogDataService sysLogDataService; /** * 根据主键id获取数据日志信息 * @param pkId * @return */ @RequestMapping(value="/getSysLogData/{pkId}",method = RequestMethod.GET) @ApiOperation(value = "获取单个系统日期信息",hidden = true) @ApiImplicitParam(value = "主键id",name = "pkId",paramType = "path") public Response<SysLogData> getSysLogData(@PathVariable String pkId){ Response<SysLogData> sysLogDataResponse=new Response<SysLogData>(); SysLogData sysLogData=sysLogDataService.searchSysLogDataByPkId(pkId); sysLogDataResponse.setData(sysLogData); return sysLogDataResponse; } /** * 添加数据日志信息 * @param sysLogData * @return */ @RequestMapping(value="/addSysLogData") @ApiOperation(value = "添加日志",hidden = true) public Response<Object> addSysLogData(@RequestBody SysLogData sysLogData){ boolean result=sysLogDataService.addSysLogDataSelective(sysLogData); return ResponseUtil.getResponseInfo(result); } /** * 删除数据日志信息 * @param pkId * @return */ @RequestMapping(value="/deleteSysLogData/{pkId}") @ApiOperation(hidden = true,value = "删除日志") public Response<Object> removeSysLogData(@PathVariable String pkId){ boolean result=sysLogDataService.removeSysLogData(pkId); return ResponseUtil.getResponseInfo(result); } /** * 修改数据日志信息 * @param sysLogData * @return */ @RequestMapping(value="/updateSysLogData") @ApiOperation(value = "修改日志",hidden = true) public Response<Object> modifySysLogData(@RequestBody SysLogData sysLogData){ boolean result=sysLogDataService.modifySysLogDataSelective(sysLogData); return ResponseUtil.getResponseInfo(result); } /** * 分页显示数据日志信息 * @return */ @RequestMapping(value="/list/sys_log_data",method = RequestMethod.POST) @ApiOperation(value = "日志列表") // @ApiImplicitParams( // { // @ApiImplicitParam(value = "对象姓名",name = "userName",paramType = "query"), // @ApiImplicitParam(value = "用户姓名",name = "personName",paramType = "query"), // @ApiImplicitParam(value = "IP地址",name = "addreIp",paramType="query") // } // ) public Response<PageData<SysLogData>> listSysLogData(@RequestBody SysDataLogConditionsDto sysDataLogConditionsDto){ Map<String,Object> conditions=MapUtils.objectTransferToMap(sysDataLogConditionsDto); PageData<SysLogData> pageData=sysLogDataService.searchSysLogDataPage(conditions); return ResponseUtil.getResponseInfo(ReturnCode.SUCCESS,pageData); } }
package com.weekendproject.connectivly.controller; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.json.JSONException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.weekendproject.connectivly.model.GoodReceivedNotes; import com.weekendproject.connectivly.model.GrnPoProduct; import com.weekendproject.connectivly.payload.GoodReceivedNotesRequest; import com.weekendproject.connectivly.payload.GrnPoProductRequest; import com.weekendproject.connectivly.payload.PurchaseOrdersRequest; import com.weekendproject.connectivly.repository.GoodReceivedNotesRepository; import com.weekendproject.connectivly.service.GoodReceivedNotesService; import com.weekendproject.connectivly.repository.GoodReceivedNotesRepository.GrnPoProduct2; @RestController @RequestMapping("/api/goodReceivedNotes") public class GoodReceivedNotesController { @Autowired private GoodReceivedNotesRepository repository; @Autowired private GoodReceivedNotesService goodReceivedNotesService; @PostMapping("/addGrnPoProduct") public void addGrnPoProduct(@Valid @RequestBody GrnPoProductRequest jsonRequest, HttpServletRequest request) throws IOException, JSONException{ goodReceivedNotesService.addGrnPoProduct(jsonRequest, JwtDecoder.decodeJwt(request).get("userId")); } @PostMapping("/getAllGoodReceivedNotes") @ResponseStatus(HttpStatus.OK) public Page<GoodReceivedNotes> getAllGoodReceivedNotes(Pageable page, HttpServletRequest request) throws IOException, JSONException { Page<GoodReceivedNotes> getAllGoodReceivedNotes = repository.findAllByUserId(page, JwtDecoder.decodeJwt(request).get("userId")); return getAllGoodReceivedNotes; } @PostMapping("/addGoodReceivedNotes") public void addGoodReceivedNotes(@Valid @RequestBody GoodReceivedNotesRequest jsonRequest, HttpServletRequest request) throws IOException, JSONException{ goodReceivedNotesService.addGoodReceivedNotes(jsonRequest, JwtDecoder.decodeJwt(request).get("userId")); } @PostMapping("/editGoodReceivedNotes") public void editGoodReceivedNotes(@Valid @RequestBody PurchaseOrdersRequest jsonRequest, HttpServletRequest request) throws IOException, JSONException{ // goodReceivedNotesService.editGoodReceivedNotes(jsonRequest, JwtDecoder.decodeJwt(request)); } @PostMapping("/approveGoodReceivedNotes") public void approveGoodReceivedNotes(@Valid @RequestBody GoodReceivedNotesRequest jsonRequest, HttpServletRequest request) throws IOException, JSONException{ goodReceivedNotesService.approveGoodReceivedNotes(jsonRequest, JwtDecoder.decodeJwt(request).get("userId")); } @PostMapping("/findGrnPoProductByPO") public List<GrnPoProduct> findGrnPoProductByPO(@Valid @RequestBody GrnPoProductRequest jsonRequest, HttpServletRequest request) throws IOException, JSONException{ return goodReceivedNotesService.findGrnPoProductByPO(jsonRequest, JwtDecoder.decodeJwt(request).get("userId")); } @PostMapping("/findGrnPoProductByCode") public List<GrnPoProduct2> findGrnPoProductByCode(@Valid @RequestBody GoodReceivedNotesRequest jsonRequest, HttpServletRequest request) throws IOException, JSONException{ return goodReceivedNotesService.findGrnPoProductByCode(jsonRequest, JwtDecoder.decodeJwt(request).get("userId")); } }
package enthu_l; //Which of the following statements are true if the above program is run with the command line : //java Test closed public class e_1173 { public static void main(String[] args) {if (args[0].equals("open")) if (args[1].equals("someone")) System.out.println("Hello!"); else System.out.println("Go away "+ args[1]);} }
package com.ricettadem.model; import java.util.Objects; public class RichiestaLottiNre { private String codiceRegione; private String paramDimensioneLotto; private String codiceFiscale; public String getCodiceRegione() { return codiceRegione; } public void setCodiceRegione(String codiceRegione) { this.codiceRegione = codiceRegione; } public String getParamDimensioneLotto() { return paramDimensioneLotto; } public void setParamDimensioneLotto(String paramDimensioneLotto) { this.paramDimensioneLotto = paramDimensioneLotto; } public String getCodiceFiscale() { return codiceFiscale; } public void setCodiceFiscale(String codiceFiscale) { this.codiceFiscale = codiceFiscale; } @Override public int hashCode() { return Objects.hash(codiceRegione, paramDimensioneLotto, codiceFiscale); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final RichiestaLottiNre that = (RichiestaLottiNre) obj; return Objects.equals(codiceRegione, that.codiceRegione) && Objects.equals(paramDimensioneLotto, that.paramDimensioneLotto) && Objects.equals(codiceFiscale, that.codiceFiscale); } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("{"); result.append("codiceRegione: " + codiceRegione); result.append(", paramDimensioneLotto: " + paramDimensioneLotto); result.append(", codiceFiscale: " + codiceFiscale); result.append("}"); return result.toString(); } }
package com.tuitaking.everyDay; import com.tuitaking.common.MockUtil; import com.tuitaking.point2offer.Robot_13; import org.junit.Assert; import org.junit.Test; public class Robot_13T { @Test public void test(){ Robot_13 robot_13=new Robot_13(); // for(int i = 0 ;i<100;i++){ // int m=MockUtil.mockArray(1)[0]; // int n=MockUtil.mockArray(1)[0]; // int k=MockUtil.mockArray(1)[0]; // System.out.println("m:"+m+" n:"+n+" k:"+k); // Assert.assertEquals(robot_13.movingCount(m+1,n+1,k),robot_13.movingCount_v1(m+1,n+1,k)); // } robot_13.movingCount_v1(99,70,27); } }
package za.co.edusys.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import za.co.edusys.domain.model.User; import za.co.edusys.domain.repository.UserRepository; import java.util.List; @Service("authService") public class AuthService implements UserDetailsService { @Autowired UserRepository userRepository; @Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { return userRepository.findUserByUserName(userName); } public Iterable<User> getAllUsers(){ return userRepository.findAll(); } }
/* * Copyright (c) 2009-2011 by Jan Stender, Bjoern Kolbeck, * Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.mrc.osdselection; import java.net.InetAddress; import java.util.Comparator; import org.xtreemfs.common.uuids.ServiceUUID; import org.xtreemfs.common.uuids.UnknownUUIDException; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.logging.Logging.Category; import org.xtreemfs.foundation.util.OutputUtils; import org.xtreemfs.mrc.metadata.XLocList; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.Service; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceSet; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.OSDSelectionPolicyType; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.VivaldiCoordinates; /** * Sorts the list of OSDs in ascending order of their distance to the client. * The distance is determined by means of the server's and client's FQDNs. * * @author bjko, stender */ public class SortFQDNPolicy extends FQDNPolicyBase { public static final short POLICY_ID = (short) OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_FQDN .getNumber(); @Override public ServiceSet.Builder getOSDs(ServiceSet.Builder allOSDs, final InetAddress clientIP, VivaldiCoordinates clientCoords, XLocList currentXLoc, int numOSDs) { if (allOSDs == null) return null; allOSDs = PolicyHelper.sortServiceSet(allOSDs, new Comparator<Service>() { public int compare(Service o1, Service o2) { try { return getMatch(new ServiceUUID(o2.getUuid()).getAddress().getHostName(), clientIP .getCanonicalHostName()) - getMatch(new ServiceUUID(o1.getUuid()).getAddress().getHostName(), clientIP .getCanonicalHostName()); } catch (UnknownUUIDException e) { Logging.logMessage(Logging.LEVEL_WARN, Category.misc, this, "cannot compare UUIDs"); Logging.logMessage(Logging.LEVEL_WARN, this, OutputUtils.stackTraceToString(e)); return 0; } } }); return allOSDs; } @Override public ServiceSet.Builder getOSDs(ServiceSet.Builder allOSDs) { return allOSDs; } @Override public void setAttribute(String key, String value) { // don't accept any attributes } }
package com.smxknife.algorithm.simple; /** * @author smxknife * 2021/2/4 */ public class _01_Int_bit_print { public static void main(String[] args) { print(1); print(-1); print(0); print(Integer.MAX_VALUE); print(Integer.MIN_VALUE); print(-Integer.MIN_VALUE); // 最小的负数取反+1后就是它自己 print(Integer.MAX_VALUE + 1); System.out.println("-----------------"); print(Integer.MIN_VALUE >> 1); print(-1024 >> 1); print(1024 >> 1); System.out.println("-----------------"); print(Integer.MIN_VALUE >>> 1); print(-1024 >>> 1); print(1024 >>> 1); System.out.println("-----------------"); int num = 5; print(num); print(-num); print(~num + 1); // 负数就是正数取反加1 /** * 负数:二进制取反加1,即补码 */ } private static void print(int num) { for (int i = 31; i >= 0; i--) { System.out.print((num & (1 << i)) == 0 ? "0" : "1"); } System.out.println(" " + num); System.out.println(); } }
package com.tencent.mm.plugin.appbrand.page; import com.tencent.mm.plugin.appbrand.jsapi.an; public enum aa { APP_LAUNCH("appLaunch"), NAVIGATE_TO(an.NAME), NAVIGATE_BACK("navigateBack"), REDIRECT_TO("redirectTo"), RE_LAUNCH("reLaunch"), AUTO_RE_LAUNCH("autoReLaunch"), SWITCH_TAB("switchTab"); private final String type; private aa(String str) { this.type = str; } public final String toString() { return this.type; } }
import javafx.scene.Group; import javafx.stage.Stage; import java.util.ArrayList; /** * Deals with tasks at the 2-D level including * placing pieces and figuring out if a connect four * exists. */ public class Plane implements CONNECT_CONSTANTS{ private Piece[][] boardPlane; private int height; /** * Creates an empty 2-D plane with dimensions * of 5 by 5 filled with EmptySquares. */ public Plane() { boardPlane = new Piece[PLANE_SIZE][PLANE_SIZE]; for (int i = 0; i < PLANE_SIZE; i++) { for (int j = 0; j < PLANE_SIZE; j++) { boardPlane[i][j] = new Piece(); } } } public Plane(Stage stage, Group board, Group piece, int height) { this.height = height; boardPlane = new Piece[PLANE_SIZE][PLANE_SIZE]; for (int i = 0; i < PLANE_SIZE; i++) { for (int j = 0; j < PLANE_SIZE; j++) { boardPlane[i][j] = new Piece(piece, height, j, i); } } } /** * FOR TESTING PURPOSES ONLY: Given an * already modified int[] board, the constructor * creates a corresponding game board. * 1 --- Player One * -1 --- player Two * 0 --- Empty * @param square int[] array containing a model of a * board that is translated into a proper * board. */ public Plane(int[][] square) { boardPlane = new Piece[square.length][square[0].length]; for (int i = 0; i < square.length; i++) { for (int j = 0; j < square.length; j++) { boardPlane[i][j] = new Piece(); // if 1 or -1, create a player piece if (square[i][j] == 1) { // boardPlane[i][j] = new Piece(true, i * 30, j * 30); } else if (square[i][j] == -1) { // boardPlane[i][j] = new Piece(false, i * 30, j * 30); } } } } /** * Gets a Square from the 2-D plane * pre: 0 <= row < PLANE_SIZE * 0 <= col < PLANE_SIZE * * @param row the row index * @param col the column index * @return a Square piece with either an empty * square or game piece */ public Square getSquare(int row, int col) { if (row == PLANE_SIZE || col == PLANE_SIZE) { throw new IllegalArgumentException("Violation: IOB error accessing pieces on plane."); } return boardPlane[row][col]; } /** * Changes a given Square to another * Square type. * pre: p != null. * 0 <= row < PLANE_SIZE * 0 <= col < PLANE_SIZE * * @param row the row index * @param col the col index * @param team the desired piece for a * piece to be changed to */ public void setSquare(int row, int col, boolean team) { if (row < 0 || col < 0 || row >= PLANE_SIZE || col >= PLANE_SIZE) { throw new IllegalArgumentException("Violation: SetSquare(), p is null " + "or row/col are invalid."); } boardPlane[row][col].activatePiece(team); } /** * Without given a piece type, determines if there * is any winner on a given 2-D Plane. * * @return true if there is a connect for of any type */ public boolean isGameDone() { return isGameDone(true) || isGameDone(false); } /** * Check if the piece type given has * an existent connect four on the board. * pre: player != null * * @param player piece type being used to determine * if there is a connect four. * @return true if there is a connect four from a * given piece type. */ public boolean isGameDone(boolean player) { return iterateBoard(MID_INDEX, PLANE_SIZE, player) || iterateBoard(PLANE_SIZE, MID_INDEX, player); } /** * NOT FINISHED * Determines if the game is done given a * row, col, and piece type. Only searches * surroundings of this piece to check for * a connect four * * @param row row index * @param col column index * @param player piece type being looked at to * check for a connect four. * @return true if there is a connection of four * from a given piece. */ public boolean isGameDone(int row, int col, boolean player) { return checkConnect4(row, col, player); } /** * Iterates over all 25 squares of the plane * only checking around piece with the specified * type. * * @param rowLimit iterates all rows until the limit * @param colLimit iterates all cols until the limit * @param player piece type being used to check for a * connect four. * @return true if there is a connect four. */ public boolean iterateBoard(int rowLimit, int colLimit, boolean player) { for (int i = 0; i < rowLimit; i++) { for (int j = 0; j < colLimit; j++) { if (!boardPlane[i][j].isEmpty() && boardPlane[i][j].getTeam() == player) { if (checkConnect4(i, j, player)) { return true; } } } } return false; } /** * Assembles a list of directions from a * given point to traverse in in order to * check for a connect four. * * @param row row index of point * @param col column index of point * @param player piece type being used to * check for a connect four. * @return true if there is a connect four. */ private boolean checkConnect4(int row, int col, boolean player) { ArrayList<Direction> dir = new ArrayList<>(); // checks if vertical or horizontal square if (col < MID_INDEX) { dir.add(new Direction(0, 1)); } if (row < MID_INDEX) { dir.add(new Direction(1, 0)); } // checks if a diagonal square if (row < MID_INDEX && col >= PLANE_SIZE - MID_INDEX) { dir.add(new Direction(1, -1)); } else if (row < MID_INDEX && col < MID_INDEX) { dir.add(new Direction(1, 1)); } // iterates from all valid direction assembled from a given point for (Direction set : dir) { if (checkDirForFour(row, col, set, player)) { return true; } } return false; } /** * Iterated over a point given a direction * path and piece type to look for. * * @param row starting row index * @param col starting column index * @param set change in row and col to * get to next point * @param player piece type being checked for * connect four. * @return true if there is a connect four from * current path. */ private boolean checkDirForFour(int row, int col, Direction set, boolean player) { int doneSearch = 0; // iterates over already identified piece row += set.getRowROC(); col += set.getColROC(); // must be 3 in a row of same piece, otherwise game isn't done while(doneSearch < THRESHOLD - 1) { if (!boardPlane[row][col].isEmpty() && boardPlane[row][col].getTeam() == player) { row += set.getRowROC(); col += set.getColROC(); } else { return false; } doneSearch++; } return true; } /** * Prints out the 2-D plane. * * @return a string representing the current * game board. */ public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < PLANE_SIZE; i++) { sb.append("["); for (int j = 0; j < PLANE_SIZE - 1; j++) { sb.append(boardPlane[i][j]).append(" "); } sb.append(boardPlane[i][PLANE_SIZE - 1]).append("]\n"); } return sb.toString(); } }
package com.yida.design.command.demo.command; /** ********************* * 增加需求的命令 * * @author yangke * @version 1.0 * @created 2018年5月12日 上午10:28:58 *********************** */ public class AddRequirementCommand extends AbstractCommand { @Override public void execute() { // 找到需求 super.requirementGroup.find(); // 增加需求 super.requirementGroup.add(); // 给出计划 super.requirementGroup.plan(); } }
package com.smxknife.java2.thread.forkjoin.demo07; import java.util.concurrent.RecursiveTask; /** * @author smxknife * 2020/5/29 */ public class ForkSumTask extends RecursiveTask<Integer> { private int begin; private int end; public ForkSumTask(int begin, int end) { this.begin = begin; this.end = end; } @Override protected Integer compute() { int sum = end + begin; int mid = sum / 2; StringBuilder builder = new StringBuilder(Thread.currentThread().getName() + " | ") .append(String.format("begin = %s, end = %s, mid = %s | ", begin, end, mid)); if (mid - begin > 0) { builder.append(String.format("leftBegin = %s, leftEnd = %s | ", begin, mid)); builder.append(String.format("rightBegin = %s, rightEnd = %s", mid + 1, end)); System.out.println(builder.toString()); ForkSumTask left = new ForkSumTask(begin, mid); ForkSumTask right = new ForkSumTask(mid + 1, end); invokeAll(left, right); return left.join() + right.join(); } else { System.out.printf( "%s_compute() begin = %s, end = %s\r\n", Thread.currentThread().getName(), begin, end); return begin == end ? begin : begin + end; } } }
package 线程交互.PC1; public class Product_1 { private int count = 0; public synchronized void produce() { try { while (count != 0) { this.wait(); } count++; System.out.println(Thread.currentThread().getName() + "生产,当前商品数:" + count); this.notifyAll(); } catch (Exception e) { e.printStackTrace(); } } public synchronized void consume() { try { while (count == 0) { this.wait(); } count--; System.out.println(Thread.currentThread().getName() + "消费,当前商品数:" + count); this.notifyAll(); } catch (Exception e) { e.printStackTrace(); } } }
package com.rudecrab.springsecurity.model.entity; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; /** * @author RudeCrab */ @Data @Accessors(chain = true) @EqualsAndHashCode(callSuper = true) @TableName("user") public class UserEntity extends BaseEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 用户名 */ private String username; /** * 用户密码 */ private String password; }
package com.timmy.highUI.recyclerview.interactive; import android.graphics.Canvas; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import com.timmy.library.util.Logger; /** * Created by admin on 2016/12/5. */ public class MyItemTouchHelpCallback extends ItemTouchHelper.Callback { private final String TAG = this.getClass().getSimpleName(); private final ItemTouchListener mItemTouchListener; public MyItemTouchHelpCallback(ItemTouchListener listener) { this.mItemTouchListener = listener; } /** * 该方法主要用于设置touch事件的方向:上下拖拽和左右滑动 * * @param recyclerView * @param viewHolder * @return */ @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { Logger.d(TAG, "getMovementFlags"); int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;//拖拽方向:上下 int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;//滑动方向:左右 return makeMovementFlags(dragFlags, swipeFlags); } /** * 是否支持item左右滑动功能 * * @return */ @Override public boolean isItemViewSwipeEnabled() { return true; } /** * 是否支持item长按拖拽功能 * * @return */ @Override public boolean isLongPressDragEnabled() { return true; } /** * item拖拽回调的方法 * * @param recyclerView * @param viewHolder * @param target * @return */ @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { Logger.d(TAG, "onMove"); return mItemTouchListener.onItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition()); } /** * recyclerview滑动时,会调用该方法-》设置接口,让接口的实现类去真是处理 * * @param viewHolder * @param direction 滑动方向,可以判断是向左滑动还是向右 */ @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { Logger.d(TAG, "onSwiped"); mItemTouchListener.onItemRemove(viewHolder.getAdapterPosition()); } /** * item左右滑动时,改变item的样式 * * @param c * @param recyclerView * @param viewHolder * @param dX * @param dY * @param actionState * @param isCurrentlyActive */ @Override public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { Logger.d("dx:" + dX + " -dy:" + dY); if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { float scale = 1 - (Math.abs(dX) / viewHolder.itemView.getWidth());// 1-0 viewHolder.itemView.setScaleX(scale); viewHolder.itemView.setScaleY(scale); viewHolder.itemView.setAlpha(scale); } //从右向左滑动,超过删除宽度的一半,就让删除界面显示 // if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE && dX < 0) { // LinearLayout container = (LinearLayout) viewHolder.itemView.findViewById(R.id.ll_container); // RelativeLayout leftCon = (RelativeLayout) viewHolder.itemView.findViewById(R.id.rl_left_container); // TextView delete = (TextView) viewHolder.itemView.findViewById(R.id.tv_delete); // if (Math.abs(dX) < delete.getWidth() / 2) { // //向左滑动未超过删除控件宽度的一半->还原 //// viewHolder.itemView. // } else { // LinearLayout.LayoutParams conLp = (LinearLayout.LayoutParams) container.getLayoutParams(); // LinearLayout.LayoutParams leftLp = (LinearLayout.LayoutParams) leftCon.getLayoutParams(); // delete.setWidth(leftLp.width / 5); // conLp.setMargins(leftLp.width / 5, 0, 0, 0); // } // } super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); } /** * 当item拖拽或滑动时调用 * * @param viewHolder * @param actionState */ @Override public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { Logger.d("actionState:" + actionState); //当item拽或滑动时改变item的背景-->放开时,item背景恢复 if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) { viewHolder.itemView.setBackgroundColor(Color.GRAY); } super.onSelectedChanged(viewHolder, actionState); } @Override public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { viewHolder.itemView.setBackgroundColor(Color.WHITE); //处理item布局复用问题 viewHolder.itemView.setScaleX(1.0f); viewHolder.itemView.setScaleY(1.0f); viewHolder.itemView.setAlpha(1.0f); super.clearView(recyclerView, viewHolder); } }
package com.tamimattafi.mydebts.ui.fragments.drawer.base.debts; import java.lang.System; @kotlin.Metadata(mv = {1, 1, 16}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000\u001e\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\u0018\u00002\u00020\u0001B\r\u0012\u0006\u0010\u0002\u001a\u00020\u0003\u00a2\u0006\u0002\u0010\u0004J\u0010\u0010\u0005\u001a\u00020\u00062\u0006\u0010\u0007\u001a\u00020\bH\u0016\u00a8\u0006\t"}, d2 = {"Lcom/tamimattafi/mydebts/ui/fragments/drawer/base/debts/BaseDebtsAdapter;", "Lcom/tamimattafi/mydebts/ui/fragments/drawer/base/BaseAdapter;", "view", "Lcom/tamimattafi/mydebts/ui/fragments/drawer/base/BaseContract$View;", "(Lcom/tamimattafi/mydebts/ui/fragments/drawer/base/BaseContract$View;)V", "getItemHolder", "Landroidx/recyclerview/widget/RecyclerView$ViewHolder;", "parent", "Landroid/view/ViewGroup;", "app_release"}) public final class BaseDebtsAdapter extends com.tamimattafi.mydebts.ui.fragments.drawer.base.BaseAdapter { @org.jetbrains.annotations.NotNull() @java.lang.Override() public androidx.recyclerview.widget.RecyclerView.ViewHolder getItemHolder(@org.jetbrains.annotations.NotNull() android.view.ViewGroup parent) { return null; } public BaseDebtsAdapter(@org.jetbrains.annotations.NotNull() com.tamimattafi.mydebts.ui.fragments.drawer.base.BaseContract.View view) { super(null); } }
package com.mindfultrader.webapp.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import com.mindfultrader.webapp.models.User; import com.mindfultrader.webapp.repositories.UserRepository; @Controller public class AppController { @Autowired private UserRepository userRepo; @GetMapping("/home") public String viewHomePage() { return "index"; } @GetMapping("/register") public String showRegistrationForm(Model model) { model.addAttribute("user", new User()); return "signup_form"; } @PostMapping("/process_register") public String processRegister(User user) { BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String encodedPassword = passwordEncoder.encode(user.getPassword()); user.setPassword(encodedPassword); userRepo.save(user); return "register_success"; } @GetMapping("/users") public String listUsers(Model model) { List<User> listUsers = userRepo.findAll(); model.addAttribute("listUsers", listUsers); return "users"; } // @RequestMapping("/users/run") // public ModelAndView run() // { // // //Run algorithm and print to console // System.out.println("Creating Data object..."); // SampleData sdata = new SampleData(); // // // System.out.println("Creating algorithm objects..."); // Algorithm algo1 = new Algorithm(sdata.data1); // Algorithm algo2 = new Algorithm(sdata.data2); // Algorithm algo3 = new Algorithm(sdata.data3); // // algo1.runAlgo(sdata.torun); // System.out.println("Algo1 run."); // System.out.println(algo1.solution.getListOfResults()); // System.out.println(algo1.solution.getFinalAdvice()); // // algo2.runAlgo(sdata.torun); // System.out.println("Algo2 run."); // System.out.println(algo2.solution.getListOfResults()); // System.out.println(algo2.solution.getFinalAdvice()); // // algo3.runAlgo(sdata.torun); // System.out.println("Algo3 run."); // System.out.println(algo3.solution.getListOfResults()); // System.out.println(algo3.solution.getFinalAdvice()); // // // System.out.println("Algorithm has run :) "); // // // //Create MVC object for webapp // ModelAndView mv = new ModelAndView(); // mv.setViewName("result"); // mv.addObject("conclusion", algo1.solution.getFinalAdvice()); // mv.addObject("advice", algo1.solution.getListOfResults()); // // // //Return to previous Page // return mv; // } // }
package com.tencent.mm.protocal.c; import f.a.a.c.a; import java.util.LinkedList; public final class cdc extends bhd { public int hcE; public String rHk; public int rjC; public String rlo; public int sdX; public int syH; public int syI = 2; public double syJ; public double syK; public String syL; public String syM; public String syN; public String syO; public int syP; public String syQ; protected final int a(int i, Object... objArr) { int fS; if (i == 0) { a aVar = (a) objArr[0]; if (this.shX != null) { aVar.fV(1, this.shX.boi()); this.shX.a(aVar); } if (this.rHk != null) { aVar.g(2, this.rHk); } aVar.fT(3, this.rjC); aVar.fT(4, this.syH); if (this.rlo != null) { aVar.g(5, this.rlo); } aVar.fT(6, this.syI); aVar.c(7, this.syJ); aVar.c(8, this.syK); aVar.fT(9, this.hcE); aVar.fT(10, this.sdX); if (this.syL != null) { aVar.g(99, this.syL); } if (this.syM != null) { aVar.g(100, this.syM); } if (this.syN != null) { aVar.g(101, this.syN); } if (this.syO != null) { aVar.g(102, this.syO); } aVar.fT(103, this.syP); if (this.syQ == null) { return 0; } aVar.g(104, this.syQ); return 0; } else if (i == 1) { if (this.shX != null) { fS = f.a.a.a.fS(1, this.shX.boi()) + 0; } else { fS = 0; } if (this.rHk != null) { fS += f.a.a.b.b.a.h(2, this.rHk); } fS = (fS + f.a.a.a.fQ(3, this.rjC)) + f.a.a.a.fQ(4, this.syH); if (this.rlo != null) { fS += f.a.a.b.b.a.h(5, this.rlo); } fS = ((((fS + f.a.a.a.fQ(6, this.syI)) + (f.a.a.b.b.a.ec(7) + 8)) + (f.a.a.b.b.a.ec(8) + 8)) + f.a.a.a.fQ(9, this.hcE)) + f.a.a.a.fQ(10, this.sdX); if (this.syL != null) { fS += f.a.a.b.b.a.h(99, this.syL); } if (this.syM != null) { fS += f.a.a.b.b.a.h(100, this.syM); } if (this.syN != null) { fS += f.a.a.b.b.a.h(101, this.syN); } if (this.syO != null) { fS += f.a.a.b.b.a.h(102, this.syO); } fS += f.a.a.a.fQ(103, this.syP); if (this.syQ != null) { fS += f.a.a.b.b.a.h(104, this.syQ); } return fS; } else if (i == 2) { f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler); for (fS = bhd.a(aVar2); fS > 0; fS = bhd.a(aVar2)) { if (!super.a(aVar2, this, fS)) { aVar2.cJS(); } } return 0; } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; cdc cdc = (cdc) objArr[1]; int intValue = ((Integer) objArr[2]).intValue(); switch (intValue) { case 1: LinkedList IC = aVar3.IC(intValue); int size = IC.size(); for (intValue = 0; intValue < size; intValue++) { byte[] bArr = (byte[]) IC.get(intValue); fk fkVar = new fk(); f.a.a.a.a aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (boolean z = true; z; z = fkVar.a(aVar4, fkVar, bhd.a(aVar4))) { } cdc.shX = fkVar; } return 0; case 2: cdc.rHk = aVar3.vHC.readString(); return 0; case 3: cdc.rjC = aVar3.vHC.rY(); return 0; case 4: cdc.syH = aVar3.vHC.rY(); return 0; case 5: cdc.rlo = aVar3.vHC.readString(); return 0; case 6: cdc.syI = aVar3.vHC.rY(); return 0; case 7: cdc.syJ = aVar3.vHC.readDouble(); return 0; case 8: cdc.syK = aVar3.vHC.readDouble(); return 0; case 9: cdc.hcE = aVar3.vHC.rY(); return 0; case 10: cdc.sdX = aVar3.vHC.rY(); return 0; case 99: cdc.syL = aVar3.vHC.readString(); return 0; case 100: cdc.syM = aVar3.vHC.readString(); return 0; case 101: cdc.syN = aVar3.vHC.readString(); return 0; case 102: cdc.syO = aVar3.vHC.readString(); return 0; case 103: cdc.syP = aVar3.vHC.rY(); return 0; case 104: cdc.syQ = aVar3.vHC.readString(); return 0; default: return -1; } } } }
package com.tencent.map.swlocation.api; import android.content.Context; import android.os.Handler; import android.text.TextUtils; import com.d.a.a.q; import com.d.a.a.t; public class SwEngine { public static void startContinousLocationUpdate(Handler handler, int i, int i2, LocationUpdateListener locationUpdateListener, ServerMessageListener serverMessageListener) { t.a(handler, (long) i2, locationUpdateListener, serverMessageListener); } public static void stopContinousLocationUpdate() { t.sP(); } public static void creatLocationEngine(Context context, q qVar) { t.a(context, qVar); } public static void setImei(String str) { if (TextUtils.isEmpty(str)) { throw new NullPointerException("SenseWhereEngine:invalid imei!"); } t.setImei(str); } public static void onDestroy() { t.finish(); } }
package datatype; public class DataTypeDemo5 { public static void main(String[] args) { // 기본 자료형의 형변환 // 자동 형변환 // 컴파일러가 알아서 타입을 변환한다. // 크기가 작은 타입의 값을 크기가 큰 타입으로 변환시키는 것 // 정밀도가 낮은 타입의 값을 정밀도가 높은 타입으로 변환시키는 것 // 값의 손실이 발생하지 않는 타입 변환이다. // byte -> short -> char -> int -> long -> float -> double // 정수(int) -> 실수(double) : 4Byte 정수를 8Byte 실수형 변수에 담기 double a = 3; // 3 -> 3.0으로 변환 -> 3.0이 a에 대입 System.out.println(a); int b = 30; // 정수(int) -> 정수(long) : 4Byte 정수를 8Byte long형 변수에 담기 long c = b; // 30 -> 8Byte 30으로 변환 -> c에 대입 System.out.println(c); // 정수(int) -> 실수(float) : 4Byte 정수(낮은 정밀도)를 4Byte 실수형(높은 정밀도) 변수에 담기 float d = b; // 30 -> 30.0으로 변환 -> d에 대입 System.out.println(d); // 연산의 결과는 연산에 참여한 값의 타입과 동일한 타입의 값이 나온다. System.out.println(2/3); // 정수/정수 ----> 결과 : 정수값 System.out.println(2/3.0); // 정수/실수 -----> 실수/실수 ---> 결과 : 실수값 // 형변환 // 수동 형변환 // 개발자가 직접 변환할 타입을 지정해서 형변환을 시킨다. // 실수 -> 정수로 변환하는 것 // 데이터의 손실이 발생하는 변환임. 컴파일러가 3.14를 3으로 변환하지 않고 오류를 표시함. // (int)와 같은 연산식으로 형변환 의사를 직접 표시한다. (형변환 연산자) // double -> float -> long -> int -> char -> short -> byte int x = (int) 3.14; System.out.println(x); int y = (int) (67.5/3.14); System.out.println(y); double z = (double) (70 + 42 + 88)/3; System.out.println(z); // double z = (70+42+88)/3; 이러면 수식 계산 하고 나온 결과값(정수)이 마지막에 double로 변환돼서 .0만 붙음 } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.bean; import javax.xml.bind.annotation.XmlRootElement; import java.util.Calendar; /** * @author pavila * */ @XmlRootElement(name = "document") public class Document extends Node { private static final long serialVersionUID = 1L; public static final String TYPE = "okm:document"; public static final String CONTENT = "okm:content"; public static final String CONTENT_TYPE = "okm:resource"; public static final String SIZE = "okm:size"; public static final String LANGUAGE = "okm:language"; public static final String VERSION_COMMENT = "okm:versionComment"; public static final String NAME = "okm:name"; public static final String TEXT = "okm:text"; public static final String TITLE = "okm:title"; public static final String DESCRIPTION = "okm:description"; private String title = ""; private String description = ""; private String language = ""; private Calendar lastModified; private String mimeType; private boolean locked; private boolean checkedOut; private Version actualVersion; private LockInfo lockInfo; private boolean convertibleToPdf; private boolean convertibleToSwf; public LockInfo getLockInfo() { return lockInfo; } public void setLockInfo(LockInfo lockInfo) { this.lockInfo = lockInfo; } public Calendar getLastModified() { return lastModified; } public void setLastModified(Calendar lastModified) { this.lastModified = lastModified; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getMimeType() { return mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isCheckedOut() { return checkedOut; } public void setCheckedOut(boolean checkedOut) { this.checkedOut = checkedOut; } public boolean isLocked() { return locked; } public void setLocked(boolean locked) { this.locked = locked; } public Version getActualVersion() { return actualVersion; } public void setActualVersion(Version actualVersion) { this.actualVersion = actualVersion; } public boolean isConvertibleToPdf() { return convertibleToPdf; } public void setConvertibleToPdf(boolean convertibleToPdf) { this.convertibleToPdf = convertibleToPdf; } public boolean isConvertibleToSwf() { return convertibleToSwf; } public void setConvertibleToSwf(boolean convertibleToSwf) { this.convertibleToSwf = convertibleToSwf; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("path=").append(path); sb.append(", title=").append(title); sb.append(", description=").append(description); sb.append(", mimeType=").append(mimeType); sb.append(", author=").append(author); sb.append(", permissions=").append(permissions); sb.append(", created=").append(created == null ? null : created.getTime()); sb.append(", lastModified=").append(lastModified == null ? null : lastModified.getTime()); sb.append(", keywords=").append(keywords); sb.append(", categories=").append(categories); sb.append(", locked=").append(locked); sb.append(", lockInfo=").append(lockInfo); sb.append(", actualVersion=").append(actualVersion); sb.append(", subscribed=").append(subscribed); sb.append(", subscriptors=").append(subscriptors); sb.append(", uuid=").append(uuid); sb.append(", convertibleToPdf=").append(convertibleToPdf); sb.append(", convertibleToSwf=").append(convertibleToSwf); sb.append(", notes=").append(notes); sb.append("}"); return sb.toString(); } }
package com.example.amitkumarroshan.amaderaninos; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class DonateFrag extends Fragment { private FirebaseDatabase firebaseDatabase; private FirebaseAuth firebaseAuth; private DatabaseReference myData; private EditText email; private EditText books; private EditText phone; private EditText name; private EditText colg; private Button submit; public DonateFrag() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_donate, container, false); firebaseAuth = FirebaseAuth.getInstance(); if(firebaseAuth.getCurrentUser()==null){ Toast.makeText(v.getContext(), "Please LOGIN to donate", Toast.LENGTH_LONG).show(); } myData = firebaseDatabase.getInstance().getReference("DONATIONS"); email = (EditText) v.findViewById(R.id.donate_email); books = (EditText) v.findViewById(R.id.donate_books); name = (EditText) v.findViewById(R.id.donate_name); phone = (EditText) v.findViewById(R.id.donate_phone); colg = (EditText) v.findViewById(R.id.donate_colg); submit = (Button) v.findViewById(R.id.donate_button); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Details details = new Details(books.getText().toString(),colg.getText().toString(),phone.getText().toString(),email.getText().toString(),name.getText().toString()); myData.push().setValue(details); } }); return v; } } class Details{ private String name; private String email; private String phone; private String colg; private String books; public Details() { } public Details(String books, String colg, String phone, String email, String name) { this.books = books; this.colg = colg; this.phone = phone; this.email = email; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBooks() { return books; } public void setBooks(String books) { this.books = books; } public String getColg() { return colg; } public void setColg(String colg) { this.colg = colg; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
package com.tencent.mm.plugin.wear.model; import com.tencent.mm.plugin.wear.model.e.r; import com.tencent.mm.plugin.wear.model.f.d; class b$2 extends d { final /* synthetic */ b pIZ; b$2(b bVar) { this.pIZ = bVar; } public final void execute() { a.bSl(); r.b(20008, null, false); } public final String getName() { return "StepCountRequest"; } }
package com.jeju.trip.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.jeju.trip.vo.Criteria; import com.jeju.trip.vo.ReplyVO; public interface ReplyMapper { int insert(ReplyVO vo); ReplyVO read(Long rseq); int delete(Long rseq); int update(ReplyVO vo); List<ReplyVO> getList(@Param("cri") Criteria cri, @Param("qseq") Long qseq); }
package corgi.hub.core.mqtt.bean; import corgi.hub.core.mqtt.ServerChannel; /** * Created by Terry LIANG on 2016/12/23. */ public class MqttSession implements HubSession { private String clientId; private ServerChannel channel; private boolean cleanSession; public MqttSession(String clientId, ServerChannel channel, boolean cleanSession) { this.clientId = clientId; this.channel = channel; this.cleanSession = cleanSession; } public boolean isCleanSession() { return cleanSession; } public String getClientId() { return clientId; } public ServerChannel getChannel() { return channel; } }
/* * 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 dotrunner; import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; /** * * @author jelly */ public class Screen extends javax.swing.JFrame { /** * Creates new form Screen */ DotRunner dotRunner; Screen(DotRunner aThis) { dotRunner = aThis; setTitle("Dot Runner"); // setExtendedState(JFrame.MAXIMIZED_BOTH); // setUndecorated(false); initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents void namePrint(Graphics g ) { g.setColor(Color.white); g.drawString("Dot Runner", getWidth()-100,getHeight()/2 - 100); } public void paint(Graphics g) { namePrint(g); if(dotRunner!=null) dotRunner.paint(g); } // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables }
package polarpelican.units; /** * A <code>Stance</code> is a team's relationship with the player team. * @author cabbagebot */ public enum Stance { HOSTILE, NEUTRAL, FRIENDLY, PLAYERTEAM }
package br.com.maikel.poc.bold.facebold.entity; import java.util.Date; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import lombok.Getter; import lombok.Setter; @Entity @Table(name="TBPOST") public class Post { @Id @Column(name="POST_ID") @GeneratedValue(strategy=GenerationType.AUTO) private @Getter @Setter Long id; @Column(name="TEXT") private @Getter @Setter String text; @Column(name="DATE") private @Getter @Setter Date date; @ManyToOne @JoinColumn(name="USER_ID", nullable=false) private @Getter @Setter User user; @OneToMany(mappedBy="post", cascade= {CascadeType.PERSIST, CascadeType.MERGE}, orphanRemoval = true) private @Getter @Setter Set<Comment> comments; @OneToMany(mappedBy="post", cascade= {CascadeType.PERSIST, CascadeType.MERGE}, orphanRemoval = true) private @Getter @Setter Set<Action> actions; }
/* * $HeadURL: $ * $Id: $ * Copyright (c) 2016 by Riversoft System, all rights reserved. */ package com.riversoft.nami; import java.io.File; import java.net.URL; import com.riversoft.vote.VoteTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * NAMI平台类<br> * 保存NAMI对应的各类路径 * * @author woden * */ public class Platform { static Logger logger = LoggerFactory.getLogger(Platform.class); private static File PATH_ROOT;// 根路径 private static File PATH_REQUEST;// 请求 private static File PATH_FUNCTION;// 函数文件夹 private static File PATH_MP;// 公众号转发文件夹 /** * 函数目录 * * @return */ static File getFunctionPath() { return PATH_FUNCTION; } /** * 请求目录 * * @return */ static File getRequestPath() { return PATH_REQUEST; } /** * NAMI平台根目录 * * @return */ static File getRootPath() { return PATH_ROOT; } /** * 公众号转发 * * @return */ static File getMpPath() { return PATH_MP; } /** * NAMI平台初始化,tomcat启动时调用 */ protected static void init() { // 已初始化,则无需重复处理 if (PATH_ROOT != null) { logger.warn("NAMI平台无需重复初始化."); return; } URL initFileUrl = Thread.currentThread().getContextClassLoader().getResource("logback-test.xml");// 开发模式特征 if (initFileUrl == null) { // 标准部署 initFileUrl = Thread.currentThread().getContextClassLoader().getResource("jdbc.properties"); logger.info("切换目录参照系:{}", initFileUrl); PATH_ROOT = new File(initFileUrl.getFile()).getParentFile().getParentFile(); } else {// 开发环境 PATH_ROOT = new File(initFileUrl.getFile()).getParentFile(); } logger.info("NAMI平台根目录初始化成功:{}", PATH_ROOT); PATH_REQUEST = new File(PATH_ROOT, "request"); if (!PATH_REQUEST.exists()) { PATH_REQUEST.mkdirs(); } logger.info("NAMI request path:{}", PATH_REQUEST); PATH_FUNCTION = new File(PATH_ROOT, "function"); if (!PATH_FUNCTION.exists()) { PATH_FUNCTION.mkdirs(); } logger.info("NAMI function path:{}", PATH_FUNCTION); PATH_MP = new File(PATH_ROOT, "mp"); if (!PATH_MP.exists()) { PATH_MP.mkdirs(); } logger.info("NAMI mp path:{}", PATH_MP); } }
package Composition.Challange; /** * @Author pankaj * @create 4/26/21 3:38 PM */ public class Wall { private String direction; public Wall(String direction) { this.direction = direction; } public String getDirection() { return direction; } }
package com.example.demo; import javax.persistence.*; @Entity // SE EU QUISER MUDAR O NOME DA TABELA SEM MUDAR O NOME DA CLASSE-@Table(name="Produtos") public class Produto { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column private String nome; }
package com.tencent.mm.ui; class LauncherUI$5 implements Runnable { final /* synthetic */ LauncherUI tkA; LauncherUI$5(LauncherUI launcherUI) { this.tkA = launcherUI; } public final void run() { this.tkA.tkn.tjF.cqC(); } }
package com.example.teamboolean.apprentidash.Controllers; import com.amazonaws.regions.Regions; import com.amazonaws.services.simpleemail.AmazonSimpleEmailService; import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder; import com.amazonaws.services.simpleemail.model.*; import com.example.teamboolean.apprentidash.Models.AppUser; import com.example.teamboolean.apprentidash.Repos.DayRepository; import com.example.teamboolean.apprentidash.Repos.AppUserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.view.RedirectView; import java.security.Principal; import java.util.ArrayList; import java.util.List; @Controller public class ApprentiDashController { @Autowired AppUserRepository appUserRepository; @Autowired PasswordEncoder passwordEncoder; @Autowired DayRepository dayRepository; TimesheetController timesheetController = new TimesheetController(); /*********************************** AWS SES *********************************************/ //Things we need for sending email to admin. static final String FROM = "test@gmail.com"; // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. static final String TO = "test@hotmail.com"; // The subject line for the email. static final String SUBJECT = "User login"; // The HTML body for the email. static final String HTMLBODY = "<h1>Welcome, you are in</h1>" + "<h2>Thank you for choosing Apprenti-Dashboard. Good luck!</h2>"; // The email body for recipients with non-HTML email clients. static final String TEXTBODY = "This email was sent to notify you that the user is logedin. "; public void sendEmail(){ try { AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard() // Replace US_WEST_2 with the AWS Region you're using for // Amazon SES. .withRegion(Regions.US_WEST_2).build(); SendEmailRequest request = new SendEmailRequest() .withDestination( new Destination().withToAddresses(TO)) .withMessage(new Message() .withBody(new Body() .withHtml(new Content() .withCharset("UTF-8").withData(HTMLBODY)) .withText(new Content() .withCharset("UTF-8").withData(TEXTBODY))) .withSubject(new Content() .withCharset("UTF-8").withData(SUBJECT))) .withSource(FROM); client.sendEmail(request); System.out.println("Email sent!"); } catch (Exception ex) { System.out.println("The email was not sent. Error message: " + ex.getMessage()); } } /********************************************************************************/ //Root route @GetMapping("/") public RedirectView getRoot(Model m, Principal p){ // If the user is logged in, redirect them to clock-in // otherwise, direct them to home page // Huge thanks to David for the idea! if(p != null){ m.addAttribute("currentPage", "home"); return new RedirectView("/recordHour"); } else { return new RedirectView("/home"); } } //Home page @GetMapping("/home") public String getHome(Model m, Principal p){ //Sets the necessary variables for the nav bar timesheetController.loggedInStatusHelper(m, p); m.addAttribute("currentPage", "home"); return "home"; } //Login Page @GetMapping("/login") public String getLogin(Model m, Principal p){ //Sets the necessary variables for the nav bar timesheetController.loggedInStatusHelper(m, p); m.addAttribute("currentPage", "login"); return "login"; } //Sign-up page @GetMapping("/signup") public String startSignUp(Model m, Principal p){ //Sets the necessary variables for the nav bar timesheetController.loggedInStatusHelper(m, p); m.addAttribute("currentPage", "signup"); return "signup"; } //AppUserSettings Page @GetMapping("/settings") public String getAppUserSettings(Model m, Principal p){ //Sets the necessary variables for the nav bar AppUser appUser = appUserRepository.findByUsername(p.getName()); m.addAttribute("appuser",appUser); m.addAttribute("isLoggedIn",true); m.addAttribute("userFirstName", appUserRepository.findByUsername(p.getName()).getFirstName()); m.addAttribute("currentPage", "settings"); return "appusersettings"; } //AppUserSettings Page @PutMapping("/settings") public String editAppUserSettings(Model m, Principal p, String firstname, String lastname, String manager, String email, String phone, boolean optEmail, boolean optText){ //Sets the necessary variables for the nav bar AppUser appUser = appUserRepository.findByUsername(p.getName()); appUser.setFirstName(firstname); appUser.setLastName(lastname); appUser.setManagerName(manager); appUser.setEmail(email); appUser.setPhone(phone); appUser.setOptEmail(optEmail); appUser.setOptText(optText); appUserRepository.save(appUser); m.addAttribute("editSaved",1); return getAppUserSettings(m,p); } @PutMapping("/resetpassword") public String resetPassword(Model m, Principal p, String oldpassword, String newpassword, String confirmpassword) { AppUser currentUser = appUserRepository.findByUsername(p.getName()); m.addAttribute("isLoggedIn",true); m.addAttribute("userFirstName", appUserRepository.findByUsername(p.getName()).getFirstName()); m.addAttribute("currentPage", "settings"); if (!passwordEncoder.matches(oldpassword, currentUser.getPassword())) { m.addAttribute("statusCode", 0); return getAppUserSettings(m,p); } else if (!newpassword.equals(confirmpassword)) { m.addAttribute("statusCode", 1); return getAppUserSettings(m,p); } else { currentUser.setPassword(passwordEncoder.encode(newpassword)); appUserRepository.save(currentUser); m.addAttribute("statusCode", 2); return getAppUserSettings(m,p); } } @PostMapping("/signup") public String addUser(String username, String password, String firstName, String lastName, String managerName, String email, String phone, boolean optEmail, boolean optText){ if (!checkUserName(username)) { AppUser newUser = new AppUser(username, passwordEncoder.encode(password), firstName, lastName, managerName, email, phone, optEmail, optText); appUserRepository.save(newUser); Authentication authentication = new UsernamePasswordAuthenticationToken(newUser, null, new ArrayList<>()); SecurityContextHolder.getContext().setAuthentication(authentication); if (newUser.isOptEmail()) { sendEmail(); } return "redirect:/"; }else { return "duplicateUsername"; } } /************************************ End of Controller to handle the Edit page ***************************************************************************/ //help function to check if the username exist in database public boolean checkUserName(String username){ Iterable<AppUser> allUsers = appUserRepository.findAll(); List<String> allUsername = new ArrayList<>(); for(AppUser appUser : allUsers){ allUsername.add(appUser.getUsername()); } if(allUsername.contains(username)){ return true; }else{ return false; } } }
/* * Copyright 2008 University of California at Berkeley. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.rebioma.server.overlays; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.apache.log4j.Logger; /** * Keeps a global variable <code>ascPath</code> representing the location of * various .asc files. * * The location is specified in "rebioma.properties" using key * "asc_storage_path" * * @author daen * */ public class StoragePathManager { private static Logger log = Logger.getLogger(StoragePathManager.class); private static String storageDir; private static final String DEFAULT_STORAGE_PATH = "/rebioma/storage"; private static final String PROPERTIES_FILE = "/rebioma.properties"; private static final String PROPERTIES_STORAGE_KEY = "storage_path"; public static String getStoragePath() { if (storageDir != null) return storageDir; String path = DEFAULT_STORAGE_PATH; try { Properties prop = new Properties(); InputStream propStream = StoragePathManager.class .getResourceAsStream(PROPERTIES_FILE); prop.load(propStream); path = prop.getProperty(PROPERTIES_STORAGE_KEY); } catch (IOException e) { log.warn("Using default value for storage directory"); } log.info("Storage directory: " + path); storageDir = path; return storageDir; } public static String getStoragePath(String fileName, String webRoot) throws IOException { File file = new File(getStoragePath(), fileName); if (file.exists()) { return file.getCanonicalPath(); } return webRoot + fileName; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package base_dato; import java.awt.Image; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.net.InetAddress; import java.net.NetworkInterface; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.*; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JOptionPane; public class ManejadorSQL { private Connection c; // conexion private Statement q; // query private String driver, nombre_db, ip, port, user, pass, jdbc; private String clave, usuario, tipo, id, nombre_usuario; String h2; public Date fecha; public int id_rol; public String cedulai; public validaciones val; public String id_usuario; Calendar calendario = new GregorianCalendar(); public ManejadorSQL(String db_name, String ip, String user, String pass, String driver2, String port2, String jdbc2, String h3, validaciones val2) { this.ip = ip; this.nombre_db = db_name; this.user = user; this.pass = pass; this.driver = driver2; this.port = port2; this.jdbc = jdbc2; this.h2 = h3; this.val = val2; Conectar(); } public Connection getConx() { return this.c; } public void close() { try { c.close(); } catch (SQLException ex) { Logger.getLogger(ManejadorSQL.class.getName()).log(Level.SEVERE, null, ex); } } public void cerrar_aplicacion() { // String separador = System.getProperty("file.separator"); // File ruta = new File("C:" + separador + "dbxconnections2.ini"); // ruta.delete(); NetworkInterface a; String macpc = null; try { a = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); byte[] mac = a.getHardwareAddress(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < mac.length; i++) { sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); } macpc = sb.toString(); this.Update("tblxian_ipapp", "in_act=0", "mac='" + macpc + "'"); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.toString()); e.printStackTrace(); } } private String toHexadecimal(byte[] digest) { String hash = ""; for (byte aux : digest) { int b = aux & 0xff; if (Integer.toHexString(b).length() == 1) { hash += "0"; } hash += Integer.toHexString(b); } return hash; } /** * * * 34 Encripta un mensaje de texto mediante algoritmo de resumen de mensaje. * 35 * * @param message texto a encriptar 36 * @param algorithm algoritmo de encriptacion, puede ser: MD2, MD5, SHA-1, * SHA-256, SHA-384, SHA-512 37 * @return mensaje encriptado * */ public String getStringMessageDigest(String message, String algorithm) { byte[] digest = null; byte[] buffer = message.getBytes(); try { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); messageDigest.reset(); messageDigest.update(buffer); digest = messageDigest.digest(); } catch (NoSuchAlgorithmException ex) { System.out.println("Error creando Digest"); } return toHexadecimal(digest); } public Statement realizarstatment() { try { q = c.createStatement(); } catch (SQLException ex) { try { this.Log("Error Critico", ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return (q); } public Connection devolverconexion() { return (this.getConexion()); } private boolean Conectar() { try { Class.forName(this.driver); if (h2.equals("1")) { this.c = DriverManager.getConnection(this.jdbc + "://" + this.ip + ";databaseName=" + this.nombre_db + ";user=" + this.user + ";password=" + this.pass + ";"); } else { this.c = DriverManager.getConnection(this.jdbc + "://" + this.ip + ":" + this.port + "/" + this.nombre_db, this.user, this.pass); } if (this.c != null) { this.q = c.createStatement(); } return true; } catch (ClassNotFoundException ex) { try { this.Log("Error Critico", ex.getMessage(), "BD"); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //System.out.println(ex); //JOptionPane.showMessageDialog(null, ex.getMessage()); System.out.println("[ClassNotFoundException]Ocurrio un error al conectar con la base de datos."); return false; //Logger.getLogger(ManejadorSQL.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { try { //System.out.println(ex); //JOptionPane.showMessageDialog(null, ex.getMessage()); this.Log("Error Critico", ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //System.out.println("[SQLException]Ocurrio un error al conectar con la base de datos."); return false; } } public void Desconectar() { try { c.close(); } catch (SQLException ex) { try { this.Log("Error Critico", ex.getMessage(), "BD"); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } } public boolean Update(String tabla, String set, String codition) { try { this.q.executeUpdate("UPDATE " + tabla + " SET " + set + " WHERE " + codition + ";"); try { this.Log(this.getUsuario(), "UPDATE " + tabla + " SET " + set + " WHERE " + codition + "; " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return true; } catch (SQLException ex) { try { //JOptionPane.showMessageDialog(null, ex.getMessage()); this.Log(this.getUsuario(), "UPDATE " + tabla + " SET " + set + " WHERE " + codition + "; " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return false; } /** * Uso: INSERT INTO table_name VALUES (value1,value2,value3,...) */ public boolean Insert(String tabla, String values) { try { this.q.executeUpdate("INSERT INTO " + tabla + " VALUES(" + values + ");"); try { this.Log(this.getUsuario(), "INSERT INTO " + tabla + " VALUES(" + values + "); " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return true; } catch (SQLException ex) { try { this.Log(this.getUsuario(), "INSERT INTO " + tabla + " VALUES(" + values + "); " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return false; } public boolean Insert(String tabla, String campos, String values) { try { this.q.executeUpdate("INSERT INTO " + tabla + "(" + campos + ") VALUES(" + values + ");"); try { this.Log(this.getUsuario(), "INSERT INTO " + tabla + "(" + campos + ") VALUES(" + values + "); " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return true; } catch (SQLException ex) { try { this.Log(this.getUsuario(), "INSERT INTO " + tabla + "(" + campos + ") VALUES(" + values + "); " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return false; } /** * Not yet tested!! DELETE FROM table_name WHERE some_column=some_value * * @param tabla * @return cierto o falso */ public boolean Delete(String tabla, String codition) { try { this.q.execute("DELETE FROM " + tabla + " WHERE " + codition); try { this.Log(this.getUsuario(), "DELETE FROM " + tabla + " WHERE " + codition + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return true; } catch (SQLException ex) { try { this.Log(this.getUsuario(), "DELETE FROM " + tabla + " WHERE " + codition + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return false; } /** * * SELECT column_name,column_name FROM table_name */ public ResultSet Select(String tabla, String columns) { ResultSet set; try { set = this.q.executeQuery("SELECT " + columns + " FROM " + tabla + ";"); try { this.Log(this.getUsuario(), "SELECT " + columns + " FROM " + tabla + "; " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return set; } catch (SQLException ex) { try { this.Log(this.getUsuario(), "SELECT " + columns + " FROM " + tabla + "; " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return null; } public ResultSet Select(String tabla, String columns, String Where) { ResultSet set; try { set = this.q.executeQuery("SELECT " + columns + " FROM " + tabla + " WHERE " + Where + ";"); try { this.Log(this.getUsuario(), "SELECT " + columns + " FROM " + tabla + " WHERE " + Where + "; " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return set; } catch (SQLException ex) { try { this.Log(this.getUsuario(), "SELECT " + columns + " FROM " + tabla + " WHERE " + Where + "; " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return null; } public ResultSet Select2(String tabla, String columns, String Where) { ResultSet set, set2 = null; try { set = this.q.executeQuery("SELECT " + columns + " FROM " + tabla + " WHERE " + Where + ";"); try { this.Log(this.getUsuario(), "SELECT " + columns + " FROM " + tabla + " WHERE " + Where + "; " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } while (set.next()) { set2 = set; break; } return set2; } catch (SQLException ex) { try { this.Log(this.getUsuario(), "SELECT " + columns + " FROM " + tabla + " WHERE " + Where + "; " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } // JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return null; } public boolean Select3(String tabla, String columns, String Where) { ResultSet set, set2 = null; try { set = this.q.executeQuery("SELECT " + columns + " FROM " + tabla + " WHERE " + Where + ";"); try { this.Log(this.getUsuario(), "SELECT " + columns + " FROM " + tabla + " WHERE " + Where + "; " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } while (set.next()) { set2 = set; return true; } } catch (SQLException ex) { try { this.Log(this.getUsuario(), "SELECT " + columns + " FROM " + tabla + " WHERE " + Where + "; " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return false; } public int SelectCount(String tabla, String Where) { ResultSet set, set2 = null; int cantidadFilas = 0; //int cont=0; try { set = this.q.executeQuery("SELECT * FROM " + tabla + " WHERE " + Where + ";"); try { this.Log(this.getUsuario(), "SELECT * FROM " + tabla + " WHERE " + Where + "; " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } while (set.next()) { set2 = set; cantidadFilas++; } } catch (SQLException ex) { try { this.Log(this.getUsuario(), "SELECT * FROM " + tabla + " WHERE " + Where + "; " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return cantidadFilas; } public ResultSet SelectUltimo(String tabla, String condicion) { ResultSet set, set2 = null; try { set = this.q.executeQuery("SELECT * FROM " + tabla + " WHERE " + condicion + ""); try { this.Log(this.getUsuario(), "SELECT * FROM " + tabla + " WHERE " + condicion + "; " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } while (set.next()) { set2 = set; if (set2.isLast()) { break; } } return set2; } catch (SQLException ex) { try { this.Log(this.getUsuario(), "SELECT * FROM " + tabla + " WHERE " + condicion + "; " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return null; } public boolean SelectUltimo2(String tabla, String condicion) { ResultSet set, set2 = null; try { set = this.q.executeQuery("SELECT * FROM " + tabla + " WHERE " + condicion + ""); try { this.Log(this.getUsuario(), "SELECT * FROM " + tabla + " WHERE " + condicion + "; " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } while (set.next()) { set2 = set; if (set2.isLast()) { return true; } } } catch (SQLException ex) { try { this.Log(this.getUsuario(), "SELECT * FROM " + tabla + " WHERE " + condicion + "; " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); /// verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return false; } public boolean Admin_Existe(String adminNombre, String adminClave) { try { // "select * from public.usuario where nombre_usuario='"+n+"' and clave='"+c+"'"; //System.out.println(this.c+"...conexion vacia"); ResultSet t = Select("tblsit_usr", "id_rol_usr, in_status_usr", "tx_login = '" + adminNombre + "' and tx_clave = '" + adminClave + "'"); if (t.next()) { return true; } return false; } catch (SQLException ex) { try { this.Log(this.getUsuario(), ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); return false; } } public boolean Respuesta_Existe(String pregunta, String respuesta, String usuario) { try { // "select * from public.usuario where nombre_usuario='"+n+"' and clave='"+c+"'"; ResultSet t = Select("public.usuario", "pregunta, respuesta", "pregunta = '" + pregunta + "' and respuesta = '" + respuesta + "' and nombreu='" + usuario + "'"); if (t.next()) { return true; } return false; } catch (SQLException ex) { try { this.Log(this.getUsuario(), ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); return false; } } /** * * @param militarCedula * @return */ public boolean ExisteUnCampo(String tabla, String campos, String campoClave, String nombreUsuario) { try { // "select * from public.usuario where nombre_usuario='"+n+"' and clave='"+c+"'"; ResultSet t = Select(tabla, campos, campoClave + "= '" + nombreUsuario + "'"); if (t.next()) { return true; } return false; } catch (SQLException ex) { try { this.Log(this.getUsuario(), ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); return false; } } public boolean ExisteCampo(String tabla, String campos, String campoClave) { try { // "select * from public.usuario where nombre_usuario='"+n+"' and clave='"+c+"'"; ResultSet t = Select(tabla, campos, campoClave); if (t.next()) { return true; } return false; } catch (SQLException ex) { try { this.Log(this.getUsuario(), ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } // JOptionPane.showMessageDialog(null, ex.getMessage()); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); return false; } } public Connection getConexion() { return this.c; } public Statement getStatement() { return this.q; } //FUNCIONES PARA MANEJAR IMAGENES PARA LA TABLA REPUESTOS public boolean guardarfoto(String codigo, String descrip, String contado, String credito, String cantidad, String categoria, String name, String ruta) { FileInputStream fis = null; try { File file = new File(ruta); fis = new FileInputStream(file); PreparedStatement pstm = c.prepareStatement("INSERT into " + " tblxian_repuesto(cod_repuesto,tx_descripcion,nu_precio_contado,nu_precio_credito,nu_cant_disponible" + ",id_categoria,nb_imagen, img_imagen) " + " VALUES(?,?,?,?,?,?,?,?)"); pstm.setString(1, codigo); pstm.setString(2, descrip); pstm.setDouble(3, Double.parseDouble(contado)); pstm.setDouble(4, Double.parseDouble(credito)); pstm.setInt(5, Integer.parseInt(cantidad)); pstm.setInt(6, Integer.parseInt(categoria)); pstm.setString(7, name); pstm.setBinaryStream(8, fis, (int) file.length()); pstm.execute(); try { this.Log(this.getUsuario(), "INSERT into " + " tblxian_repuesto(cod_repuesto,tx_descripcion,nu_precio_contado,nu_precio_credito,nu_cant_disponible" + ",id_categoria,nb_imagen, img_imagen) " + " VALUES(?,?,?,?,?,?,?,?); " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } pstm.close(); return true; } catch (FileNotFoundException | SQLException e) { try { this.Log(this.getUsuario(), "INSERT into " + " tblxian_repuesto(cod_repuesto,tx_descripcion,nu_precio_contado,nu_precio_credito,nu_cant_disponible" + ",id_categoria,nb_imagen, img_imagen) " + " VALUES(?,?,?,?,?,?,?,?); " + calendario.getTime() + "ERROR= " + e.getMessage(), "BD"); //System.out.println(e.getMessage()); //System.out.println(e.getMessage()); // verificar_estado_conexion(); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } } finally { try { fis.close(); } catch (IOException e) { try { this.Log(this.getUsuario(), e.getMessage(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } //JOptionPane.showMessageDialog(null, e.getMessage()); //System.out.println(e.getMessage()); } } return false; } public boolean guardarfotocrucifijo(String nombre, String ruta, String cantidad, String puntos) { FileInputStream fis = null; try { File file = new File(ruta); fis = new FileInputStream(file); PreparedStatement pstm = c.prepareStatement("INSERT into" + " tbl_crucifijo(nb_crucifijo,img_crucifijo,cant_resp_correcta,puntos) " + " VALUES(?,?,?,?)"); pstm.setString(1, nombre); pstm.setBinaryStream(2, fis, (int) file.length()); pstm.setInt(3, Integer.parseInt(cantidad)); pstm.setInt(4, Integer.parseInt(puntos)); pstm.execute(); pstm.close(); return true; } catch (FileNotFoundException | SQLException e) { } finally { try { fis.close(); } catch (IOException e) { try { this.Log(this.getUsuario(), e.getMessage(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } //JOptionPane.showMessageDialog(null, e.getMessage()); //System.out.println(e.getMessage()); } } return false; } public boolean modificarfoto(String codigo, String descrip, String contado, String credito, String cantidad, String categoria, String name, String ruta) { FileInputStream fis = null; try { File file = new File(ruta); fis = new FileInputStream(file); // PreparedStatement pstm = c.prepareStatement("UPDATE" + // " public.imagenes SET tx_descr_repuesto='"+descrip+"',nu_precio_contado="+contado+",nu_precio_credito=" // + ""+credito+",nu_cant_disponible="+cantidad+",id_categoria="+categoria+",nb_imagen='"+name+"', img_imagen WHERE cod_repuesto='"+codigo+"'"); PreparedStatement pstm = c.prepareStatement("UPDATE tblxian_repuesto " + "set tx_descripcion = ? ," + "nu_precio_contado = ? ," + "nu_precio_credito = ? ," + "nu_cant_disponible = ? ," + "id_categoria = ? ," + "nb_imagen = ? ," + "img_imagen = ? " + "WHERE cod_repuesto = ? "); // pstm.setString(1, name); // pstm.setBinaryStream(2, fis,(int) file.length()); // pstm.setString(1, codigo); pstm.setString(1, descrip); pstm.setDouble(2, Double.parseDouble(contado)); pstm.setDouble(3, Double.parseDouble(credito)); pstm.setInt(4, Integer.parseInt(cantidad)); pstm.setInt(5, Integer.parseInt(categoria)); pstm.setString(6, name); pstm.setBinaryStream(7, fis, (int) file.length()); pstm.setString(8, codigo); pstm.execute(); try { this.Log(this.getUsuario(), "UPDATE tblxian_repuesto " + "set tx_descripcion = ? ," + "nu_precio_contado = ? ," + "nu_precio_credito = ? ," + "nu_cant_disponible = ? ," + "id_categoria = ? ," + "nb_imagen = ? ," + "img_imagen = ? " + "WHERE cod_repuesto = ? ; " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } pstm.close(); return true; } catch (FileNotFoundException e) { try { this.Log(this.getUsuario(), "UPDATE tblxian_repuesto " + "set tx_descripcion = ? ," + "nu_precio_contado = ? ," + "nu_precio_credito = ? ," + "nu_cant_disponible = ? ," + "id_categoria = ? ," + "nb_imagen = ? ," + "img_imagen = ? " + "WHERE cod_repuesto = ? ; " + calendario.getTime() + "ERROR= " + e.getMessage(), "BD"); //JOptionPane.showMessageDialog(null, e.getMessage()); //System.out.println(e.getMessage()); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } } catch (SQLException e) { try { //JOptionPane.showMessageDialog(null, e.getMessage()); this.Log(this.getUsuario(), "UPDATE tblxian_repuesto " + "set tx_descripcion = ? ," + "nu_precio_contado = ? ," + "nu_precio_credito = ? ," + "nu_cant_disponible = ? ," + "id_categoria = ? ," + "nb_imagen = ? ," + "img_imagen = ? " + "WHERE cod_repuesto = ? ; " + calendario.getTime() + "ERROR= " + e.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, e); // System.out.println(e.getMessage()); } finally { try { fis.close(); } catch (IOException e) { try { this.Log(this.getUsuario(), "UPDATE tblxian_repuesto " + "set tx_descripcion = ? ," + "nu_precio_contado = ? ," + "nu_precio_credito = ? ," + "nu_cant_disponible = ? ," + "id_categoria = ? ," + "nb_imagen = ? ," + "img_imagen = ? " + "WHERE cod_repuesto = ? ; " + calendario.getTime() + "ERROR= " + e.getMessage(), "BD"); //System.out.println(e.getMessage()); //System.out.println(e.getMessage()); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } } } return false; } public boolean modificarfoto2(String codigo, String descrip, String contado, String credito, String cantidad, String categoria) { try { // PreparedStatement pstm = c.prepareStatement("UPDATE" + // " public.imagenes SET tx_descr_repuesto='"+descrip+"',nu_precio_contado="+contado+",nu_precio_credito=" // + ""+credito+",nu_cant_disponible="+cantidad+",id_categoria="+categoria+",nb_imagen='"+name+"', img_imagen WHERE cod_repuesto='"+codigo+"'"); PreparedStatement pstm = c.prepareStatement("UPDATE tblxian_repuesto " + "set tx_descripcion = ? ," + "nu_precio_contado = ? ," + "nu_precio_credito = ? ," + "nu_cant_disponible = ? ," + "id_categoria = ? " + "WHERE cod_repuesto = ? "); // pstm.setString(1, name); // pstm.setBinaryStream(2, fis,(int) file.length()); // pstm.setString(1, codigo); pstm.setString(1, descrip); pstm.setDouble(2, Double.parseDouble(contado)); pstm.setDouble(3, Double.parseDouble(credito)); pstm.setInt(4, Integer.parseInt(cantidad)); pstm.setInt(5, Integer.parseInt(categoria)); pstm.setString(6, codigo); pstm.execute(); try { this.Log(this.getUsuario(), "UPDATE tblxian_repuesto " + "set tx_descripcion = ? ," + "nu_precio_contado = ? ," + "nu_precio_credito = ? ," + "nu_cant_disponible = ? ," + "id_categoria = ? " + "WHERE cod_repuesto = ? ; " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } pstm.close(); return true; } catch (SQLException ex) { try { this.Log(this.getUsuario(), "UPDATE tblxian_repuesto " + "set tx_descripcion = ? ," + "nu_precio_contado = ? ," + "nu_precio_credito = ? ," + "nu_cant_disponible = ? ," + "id_categoria = ? " + "WHERE cod_repuesto = ? ; " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } //JOptionPane.showMessageDialog(null, ex); Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } return false; } /* Metodo que convierte una cadena de bytes en una imagen JPG * input: * bytes: array que contiene los binarios de la imagen * Output: la foto JPG en formato IMAGE */ private Image ConvertirImagen(byte[] bytes, String tipo) throws IOException { //String tipo="gif"; ByteArrayInputStream bis = new ByteArrayInputStream(bytes); Iterator readers = ImageIO.getImageReadersByFormatName(tipo); ImageReader reader = (ImageReader) readers.next(); Object source = bis; ImageInputStream iis = ImageIO.createImageInputStream(source); reader.setInput(iis, true); ImageReadParam param = reader.getDefaultReadParam(); return reader.read(0, param); } /* Metodo que extrae los registros de la tabla IMAGEN de la base de datos * crea instancia nueva de la clase imagen.java y añade los datos * agrega estos datos a un DefaultListModel * output: * dml: Es un DefaultListModel que contiene instancia de la clase imagen.java */ public imagen cargarFoto(String id_foto) { imagen img = new imagen(); try { q = c.createStatement(); ResultSet set = q.executeQuery("SELECT cod_repuesto,nb_imagen,img_imagen FROM tblxian_repuesto WHERE cod_repuesto='" + id_foto + "'"); try { this.Log(this.getUsuario(), "SELECT cod_repuesto,nb_imagen,img_imagen FROM tblxian_repuesto WHERE cod_repuesto='" + id_foto + "' ; " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } while (set.next()) { img.setId(set.getString("cod_repuesto")); img.setName(set.getString("nb_imagen")); String t = img.getName();//obtengo el nombre de la imagen int indice = 0; int longitud = t.length();//obtenemos la longitud del nombre int indicepunto = t.indexOf('.', indice);//obtengo el lugar donde esta el primer punto en ese nombre while (indicepunto >= 0) {//verificamos si existen mas puntos indice = indicepunto + 1;//aumentamos el indice a la posicion del primer punto indicepunto = t.indexOf('.', indice);//volvemos a buscar un punto a partir del nuevo indice } t = t.substring(indice, longitud); try { //antes de agregar el campo imagen, realiza la conversion de bytes a JPG img.setArchivo(ConvertirImagen(set.getBytes("img_imagen"), t)); } catch (IOException ex) { try { this.Log(this.getUsuario(), "SELECT cod_repuesto,nb_imagen,img_imagen FROM tblxian_repuesto WHERE cod_repuesto='" + id_foto + "' ; " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); //System.err.println(ex.getMessage()); //System.err.println(ex.getMessage()); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } } } } catch (SQLException ex) { try { this.Log(this.getUsuario(), "SELECT cod_repuesto,nb_imagen,img_imagen FROM tblxian_repuesto WHERE cod_repuesto='" + id_foto + "' ; " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); // JOptionPane.showMessageDialog(null, ex); } return img; } public imagen cargarFotocrucifijo(String id_foto) { imagen img = new imagen(); try { q = c.createStatement(); ResultSet set = q.executeQuery("SELECT * FROM tbl_crucifijo WHERE id_crucifijo=" + id_foto + ""); try { this.Log(this.getUsuario(), "SELECT * FROM tbl_crucifijo WHERE id_crucifijo=" + id_foto + " ; " + calendario.getTime(), "BD"); } catch (IOException ex) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); } while (set.next()) { img.setId(set.getString("id_crucifijo")); img.setName(set.getString("nb_crucifijo")); String t = img.getName();//obtengo el nombre de la imagen int indice = 0; int longitud = t.length();//obtenemos la longitud del nombre int indicepunto = t.indexOf('.', indice);//obtengo el lugar donde esta el primer punto en ese nombre while (indicepunto >= 0) {//verificamos si existen mas puntos indice = indicepunto + 1;//aumentamos el indice a la posicion del primer punto indicepunto = t.indexOf('.', indice);//volvemos a buscar un punto a partir del nuevo indice } t = t.substring(indice, longitud); try { //antes de agregar el campo imagen, realiza la conversion de bytes a JPG img.setArchivo(ConvertirImagen(set.getBytes("img_crucifijo"), t)); } catch (IOException ex) { try { this.Log(this.getUsuario(), "SELECT * FROM tbl_crucifijo WHERE id_crucifijo='" + id_foto + "' ; " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); //System.err.println(ex.getMessage()); //System.err.println(ex.getMessage()); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } } } } catch (SQLException ex) { try { this.Log(this.getUsuario(), "SELECT cod_repuesto,nb_imagen,img_imagen FROM tblxian_repuesto WHERE cod_repuesto='" + id_foto + "' ; " + calendario.getTime() + "ERROR= " + ex.getMessage(), "BD"); // verificar_estado_conexion(); } catch (IOException ex1) { Logger.getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex1); } Logger .getLogger(ManejadorSQL.class .getName()).log(Level.SEVERE, null, ex); // JOptionPane.showMessageDialog(null, ex); } return img; } /** * @return the clave */ public String getClave() { return clave; } /** * @param clave the clave to set */ public void setClave(String clave) { this.clave = clave; } /** * @return the usuario */ public String getUsuario() { return usuario; } /** * @param usuario the usuario to set */ public void setUsuario(String usuario) { this.usuario = usuario; } /** * @return the tipo */ public String getTipo() { return tipo; } /** * @param tipo the tipo to set */ public void setTipo(String tipo) { this.tipo = tipo; } /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the nombre_usuario */ public String getNombre_usuario() { return nombre_usuario; } /** * @param nombre_usuario the nombre_usuario to set */ public void setNombre_usuario(String nombre_usuario) { this.nombre_usuario = nombre_usuario; } public void Log(String Usr, String Mensaje, String tipo) throws IOException { //try{ String nbFile; BufferedWriter bfw; FileReader fr = null; Object file = new Object();//verificar este tipo de variable para encontrar el correcto String nbFold; Calendar Calendario = Calendar.getInstance(); //Fecha del Sistema******************************************************** String ano = Integer.toString(Calendario.get(Calendar.YEAR)); String mes = Integer.toString(Calendario.get(Calendar.MONTH) + 1); String dia = Integer.toString(Calendario.get(Calendar.DATE)); String sistema = dia + "/" + mes + "/" + ano; //************************************************************************* File fichero1 = null; FileWriter fichero = null; PrintWriter pw = null; if (mes.length() == 1) { mes = "0" + mes; } if (dia.length() == 1) { dia = "0" + dia; } String directorio = System.getProperty("user.dir"); String separador = System.getProperty("file.separator"); nbFold = directorio + separador + "log" + separador + ano + mes + dia; nbFile = nbFold + separador + Usr + ".xml";//verificar el doble / que antes era solo 1 File fichero2 = new File(nbFold); if (!fichero2.exists()) { fichero2.mkdirs(); } FileWriter fichero3 = new FileWriter(nbFile, true); pw = new PrintWriter(fichero3); String linea = "<LOG TP='" + tipo + "'><![CDATA[" + sistema + " -> " + Mensaje + "]]></LOG>"; pw.append(linea); pw.flush(); pw.close(); fichero3.close(); } // public void verificar_estado_conexion() { // // // Icon icono = new ImageIcon(ClassLoader.getSystemResource("imagenesavatar/noconexion2.png")); // // if (JOptionPane.showConfirmDialog(null, "Error al Conectarse a la Base de Datos ¿Desea intentar conectarse nuevamente\n (Si el problema persiste, Favor comuníquese con su Administrador)", // "Error de Conexión", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, icono) == JOptionPane.YES_OPTION) { // // if (this.Conectar()) { // JOptionPane.showMessageDialog(null, "Conexión a Base de Datos exitosa", "Conexión Restablecida", JOptionPane.INFORMATION_MESSAGE, icono); // } // } // // //JOptionPane.showMessageDialog(null, "No hay comunicación con la Base de Datos", "Error de Conexión", JOptionPane.ERROR_MESSAGE, icono); // //this.cerrar_aplicacion(); // // this.Desconectar(); // // ImportadoraXian ia=new ImportadoraXian(); // //System.exit(0); // } /** * @return the cvt */ }
package com.example.atos.myapplication.controller; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.widget.ImageView; import com.example.atos.myapplication.R; /** * Created by Atos on 06/09/17. */ public class RoundedImageViewActivity extends Activity { private ImageView imageViewRound; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rounded_imageview); imageViewRound=(ImageView)findViewById(R.id.imageView_round); Bitmap icon = BitmapFactory.decodeResource(getResources(),R.drawable.newark_prudential_sunny); imageViewRound.setImageBitmap(icon); } }
package com.zhcw.analysisdata.utils; import android.util.Base64; /** * Created by YangChun . * on 2017/3/11. */ public class Base64Util { public static byte[] encode(byte[] s) { if (s == null) return null; return Base64.encode(s, Base64.DEFAULT); } public static byte[] decode(String s) { if (s == null) return null; try { return Base64.decode(s, Base64.DEFAULT); } catch (Exception e) { return null; } } }
package com.beiyelin.account.bean; import lombok.Data; /** * @Author: xinsh * @Description: 前端绑定具体账户到第三方账户的token上 * @Date: Created in 8:38 2018/8/19. */ @Data public class OAuthRegister { private String code;//第一次第三方平台返回的code private String username; private String email; private String phone; private String password; }
package dao; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import entity.*; public class Dao { private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("DevPU"); // CREATE DEVICE public void saveTransactions(Transactions transactions) { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.persist(transactions); em.getTransaction().commit(); em.close(); } public void saveAccount(Account account) { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.persist(account); em.getTransaction().commit(); em.close(); } public void saveCategory(Category category) { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.persist(category); em.getTransaction().commit(); em.close(); } }
package enthu_l; public class e_1000 { static String s = ""; public static void m0(int a, int b) { s += a; m2(); m1(b); } public static void m1(int i) { s += i; } public static void m2() { throw new NullPointerException("aa"); } public static void m() { m0(1, 2); m1(3); } public static void main(String args[]) { try { m(); } catch (Exception e) { } System.out.println(s); } }
package org.springframework.sync; import lombok.RequiredArgsConstructor; import org.springframework.shadowstore.ShadowStore; import org.springframework.shadowstore.ShadowStoreFactory; import org.springframework.sync.diffsync.DiffSync; import org.springframework.sync.diffsync.Equivalency; import org.springframework.sync.diffsync.PersistenceCallback; import org.springframework.sync.diffsync.PersistenceCallbackRegistry; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; @RequiredArgsConstructor public class DiffSyncService implements IDiffSyncService { private final ShadowStoreFactory shadowStoreFactory; private final Equivalency equivalency; private final PersistenceCallbackRegistry callbackRegistry; @Override public Patch patch(final String resource, final String resourceId, final String shadowStoreId, final Patch patch) { PersistenceCallback<? extends Serializable> persistenceCallback = callbackRegistry.findPersistenceCallback( resource); Object findOne = persistenceCallback.findOne(resourceId); return applyAndDiff(patch, findOne, persistenceCallback, shadowStoreId); } @SuppressWarnings("unchecked") private <T extends Serializable> Patch applyAndDiff(Patch patch, Object target, PersistenceCallback<T> persistenceCallback, final String shadowStoreId) { final ShadowStore shadowStore = getShadowStore(shadowStoreId); DiffSync<T> sync = new DiffSync<>(shadowStore, persistenceCallback.getEntityType()); T patched = sync.apply((T) target, patch); persistenceCallback.persistChange(patched); return sync.diff(patched); } private <T extends Serializable> Patch applyAndDiffAgainstList(Patch patch, List<T> target, PersistenceCallback<T> persistenceCallback, final String shadowStoreId) { final ShadowStore shadowStore = getShadowStore(shadowStoreId); DiffSync<T> sync = new DiffSync<>(shadowStore, persistenceCallback.getEntityType()); List<T> patched = sync.apply(target, patch); List<T> itemsToSave = new ArrayList<>(patched); itemsToSave.removeAll(target); // Determine which items should be deleted. // Make a shallow copy of the target, remove items that are equivalent to items in the working copy. // Equivalent is not the same as equals. It means "this is the same resource, even if it has changed". // It usually means "are the id properties equals". List<T> itemsToDelete = new ArrayList<>(target); for (T candidate : target) { for (T item : patched) { if (equivalency.isEquivalent(candidate, item)) { itemsToDelete.remove(candidate); break; } } } persistenceCallback.persistChanges(itemsToSave, itemsToDelete); return sync.diff(patched); } private ShadowStore getShadowStore(final String shadowStoreId) { final ShadowStore shadowStore; try { shadowStore = shadowStoreFactory.getShadowStore(shadowStoreId); } catch (InvocationTargetException | IllegalAccessException | InstantiationException | NoSuchMethodException e) { throw new PatchException("Could not instantiate a shadow store!"); } return shadowStore; } @Override public Patch patch(final String resource, final Patch patch, final String shadowStoreId) { PersistenceCallback<? extends Serializable> persistenceCallback = callbackRegistry.findPersistenceCallback( resource); return applyAndDiffAgainstList(patch, (List) persistenceCallback.findAll(), persistenceCallback, shadowStoreId); } }
package com.StringAssignment_10_Sep_2021; public class Split { public static void main(String args[]) { String string = "My,name,is,Dheeru"; String[] arrayOfString = string.split(","); for (String array : arrayOfString) System.out.println(array); } }
package com.uwetrottmann.trakt5.entities; public abstract class GenericProgress { public SyncEpisode episode; public SyncShow show; public SyncMovie movie; public Double progress; }
package com.example.ComicToon.Models.ModelRepositories; import java.util.List; import com.example.ComicToon.Models.ComicModel; import org.springframework.data.mongodb.repository.MongoRepository; import java.util.ArrayList; public interface ComicRepository extends MongoRepository<ComicModel, String>{ public ComicModel findByid(String ID); public void deleteById(String id); public ArrayList<ComicModel> findByUserID(String userID); public ArrayList<ComicModel> findByname(String name); public List<ComicModel> findAll(); }
/* * Copyright © 2019 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.dom.builder.shared; import org.gwtproject.safehtml.shared.SafeUri; import org.gwtproject.safehtml.shared.annotations.IsSafeUri; /** Builds an form element. */ public interface FormBuilder extends ElementBuilderBase<FormBuilder> { /** * List of character sets supported by the server. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#adef-accept-charset">W3C * HTML Specification</a> */ FormBuilder acceptCharset(String acceptCharset); /** * Server-side form handler. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#adef-action">W3C * HTML Specification</a> */ FormBuilder action(SafeUri action); /** * Server-side form handler. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#adef-action">W3C * HTML Specification</a> */ FormBuilder action(@IsSafeUri String action); /** * The content type of the submitted form, generally "application/x-www-form-urlencoded". * * <p>Note: The onsubmit even handler is not guaranteed to be triggered when invoking this method. * The behavior is inconsistent for historical reasons and authors should not rely on a particular * one. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#adef-enctype">W3C * HTML Specification</a> */ FormBuilder enctype(String enctype); /** * HTTP method [IETF RFC 2616] used to submit form. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#adef-method">W3C * HTML Specification</a> */ FormBuilder method(String method); /** Names the form. */ FormBuilder name(String name); /** * Frame to render the resource in. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/present/frames.html#adef-target">W3C * HTML Specification</a> */ FormBuilder target(String target); }
public class Number21 { public static void main(String[]args){ Long startTime = System.nanoTime(); int sum = 0; int n = 160000; for(int i = 1; i <- n; i++) for(int j = 1; j <= i * i; j++) if(j % i == 0) for(int k = 0; k < j; k++) sum++; Long runTime = System.nanoTime() - startTime; System.out.println(runTime); } }
package abstractfactory.design.pattern.edureka.assignment; public class IgnorableError extends Error { @Override void setErrorType(String errType) { errorType = errType; } }
package Chapter3; //문자형 변수 ch가 영문자(대문자 OR 소문자)이거나 숫자일때만 변수 b의 값이 true가 되도록 하는 코드 public class Exercise3_9 { public static void main(String args[]) { char ch = 'z'; boolean b = ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9'); System.out.println(b); } }