text
stringlengths
10
2.72M
package main; import main.zad2.TestSuite2_ExceptionTest; import main.zad3.TestSuite3; import main.zad4.TestSuite4; import main.zad5.TestSuite5; import org.junit.runner.RunWith; import main.zad1.TestSuit1; import main.zad2.TestSuite2; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ TestSuit1.class, TestSuite2.class, TestSuite2_ExceptionTest.class, TestSuite3.class, TestSuite4.class, TestSuite5.class }) public class TestSuite { }
package com.github.ezauton.core.pathplanning.purepursuit; import com.github.ezauton.core.pathplanning.PP_PathGenerator; import com.github.ezauton.core.trajectory.geometry.ImmutableVector; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Waypoint used in Pure Pursuit which includes translational location, speed, accel, decel... */ public class PPWaypoint implements Serializable { private final ImmutableVector location; private final double speed; private final double acceleration; private final double deceleration; /** * Create a waypoint for Pure Pursuit to drive to * * @param location Where the waypoint is, given that the Y axis is the forward axis * @param speed Approximately how fast the robot should be going by the time it reaches this waypoint * @param acceleration Maximum acceleration allowed to reach the target speed * @param deceleration Maximum deceleration allowed to reach the target speed */ //TODO: Confirm documentation is accurate public PPWaypoint(ImmutableVector location, double speed, double acceleration, double deceleration) { this.location = location; this.speed = speed; this.acceleration = acceleration; this.deceleration = deceleration; } /** * A shortcut to making a 2D waypoint * * @param x X-coordinate for the location of this waypoint * @param y Y-coordinate for the location of this waypoint * @param speed Approximately how fast the robot should be going by the time it reaches this waypoint * @param acceleration Maximum acceleration allowed to reach the target speed * @param deceleration Maximum deceleration allowed to reach the target speed * @return A waypoint with the specified properties */ public static PPWaypoint simple2D(double x, double y, double speed, double acceleration, double deceleration) { if (deceleration > 0) throw new IllegalArgumentException("Deceleration cannot be positive!"); return new PPWaypoint(new ImmutableVector(x, y), speed, acceleration, deceleration); } /** * A shortcut to making a 3D waypoint (Deep Space will have drones so we need 3D PP) ... ofc you never * know when we will need 4D either!! * <p> * ⠀⠰⡿⠿⠛⠛⠻⠿⣷ * ⠀⠀⠀⠀⠀⠀⣀⣄⡀⠀⠀⠀⠀⢀⣀⣀⣤⣄⣀⡀ * ⠀⠀⠀⠀⠀⢸⣿⣿⣷⠀⠀⠀⠀⠛⠛⣿⣿⣿⡛⠿⠷ * ⠀⠀⠀⠀⠀⠘⠿⠿⠋⠀⠀⠀⠀⠀⠀⣿⣿⣿⠇ * ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠁ * <p> * ⠀⠀⠀⠀⣿⣷⣄⠀⢶⣶⣷⣶⣶⣤⣀ * ⠀⠀⠀⠀⣿⣿⣿⠀⠀⠀⠀⠀⠈⠙⠻⠗ * ⠀⠀⠀⣰⣿⣿⣿⠀⠀⠀⠀⢀⣀⣠⣤⣴⣶⡄ * ⠀⣠⣾⣿⣿⣿⣥⣶⣶⣿⣿⣿⣿⣿⠿⠿⠛⠃ * ⢰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡄ * ⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡁ * ⠈⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠁ * ⠀⠀⠛⢿⣿⣿⣿⣿⣿⣿⡿⠟ * ⠀⠀⠀⠀⠀⠉⠉⠉ * * @param x X-coordinate for the location of this waypoint * @param y Y-coordinate for the location of this waypoint * @param z Z-coordinate for the location of this waypoint * @param speed Approximately how fast the robot should be going by the time it reaches this waypoint * @param acceleration Maximum acceleration allowed to reach the target speed * @param deceleration Maximum deceleration allowed to reach the target speed * @return A waypoint with the specified properties */ public static PPWaypoint simple3D(double x, double y, double z, double speed, double acceleration, double deceleration) { return new PPWaypoint(new ImmutableVector(x, y, z), speed, acceleration, deceleration); } public ImmutableVector getLocation() { return location; } public double getSpeed() { return speed; } public double getAcceleration() { return acceleration; } public double getDeceleration() { return deceleration; } @Override public String toString() { return "PPWaypoint{" + "location=" + location + ", speed=" + speed + ", acceleration=" + acceleration + ", deceleration=" + deceleration + '}'; } public static class Builder { private List<PPWaypoint> waypointList = new ArrayList<>(); public Builder add(double x, double y, double speed, double acceleration, double deceleration) { PPWaypoint waypoint = PPWaypoint.simple2D(x, y, speed, acceleration, deceleration); waypointList.add(waypoint); return this; } public PPWaypoint[] buildArray() { return waypointList.toArray(new PPWaypoint[0]); } public PP_PathGenerator buildPathGenerator() { return new PP_PathGenerator(buildArray()); } public Builder flipY() { Builder ret = new Builder(); for (PPWaypoint wp : waypointList) { ret.add(-wp.getLocation().get(0), wp.getLocation().get(1), wp.getSpeed(), wp.getAcceleration(), wp.getDeceleration()); } return ret; } } }
package com.rcwang.seal.fetch; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.OutputStream; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.input.ReaderInputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.InputStreamBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import com.rcwang.seal.expand.Entity; import com.rcwang.seal.expand.EntityList; import com.rcwang.seal.util.GlobalVar; import com.rcwang.seal.util.Helper; public class ClueWebSearcher extends WebSearcher { private static final Logger log = Logger.getLogger(ClueWebSearcher.class); private static final Pattern TITLE_PATTERN=Pattern.compile("<TITLE>(.+)</TITLE>", Pattern.CASE_INSENSITIVE); private static final String WIKIPEDIA_BASEURL="http://boston.lti.cs.cmu.edu/NELL/search/clueweb09_wikipedia/"; public static final String BATCH_CATB_BASEURL="http://boston.lti.cs.cmu.edu/NELL/batchquery/upload.cgi"; public static final String CATB_CACHE_BASEURL="http://boston.lti.cs.cmu.edu:8085/clueweb09/render/renderpage.cgi?id=%s"; public static final String FORMAT_INDRI="0"; public static final String FORMAT_TREC_EVAL="1"; private static ClueWebSearcher lastRun=null; /** Get a ClueWebSearcher object, returning a persisted one if it exists. * This is necessary because SEAL refreshes its WebSearcher object for each * query, but a single ClueWebSearcher object collects results for multiple * queries at a time. * @return a new ClueWebSearcher object, or if we are in multiquery mode and * a persisted ClueWebSearcher object exists, the old object. */ public static ClueWebSearcher getSearcher() { if (gv.isMultiquery()) { if (lastRun == null) lastRun = new ClueWebSearcher(); return lastRun; } return new ClueWebSearcher(); } /** Get the persisted ClueWebSearcher object. * @return the old ClueWebSearcher object, or null if in single-query mode. */ public static ClueWebSearcher getLastRun() { return lastRun; } private boolean memoryManagement=false; private long lastTimeMemoryWasOk=0; /** Enable memory management (default false) (turn on for memory-impoverished machines or large batches) **/ public void setMemoryManagement(boolean s) { memoryManagement = s; } private File tmpDir; /** Set directory where the raw uploaded batch request file and raw * downloaded batch response files should be stored. Directory is * created if it doesn't already exist. * @param d */ public void setTmpDir(File d) { this.tmpDir=d; if (!d.exists()) d.mkdir(); } private boolean keepResponseFile=false; /** Keep raw batch response file (default: delete once file is parsed into the SEAL cache) **/ public void setKeepResponseFile(boolean k) { keepResponseFile = k; } private boolean keepQuery=false; /** Keep raw batch request file (default: delete once response is parsed into the SEAL cache) **/ public void setKeepQuery(boolean k) { keepQuery = k; } private List<DocumentSet> documents; private List<Set<Snippet>> snippetsByQuery; private String format=FORMAT_TREC_EVAL; private boolean fulltext=true; /** Request fulltext (default:on) **/ public void setFulltext(boolean f) { fulltext = f; } /** Get whether fulltext is being requested **/ public boolean getFulltext() { return fulltext; } private boolean encodeQueries; private boolean diskMode; /** Set whether to store fulltext document sets on disk or in memory (default:none). * If memory management has been turned on, the system monitors memory usage and * automatically turns on disk mode once space becomes tight. **/ public void setDiskMode(boolean s) { diskMode = s; } /** Default constructor (encodeQueries on) **/ public ClueWebSearcher() { this(true); } /** Create a new ClueWebSearcher and set whether queries should be encoded or not * * @param encodeQueries - true to use seed-style queries (single-query * mode), false for batch-style queries (multi-query mode). Seed-style * queries are provided for command-line calls and for backwards * compatibility for other SEAL searchers, for which "addQuery(s:String)" * adds a seed, and the list of queries is the list of seeds; thus the * encoded queries form the single search string sent to the search engine. * For ClueWebSearcher in multi-query/batch mode, addQuery(s:String) adds * an indri-style query which is already formed of multiple seeds, and the * list of queries is the same as the batch. */ public ClueWebSearcher(boolean encodeQueries) { documents = new ArrayList<DocumentSet>();//new DocumentSet(); snippetsByQuery = new ArrayList<Set<Snippet>>(); this.encodeQueries = encodeQueries; GlobalVar gv = GlobalVar.getGlobalVar(); this.setKeepQuery(gv.getClueWebKeepQueryFile()); this.setKeepResponseFile(gv.getClueWebKeepResponseFile()); this.setMemoryManagement(gv.getClueWebMemoryManagement()); String tdirname = gv.getProperties().getProperty(GlobalVar.CLUEWEB_TMP_DIR); if (tdirname != null) this.setTmpDir(new File(tdirname)); } @Override /** * Sends queries to search service. * * 1. Build query set * 2. Send batch query and retrieve response * 3. Build snippets from the response */ public void run() { lastRun = this; System.gc(); String className = this.getClass().getSimpleName(); Collection<String> querySet = new TreeSet<String>(); if (this.encodeQueries) querySet.add(this.getEncodedQuery()); else querySet = this.getQueries(); log.info("Querying " + className + " for " + Helper.toReadableString(querySet) + "..."); snippets.clear(); snippetsByQuery.clear(); //snippetsByQuery.add(snippets); for (int i=0;i<querySet.size();i++) this.snippetsByQuery.add(new HashSet<Snippet>()); File result = sendBatchQuery(querySet); if (result != null) buildSnippets(result); else log.error("Problem while sending query; no results recorded."); // assign index of query string to each snippet // for (Snippet snippet : snippets) // snippet.setIndex(this.getIndex()); // true to annotate query string in snippets if (isAnnotateQuery()) annotateQuery(); log.info(className + " retrieved a total of " + snippets.size() + " URLs and documents for " + Helper.toReadableString(this.getQueries()) + "!"); } /** Formulate the set of queries as a batch request, send it, and retrieve the * response from the server as a file. * @param querySet - a set of Indri-formatted queries * @return */ public File sendBatchQuery(Collection<String> querySet) { StringBuilder sb = new StringBuilder(); sb.append("<parameters>"); if (fulltext) sb.append("<printDocuments>true</printDocuments>"); int i=0; for (String q : querySet) { sb.append("<query>\n"); sb.append("<number>").append(i++).append("</number>\n"); sb.append("<text>").append(q).append("</text>\n"); sb.append("</query>\n"); if (!diskMode) documents.add(new DocumentSet()); } sb.append("</parameters>"); if (log.isDebugEnabled()) log.debug("Query parameters file:\n"+sb.toString()); if (keepQuery) { try { BufferedWriter ow = new BufferedWriter(new FileWriter(File.createTempFile("clueweb-query_", ".txt",this.tmpDir))); ow.write(sb.toString()); ow.close(); } catch (FileNotFoundException e) { log.error("Problem saving query file:",e); } catch (IOException e) { log.error("Problem saving query file:",e); } } HttpClient httpclient = new DefaultHttpClient(); try { int numTrials = Integer.parseInt(gv.getProperties().getProperty(GlobalVar.CLUEWEB_TIMEOUT_NUMTRIALS,"2")); String headerTimeout =gv.getProperties().getProperty(GlobalVar.CLUEWEB_HEADER_TIMEOUT_MS,"-1"); int timeoutms = Integer.parseInt(headerTimeout); long reportingPeriod = Long.parseLong(gv.getProperties().getProperty(GlobalVar.CLUEWEB_TIMEOUT_REPORTING_MS,"1000")); HttpEntity resentity=null; File result=null; boolean timedOut = true; trials: // multiple trials only relevant when timeoutms is set >0 for (int trial = 0; trial < numTrials; trial++) { if (trial > 0) { if (timeoutms < Integer.MAX_VALUE/2) timeoutms *= 2; EntityUtils.consume(resentity); } HttpPost post = makePost(sb.toString()); HttpResponse response = httpclient.execute(post); resentity = response.getEntity(); StatusLine sline = response.getStatusLine(); if (log.isDebugEnabled()) { for (Header h : response.getAllHeaders()) { log.debug(h.getName()+": "+h.getValue()); } } if (sline.getStatusCode() != 200) { log.error("Bad status code "+sline.getStatusCode()+": "+sline.getReasonPhrase()); return null; } if (resentity == null) { log.error("Null result entity?"); return null; } result = File.createTempFile("clueweb-resp_", ".txt", this.tmpDir); FileOutputStream os = new FileOutputStream(result); long starttime=System.currentTimeMillis(); if (timeoutms < 0) { log.info("Saving file directly..."); resentity.writeTo(os); log.info((System.currentTimeMillis() - starttime)+" ms"); timedOut=false; } else { log.info("[trial "+(trial+1)+" of "+numTrials+"] "+timeoutms/1000+" seconds to read header."); ResponseReaderThread r = new ResponseReaderThread(resentity.getContent(), os); Thread readerthread = new Thread(r,result.getName()); readerthread.start(); long then = starttime; while(!r.hasTimedOut) { try { if(r.hasFinishedHeader) { log.info("Header complete at "+(System.currentTimeMillis() - starttime)+"ms. Saving results..."); readerthread.join(); timedOut = false; break trials; // outer loop } long now = System.currentTimeMillis(); long timeElapsed = now - starttime; long timeLeft = timeoutms - timeElapsed; if (timeLeft > 0) { if (now - then > reportingPeriod || timeLeft < 6000) { double byterate = (double) 1000 * r.bytes / (now-starttime); log.info(timeLeft/1000+" seconds remaining; "+byterate+" bytes/s"); then += reportingPeriod; } Thread.sleep(Math.min(timeLeft,1000)); } else { // then we've timed out log.warn("Timed out reading header! Waiting to finish..."); r.hasTimedOut = true; readerthread.join(); } } catch (InterruptedException e) { log.error(e); } } // timer poll loop } // timeout case log.info("File complete at "+(System.currentTimeMillis() - starttime)+" ms"); } // trials loop // not sure whether these are strictly necessary but we'll go with it EntityUtils.consume(resentity); if (timedOut) return null; return result; } catch (UnsupportedEncodingException e) { log.error(e); } catch (ClientProtocolException e) { log.error(e); } catch (IOException e) { log.error(e); } finally { httpclient.getConnectionManager().shutdown(); } return null; } /** Utility method: * Formulate an HTTP POST request to upload the batch query file * @param queryBody * @return * @throws UnsupportedEncodingException */ private HttpPost makePost(String queryBody) throws UnsupportedEncodingException { HttpPost post = new HttpPost(ClueWebSearcher.BATCH_CATB_BASEURL); InputStreamBody qparams = new InputStreamBody( new ReaderInputStream(new StringReader(queryBody)), "text/plain", "query.txt"); MultipartEntity entity = new MultipartEntity(); entity.addPart("viewstatus", new StringBody("1")); entity.addPart("indextype", new StringBody("catbparams")); entity.addPart("countmax", new StringBody("100")); entity.addPart("formattype", new StringBody(format)); entity.addPart("infile", qparams); post.setEntity(entity); return post; } /** * Detect Indri or trec_eval formatted results line, which delimits WARC records in full-text responses. * @param line * @return */ private boolean isResultsLine(String line) { String[] header; if (format == FORMAT_INDRI) return (line.length() > 23) && ((header = line.split("\t")).length == 4) && header[1].startsWith("clueweb"); // then we have something like // -2.18963 clueweb09-en0009-21-22503 0 2558 // and we're done with this document else if (format == FORMAT_TREC_EVAL) return (line.length() > 25) && ((header = line.split(" ")).length == 6) && header[2].startsWith("clueweb"); log.error("Invalid format setting '"+format+"' for indri-clueweb response"); return false; } /** Consumes, records, and caches a single document from the WARC file returned by the batch service **/ protected void parseWARC(BufferedReader reader, Snippet snippet, int queryNumber) throws IOException { if (snippet == null) { log.warn("No snippet provided"); return; } // consume WARC headers String line = ""; URL url = null; int doclen = 0; while (!line.startsWith("HTTP")) { line = reader.readLine(); if (line == null) { log.warn("Unexpected end of results file while reading WARC headers for document "+snippet.getTitle().getText()); return; } if (line.startsWith("WARC-Target-URI")) { url = new URL(line.substring(line.indexOf(":")+2)); snippet.setPageURL(url.toString()); } } // now 'line' contains the first line of the HTTP header for this document // consume the HTTP headers while(!line.startsWith("Content-Length")) { line = reader.readLine(); if (line == null) { log.warn("Unexpected end of results file while reading HTTP headers for document "+snippet.getTitle().getText()); return; } } // now 'line' contains the (incorrect) content length doclen = Integer.parseInt(line.substring(line.indexOf(':')+2)); reader.readLine(); // toss the newline // read the file StringBuilder sb = new StringBuilder(); while ( (line = reader.readLine()) != null) { //gross: no delimiters, must detect header of next file if ( isResultsLine(line) ) { reader.reset(); break; } reader.mark(128); sb.append(line).append("\n"); } if (doclen - sb.length() > 5) log.debug("Content-length "+doclen+" for document length "+sb.length()+"; header off by "+(doclen - sb.length())); Document document = new Document(sb.toString(), url); Matcher m = TITLE_PATTERN.matcher(document.getText()); if (m.find()) { snippet.setTitle(m.group(1)); // snippet.setTitle(String.copyValueOf(m.group(1).toCharArray())); } document.setSnippet(snippet); if (!diskMode) { DocumentSet d = null; if (documents.size()>queryNumber) d = documents.get(queryNumber); else { log.warn("query number "+queryNumber+" out of known range; adding a new one"); d = new DocumentSet(); while (queryNumber > documents.size()) documents.add(new DocumentSet()); documents.add(queryNumber,d); } log.debug("Added document to documentset "+d+" @query "+queryNumber); d.add(document); } //log.debug("Added document to query "+queryNumber); WebManager.writeToCache(url, document.getText(), getCacheDir()); if (memoryManagement) { Runtime runtime = Runtime.getRuntime(); if (runtime.freeMemory() > 1e7) lastTimeMemoryWasOk = System.currentTimeMillis(); long dt =System.currentTimeMillis() - lastTimeMemoryWasOk; log.debug("Last good: "+dt+ (diskMode ? " (disk)" : "")); if (!diskMode & (dt > 1000)) { log.info("Memory getting tight. Caching documentsets on disk instead..."); cacheOut(); diskMode=true; } } } private void cacheOut() { this.documents.clear(); } /** Parses the batch response file from the search service into a set of * snippet collections for each query in the batch. * @param resultsFile Batch query response */ protected void buildSnippets(File resultsFile) { LineNumberReader reader = null; int queryNumber=-1,docnumber=-1; try { reader = new LineNumberReader(new FileReader(resultsFile)); for (int i=0;i<4;i++) { String line = reader.readLine(); log.debug(line); if (line.startsWith("Approximately")) i--; } for (String line; (line = reader.readLine()) != null;) { String docid = ""; if (format == FORMAT_INDRI) { String[] parts = line.split("\t"); if (parts.length != 4) { log.debug("Missed a boundary. Skipping this line..."); continue; } docid = parts[1]; } else if (format == FORMAT_TREC_EVAL) { String parts[] = line.split(" "); if (parts.length != 6) { log.debug("Missed a boundary. Skipping this line..."); continue; } docid = parts[2]; int newQueryNumber = Integer.parseInt(parts[0]); if (newQueryNumber - queryNumber > 1) { if (log.isInfoEnabled()) { for (int i=queryNumber+1; i<newQueryNumber; i++) { log.info("Likely malformed query: "+ (i < this.getQueries().size() ? this.getQuery(i) : i)); } } } queryNumber = newQueryNumber; docnumber = Integer.parseInt(parts[3]); } Snippet snippet = new Snippet(); snippet.setCacheURL(String.format(CATB_CACHE_BASEURL,docid)); snippet.setTitle(docid); if (fulltext) { log.debug("Parsing document "+docid+"; #"+docnumber+" for query "+queryNumber); parseWARC(reader,snippet,queryNumber); } else { snippet.setPageURL(String.format(CATB_CACHE_BASEURL,docid)); } if (snippet.getTitle().getText() == docid) snippet.setTitle("(unknown; fetch from local cache)"); snippet.setRank(docnumber); snippet.setIndex(queryNumber); snippets.add(snippet); Set<Snippet> qsnippets=null; if (queryNumber < snippetsByQuery.size()) qsnippets = snippetsByQuery.get(queryNumber); else { log.debug("Snippet groups not initialized? Adding query group for query "+queryNumber); while (snippetsByQuery.size() < queryNumber) snippetsByQuery.add(new HashSet<Snippet>()); qsnippets = new HashSet<Snippet>(); snippetsByQuery.add(queryNumber,qsnippets); } qsnippets.add(snippet); } } catch (IOException e) { log.error(e); } if (log.isDebugEnabled()) { StringBuilder sb = new StringBuilder("Added snippets:"); for (int i=0;i<snippetsByQuery.size();i++) { sb.append("\n\t(").append(i).append(", ").append(snippetsByQuery.get(i).size()).append(")"); } sb.append("\nTotal: ").append(snippets.size()); log.debug(sb.toString()); } if (!keepResponseFile) resultsFile.delete(); } public String getQuery(int queryNumber) { return this.getQueries().get(queryNumber); } /** Get all the documents returned by this request, regardless of query **/ public DocumentSet getDocuments() { if (this.snippetsByQuery.size() > 1) log.warn("WARNING: Returning documents from "+this.snippetsByQuery.size()+" different queries as if they were a single query."); return loadFromDisk(snippets); } /** Get the documents returned by a particular query inside the batch **/ public DocumentSet getDocuments(int queryNumber) { if (diskMode) return loadFromDisk(queryNumber); return documents.get(queryNumber); } /** (Disk mode) Retrieve from disk the set of documents returned by a particular query **/ private DocumentSet loadFromDisk(int queryNumber) { return loadFromDisk(this.snippetsByQuery.get(queryNumber)); } /** (Disk mode) Retrieve from disk an arbitrary set of documents represented by a set of snippets **/ private DocumentSet loadFromDisk(Set<Snippet> snippets) { DocumentSet result = new DocumentSet(); for (Snippet s: snippets) { Document d = new Document(WebManager.readFromCache(s.getPageURL(), getCacheDir()),s.getPageURL()); d.setSnippet(s); result.add(d); } return result; } /** Set the format of the batch results; use FORMAT_INDRI or FORMAT_TREC_EVAL. **/ public void setFormat(String format) { this.format = format; } public void setEncodeQueries(boolean eq) { this.encodeQueries = eq; } @Override public String getEncodedQuery() { StringBuilder sb = new StringBuilder(); for (String q : this.getQueries()) { if (sb.length()>0) sb.append(" "); sb.append(q); } return sb.toString(); } protected static String sanitize(String keyword) { return keyword.replaceAll("['.!()]", "").replaceAll("[/,&+:]", " ").trim(); } @Override /** ClueWeb query keywords are never enclosed in quotes. **/ public void addQuery(String query, boolean addQuote) { if (query == null) return; super.addQuery(String.format(" #1(%s)",sanitize(query)),false); } /** Add a batch-style query (made of a list of seed strings) **/ public void addQuery(String ... query) { if (query.length == 0) addQuery("",false); StringBuilder sb = new StringBuilder(); for (String q : query) { sb.append(String.format(" #1(%s)",sanitize(q))); } super.addQuery(sb.substring(1),false); } public void addQuery(EntityList query) { if (query.size() == 0) addQuery("",false); StringBuilder sb = new StringBuilder(); for (Entity e : query) { for (String q : e.getNames()) { sb.append(String.format(" #1(%s)",sanitize(q))); } } super.addQuery(sb.substring(1),false); } @Override /** * Not in use -- ClueWeb should be used with fetchFromWeb=false to prevent the webfetcher * from using URL-based fetching & search. */ protected String getSearchURL(int numResultsForThisPage, int pageNum, String query) { StringBuilder url = new StringBuilder(WIKIPEDIA_BASEURL); url.append("lemur.cgi?d=0"); url.append("&s=").append(pageNum*numResultsForThisPage); url.append("&n=").append(numResultsForThisPage); url.append("&q=").append(query); return url.toString(); } @Override protected void buildSnippets(String resultPage) { throw new UnsupportedOperationException("ClueWebSearcher does not use the method signature buildSnippets(String):void; something has gone horribly wrong"); } /** * Utility class to monitor response retrieval, so that we can * retry the request if the response hangs for too long. * @author krivard * */ class ResponseReaderThread implements Runnable { InputStream fromServer; OutputStream toFile; boolean hasTimedOut = false; boolean hasFinishedHeader = false; int bytes=0; public ResponseReaderThread(InputStream in, OutputStream out) { fromServer = in; toFile = out; } @Override public void run() { try { for (int ch; (ch=fromServer.read()) != -1; bytes++) { if ((char)ch == '!') hasFinishedHeader = true; if (!hasFinishedHeader && hasTimedOut) { fromServer.close(); toFile.close(); log.debug("Timed out! I/O streams closed."); return; } toFile.write(ch); } log.debug("Finished writing file"); } catch (IOException e) { log.error("Couldn't reach clueweb-resp file."); } } } }
package org.github.chajian.matchgame.board; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Score; import org.github.chajian.matchgame.MatchGame; import org.github.chajian.matchgame.data.MatchVariable; import org.github.chajian.matchgame.data.config.Configurator; import org.github.chajian.matchgame.data.define.PoolStatus; import sun.security.krb5.Config; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; /** * 大厅计分板 * - 当玩家进行匹配时显示 * - 显示玩家的段位,胜率,杀敌,死亡等 * - 显示当前匹配状态,匹配人数等 * * @author Chajian */ public class LobbyScoreBoard extends BaseScore{ @Override void init() { } /** * 向玩家展示score信息 * @param player 玩家对象 * @param title score标题 * @param lore score消息主题 */ @Override public void show(Player player,String title,List<String> lore) { scoreboard = MatchGame.getMatchGame().getServer().getScoreboardManager().getNewScoreboard(); Objective objective = scoreboard.registerNewObjective("obj","obj",title); for(int i = 0 ; i < lore.size() ; i++){ String oldS = lore.get(i); String newS = MatchVariable.getMatchVariable("bedwar").replace(oldS,player.getName(),"bedwar"); Score score = null; if (newS != null) score = objective.getScore(newS); else score = objective.getScore(oldS); score.setScore(i); } objective.setDisplaySlot(DisplaySlot.SIDEBAR); player.setScoreboard(scoreboard); } @Override public void showByStatus(Player player, PoolStatus poolStatus, Map<String,Object> board) { String title = ""; List<String> lore = new ArrayList<>(); Map<String,Object> body = (Map<String, Object>) board.get(poolStatus.name()); switch (poolStatus){ case WAITING: title = (String) body.get("title"); lore = (List<String>) body.get("lore"); show(player,title,lore); break; case BEFORE_START: break; case START: break; case ENDING: break; } } @Override public void hide(Player player) { player.getScoreboard().clearSlot(DisplaySlot.SIDEBAR); } @Override public void update() { } }
package com.rahul.splitwise.service; import com.rahul.splitwise.exception.GroupNotFound; import com.rahul.splitwise.exception.UserNotFound; import com.rahul.splitwise.model.GroupUserMapping; import com.rahul.splitwise.repository.GroupDao; import com.rahul.splitwise.repository.GroupUserMappingDao; import com.rahul.splitwise.repository.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * The type Group user mapping service. */ @Service public class GroupUserMappingServiceImpl implements IGroupUserMappingService { /** * The Group user mapping dao. */ @Autowired GroupUserMappingDao groupUserMappingDao; /** * The User dao. */ @Autowired UserDao userDao; /** * The Group dao. */ @Autowired GroupDao groupDao; @Override public GroupUserMapping addGroupUserMapping(GroupUserMapping groupUserMapping) throws UserNotFound, GroupNotFound { int userId1 = groupUserMapping.getUserId(); int groupId = groupUserMapping.getGroupId(); if (!userDao.existsById(userId1)) { throw new UserNotFound("User ID not Found"); } if (!groupDao.existsById(groupId)) { throw new GroupNotFound("Group ID not Found"); } return groupUserMappingDao.save(groupUserMapping); } @Override public GroupUserMapping editGroupUserMapping(GroupUserMapping groupUserMapping) { return groupUserMappingDao.save(groupUserMapping); } @Override public GroupUserMapping deleteGroupUserMapping(GroupUserMapping groupUserMapping) { groupUserMappingDao.delete(groupUserMapping); return groupUserMapping; } @Override public List<GroupUserMapping> getAllGroupUserMapping(int userId) { return groupUserMappingDao.findByUserId(userId); } @Override public List<GroupUserMapping> findByGroupID(int groupId) { return groupUserMappingDao.findByGroupId(groupId); } }
package com.example.demojpush.controller; import com.example.demojpush.config.JPushConfig; import com.example.demojpush.entity.PushBean; import com.example.demojpush.service.MyJPushService; import com.sun.org.apache.bcel.internal.generic.PUSH; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.Map; @Controller public class JPushController { @Autowired private MyJPushService myJPushService; @ResponseBody @GetMapping(value = "/pushAndriod") public boolean pushAndiod(String title, String content){ PushBean pushBean = new PushBean(); pushBean.setTitle(title); pushBean.setAlert(content); boolean res = myJPushService.pushAndriod(pushBean); return res; } @ResponseBody @GetMapping(value = "/pushIos") public void pushIos(String alert, @RequestParam(value = "extras") Map<String, String> extras){ System.out.println("alert = " + alert + " extras = " + extras); PushBean pushBean = new PushBean(); pushBean.setExtras(extras); pushBean.setAlert(alert); boolean res = myJPushService.pushIos(pushBean); System.out.println("推送结果: " + res); } @ResponseBody @GetMapping(value = "/pushIosWithRegIds") public void pushIos(String alert, @RequestParam(value = "extras") Map<String, String> extras, String... regIds){ System.out.println("alert = " + alert + " extras = " + extras + " regIds = " + regIds); PushBean pushBean = new PushBean(); pushBean.setExtras(pushBean.getExtras()); pushBean.setAlert(pushBean.getAlert()); boolean res = myJPushService.pushIos(pushBean, regIds); System.out.println("推送结果: " + res); } @ResponseBody @GetMapping(value = "/customContent") public void customContent(String content){ System.out.println("content = " + content); boolean res = myJPushService.customContentIos(content); System.out.println("推送结果: " + res); } }
package ninja.farhood.exercises.shapes; public class Triangle extends Shape { @Override public double calculateArea() { return 0; } @Override public double calculatePerimeter() { return 0; } }
package algorithms.dynamic_programming.knapsack; public class CountOfSubsetSum { public int countSubsetsMemoization(int[] num, int sum) { return countSubsetsMemoization(num, new Integer[num.length][sum+1], sum, num.length-1); } private int countSubsetsMemoization(int[] num, Integer[][] memo, int sum, int i) { if (i < 0 && sum != 0) return 0; if (sum == 0) return 1; if (memo[i][sum] != null) return memo[i][sum]; int pick = 0; if (num[i] <= sum) pick = countSubsetsMemoization(num, memo, sum-num[i], i-1); int unPick = countSubsetsMemoization(num, memo, sum, i-1); memo[i][sum] = pick + unPick; return memo[i][sum]; } public int countSubsetsRecursive(int[] num, int sum) { return countSubsetsRecursive(num, sum, num.length-1); } private int countSubsetsRecursive(int[] num, int sum, int i) { if (i < 0 && sum != 0) return 0; if (sum == 0) return 1; int pick = 0; if (num[i] <= sum) pick = countSubsetsRecursive(num, sum-num[i], i-1); int unPick = countSubsetsRecursive(num, sum, i-1); return pick + unPick; } public static void main(String[] args) { CountOfSubsetSum ss = new CountOfSubsetSum(); int[] num = {1, 1, 2, 3}; System.out.println(ss.countSubsetsRecursive(num, 4)); num = new int[]{1, 2, 7, 1, 5}; System.out.println(ss.countSubsetsRecursive(num, 9)); num = new int[]{1, 1, 2, 3}; System.out.println(ss.countSubsetsMemoization(num, 4)); num = new int[]{1, 2, 7, 1, 5}; System.out.println(ss.countSubsetsMemoization(num, 9)); } }
class URLify { public static String urlify(String s, int len) { char[] a = new char[s.length()]; int p = s.length() - 1; for (int i = len - 1; i >=0; i--) { if (s.charAt(i) == ' ') { a[p] = '0'; a[p-1] = '2'; a[p-2] = '%'; p -= 3; } else { a[p] = s.charAt(i); --p; } } return new String(a); } public static void main(String[] args) { String toUrl = "Mr John Smith "; int toUrlLen = 13; System.out.println(urlify(toUrl, toUrlLen)); } }
package pl.sda.spring.decouplinginterface; public class Child { public String getName(){ return "My name is..."; } }
package shape; import java.awt.Polygon; import main.GConstants; public class GTriangle extends GPolygon { private static final long serialVersionUID = GConstants.serialVersionUID; public GTriangle() { this.eDrawingStyle = EDrawingStyle.e2Points; this.shape = new Polygon(); } @Override public void setOrigin(int x, int y) { Polygon triangle = (Polygon) this.shape; triangle.npoints = 3; for (int i = 0; i < 3; i++) { triangle.xpoints[i] = x; triangle.ypoints[i] = y; } } @Override public void setPoint(int x, int y) { Polygon triangle = (Polygon) this.shape; int w = x - triangle.xpoints[1]; triangle.xpoints[0] = (int) (triangle.xpoints[1] + w * 0.5); triangle.xpoints[2] = x; triangle.ypoints[1] = y; triangle.ypoints[2] = y; } @Override public void addPoint(int x, int y) { } }
package MutuallyExclusiveThreads; public class P { static int pressureGuage = 0; static final int safetyLimit = 20; public static void main(String[] args) { Pressure[] P1 = new Pressure [10]; for(int i=0; i<10; i++) { P1[i] = new Pressure(); P1[i].start(); } try { for(int i=0; i<10; i++) P1[i].join(); } catch(Exception e) { } System.out.println("Guage reads " + pressureGuage + " safe limit is " + safetyLimit); } }
/** * Javassonne * http://code.google.com/p/javassonne/ * * @author [Add Name Here] * @date Jan 25, 2009 * * Copyright 2009 Javassonne Team * 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.javassonne.model.test; import junit.framework.TestCase; import org.javassonne.model.Tile; import org.javassonne.model.TileFeature; import org.javassonne.model.TileSet; public class TileSetTests extends TestCase { TileSet testSet_ = null; protected void setUp() throws Exception { super.setUp(); testSet_ = new TileSet("test"); } public void testAddTile() { int startTileCount = testSet_.tileCount(); Tile t = new Tile(); t.setUniqueIdentifier("identifier"); testSet_.addTile(t, 4); assertNotNull(testSet_.tileWithUniqueIdentifier("identifier")); assertTrue(testSet_.tileCount() == startTileCount + 1); assertTrue(testSet_.tileCountAtIndex(0) == 4); } public void testAddTileFeature() { int startFeatureCount = testSet_.tileFeatureCount(); TileFeature f = new TileFeature("name", "identifier", false, 0); testSet_.addTileFeature(f); assertNotNull(testSet_.tileFeatureWithIdentifier("identifier")); assertTrue(testSet_.tileFeatureCount() == startFeatureCount + 1); } public void testGetTileByIdentifier() { Tile t = new Tile(); t.setUniqueIdentifier("test"); testSet_.addTile(t, 1); assertTrue(testSet_.tileWithUniqueIdentifier(t.getUniqueIdentifier()) == t); } public void testSetName() { String name = "test"; testSet_.setName(name); assertTrue(testSet_.getName() == name); } public void testSetImagesFolder() { String folder = "folder"; testSet_.setTileImagesFolder(folder); assertTrue(testSet_.tileImagesFolder() == folder); } protected void tearDown() throws Exception { super.tearDown(); } }
package String; public class Strempty { public static void main(String[] args) { //System.out.println( S1.isEmpty()); //System.out.println( S2.isEmpty()); String S1 =" "; String S2 ="Nidarsana"; if(S1.length()== 0 || S1.isEmpty()) System.out.println(" S1 is Empty"); else System.out.println( S1); } }
package com.subrata.androidanimation; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; public class MainActivity4 extends AppCompatActivity { ImageView imageview4; Button bounce, blink, next; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main4); //Hide the action bar getSupportActionBar().hide(); imageview4=(ImageView)findViewById(R.id.imageview4); blink=(Button)findViewById(R.id.blink); bounce=(Button)findViewById(R.id.bounce); next=(Button)findViewById(R.id.next); //Zoom In button click event .......................................... bounce.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Animation a; a= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce); imageview4.startAnimation(a); } }); //Zoom out button click event .......................................... blink.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Animation b; b= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.blink); imageview4.startAnimation(b); } }); //Next button click event .......................................... next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i=new Intent(getApplicationContext(), MainActivity5.class); startActivity(i); } }); } }
package com.elvarg.world.content; import java.util.ArrayList; import java.util.List; import com.elvarg.GameConstants; import com.elvarg.definitions.ItemDefinition; import com.elvarg.engine.task.Task; import com.elvarg.engine.task.TaskManager; import com.elvarg.util.Misc; import com.elvarg.world.entity.impl.player.Player; import com.elvarg.world.model.Item; import com.elvarg.world.model.PlayerInteractingOption; import com.elvarg.world.model.PlayerStatus; import com.elvarg.world.model.Position; import com.elvarg.world.model.SecondsTimer; import com.elvarg.world.model.container.ItemContainer; import com.elvarg.world.model.container.StackType; import com.elvarg.world.model.container.impl.Equipment; import com.elvarg.world.model.container.impl.Inventory; import com.elvarg.world.model.movement.MovementStatus; /** * Handles the dueling system. * @author Professor Oak */ public class Dueling { private final Player player; private final ItemContainer container; private Player interact; private int configValue; private DuelState state = DuelState.NONE; //Delays!! private SecondsTimer button_delay = new SecondsTimer(); private SecondsTimer request_delay = new SecondsTimer(); //Rules private final boolean[] rules = new boolean[DuelRule.values().length]; private static final int DUELING_WITH_FRAME = 6671; private static final int INTERFACE_ID = 6575; private static final int CONFIRM_INTERFACE_ID = 6412; private static final int SCOREBOARD_INTERFACE_ID = 6733; private static final int SCOREBOARD_CONTAINER = 6822; private static final int SCOREBOARD_USERNAME_FRAME = 6840; private static final int SCOREBOARD_COMBAT_LEVEL_FRAME = 6839; public static final int MAIN_INTERFACE_CONTAINER = 6669; private static final int SECOND_INTERFACE_CONTAINER = 6670; private static final int STATUS_FRAME_1 = 6684; private static final int STATUS_FRAME_2 = 6571; private static final int ITEM_LIST_1_FRAME = 6516; private static final int ITEM_LIST_2_FRAME = 6517; private static final int RULES_FRAME_START = 8242; private static final int RULES_CONFIG_ID = 286; private static final int TOTAL_WORTH_FRAME = 24234; public Dueling(Player player) { this.player = player; //The container which will hold all our offered items. this.container = new ItemContainer(player) { @Override public StackType stackType() { return StackType.DEFAULT; } @Override public ItemContainer refreshItems() { player.getPacketSender().sendInterfaceSet(INTERFACE_ID, Trading.CONTAINER_INVENTORY_INTERFACE); player.getPacketSender().sendItemContainer(player.getInventory(), Trading.INVENTORY_CONTAINER_INTERFACE); player.getPacketSender().sendInterfaceItems(MAIN_INTERFACE_CONTAINER, player.getDueling().getContainer().getValidItems()); player.getPacketSender().sendInterfaceItems(SECOND_INTERFACE_CONTAINER, interact.getDueling().getContainer().getValidItems()); interact.getPacketSender().sendInterfaceItems(MAIN_INTERFACE_CONTAINER, interact.getDueling().getContainer().getValidItems()); interact.getPacketSender().sendInterfaceItems(SECOND_INTERFACE_CONTAINER, player.getDueling().getContainer().getValidItems()); return this; } @Override public ItemContainer full() { getPlayer().getPacketSender().sendMessage("You cannot stake more items."); return this; } @Override public int capacity() { return 28; } }; } public enum DuelState { NONE, REQUESTED_DUEL, DUEL_SCREEN, ACCEPTED_DUEL_SCREEN, CONFIRM_SCREEN, ACCEPTED_CONFIRM_SCREEN, STARTING_DUEL, IN_DUEL; } public enum DuelRule { NO_RANGED(16, 6725, -1, -1), NO_MELEE(32, 6726, -1, -1), NO_MAGIC(64, 6727, -1, -1), NO_SPECIAL_ATTACKS(8192, 7816, -1, -1), LOCK_WEAPON(4096, 670, -1, -1), NO_FORFEIT(1, 6721, -1, -1), NO_POTIONS(128, 6728, -1, -1), NO_FOOD(256, 6729, -1, -1), NO_PRAYER(512, 6730, -1, -1), NO_MOVEMENT(2, 6722, -1, -1), OBSTACLES(1024, 6732, -1, -1), NO_HELM(16384, 13813, 1, Equipment.HEAD_SLOT), NO_CAPE(32768, 13814, 1, Equipment.CAPE_SLOT), NO_AMULET(65536, 13815, 1, Equipment.AMULET_SLOT), NO_AMMUNITION(134217728, 13816, 1, Equipment.AMMUNITION_SLOT), NO_WEAPON(131072, 13817, 1, Equipment.WEAPON_SLOT), NO_BODY(262144, 13818, 1, Equipment.BODY_SLOT), NO_SHIELD(524288, 13819, 1, Equipment.SHIELD_SLOT), NO_LEGS(2097152, 13820, 1, Equipment.LEG_SLOT), NO_RING(67108864, 13821, 1, Equipment.RING_SLOT), NO_BOOTS(16777216, 13822, 1, Equipment.FEET_SLOT), NO_GLOVES(8388608, 13823, 1, Equipment.HANDS_SLOT); DuelRule(int configId, int buttonId, int inventorySpaceReq, int equipmentSlot) { this.configId = configId; this.buttonId = buttonId; this.inventorySpaceReq = inventorySpaceReq; this.equipmentSlot = equipmentSlot; } private int configId; private int buttonId; private int inventorySpaceReq; private int equipmentSlot; public int getConfigId() { return configId; } public int getButtonId() { return this.buttonId; } public int getInventorySpaceReq() { return this.inventorySpaceReq; } public int getEquipmentSlot() { return this.equipmentSlot; } public static DuelRule forId(int i) { for(DuelRule r : DuelRule.values()) { if(r.ordinal() == i) return r; } return null; } static DuelRule forButtonId(int buttonId) { for(DuelRule r : DuelRule.values()) { if(r.getButtonId() == buttonId) return r; } return null; } @Override public String toString() { return Misc.formatText(this.name().toLowerCase()); } } public void process() { if(state == DuelState.NONE || state == DuelState.REQUESTED_DUEL) { //Show challenge option if(player.getPlayerInteractingOption() != PlayerInteractingOption.CHALLENGE) { player.getPacketSender().sendInteractionOption("Challenge", 1, false); player.getPacketSender().sendInteractionOption("null", 2, true); //Remove attack option } } else if(state == DuelState.STARTING_DUEL || state == DuelState.IN_DUEL) { //Show attack option if(player.getPlayerInteractingOption() != PlayerInteractingOption.ATTACK) { player.getPacketSender().sendInteractionOption("Attack", 2, true); player.getPacketSender().sendInteractionOption("null", 1, false); //Remove challenge option } } else { //Hide both options if player isn't in one of those states if(player.getPlayerInteractingOption() != PlayerInteractingOption.NONE) { player.getPacketSender().sendInteractionOption("null", 2, true); player.getPacketSender().sendInteractionOption("null", 1, false); } } } public void requestDuel(Player t_) { if(state == DuelState.NONE || state == DuelState.REQUESTED_DUEL) { //Make sure to not allow flooding! if(!request_delay.finished()) { int seconds = request_delay.secondsRemaining(); player.getPacketSender().sendMessage("You must wait another "+(seconds == 1 ? "second" : ""+seconds+" seconds")+" before sending more duel challenges."); return; } //The other players' current duel state. final DuelState t_state = t_.getDueling().getState(); //Should we initiate the duel or simply send a request? boolean initiateDuel = false; //Update this instance... this.setInteract(t_); this.setState(DuelState.REQUESTED_DUEL); //Check if target requested a duel with us... if(t_state == DuelState.REQUESTED_DUEL) { if(t_.getDueling().getInteract() != null && t_.getDueling().getInteract() == player) { initiateDuel = true; } } //Initiate duel for both players with eachother? if(initiateDuel) { player.getDueling().initiateDuel(); t_.getDueling().initiateDuel(); } else { player.getPacketSender().sendMessage("You've sent a duel challenge to "+t_.getUsername()+"..."); t_.getPacketSender().sendMessage(player.getUsername() + ":duelreq:"); } //Set the request delay to 2 seconds at least. request_delay.start(2); } else { player.getPacketSender().sendMessage("You cannot do that right now."); } } public void initiateDuel() { //Set our duel state setState(DuelState.DUEL_SCREEN); //Set our player status player.setStatus(PlayerStatus.DUELING); //Reset rule toggle configs player.getPacketSender().sendConfig(RULES_CONFIG_ID, 0); //Update strings on interface player.getPacketSender(). sendString(DUELING_WITH_FRAME, "@or1@Dueling with: @whi@"+interact.getUsername()+"@or1@ Combat level: @whi@"+interact.getSkillManager().getCombatLevel()). sendString(STATUS_FRAME_1, "").sendString(669, "Lock Weapon").sendString(8278, "Neither player is allowed to change weapon."); //Send equipment on the interface.. int equipSlot = 0; for(Item item : player.getEquipment().getItems()) { player.getPacketSender().sendItemOnInterface(13824, item.getId(), equipSlot, item.getAmount()); equipSlot++; } //Reset container container.resetItems(); //Refresh and send container... container.refreshItems(); } public void closeDuel() { if(state != DuelState.NONE) { //Cache the current interact final Player interact_ = interact; //Return all items... for(Item t : container.getValidItems()) { container.switchItem(player.getInventory(), t.copy(), false, false); } //Refresh inventory player.getInventory().refreshItems(); //Reset all attributes... resetAttributes(); //Send decline message player.getPacketSender().sendMessage("Duel declined."); player.getPacketSender().sendInterfaceRemoval(); //Reset/close duel for other player aswell (the cached interact) if(interact_ != null) { if(interact_.getStatus() == PlayerStatus.DUELING) { if(interact_.getDueling().getInteract() != null && interact_.getDueling().getInteract() == player) { interact_.getPacketSender().sendInterfaceRemoval(); } } } } } public void resetAttributes() { //Reset duel attributes setInteract(null); setState(DuelState.NONE); //Reset player status if it's dueling. if(player.getStatus() == PlayerStatus.DUELING) { player.setStatus(PlayerStatus.NONE); } //Reset container.. container.resetItems(); //Reset rules for(int i = 0; i < rules.length; i++) { rules[i] = false; } //Clear toggles configValue = 0; player.getPacketSender().sendConfig(RULES_CONFIG_ID, 0); //Clear head hint player.getPacketSender().sendEntityHintRemoval(true); //Clear items on interface player.getPacketSender(). clearItemOnInterface(MAIN_INTERFACE_CONTAINER). clearItemOnInterface(SECOND_INTERFACE_CONTAINER); } //Deposit or withdraw an item.... public void handleItem(int id, int amount, int slot, ItemContainer from, ItemContainer to) { if(player.getInterfaceId() == INTERFACE_ID) { //Validate this stake action.. if(!validate(player, interact, PlayerStatus.DUELING, new DuelState[]{DuelState.DUEL_SCREEN, DuelState.ACCEPTED_DUEL_SCREEN})) { return; } if(ItemDefinition.forId(id).getValue() == 0) { player.getPacketSender().sendMessage("There's no point in staking that. It's spawnable!"); return; } //Check if the duel was previously accepted (and now modified)... if(state == DuelState.ACCEPTED_DUEL_SCREEN) { state = DuelState.DUEL_SCREEN; } if(interact.getDueling().getState() == DuelState.ACCEPTED_DUEL_SCREEN) { interact.getDueling().setState(DuelState.DUEL_SCREEN); } player.getPacketSender().sendString(STATUS_FRAME_1, "@red@DUEL MODIFIED!"); interact.getPacketSender().sendString(STATUS_FRAME_1, "@red@DUEL MODIFIED!"); //Handle the item switch.. if(state == DuelState.DUEL_SCREEN && interact.getDueling().getState() == DuelState.DUEL_SCREEN) { //Check if the item is in the right place if(from.getItems()[slot].getId() == id) { //Make sure we can fit that amount in the duel if(from instanceof Inventory) { if(!ItemDefinition.forId(id).isStackable()) { if(amount > container.getFreeSlots()) { amount = container.getFreeSlots(); } } } if(amount <= 0) { return; } final Item item = new Item(id, amount); //Only sort items if we're withdrawing items from the duel. final boolean sort = (from == (player.getDueling().getContainer())); //Do the switch! if(item.getAmount() == 1) { from.switchItem(to, item, slot, sort, true); } else { from.switchItem(to, item, sort, true); } } } else { player.getPacketSender().sendInterfaceRemoval(); } } } public void acceptDuel() { //Validate this stake action.. if(!validate(player, interact, PlayerStatus.DUELING, new DuelState[]{DuelState.DUEL_SCREEN, DuelState.ACCEPTED_DUEL_SCREEN, DuelState.CONFIRM_SCREEN, DuelState.ACCEPTED_CONFIRM_SCREEN})) { return; } //Check button delay... if(!button_delay.finished()) { return; } //Check button delay... //if(!button_delay.finished()) { // return; //} //Cache the interact... final Player interact_ = interact; //Interact's current trade state. final DuelState t_state = interact_.getDueling().getState(); //Check which action to take.. if(state == DuelState.DUEL_SCREEN) { //Verify that the interact can receive all items first.. int slotsRequired = getFreeSlotsRequired(player); if(player.getInventory().getFreeSlots() < slotsRequired) { player.getPacketSender().sendMessage("You need at least "+slotsRequired+" free inventory slots for this duel."); return; } if(rules[DuelRule.NO_MELEE.ordinal()] && rules[DuelRule.NO_RANGED.ordinal()] && rules[DuelRule.NO_MAGIC.ordinal()]) { player.getPacketSender().sendMessage("You must enable at least one of the three combat styles."); return; } //Both are in the same state. Do the first-stage accept. setState(DuelState.ACCEPTED_DUEL_SCREEN); //Update status... player.getPacketSender().sendString(STATUS_FRAME_1, "Waiting for other player.."); interact_.getPacketSender().sendString(STATUS_FRAME_1, ""+player.getUsername()+" has accepted."); //Check if both have accepted.. if(state == DuelState.ACCEPTED_DUEL_SCREEN && t_state == DuelState.ACCEPTED_DUEL_SCREEN) { //Technically here, both have accepted. //Go into confirm screen! player.getDueling().confirmScreen(); interact_.getDueling().confirmScreen(); } } else if(state == DuelState.CONFIRM_SCREEN) { //Both are in the same state. Do the second-stage accept. setState(DuelState.ACCEPTED_CONFIRM_SCREEN); //Update status... player.getPacketSender().sendString(STATUS_FRAME_2, "Waiting for "+interact_.getUsername()+"'s confirmation.."); interact_.getPacketSender().sendString(STATUS_FRAME_2, ""+player.getUsername()+" has accepted. Do you wish to do the same?"); //Check if both have accepted.. if(state == DuelState.ACCEPTED_CONFIRM_SCREEN && t_state == DuelState.ACCEPTED_CONFIRM_SCREEN) { //Both accepted, start duel //Decide where they will spawn in the arena.. final boolean obstacle = rules[DuelRule.OBSTACLES.ordinal()]; final boolean movementDisabled = rules[DuelRule.NO_MOVEMENT.ordinal()]; Position pos1 = getRandomSpawn(obstacle); Position pos2 = getRandomSpawn(obstacle); //Make them spaw next to eachother if(movementDisabled) { pos2 = pos1.copy().add(-1, 0); } player.getDueling().startDuel(pos1); interact_.getDueling().startDuel(pos2); } } button_delay.start(1); } public Position getRandomSpawn(boolean obstacle) { if(obstacle) { return new Position(3366 + Misc.getRandom(11), 3246 + Misc.getRandom(6)); } return new Position(3335 + Misc.getRandom(11), 3246 + Misc.getRandom(6)); } private void confirmScreen() { //Update state player.getDueling().setState(DuelState.CONFIRM_SCREEN); //Send new interface frames String this_items = Trading.listItems(container); String interact_item = Trading.listItems(interact.getDueling().getContainer()); player.getPacketSender().sendString(ITEM_LIST_1_FRAME, this_items); player.getPacketSender().sendString(ITEM_LIST_2_FRAME, interact_item); //Reset all previous strings related to rules for (int i = 8238; i <= 8253; i++) { player.getPacketSender().sendString(i, ""); } //Send new ones player.getPacketSender().sendString(8250, "Hitpoints will be restored."); player.getPacketSender().sendString(8238, "Boosted stats will be restored."); if (rules[DuelRule.OBSTACLES.ordinal()]) { player.getPacketSender().sendString(8239, "@red@There will be obstacles in the arena."); } player.getPacketSender().sendString(8240, ""); player.getPacketSender().sendString(8241, ""); int ruleFrameIndex = RULES_FRAME_START; for (int i = 0; i < DuelRule.values().length; i++) { if(i == DuelRule.OBSTACLES.ordinal()) continue; if (rules[i]) { player.getPacketSender().sendString(ruleFrameIndex, "" + DuelRule.forId(i).toString()); ruleFrameIndex++; } } player.getPacketSender().sendString(STATUS_FRAME_2, ""); //Send new interface.. player.getPacketSender().sendInterfaceSet(CONFIRM_INTERFACE_ID, Inventory.INTERFACE_ID); player.getPacketSender().sendItemContainer(player.getInventory(), Trading.INVENTORY_CONTAINER_INTERFACE); } public boolean checkRule(int button) { DuelRule rule = DuelRule.forButtonId(button); if(rule != null) { checkRule(rule); return true; } return false; } private void checkRule(DuelRule rule) { //Check if we're actually dueling.. if(player.getStatus() != PlayerStatus.DUELING) { return; } //Verify stake... if(!validate(player, interact, PlayerStatus.DUELING, new DuelState[]{DuelState.DUEL_SCREEN, DuelState.ACCEPTED_DUEL_SCREEN})) { return; } //Verify our current state.. if(state == DuelState.DUEL_SCREEN || state == DuelState.ACCEPTED_DUEL_SCREEN) { //Toggle the rule.. if(!rules[rule.ordinal()]) { rules[rule.ordinal()] = true; configValue += rule.getConfigId(); } else { rules[rule.ordinal()] = false; configValue -= rule.getConfigId(); } //Update interact's rules to match ours. interact.getDueling().setConfigValue(configValue); interact.getDueling().getRules()[rule.ordinal()] = rules[rule.ordinal()]; //Send toggles for both players. player.getPacketSender().sendToggle(RULES_CONFIG_ID, configValue); interact.getPacketSender().sendToggle(RULES_CONFIG_ID, configValue); //Send modify status if(state == DuelState.ACCEPTED_DUEL_SCREEN) { state = DuelState.DUEL_SCREEN; } if(interact.getDueling().getState() == DuelState.ACCEPTED_DUEL_SCREEN) { interact.getDueling().setState(DuelState.DUEL_SCREEN); } player.getPacketSender().sendString(STATUS_FRAME_1, "@red@DUEL MODIFIED!"); interact.getPacketSender().sendString(STATUS_FRAME_1, "@red@DUEL MODIFIED!"); //Inform them about this "custom" rule. if(rule == DuelRule.LOCK_WEAPON && rules[rule.ordinal()]) { player.getPacketSender().sendMessage("@red@Warning! The rule 'Lock Weapon' has been enabled. You will not be able to change").sendMessage("@red@weapon during the duel!"); interact.getPacketSender().sendMessage("@red@Warning! The rule 'Lock Weapon' has been enabled. You will not be able to change").sendMessage("@red@weapon during the duel!"); } } } private void startDuel(Position telePos) { //Let's start the duel! //Set current duel state setState(DuelState.STARTING_DUEL); //Close open interfaces player.getPacketSender().sendInterfaceRemoval(); //Unequip items based on the rules set for this duel for(int i = 11; i < rules.length; i++) { DuelRule rule = DuelRule.forId(i); if(rules[i]) { if(rule.getEquipmentSlot() < 0) continue; if(player.getEquipment().getItems()[rule.getEquipmentSlot()].getId() > 0) { Item item = new Item(player.getEquipment().getItems()[rule.getEquipmentSlot()].getId(), player.getEquipment().getItems()[rule.getEquipmentSlot()].getAmount()); player.getEquipment().delete(item); player.getInventory().add(item); } } } if(rules[DuelRule.NO_WEAPON.ordinal()] || rules[DuelRule.NO_SHIELD.ordinal()]) { if(player.getEquipment().getItems()[Equipment.WEAPON_SLOT].getId() > 0) { if(ItemDefinition.forId(player.getEquipment().getItems()[Equipment.WEAPON_SLOT].getId()).isDoubleHanded()) { Item item = new Item(player.getEquipment().getItems()[Equipment.WEAPON_SLOT].getId(), player.getEquipment().getItems()[Equipment.WEAPON_SLOT].getAmount()); player.getEquipment().delete(item); player.getInventory().add(item); } } } //Clear items on interface player.getPacketSender(). clearItemOnInterface(MAIN_INTERFACE_CONTAINER). clearItemOnInterface(SECOND_INTERFACE_CONTAINER); //Restart the player player.restart(true); //Freeze the player if(rules[DuelRule.NO_MOVEMENT.ordinal()]) { player.getMovementQueue().reset().setMovementStatus(MovementStatus.DISABLED); } //Send interact hints player.getPacketSender().sendPositionalHint(interact.getPosition().copy(), 10); player.getPacketSender().sendEntityHint(interact); //Teleport the player player.moveTo(telePos); //Make them interact with eachother player.setEntityInteraction(interact); //Send countdown as a task TaskManager.submit(new Task(2, player, false) { int timer = 3; @Override public void execute() { if(player.getDueling().getState() != DuelState.STARTING_DUEL) { stop(); return; } if(timer == 3 || timer == 2 || timer == 1) { player.forceChat(""+timer+".."); } else { player.getDueling().setState(DuelState.IN_DUEL); player.forceChat("FIGHT!!"); stop(); } timer--; } }); } public void duelLost() { //Make sure both players are in a duel.. if(validate(player, interact, null, new DuelState[]{DuelState.STARTING_DUEL, DuelState.IN_DUEL})) { //Add won items to a list.. int totalValue = 0; List<Item> winnings = new ArrayList<Item>(); for(Item item : interact.getDueling().getContainer().getValidItems()) { interact.getInventory().add(item); winnings.add(item); totalValue += item.getDefinition().getValue(); } for(Item item : player.getDueling().getContainer().getValidItems()) { interact.getInventory().add(item); winnings.add(item); totalValue += item.getDefinition().getValue(); } //Send interface data.. interact.getPacketSender(). sendString(SCOREBOARD_USERNAME_FRAME, player.getUsername()). sendString(SCOREBOARD_COMBAT_LEVEL_FRAME, ""+player.getSkillManager().getCombatLevel()). sendString(TOTAL_WORTH_FRAME, "@yel@Total: @or1@"+Misc.insertCommasToNumber(""+totalValue+"") + " value!"); //Send winnings onto interface interact.getPacketSender().sendInterfaceItems(SCOREBOARD_CONTAINER, winnings); //Send the scoreboard interface interact.getPacketSender().sendInterface(SCOREBOARD_INTERFACE_ID); //Restart the winner's stats interact.restart(true); //Move players home interact.moveTo(GameConstants.DEFAULT_POSITION.copy().add(Misc.getRandom(2), Misc.getRandom(2))); player.moveTo(GameConstants.DEFAULT_POSITION.copy().add(Misc.getRandom(2), Misc.getRandom(2))); //Send messages interact.getPacketSender().sendMessage("You won the duel!"); player.getPacketSender().sendMessage("You lost the duel!"); //Reset attributes for both interact.getDueling().resetAttributes(); player.getDueling().resetAttributes(); } else { player.getDueling().resetAttributes(); player.getPacketSender().sendInterfaceRemoval(); if(interact != null) { interact.getDueling().resetAttributes(); interact.getPacketSender().sendInterfaceRemoval(); } } } public boolean inDuel() { return state == DuelState.STARTING_DUEL || state == DuelState.IN_DUEL; } /** * Validates a player. Basically checks that all specified params add up. * @param player * @param interact * @param playerStatus * @param duelStates * @return */ private static boolean validate(Player player, Player interact, PlayerStatus playerStatus, DuelState... duelStates) { //Verify player... if(player == null || interact == null) { return false; } //Make sure we have proper status if(playerStatus != null) { if(player.getStatus() != playerStatus) { return false; } //Make sure we're interacting with eachother if(interact.getStatus() != playerStatus) { return false; } } if(player.getDueling().getInteract() == null || player.getDueling().getInteract() != interact) { return false; } if(interact.getDueling().getInteract() == null || interact.getDueling().getInteract() != player) { return false; } //Make sure we have proper duel state. boolean found = false; for(DuelState duelState : duelStates) { if(player.getDueling().getState() == duelState) { found = true; break; } } if(!found) { return false; } //Do the same for our interact found = false; for(DuelState duelState : duelStates) { if(interact.getDueling().getState() == duelState) { found = true; break; } } if(!found) { return false; } return true; } private int getFreeSlotsRequired(Player player) { int slots = 0; //Count equipment that needs to be taken off for(int i = 11; i < player.getDueling().getRules().length; i++) { DuelRule rule = DuelRule.values()[i]; if(player.getDueling().getRules()[rule.ordinal()]) { Item item = player.getEquipment().getItems()[rule.getEquipmentSlot()]; if(!item.isValid()) { continue; } if(!(item.getDefinition().isStackable() && player.getInventory().contains(item.getId()))) { slots += rule.getInventorySpaceReq(); } if(rule == DuelRule.NO_WEAPON || rule == DuelRule.NO_SHIELD) { } } } //Count inventory slots from interact's container aswell as ours for(Item item : container.getItems()) { if(item == null || !item.isValid()) continue; if(!(item.getDefinition().isStackable() && player.getInventory().contains(item.getId()))) { slots++; } } for(Item item : interact.getDueling().getContainer().getItems()) { if(item == null || !item.isValid()) continue; if(!(item.getDefinition().isStackable() && player.getInventory().contains(item.getId()))) { slots++; } } return slots; } public SecondsTimer getButtonDelay() { return button_delay; } public DuelState getState() { return state; } public void setState(DuelState state) { this.state = state; } public ItemContainer getContainer() { return container; } public Player getInteract() { return interact; } public void setInteract(Player interact) { this.interact = interact; } public boolean[] getRules() { return rules; } public int getConfigValue() { return configValue; } public void setConfigValue(int configValue) { this.configValue = configValue; } public void incrementConfigValue(int configValue) { this.configValue += configValue; } }
package phoneBook; import exceptions.InvalidContactNameException; import exceptions.InvalidCountryCodeException; import exceptions.InvalidPhoneNumberException; import exceptions.PhoneManagerException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class PhoneManager implements IPhoneManager { //ToDo //Add variables //Add methods //ToDo: add recover and backup }
package com.app.exception; public class Test2 { public static void main(String[] args) { /*ArrayIndexOutofBoundsException int x[] = new int[10]; System.out.println(x[9]); //System.out.println(x[15]); System.out.println(x[-15]);*/ /*NullPointerException String s = null; System.out.println(s.length());*/ /*ClassCastException //String s = new String("ashok"); Object o = new Object(); String s = (String)o; System.out.println(s);*/ /*IllegalArgumentException Thread t = new Thread(); t.setPriority(10); t.setPriority(100);*/ /*NumberFormatException int i = Integer.parseInt("10"); int j = Integer.parseInt("ten");*/ } }
package es.davidcampos.yep; /** * Created by David on 26/07/2015. */ public class ParseConstants { public static final String KEY_USERNAME = "username"; public static final int MAX_USERS = 1000; public static final String KEY_FRIENDS_RELATION = "friendsRelation"; public static final String CLASE_MENSAJE = "mensaje"; public static final String KEY_RECEPTOR_ID = "id_receptor"; public static final String KEY_RECEPTOR_NOMBRE = "nombre_receptor" ; public static final String KEY_DESTINATARIOS_IDS = "destinatarios" ; public static final String KEY_TIPO_FICHERO = "tipo_fichero" ; public static final String TYPE_IMAGE = "imagen" ; public static final String TYPE_VIDEO = "video" ; }
package chapter12.Exercise12_03; import java.util.Scanner; public class Exercise12_03 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] list = new int[100]; for (int i = 0; i < list.length; i++) { list[i] = (int) (Math.random() * 100); } try { System.out.println("Enter the index of the array between 0 to 99"); int index = input.nextInt(); System.out.println("The element value is " + list[index]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Out of Bounds."); } } }
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.ColorSensor; import com.qualcomm.robotcore.hardware.Servo; @TeleOp(name = "DriveExample", group = "Iterative OpMode" ) public class DriveExample extends OpMode { private DcMotor dcmotor_fr = null; private DcMotor dcmotor_fl = null; private DcMotor dcmotor_br = null; private DcMotor dcmotor_bl = null; double motorPower = 1; @Override public void init() { dcmotor_fr = hardwareMap.dcMotor.get("dcmotor_fr"); //controller 2 port 1 dcmotor_fl = hardwareMap.dcMotor.get("dcmotor_fl"); //controller 1 port 1 dcmotor_bl = hardwareMap.dcMotor.get("dcmotor_bl"); //controller 1 port 2 dcmotor_br = hardwareMap.dcMotor.get("dcmotor_br"); //controller 2 port 2 } @Override public void init_loop() { dcmotor_fr.setPower(0); dcmotor_fl.setPower(0); dcmotor_br.setPower(0); dcmotor_br.setPower(0); } @Override public void start() { //runtime.reset(); } @Override public void loop() { dcmotor_fl.setPower(gamepad1.left_stick_y * motorPower); dcmotor_fr.setPower(-gamepad1.right_stick_y * motorPower); dcmotor_bl.setPower(gamepad1.left_stick_y * motorPower); dcmotor_br.setPower(-gamepad1.right_stick_y * motorPower); } @Override public void stop(){ dcmotor_br.setPower(0); dcmotor_bl.setPower(0); dcmotor_fl.setPower(0); dcmotor_fr.setPower(0); } }
package JavaSessions; public class StringConcatenation { public static void main(String[] args) { double d=12.33; double d1=23.33; int a=100; int b=200; String x="Hello"; String y="Testing"; System.out.println(d+d1); System.out.println(a+b); System.out.println(x+y); System.out.println(a+b+x+y); System.out.println(x+y+a+b); System.out.println(x+y+(a+b)); System.out.println(x+y+d+d1+a+b); System.out.println(x+y+(d+d1)+a+b); System.out.println(x+y+" "+(d+d1)+(a+b)); System.out.println("the value of a is" + " " + a); System.out.println("the sum of a and b is " +(a+b)); int i=4/2; // 4 divided by 2 System.out.println(i); System.out.println(4/2); // printing directly System.out.println(5/2);// it will print =2 //.5 depends on 5 and 2. they are both integers , output will be // an integer System.out.println(5.0/2);//2.5 ..either of 5.0 or 2 is a float System.out.println(5/2.0);//2.5 System.out.println(5.0/2.0);//2.5 //int k=9/2.0; //System.out.println(k); float k1=9/2.0f; float k2=(float)(9/2.0); double d3=9/2.0; System.out.println(k1); System.out.println(k2); System.out.println(d3); //int p=9/0;// anything divided by zero will throw an exception //java.lang.ArithmeticException: / by zero int m=0/9; System.out.println(m);//0 int n=0/0; System.out.println(n);//anything divided by zero will throw an exception //java.lang.ArithmeticException: / by zero } }
package com.capgemini.service; import java.util.Date; import java.util.List; import com.capgemini.exceptions.NoSuchParkingSlotException; import com.capgemini.exceptions.ParkingSlotNotAvailableException; import com.capgemini.model.ParkingFloor; import com.capgemini.model.ParkingPremise; import com.capgemini.model.ParkingSlots; public interface ParkingService { public boolean checkAvailability(Date date, String time) throws ParkingSlotNotAvailableException; public boolean bookParkingSlot(ParkingSlots slot) throws ParkingSlotNotAvailableException; public boolean cancelParkingSlotBooking(ParkingSlots slot) throws NoSuchParkingSlotException; public List<ParkingSlots> getAllParkingSlotsByPremise(ParkingPremise parkingPremise); public List<ParkingSlots> getAllParkingSlotsByFloor(ParkingFloor parkingFloor); public ParkingSlots getParkingSlotsById(long parkingSlotId) throws NoSuchParkingSlotException; }
package mt.dou; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * @author Andrey Lomakin <a href="mailto:lomakin.andrey@gmail.com">Andrey Lomakin</a> * @since 10/5/14 */ public class TestReadLockCountdown { private final ReadWriteLock spinLock = new ReentrantReadWriteLock(); private final ExecutorService executorService = Executors.newCachedThreadPool(); private final CountDownLatch latch = new CountDownLatch(1); @Test public void benchmark() throws Exception { List<Future<Long>> futures = new ArrayList<Future<Long>>(); for (int i = 0; i < 8; i++) futures.add(executorService.submit(new CountDown(2000000))); long star = System.currentTimeMillis(); latch.countDown(); long total = 0; for (Future<Long> future : futures) total += future.get(); long end = System.currentTimeMillis(); System.out.println("Count down for : " + total + " ns."); System.out.println("Execution time is : " + (end - star) + " ms."); } public final class CountDown implements Callable<Long> { private final long counter; public CountDown(long counter) { this.counter = counter; } @Override public Long call() throws Exception { latch.await(); long cnt = counter; final long start = System.nanoTime(); while (cnt > 0) { spinLock.readLock().lock(); cnt--; spinLock.readLock().unlock(); } final long end = System.nanoTime(); return (end - start); } } }
package com.example.demo.core.systems; import com.example.demo.core.components.Cabinet; import com.example.demo.core.components.Motherboard; import com.example.demo.core.components.PSU; import lombok.Getter; @Getter public class Tower { private Motherboard motherboard; private Cabinet cabinet; private PSU psu; public Tower(Motherboard motherboard, Cabinet cabinet, PSU psu) { this.motherboard = motherboard; this.cabinet = cabinet; this.psu = psu; } // // public boolean fullyConfigured() { // /* // TODO: add logic to check for minimum component's // 1. motherboard installed // 2. CPU installed // 3. RAM installed // 4. CPU has internal GPU, or GPU is installed. // 5. At least one storage installed // 6. SMPS installed // 6.a SMPS power >= CPU + GPU power requirement // */ // return false; // } public static class Builder { private Motherboard motherboard; private Cabinet cabinet; private PSU psu; public Builder withMotherboard(Motherboard motherboard) { this.motherboard = motherboard; return this; } public Builder withCabinet(Cabinet cabinet) { this.cabinet = cabinet; return this; } public Builder withPSU(PSU psu) { this.psu = psu; return this; } // TODO: installing motherboard to be mandatory first step // -> replacing motherboard won't be possible // -> all other installation will first check if motherboard exists or not. public Tower build() { /** * TODO: * 1. check PSU power >= motherboard + cabinet power requirement. * 2. cabinet size >= motherboard size */ if (cabinet == null) { throw new IllegalStateException("Cannot built tower without a cabinet"); } if (motherboard == null) { throw new IllegalStateException("Cannot built tower without a motherboard"); } if (psu == null) { throw new IllegalStateException("Cannot built tower without a psu"); } if (cabinet.formFactors().getSize() < motherboard.formFactors().getSize()) { throw new IllegalStateException("cannot fit bigger motherboard in small cabinet"); } if (psu.suppliedPower() < motherboard.consumedPower() + cabinet.consumedPower()) { throw new IllegalStateException("PSU not sufficient for power needs"); } var tower = new Tower(motherboard, cabinet, psu); return tower; } } }
package com.zking.ssm.mapper; import com.zking.ssm.model.SysPermisson; public interface SysPermissonMapper { int deleteByPrimaryKey(Integer perid); int insert(SysPermisson record); int insertSelective(SysPermisson record); SysPermisson selectByPrimaryKey(Integer perid); int updateByPrimaryKeySelective(SysPermisson record); int updateByPrimaryKey(SysPermisson record); }
/* * 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 Ejercicio3_17; import java.util.Scanner; /** * * @author leonardo */ public class PruebaPerfilMedico { public static void main(String[] args) { PerfilMedico pm1 = new PerfilMedico("leonardo", "rodhen", "masculino", 178.34, 198.56, 8, 1995, 2, 11, 2018, 3); System.out.println(pm1); } }
package enthu_leitner; public class e_1199 { public static int getSwitch(String str) { return (int) Math.round(Double.parseDouble(str.substring(1, str.length() - 1))); } public static void main(String args[]) { switch (getSwitch(args[0])) { case 0: System.out.print("Hello "); case 1: System.out.print("World"); break; default: System.out.print("Good Bye"); } } }
package pl.edu.pw.mini.gapso.function; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; public class FunctionTest { @Test public void isTargetReached() { FunctionWhiteBox functionFullSquare = new ConvexSquareFunction(); FunctionWhiteBox functionSeparableSquare = new ConvexSeparableSquareFunction(); final double[] someX = {2.0, 2.0}; double[] opt1 = functionFullSquare.getOptimumLocation(); double[] opt2 = functionSeparableSquare.getOptimumLocation(); testForOptAndFunction(functionFullSquare, someX, opt1); testForOptAndFunction(functionSeparableSquare, someX, opt2); FunctionWhiteBox functionPartiallyFalt = new PartiallyFlatLinearFunction(); testFunctionBeforeAndAfterSomeEvaluation(functionPartiallyFalt, someX); } private void testForOptAndFunction(FunctionWhiteBox function, double[] someX, double[] opt) { Assert.assertFalse(Arrays.equals(opt, someX)); testFunctionBeforeAndAfterSomeEvaluation(function, someX); function.getValue(opt); Assert.assertTrue(function.isTargetReached()); function.resetOptimumVisitedState(); Assert.assertFalse(function.isTargetReached()); } private void testFunctionBeforeAndAfterSomeEvaluation(FunctionWhiteBox function, double[] someX) { Assert.assertFalse(function.isTargetReached()); function.getValue(someX); Assert.assertFalse(function.isTargetReached()); } }
package game; import game.cards.Card; import java.util.ArrayList; import serverPart.Gamer; public class Player { private boolean activated; private Gamer gamer; private ArrayList<Card> myCards; public Player(Gamer gamer) { super(); this.gamer = gamer; this.activated = false; } public void activate() { this.activated = true; } public Gamer getGamer() { return this.gamer; } protected void giveCards(ArrayList<Card> cards) { this.myCards = cards; } protected boolean hasCard(int value) { for (Card card : this.myCards) { if (card.getValue() == value) { return true; } } return false; } public boolean isActivated() { return this.activated; } }
package com.mysql.cj.jdbc.ha; import com.mysql.cj.Messages; import com.mysql.cj.jdbc.ConnectionImpl; import com.mysql.cj.jdbc.JdbcConnection; import com.mysql.cj.jdbc.exceptions.SQLError; import java.lang.reflect.InvocationHandler; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class RandomBalanceStrategy implements BalanceStrategy { public ConnectionImpl pickConnection(InvocationHandler proxy, List<String> configuredHosts, Map<String, JdbcConnection> liveConnections, long[] responseTimes, int numRetries) throws SQLException { int numHosts = configuredHosts.size(); SQLException ex = null; List<String> whiteList = new ArrayList<>(numHosts); whiteList.addAll(configuredHosts); Map<String, Long> blackList = ((LoadBalancedConnectionProxy)proxy).getGlobalBlacklist(); whiteList.removeAll(blackList.keySet()); Map<String, Integer> whiteListMap = getArrayIndexMap(whiteList); for (int attempts = 0; attempts < numRetries; ) { int random = (int)Math.floor(Math.random() * whiteList.size()); if (whiteList.size() == 0) throw SQLError.createSQLException(Messages.getString("RandomBalanceStrategy.0"), null); String hostPortSpec = whiteList.get(random); ConnectionImpl conn = (ConnectionImpl)liveConnections.get(hostPortSpec); if (conn == null) try { conn = ((LoadBalancedConnectionProxy)proxy).createConnectionForHost(hostPortSpec); } catch (SQLException sqlEx) { ex = sqlEx; if (((LoadBalancedConnectionProxy)proxy).shouldExceptionTriggerConnectionSwitch(sqlEx)) { Integer whiteListIndex = whiteListMap.get(hostPortSpec); if (whiteListIndex != null) { whiteList.remove(whiteListIndex.intValue()); whiteListMap = getArrayIndexMap(whiteList); } ((LoadBalancedConnectionProxy)proxy).addToGlobalBlacklist(hostPortSpec); if (whiteList.size() == 0) { attempts++; try { Thread.sleep(250L); } catch (InterruptedException interruptedException) {} whiteListMap = new HashMap<>(numHosts); whiteList.addAll(configuredHosts); blackList = ((LoadBalancedConnectionProxy)proxy).getGlobalBlacklist(); whiteList.removeAll(blackList.keySet()); whiteListMap = getArrayIndexMap(whiteList); } continue; } throw sqlEx; } return conn; } if (ex != null) throw ex; return null; } private Map<String, Integer> getArrayIndexMap(List<String> l) { Map<String, Integer> m = new HashMap<>(l.size()); for (int i = 0; i < l.size(); i++) m.put(l.get(i), Integer.valueOf(i)); return m; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\jdbc\ha\RandomBalanceStrategy.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.hx.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * @program: eqds-ms * @description: * @author: yangyue * @create: 2019/12/21 14:19 */ public class DbUtil { public static Connection getConnection(String dbpath, String password) { Connection conn = null; try { Properties prop = new Properties(); prop.put("charSet", "UTF-8"); prop.put("password", password); Class.forName("com.hxtt.sql.access.AccessDriver"); conn = (Connection) DriverManager.getConnection("jdbc:Access:///" + dbpath, prop); // 连接数据库 } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return conn; } }
package com.sabre.api.sacs.soap.interceptor; import javax.xml.bind.JAXBException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.ws.client.WebServiceClientException; import org.springframework.ws.context.MessageContext; import com.sabre.api.sacs.contract.soap.MessageHeader; import com.sabre.api.sacs.soap.pool.SessionPool; /** * Responsible for returning a session to a pool. Should be added to a last call * of the flow. * 用于将session还回池中,应该在工作流的最后一个调用上添加 */ @Controller @Scope("prototype") public class SessionPoolInterceptor extends AbstractSessionInterceptor { private static final Logger LOG = LogManager.getLogger(SessionPoolInterceptor.class); @Autowired private SessionPool sessionPool; @Override public boolean handleRequest(MessageContext messageContext) { return true; } @SuppressWarnings("serial") @Override public boolean handleResponse(MessageContext messageContext) { String conversationId = null; try { MessageHeader header = extractMessageHeaderFromMessageContext(messageContext); conversationId = header.getConversationId(); } catch (JAXBException | NullPointerException e) { LOG.fatal("Error occurred during retrieving session token", e); } if (conversationId == null) { throw new WebServiceClientException("Couldn't retrieve session token from message") { }; } logTokenAndConversationIdFromMessage("", conversationId); sessionPool.returnToPool(conversationId); return true; } }
package com.duanxr.yith.midium; /** * @author 段然 2021/9/10 */ public class SearchInRotatedSortedArray { /** * There is an integer array nums sorted in ascending order (with distinct values). * * Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. * * Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. * * You must write an algorithm with O(log n) runtime complexity. * *   * * Example 1: * * Input: nums = [4,5,6,7,0,1,2], target = 0 * Output: 4 * Example 2: * * Input: nums = [4,5,6,7,0,1,2], target = 3 * Output: -1 * Example 3: * * Input: nums = [1], target = 0 * Output: -1 *   * * Constraints: * * 1 <= nums.length <= 5000 * -104 <= nums[i] <= 104 * All values of nums are unique. * nums is guaranteed to be rotated at some pivot. * -104 <= target <= 104 * * 整数数组 nums 按升序排列,数组中的值 互不相同 。 * * 在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了 旋转,使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标 从 0 开始 计数)。例如, [0,1,2,4,5,6,7] 在下标 3 处经旋转后可能变为 [4,5,6,7,0,1,2] 。 * * 给你 旋转后 的数组 nums 和一个整数 target ,如果 nums 中存在这个目标值 target ,则返回它的下标,否则返回 -1 。 * *   * * 示例 1: * * 输入:nums = [4,5,6,7,0,1,2], target = 0 * 输出:4 * 示例 2: * * 输入:nums = [4,5,6,7,0,1,2], target = 3 * 输出:-1 * 示例 3: * * 输入:nums = [1], target = 0 * 输出:-1 *   * * 提示: * * 1 <= nums.length <= 5000 * -10^4 <= nums[i] <= 10^4 * nums 中的每个值都 独一无二 * 题目数据保证 nums 在预先未知的某个下标上进行了旋转 * -10^4 <= target <= 10^4 *   * * 进阶:你可以设计一个时间复杂度为 O(log n) 的解决方案吗? * */ class Solution { public int search(int[] nums, int target) { return target == nums[0] ? 0 : search0(nums, target, nums[0], 0, nums.length - 1); } private int search0(int[] nums, int target, int pivot, int low, int high) { while (low <= high) { int mid = (low + high) >>> 1; int midVal = nums[mid]; boolean th = target > pivot; boolean ch = midVal >= pivot; if (th == ch) { if (midVal < target) { low = mid + 1; } else if (midVal > target) { high = mid - 1; } else { return mid; } } else { if (ch) { low = mid + 1; } else { high = mid - 1; } } } return -1; } } }
package br.senai.sp.informatica.meusalbuns.control; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import java.util.List; import br.senai.sp.informatica.meusalbuns.R; import br.senai.sp.informatica.meusalbuns.model.Album; import br.senai.sp.informatica.meusalbuns.model.AlbumDao; import br.senai.sp.informatica.meusalbuns.view.adapter.AlbumAdapterRecycler; public class ListaAlbunsRecycler extends AppCompatActivity { private AlbumDao dao = AlbumDao.manager; private RecyclerView rvAlbuns; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.lista_albuns_rv); rvAlbuns = (RecyclerView)findViewById(R.id.rvAlbuns); List<Album> albumList = dao.getLista("Album"); rvAlbuns.setAdapter(new AlbumAdapterRecycler(albumList, this)); //RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); //rvAlbuns.setLayoutManager(layoutManager); StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); rvAlbuns.setLayoutManager(staggeredGridLayoutManager); android.app.ActionBar actionBar = getActionBar(); if (actionBar != null){ actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); } } }
package com.stryksta.swtorcentral.models; public class CodexItem { public int cdxID; public String cdxTitle; public String cdxDescription; public String cdxCategory; public String cdxLevel; public String cdxImage; public String cdxFaction; public String cdxIsPlanetCodex; public String cdxPlants; public CodexItem(int cdxID, String cdxTitle, String cdxDescription, String cdxCategory, String cdxLevel, String cdxImage, String cdxFaction, String cdxIsPlanetCodex, String cdxPlants) { this.cdxID = cdxID; this.cdxTitle = cdxTitle; this.cdxDescription = cdxDescription; this.cdxCategory = cdxCategory; this.cdxLevel = cdxLevel; this.cdxImage = cdxImage; this.cdxFaction = cdxFaction; this.cdxIsPlanetCodex = cdxIsPlanetCodex; this.cdxPlants = cdxPlants; } public int getID() { return cdxID; } public void setID(int cdxID){ this.cdxID = cdxID; } public String getTitle() { return cdxTitle; } public void setTitle(String cdxTitle){ this.cdxTitle = cdxTitle; } public String getDescription() { return cdxDescription; } public void setDescription(String cdxDescription){ this.cdxDescription = cdxDescription; } public String getCategory() { return cdxCategory; } public void setCategory(String cdxCategory){ this.cdxCategory = cdxCategory; } public String getLevel() { return cdxLevel; } public void setLevel(String cdxLevel){ this.cdxLevel = cdxLevel; } public String getImage() { return cdxImage; } public void setImage(String cdxImage){ this.cdxImage = cdxImage; } public String getFaction() { return cdxFaction; } public void setFaction(String cdxFaction){ this.cdxFaction = cdxFaction; } public String getCdxIsPlanetCodex() { return cdxIsPlanetCodex; } public void setCdxIsPlanetCodex(String cdxIsPlanetCodex){ this.cdxIsPlanetCodex = cdxIsPlanetCodex; } public String getPlanets() { return cdxPlants; } public void setPlanets(String cdxPlants){ this.cdxPlants = cdxPlants; } }
package lintcode; import java.util.Comparator; import java.util.PriorityQueue; /** * @Author: Mr.M * @Date: 2019-06-04 10:25 * @Description: **/ public class T461无序数组K小元素 { public static int kthSmallest(int k, int[] nums) { // write your code here PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }); int re = Integer.MAX_VALUE; for (int x : nums) { // 这里需要记录边界为k-1,如果为k的话,最小的三个数,那么p里面存储的是三个数,因为当size==2的时候仍然会存储,这时p里面存储了3个数值,而你需要的存储前k-1的数字,这样保证, // 没有在里面的数字可以获取其中最小的那个,保证是最小第k个数 if (priorityQueue.size() < k - 1) { priorityQueue.add(x); } else { if (x < priorityQueue.peek()) { int a = priorityQueue.poll(); // System.out.println(a); if (a < re) { re = a; } priorityQueue.add(x); } else { if (x < re) { re = x; } } System.out.println(x); } } return re; } public static void main(String[] args) { System.out.println(kthSmallest(3, new int[]{3, 4, 1, 2, 5})); } }
package pl.edu.amu.datasupplier.resource; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; public abstract class AbstractController { private final ModelMapper modelMapper; @Autowired public AbstractController(ModelMapper modelMapper) { this.modelMapper = modelMapper; } protected <S, T> List<T> convertModelList(List<S> list, Class<T> clazz) { return modelMapper.map(list, new ParameterizedType() { @Override public Type[] getActualTypeArguments() { return new Type[]{clazz}; } @Override public Type getRawType() { return List.class; } @Override public Type getOwnerType() { return null; } }); } protected <T, S> T convertModel(S model, Class<T> clazz) { return modelMapper.map(model, clazz); } }
package MasterMind; import MasterMind.AI.AI; import MasterMind.GUI.GUI; import MasterMind.GUI.PegResultsPanel; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.ForkJoinPool; /** * This class controls the interactions between the GUI, AI and Game classes. It handles GUI events, starts the AI and * holds a reference to the game to enable communications. * @author Jim Spagnola */ public class Controller implements ActionListener { private Game game; private GUI gui; /** * The constructor. * * @param gui The user interface. * @param game The game of MasterMind */ Controller(GUI gui, Game game){ this.game = game; this.gui = gui; setupListeners(); } private void setupListeners() { gui.settingsPanel.startButton.addActionListener(this); gui.gameBoardPanel.submitTurnButton.addActionListener(this); gui.gameBoardPanel.guesses.forEach(g->g.pegs.forEach(p->p.addActionListener(this))); gui.colorsPanel.colors.forEach(b->b.addActionListener(this)); } @Override public void actionPerformed(ActionEvent e) { JButton b = (JButton)e.getSource(); //if submit button was pressed if(b.getText().equals("Submit")){ System.out.println("Submit pressed"); playTurn(); } //if color button was pressed if(gui.colorsPanel.colors.contains(b)){ //change that to active color changeHighlightedColor(b); } //if peg was clicked if(gui.gameBoardPanel.guesses.get(gui.gameBoardPanel.getCurrentGuess()).pegs.contains(b)){ changePegColor(b); } if(b.getText().equals("Start")){ startGame(); } } private void startGame() { gui.settingsPanel.startButton.setEnabled(false); if(gui.settingsPanel.getSelected() == 0){ gui.gameBoardPanel.submitTurnButton.setEnabled(true); }else{ new Thread(this::runAI).start(); } } private void playTurn(){ //check/verify valid submission int[] guess = getGuessFromPegs(); int[] results; boolean b = true; for (int gues : guess) { if (gues == -1) { b = false; break; } } if(b) { //lock current row gui.gameBoardPanel.lockCurrentRow(); //send to game results = game.guess(guess); //if no win add results if(!game.checkWin()) { updateResults(results); //if not game over unlock next row if(!game.checkLost()) { gui.gameBoardPanel.unlockNextRow(); } else{ System.out.println("Game Over"); gui.gameBoardPanel.revealAnswer(game.getAnswer()); } } //else you win else{ System.out.println("You win"); gui.gameBoardPanel.revealAnswer(game.getAnswer()); } } else{ JOptionPane.showMessageDialog(null,"You have not finished your turn!!","Error!", JOptionPane.ERROR_MESSAGE); } } private void updateResults(int[] results) { PegResultsPanel pegPanel = gui.gameBoardPanel.getCurrentTurn().getResults(); pegPanel.setResults(results); } private void changeHighlightedColor(JButton b){ //if previous highlighted color, unhighlight. if(gui.colorsPanel.currentColor != null) { //set new color to highlighted. gui.colorsPanel.currentColor.setBorder(null); } b.setBorder(BorderFactory.createEtchedBorder(Color.GRAY,Color.BLACK)); gui.colorsPanel.currentColor = b; } private void changePegColor(JButton peg){ //if there is highlighted color. if(gui.colorsPanel.currentColor != null){ //change peg to that color. peg.setBackground(gui.colorsPanel.currentColor.getBackground()); } } private int[] getGuessFromPegs(){ return gui.gameBoardPanel.getGuess(); } //latch for AI to play private void submit(int[] guess){ //ask game for result gui.gameBoardPanel.updateCurrentGuess(guess); playTurn(); } private void runAI(){ AI ai; ForkJoinPool pool = new ForkJoinPool(); int[] temp = {0,0,0,0,0}; System.out.println("AI has started"); submit(temp); while(!game.checkLost() && !game.checkWin()){ ai = new AI(game); submit(pool.invoke(ai).getPlayAsArray()); System.out.println("Turn Submitted"); } } }
package com.takshine.wxcrm.service; import java.util.List; import com.takshine.wxcrm.base.services.EntityService; import com.takshine.wxcrm.domain.AccessLogs; import com.takshine.wxcrm.message.sugar.AccesslogResp; /** * 访问日志接口 * @author liulin * */ public interface AccessLogsService extends EntityService{ /** * 查询访问日志 * @param startDate * @param endDate * @return */ public List<AccessLogs> findAccessLogByFilter(String crmId,String startDate, String endDate, Integer curr, Integer pagecount); /** * 查询访问日志数量 * @param entId * @return */ public String countAccessLogs(String crmId,String url, String params, String startDate, String endDate); /** * 访问统计 * @param startDate * @param endDate * @return */ public List<AccessLogs> countAccessLogs(String crmId,String startDate,String endDate,String type); /** * 用户行为统计 * @param startDate * @param endDate * @return */ public AccesslogResp addcountAccessLogs(AccessLogs sche , String source); }
package enthu_leitner; public class e_1212 { public static void main(String[] args) { String a = "java"; char[] b = { 'j', 'a', 'v', 'a' }; String c = new String(b); String d = a; System.out.println(a == d); System.out.println(b == d); System.out.println(a == "java"); System.out.println(a.equals(c)); } }
package org.anasis; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import scala.Tuple2; public class LinkPrediction { private static final Pattern SPACE = Pattern.compile("[ \\t\\x0B\\f\\r]+"); public static JavaPairRDD<Tuple2<String, String>, Double> computeCommon (JavaRDD<String> lines) { JavaPairRDD<String, String> edges = lines.flatMapToPair(t -> { List<Tuple2<String,String>> result = new ArrayList<>(); if(!t.contains("#")) { String [] nodes = SPACE.split(t); result.add(new Tuple2<>(nodes[0], nodes[1])); result.add(new Tuple2<>(nodes[1], nodes[0])); } return result.iterator(); }).distinct(); JavaPairRDD<Tuple2<String, String>, Double> commonNeighborsSorted = edges.join(edges).flatMapToPair(t -> { double neighbor = Double.parseDouble(t._1()); double source = Double.parseDouble(t._2()._1()); double target = Double.parseDouble(t._2()._2()); List<Tuple2<Tuple2<String,String>,Double>> result = new ArrayList<>(); if(source == target) { if(neighbor<source) { result.add(new Tuple2<>(new Tuple2<>(t._1(),t._2()._1()), Double.parseDouble("0"))); } } else if (source<target) { result.add(new Tuple2<>(new Tuple2<>(t._2()._1(),t._2()._2()), Double.parseDouble("1"))); } return result.iterator(); }).groupByKey().mapValues(v -> { int count=0; for (Double item: v) { if(item == 0) { return Double.parseDouble("0"); } count++; } return Double.parseDouble(Integer.toString(count)); }).filter(t -> { return t._2!=0.0?true:false; }).mapToPair(t -> { return new Tuple2<>(t._2(),t._1()); }).sortByKey(false).mapToPair(t -> { return new Tuple2<>(t._2(),Double.parseDouble(t._1().toString())); }); return commonNeighborsSorted; } public static JavaPairRDD<Tuple2<String, String>, Double> computeJaccard (JavaRDD<String> lines) { JavaPairRDD<String, String> edges = lines.flatMapToPair(t -> { List<Tuple2<String,String>> result = new ArrayList<>(); if(!t.contains("#")) { String [] nodes = SPACE.split(t); result.add(new Tuple2<>(nodes[0], nodes[1])); result.add(new Tuple2<>(nodes[1], nodes[0])); } return result.iterator(); }).distinct(); JavaPairRDD<Tuple2<String, String>, Double> intersection = edges.join(edges).flatMapToPair(t -> { double neighbor = Double.parseDouble(t._1()); double source = Double.parseDouble(t._2()._1()); double target = Double.parseDouble(t._2()._2()); List<Tuple2<Tuple2<String,String>,Double>> result = new ArrayList<>(); if(source == target) { if(neighbor<source) { result.add(new Tuple2<>(new Tuple2<>(t._1(),t._2()._1()), Double.parseDouble("0"))); } } else if (source<target) { result.add(new Tuple2<>(new Tuple2<>(t._2()._1(),t._2()._2()), Double.parseDouble("1"))); } return result.iterator(); }).groupByKey().mapValues(v -> { int count=0; for (Double item: v) { if(item == 0) { return Double.parseDouble("0"); } count++; } return Double.parseDouble(Integer.toString(count)); }).filter(t -> { return t._2!=0.0?true:false; }); JavaPairRDD<String, Double> adjacencyListCount = edges.mapValues(v -> Double.parseDouble("1")).reduceByKey((a,b)->a+b); JavaPairRDD<Tuple2<String, String>, Double> jaccardSorted = intersection.mapToPair(t -> { return new Tuple2<>(t._1()._1(), new Tuple2<>(t._1()._2(),t._2())); }).join(adjacencyListCount).mapToPair(t -> { return new Tuple2<>(t._2()._1()._1(), new Tuple2<>(new Tuple2<>(t._1(),t._2()._1()._2()),t._2()._2())); }).join(adjacencyListCount).mapToPair(t -> { String source = t._2()._1()._1()._1(); String target = t._1(); double inter = t._2()._1()._1()._2(); double sourceNeighbors = t._2()._1()._2(); double targetNeighbors = t._2()._2(); double sumNeighbors = sourceNeighbors + targetNeighbors; return new Tuple2<>(new Tuple2<>(source,target),inter/(sumNeighbors-inter)); }).mapToPair(t -> { return new Tuple2<>(t._2(),t._1()); }).sortByKey(false).mapToPair(t -> { return new Tuple2<>(t._2(),t._1()); }); return jaccardSorted; } public static JavaPairRDD<Tuple2<String, String>, Double> computeAdamicAdar (JavaRDD<String> lines) { JavaPairRDD<String, String> edges = lines.flatMapToPair(t -> { List<Tuple2<String,String>> result = new ArrayList<>(); if(!t.contains("#")) { String [] nodes = SPACE.split(t); result.add(new Tuple2<>(nodes[0], nodes[1])); result.add(new Tuple2<>(nodes[1], nodes[0])); } return result.iterator(); }).distinct(); JavaPairRDD<String, Double> logarithms = edges.mapValues(v -> Long.parseLong("1") ).reduceByKey((a,b) -> a+b) .mapValues(v -> { if (v == 1) { return Double.parseDouble("-1"); } return 1/Math.log10(v.doubleValue()); }); JavaPairRDD<Tuple2<String, String>, Double> adamicadarSorted = edges.join(edges).join(logarithms).flatMapToPair(t -> { long neighbor = Long.parseLong(t._1()); long source = Long.parseLong(t._2()._1()._1()); long target = Long.parseLong(t._2()._1()._2()); List<Tuple2<Tuple2<String,String>, Double>> result = new ArrayList<>(); if(source == target) { if(neighbor<source) { result.add(new Tuple2<>(new Tuple2<>(t._1(),t._2()._1()._1()), Double.parseDouble("-1"))); } } else if (source<target) { result.add(new Tuple2<>(new Tuple2<>(t._2()._1()._1(),t._2()._1()._2()), t._2()._2())); } return result.iterator(); }).groupByKey().mapValues(v -> { double sum=0.0; for (Double item: v) { if(item == -1.0) { return Double.parseDouble("-1"); } sum+=item; } return Double.parseDouble(Double.toString(sum)); }).filter(t -> { return t._2>=0.0?true:false; }).mapToPair(t -> { return new Tuple2<>(t._2(),t._1()); }).sortByKey(false).mapToPair(t -> { return new Tuple2<>(t._2(),t._1()); }); return adamicadarSorted; } public static void main(String[] args) throws Exception { if (args.length != 4) { System.err.println("WRONG: NUMBER OF ARGUMENTS"); System.err.println("Usage: LinkPrediction <inputpath> <outputpath> <top-k> <method>"); System.err.println("method:\tString Argument"); System.err.println("common neighbors:\t\"common\""); System.err.println("Jaccard coefficient:\t\"jaccard\""); System.err.println("Adamic Adar:\t\t\"adamicadar\""); System.exit(1); } if (!args[3].equals("common")&&!args[3].equals("jaccard")&&!args[3].equals("adamicadar")) { System.err.println("WRONG: NAME OF METHOD"); System.err.println("Usage: LinkPrediction <inputpath> <outputpath> <top-k> <method>"); System.err.println("method:\tString Argument"); System.err.println("common neighbors:\t\"common\""); System.err.println("Jaccard coefficient:\t\"jaccard\""); System.err.println("Adamic Adar:\t\t\"adamicadar\""); System.exit(1); } try { if(Integer.parseInt(args[2])<0) { System.err.println("WRONG: NEGATIVE NUMBER OF K"); System.err.println("Usage: LinkPrediction <inputpath> <outputpath> <top-k> <method>"); System.err.println("top-k inappropriate value. Give an appropriate k: k>0 or k=0 to get all the records"); System.exit(1); } } catch (NumberFormatException e){ System.err.println("WRONG: K IS NOT A NUMBER"); System.err.println("Usage: LinkPrediction <inputpath> <outputpath> <top-k> <method>"); System.err.println("top-k inappropriate value. Give an appropriate k: k>0 or k=0 to get all the records"); System.exit(1); } SparkConf sparkConf = new SparkConf().setAppName("LinkPrediction"); JavaSparkContext sc = new JavaSparkContext(sparkConf); JavaRDD<String> lines = sc.textFile(args[0]); if (Integer.parseInt(args[2])>0) { if (args[3].equals("common")) { //sc.parallelizePairs(computeScore(lines,"common").take(Integer.parseInt(args[2]))).saveAsTextFile(args[1]); computeCommon(lines).zipWithUniqueId().filter(t->{ return t._2()<Integer.parseInt(args[2])?true:false; }).saveAsTextFile(args[1]); } else if (args[3].equals("jaccard")) { computeJaccard(lines).zipWithUniqueId().filter(t->{ return t._2()<Integer.parseInt(args[2])?true:false; }).saveAsTextFile(args[1]); } else if (args[3].equals("adamicadar")) { computeAdamicAdar(lines).zipWithUniqueId().filter(t->{ return t._2()<Integer.parseInt(args[2])?true:false; }).saveAsTextFile(args[1]); } } else { if (args[3].equals("common")) { computeCommon(lines).saveAsTextFile(args[1]); } else if (args[3].equals("jaccard")) { computeJaccard(lines).saveAsTextFile(args[1]); } else if (args[3].equals("adamicadar")) { computeAdamicAdar(lines).saveAsTextFile(args[1]); } } sc.stop(); } }
package initializations; /** * * @Ioanna Kyriazidou */ import twitter4j.conf.ConfigurationBuilder; public final class InitializeTwitter { private static final String ACCESS_TOKEN = "2999643856-jZxniwexoSq6af0NX3aHnKLITvQufIkA9ArLGfY"; private static final String ACCESS_TOKEN_SECRET = "jEcVM5SM22s1tlj4Ve3Tn5GhG7af4Yu4sp0lZkEOVuDyk"; private static final String CONSUMER_KEY = "akqzjginDHVhUV5wFZkpRbihz"; private static final String CONSUMER_SECRET = "cxRESqZy0tlPoLaSrvbFgXEeMMpuWODtuJ5KsX8w5SJx3xCkYt"; /* constructor */ public InitializeTwitter() { } public ConfigurationBuilder returnTwitterBuilder() { // create new db to store the tweets ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthAccessToken(ACCESS_TOKEN); cb.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET); cb.setOAuthConsumerKey(CONSUMER_KEY); cb.setOAuthConsumerSecret(CONSUMER_SECRET); return cb; } }
/** * Copyright (c) 2016 - 2018 Syncleus, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aparapi.natives; import com.aparapi.natives.util.NativeUtils; import java.io.IOException; public class NativeLoader { private static final String ARCH = System.getProperty("os.arch").toLowerCase(); private static final String OS = System.getProperty("os.name").toLowerCase(); public static void load() throws IOException { // String arch = System.getenv("PROCESSOR_ARCHITECTURE"); // String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432"); // // String realArch = arch.endsWith("64") // || wow64Arch != null && wow64Arch.endsWith("64") // ? "64" : "32"; if( isUnix() ) { if( is64Bit() ) NativeUtils.loadLibraryFromJar("/linux/libaparapi_x86_64.so"); else NativeUtils.loadLibraryFromJar("/linux/libaparapi_x86.so"); } else if( isMac() && is64Bit() ){ System.out.println("We in a mac yo"); NativeUtils.loadLibraryFromJar("/osx/libaparapi_x86_64.dylib"); } else if( isWindows() && is64Bit() ) NativeUtils.loadLibraryFromJar("/win/libaparapi_x86_64.dll"); else if( isWindows() && is32Bit() ) NativeUtils.loadLibraryFromJar("/win/libaparapi_x86.dll"); else throw new IOException("System is not compatable with any of the known native libraries."); } private static boolean isWindows() { return OS.contains("win"); } private static boolean isMac() { return OS.contains("mac"); } private static boolean isUnix() { return (OS.contains("nix") || OS.contains("nux") || OS.contains("aix")); } private static boolean isSolaris() { return OS.contains("sunos"); } private static boolean is64Bit() { if( ARCH.contains("64")) return true; return false; } private static boolean is32Bit() { return !is64Bit(); } }
package com.test.webui.controller; import com.test.data.domain.Actor; import com.test.data.repositories.ActorRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; @RestController @RequestMapping("/actor") public class ActorController { private static Logger logger = LoggerFactory.getLogger(ActorController.class); @Autowired private ActorRepository actorRepository; @RequestMapping("/index") public ModelAndView index(){ return new ModelAndView("actor/index"); } @RequestMapping(value="/{id}") public ModelAndView show(ModelMap model,@PathVariable Long id) { Actor actor = actorRepository.findOne(id); model.addAttribute("actor",actor); return new ModelAndView("actor/show"); } @RequestMapping("/new") public ModelAndView create(){ return new ModelAndView("actor/new"); } @RequestMapping(value="/save", method = RequestMethod.POST) public String save(Actor actor) throws Exception{ actorRepository.save(actor); logger.info("新增->ID={}", actor.getId()); return "1"; } @RequestMapping(value="/edit/{id}") public ModelAndView update(ModelMap model,@PathVariable Long id){ Actor actor = actorRepository.findOne(id); model.addAttribute("actor",actor); return new ModelAndView("actor/edit"); } @RequestMapping(method = RequestMethod.POST, value="/update") public String update(Actor actor) throws Exception{ actorRepository.save(actor); logger.info("修改->ID="+actor.getId()); return "1"; } @RequestMapping(value="/delete/{id}",method = RequestMethod.GET) public String delete(@PathVariable Long id) throws Exception{ Actor actor = actorRepository.findOne(id); actorRepository.delete(actor); logger.info("删除->ID="+id); return "1"; } @RequestMapping(value="/list") public Page<Actor> list(HttpServletRequest request) throws Exception{ String name = request.getParameter("name"); String page = request.getParameter("page"); String size = request.getParameter("size"); Pageable pageable = new PageRequest(page==null? 0: Integer.parseInt(page), size==null? 10:Integer.parseInt(size), new Sort(Sort.Direction.DESC, "id")); return actorRepository.findAll(pageable); } }
package com.smartup.manageorderapplication.services.impl; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.smartup.manageorderapplication.dto.ProductDto; import com.smartup.manageorderapplication.entities.Product; import com.smartup.manageorderapplication.repositories.ProductRepository; import com.smartup.manageorderapplication.services.ProductService; import com.smartup.manageorderapplication.utils.mappers.ProductMapper; @Service public class ProductServiceImpl implements ProductService{ private ProductRepository productRepository; private ProductMapper productMapper; public ProductServiceImpl(ProductRepository repository, ProductMapper mapper) { this.productRepository=repository; this.productMapper=mapper; } @Override @Transactional(readOnly = false) public ProductDto createProduct(ProductDto inDto) { inDto.setId(null); Product entity = productRepository.save(productMapper.dto2Entity(inDto)); return productMapper.entity2Dto(entity); } }
package cn.com.ykse.santa.service.impl; import cn.com.ykse.santa.repository.dao.*; import cn.com.ykse.santa.repository.entity.FileDO; import cn.com.ykse.santa.repository.entity.RequirementDO; import cn.com.ykse.santa.repository.entity.RequirementDemandCfgDO; import cn.com.ykse.santa.repository.entity.RequirementFileCfgDO; import cn.com.ykse.santa.repository.pagination.Page; import cn.com.ykse.santa.service.FileService; import cn.com.ykse.santa.service.RequirementService; import cn.com.ykse.santa.service.convertor.BaseConvertor; import cn.com.ykse.santa.service.enums.RequirementStatusEnum; import cn.com.ykse.santa.service.util.DateUtil; import cn.com.ykse.santa.service.vo.RequirementFileVO; import cn.com.ykse.santa.service.vo.RequirementVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by youyi on 2016/5/24. */ @Service public class RequirementServiceImpl implements RequirementService { @Autowired RequirementDOMapper requirementDOMapper; @Autowired RequirementFileCfgDOMapper requirementFileCfgDOMapper; @Autowired FileService fileService; @Autowired FileDOMapper fileDOMapper; @Autowired RequirementDemandCfgDOMapper requirementDemandCfgDOMapper; @Autowired DemandDOMapper demandDOMapper; @Override public List<RequirementVO> getEnableRequirements(Page page) { List<RequirementDO> dos=requirementDOMapper.selectAllUnfinished(page); if(page!=null){ int records=requirementDOMapper.countAllUnfinished(); page.setTotalRecords(records); page.setSearchedRecords(records); } return convertDemandVOList(dos); } private List<RequirementVO> convertDemandVOList(List<RequirementDO> dos){ List<RequirementVO> vos = new ArrayList<>(); for(RequirementDO dO : dos){ RequirementVO vo= BaseConvertor.convert(dO,RequirementVO.class); if(dO.getGmtModified()!=null){ vo.setGmtModified(DateUtil.formatDateTime(dO.getGmtModified())); } vo.setGmtExpected(DateUtil.formatDateOnly(dO.getGmtExpected())); vos.add(vo); } return vos; } @Override public List<RequirementVO> searchRequirementByTitle(String title, Page page) { List<RequirementDO> dos=requirementDOMapper.searchByTitle(title, page); if(page!=null){ page.setSearchedRecords(requirementDOMapper.countByTitle(title)); } return convertDemandVOList(dos); } @Override public RequirementVO getRequirementById(int requirementId) { RequirementDO dO= requirementDOMapper.selectByPrimaryKey(requirementId); if(dO!=null){ RequirementVO vo= BaseConvertor.convert(dO,RequirementVO.class); vo.setGmtExpected(DateUtil.formatDateOnly(dO.getGmtExpected())); vo.setGmtCreate(DateUtil.formatDateOnly(dO.getGmtCreate())); vo.setGmtModified(DateUtil.formatDateTime(dO.getGmtModified())); return vo; }else{ return null; } } @Override public boolean updateRequirement(RequirementDO requirementDO) { String status=requirementDOMapper.selectStatusByPrimaryKey(requirementDO.getRequirementId()); if(RequirementStatusEnum.NOTPASS.getDescription().equals(status)){ requirementDO.setRequirementStatus(RequirementStatusEnum.TOESTIMATE.getDescription()); } int count=requirementDOMapper.updateByPrimaryKeySelective(requirementDO); return count>0?true:false; } @Override public boolean addRequirement(RequirementDO requirementDO) { int count=requirementDOMapper.insertSelective(requirementDO); return count>0?true:false; } @Override public boolean logicalRemoveRequirement(int requirementId) { return false; } @Override public List<RequirementVO> advancedSearchRequirement(RequirementDO requirementDO, String expectedDateStart, String expectedDateEnd, Page page) { List<RequirementVO> vos=new ArrayList<>(); if(requirementDO!=null){ Date expStart=null,expEnd=null; if(expectedDateStart!=null && expectedDateEnd!=null){ expStart=DateUtil.parseDateTime(expectedDateStart); expEnd=DateUtil.parseDateTime(expectedDateEnd); } List<RequirementDO> dos=requirementDOMapper.searchSelective(requirementDO,expStart,expEnd,page); if(page!=null){ page.setSearchedRecords(requirementDOMapper.countSelective(requirementDO,expStart,expEnd)); } vos=convertDemandVOList(dos); } return vos; } @Override public boolean addRequirementFile(RequirementFileVO requirementFile) { RequirementFileCfgDO cfgDO=BaseConvertor.convert(requirementFile, RequirementFileCfgDO.class); int count=requirementFileCfgDOMapper.insert(cfgDO); return count>0?true:false; } @Override public boolean addRequirementFiles(List<MultipartFile> files, int requirementId, String uploader) { boolean isSuccess=false; for(MultipartFile file :files){ int fileId=fileService.saveFileAndReturnFileId(file,uploader); if(fileId!=0){ RequirementFileVO vo=new RequirementFileVO(); vo.setRequirementId(requirementId); vo.setFileId(fileId); isSuccess=addRequirementFile(vo); if(!isSuccess){ return isSuccess; } }else{ return isSuccess; } } return isSuccess; } @Override public List<RequirementFileVO> getRequirementFilesByRequirementId(int requirementId) { List<FileDO> dos=requirementFileCfgDOMapper.selectFilesByRequirementId(requirementId); List<RequirementFileVO> vos=new ArrayList<>(); for(FileDO dO : dos){ RequirementFileVO vo = BaseConvertor.convert(dO,RequirementFileVO.class); vo.setGmtCreate(DateUtil.formatDateTime(dO.getGmtCreate())); vos.add(vo); } return vos; } @Override public boolean removeRelatedFileForRequirement(int requirementId) { List<Integer> ids=requirementFileCfgDOMapper.selectFileIdListByRequirementId(requirementId); if(ids.size()>0){ int count=requirementFileCfgDOMapper.deleteFilesForRequirement(requirementId); if(count>0){ count=fileDOMapper.logicalRemove(ids); return count>0?true:false; } } return true; } @Override public void removeRelatedDemandForRequirement(int requirementId) { int count=requirementDemandCfgDOMapper.deleteByRequirementId(requirementId); } @Override public List<RequirementVO> getUnclaimedRequirements(Page page) { List<RequirementVO> vos=new ArrayList<>(); List<RequirementDO> dos=requirementDOMapper.selectRequirementsByStatus(RequirementStatusEnum.NEW.getDescription(),page); if(page!=null){ int records=requirementDOMapper.countRequirementByStatus(RequirementStatusEnum.NEW.getDescription()); page.setTotalRecords(records); page.setSearchedRecords(records); } return convert2RequirementVOList(dos); } @Override public boolean acceptRequirementsById(List<Integer> ids,String pd) { int count=requirementDOMapper.updateBatchNewRequirement(ids,pd); return count>0 ? true : false; } @Override public List<RequirementVO> getRequirementsForHandling(String self) { List<String> unhandledStatusList=new ArrayList<String>(); unhandledStatusList.add(RequirementStatusEnum.TOESTIMATE.getDescription()); unhandledStatusList.add(RequirementStatusEnum.TODO.getDescription()); List<RequirementDO> dos=requirementDOMapper.selectEnableRequirementsForHandling(self, unhandledStatusList); return convert2RequirementVOList(dos); } @Override public boolean estimateRequirement(int requirementId, RequirementStatusEnum statusEnum, String modifier) { RequirementDO dO=new RequirementDO(); dO.setRequirementId(requirementId); dO.setRequirementStatus(statusEnum.getDescription()); dO.setModifier(modifier); int count=requirementDOMapper.updateByPrimaryKeySelective(dO); return count>0?true:false; } @Override public boolean associateDemandsToRequirement(int requirementId, String[] demandIds) { List<RequirementDemandCfgDO> dos=new ArrayList<>(); for(String demandId : demandIds){ RequirementDemandCfgDO dO=new RequirementDemandCfgDO(); dO.setRequirementId(requirementId); dO.setDemandId(Integer.parseInt(demandId)); dos.add(dO); } int count=requirementDemandCfgDOMapper.insertBatch(dos); return count>0?true:false; } @Override public boolean updateRequirementStatus(int requirementId, RequirementStatusEnum statusEnum) { RequirementDO dO=new RequirementDO(); dO.setRequirementId(requirementId); dO.setRequirementStatus(statusEnum.getDescription()); int count=requirementDOMapper.updateByPrimaryKeySelective(dO); return count>0?true:false; } @Override public List<RequirementVO> getDemandRequirements(int demandId) { List<RequirementDO> dos = requirementDOMapper.selectRequirementsForDemand(demandId); return convert2RequirementVOList(dos); } @Override public String getRequirementCreator(int requirementId) { return requirementDOMapper.selectCreatorByPrimaryKey(requirementId); } @Override public boolean logicalRemove(int requirementId) { int count=requirementDOMapper.unableRequirement(requirementId); return count>0?true:false; } @Override public void changeStatusToDoingByDemandIds(List<Integer> demandIds) { int count=requirementDOMapper.updateStatusToDoingInBatch(demandIds); } // @Override // public void finalizeRequirementAfterPrjPublish(int prjId) { // List<Integer> reqIds=requirementDemandCfgDOMapper.selectRequirementIdsByPrjId(prjId); // for(Integer id : reqIds){ // int count=demandDOMapper.countNotFinishedDemandInRequirement(id); // if(count==0){ // requirementDOMapper.updateStatusByPrimaryKey(id,RequirementStatusEnum.DONE.getDescription()); // } // } // } @Override public boolean unassociateDemandFromRequirement(int requirementId, int demandId) { RequirementDemandCfgDO dO=new RequirementDemandCfgDO(); dO.setRequirementId(requirementId); dO.setDemandId(demandId); int count = requirementDemandCfgDOMapper.deleteByRequirementDemandSelective(dO); return count>0 ? true:false; } @Override public boolean containsDemand(int requirementId) { int count=requirementDemandCfgDOMapper.countDemandForRequirement(requirementId); return count>0 ? true:false; } @Override public boolean finalizeRequirement(int requirementId, String reason) { int count = requirementDOMapper.updateStatusToDone(requirementId,reason); return count>0 ? true:false; } private List<RequirementVO> convert2RequirementVOList(List<RequirementDO> dos){ List<RequirementVO> vos = new ArrayList<>(); for(RequirementDO dO : dos){ RequirementVO vo=BaseConvertor.convert(dO,RequirementVO.class); if(dO.getGmtCreate()!=null){ vo.setGmtCreate(DateUtil.formatDateTime(dO.getGmtCreate())); } if(dO.getGmtModified()!=null){ vo.setGmtModified(DateUtil.formatDateTime(dO.getGmtModified())); } vo.setGmtExpected(DateUtil.formatDateOnly(dO.getGmtExpected())); vos.add(vo); } return vos; } }
package org.motechproject.server.model.db.hibernate.rct; import org.hibernate.Criteria; import org.hibernate.SessionFactory; import org.hibernate.classic.Session; import org.hibernate.criterion.Restrictions; import org.motechproject.server.model.db.RctDAO; import org.motechproject.server.model.rct.PhoneOwnershipType; import org.motechproject.server.model.rct.RCTFacility; import org.motechproject.server.model.rct.RCTPatient; import org.motechproject.server.model.rct.Stratum; import org.motechproject.ws.rct.PregnancyTrimester; import java.util.List; public class HibernateRctDAO implements RctDAO { private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Stratum stratumWith(RCTFacility facility, PhoneOwnershipType phoneOwnershipType, PregnancyTrimester trimester) { Session session = sessionFactory.getCurrentSession(); Criteria criteria = session.createCriteria(Stratum.class, "s"); criteria.add(Restrictions.eq("s.phoneOwnership", phoneOwnershipType)); criteria.add(Restrictions.eq("s.pregnancyTrimester", trimester)); criteria.add(Restrictions.eq("s.facility", facility)); criteria.add(Restrictions.eq("s.isActive", true)); return (Stratum) criteria.uniqueResult(); } public RCTPatient saveRCTPatient(RCTPatient patient) { Session session = sessionFactory.getCurrentSession(); session.saveOrUpdate(patient); return patient; } public Stratum updateStratum(Stratum stratum) { Session session = sessionFactory.getCurrentSession(); session.saveOrUpdate(stratum); return stratum; } public Boolean isPatientRegisteredIntoRCT(Integer motechId) { Session session = sessionFactory.getCurrentSession(); Criteria criteria = session.createCriteria(RCTPatient.class); criteria.add(Restrictions.eq("studyId", motechId.toString())); List list = criteria.list(); return list.size() == 1; } public RCTFacility getRCTFacility(Integer facilityId) { Session session = sessionFactory.getCurrentSession(); Criteria criteria = session.createCriteria(RCTFacility.class); criteria.add(Restrictions.eq("facility.facilityId", facilityId)); criteria.add(Restrictions.eq("active",true)); List results = criteria.list(); return results.size() > 0 ? (RCTFacility) results.get(0) : null; } public RCTPatient getRCTPatient(Integer motechId) { Session currentSession = sessionFactory.getCurrentSession(); Criteria criteria = currentSession.createCriteria(RCTPatient.class); criteria.add(Restrictions.eq("studyId", motechId.toString())); return (RCTPatient) criteria.uniqueResult(); } public List<RCTPatient> getAllRCTPatients() { Session currentSession = sessionFactory.getCurrentSession(); Criteria criteria = currentSession.createCriteria(RCTPatient.class); return criteria.list(); } }
package main; /** * @author KOUASSI Yves Anselme Magloire * @version 13/01/2018 */ import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; /** * Cette classe correspond a un Compte distant. Elle permet aux clients * d'effectuer un depot , un retrait, ou consulter leur solde. * Elle implemente l'interface Compte. */ public class CompteDistant extends UnicastRemoteObject implements Compte{ /** * */ private static final long serialVersionUID = 1L; private double solde ; protected CompteDistant() throws RemoteException { // TODO Auto-generated constructor stub //super(); solde=0; } @Override public synchronized boolean retrait(double montant) throws RemoteException { // TODO Auto-generated method stub if ((solde - montant)>=0) { solde -= montant; return true; } else return false; } @Override public synchronized boolean depot(double montant) throws RemoteException { // TODO Auto-generated method stub try{ try { Thread.sleep(20000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } solde += montant; return true; }catch(Exception e) { return false; } } @Override public double getSolde() throws RemoteException { // TODO Auto-generated method stub return solde; } }
package com.tencent.mm.plugin.appbrand.task; import android.os.Parcel; import android.os.Parcelable.Creator; class AppBrandRemoteTaskController$2 implements Creator<AppBrandRemoteTaskController> { AppBrandRemoteTaskController$2() { } public final /* synthetic */ Object createFromParcel(Parcel parcel) { AppBrandRemoteTaskController appBrandRemoteTaskController = new AppBrandRemoteTaskController(); appBrandRemoteTaskController.g(parcel); return appBrandRemoteTaskController; } public final /* bridge */ /* synthetic */ Object[] newArray(int i) { return new AppBrandRemoteTaskController[i]; } }
package com.kh.runLearn.board.model.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.kh.runLearn.board.model.vo.Board; import com.kh.runLearn.board.model.vo.Board_Image; import com.kh.runLearn.common.PageInfo; @Repository("bDAO") public class BoardDAO { @Autowired private SqlSessionTemplate sqlSession; public int getListCount(String b_category) { return sqlSession.selectOne("boardMapper.getListCount", b_category); } public ArrayList<Board> selectBoardList(PageInfo pi, String b_category) { int offset = (pi.getCurrentPage() - 1) * pi.getBoardLimit(); RowBounds rowBounds = new RowBounds(offset, pi.getBoardLimit()); return (ArrayList) sqlSession.selectList("boardMapper.selectBoardList", b_category, rowBounds); } public void addReadCount(int b_num) { sqlSession.update("boardMapper.updateCount", b_num); } public Board selectBoard(int b_num) { return sqlSession.selectOne("boardMapper.selectBoard", b_num); } public int insertBoard(Board b) { return sqlSession.insert("boardMapper.insertBoard", b); } public int deleteBoard(int b_num) { return sqlSession.update("boardMapper.deleteBoard", b_num); } public int updateBoard(Board b) { return sqlSession.update("boardMapper.updateBoard", b); } public int insertBoard_Image(Board_Image bi) { return sqlSession.insert("boardMapper.insertBoardImg", bi); } public String selectBoardImg(Board b) { return sqlSession.selectOne("boardMapper.selectBoardImg", b.getB_num()); } public int updateBoard_Image(Board_Image bi) { return sqlSession.update("boardMapper.updateBoardImg", bi); } public int deleteBoard_Image(Board_Image bi) { return sqlSession.delete("boardMapper.deleteBoardImg", bi); } /* ---------------고객센터용--------------- */ public ArrayList<HashMap<String, String>> selectCenterBoardList(Map<String, Object> map) { PageInfo pi = (PageInfo) map.get("pi"); int offset = (pi.getCurrentPage() - 1) * pi.getBoardLimit(); RowBounds rowBounds = new RowBounds(offset, pi.getBoardLimit()); return (ArrayList) sqlSession.selectList("boardMapper.selectCenterBoardList", map, rowBounds); } public int getCenterListCount(Map<String, Object> map) { return sqlSession.selectOne("boardMapper.getCenterListCount", map); } /* ---------------마이페이지용--------------- */ public Board selectBoardTutor(String userId) { return sqlSession.selectOne("boardMapper.selectBoardTutor", userId); } }
package com.cn.my.service; import com.cn.my.bean.User; import java.util.Map; public interface IUserService { public Map<String, Object> findAllUser(int page,int rows,User user); public void insertUser(User user); public User findUserbyUsername(String username); public int isExistUser(User user); }
package com.ccxia.cbcraft.item; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.ccxia.cbcraft.CbCraft; import com.ccxia.cbcraft.creativetab.CreativeTabsCbCraft; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemBucketMilk; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.stats.StatList; import net.minecraft.world.World; public class ItemHotChocolate extends ItemBucketMilk { public ItemHotChocolate() { this.setUnlocalizedName(CbCraft.MODID + ".hotChocolate"); this.setRegistryName("chocolate_milk"); this.setMaxStackSize(16); this.setCreativeTab(CreativeTabsCbCraft.tabCbCraft); } public ItemStack onItemUseFinish(ItemStack stack, World worldIn, EntityLivingBase entityLiving) { if (!worldIn.isRemote) this.removeBadPotion(stack, entityLiving); if (entityLiving instanceof EntityPlayerMP) { EntityPlayerMP entityplayermp = (EntityPlayerMP) entityLiving; CriteriaTriggers.CONSUME_ITEM.trigger(entityplayermp, stack); entityplayermp.addStat(StatList.getObjectUseStats(this)); } if (entityLiving instanceof EntityPlayer && !((EntityPlayer) entityLiving).capabilities.isCreativeMode) { stack.shrink(1); } return stack.isEmpty() ? new ItemStack(Items.AIR) : stack; } // 移除所有负面效果 public void removeBadPotion(ItemStack stack, EntityLivingBase entityLiving) { if (entityLiving.world.isRemote) return; List<Potion> badPotion = new ArrayList<Potion>(); Iterator<PotionEffect> iterator = entityLiving.getActivePotionMap().values().iterator(); while (iterator.hasNext()) { PotionEffect effect = iterator.next(); if (effect.getPotion().isBadEffect()) { badPotion.add(effect.getPotion()); } } for (Potion potion : badPotion) { entityLiving.removePotionEffect(potion); } } }
package com.tencent.mm.ui.chatting; import android.graphics.Color; import android.graphics.PorterDuff.Mode; import android.graphics.drawable.Drawable; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; import com.tencent.mm.plugin.game.gamewebview.jsapi.biz.b; public class q$a implements OnTouchListener { private int pN; public q$a() { this(Color.argb(b.CTRL_BYTE, 136, 136, 136)); } private q$a(int i) { this.pN = i; } public final boolean onTouch(View view, MotionEvent motionEvent) { Drawable drawable; int action = motionEvent.getAction(); if (view instanceof ImageView) { drawable = ((ImageView) view).getDrawable(); } else { drawable = view.getBackground(); } if (drawable != null) { if (action == 0) { drawable.setColorFilter(this.pN, Mode.MULTIPLY); } else if (action == 3 || action == 1) { drawable.clearColorFilter(); } } return false; } }
package tech.chazwarp923.unifieditems.crafting; import java.util.Map; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import tech.chazwarp923.unifieditems.item.UIItemIngot; import tech.chazwarp923.unifieditems.item.UIItems; import tech.chazwarp923.unifieditems.material.Material; import tech.chazwarp923.unifieditems.tools.RecipeJsonHelper; public class Shaped { public static void init() { //Adds the recipe for the "Mortar and Pestle" RecipeJsonHelper.addShapedRecipe(new ItemStack(UIItems.mortarAndPestle), new Object[] { "BC", 'B', Items.BOWL, 'C', "cobblestone" }); RecipeJsonHelper.addShapedRecipe(new ItemStack(UIItems.mortarAndPestle), new Object[] { "BC", 'B', Items.BOWL, 'C', "blockCobblestone" }); //Adds the recipes for the gears for(Map.Entry<Material, UIItemIngot> item : UIItems.ingots.entrySet()) { RecipeJsonHelper.addShapedRecipe(new ItemStack(UIItems.gears.get(item.getKey()), 1), new Object[] { "SIS", "I I", "SIS", 'S', "stickWood", 'I', item.getValue() }); } RecipeJsonHelper.addShapedRecipe(new ItemStack(UIItems.gears.get(Material.IRON), 1), new Object[] { "SIS", "I I", "SIS", 'S', "stickWood", 'I', Items.IRON_INGOT }); RecipeJsonHelper.addShapedRecipe(new ItemStack(UIItems.gears.get(Material.GOLD), 1), new Object[] { "SIS", "I I", "SIS", 'S', "stickWood", 'I', Items.GOLD_INGOT }); //Adds the recipes for the plates for(Map.Entry<Material, UIItemIngot> item : UIItems.ingots.entrySet()) { RecipeJsonHelper.addShapedRecipe(new ItemStack(UIItems.plates.get(item.getKey()), 4), new Object[] { "II", "II", 'I', item.getValue() }); } RecipeJsonHelper.addShapedRecipe(new ItemStack(UIItems.plates.get(Material.IRON), 4), new Object[] { "II", "II", 'I', Items.IRON_INGOT }); RecipeJsonHelper.addShapedRecipe(new ItemStack(UIItems.plates.get(Material.GOLD), 4), new Object[] { "II", "II", 'I', Items.GOLD_INGOT }); } }
package pl.kfeed.gallerywithmusicplayer.ui.gallery.adapter; import android.content.Context; import android.database.Cursor; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife; import pl.kfeed.gallerywithmusicplayer.R; public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.GalleryViewHolder> { private static final String TAG = GalleryAdapter.class.getSimpleName(); private Context mContext; private Cursor mThumbImageCursor; private OnPhotoClick mListener; public GalleryAdapter(Context context, Cursor thumbImageCursor, OnPhotoClick listener) { mThumbImageCursor = thumbImageCursor; mContext = context; mListener = listener; } @Override public GalleryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_view_holder, null); return new GalleryViewHolder(view); } @Override public void onBindViewHolder(GalleryViewHolder holder, int position) { mThumbImageCursor.moveToPosition(position); if (mThumbImageCursor.getString(0) == null) { Picasso.with(mContext) .load("file://" + mThumbImageCursor.getString(6)) .fit() .centerCrop() .placeholder(R.drawable.rick) .into(holder.image); } else { Picasso.with(mContext) .load("file://" + mThumbImageCursor.getString(0)) .fit() .centerCrop() .placeholder(R.drawable.rick) .into(holder.image); } } public void updateCursor(Cursor newImageThumbCursor) { mThumbImageCursor = newImageThumbCursor; notifyDataSetChanged(); } @Override public int getItemCount() { return mThumbImageCursor.getCount(); } public interface OnPhotoClick { void showPhotoPopup(int position); } public class GalleryViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.galleryViewHolderThumbnail) ImageView image; public GalleryViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); itemView.setOnClickListener(view -> { Log.d(TAG, "Item clicked on position: " + getAdapterPosition()); mListener.showPhotoPopup(getAdapterPosition()); }); } } }
package com.czm.cloudocr.model; public class HistoryResult { private String id; private String imgText; private String date; private String imgPath; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getImgText() { return imgText; } public void setImgText(String imgText) { this.imgText = imgText; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getImgPath() { return imgPath; } public void setImgPath(String imgPath) { this.imgPath = imgPath; } @Override public String toString() { return "HistoryResult{" + "id=" + id + ", imgText='" + imgText + '\'' + ", date='" + date + '\'' + ", imgPath='" + imgPath + '\'' + '}'; } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.cmsitems; import de.hybris.platform.core.model.type.AttributeDescriptorModel; import java.util.function.Function; /** * This interface is used to transform an attribute, described by its {@link de.hybris.platform.core.model.type.AttributeDescriptorModel}, * leveraging a transformation function. * * This interface can be useful to transform lists or other types of collections. * * @param <T> the type of the attribute to convert. * @param <S> the type of the output to produce. */ @FunctionalInterface public interface AttributeValueToRepresentationConverter<T, S> { /** * Converts an item of type {@code T}, described by the provided {@link de.hybris.platform.core.model.type.AttributeDescriptorModel}, * into a new object of type {@code S} by applying the provided transformation function. * * This function can be useful to transform lists or other types of collections, where the transformation function has to be applied * individually to each element of the collection. * * @param attribute A model describing the attribute * @param item The item to convert * @param transformationFunction Function that will be used to transform the provided item. * @return an instance of {@code S}, converted from {@code T} by leveraging the provided transformationFunction. */ S convert(AttributeDescriptorModel attribute, T item, Function<Object, Object> transformationFunction); }
package com.rectus29.nimmt.entities; import com.rectus29.nimmt.report.SceneReport; import com.sun.istack.internal.NotNull; public class CardPayLoad extends PayLoad implements Comparable<CardPayLoad>{ private Card card; public CardPayLoad(@NotNull Player player, @NotNull Card card) { super(player); this.card = card; } public Card getCard() { return card; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CardPayLoad)) return false; CardPayLoad payLoad = (CardPayLoad) o; return player != null ? player.equals(payLoad.player) : payLoad.player == null; } @Override public int hashCode() { return player != null ? player.hashCode() : 0; } @Override public int compareTo(CardPayLoad o) { if(this.getCard().getValue() < o.getCard().getValue()){ return -1; }else if(this.getCard().getValue() > o.getCard().getValue()){ return 1; } return 0; } @Override public SceneReport act(Scene scene) { return scene.addCard(getCard()); } }
package app.rule; public interface Rule <T> { /** * @param data element that should be tested * @return factor of factor of similarity data with something, 0 means elements are completely different, 1 is equal */ double test(T data); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.gossip.protocol.json; import org.apache.gossip.model.Base; import org.apache.gossip.udp.Trackable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Objects; /* * Here is a test class for serialization. I've tried to include a lot of things in it including nested classes. * Note that there are no Jackson annotations. * getters and setters are the keys to making this work without the Jackson annotations. */ class TestMessage extends Base implements Trackable { private String unique; private String from; private String uuid; private String derivedField; private Subclass otherThing; private float floatValue; private double doubleValue; private Object[] arrayOfThings; private Map<String, String> mapOfThings = new HashMap<>(); @SuppressWarnings("unused")//Used by ObjectMapper private TestMessage() { } TestMessage(String unique) { this.unique = unique; from = Integer.toHexString(unique.hashCode()); uuid = Integer.toHexString(from.hashCode()); derivedField = Integer.toHexString(uuid.hashCode()); otherThing = new Subclass(Integer.toHexString(derivedField.hashCode())); floatValue = (float) unique.hashCode() / (float) from.hashCode(); doubleValue = (double) uuid.hashCode() / (double) derivedField.hashCode(); arrayOfThings = new Object[]{ this.unique, from, uuid, derivedField, otherThing, floatValue, doubleValue }; String curThing = unique; for (int i = 0; i < 100; i++) { String key = Integer.toHexString(curThing.hashCode()); String value = Integer.toHexString(key.hashCode()); curThing = value; mapOfThings.put(key, value); } } @Override public String getUriFrom() { return from; } @Override public void setUriFrom(String uriFrom) { this.from = uriFrom; } @Override public String getUuid() { return uuid; } @Override public void setUuid(String uuid) { this.uuid = uuid; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TestMessage)) return false; TestMessage that = (TestMessage) o; return Objects.equals(unique, that.unique) && Objects.equals(from, that.from) && Objects.equals(getUuid(), that.getUuid()) && Objects.equals(derivedField, that.derivedField) && Objects.equals(floatValue, that.floatValue) && Objects.equals(doubleValue, that.doubleValue) && Arrays.equals(arrayOfThings, that.arrayOfThings) && Objects.equals(mapOfThings, that.mapOfThings); } public String getUnique() { return unique; } public void setUnique(String unique) { this.unique = unique; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getDerivedField() { return derivedField; } public void setDerivedField(String derivedField) { this.derivedField = derivedField; } public Subclass getOtherThing() { return otherThing; } public void setOtherThing(Subclass otherThing) { this.otherThing = otherThing; } public float getFloatValue() { return floatValue; } public void setFloatValue(float floatValue) { this.floatValue = floatValue; } public double getDoubleValue() { return doubleValue; } public void setDoubleValue(double doubleValue) { this.doubleValue = doubleValue; } public Object[] getArrayOfThings() { return arrayOfThings; } public void setArrayOfThings(Object[] arrayOfThings) { this.arrayOfThings = arrayOfThings; } public Map<String, String> getMapOfThings() { return mapOfThings; } public void setMapOfThings(Map<String, String> mapOfThings) { this.mapOfThings = mapOfThings; } @Override public int hashCode() { return Objects.hash(unique, getUriFrom(), getUuid(), derivedField, floatValue, doubleValue, arrayOfThings, mapOfThings); } static class Subclass { private String thing; public Subclass() { } public Subclass(String thing) { this.thing = thing; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Subclass)) return false; Subclass subclass = (Subclass) o; return Objects.equals(thing, subclass.thing); } @Override public int hashCode() { return Objects.hash(thing); } public String getThing() { return thing; } } }
package it.polimi.ingsw.GC_21.CONTROLLER; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StringWriter; import java.util.ArrayList; import java.util.Random; import javax.annotation.Resource; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import it.polimi.ingsw.GC_21.GAMECOMPONENTS.DevCardType; import it.polimi.ingsw.GC_21.GAMECOMPONENTS.DevelopmentCard; import it.polimi.ingsw.GC_21.GAMEMANAGEMENT.Game; import it.polimi.ingsw.GC_21.PLAYER.Player; import it.polimi.ingsw.GC_21.VIEW.RemoteView; public class ControllerManager { private ArrayList<Controller> controllers; private ArrayList<RemoteView> remoteViews; private ArrayList<Game> gamesInLobby; private ArrayList<Game> activeGames; private ArrayList<Game> savedGames; private JSONParser parser = new JSONParser(); public ControllerManager() { controllers = new ArrayList<Controller>(); gamesInLobby = new ArrayList<Game>(); remoteViews = new ArrayList<RemoteView>(); activeGames = new ArrayList<Game>(); savedGames = new ArrayList<Game>(); loadSavedGames(); } private void loadSavedGames() { try { File[] files = new File("src/main/resources/savedgames").listFiles(); for (File file : files) { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); Game game = (Game) ois.readObject(); savedGames.add(game); ois.close(); } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } public ArrayList<Controller> getControllers() { return controllers; } public synchronized Game createGame(Controller controller) { String host = controller.getRemoteView().getUsername(); Game game = new Game(host); controllers.add(controller); addGame(game); return game; } public ArrayList<RemoteView> getRemoteViews() { return remoteViews; } public void addRemoteView(RemoteView remoteView) { remoteViews.add(remoteView); } public ArrayList<Game> getGames() { return gamesInLobby; } public synchronized void addGame(Game game) { gamesInLobby.add(game); } public synchronized boolean gameReconnection(String user) { for (int i = 0; i < activeGames.size(); i++) { ArrayList<Player> players = activeGames.get(i).getPlayers(); for (int j = 0; j < players.size(); j++) { if (user.equals(players.get(j).getName())) { return true; } } } return false; } public synchronized boolean gameSavedReconnection(String user) { for (int i = 0; i < savedGames.size(); i++) { if (!activeGames.contains(savedGames.get(i))) {//I cannot load a game which is already active ArrayList<Player> players = savedGames.get(i).getPlayers(); for (int j = 0; j < players.size(); j++) { if (user.equals(players.get(j).getName())) { return true; } } } } return false; } public synchronized void saveGame(Game game) { game.setNumberOfPlayersActuallyPresent(0); savedGames.add(game); try { Random random = new Random(); int gameNumber = random.nextInt(100000); File file = new File("src/main/resources/savedgames/" + gameNumber + game.getHost() + ".ser"); game.setAssociatedFile(file); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fileOutputStream); oos.writeObject(game); oos.close(); } catch (IOException e) { e.printStackTrace(); } } public synchronized boolean Login(String user, String psw, Boolean insert) throws FileNotFoundException, IOException, ParseException { Object obj = parser.parse(new FileReader("Users.json")); JSONObject users = (JSONObject) obj; JSONArray usersarray= (JSONArray) users.get("users"); for (Object o : usersarray) { JSONObject jsonLineItem = (JSONObject) o; if(user.equals(jsonLineItem.get("name").toString())){ if (psw.equals(jsonLineItem.get("psw").toString()) && !insert) { return true; } else { return false; } } } if(insert) { JSONObject objec = new JSONObject(); JSONObject jsonObj = new JSONObject(); jsonObj.put("name", user.toString()); jsonObj.put("psw", psw.toString()); jsonObj.put("VictoryPoints", 0); jsonObj.put("numberOfWins", 0); usersarray.add(jsonObj); objec.put("users", usersarray); File file = new File("Users.json"); file.createNewFile(); FileWriter filewriter = new FileWriter(file); try { filewriter.write(objec.toJSONString()); filewriter.flush(); filewriter.close(); } catch (IOException e) { e.printStackTrace(); } return true; } return false; } public synchronized RemoteView getMyActiveRemoteView(String username) { for (int i = 0; i < remoteViews.size(); i++) { if (remoteViews.get(i).getUsername().equals(username)) { return remoteViews.get(i); } } return null;//it should not } public ArrayList<Game> getActiveGames() { return activeGames; } public void setActiveGames(ArrayList<Game> activeGames) { this.activeGames = activeGames; } public ArrayList<Game> getSavedGames() { return savedGames; } public void setSavedGames(ArrayList<Game> savedGames) { this.savedGames = savedGames; } public synchronized Game getMySavedGame(String username) { for (int i = 0; i < savedGames.size(); i++) { ArrayList<Player> players = savedGames.get(i).getPlayers(); for (int j = 0; j < players.size(); j++) { if (username.equals(players.get(j).getName())) { File[] files = new File("src/main/resources/savedgames").listFiles(); for (File file : files) { if(file.getName().equals(savedGames.get(i).getAssociatedFile().getName())) { file.delete(); } } return savedGames.get(i); } } } return null;//if I return null here there are some problems before } }
public class IncrementDecrement2 { public static void main(String[] args) { int i = 0; int number = 0; number = i++; // 相当于number = i; i = i + 1; System.out.println(number); number = i--; // 相当于 number = i; i = i - 1; System.out.println(number); } }
package Flonx8; /** * @Auther:Flonx * @Date:2021/1/11 - 01 - 11 - 20:23 * @Description: Flonx8 * @Version: 1.0 */ public class Test { public static void main(String[] args) { // create a Student class Student stu1 = new Student(); stu1.setName("nana"); stu1.setAge(19); stu1.setSex("女"); System.out.println(stu1.getName()); System.out.println(stu1.getAge()); System.out.println(stu1.getSex()); Student stu2 = new Student(18,"Flonx","男"); System.out.println(stu2.getName()); System.out.println(stu2.getAge()); System.out.println(stu2.getSex()); } }
/** * */ package alg.code123; /** * <a href= * "http://www.code123.cc/749.html">题目:写一个函数处理一个MxN的矩阵,如果矩阵中某个元素为0,那么把它所在的行和列都置为0.</a> * * @title MatrixSetZero */ public class MatrixSetZero { public void setZero(int[][] a, int n, int m) { } }
/* * @version 1.0 * @author PSE group */ package kit.edu.pse.goapp.server.converter.daos; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import kit.edu.pse.goapp.server.daos.GPS_DAO; import kit.edu.pse.goapp.server.daos.GpsDaoImpl; import kit.edu.pse.goapp.server.datamodels.GPS; import kit.edu.pse.goapp.server.exceptions.CustomServerException; /** * GPS Dao converter */ public class GpsDaoConverter implements DaoConverter<GPS_DAO> { /** * Converts GPS json string to GPS dao * * @param jsonString * JsonString * @return dao GPS dao * @throws CustomServerException * CustomServerException */ @Override public GPS_DAO parse(String jsonString) throws CustomServerException { if (jsonString == null) { return null; } GPS gpsJsonObject = null; try { Gson gson = new Gson(); gpsJsonObject = gson.fromJson(jsonString, GPS.class); } catch (Exception e) { throw new CustomServerException("The JSON-String is not correct!", HttpServletResponse.SC_BAD_REQUEST); } GpsDaoImpl dao = new GpsDaoImpl(); dao.setGps(gpsJsonObject); return dao; } }
package com.app.servletcontext; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class MyServletContext */ public class MyServletContext extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyServletContext() { super(); // TODO Auto-generated constructor stub } /** * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException { // way1 to read context param ServletContext context = config.getServletContext(); String val = context.getInitParameter("mydata"); System.out.println("From init : "+val); } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //way2 to read context param ServletContext sc= request.getServletContext(); String str = sc.getInitParameter("mydata"); System.out.println("From service: "+str); } }
package com.weixin.dto.message.resp; import com.weixin.dto.message.Image; /** * Created by White on 2017/2/27. */ public class RespImageMessage extends RespBaseMessage { private Image Image; public com.weixin.dto.message.Image getImage() { return Image; } public void setImage(com.weixin.dto.message.Image image) { Image = image; } }
package com.gmail.ivanytskyy.vitaliy.repository.impl; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import com.gmail.ivanytskyy.vitaliy.model.Group; import com.gmail.ivanytskyy.vitaliy.repository.GroupRepository; /* * JPA implementation of the {@link GroupRepository} interface. * @author Vitaliy Ivanytskyy */ @Repository("groupRepository") public class GroupRepositoryImpl implements GroupRepository { @PersistenceContext private EntityManager entityManager; @Override public Group create(Group group) { if(group.getId() == null){ entityManager.persist(group); }else{ entityManager.merge(group); } entityManager.flush(); return group; } @Override public Group findById(long id) { return entityManager.find(Group.class, id); } @SuppressWarnings("unchecked") @Override public List<Group> findByName(String name) { return entityManager.createQuery( "SELECT g FROM Group g WHERE g.name=:name") .setParameter("name", name) .getResultList(); } @SuppressWarnings("unchecked") @Override public List<Group> findAll() { return entityManager.createQuery( "SELECT g FROM Group g") .getResultList(); } @Override public boolean isExistsWithName(String name) { long result = (long) entityManager.createQuery( "SELECT COUNT(g) FROM Group g WHERE g.name=:name") .setParameter("name", name) .getSingleResult(); return result > 0; } @Override public void deleteById(long id) { Group group = findById(id); entityManager.remove(group); } }
package net.youzule.javase.concurrency.chapter05.app2; import org.junit.Test; public class AppTest { @Test public void test1(){ String idNumber = "410881199209055571"; String idNumber1 = idNumber.substring(0,14)+"****"; System.out.println(idNumber1); } }
package com.qq.wx.voice.embed.recognizer; public final class d { public String bgn; public String bgo; public String bgp; public String bgq; public String bgr; public String userName; public d(String str, String str2, String str3) { this.userName = str; this.bgn = str2; this.bgo = str3; } }
import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Main */ public class Main { public static void main(String[] args) { Theater theater = new Theater("AMC", 8, 12); // List<Theater.Seat> seatCopy = new ArrayList<>(theater.seats); // printList(seatCopy); // seatCopy.get(1).reserve(); // if(theater.reserveSeat("D12")) { // System.out.println("Please pay for D12"); // } else { // System.out.println("Seat already reserved"); // } // if(theater.reserveSeat("D12")) { // System.out.println("Please pay for D12"); // } else { // System.out.println("Seat already reserved"); // } // if(theater.reserveSeat("B13")) { // System.out.println("Please pay for B13"); // } else { // System.out.println("Seat already reserved"); // } // List<Theater.Seat> reverseSeats = new ArrayList<>(theater.getSeats()); // Collections.reverse(reverseSeats); // printList(reverseSeats); List<Theater.Seat> priceSeats = new ArrayList<>(theater.getSeats()); priceSeats.add(theater.new Seat("B00", 13.00)); priceSeats.add(theater.new Seat("A00", 13.00)); Collections.sort(priceSeats, Theater.PRICE_ORDER); printList(priceSeats); // Collections.shuffle(seatCopy); // System.out.println("Printing seatCopy"); // printList(seatCopy); // System.out.println("Printing theater.seats"); // printList(theater.seats); // Theater.Seat minSeat = Collections.min(seatCopy); // Theater.Seat maxSeat = Collections.max(seatCopy); // System.out.println("Min seat #" + minSeat.getSeatNumber() + " Max seat #" + maxSeat.getSeatNumber()); // sortList(seatCopy); // System.out.println("Printing sorted seatCopy"); // printList(seatCopy); } public static void printList(List<Theater.Seat> list) { for (Theater.Seat seat : list) { System.out.print(" " + seat.getSeatNumber() + " $" + seat.getPrice()); } System.out.println(); System.out.println("========================================="); } public static void sortList(List<? extends Theater.Seat> list) { for (int i = 0; i < list.size() - 1; i++) { for (int j = i + 1; j < list.size(); j++) { if (list.get(i).compareTo(list.get(j)) > 0) { Collections.swap(list, i, j); } } } } }
public class BuildArrayFromPermutation { public static int[] buildArray(int[] nums) { int[] res = new int[nums.length]; for (int i = 0;i< nums.length;i++){ res[i] = nums[nums[i]]; } return res; } public static void main(String[] args) { int[] nums = {5,0,1,2,3,4}; int[] res = buildArray(nums); for (int i =0;i< res.length;i++){ System.out.print(res[i] + " "); } } }
package com.usnschool; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; public class DBConnector { private static DBConnector connector = new DBConnector(); static DBConnector getDBconnector(){ return connector; } private Connection con; public DBConnector() { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/melon", "root", "1234"); System.out.println("db connected"); } catch (Exception e) { e.printStackTrace(); } } public void insertIntoSongDB(ArrayList<SongAddPanel.EachSong> eachsonglist, int currentnum){ String sql = null; for (int i = 0; i < eachsonglist.size(); i++) { PreparedStatement pstm = null; if(eachsonglist.get(i).getSongpath() != null){ sql = "insert into songtbl (albumnum, songname, songcontent, songblob)" + " values(?, ?, ?, ?)"; }else { sql = "insert into songtbl (albumnum, songname, songcontent)" + " values(?, ?, ?)"; } try { pstm = con.prepareStatement(sql); pstm.setInt(1, currentnum); pstm.setString(2, eachsonglist.get(i).getSongname()); pstm.setString(3, eachsonglist.get(i).getSongcontent()); if(eachsonglist.get(i).getSongpath() != null){ pstm.setBinaryStream(4, new FileInputStream(eachsonglist.get(i).getSongpath())); } pstm.execute(); } catch (Exception e) { e.printStackTrace(); }finally{ if(pstm !=null){ try { pstm.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } public void insertIntoDB(AlbumData albumdata){ PreparedStatement pstm =null; try { String sql = "insert into albumtbl (genre, singer, writer, writerrythm, relday, publisher, planner, introduce, imgstream, albumname) " + "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; pstm = con.prepareStatement(sql); pstm.setString(1, albumdata.getGenre()); pstm.setString(2, albumdata.getSinger()); pstm.setString(3, albumdata.getWriter()); pstm.setString(4, albumdata.getWriterrythm()); pstm.setString(5, albumdata.getRelday()); pstm.setString(6, albumdata.getPublisher()); pstm.setString(7, albumdata.getPlanner()); pstm.setString(8, albumdata.getIntroduce()); pstm.setBinaryStream(9, albumdata.getImgstream()); pstm.setString(10, albumdata.getAlbumname()); pstm.execute(); } catch (SQLException e) { e.printStackTrace(); }finally{ if(pstm !=null){ try { pstm.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public void updateAlbum(AlbumData albumdata){ String sql = "update albumtbl set genre= ?, singer=?, writer=?," + " writerrythm=?, relday=?, publisher=?, planner=?," + " introduce=?, imgstream=?,albumname=? where num = ?"; PreparedStatement pstm = null; try { pstm = con.prepareStatement(sql); pstm.setString(1, albumdata.getGenre()); pstm.setString(2, albumdata.getSinger()); pstm.setString(3, albumdata.getWriter()); pstm.setString(4, albumdata.getWriterrythm()); pstm.setString(5, albumdata.getRelday()); pstm.setString(6, albumdata.getPublisher()); pstm.setString(7, albumdata.getPlanner()); pstm.setString(8, albumdata.getIntroduce()); pstm.setBinaryStream(9, albumdata.getImgstream()); pstm.setString(10, albumdata.getAlbumname()); pstm.setInt(11, albumdata.getNum()); pstm.execute(); } catch (SQLException e) { e.printStackTrace(); }finally{ if(pstm !=null){ try { pstm.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public void updateAlbumNo(AlbumData albumdata){ String sql = "update albumtbl set genre= ?, singer=?, writer=?," + " writerrythm=?, relday=?, publisher=?, planner=?," + " introduce=?,albumname=? where num = ?"; PreparedStatement pstm = null; try { pstm = con.prepareStatement(sql); pstm.setString(1, albumdata.getGenre()); pstm.setString(2, albumdata.getSinger()); pstm.setString(3, albumdata.getWriter()); pstm.setString(4, albumdata.getWriterrythm()); pstm.setString(5, albumdata.getRelday()); pstm.setString(6, albumdata.getPublisher()); pstm.setString(7, albumdata.getPlanner()); pstm.setString(8, albumdata.getIntroduce()); pstm.setString(9, albumdata.getAlbumname()); pstm.setInt(10, albumdata.getNum()); pstm.execute(); } catch (SQLException e) { e.printStackTrace(); }finally{ if(pstm !=null){ try { pstm.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public int getAlbumCount(){ Statement st = null; ResultSet rs = null; String sql = "Select count(*) from albumtbl"; int count = 0; try { st = con.createStatement(); rs = st.executeQuery(sql); rs.next(); count = rs.getInt(0); } catch (SQLException e) { e.printStackTrace(); } finally{ if(st != null){ try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return count; } public ArrayList<AlbumData> getAlbumList(){ Statement st = null; ResultSet rs = null; String sql = "select * from albumtbl"; ArrayList<AlbumData> arrdata = new ArrayList<AlbumData>(); try { st = con.createStatement(); rs = st.executeQuery(sql); while(rs.next()){ AlbumData albumdata = new AlbumData(); albumdata.setNum(rs.getInt("num")); albumdata.setImgstream(rs.getBinaryStream("imgstream")); albumdata.setIntroduce(rs.getString("introduce")); albumdata.setGenre(rs.getString("genre")); albumdata.setPlanner(rs.getString("planner")); albumdata.setPublisher(rs.getString("publisher")); albumdata.setRelday(rs.getString("relday")); albumdata.setSinger(rs.getString("singer")); albumdata.setWriter(rs.getString("writer")); albumdata.setWriterrythm(rs.getString("writerrythm")); albumdata.setAlbumname(rs.getString("albumname")); arrdata.add(albumdata); } } catch (SQLException e) { e.printStackTrace(); }finally { if(st != null){ try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return arrdata; } public ArrayList<SongData> getSongDataList(int albumnum){ ArrayList<SongData> songdatalist = new ArrayList<>(); String sql = "select * from songtbl where albumnum = "+ albumnum; Statement st = null; ResultSet rs = null; try { st = con.createStatement(); rs = st.executeQuery(sql); while(rs.next()){ SongData songdata = new SongData(); songdata.setNum(rs.getInt("num")); songdata.setAlbumnum(rs.getInt("albumnum")); songdata.setSongname(rs.getString("songname")); songdata.setSongcontent(rs.getString("songcontent")); songdatalist.add(songdata); } } catch (SQLException e) { e.printStackTrace(); }finally { if(st != null){ try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return songdatalist; } public ArrayList<SongData> getSongDataList (){ Statement st = null; ResultSet rs = null; ArrayList<SongData> songdatalist = new ArrayList<>(); String sql = "select * from songtbl"; try { st = con.createStatement(); rs = st.executeQuery(sql); while(rs.next()){ SongData songdata = new SongData(); songdata.setNum(rs.getInt("num")); songdata.setSongname(rs.getString("songname")); songdata.setSongcontent(rs.getString("songcontent")); songdata.setAlbumnum(rs.getInt("albumnum")); songdata.setSongblob(rs.getBinaryStream("songblob")); songdatalist.add(songdata); System.out.println("songname " + rs.getString("songname")); } } catch (SQLException e) { e.printStackTrace(); }finally { if(st != null){ try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return songdatalist; } public void DeleteAlbumAndSong(int albumnum){ Statement st = null; String sql = "delete from albumtbl where num = "+ albumnum; String sql2 = "select * from songtbl where albumnum = " + albumnum; ResultSet rs = null; try { st = con.createStatement(); st.execute(sql); rs = st.executeQuery(sql2); ArrayList<Integer> numlist = new ArrayList<>(); while(rs.next()){ numlist.add(rs.getInt("num")); } for (int i = 0; i < numlist.size(); i++) { String delsql = "delete from songtbl where num = " + numlist.get(i); st.execute(delsql); } } catch (SQLException e) { e.printStackTrace(); }finally { if(st != null){ try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public void DeleteSong(int num){ Statement st = null; String sql = "delete from songtbl where num = "+ num; try { st = con.createStatement(); st.execute(sql); } catch (SQLException e) { e.printStackTrace(); }finally { if(st != null){ try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
package com.tencent.mm.plugin.walletlock.gesture.ui; import android.widget.Toast; import com.tencent.mm.ab.b; import com.tencent.mm.ab.l; import com.tencent.mm.ab.v.a; import com.tencent.mm.plugin.walletlock.a$g; class GestureGuardLogicUI$23 implements a { final /* synthetic */ GestureGuardLogicUI pHr; GestureGuardLogicUI$23(GestureGuardLogicUI gestureGuardLogicUI) { this.pHr = gestureGuardLogicUI; } public final int a(int i, int i2, String str, b bVar, l lVar) { GestureGuardLogicUI.b(this.pHr); GestureGuardLogicUI.d(this.pHr); if (i2 == 0) { Toast.makeText(this.pHr, this.pHr.getString(a$g.gesture_pwd_toast_enabled), 0).show(); GestureGuardLogicUI.a(this.pHr, -1, 0, "open gesture ok"); } else { Toast.makeText(this.pHr, this.pHr.getString(a$g.gesture_pwd_err_runtime), 0).show(); GestureGuardLogicUI.a(this.pHr, -1, -1, "open gesture failed"); } return 0; } }
package com.webcloud.func.template.adapter; import java.util.List; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.webcloud.R; import com.webcloud.manager.SystemManager; import com.webcloud.manager.client.ImageCacheManager; import com.webcloud.model.Menu; /** * 抽屉应用菜单列表适配器。 * * @author bangyue * @version [版本号, 2014-1-17] * @see [相关类/方法] * @since [产品/模块版本] */ public class FragSlideMenuListViewAdapter extends BaseAdapter { private List<Menu> data; private Activity context; private LayoutInflater inflater; private ImageLoader imgLoader; private DisplayImageOptions options; public FragSlideMenuListViewAdapter(Activity context, List<Menu> data) { inflater = LayoutInflater.from(context); this.data = data; this.context = context; this.imgLoader = SystemManager.getInstance(context).imgCacheMgr.getImageLoader(); this.options = SystemManager.getInstance(context).imgCacheMgr.getOptions(ImageCacheManager.CACHE_MODE_CACHE); } @Override public int getCount() { return data.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { final ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.home_slidemenu_menu_item, null); holder.ivMenu = (ImageView) convertView.findViewById(R.id.ivMenu); holder.tvMenu = (TextView) convertView.findViewById(R.id.tvMenu); holder.layMenu = convertView.findViewById(R.id.layMenu); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } Menu menu = data.get(position); try { holder.ivMenu.setTag(menu); holder.tvMenu.setText(menu.getName()); //ImageTool.setImgView(HomeActivity.this, btnMenu, menu.getIconUrl(), false); //ImageView ivPic = new ImageView(context); //ivPic.setTag(holder.ivMenu); imgLoader.displayImage(menu.getIconUrl(), holder.ivMenu, options,null /*new SimpleImageLoadingListener(){ @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { super.onLoadingComplete(imageUri, view, loadedImage); ImageView ivMenu = (ImageView)view.getTag(); ivMenu.setBackgroundDrawable(new BitmapDrawable(context.getResources(), loadedImage)); } }*/); /*holder.layMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Menu menu = (Menu)(((ViewGroup)v).getChildAt(0).getTag()); context.menuOnClick(menu); Toast.makeText(context, menu.getMsg(), 500).show(); } });*/ } catch (Exception e) { e.printStackTrace(); } return convertView; } private static class ViewHolder { ImageView ivMenu; TextView tvMenu; View layMenu; } }
package com.bytedance.ies.bullet.kit.rn.internal.wrapper; import android.view.View; import com.facebook.react.uimanager.ReactStylesDiffMap; import com.facebook.react.uimanager.ViewManager; import com.facebook.react.uimanager.ViewManagerPropertyUpdater; import java.util.Map; public class ViewGroupManagerWrapper$$PropsSetter implements ViewManagerPropertyUpdater.ViewManagerSetter<ViewGroupManagerWrapper, View> { public void getProperties(Map<String, String> paramMap) {} public void setProperty(ViewGroupManagerWrapper paramViewGroupManagerWrapper, View paramView, String paramString, ReactStylesDiffMap paramReactStylesDiffMap) { paramViewGroupManagerWrapper.setProperty(paramView, paramString, paramReactStylesDiffMap); } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\bytedance\ies\bullet\kit\rn\internal\wrapper\ViewGroupManagerWrapper$$PropsSetter.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package net.minecraft.network.play.server; import java.io.IOException; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.network.INetHandler; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class SPacketBlockChange implements Packet<INetHandlerPlayClient> { private BlockPos blockPosition; private IBlockState blockState; public SPacketBlockChange() {} public SPacketBlockChange(World worldIn, BlockPos posIn) { this.blockPosition = posIn; this.blockState = worldIn.getBlockState(posIn); } public void readPacketData(PacketBuffer buf) throws IOException { this.blockPosition = buf.readBlockPos(); this.blockState = (IBlockState)Block.BLOCK_STATE_IDS.getByValue(buf.readVarIntFromBuffer()); } public void writePacketData(PacketBuffer buf) throws IOException { buf.writeBlockPos(this.blockPosition); buf.writeVarIntToBuffer(Block.BLOCK_STATE_IDS.get(this.blockState)); } public void processPacket(INetHandlerPlayClient handler) { handler.handleBlockChange(this); } public IBlockState getBlockState() { return this.blockState; } public BlockPos getBlockPosition() { return this.blockPosition; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\network\play\server\SPacketBlockChange.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
public class TestB { public static void main(String[] args) { Student s=new Student(); Student a=new Student(); a.age=23; a.height=6.0; a.name="Mayank"; a.Display(); s.Walk(); } }
package project; import java.util.Random; public class Employee { private double performance; private double wage; private static Random rand = new Random(); public Employee() { // Performance in between 1 and 2 ??? this.performance = 1 + rand.nextDouble(); this.wage = 9.5; } public double getPerformance() { return this.performance; } public void setPerformance(double performance) { this.performance = performance; } public double getWage() { return wage; } }
package com.nexon; public interface IGame { void getRockScissorsPaper(); void playGame(); }
package com.sneaker.mall.api.api.saleman; import com.google.common.base.Strings; import com.sneaker.mall.api.exception.ParameterException; import com.sneaker.mall.api.exception.SessionException; import com.sneaker.mall.api.model.Market; import com.sneaker.mall.api.model.ResponseMessage; import com.sneaker.mall.api.service.MarketService; import com.sneaker.mall.api.util.CONST; import com.sneaker.mall.api.util.JsonParser; import com.sneaker.mall.api.util.RequestUtil; import com.sneaker.mall.api.util.ResponseUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * 营销活动 */ @Controller("salemanmarketapi") @RequestMapping(value = "/saleman/market") public class MarketApi extends BaseController { @Autowired private MarketService marketService; /** * 根据商品ID获取营销活动信息 * * @param request * @param response */ @RequestMapping(value = "getmarketbymgid.action") public void getMarketByMgid(HttpServletRequest request, HttpServletResponse response) { ResponseMessage<List<Market>> responseMessage = new ResponseMessage<>(200, "success"); String callback = RequestUtil.getString(request, "callback", CONST.CALLBACK_VAR); String encode = RequestUtil.getString(request, "encode", CONST.ENCODE); try { long ccid = RequestUtil.getLong(request, "ccid", 0); long cid = getLoginUser(request).getCid(); long mgid = RequestUtil.getLong(request, "mgid", 0); String mids = RequestUtil.getString(request, "mids", ""); if (ccid > 0 && mgid > 0 && !Strings.isNullOrEmpty(mids)) { List<Market> markets = this.marketService.getGoodsMarketByMgid(mgid, ccid, cid, mids); if (markets != null) { responseMessage.setData(markets); } } } catch (ParameterException pe) { pe.printStackTrace(); } catch (SessionException e1) { responseMessage.setStatus(306); responseMessage.setMessage("login fail"); } catch (Exception e) { responseMessage.setStatus(400); responseMessage.setMessage(e.getMessage()); e.printStackTrace(); } ResponseUtil.writeResult(response, ResponseUtil.CallBackResultJsonP(JsonParser.simpleJson(responseMessage), callback), encode); } }
package org.Chapter8.metaq; import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; import org.apache.rocketmq.client.exception.MQClientException; import org.apache.rocketmq.common.consumer.ConsumeFromWhere; import org.apache.rocketmq.common.message.MessageExt; import org.apache.rocketmq.remoting.common.RemotingHelper; import java.io.UnsupportedEncodingException; public class Consumer { /** * Consumer Started. * ConsumeMessageThread_4 Receive New Messages: C0A8322D315018B4AAC237F23B580007 Hello RocketMQ 7 * ConsumeMessageThread_10 Receive New Messages: C0A8322D316918B4AAC237F275BC0003 Hello RocketMQ 3 * ConsumeMessageThread_11 Receive New Messages: C0A8322D316918B4AAC237F273C60002 Hello RocketMQ 2 * ConsumeMessageThread_16 Receive New Messages: C0A8322D316918B4AAC237F27D8E0007 Hello RocketMQ 7 * ConsumeMessageThread_7 Receive New Messages: C0A8322D316918B4AAC237F270B60000 Hello RocketMQ 0 * ConsumeMessageThread_11 Receive New Messages: C0A8322D317818B4AAC237F29B5F0000 Hello RocketMQ 0 * ConsumeMessageThread_18 Receive New Messages: C0A8322D316918B4AAC237F2895C000D Hello RocketMQ 13 * ConsumeMessageThread_17 Receive New Messages: C0A8322D316918B4AAC237F2856E000B Hello RocketMQ 11 * ConsumeMessageThread_9 Receive New Messages: C0A8322D315018B4AAC237F23B5B0008 Hello RocketMQ 8 * ConsumeMessageThread_20 Receive New Messages: C0A8322D316918B4AAC237F28F3E0010 Hello RocketMQ 16 * ConsumeMessageThread_8 Receive New Messages: C0A8322D316918B4AAC237F271CF0001 Hello RocketMQ 1 * ConsumeMessageThread_15 Receive New Messages: C0A8322D316918B4AAC237F27F880008 Hello RocketMQ 8 * ConsumeMessageThread_5 Receive New Messages: C0A8322D315018B4AAC237F23B560006 Hello RocketMQ 6 * ConsumeMessageThread_13 Receive New Messages: C0A8322D316918B4AAC237F281850009 Hello RocketMQ 9 * ConsumeMessageThread_14 Receive New Messages: C0A8322D316918B4AAC237F277B00004 Hello RocketMQ 4 * ConsumeMessageThread_1 Receive New Messages: C0A8322D315018B4AAC237F23B480003 Hello RocketMQ 3 * ConsumeMessageThread_12 Receive New Messages: C0A8322D316918B4AAC237F27B990006 Hello RocketMQ 6 * ConsumeMessageThread_3 Receive New Messages: C0A8322D315018B4AAC237F23B1D0000 Hello RocketMQ 0 * ConsumeMessageThread_19 Receive New Messages: C0A8322D316918B4AAC237F28B50000E Hello RocketMQ 14 * ConsumeMessageThread_2 Receive New Messages: C0A8322D315018B4AAC237F23B450002 Hello RocketMQ 2 * ConsumeMessageThread_6 Receive New Messages: C0A8322D315018B4AAC237F23B4A0004 Hello RocketMQ 4 * ConsumeMessageThread_11 Receive New Messages: C0A8322D316918B4AAC237F28D47000F Hello RocketMQ 15 * ConsumeMessageThread_7 Receive New Messages: C0A8322D316918B4AAC237F28766000C Hello RocketMQ 12 * ConsumeMessageThread_10 Receive New Messages: C0A8322D316918B4AAC237F28378000A Hello RocketMQ 10 * ConsumeMessageThread_4 Receive New Messages: C0A8322D317818B4AAC237F29B6C0002 Hello RocketMQ 2 * ConsumeMessageThread_16 Receive New Messages: C0A8322D316918B4AAC237F293290012 Hello RocketMQ 18 * ConsumeMessageThread_17 Receive New Messages: C0A8322D315018B4AAC237F23B4E0005 Hello RocketMQ 5 * ConsumeMessageThread_5 Receive New Messages: C0A8322D317818B4AAC237F29B6A0001 Hello RocketMQ 1 * ConsumeMessageThread_15 Receive New Messages: C0A8322D316918B4AAC237F295220013 Hello RocketMQ 19 * ConsumeMessageThread_8 Receive New Messages: C0A8322D316918B4AAC237F291340011 Hello RocketMQ 17 * ConsumeMessageThread_20 Receive New Messages: C0A8322D316918B4AAC237F279A50005 Hello RocketMQ 5 * ConsumeMessageThread_9 Receive New Messages: C0A8322D315018B4AAC237F23B600009 Hello RocketMQ 9 * ConsumeMessageThread_18 Receive New Messages: C0A8322D315018B4AAC237F23B3F0001 Hello RocketMQ 1 * ConsumeMessageThread_13 Receive New Messages: C0A8322D31DD18B4AAC237F37E4A0000 Hello RocketMQ 0 * ConsumeMessageThread_14 Receive New Messages: C0A8322D31DD18B4AAC237F37E530001 Hello RocketMQ 1 * ConsumeMessageThread_1 Receive New Messages: C0A8322D31DD18B4AAC237F37E580002 Hello RocketMQ 2 * ConsumeMessageThread_12 Receive New Messages: C0A8322D31DD18B4AAC237F37E5C0003 Hello RocketMQ 3 * ConsumeMessageThread_3 Receive New Messages: C0A8322D31DD18B4AAC237F37E5E0004 Hello RocketMQ 4 * ConsumeMessageThread_19 Receive New Messages: C0A8322D31DD18B4AAC237F37E600005 Hello RocketMQ 5 * ConsumeMessageThread_2 Receive New Messages: C0A8322D31DD18B4AAC237F37E640006 Hello RocketMQ 6 * ConsumeMessageThread_6 Receive New Messages: C0A8322D31DD18B4AAC237F37E660007 Hello RocketMQ 7 * ConsumeMessageThread_11 Receive New Messages: C0A8322D31DD18B4AAC237F37E680008 Hello RocketMQ 8 * ConsumeMessageThread_7 Receive New Messages: C0A8322D31DD18B4AAC237F37E6B0009 Hello RocketMQ 9 */ public static void main(String[] args) throws InterruptedException, MQClientException { // 1. 创建消费实例 和 配置ns地址 DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("my-consumer-group"); consumer.setNamesrvAddr("127.0.0.1:9876"); // 2. 消费属性配置 consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); // 3. 订阅TopicTest topic下所有tag consumer.subscribe("TopicTest", "*"); // 4. 注册回调 consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> { for (MessageExt msg : msgs) { String body = ""; try { body = new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.printf("%s Receive New Messages: %s %s %n", Thread.currentThread().getName(), msg.getMsgId(), body); } return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; }); // 5.启动消费实例 consumer.start(); System.out.printf("Consumer Started.%n"); } }
/* * [y] hybris Platform * * Copyright (c) 2000-2016 hybris AG * All rights reserved. * * This software is the confidential and proprietary information of hybris * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with hybris. * * */ package com.cnk.travelogix.b2c.storefront.controllers.pages; import de.hybris.platform.acceleratorservices.controllers.page.PageType; import de.hybris.platform.acceleratorservices.customer.CustomerLocationService; import de.hybris.platform.acceleratorstorefrontcommons.breadcrumb.impl.SearchBreadcrumbBuilder; import de.hybris.platform.acceleratorstorefrontcommons.constants.WebConstants; import de.hybris.platform.acceleratorstorefrontcommons.controllers.ThirdPartyConstants; import de.hybris.platform.acceleratorstorefrontcommons.controllers.pages.AbstractSearchPageController; import de.hybris.platform.acceleratorstorefrontcommons.util.MetaSanitizerUtil; import de.hybris.platform.acceleratorstorefrontcommons.util.XSSFilterUtil; import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException; import de.hybris.platform.cms2.servicelayer.services.CMSComponentService; import de.hybris.platform.commercefacades.product.data.ProductData; import de.hybris.platform.commercefacades.search.ProductSearchFacade; import de.hybris.platform.commercefacades.search.data.AutocompleteResultData; import de.hybris.platform.commercefacades.search.data.AutocompleteSuggestionData; import de.hybris.platform.commercefacades.search.data.SearchQueryData; import de.hybris.platform.commercefacades.search.data.SearchStateData; import de.hybris.platform.commerceservices.search.facetdata.FacetData; import de.hybris.platform.commerceservices.search.facetdata.FacetRefinement; import de.hybris.platform.commerceservices.search.facetdata.FacetValueData; import de.hybris.platform.commerceservices.search.facetdata.ProductSearchPageData; import de.hybris.platform.commerceservices.search.pagedata.PageableData; import de.hybris.platform.converters.impl.AbstractPopulatingConverter; import de.hybris.platform.servicelayer.dto.converter.ConversionException; import de.hybris.platform.util.Config; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.cnk.travelogix.b2c.facades.audoSuggestion.CitySearchFacade; import com.cnk.travelogix.common.core.model.EzgSearchBoxComponentModel; import com.cnk.travelogix.common.facades.autoSuggestion.AutoSuggestionFacade; import com.cnk.travelogix.common.facades.product.CnkProductCompareFacade; import com.cnk.travelogix.common.facades.product.CnkProductSearchFacade; import com.cnk.travelogix.common.facades.product.data.CnkBreadcrumbData; import com.cnk.travelogix.common.facades.product.data.CnkFacetData; import com.cnk.travelogix.common.facades.product.data.CnkFacetDataList; import com.cnk.travelogix.common.facades.product.data.CnkProductSearchPageData; import com.cnk.travelogix.common.facades.product.data.CnkProductSortConditionData; import com.cnk.travelogix.common.facades.product.data.CnkSortedDataList; import com.cnk.travelogix.common.facades.product.data.FlightHotelSearchData; import com.cnk.travelogix.common.facades.product.data.FlightHotelSearchRoomData; import com.cnk.travelogix.common.facades.product.data.FlightProductSearchPageData; import com.cnk.travelogix.common.facades.product.data.HotelSearchData; import com.cnk.travelogix.common.facades.product.data.hotel.HotelCompareData; import com.cnk.travelogix.common.facades.product.data.hotel.HotelData; import com.cnk.travelogix.common.facades.product.data.hotel.HotelMarkerData; import com.cnk.travelogix.common.facades.product.util.CnkBeanUtil; import com.sap.security.core.server.csi.XSSEncoder; @Controller @Scope("tenant") @RequestMapping("/search") public class SearchPageController extends AbstractSearchPageController { private static final String SEARCH_META_DESCRIPTION_ON = "search.meta.description.on"; private static final String SEARCH_META_DESCRIPTION_RESULTS = "search.meta.description.results"; @SuppressWarnings("unused") private static final Logger LOG = Logger.getLogger(SearchPageController.class); //TODO: delete the static default setting static { LOG.setLevel(Level.DEBUG); } private static final String COMPONENT_UID_PATH_VARIABLE_PATTERN = "{componentUid:.*}"; private static final String FACET_SEPARATOR = ":"; private static final String SEARCH_CMS_PAGE_ID = "search"; private static final String SEARCH_HOTEL_PAGE_ID = "ezgHotelSearchResultPage"; private static final String NO_RESULTS_CMS_PAGE_ID = "searchEmpty"; private static final String VIEW_PAGE_SIZE = Config.getParameter("ezg.storefront.view.pageSize"); @Resource(name = "productSearchFacade") private ProductSearchFacade<ProductData> productSearchFacade; @Resource(name = "searchBreadcrumbBuilder") private SearchBreadcrumbBuilder searchBreadcrumbBuilder; @Resource(name = "customerLocationService") private CustomerLocationService customerLocationService; @Resource(name = "cmsComponentService") private CMSComponentService cmsComponentService; @Resource(name = "facetFlightAndHotelSearchFacade") CnkProductSearchFacade facetFlightAndHotelSearchFacade; @Resource(name = "sortedHotelSearchFacade") private CnkProductSearchFacade sortedHotelSearchFacade; @Resource(name = "sortedFlightSearchFacade") private CnkProductSearchFacade sortedFlightSearchFacade; @Resource(name = "multicityIntlSortedFlightSearchFacade") private CnkProductSearchFacade multicityIntlSortedFlightSearchFacade; @Resource(name = "defaultSolrCitySearchFacade") private CitySearchFacade defaultSolrCitySearchFacade; @Resource(name = "defaultAutoSuggestionFacade") private AutoSuggestionFacade defaultAutoSuggestionFacade; @Resource(name = "defaultHotelCompareFacade") private CnkProductCompareFacade defaultHotelCompareFacade; @Resource private AbstractPopulatingConverter defaultHotelDataConverter; @RequestMapping(method = RequestMethod.GET, params = "!q") public String textSearch(@RequestParam(value = "text", defaultValue = "") final String searchText, final HttpServletRequest request, final Model model) throws CMSItemNotFoundException { if (StringUtils.isNotBlank(searchText)) { final PageableData pageableData = createPageableData(0, getSearchPageSize(), null, ShowMode.Page); final String encodedSearchText = XSSFilterUtil.filter(searchText); final SearchStateData searchState = new SearchStateData(); final SearchQueryData searchQueryData = new SearchQueryData(); searchQueryData.setValue(encodedSearchText); searchState.setQuery(searchQueryData); ProductSearchPageData<SearchStateData, ProductData> searchPageData = null; try { searchPageData = encodeSearchPageData(productSearchFacade.textSearch(searchState, pageableData)); } catch (final ConversionException e) // NOSONAR { // nothing to do - the exception is logged in SearchSolrQueryPopulator } if (searchPageData == null) { storeCmsPageInModel(model, getContentPageForLabelOrId(NO_RESULTS_CMS_PAGE_ID)); } else if (searchPageData.getKeywordRedirectUrl() != null) { // if the search engine returns a redirect, just return "redirect:" + searchPageData.getKeywordRedirectUrl(); } else if (searchPageData.getPagination().getTotalNumberOfResults() == 0) { model.addAttribute("searchPageData", searchPageData); storeCmsPageInModel(model, getContentPageForLabelOrId(NO_RESULTS_CMS_PAGE_ID)); updatePageTitle(encodedSearchText, model); } else { storeContinueUrl(request); populateModel(model, searchPageData, ShowMode.Page); storeCmsPageInModel(model, getContentPageForLabelOrId(SEARCH_CMS_PAGE_ID)); updatePageTitle(encodedSearchText, model); } model.addAttribute("userLocation", customerLocationService.getUserLocation()); getRequestContextData(request).setSearch(searchPageData); if (searchPageData != null) { model.addAttribute(WebConstants.BREADCRUMBS_KEY, searchBreadcrumbBuilder.getBreadcrumbs(null, encodedSearchText, CollectionUtils.isEmpty(searchPageData.getBreadcrumbs()))); } } else { storeCmsPageInModel(model, getContentPageForLabelOrId(NO_RESULTS_CMS_PAGE_ID)); } model.addAttribute("pageType", PageType.PRODUCTSEARCH.name()); model.addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS, ThirdPartyConstants.SeoRobots.NOINDEX_FOLLOW); final String metaDescription = MetaSanitizerUtil .sanitizeDescription(getMessageSource().getMessage(SEARCH_META_DESCRIPTION_RESULTS, null, SEARCH_META_DESCRIPTION_RESULTS, getI18nService().getCurrentLocale()) + " " + searchText + " " + getMessageSource().getMessage(SEARCH_META_DESCRIPTION_ON, null, SEARCH_META_DESCRIPTION_ON, getI18nService().getCurrentLocale()) + " " + getSiteName()); final String metaKeywords = MetaSanitizerUtil.sanitizeKeywords(searchText); setUpMetaData(model, metaKeywords, metaDescription); return getViewForPage(model); } @RequestMapping(method = RequestMethod.POST, value = "/hotel/{searchType}") public String hotelSearch(final HttpServletRequest request, final Model model, @PathVariable(value = "searchType") final String searchType, @RequestParam(value = "tabName", defaultValue = "hotel") final String tabName) throws CMSItemNotFoundException { //get pageNumber final String pageNumber = "1"; //get search widget view model-last changed data final String topSearchViewModel = request.getParameter("topSearchViewModel"); //get search widget data model-changed data final String topSearchDataModel = request.getParameter("topSearchDataModel"); //get facet search data String facetDataJson = request.getParameter("facetViewModel"); //get filter search data String filterSearchDataJson = request.getParameter("filterSearchViewModel"); if (LOG.isDebugEnabled()) { LOG.info("topSearchViewModel:" + topSearchViewModel); LOG.info("topSearchDataModel:" + topSearchViewModel); LOG.info("facetDataJson:" + facetDataJson); LOG.info("filterSearchDataJson:" + filterSearchDataJson); } final HotelSearchData searchData = CnkBeanUtil.getBeanFromJson(topSearchDataModel, HotelSearchData.class); searchData.setPageNum(Integer.valueOf(pageNumber).intValue()); searchData.setPageSize(Integer.valueOf(VIEW_PAGE_SIZE).intValue()); List<CnkFacetDataList> facetDataListModel = new ArrayList<CnkFacetDataList>(); if (StringUtils.equalsIgnoreCase(searchType, "topSearch")) { // } if (StringUtils.equalsIgnoreCase(searchType, "facetSearch")) { //search from plp page with facet facetDataListModel = CnkBeanUtil.getBeanListFromJson(facetDataJson, CnkFacetData.class); } if (StringUtils.equalsIgnoreCase(searchType, "filterSearch")) { facetDataListModel = CnkBeanUtil.getBeanListFromJson(filterSearchDataJson, CnkFacetData.class); } //set facet search items (facetSearch and filterSearch are all treated as facet attribute of searchData) if (CollectionUtils.isNotEmpty(facetDataListModel)) { searchData.setFacets(facetDataListModel); } //TODO:search data - supplier //search products final CnkProductSearchPageData<HotelData> result = sortedHotelSearchFacade.searchProduct(searchData); //TODO:MOCK Convert data from SI // for (final HotelData data : result.getResult()) // { // defaultHotelDataConverter.populate(data, data); // } //this only used to init the facet search and filter search page when the page loaded first time; final List<CnkFacetDataList> facetSearch = result.getFacets(); if (StringUtils.isEmpty(facetDataJson)) { final List<CnkFacetData> cnkFacetDataList = facetSearch.get(0).getFacets(); if (CollectionUtils.isNotEmpty(cnkFacetDataList)) { facetDataJson = CnkBeanUtil.getJsonFromObject(cnkFacetDataList); } } if (StringUtils.isEmpty(filterSearchDataJson)) { filterSearchDataJson = CnkBeanUtil.getJsonFromObject(facetSearch.get(0).getFacets()); } this.buildTitileReturnInfo(model, searchData); final List<HotelData> bestRecommends = result.getBestPriceRecommend(); final List<CnkBreadcrumbData> breadcrumbs = result.getBreadcrumbs(); final List<HotelData> products = result.getResult(); final List<CnkSortedDataList> sortContionList = result.getSortConditionList(); model.addAttribute("bestRecommends", CnkBeanUtil.getJsonFromObject(bestRecommends)); model.addAttribute("breadcrumbs", breadcrumbs); model.addAttribute("hotelList", CnkBeanUtil.getJsonFromObject(products)); model.addAttribute("sortContionList", CnkBeanUtil.getJsonFromObject(sortContionList)); //add paging info model.addAttribute("result", result); //search query json transfer to pdp page final String lastSearchQuerys = CnkBeanUtil.getJsonFromObject(searchData); model.addAttribute("querys", lastSearchQuerys); model.addAttribute("searchData", searchData); //return facet search view model to bind model.addAttribute("facetViewJson", facetDataJson); //return top search view and data model to bind model.addAttribute("topSearchViewModel", topSearchViewModel); model.addAttribute("topSearchDataModel", topSearchDataModel); //return filter Search view and data model to bind model.addAttribute("filterSearchViewJson", filterSearchDataJson); //return lat/long array model.addAttribute("markers", generateMarkers(products)); model.addAttribute("tabName", tabName); storeCmsPageInModel(model, getContentPageForLabelOrId(SEARCH_HOTEL_PAGE_ID)); return getViewForPage(model); } private String generateMarkers(final List<HotelData> products) { final List<HotelMarkerData> markerList = new ArrayList<HotelMarkerData>(); for (final HotelData hotelData : products) { markerList.add(hotelData.getMarker()); } return CnkBeanUtil.getJsonFromObject(markerList); } @SuppressWarnings("boxing") private void buildTitileReturnInfo(final Model model, final HotelSearchData searchData) { model.addAttribute("view_destination", searchData.getDestination()); model.addAttribute("view_checkInDate", searchData.getCheckInDate()); model.addAttribute("view_checkOutDate", searchData.getCheckOutDate()); model.addAttribute("view_nights", searchData.getNights()); int adults = 0; int childs = 0; int rooms = 0; for (final FlightHotelSearchRoomData room : searchData.getHotelSearchRooms()) { adults += room.getAdultCount(); childs += room.getChildren().size(); rooms++; } model.addAttribute("view_rooms", rooms); model.addAttribute("view_adults", adults); model.addAttribute("view_childs", childs); } @ResponseBody @RequestMapping(value = "/hotel/{searchType}/ajax", method = RequestMethod.POST) public CnkProductSearchPageData<HotelData> facetFilterHotelData(final HttpServletRequest request, final Model model, @PathVariable(value = "searchType") final String searchType) { final String pageNumber = request.getParameter("pageNumber") != null ? request.getParameter("pageNumber") : "1"; //get search widget data model-changed data final String topSearchDataModel = request.getParameter("topSearchDataModel"); //get facet search data final String facetDataJson = request.getParameter("facetViewModel"); //get filter search data final String filterSearchDataJson = request.getParameter("filterSearchViewModel"); //get selected sorted item final String selectedCode = request.getParameter("selectedCode"); //get sort condition list final String sortConditionList = request.getParameter("sortConditionList"); final HotelSearchData searchData = CnkBeanUtil.getBeanFromJson(topSearchDataModel, HotelSearchData.class); final List<CnkSortedDataList> sortConditions = CnkBeanUtil.getBeanListFromJson(sortConditionList, CnkSortedDataList.class); if (CollectionUtils.isNotEmpty(sortConditions) || StringUtils.isNotEmpty(selectedCode)) { searchData.setSortConditionList(updateSortContionList(sortConditions, selectedCode)); } searchData.setPageNum(Integer.valueOf(pageNumber).intValue()); searchData.setPageSize(Integer.valueOf(VIEW_PAGE_SIZE).intValue()); List<CnkFacetData> facetDataModel = new ArrayList<CnkFacetData>(); if (StringUtils.equalsIgnoreCase(searchType, "facetSearch")) { //search from plp page with facet facetDataModel = CnkBeanUtil.getBeanListFromJson(facetDataJson, CnkFacetData.class); } else if (StringUtils.equalsIgnoreCase(searchType, "filterSearch")) { facetDataModel = CnkBeanUtil.getBeanListFromJson(filterSearchDataJson, CnkFacetData.class); } //set facet search items (facetSearch and filterSearch are all treated as facet attribute of searchData) if (CollectionUtils.isNotEmpty(facetDataModel)) { final List<CnkFacetDataList> facetDataListModel = new ArrayList<CnkFacetDataList>(); final CnkFacetDataList cnkFacetDataList = new CnkFacetDataList(); cnkFacetDataList.setFacets(facetDataModel); facetDataListModel.add(cnkFacetDataList); searchData.setFacets(facetDataListModel); } //search products final CnkProductSearchPageData<HotelData> result = sortedHotelSearchFacade.searchProduct(searchData); return result; } private List<CnkSortedDataList> updateSortContionList(final List<CnkSortedDataList> sortConditionList, final String selectedCode) { for (final CnkSortedDataList conditionList : sortConditionList) { for (final CnkProductSortConditionData condition : conditionList.getConditions()) { if (StringUtils.endsWithIgnoreCase(selectedCode, condition.getCode())) { condition.setSelected(true); } else { condition.setSelected(false); } } } return sortConditionList; } @ResponseBody @RequestMapping(value = "/comparehotel/ajax", method = RequestMethod.GET) public List<HotelCompareData> getComparedHotelDataList(final HttpServletRequest request, @RequestParam(value = "hotelIds", required = false) final String[] hotelIds) { final List<HotelCompareData> hotelDataList = defaultHotelCompareFacade.searchProductByIds(hotelIds); return hotelDataList; } /** * By default, all input/output parameters are data in JSON format. * * @param serviceType * @param request * @param model * @return don't tell :U * @throws CMSItemNotFoundException */ @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = "/flight_and_hotel/{serviceType}") public String flightAndHotelSearch(@PathVariable("serviceType") final String serviceType, final HttpServletRequest request, final Model model) throws CMSItemNotFoundException { // import previous front-end JSON view model final String section1JsonViewModel = request.getParameter("section1ViewModel"); // import previous front-end JSON data model final String searchJsonDataModel = request.getParameter("section1DataModel"); final String facetsJsonDataModel = request.getParameter("section2ADataModel"); if (LOG.isDebugEnabled()) { LOG.debug(new Object[] { section1JsonViewModel, searchJsonDataModel, facetsJsonDataModel }); } try { // covert front-end JSON data model to back-end bean data model final FlightHotelSearchData searchBeanDataModel = CnkBeanUtil.getBeanFromJson(searchJsonDataModel, FlightHotelSearchData.class); final List<CnkFacetDataList> facetsBeanDataModelList = CnkBeanUtil.getBeanListFromJson(facetsJsonDataModel, CnkFacetDataList.class); searchBeanDataModel.setFacets(facetsBeanDataModelList); // search product now final CnkProductSearchPageData searchResultBeanDataModel = facetFlightAndHotelSearchFacade .searchProduct(searchBeanDataModel); final String facetJsonViewModel = CnkBeanUtil.getJsonFromObject(searchResultBeanDataModel.getFacets()); final String searchResultJsonDataModel = CnkBeanUtil.getJsonFromObject(searchResultBeanDataModel); // export next front-end JSON view model model.addAttribute("section1ViewModel", section1JsonViewModel); model.addAttribute("section2AViewModel", facetJsonViewModel); // export next front-end JSON data model model.addAttribute("section1DataModel", searchJsonDataModel); model.addAttribute("section2BDataModel", searchResultJsonDataModel); // export next front-end BEAN data model model.addAttribute("section2BBeanDataModel", searchResultBeanDataModel); } catch (final Exception e) { LOG.error(e); } final String pageId = String.format("ezgFlightHotel%sSearchResultPage", StringUtils.capitalize(serviceType)); storeCmsPageInModel(model, getContentPageForLabelOrId(pageId)); return getViewForPage(model); } @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = "/flight/multicity-intl") public String flightSearchForMulticityIntl(final HttpServletRequest request, @RequestParam(value = "tabName", defaultValue = "flight") final String tabName, final Model model) throws CMSItemNotFoundException { final String jsonViewModel = request.getParameter("flightSection1ViewModel"); final String jsonDataModel = request.getParameter("flightSection1DataModel"); final String facetsJsonDataModel = request.getParameter("flightSection2AViewModel"); final String flightSortDataModel = request.getParameter("flightSortDataModel"); final FlightHotelSearchData searchBeanDataModel = CnkBeanUtil.getBeanFromJson(jsonDataModel, FlightHotelSearchData.class); final List<CnkFacetDataList> facetsBeanDataModelList = CnkBeanUtil.getBeanListFromJson(facetsJsonDataModel, CnkFacetDataList.class); final List<CnkSortedDataList> sortConditionList = CnkBeanUtil.getBeanListFromJson(flightSortDataModel, CnkSortedDataList.class); searchBeanDataModel.setFacets(facetsBeanDataModelList); searchBeanDataModel.setSortConditionList(sortConditionList); searchBeanDataModel.setFlightType("MULTICITY-INTL"); final CnkProductSearchPageData searchPageData; try { searchPageData = multicityIntlSortedFlightSearchFacade.searchProduct(searchBeanDataModel); } catch (final Exception e) { LOG.error(e); return getViewForPage(model); } final String returnedFacetJsonViewModel = CnkBeanUtil.getJsonFromObject(searchPageData.getFacets()); final String returnedFlightSortDataModel = CnkBeanUtil.getJsonFromObject(searchPageData.getSortConditionList()); final String bestRecommends = CnkBeanUtil.getJsonFromObject(searchPageData.getBestPriceRecommend()); final String resultList = CnkBeanUtil.getJsonFromObject(searchPageData.getResult()); model.addAttribute("bestRecommends", bestRecommends); model.addAttribute("resultList", resultList); model.addAttribute("flightSection1ViewModel", jsonViewModel); model.addAttribute("flightSection1DataModel", jsonDataModel); model.addAttribute("flightSortDataModel", returnedFlightSortDataModel); model.addAttribute("flightSection2AViewModel", returnedFacetJsonViewModel); model.addAttribute("flightSection2BViewModel", searchPageData); model.addAttribute("tabName", tabName); //used only when from cart page to SRP. model.addAttribute("originalGroupId", request.getParameter("originalGroupId")); storeCmsPageInModel(model, getContentPageForLabelOrId("ezgFlightMulticityIntlSearchResultPage")); return getViewForPage(model); } @ResponseBody @RequestMapping(value = "/flight/multicity-intl/ajax", method = RequestMethod.POST) public FlightProductSearchPageData flightSearchAjaxForMulticityIntl(final HttpServletRequest request, @RequestParam(value = "tabName", defaultValue = "flight") final String tabName, final Model model) { final String jsonDataModel = request.getParameter("flightSection1DataModel"); final String facetsJsonDataModel = request.getParameter("flightSection2AViewModel"); final String flightSortDataModel = request.getParameter("flightSortDataModel"); final List<CnkSortedDataList> sortConditionList = CnkBeanUtil.getBeanListFromJson(flightSortDataModel, CnkSortedDataList.class); final FlightHotelSearchData searchBeanDataModel = CnkBeanUtil.getBeanFromJson(jsonDataModel, FlightHotelSearchData.class); final List<CnkFacetDataList> facetsBeanDataModelList = CnkBeanUtil.getBeanListFromJson(facetsJsonDataModel, CnkFacetDataList.class); searchBeanDataModel.setFacets(facetsBeanDataModelList); searchBeanDataModel.setSortConditionList(sortConditionList); return (FlightProductSearchPageData) multicityIntlSortedFlightSearchFacade.searchProduct(searchBeanDataModel); } @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = "/flight/{serviceType}") public String flightSearch(@PathVariable("serviceType") final String serviceType, final HttpServletRequest request, @RequestParam(value = "tabName", defaultValue = "flight") final String tabName, final Model model) throws CMSItemNotFoundException { final String jsonViewModel = request.getParameter("flightSection1ViewModel"); final String jsonDataModel = request.getParameter("flightSection1DataModel"); final String facetsJsonDataModel = request.getParameter("flightSection2AViewModel"); final String flightSortDataModel = request.getParameter("flightSortDataModel"); //String jsonSearchPageData = null; try { // covert front-end JSON data model to back-end bean data model final FlightHotelSearchData searchBeanDataModel = CnkBeanUtil.getBeanFromJson(jsonDataModel, FlightHotelSearchData.class); final List<CnkFacetDataList> facetsBeanDataModelList = CnkBeanUtil.getBeanListFromJson(facetsJsonDataModel, CnkFacetDataList.class); final List<CnkSortedDataList> sortConditionList = CnkBeanUtil.getBeanListFromJson(flightSortDataModel, CnkSortedDataList.class); searchBeanDataModel.setFacets(facetsBeanDataModelList); searchBeanDataModel.setSortConditionList(sortConditionList); //final ObjectMapper objectMapper = CnkBeanUtil.getObjectMapper(); final CnkProductSearchPageData searchPageData = sortedFlightSearchFacade.searchProduct(searchBeanDataModel); final String returnedFacetJsonViewModel = CnkBeanUtil.getJsonFromObject(searchPageData.getFacets()); final String returnedFlightSortDataModel = CnkBeanUtil.getJsonFromObject(searchPageData.getSortConditionList()); final String bestRecommends = CnkBeanUtil.getJsonFromObject(searchPageData.getBestPriceRecommend()); final String resultList = CnkBeanUtil.getJsonFromObject(searchPageData.getResult()); model.addAttribute("bestRecommends", bestRecommends); model.addAttribute("resultList", resultList); model.addAttribute("flightSection1ViewModel", jsonViewModel); model.addAttribute("flightSection1DataModel", jsonDataModel); model.addAttribute("flightSortDataModel", returnedFlightSortDataModel); model.addAttribute("flightSection2AViewModel", returnedFacetJsonViewModel); model.addAttribute("flightSection2BViewModel", searchPageData); model.addAttribute("tabName", tabName); //used only when from cart page to SRP. model.addAttribute("originalGroupId", request.getParameter("originalGroupId")); final String pageId = String.format("ezgFlight%sSearchResultPage", StringUtils.capitalize(serviceType)); storeCmsPageInModel(model, getContentPageForLabelOrId(pageId)); } catch (final Exception e) { LOG.error(e); } return getViewForPage(model); } @ResponseBody @RequestMapping(value = "/flight/{serviceType}/ajax", method = RequestMethod.POST) public FlightProductSearchPageData flightSearchAjax(@PathVariable("serviceType") final String serviceType, final HttpServletRequest request, @RequestParam(value = "tabName", defaultValue = "flight") final String tabName, final Model model) { final String jsonDataModel = request.getParameter("flightSection1DataModel"); final String facetsJsonDataModel = request.getParameter("flightSection2AViewModel"); final String flightSortDataModel = request.getParameter("flightSortDataModel"); final List<CnkSortedDataList> sortConditionList = CnkBeanUtil.getBeanListFromJson(flightSortDataModel, CnkSortedDataList.class); final FlightHotelSearchData searchBeanDataModel = CnkBeanUtil.getBeanFromJson(jsonDataModel, FlightHotelSearchData.class); final List<CnkFacetDataList> facetsBeanDataModelList = CnkBeanUtil.getBeanListFromJson(facetsJsonDataModel, CnkFacetDataList.class); searchBeanDataModel.setFacets(facetsBeanDataModelList); searchBeanDataModel.setSortConditionList(sortConditionList); return (FlightProductSearchPageData) sortedFlightSearchFacade.searchProduct(searchBeanDataModel); } @RequestMapping(method = RequestMethod.GET, params = "q") public String refineSearch(@RequestParam("q") final String searchQuery, @RequestParam(value = "page", defaultValue = "0") final int page, @RequestParam(value = "show", defaultValue = "Page") final ShowMode showMode, @RequestParam(value = "sort", required = false) final String sortCode, @RequestParam(value = "text", required = false) final String searchText, final HttpServletRequest request, final Model model) throws CMSItemNotFoundException { final ProductSearchPageData<SearchStateData, ProductData> searchPageData = performSearch(searchQuery, page, showMode, sortCode, getSearchPageSize()); populateModel(model, searchPageData, showMode); model.addAttribute("userLocation", customerLocationService.getUserLocation()); if (searchPageData.getPagination().getTotalNumberOfResults() == 0) { updatePageTitle(searchPageData.getFreeTextSearch(), model); storeCmsPageInModel(model, getContentPageForLabelOrId(NO_RESULTS_CMS_PAGE_ID)); } else { storeContinueUrl(request); updatePageTitle(searchPageData.getFreeTextSearch(), model); storeCmsPageInModel(model, getContentPageForLabelOrId(SEARCH_CMS_PAGE_ID)); } model.addAttribute(WebConstants.BREADCRUMBS_KEY, searchBreadcrumbBuilder.getBreadcrumbs(null, searchPageData)); model.addAttribute("pageType", PageType.PRODUCTSEARCH.name()); final String metaDescription = MetaSanitizerUtil .sanitizeDescription(getMessageSource().getMessage(SEARCH_META_DESCRIPTION_RESULTS, null, SEARCH_META_DESCRIPTION_RESULTS, getI18nService().getCurrentLocale()) + " " + searchText + " " + getMessageSource().getMessage(SEARCH_META_DESCRIPTION_ON, null, SEARCH_META_DESCRIPTION_ON, getI18nService().getCurrentLocale()) + " " + getSiteName()); final String metaKeywords = MetaSanitizerUtil.sanitizeKeywords(searchText); setUpMetaData(model, metaKeywords, metaDescription); return getViewForPage(model); } protected ProductSearchPageData<SearchStateData, ProductData> performSearch(final String searchQuery, final int page, final ShowMode showMode, final String sortCode, final int pageSize) { final PageableData pageableData = createPageableData(page, pageSize, sortCode, showMode); final SearchStateData searchState = new SearchStateData(); final SearchQueryData searchQueryData = new SearchQueryData(); searchQueryData.setValue(searchQuery); searchState.setQuery(searchQueryData); return encodeSearchPageData(productSearchFacade.textSearch(searchState, pageableData)); } @ResponseBody @RequestMapping(value = "/results", method = RequestMethod.GET) public SearchResultsData<ProductData> jsonSearchResults(@RequestParam("q") final String searchQuery, @RequestParam(value = "page", defaultValue = "0") final int page, @RequestParam(value = "show", defaultValue = "Page") final ShowMode showMode, @RequestParam(value = "sort", required = false) final String sortCode) throws CMSItemNotFoundException { final ProductSearchPageData<SearchStateData, ProductData> searchPageData = performSearch(searchQuery, page, showMode, sortCode, getSearchPageSize()); final SearchResultsData<ProductData> searchResultsData = new SearchResultsData<>(); searchResultsData.setResults(searchPageData.getResults()); searchResultsData.setPagination(searchPageData.getPagination()); return searchResultsData; } @ResponseBody @RequestMapping(value = "/facets", method = RequestMethod.GET) public FacetRefinement<SearchStateData> getFacets(@RequestParam("q") final String searchQuery, @RequestParam(value = "page", defaultValue = "0") final int page, @RequestParam(value = "show", defaultValue = "Page") final ShowMode showMode, @RequestParam(value = "sort", required = false) final String sortCode) throws CMSItemNotFoundException { final SearchStateData searchState = new SearchStateData(); final SearchQueryData searchQueryData = new SearchQueryData(); searchQueryData.setValue(searchQuery); searchState.setQuery(searchQueryData); final ProductSearchPageData<SearchStateData, ProductData> searchPageData = productSearchFacade.textSearch(searchState, createPageableData(page, getSearchPageSize(), sortCode, showMode)); final List<FacetData<SearchStateData>> facets = refineFacets(searchPageData.getFacets(), convertBreadcrumbsToFacets(searchPageData.getBreadcrumbs())); final FacetRefinement<SearchStateData> refinement = new FacetRefinement<>(); refinement.setFacets(facets); refinement.setCount(searchPageData.getPagination().getTotalNumberOfResults()); refinement.setBreadcrumbs(searchPageData.getBreadcrumbs()); return refinement; } @SuppressWarnings("boxing") @ResponseBody @RequestMapping(value = "/autocomplete/" + COMPONENT_UID_PATH_VARIABLE_PATTERN, method = RequestMethod.GET) public AutocompleteResultData getAutocompleteSuggestions(@PathVariable final String componentUid, @RequestParam("term") final String term) throws CMSItemNotFoundException { final AutocompleteResultData resultData = new AutocompleteResultData(); final List<AutocompleteSuggestionData> list = new ArrayList<AutocompleteSuggestionData>(); final EzgSearchBoxComponentModel component = (EzgSearchBoxComponentModel) cmsComponentService .getSimpleCMSComponent(componentUid); final int suggestSize = component.getMaxSuggestions(); final int productSize = component.getMaxProducts(); if (component.isDisplaySuggestions()) { list.addAll(subList(productSearchFacade.getAutocompleteSuggestions(term), suggestSize)); } if (component.isDisplayCity()) { list.addAll(subList(defaultSolrCitySearchFacade.getAutocompleteSuggestions(term), suggestSize)); } if (component.isDisplayArea()) { list.addAll(defaultAutoSuggestionFacade.getSuggestedArea(term)); } if (component.isDisplayChain()) { //get chain, totally 269,provided by excel } if (component.isDisplayLandMark()) { // } if (list.size() > suggestSize) { resultData.setSuggestions(list.subList(0, suggestSize)); } else { resultData.setSuggestions(list); } if (component.isDisplayProducts()) { resultData.setProducts(subList(productSearchFacade.textSearch(term).getResults(), productSize)); } return resultData; } protected <E> List<E> subList(final List<E> list, final int maxElements) { if (CollectionUtils.isEmpty(list)) { return Collections.emptyList(); } if (list.size() > maxElements) { return list.subList(0, maxElements); } return list; } protected void updatePageTitle(final String searchText, final Model model) { storeContentPageTitleInModel(model, getPageTitleResolver().resolveContentPageTitle( getMessageSource().getMessage("search.meta.title", null, "search.meta.title", getI18nService().getCurrentLocale()) + " " + searchText)); } protected ProductSearchPageData<SearchStateData, ProductData> encodeSearchPageData( final ProductSearchPageData<SearchStateData, ProductData> searchPageData) { final SearchStateData currentQuery = searchPageData.getCurrentQuery(); if (currentQuery != null) { try { final SearchQueryData query = currentQuery.getQuery(); final String encodedQueryValue = XSSEncoder.encodeHTML(query.getValue()); query.setValue(encodedQueryValue); currentQuery.setQuery(query); searchPageData.setCurrentQuery(currentQuery); searchPageData.setFreeTextSearch(XSSEncoder.encodeHTML(searchPageData.getFreeTextSearch())); final List<FacetData<SearchStateData>> facets = searchPageData.getFacets(); if (CollectionUtils.isNotEmpty(facets)) { processFacetData(facets); } } catch (final UnsupportedEncodingException e) { if (LOG.isDebugEnabled()) { LOG.debug("Error occured during Encoding the Search Page data values", e); } } } return searchPageData; } protected void processFacetData(final List<FacetData<SearchStateData>> facets) throws UnsupportedEncodingException { for (final FacetData<SearchStateData> facetData : facets) { final List<FacetValueData<SearchStateData>> topFacetValueDatas = facetData.getTopValues(); if (CollectionUtils.isNotEmpty(topFacetValueDatas)) { processFacetDatas(topFacetValueDatas); } final List<FacetValueData<SearchStateData>> facetValueDatas = facetData.getValues(); if (CollectionUtils.isNotEmpty(facetValueDatas)) { processFacetDatas(facetValueDatas); } } } protected void processFacetDatas(final List<FacetValueData<SearchStateData>> facetValueDatas) throws UnsupportedEncodingException { for (final FacetValueData<SearchStateData> facetValueData : facetValueDatas) { final SearchStateData facetQuery = facetValueData.getQuery(); final SearchQueryData queryData = facetQuery.getQuery(); final String queryValue = queryData.getValue(); if (StringUtils.isNotBlank(queryValue)) { final String[] queryValues = queryValue.split(FACET_SEPARATOR); final StringBuilder queryValueBuilder = new StringBuilder(); queryValueBuilder.append(XSSEncoder.encodeHTML(queryValues[0])); for (int i = 1; i < queryValues.length; i++) { queryValueBuilder.append(FACET_SEPARATOR).append(queryValues[i]); } queryData.setValue(queryValueBuilder.toString()); } } } }
package de.raidcraft.skillsandeffects.pvp.skills.movement; import com.sk89q.minecraft.util.commands.CommandContext; import de.raidcraft.skills.api.combat.EffectType; import de.raidcraft.skills.api.exceptions.CombatException; import de.raidcraft.skills.api.hero.Hero; import de.raidcraft.skills.api.persistance.SkillProperties; import de.raidcraft.skills.api.profession.Profession; import de.raidcraft.skills.api.skill.AbstractSkill; import de.raidcraft.skills.api.skill.SkillInformation; import de.raidcraft.skills.api.trigger.CommandTriggered; import de.raidcraft.skills.tables.THeroSkill; import de.raidcraft.util.EffectUtil; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import java.util.HashSet; import java.util.List; /** * @author Silthus */ @SkillInformation( name = "Blink", description = "Teleportiert dich nach vorne und entfernt alle Stun Effekte.", types = {EffectType.MOVEMENT, EffectType.HELPFUL} ) public class Blink extends AbstractSkill implements CommandTriggered { public Blink(Hero hero, SkillProperties data, Profession profession, THeroSkill database) { super(hero, data, profession, database); } @Override public void runCommand(CommandContext args) throws CombatException { Location loc = getTargetBlock().add(0, 1, 0); Location oldLoc = getHolder().getEntity().getLocation(); List<Block> lineOfSight = getHolder().getEntity().getLineOfSight(new HashSet<Material>(), getTotalRange()); loc.setPitch(oldLoc.getPitch()); loc.setYaw(oldLoc.getYaw()); getHolder().removeEffectTypes(EffectType.DISABLEING); getHolder().getEntity().teleport(loc); EffectUtil.playEffect(oldLoc, Effect.ENDER_SIGNAL, 1); EffectUtil.playEffect(loc, Effect.ENDER_SIGNAL, 2); for (Block block : lineOfSight) { EffectUtil.playEffect(block.getLocation(), Effect.SMOKE, 1); } } }
package br.eti.ns.nssuite.requisicoes.cte; import br.eti.ns.nssuite.requisicoes._genericos.DownloadReq; public class DownloadReqCTe extends DownloadReq { public String chCTe; public String CNPJ; }
package bai_tap; import java.util.ArrayList; public class InsertionSort { public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<>(); arr.add(4); arr.add(3); arr.add(2); arr.add(10); arr.add(1); arr.add(5); arr.add(6); System.out.println(arr); insertionSort(arr); } public static void insertionSort(ArrayList<Integer> arr) { for (int i = 1; i < arr.size(); i++) { int key = arr.get(i); System.out.println("key " + key); int currentMaxIndex = i - 1; while (currentMaxIndex > -1) { int comparedNum = arr.get(currentMaxIndex); if (key < comparedNum) { System.out.println(key + " < " + comparedNum); currentMaxIndex--; } else { System.out.println(key + " > " + comparedNum); System.out.println("Move " + key + " to position after " + comparedNum); break; } } if(currentMaxIndex == -1) System.out.println("Move " + key + " to first position"); arr.add(currentMaxIndex + 1, key); arr.remove(i + 1); System.out.println(arr); } } }
package com.xp.template.framework.utils; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.xp.template.framework.R; import com.xp.template.framework.config.XPConfig; /** * describe * date 2018/5/15 * author xugaopan */ public class ToastUtils { public static void show(String msg){ Toast toast=makeToast(); TextView tvMsg = (TextView) toast.getView().getTag(R.id.toast_content); tvMsg.setText(msg); toast.show(); } private static Toast makeToast() { Toast toast = new Toast(XPConfig.getAppCtx()); View view = LayoutInflater.from(XPConfig.getAppCtx()).inflate(R.layout.lib_utils_view_toast, null); TextView tvMsg = view.findViewById(R.id.toast_content); view.setTag(R.id.toast_content, tvMsg); toast.setView(view); toast.setGravity(Gravity.CENTER, 0, 0); return toast; } }
/** * Spring Framework configuration files. */ package com.staj.proje.config;
package javaBean; public class Image { private String id=""; private String fileName=""; private String fileClass=""; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileClass() { return fileClass; } public void setFileClass(String fileClass) { this.fileClass = fileClass; } }
package com.worldchip.advertising.client.entity; public class Caption { private String fgcolor; private String bgcolor; private float size; private String speed; private boolean isShow; private int showLocation; private int transparency; public String getFgcolor() { return fgcolor; } public void setFgcolor(String fgcolor) { this.fgcolor = fgcolor; } public String getBgcolor() { return bgcolor; } public void setBgcolor(String bgcolor) { this.bgcolor = bgcolor; } public float getSize() { return size; } public void setSize(float size) { this.size = size; } public String getSpeed() { return speed; } public void setSpeed(String speed) { this.speed = speed; } public boolean isShow() { return isShow; } public void setShow(boolean isShow) { this.isShow = isShow; } public int getShowLocation() { return showLocation; } public void setShowLocation(int showLocation) { this.showLocation = showLocation; } public int getTransparency() { return transparency; } public void setTransparency(int transparency) { this.transparency = transparency; } }
package com.finix.manager.impl; import java.util.HashMap; import java.util.Map; import com.finix.bean.BillingDetailsBean; import com.finix.bean.TemplateBean; import com.finix.bean.TheaterOwnerBean; import com.finix.bean.UserBean; import com.finix.dao.IUserDao; import com.finix.dao.impl.UserDaoImpl; import com.finix.manager.IUserManager; public class UserManagerImpl implements IUserManager { IUserDao userDao = new UserDaoImpl(); //setUserRegisterDetails public UserBean setUserRegisterDetails(UserBean userBean) throws Exception { userBean = userDao.setUserRegisterDetails(userBean); return userBean; } //setSMSDetails public UserBean setSMSDetails(UserBean userBean) throws Exception { userBean = userDao.setSMSDetails(userBean); return userBean; } //setAccountActivationDetails public UserBean setAccountActivationDetails(UserBean userBean) throws Exception { userBean = userDao.setAccountActivationDetails(userBean); return userBean; } //getUserDetails public UserBean getUserDetails(UserBean userBean) throws Exception { userBean = userDao.getUserDetails(userBean); return userBean; } //forgetPasswordForUser public UserBean forgetPasswordForUser(UserBean userBean) throws Exception { userBean = userDao.forgetPasswordForUser(userBean); return userBean; } //getSearchLocationDetail public UserBean getSearchCategoryDetail(UserBean userBean) throws Exception { userBean = userDao.getSearchCategoryDetail(userBean); return userBean; } //getCityDetail public Map<Integer, String> getCityDetail() throws Exception { Map<Integer, String> citymap = new HashMap<Integer, String>(); citymap = userDao.getCityDetail(); return citymap; } //getCitywiseMovieDetail created by ramya 18-08-18 public UserBean getCitywiseMovieDetail(UserBean userBean) throws Exception { userBean = userDao.getCitywiseMovieDetail(userBean); return userBean; } //getMoviewiseTheaterDetail created by ramya 18-08-18 public TheaterOwnerBean getMoviewiseTheaterDetail( TheaterOwnerBean theaterOwnerBean) throws Exception { theaterOwnerBean = userDao.getMoviewiseTheaterDetail(theaterOwnerBean); return theaterOwnerBean; } //getSearchTheaterDetail created by ramya 18-08-18 public TheaterOwnerBean getSearchTheaterDetail(TheaterOwnerBean theaterOwnerBean) throws Exception { theaterOwnerBean = userDao.getSearchTheaterDetail(theaterOwnerBean); return theaterOwnerBean; } //getCityMovieDetail created by ramya 20-08-18 public TheaterOwnerBean getCityMovieDetail(TheaterOwnerBean theaterOwnerBean) throws Exception { theaterOwnerBean = userDao.getCityMovieDetail(theaterOwnerBean); return theaterOwnerBean; } //getTheaterMovieDetail created by ramya 20-08-18 public TheaterOwnerBean getTheaterMovieDetail( TheaterOwnerBean theaterOwnerBean) throws Exception { theaterOwnerBean = userDao.getTheaterMovieDetail(theaterOwnerBean); return theaterOwnerBean; } //getMasterMoviePosterImage created by ramya 20-08-18 public Map<Integer, byte[]> getMasterMoviePosterImage( TheaterOwnerBean theaterOwnerBean) throws Exception { Map<Integer, byte[]> moviePosterMap = new HashMap<Integer,byte[]>(); moviePosterMap = userDao.getMasterMoviePosterImage(theaterOwnerBean); return moviePosterMap; } //getMasterMovieBgPosterImage created by ramya 20-08-18 public Map<Integer, byte[]> getMasterMovieBgPosterImage( TheaterOwnerBean theaterOwnerBean) throws Exception { Map<Integer, byte[]> movieBgPosterMap = new HashMap<Integer,byte[]>(); movieBgPosterMap = userDao.getMasterMovieBgPosterImage(theaterOwnerBean); return movieBgPosterMap; } //getMovieBgPosterCountDetail created by ramya 21-08-18 public TheaterOwnerBean getMovieBgPosterCountDetail( TheaterOwnerBean theaterOwnerBean) throws Exception { theaterOwnerBean = userDao.getMovieBgPosterCountDetail(theaterOwnerBean); return theaterOwnerBean; } //get theatre layout public UserBean getScreenwiseSeatingDetails(UserBean userBean) throws Exception { userBean = userDao.getScreenwiseSeatingDetails(userBean); return userBean; } //set ticket details public UserBean getTicketSoldDetail(UserBean userBean) throws Exception { userBean=userDao.getTicketSoldDetail(userBean); return userBean; } //getOrderSummaryDetails public UserBean getOrderSummaryDetails(UserBean userBean) throws Exception { userBean = userDao.getOrderSummaryDetails(userBean); return userBean; } @Override public BillingDetailsBean getUserPaymentDetails(UserBean userBean, BillingDetailsBean billingDetailsBean) throws Exception { billingDetailsBean=userDao.getUserPaymentDetails(userBean,billingDetailsBean); return billingDetailsBean; } //userPrincingPaymentRedirect public UserBean userPrincingPaymentRedirect(UserBean userBean) throws Exception { userBean = userDao.userPrincingPaymentRedirect(userBean); return userBean; } public UserBean getTheaterScreenDetail(UserBean userBean) throws Exception { userBean=userDao.getTheaterScreenDetail(userBean); return userBean; } @Override public TemplateBean getUserTemp(TemplateBean templateBean) throws Exception { templateBean=userDao.getUserTemp(templateBean); return templateBean; } @Override public UserBean getTheatreLayoutUserViewDetails(UserBean userBean) throws Exception { userBean=userDao.getTheatreLayoutUserViewDetails(userBean); return userBean; } public UserBean setTicketBlockDetails(UserBean userBean) throws Exception { userBean=userDao.setTicketBlockDetails(userBean); return userBean; } //update ticket block public UserBean updateTicketBlockDetails(UserBean userBean) throws Exception { userBean=userDao.updateTicketBlockDetails(userBean); return userBean; } //setUserSeatStatusInActive public UserBean setUserSeatStatusInActive(UserBean userBean) throws Exception { userBean=userDao.setUserSeatStatusInActive(userBean); return userBean; } //setUserContactInformationDetails public UserBean setUserContactInformationDetails(UserBean userBean) throws Exception { userBean=userDao.setUserContactInformationDetails(userBean); return userBean; } //getTaxPercentageDetail public UserBean getTaxPercentageDetail(UserBean userBean) throws Exception { userBean = userDao.getTaxPercentageDetail(userBean); return userBean; } }
package cn.droidlover.xdroid.demo.ui; import android.content.Context; import android.graphics.Bitmap; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.ImageView; import android.widget.RelativeLayout; import android.view.View; import android.widget.TextView; import cn.droidlover.xdroid.demo.R; import cn.droidlover.xdroid.demo.kit.AppKit; /** * Created by Administrator on 2017/5/7 0007. */ public class PersonItem extends RelativeLayout implements View.OnClickListener { Context mContext; TextView mItemName; TextView mItemValue; TextView mItemValue2; ImageView mItemValueImage; ImageView mItemNameImage; ImageView mItemValue2Image; View mLine; View mItemLayout; View mArrow; View.OnClickListener mListener = null; public PersonItem(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View parentView = inflater.inflate(R.layout.person_item, this, true); mItemLayout = (View)findViewById(R.id.item_layout); mItemLayout.setOnClickListener(this); mItemName = (TextView)findViewById(R.id.item_name); mItemValue = (TextView)findViewById(R.id.item_value); mItemValue2 = (TextView)findViewById(R.id.item_value2); mItemValueImage = (ImageView)findViewById(R.id.item_value_image); mItemNameImage = (ImageView)findViewById(R.id.item_name_image); mItemValue2Image = (ImageView)findViewById(R.id.item_value2_image); mLine = (View)findViewById(R.id.line); mArrow = (View)findViewById(R.id.image_arrow); } @Override public void onClick(View view) { if(mListener != null){ mListener.onClick(this); } } public void setItemName(String itemName){ if(itemName == null){ mItemName.setVisibility(View.GONE); return; } mItemName.setText(itemName); } public void setItemValue(String itemValue){ if(itemValue == null){ mItemValue.setVisibility(View.GONE); return; } mItemValue.setVisibility(View.VISIBLE); mItemValue.setText(itemValue); } public void setItemValue2(String itemValue){ if(itemValue == null){ mItemValue2.setVisibility(View.GONE); return; } mItemValue2.setVisibility(View.VISIBLE); mItemValue2.setText(itemValue); } public void setItemValueImage(Bitmap bitmap){ if(bitmap == null){ mItemValueImage.setVisibility(View.GONE); return; } mItemValueImage.setVisibility(View.VISIBLE); mItemValueImage.setImageBitmap(bitmap); Context context = getContext(); int left = AppKit.dip2px(context,12f); int top = AppKit.dip2px(context,5f); int right = AppKit.dip2px(context,12f); int bottom = AppKit.dip2px(context,5f); mItemLayout.setPadding(left,top,right,bottom); } public void setItemValue2Image(int resId){ mItemValue2Image.setVisibility(View.VISIBLE); mItemValue2Image.setImageResource(resId); } public void setItemNameImage(int resId){ mItemNameImage.setVisibility(View.VISIBLE); mItemNameImage.setImageResource(resId); } public void setArrowVisible(int visible){ mArrow.setVisibility(visible); } public View getChildView(String viewId){ if(viewId.equals("item_name")){ return mItemName; } if(viewId.equals("item_value")){ return mItemValue; } if(viewId.equals("item_value_image")){ return mItemValueImage; } if(viewId.equals("item_name_image")){ return mItemNameImage; } if(viewId.equals("line")){ return mLine; } if(viewId.equals("image_arrow")){ return mArrow; } return null; } public void setLineVisible(int visibility){ mLine.setVisibility(visibility); } public void setOnClickListener(View.OnClickListener listener){ mListener = listener; } }
package com.tencent.mm.plugin.account.bind.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.account.a.a.a; class MobileFriendUI$6 implements OnClickListener { final /* synthetic */ MobileFriendUI eIS; MobileFriendUI$6(MobileFriendUI mobileFriendUI) { this.eIS = mobileFriendUI; } public final void onClick(DialogInterface dialogInterface, int i) { g.Ei().DT().set(12322, Boolean.valueOf(false)); ((a) g.n(a.class)).syncUploadMContactStatus(false, true); this.eIS.finish(); } }
package com.yida.design.responsibility.generator; /** ********************* * 定义一个请求和处理等级 * * @author yangke * @version 1.0 * @created 2018年5月12日 下午3:36:11 *********************** */ public class Level { }
package com.tsm.template.security; import com.fasterxml.jackson.databind.ObjectMapper; import com.tsm.template.model.User; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import static com.tsm.template.security.SecurityConstants.EXPIRATION_TIME; public class JWTAuthenticationFilter extends AbstractAuthenticationProcessingFilter { private AuthenticationManager authenticationManager; public JWTAuthenticationFilter(String url, AuthenticationManager authenticationManager) { super(new AntPathRequestMatcher(url)); this.authenticationManager = authenticationManager; } @Override public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException { try { User creds = new ObjectMapper().readValue(req.getInputStream(), User.class); return authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(creds.getEmail(), creds.getPassword(), new ArrayList<>())); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) { String token = Jwts.builder().setSubject(((org.springframework.security.core.userdetails.User) auth.getPrincipal()).getUsername()) .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) .signWith(SignatureAlgorithm.HS512, "").compact(); res.addHeader(SecurityConstants.HEADER_STRING, token); } }
package com.module.model.entity; import com.module.xml.adapters.LocalDateAdapter; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.time.LocalDate; import java.util.UUID; @Entity @Table(name = "military_terms") public class MilitaryTermEntity { @Column(name = "country") private String country; @Column(name = "end_of_military_service") private LocalDate endOfMilitaryService; @Column(name = "locality") private String locality; @Column(name = "start_of_military_service") private LocalDate startOfMilitaryService; @Column(name = "unit") private String unit; @Id @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "com.module.helpers.UuidAutoGenerator") @Column(name = "uuid") private UUID uuid; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "veteran_uuid") private VeteranEntity veteran; public MilitaryTermEntity() { this(null, null, null, null, null, null); } public MilitaryTermEntity(String unit, String country, String locality, LocalDate startOfMilitaryService, LocalDate endOfMilitaryService, VeteranEntity veteran) { this.unit = unit; this.country = country; this.locality = locality; this.startOfMilitaryService = startOfMilitaryService; this.endOfMilitaryService = endOfMilitaryService; this.veteran = veteran; } public boolean equals(Object object) { if (object == this) return true; if ((object == null) || !(object instanceof MilitaryTermEntity)) return false; final MilitaryTermEntity b = (MilitaryTermEntity) object; return uuid != null && b.getUuid() != null && uuid.equals(b.getUuid()); } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public LocalDate getEndOfMilitaryService() { return endOfMilitaryService; } @XmlJavaTypeAdapter(value = LocalDateAdapter.class) public void setEndOfMilitaryService(LocalDate endOfMilitaryService) { this.endOfMilitaryService = endOfMilitaryService; } public String getLocality() { return locality; } public void setLocality(String locality) { this.locality = locality; } public LocalDate getStartOfMilitaryService() { return startOfMilitaryService; } @XmlJavaTypeAdapter(value = LocalDateAdapter.class) public void setStartOfMilitaryService(LocalDate startOfMilitaryService) { this.startOfMilitaryService = startOfMilitaryService; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public UUID getUuid() { return uuid; } public void setUuid(UUID uuid) { this.uuid = uuid; } public VeteranEntity getVeteran() { return veteran; } @XmlTransient public void setVeteran(VeteranEntity veteran) { this.veteran = veteran; } public String toString() { return "Срок службы: " + country + " " + locality + " " + startOfMilitaryService + " " + endOfMilitaryService; } }
package com.hqb.patshop.mbg.dao; import com.hqb.patshop.mbg.model.PmsProductCategory; public interface PmsProductCategoryDao { int deleteByPrimaryKey(Long id); int insert(PmsProductCategory record); int insertSelective(PmsProductCategory record); PmsProductCategory selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(PmsProductCategory record); int updateByPrimaryKey(PmsProductCategory record); PmsProductCategory selectByCategoryName(String categoryName); }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * 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.wso2.charon3.core.protocol.endpoints; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; import org.wso2.charon3.core.attributes.AbstractAttribute; import org.wso2.charon3.core.attributes.Attribute; import org.wso2.charon3.core.attributes.ComplexAttribute; import org.wso2.charon3.core.config.SchemasConfig; import org.wso2.charon3.core.encoder.JSONDecoder; import org.wso2.charon3.core.encoder.JSONEncoder; import org.wso2.charon3.core.exceptions.BadRequestException; import org.wso2.charon3.core.exceptions.CharonException; import org.wso2.charon3.core.exceptions.InternalErrorException; import org.wso2.charon3.core.exceptions.NotFoundException; import org.wso2.charon3.core.exceptions.NotImplementedException; import org.wso2.charon3.core.extensions.UserManager; import org.wso2.charon3.core.objects.AbstractSCIMObject; import org.wso2.charon3.core.objects.ListedResource; import org.wso2.charon3.core.objects.User; import org.wso2.charon3.core.objects.bulk.BulkRequestData; import org.wso2.charon3.core.objects.bulk.BulkResponseData; import org.wso2.charon3.core.protocol.BulkRequestProcessor; import org.wso2.charon3.core.protocol.ResponseCodeConstants; import org.wso2.charon3.core.protocol.SCIMResponse; import org.wso2.charon3.core.schema.ResourceTypeSchema; import org.wso2.charon3.core.schema.SCIMConstants; import org.wso2.charon3.core.schema.SCIMResourceSchemaManager; import org.wso2.charon3.core.schema.SCIMResourceTypeSchema; import org.wso2.charon3.core.schema.ServerSideValidator; import org.wso2.charon3.core.schema.SCIMDefinitions.Mutability; import org.wso2.charon3.core.utils.CopyUtil; import org.wso2.charon3.core.utils.ResourceManagerUtil; import org.wso2.charon3.core.utils.codeutils.ExpressionNode; import org.wso2.charon3.core.utils.codeutils.FilterTreeManager; import org.wso2.charon3.core.utils.codeutils.Node; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.validation.Schema; /** * REST API exposed by Charon-Core to perform bulk operations. * Any SCIM service provider can call this API perform bulk operations, * based on the HTTP requests received by SCIM Client. */ public class BulkResourceManager extends AbstractResourceManager { private Log logger = LogFactory.getLog(BulkResourceManager.class); private JSONEncoder encoder; private JSONDecoder decoder; private BulkRequestProcessor bulkRequestProcessor; public BulkResourceManager() { bulkRequestProcessor = new BulkRequestProcessor(); } public SCIMResponse processBulkData(String data, UserManager userManager) { BulkResponseData bulkResponseData; try { //Get encoder and decoder from AbstractResourceEndpoint encoder = getEncoder(); decoder = getDecoder(); BulkRequestData bulkRequestDataObject; //decode the request bulkRequestDataObject = decoder.decodeBulkData(data); bulkRequestProcessor.setFailOnError(bulkRequestDataObject.getFailOnErrors()); bulkRequestProcessor.setUserManager(userManager); //Get bulk response data bulkResponseData = bulkRequestProcessor.processBulkRequests(bulkRequestDataObject); //encode the BulkResponseData object String finalEncodedResponse = encoder.encodeBulkResponseData(bulkResponseData); //careate SCIM response message Map<String, String> responseHeaders = new HashMap<String, String>(); //add location header responseHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON); //create the final response return new SCIMResponse(ResponseCodeConstants.CODE_OK, finalEncodedResponse, responseHeaders); } catch (CharonException e) { return AbstractResourceManager.encodeSCIMException(e); } catch (BadRequestException e) { return AbstractResourceManager.encodeSCIMException(e); } catch (InternalErrorException e) { return AbstractResourceManager.encodeSCIMException(e); } } @Override public SCIMResponse get(String id, UserManager userManager, String attributes, String excludeAttributes) { return null; } @Override public SCIMResponse create(String scimObjectString, UserManager userManager, String attributes, String excludeAttributes) { return null; } @Override public SCIMResponse delete(String id, UserManager userManager) { return null; } @Override public SCIMResponse listWithGET(UserManager userManager, String filter, int startIndex, int count, String sortBy, String sortOrder, String attributes, String excludeAttributes) { // FilterTreeManager filterTreeManager = null; // Node rootNode = null; JSONEncoder encoder = null; // ExpressionNode expressionNode ; try { //According to SCIM 2.0 spec minus values will be considered as 0 if (count < 0) { count = 0; } //According to SCIM 2.0 spec minus values will be considered as 1 if (startIndex < 1) { startIndex = 1; } if (sortOrder != null) { if (!(sortOrder.equalsIgnoreCase(SCIMConstants.OperationalConstants.ASCENDING) || sortOrder.equalsIgnoreCase(SCIMConstants.OperationalConstants.DESCENDING))) { String error = " Invalid sortOrder value is specified"; throw new BadRequestException(error, ResponseCodeConstants.INVALID_VALUE); } } //If a value for "sortBy" is provided and no "sortOrder" is specified, "sortOrder" SHALL default to // ascending. if (sortOrder == null && sortBy != null) { sortOrder = SCIMConstants.OperationalConstants.ASCENDING; } // unless configured returns core-user schema or else returns extended user schema) SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getShemasResourcesSchema(); /* if (filter != null) { filterTreeManager = new FilterTreeManager(filter, schema); rootNode = filterTreeManager.buildTree(); //Custom Added // Custom Ends Here }*/ //obtain the json encoder encoder = getEncoder(); //get the URIs of required attributes which must be given a value Map<String, Boolean> requiredAttributes = ResourceManagerUtil.getOnlyRequiredAttributesURIs( (SCIMResourceTypeSchema) CopyUtil.deepCopy(schema), attributes, excludeAttributes); List<Object> returnedUsers; int totalResults = 0; //API user should pass a usermanager usermanager to UserResourceEndpoint. if (userManager != null) { System.out.println("$$$..Entered in ListWithGet method..$$$"); List<Object> tempList = listBulk(requiredAttributes, schema); totalResults = (int) tempList.get(0); tempList.remove(0); returnedUsers = tempList; /*for (Object user : returnedUsers) { //perform service provider side validation. ServerSideValidator.validateRetrievedSCIMObjectInList((User) user, schema, attributes, excludeAttributes); }*/ //create a listed resource object out of the returned users list. ListedResource listedResource = createListedResource(returnedUsers, startIndex, totalResults); //convert the listed resource into specific format. String encodedListedResource = encoder.encodeSCIMObject(listedResource); //if there are any http headers to be added in the response header. Map<String, String> responseHeaders = new HashMap<String, String>(); responseHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON); return new SCIMResponse(ResponseCodeConstants.CODE_OK, encodedListedResource, responseHeaders); } else { String error = "Provided user manager handler is null."; //log the error as well. //throw internal server error. throw new InternalErrorException(error); } } catch (CharonException e) { return AbstractResourceManager.encodeSCIMException(e); } catch (NotFoundException e) { return AbstractResourceManager.encodeSCIMException(e); } catch (InternalErrorException e) { return AbstractResourceManager.encodeSCIMException(e); } catch (BadRequestException e) { return AbstractResourceManager.encodeSCIMException(e); } /*catch (NotImplementedException e) { return AbstractResourceManager.encodeSCIMException(e); }*/ // catch (Exception e) { // String error = "Error in tokenization of the input filter"; // CharonException charonException = new CharonException(error); // return AbstractResourceManager.encodeSCIMException(charonException); // } /*catch (IOException e) { // TODO Auto-generated catch block return null; e.printStackTrace(); }*/ } @Override public SCIMResponse listWithPOST(String resourceString, UserManager userManager) { return null; } @Override public SCIMResponse updateWithPUT(String existingId, String scimObjectString, UserManager userManager, String attributes, String excludeAttributes) { return null; } @Override public SCIMResponse updateWithPATCH(String existingId, String scimObjectString, UserManager userManager, String attributes, String excludeAttributes) { return null; } /*@Override public SCIMResponse create(String scimObjectString, CreateUserManager userManager, String attributes, String excludeAttributes) { // TODO Auto-generated method stub return null; }*/ private List<Object> listBulk(Map<String, Boolean> requiredAttributes, ResourceTypeSchema schema){ try { encoder = getEncoder(); decoder = getDecoder(); List<Object> rootObject = new ArrayList<>(); ArrayList<Object[]> attributesSchemes = new ArrayList<Object[]>(); Object [] attributesObjects = new Object[30]; AbstractAttribute attributesObject = new ComplexAttribute(); attributesObject.setCaseExact(false); attributesObject.setDescription("Default description"); attributesObject.setMultiValued(false); attributesObject.setMutability(Mutability.READ_ONLY); attributesObject.setRequired(false); attributesObjects[0] = attributesObject.getCaseExact(); attributesObjects[1] = attributesObject.getDescription(); attributesObjects[2] = attributesObject.getMultiValued(); attributesObjects[3] = attributesObject.getMutability(); attributesObjects[4] = attributesObject.getRequired(); attributesSchemes.add(attributesObjects); SchemasConfig config = SchemasConfig.getInstance(); config.setAttributesSchemes(attributesSchemes); config.setAttribute(attributesObject); // config.setSchema(schema); rootObject.add(0); rootObject.add(config); String scimObjectString = encoder.buildSchemasJsonBody(config.getConfig()); System.out.println("SCIM OBJECT STRING ="+scimObjectString); decoder.decodeResource( scimObjectString, schema, new AbstractSCIMObject()); return (List<Object>) CopyUtil.deepCopy(rootObject); } catch (CharonException | JSONException | BadRequestException | InternalErrorException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } protected ListedResource createListedResource(List<Object> users, int startIndex, int totalResults) throws CharonException, NotFoundException { ListedResource listedResource = new ListedResource(); listedResource.setSchema(SCIMConstants.LISTED_RESOURCE_CORE_SCHEMA_URI); listedResource.setTotalResults(totalResults); listedResource.setStartIndex(startIndex); listedResource.setItemsPerPage(users.size()); for (Object user : users) { Map<String, Attribute> userAttributes = ((SchemasConfig) user).getAttributeList(); listedResource.setResources(userAttributes); } return listedResource; } }
package com.asiainfo.dubbo.merge; import java.util.List; /** * @Description: Merge 业务接口 * * @author chenzq * @date 2019年5月1日 下午6:42:24 * @version V1.0 * @Copyright: Copyright(c) 2019 jaesonchen.com Inc. All rights reserved. */ public interface MenuService { List<String> getMenu(); }