List of usage examples for java.util Date Date
public Date()
From source file:com.hortonworks.minicluster.StartMiniHadoopCluster.java
/** * MAKE SURE to start with enough memory -Xmx2048m -XX:MaxPermSize=256 * * Will start a two node Hadoop DFS/YARN cluster * *///from w w w .ja v a 2 s. c o m public static void main(String[] args) throws Exception { System.out.println("=============== Starting YARN/HDFS MINI CLUSTER ==============="); int nodeCount = 2; logger.info("Starting with " + nodeCount + " nodes"); final MiniHadoopCluster yarnCluster = new MiniHadoopCluster("MINI_YARN_CLUSTER", nodeCount); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { yarnCluster.stop(); System.out.println("=============== Stopped YARN/HDFS MINI CLUSTER ==============="); } }); try { yarnCluster.start(); System.out.println("######## MINI CLUSTER started on " + new Date() + ". ########"); System.out.println("\t - YARN log and work directories are available in target/MINI_YARN_CLUSTER"); System.out.println("\t - DFS log and work directories are available in target/MINI_DFS_CLUSTER"); } catch (Exception e) { // won't actually shut down process. Need to see what's going on logger.error("Failed to start mini cluster", e); yarnCluster.close(); } }
From source file:com.example.java.collections.ArrayExample.java
public static void main(String[] args) { /* ########################################################### */ // Initializing an Array String[] creatures = { "goldfish", "oscar", "guppy", "minnow" }; int[] numbers = new int[10]; int counter = 0; while (counter < numbers.length) { numbers[counter] = counter;//from w ww . ja v a 2 s . co m System.out.println("number[" + counter + "]: " + counter); counter++; } for (int theInt : numbers) { System.out.println(theInt); } //System.out.println(numbers[numbers.length]); /* ########################################################### */ /* ########################################################### */ // Using Charecter Array String name = "Michael"; // Charecter Array char[] charName = name.toCharArray(); System.out.println(charName); // Array Fuctions char[] html = new char[] { 'M', 'i', 'c', 'h', 'a', 'e', 'l' }; char[] lastFour = new char[4]; System.arraycopy(html, 3, lastFour, 0, lastFour.length); System.out.println(lastFour); /* ########################################################### */ /* ########################################################### */ // Using Arrays of Other Types Object[] person = new Object[] { "Michael", new Integer(94), new Integer(1), new Date() }; String fname = (String) person[0]; //ok Integer age = (Integer) person[1]; //ok Date start = (Date) person[2]; //oops! /* ########################################################### */ /* ########################################################### */ // Muti Dimestional Array String[][] bits = { { "Michael", "Ernest", "MFE" }, { "Ernest", "Friedman-Hill", "EFH" }, { "Kathi", "Duggan", "KD" }, { "Jeff", "Kellum", "JK" } }; bits[0] = new String[] { "Rudy", "Polanski", "RP" }; bits[1] = new String[] { "Rudy", "Washington", "RW" }; bits[2] = new String[] { "Rudy", "O'Reilly", "RO" }; /* ########################################################### */ /* ########################################################### */ //Create ArrayList from array String[] stringArray = { "a", "b", "c", "d", "e" }; ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray)); System.out.println(arrayList); // [a, b, c, d, e] /* ########################################################### */ /* ########################################################### */ //Check if an array contains a certain value String[] stringArray1 = { "a", "b", "c", "d", "e" }; boolean b = Arrays.asList(stringArray).contains("a"); System.out.println(b); // true /* ########################################################### */ /* ########################################################### */ //Concatenate two arrays int[] intArray = { 1, 2, 3, 4, 5 }; int[] intArray2 = { 6, 7, 8, 9, 10 }; // Apache Commons Lang library int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2); /* ########################################################### */ /* ########################################################### */ //Joins the elements of the provided array into a single String // Apache common lang String j = StringUtils.join(new String[] { "a", "b", "c" }, ", "); System.out.println(j); // a, b, c /* ########################################################### */ /* ########################################################### */ //Covnert ArrayList to Array String[] stringArray3 = { "a", "b", "c", "d", "e" }; ArrayList<String> arrayList1 = new ArrayList<String>(Arrays.asList(stringArray)); String[] stringArr = new String[arrayList.size()]; arrayList.toArray(stringArr); for (String s : stringArr) { System.out.println(s); } /* ########################################################### */ /* ########################################################### */ //Convert Array to Set Set<String> set = new HashSet<String>(Arrays.asList(stringArray)); System.out.println(set); //[d, e, b, c, a] /* ########################################################### */ /* ########################################################### */ //Reverse an array int[] intArray1 = { 1, 2, 3, 4, 5 }; ArrayUtils.reverse(intArray1); System.out.println(Arrays.toString(intArray1)); //[5, 4, 3, 2, 1] /* ########################################################### */ /* ########################################################### */ // Remove element of an array int[] intArray3 = { 1, 2, 3, 4, 5 }; int[] removed = ArrayUtils.removeElement(intArray3, 3);//create a new array System.out.println(Arrays.toString(removed)); /* ########################################################### */ /* ########################################################### */ byte[] bytes = ByteBuffer.allocate(4).putInt(8).array(); for (byte t : bytes) { System.out.format("0x%x ", t); } /* ########################################################### */ }
From source file:ci6226.buildindex.java
/** * @param args the command line arguments *//*w w w . ja va 2 s.c o m*/ public static void main(String[] args) throws FileNotFoundException, IOException, ParseException { String file = "/home/steven/Dropbox/workspace/ntu_coursework/ci6226/Assiment/yelpdata/yelp_training_set/yelp_training_set_review.json"; JSONParser parser = new JSONParser(); BufferedReader in = new BufferedReader(new FileReader(file)); // List<Document> jdocs = new LinkedList<Document>(); Date start = new Date(); String indexPath = "./myindex"; System.out.println("Indexing to directory '" + indexPath + "'..."); // Analyzer analyzer= new NGramAnalyzer(2,8); Analyzer analyzer = new myAnalyzer(); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_47, analyzer); Directory dir = FSDirectory.open(new File(indexPath)); // :Post-Release-Update-Version.LUCENE_XY: // TODO: try different analyzer,stop words,words steming check size // Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_47); // Add new documents to an existing index: // iwc.setOpenMode(OpenMode.CREATE_OR_APPEND); iwc.setOpenMode(OpenMode.CREATE_OR_APPEND); // Optional: for better indexing performance, if you // are indexing many documents, increase the RAM // buffer. But if you do this, increase the max heap // size to the JVM (eg add -Xmx512m or -Xmx1g): // // iwc.setRAMBufferSizeMB(256.0); IndexWriter writer = new IndexWriter(dir, iwc); // writer.addDocuments(jdocs); int line = 0; while (in.ready()) { String s = in.readLine(); Object obj = JSONValue.parse(s); JSONObject person = (JSONObject) obj; String text = (String) person.get("text"); String user_id = (String) person.get("user_id"); String business_id = (String) person.get("business_id"); String review_id = (String) person.get("review_id"); JSONObject votes = (JSONObject) person.get("votes"); long funny = (Long) votes.get("funny"); long cool = (Long) votes.get("cool"); long useful = (Long) votes.get("useful"); Document doc = new Document(); Field review_idf = new StringField("review_id", review_id, Field.Store.YES); doc.add(review_idf); Field business_idf = new StringField("business_id", business_id, Field.Store.YES); doc.add(business_idf); //http://qindongliang1922.iteye.com/blog/2030639 FieldType ft = new FieldType(); ft.setIndexed(true);// ft.setStored(true);// ft.setStoreTermVectors(true); ft.setTokenized(true); ft.setStoreTermVectorPositions(true);//? ft.setStoreTermVectorOffsets(true);//??? Field textf = new Field("text", text, ft); doc.add(textf); // Field user_idf = new StringField("user_id", user_id, Field.Store.YES); // doc.add(user_idf); // doc.add(new LongField("cool", cool, Field.Store.YES)); // doc.add(new LongField("funny", funny, Field.Store.YES)); // doc.add(new LongField("useful", useful, Field.Store.YES)); writer.addDocument(doc); System.out.println(line++); } writer.close(); Date end = new Date(); System.out.println(end.getTime() - start.getTime() + " total milliseconds"); // BufferedReader in = new BufferedReader(new FileReader(file)); //while (in.ready()) { // String s = in.readLine(); // //System.out.println(s); // JSONObject jsonObject = (JSONObject) ((Object)s); // String rtext = (String) jsonObject.get("text"); // System.out.println(rtext); // //long age = (Long) jsonObject.get("age"); // //System.out.println(age); //} //in.close(); }
From source file:eu.europa.esig.dss.cookbook.example.sign.SigningApplication.java
public static void main(String[] args) throws IOException { preparePKCS12TokenAndKey();/*from www. j av a 2s . c o m*/ DSSDocument toBeSigned = new FileDocument("src/main/resources/xml_example.xml"); XAdESSignatureParameters params = new XAdESSignatureParameters(); params.setSignatureLevel(SignatureLevel.XAdES_BASELINE_B); params.setSignaturePackaging(SignaturePackaging.ENVELOPED); params.setSigningCertificate(privateKey.getCertificate()); params.setCertificateChain(privateKey.getCertificateChain()); params.bLevel().setSigningDate(new Date()); CommonCertificateVerifier commonCertificateVerifier = new CommonCertificateVerifier(); XAdESService service = new XAdESService(commonCertificateVerifier); ToBeSigned dataToSign = service.getDataToSign(toBeSigned, params); SignatureValue signatureValue = signingToken.sign(dataToSign, params.getDigestAlgorithm(), privateKey); DSSDocument signedDocument = service.signDocument(toBeSigned, params, signatureValue); IOUtils.copy(signedDocument.openStream(), System.out); }
From source file:MainClass.java
public static void main(String[] args) throws Exception { String keystoreFile = "keyStoreFile.bin"; String caAlias = "caAlias"; String certToSignAlias = "cert"; String newAlias = "newAlias"; char[] password = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' }; char[] caPassword = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' }; char[] certPassword = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' }; FileInputStream input = new FileInputStream(keystoreFile); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(input, password);//from w ww. ja v a 2 s . c om input.close(); PrivateKey caPrivateKey = (PrivateKey) keyStore.getKey(caAlias, caPassword); java.security.cert.Certificate caCert = keyStore.getCertificate(caAlias); byte[] encoded = caCert.getEncoded(); X509CertImpl caCertImpl = new X509CertImpl(encoded); X509CertInfo caCertInfo = (X509CertInfo) caCertImpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO); X500Name issuer = (X500Name) caCertInfo.get(X509CertInfo.SUBJECT + "." + CertificateIssuerName.DN_NAME); java.security.cert.Certificate cert = keyStore.getCertificate(certToSignAlias); PrivateKey privateKey = (PrivateKey) keyStore.getKey(certToSignAlias, certPassword); encoded = cert.getEncoded(); X509CertImpl certImpl = new X509CertImpl(encoded); X509CertInfo certInfo = (X509CertInfo) certImpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO); Date firstDate = new Date(); Date lastDate = new Date(firstDate.getTime() + 365 * 24 * 60 * 60 * 1000L); CertificateValidity interval = new CertificateValidity(firstDate, lastDate); certInfo.set(X509CertInfo.VALIDITY, interval); certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber((int) (firstDate.getTime() / 1000))); certInfo.set(X509CertInfo.ISSUER + "." + CertificateSubjectName.DN_NAME, issuer); AlgorithmId algorithm = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid); certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algorithm); X509CertImpl newCert = new X509CertImpl(certInfo); newCert.sign(caPrivateKey, "MD5WithRSA"); keyStore.setKeyEntry(newAlias, privateKey, certPassword, new java.security.cert.Certificate[] { newCert }); FileOutputStream output = new FileOutputStream(keystoreFile); keyStore.store(output, password); output.close(); }
From source file:com.heren.turtle.server.utils.SampleDateUtils.java
public static void main(String[] args) { Date d1 = new Date(); Date d2 = new Date(); System.out.println(d1.after(d2)); boolean sameDay = DateUtils.isSameDay(d1, d2); System.out.println(sameDay);/*from w ww.ja va 2 s. co m*/ System.out.println(addDay("2016-11-16", 3)); }
From source file:ArrayToVector.java
public static void main(String[] args) { Object[] a1d = { "Hello World", new Date(), Calendar.getInstance(), }; // Arrays.asList(Object[]) --> List List l = Arrays.asList(a1d); // Vector contstructor takes Collection // List is a subclass of Collection Vector v;//from www .ja va2 s . c o m v = new Vector(l); // Or, more simply: v = new Vector(Arrays.asList(a1d)); // Just to prove that it worked. Enumeration e = v.elements(); while (e.hasMoreElements()) { System.out.println(e.nextElement()); } }
From source file:ch.epfl.lsir.xin.test.GlobalMeanTest.java
/** * @param args// ww w . j a v a 2 s .c o m */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub PrintWriter logger = new PrintWriter(".//results//GlobalMean"); PropertiesConfiguration config = new PropertiesConfiguration(); config.setFile(new File("conf//GlobalMean.properties")); try { config.load(); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data..."); DataLoaderFile loader = new DataLoaderFile(".//data//MoveLens100k.txt"); loader.readSimple(); DataSetNumeric dataset = loader.getDataset(); System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: " + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size()); logger.println("Number of ratings: " + dataset.getRatings().size() + ", Number of users: " + dataset.getUserIDs().size() + ", Number of items: " + dataset.getItemIDs().size()); double totalMAE = 0; double totalRMSE = 0; int F = 5; logger.println(F + "- folder cross validation."); logger.flush(); ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>(); for (int i = 0; i < F; i++) { folders.add(new ArrayList<NumericRating>()); } while (dataset.getRatings().size() > 0) { int index = new Random().nextInt(dataset.getRatings().size()); int r = new Random().nextInt(F); folders.get(r).add(dataset.getRatings().get(index)); dataset.getRatings().remove(index); } for (int folder = 1; folder <= F; folder++) { System.out.println("Folder: " + folder); logger.println("Folder: " + folder); ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>(); ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>(); for (int i = 0; i < folders.size(); i++) { if (i == folder - 1)//test data { testRatings.addAll(folders.get(i)); } else {//training data trainRatings.addAll(folders.get(i)); } } //create rating matrix HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>(); HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>(); for (int i = 0; i < dataset.getUserIDs().size(); i++) { userIDIndexMapping.put(dataset.getUserIDs().get(i), i); } for (int i = 0; i < dataset.getItemIDs().size(); i++) { itemIDIndexMapping.put(dataset.getItemIDs().get(i), i); } RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < trainRatings.size(); i++) { trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()), itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue()); } RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < testRatings.size(); i++) { testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()), itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue()); } System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: " + testRatingMatrix.getTotalRatingNumber()); logger.println("Initialize a recommendation model based on global average method."); GlobalAverage algo = new GlobalAverage(trainRatingMatrix); algo.setLogger(logger); algo.build(); algo.saveModel(".//localModels//" + config.getString("NAME")); logger.println("Save the model."); logger.flush(); System.out.println(trainRatings.size() + " vs. " + testRatings.size()); double RMSE = 0; double MAE = 0; int count = 0; for (int i = 0; i < testRatings.size(); i++) { NumericRating rating = testRatings.get(i); double prediction = algo.predict(rating.getUserID(), rating.getItemID()); if (Double.isNaN(prediction)) { System.out.println("no prediction"); continue; } MAE = MAE + Math.abs(rating.getValue() - prediction); RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2); count++; } MAE = MAE / count; RMSE = Math.sqrt(RMSE / count); // System.out.println("MAE: " + MAE + " RMSE: " + RMSE); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " MAE: " + MAE + " RMSE: " + RMSE); logger.flush(); totalMAE = totalMAE + MAE; totalRMSE = totalRMSE + RMSE; } System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Final results: MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F); logger.flush(); logger.close(); //MAE: 0.9338607074893257 RMSE: 1.1170971131112037 (MovieLens1M) //MAE: 0.9446876509332618 RMSE: 1.1256517870920375 (MovieLens100K) }
From source file:com.isoftstone.proxy.Program.java
public static void main(String[] args) throws IOException { int insertIntervalTime = Integer.valueOf(Config.getValue("proxy_insert_minutes")); int checkIntervalTime = Integer.valueOf(Config.getValue("proxy_check_minute")); SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched;//from w w w . j a va 2 s . c om try { sched = sf.getScheduler(); // ???? JobDetail parseProxyJob = JobBuilder.newJob(ParseProxyJob.class).withIdentity("parseProxyJob", "Group") .build(); SimpleTrigger parseProxyTrigger = (SimpleTrigger) TriggerBuilder .newTrigger().withIdentity("parseProxyJob", "Group").withSchedule(SimpleScheduleBuilder .simpleSchedule().withIntervalInMinutes(insertIntervalTime).repeatForever()) .startAt(new Date()).build(); sched.scheduleJob(parseProxyJob, parseProxyTrigger); // ?? JobDetail checkProxyJob = JobBuilder.newJob(CheckProxyJob.class).withIdentity("checkProxyJob", "Group") .build(); /** * 10s?. */ Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, 10); SimpleTrigger checkProxyTrigger = (SimpleTrigger) TriggerBuilder.newTrigger() .withIdentity("checkProxyJob", "Group").withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInMinutes(checkIntervalTime).repeatForever()) .startAt(calendar.getTime()).build(); sched.scheduleJob(checkProxyJob, checkProxyTrigger); sched.start(); String uriHost = Config.getValue("http_server_host"); URI baseUri = UriBuilder.fromUri(uriHost).port(9998).build(); ResourceConfig config = new ResourceConfig(HttpProxyServer.class); HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, config); } catch (SchedulerException e) { LOG.error("SchedulerException", e); } }
From source file:Reminder.java
public static void main(String[] argv) throws InterruptedException { //+//from www . j a va 2s . c om while (true) { System.out.println(new Date() + "\007"); Thread.sleep(5 * 60 * 1000); } //- }