List of usage examples for java.lang String split
public String[] split(String regex)
From source file:edu.msu.cme.rdp.multicompare.Main.java
public static void main(String[] args) throws Exception { PrintStream hier_out = null;// w w w . ja v a 2s . c o m PrintWriter assign_out = new PrintWriter(new NullWriter()); PrintStream bootstrap_out = null; File hier_out_filename = null; String propFile = null; File biomFile = null; File metadataFile = null; PrintWriter shortseq_out = null; List<MCSample> samples = new ArrayList(); ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank; float conf = CmdOptions.DEFAULT_CONF; String gene = null; int min_bootstrap_words = Classifier.MIN_BOOTSTRSP_WORDS; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) { assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT)); } else { throw new IllegalArgumentException("Require the output file for classification assignment"); } if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) { hier_out_filename = new File(line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT)); hier_out = new PrintStream(hier_out_filename); } if (line.hasOption(CmdOptions.BIOMFILE_SHORT_OPT)) { biomFile = new File(line.getOptionValue(CmdOptions.BIOMFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.METADATA_SHORT_OPT)) { metadataFile = new File(line.getOptionValue(CmdOptions.METADATA_SHORT_OPT)); } if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) { if (gene != null) { throw new IllegalArgumentException( "Already specified the gene from the default location. Can not specify train_propfile"); } else { propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT); } } if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) { String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT); if (f.equalsIgnoreCase("allrank")) { format = ClassificationResultFormatter.FORMAT.allRank; } else if (f.equalsIgnoreCase("fixrank")) { format = ClassificationResultFormatter.FORMAT.fixRank; } else if (f.equalsIgnoreCase("filterbyconf")) { format = ClassificationResultFormatter.FORMAT.filterbyconf; } else if (f.equalsIgnoreCase("db")) { format = ClassificationResultFormatter.FORMAT.dbformat; } else if (f.equalsIgnoreCase("biom")) { format = ClassificationResultFormatter.FORMAT.biom; } else { throw new IllegalArgumentException( "Not an valid output format, only allrank, fixrank, biom, filterbyconf and db allowed"); } } if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) { if (propFile != null) { throw new IllegalArgumentException( "Already specified train_propfile. Can not specify gene any more"); } gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase(); if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) { throw new IllegalArgumentException(gene + " not found, choose from" + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", " + ClassifierFactory.FUNGALITS_warcup_GENE + ", " + ClassifierFactory.FUNGALITS_unite_GENE); } } if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) { min_bootstrap_words = Integer .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)); if (min_bootstrap_words < Classifier.MIN_BOOTSTRSP_WORDS) { throw new IllegalArgumentException(CmdOptions.MIN_BOOTSTRAP_WORDS_LONG_OPT + " must be at least " + Classifier.MIN_BOOTSTRSP_WORDS); } } if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) { String confString = line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT); try { conf = Float.valueOf(confString); } catch (NumberFormatException e) { throw new IllegalArgumentException("Confidence must be a decimal number"); } if (conf < 0 || conf > 1) { throw new IllegalArgumentException("Confidence must be in the range [0,1]"); } } if (line.hasOption(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)) { shortseq_out = new PrintWriter(line.getOptionValue(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)) { bootstrap_out = new PrintStream(line.getOptionValue(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)); } if (format.equals(ClassificationResultFormatter.FORMAT.biom) && biomFile == null) { throw new IllegalArgumentException("biom format requires an input biom file"); } if (biomFile != null) { // if input biom file provided, use biom format format = ClassificationResultFormatter.FORMAT.biom; } args = line.getArgs(); for (String arg : args) { String[] inFileNames = arg.split(","); File inputFile = new File(inFileNames[0]); File idmappingFile = null; if (!inputFile.exists()) { throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[0] + "\""); } if (inFileNames.length == 2) { idmappingFile = new File(inFileNames[1]); if (!idmappingFile.exists()) { throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[1] + "\""); } } MCSample nextSample = new MCSample(inputFile, idmappingFile); samples.add(nextSample); } if (propFile == null && gene == null) { gene = CmdOptions.DEFAULT_GENE; } if (samples.size() < 1) { throw new IllegalArgumentException("Require at least one sample files"); } } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(80, " [options] <samplefile>[,idmappingfile] ...", "", options, ""); return; } MultiClassifier multiClassifier = new MultiClassifier(propFile, gene, biomFile, metadataFile); MultiClassifierResult result = multiClassifier.multiCompare(samples, conf, assign_out, format, min_bootstrap_words); assign_out.close(); if (hier_out != null) { DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(hier_out, samples); result.getRoot().topDownVisit(printVisitor); hier_out.close(); if (multiClassifier.hasCopyNumber()) { // print copy number corrected counts File cn_corrected_s = new File(hier_out_filename.getParentFile(), "cnadjusted_" + hier_out_filename.getName()); PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s); printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true); result.getRoot().topDownVisit(printVisitor); cn_corrected_hier_out.close(); } } if (bootstrap_out != null) { for (MCSample sample : samples) { MCSamplePrintUtil.printBootstrapCountTable(bootstrap_out, sample); } bootstrap_out.close(); } if (shortseq_out != null) { for (String id : result.getBadSequences()) { shortseq_out.write(id + "\n"); } shortseq_out.close(); } }
From source file:com.auditbucket.client.Importer.java
public static void main(String args[]) { try {//from ww w . ja v a 2 s .com ArgumentParser parser = ArgumentParsers.newArgumentParser("ABImport").defaultHelp(true) .description("Import file formats to AuditBucket"); parser.addArgument("-s", "--server").setDefault("http://localhost/ab-engine") .help("Host URL to send files to"); parser.addArgument("-b", "--batch").setDefault(100).help("Default batch size"); parser.addArgument("-x", "--xref").setDefault(false).help("Cross References Only"); parser.addArgument("files").nargs("*").help( "Path and filename of Audit records to import in the format \"[/filepath/filename.ext],[com.import.YourClass],{skipCount}\""); Namespace ns = null; try { ns = parser.parseArgs(args); } catch (ArgumentParserException e) { parser.handleError(e); System.exit(1); } List<String> files = ns.getList("files"); if (files.isEmpty()) { parser.handleError(new ArgumentParserException("No files to parse", parser)); System.exit(1); } String b = ns.getString("batch"); int batchSize = 100; if (b != null && !"".equals(b)) batchSize = Integer.parseInt(b); StopWatch watch = new StopWatch(); watch.start(); logger.info("*** Starting {}", DateFormat.getDateTimeInstance().format(new Date())); long totalRows = 0; for (String file : files) { int skipCount = 0; List<String> items = Arrays.asList(file.split("\\s*,\\s*")); if (items.size() == 0) parser.handleError(new ArgumentParserException("No file arguments to process", parser)); int item = 0; String fileName = null; String fileClass = null; for (String itemArg : items) { if (item == 0) { fileName = itemArg; } else if (item == 1) { fileClass = itemArg; } else if (item == 2) skipCount = Integer.parseInt(itemArg); item++; } logger.debug("*** Calculated process args {}, {}, {}, {}", fileName, fileClass, batchSize, skipCount); totalRows = totalRows + processFile(ns.get("server").toString(), fileName, (fileClass != null ? Class.forName(fileClass) : null), batchSize, skipCount); } endProcess(watch, totalRows); logger.info("Finished at {}", DateFormat.getDateTimeInstance().format(new Date())); } catch (Exception e) { logger.error("Import error", e); } }
From source file:com.mgmtp.jfunk.core.JFunk.java
/** * Starts jFunk.//from w w w. j ava2 s. c o m * * <pre> * -threadcount=<count> Optional Number of threads to be used. Allows for parallel * execution of test scripts. * -parallel Optional Allows a single script to be executed in parallel * depending on the number of threads specified. The * argument is ignored if multiple scripts are specified. * <script parameters> Optional Similar to Java system properties they can be provided * as key-value-pairs preceded by -S, e.g. -Skey=value. * These parameters are then available in the script as * Groovy variables. * <script(s)> Required At least one test script must be specified. * * Example: * java -cp <jFunkClasspath> com.mgmtp.jfunk.core.JFunk -Skey=value -threadcount=4 -parallel mytest.script * </pre> * * @param args * The program arguments. */ public static void main(final String[] args) { SLF4JBridgeHandler.install(); boolean exitWithError = true; StopWatch stopWatch = new StopWatch(); try { RESULT_LOG.info("jFunk started"); stopWatch.start(); int threadCount = 1; boolean parallel = false; Properties scriptProperties = new Properties(); List<File> scripts = Lists.newArrayList(); for (String arg : args) { if (arg.startsWith("-threadcount")) { String[] split = arg.split("="); Preconditions.checkArgument(split.length == 2, "The number of threads must be specified as follows: -threadcount=<value>"); threadCount = Integer.parseInt(split[1]); RESULT_LOG.info("Using " + threadCount + (threadCount == 1 ? " thread" : " threads")); } else if (arg.startsWith("-S")) { arg = arg.substring(2); String[] split = arg.split("="); Preconditions.checkArgument(split.length == 2, "Script parameters must be given in the form -S<name>=<value>"); scriptProperties.setProperty(split[0], normalizeScriptParameterValue(split[1])); RESULT_LOG.info("Using script parameter " + split[0] + " with value " + split[1]); } else if (arg.equals("-parallel")) { parallel = true; RESULT_LOG.info("Using parallel mode"); } else { scripts.add(new File(arg)); } } if (scripts.isEmpty()) { scripts.addAll(requestScriptsViaGui()); if (scripts.isEmpty()) { RESULT_LOG.info("Execution finished (took " + stopWatch + " H:mm:ss.SSS)"); System.exit(0); } } String propsFileName = System.getProperty("jfunk.props.file", "jfunk.properties"); Module module = ModulesLoader.loadModulesFromProperties(new JFunkDefaultModule(), propsFileName); Injector injector = Guice.createInjector(module); JFunkFactory factory = injector.getInstance(JFunkFactory.class); JFunkBase jFunk = factory.create(threadCount, parallel, scripts, scriptProperties); jFunk.execute(); exitWithError = false; } catch (JFunkExecutionException ex) { // no logging necessary } catch (Exception ex) { Logger.getLogger(JFunk.class).error("jFunk terminated unexpectedly.", ex); } finally { stopWatch.stop(); RESULT_LOG.info("Execution finished (took " + stopWatch + " H:mm:ss.SSS)"); } System.exit(exitWithError ? -1 : 0); }
From source file:module.entities.NameFinder.RegexNameFinder.java
/** * @param args the command line arguments *//*from www . j ava2s .c o m*/ public static void main(String[] args) throws SQLException, IOException { if (args.length == 1) { Config.configFile = args[0]; } long lStartTime = System.currentTimeMillis(); Timestamp startTime = new Timestamp(lStartTime); System.out.println("Regex Name Finder process started at: " + startTime); DB.initPostgres(); regexerId = DB.LogRegexFinder(lStartTime); initLexicons(); JSONObject obj = new JSONObject(); TreeMap<Integer, String> consultations = DB.getDemocracitConsultationBody(); Document doc; int count = 0; TreeMap<Integer, String> consFoundNames = new TreeMap<>(); TreeMap<Integer, String> consFoundRoles = new TreeMap<>(); for (int consId : consultations.keySet()) { String consBody = consultations.get(consId); String signName = "", roleName = ""; doc = Jsoup.parse(consBody); Elements allPars = new Elements(); Elements paragraphs = doc.select("p"); for (Element par : paragraphs) { if (par.html().contains("<br>")) { String out = "<p>" + par.html().replaceAll("<br>", "</p><p>") + "</p>"; Document internal_doc = Jsoup.parse(out); Elements subparagraphs = internal_doc.select("p"); allPars.addAll(subparagraphs); } else { allPars.add(par); } // System.out.println(formatedText); } String signature = getSignatureFromParagraphs(allPars); // System.out.println(signature); if (signature.contains("#")) { String[] sign_tokens = signature.split("#"); signName = sign_tokens[0]; if (sign_tokens.length > 1) { roleName = sign_tokens[1]; } consFoundNames.put(consId, signName.trim()); consFoundRoles.put(consId, roleName.trim()); count++; } else { System.err.println("--" + consId); } // } DB.insertDemocracitConsultationMinister(consFoundNames, consFoundRoles); TreeMap<Integer, String> consultationsCompletedText = DB.getDemocracitCompletedConsultationBody(); Document doc2; TreeMap<Integer, String> complConsFoundNames = new TreeMap<>(); int count2 = 0; for (int consId : consultationsCompletedText.keySet()) { String consBody = consultationsCompletedText.get(consId); String signName = "", roleName = ""; doc2 = Jsoup.parse(consBody); // if (doc.text().contains("<br>")) { // doc.text().replaceAll("(<[Bb][Rr]>)+", "<p>"); // } Elements allPars = new Elements(); Elements paragraphs = doc2.select("p"); for (Element par : paragraphs) { if (par.html().contains("<br>")) { String out = "<p>" + par.html().replaceAll("<br>", "</p><p>") + "</p>"; Document internal_doc = Jsoup.parse(out); Elements subparagraphs = internal_doc.select("p"); allPars.addAll(subparagraphs); } else { allPars.add(par); } } String signature = getSignatureFromParagraphs(allPars); if (signature.contains("#")) { String[] sign_tokens = signature.split("#"); signName = sign_tokens[0]; if (sign_tokens.length > 1) { roleName = sign_tokens[1]; } consFoundNames.put(consId, signName.trim()); consFoundRoles.put(consId, roleName.trim()); // System.out.println(consId); // System.out.println(signName.trim()); // System.out.println("***************"); count2++; } else { System.err.println("++" + consId); } } DB.insertDemocracitConsultationMinister(complConsFoundNames, consFoundRoles); long lEndTime = System.currentTimeMillis(); System.out.println("Regex Name Finder process finished at: " + startTime); obj.put("message", "Regex Name Finder finished with no errors"); obj.put("details", ""); DB.UpdateLogRegexFinder(lEndTime, regexerId, obj); DB.close(); }
From source file:zz.pseas.ghost.login.weibo.WeibocnLogin.java
public static void main(String[] args) throws NullPointerException { // ?URL/*from w ww .j av a 2 s.c o m*/ String Loginurl = "http://login.weibo.cn/login/"; String firstpage = "http://weibo.cn/?vt=4"; // ?? String loginnum = "test"; String loginpwd = "test"; CloseableHttpClient httpclient = HttpClients.createDefault(); // HttpGet httpget = new HttpGet(Loginurl); try { CloseableHttpResponse response = httpclient.execute(httpget); String responhtml = null; try { responhtml = EntityUtils.toString(response.getEntity()); // System.out.println(responhtml); } catch (IOException e1) { e1.printStackTrace(); } // vk?,splithtml,?? String vk = responhtml.split("<input type=\"hidden\" name=\"vk\" value=\"")[1].split("\" /><input")[0]; System.out.println(vk); String pass = vk.split("_")[0]; String finalpass = "password_" + pass; System.out.println(finalpass); response.close(); List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>(); pairs.add(new BasicNameValuePair("mobile", loginnum)); pairs.add(new BasicNameValuePair(finalpass, loginpwd)); pairs.add(new BasicNameValuePair("remember", "on")); pairs.add(new BasicNameValuePair("vk", vk)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, Consts.UTF_8); // HttpPost httppost = new HttpPost(Loginurl); httppost.setEntity(entity); // ??? CloseableHttpResponse response2 = httpclient.execute(httppost); System.out.println(response2.getStatusLine().toString()); httpclient.execute(httppost); // ? System.out.println("success"); HttpGet getinfo = new HttpGet("http://m.weibo.cn/p/100803?vt=4"); CloseableHttpResponse res; res = httpclient.execute(getinfo); System.out.println("??:"); // ?html System.out.println(EntityUtils.toString(res.getEntity())); res.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:enrichment.Disambiguate.java
/**prerequisites: * cd silk_2.5.3/*_links//from w w w . jav a 2 s . c om * cat *.nt|sort -t' ' -k3 > $filename * * @param args $filename * @throws IOException * @throws URISyntaxException */ public static void main(String[] args) { File file = new File(args[0]); if (file.isDirectory()) { args = file.list(new OnlyExtFilenameFilter("nt")); } BufferedReader in; for (int q = 0; q < args.length; q++) { String filename = null; if (file.isDirectory()) { filename = file.getPath() + File.separator + args[q]; } else { filename = args[q]; } try { FileWriter output = new FileWriter(filename + "_disambiguated.nt"); String prefix = "@prefix rdrel: <http://rdvocab.info/RDARelationshipsWEMI/> .\n" + "@prefix dbpedia: <http://de.dbpedia.org/resource/> .\n" + "@prefix frbr: <http://purl.org/vocab/frbr/core#> .\n" + "@prefix lobid: <http://lobid.org/resource/> .\n" + "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n" + "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n" + "@prefix mo: <http://purl.org/ontology/mo/> .\n" + "@prefix wikipedia: <https://de.wikipedia.org/wiki/> ."; output.append(prefix + "\n\n"); in = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); HashMap<String, HashMap<String, ArrayList<String>>> hm = new HashMap<String, HashMap<String, ArrayList<String>>>(); String s; HashMap<String, ArrayList<String>> hmLobid = new HashMap<String, ArrayList<String>>(); Stack<String> old_object = new Stack<String>(); while ((s = in.readLine()) != null) { String[] triples = s.split(" "); String object = triples[2].substring(1, triples[2].length() - 1); if (old_object.size() > 0 && !old_object.firstElement().equals(object)) { hmLobid = new HashMap<String, ArrayList<String>>(); old_object = new Stack<String>(); } old_object.push(object); String subject = triples[0].substring(1, triples[0].length() - 1); System.out.print("\nSubject=" + object); System.out.print("\ntriples[2]=" + triples[2]); hmLobid.put(subject, getAllCreators(new URI(subject))); hm.put(object, hmLobid); } // get all dbpedia resources for (String key_one : hm.keySet()) { System.out.print("\n==============\n==== " + key_one + "\n==============="); int resources_cnt = hm.get(key_one).keySet().size(); ArrayList<String>[] creators = new ArrayList[resources_cnt]; HashMap<String, Integer> creators_backed = new HashMap<String, Integer>(); int x = 0; // get all lobid_resources subsumed under the dbpedia resource for (String subject_uri : hm.get(key_one).keySet()) { creators[x] = new ArrayList<String>(); System.out.print("\n subject_uri=" + subject_uri); Iterator<String> ite = hm.get(key_one).get(subject_uri).iterator(); int y = 0; // get all creators of the lobid resource while (ite.hasNext()) { String creator = ite.next(); System.out.print("\n " + creator); if (creators_backed.containsKey(creator)) { y = creators_backed.get(creator); } else { y = creators_backed.size(); creators_backed.put(creator, y); } while (creators[x].size() <= y) { creators[x].add("-"); } creators[x].set(y, creator); y++; } x++; } if (creators_backed.size() == 1) { System.out .println("\n" + "Every resource pointing to " + key_one + " has the same creator!"); for (String key_two : hm.get(key_one).keySet()) { output.append("<" + key_two + "> rdrel:workManifested <" + key_one + "> .\n"); output.append("<" + key_two + "> mo:wikipedia <" + key_one.replaceAll("dbpedia\\.org/resource", "wikipedia\\.org/wiki") + "> .\n"); } } /*else { for (int a = 0; a < creators.length; a++) { System.out.print(creators[a].toString()+","); } }*/ } output.flush(); if (output != null) { output.close(); } } catch (Exception e) { System.out.print("Exception while working on " + filename + ": \n"); e.printStackTrace(System.out); } } }
From source file:fuse.okuyamafs.OkuyamaFuse.java
public static void main(String[] args) { String fuseArgs[] = new String[args.length - 1]; System.arraycopy(args, 0, fuseArgs, 0, fuseArgs.length); ImdstDefine.valueCompresserLevel = 9; try {/*from ww w . java 2s . c o m*/ String okuyamaStr = args[args.length - 1]; // Raid0????????? if (okuyamaStr.indexOf("#") != -1) { stripingDataBlock = true; okuyamaStr = okuyamaStr.substring(0, (okuyamaStr.length() - 1)); } String[] masterNodeInfos = null; if (okuyamaStr.indexOf(",") != -1) { masterNodeInfos = okuyamaStr.split(","); } else { masterNodeInfos = (okuyamaStr + "," + okuyamaStr).split(","); } // 1=Memory // 2=okuyama // 3=LocalCacheOkuyama String[] optionParams = { "2", "true" }; String fsystemMode = optionParams[0].trim(); boolean singleFlg = new Boolean(optionParams[1].trim()).booleanValue(); OkuyamaFilesystem.storageType = new Integer(fsystemMode).intValue(); if (OkuyamaFilesystem.storageType == 1) OkuyamaFilesystem.blockSize = OkuyamaFilesystem.blockSize; CoreMapFactory.init(new Integer(fsystemMode.trim()).intValue(), masterNodeInfos, stripingDataBlock); FilesystemCheckDaemon loopDaemon = new FilesystemCheckDaemon(1, fuseArgs[fuseArgs.length - 1]); loopDaemon.start(); if (OkuyamaFilesystem.storageType == 2) { FilesystemCheckDaemon bufferCheckDaemon = new FilesystemCheckDaemon(2, null); bufferCheckDaemon.start(); } Runtime.getRuntime().addShutdownHook(new JVMShutdownSequence()); FuseMount.mount(fuseArgs, new OkuyamaFilesystem(fsystemMode, singleFlg), log); } catch (Exception e) { e.printStackTrace(); } }
From source file:net.navasoft.madcoin.backend.services.security.Encrypter.java
/** * The main method.// w w w . jav a 2 s. c o m * * @param args * the arguments * @since 5/08/2014, 08:57:04 PM */ public static void main(String[] args) { try { String raw = "drandx/$2a$14$nv0yHyxSwnROrYnevt66TOx5pVCBr58wFiMOjkZKQScciwsiC18xG"; Encrypter x = new Encrypter("Click-n-Done2014", "madcoins"); String crypted = x.encrypt(raw); System.out.println("este es el token" + crypted); String dec; dec = x.decrypt(crypted); System.out.println(raw.split("/")[1]); System.out.println(dec.split("/")[1]); System.out.println( raw + (BCrypt.checkpw(raw.split("/")[1], dec.split("/")[1]) ? " muchooooo!" : " es mentira")); } catch (BadPaddingException e) { e.printStackTrace(); } }
From source file:org.openimaj.demos.sandbox.flickr.geo.PlotFlickrGeo.java
public static void main(String[] args) throws IOException { final File inputcsv = new File("/Volumes/SSD/training_latlng"); final List<double[]> data = new ArrayList<double[]>(10000000); // read in images final BufferedReader br = new BufferedReader(new FileReader(inputcsv)); String line; int i = 0;// ww w.ja v a 2 s. co m br.readLine(); while ((line = br.readLine()) != null) { final String[] parts = line.split(" "); final double longitude = Double.parseDouble(parts[2]); final double latitude = Double.parseDouble(parts[1]); data.add(new double[] { longitude, latitude }); if (longitude >= -0.1 && longitude < 0 && latitude > 50 && latitude < 54) System.out.println(parts[0] + " " + latitude + " " + longitude); // if (i++ % 10000 == 0) // System.out.println(i); } br.close(); System.out.println("Done reading"); final float[][] dataArr = new float[2][data.size()]; for (i = 0; i < data.size(); i++) { dataArr[0][i] = (float) data.get(i)[0]; dataArr[1][i] = (float) data.get(i)[1]; } final NumberAxis domainAxis = new NumberAxis("X"); domainAxis.setRange(-180, 180); final NumberAxis rangeAxis = new NumberAxis("Y"); rangeAxis.setRange(-90, 90); final FastScatterPlot plot = new FastScatterPlot(dataArr, domainAxis, rangeAxis); final JFreeChart chart = new JFreeChart("Fast Scatter Plot", plot); chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); final ApplicationFrame frame = new ApplicationFrame("Title"); frame.setContentPane(chartPanel); frame.pack(); frame.setVisible(true); }
From source file:cc.twittertools.index.IndexStatuses.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(HELP_OPTION, "show help")); options.addOption(new Option(OPTIMIZE_OPTION, "merge indexes into a single segment")); options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors")); options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory") .create(COLLECTION_OPTION)); options.addOption(/*from www. ja v a 2 s .c om*/ OptionBuilder.withArgName("dir").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("file with deleted tweetids") .create(DELETES_OPTION)); options.addOption(OptionBuilder.withArgName("id").hasArg().withDescription("max id").create(MAX_ID_OPTION)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(COLLECTION_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(IndexStatuses.class.getName(), options); System.exit(-1); } String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION); String indexPath = cmdline.getOptionValue(INDEX_OPTION); final FieldType textOptions = new FieldType(); textOptions.setIndexed(true); textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); textOptions.setStored(true); textOptions.setTokenized(true); if (cmdline.hasOption(STORE_TERM_VECTORS_OPTION)) { textOptions.setStoreTermVectors(true); } LOG.info("collection: " + collectionPath); LOG.info("index: " + indexPath); LongOpenHashSet deletes = null; if (cmdline.hasOption(DELETES_OPTION)) { deletes = new LongOpenHashSet(); File deletesFile = new File(cmdline.getOptionValue(DELETES_OPTION)); if (!deletesFile.exists()) { System.err.println("Error: " + deletesFile + " does not exist!"); System.exit(-1); } LOG.info("Reading deletes from " + deletesFile); FileInputStream fin = new FileInputStream(deletesFile); byte[] ignoreBytes = new byte[2]; fin.read(ignoreBytes); // "B", "Z" bytes from commandline tools BufferedReader br = new BufferedReader(new InputStreamReader(new CBZip2InputStream(fin))); String s; while ((s = br.readLine()) != null) { if (s.contains("\t")) { deletes.add(Long.parseLong(s.split("\t")[0])); } else { deletes.add(Long.parseLong(s)); } } br.close(); fin.close(); LOG.info("Read " + deletes.size() + " tweetids from deletes file."); } long maxId = Long.MAX_VALUE; if (cmdline.hasOption(MAX_ID_OPTION)) { maxId = Long.parseLong(cmdline.getOptionValue(MAX_ID_OPTION)); LOG.info("index: " + maxId); } long startTime = System.currentTimeMillis(); File file = new File(collectionPath); if (!file.exists()) { System.err.println("Error: " + file + " does not exist!"); System.exit(-1); } StatusStream stream = new JsonStatusCorpusReader(file); Directory dir = FSDirectory.open(new File(indexPath)); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_43, IndexStatuses.ANALYZER); config.setOpenMode(OpenMode.CREATE); IndexWriter writer = new IndexWriter(dir, config); int cnt = 0; Status status; try { while ((status = stream.next()) != null) { if (status.getText() == null) { continue; } // Skip deletes tweetids. if (deletes != null && deletes.contains(status.getId())) { continue; } if (status.getId() > maxId) { continue; } cnt++; Document doc = new Document(); doc.add(new LongField(StatusField.ID.name, status.getId(), Field.Store.YES)); doc.add(new LongField(StatusField.EPOCH.name, status.getEpoch(), Field.Store.YES)); doc.add(new TextField(StatusField.SCREEN_NAME.name, status.getScreenname(), Store.YES)); doc.add(new Field(StatusField.TEXT.name, status.getText(), textOptions)); doc.add(new IntField(StatusField.FRIENDS_COUNT.name, status.getFollowersCount(), Store.YES)); doc.add(new IntField(StatusField.FOLLOWERS_COUNT.name, status.getFriendsCount(), Store.YES)); doc.add(new IntField(StatusField.STATUSES_COUNT.name, status.getStatusesCount(), Store.YES)); long inReplyToStatusId = status.getInReplyToStatusId(); if (inReplyToStatusId > 0) { doc.add(new LongField(StatusField.IN_REPLY_TO_STATUS_ID.name, inReplyToStatusId, Field.Store.YES)); doc.add(new LongField(StatusField.IN_REPLY_TO_USER_ID.name, status.getInReplyToUserId(), Field.Store.YES)); } String lang = status.getLang(); if (!lang.equals("unknown")) { doc.add(new TextField(StatusField.LANG.name, status.getLang(), Store.YES)); } long retweetStatusId = status.getRetweetedStatusId(); if (retweetStatusId > 0) { doc.add(new LongField(StatusField.RETWEETED_STATUS_ID.name, retweetStatusId, Field.Store.YES)); doc.add(new LongField(StatusField.RETWEETED_USER_ID.name, status.getRetweetedUserId(), Field.Store.YES)); doc.add(new IntField(StatusField.RETWEET_COUNT.name, status.getRetweetCount(), Store.YES)); if (status.getRetweetCount() < 0 || status.getRetweetedStatusId() < 0) { LOG.warn("Error parsing retweet fields of " + status.getId()); } } writer.addDocument(doc); if (cnt % 100000 == 0) { LOG.info(cnt + " statuses indexed"); } } LOG.info(String.format("Total of %s statuses added", cnt)); if (cmdline.hasOption(OPTIMIZE_OPTION)) { LOG.info("Merging segments..."); writer.forceMerge(1); LOG.info("Done!"); } LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms"); } catch (Exception e) { e.printStackTrace(); } finally { writer.close(); dir.close(); stream.close(); } }