List of usage examples for java.util List add
boolean add(E e);
From source file:joshelser.as2015.query.Query.java
public static void main(String[] args) throws Exception { JCommander commander = new JCommander(); final Opts options = new Opts(); commander.addObject(options);// www . jav a 2 s . c o m commander.setProgramName("Query"); try { commander.parse(args); } catch (ParameterException ex) { commander.usage(); System.err.println(ex.getMessage()); System.exit(1); } ClientConfiguration conf = ClientConfiguration.loadDefault(); if (null != options.clientConfFile) { conf = new ClientConfiguration(new PropertiesConfiguration(options.clientConfFile)); } conf.withInstance(options.instanceName).withZkHosts(options.zookeepers); ZooKeeperInstance inst = new ZooKeeperInstance(conf); Connector conn = inst.getConnector(options.user, new PasswordToken(options.password)); BatchScanner bs = conn.createBatchScanner(options.table, Authorizations.EMPTY, 16); try { bs.setRanges(Collections.singleton(new Range())); final Text categoryText = new Text("category"); bs.fetchColumn(categoryText, new Text("name")); bs.fetchColumn(new Text("review"), new Text("score")); bs.fetchColumn(new Text("review"), new Text("userId")); bs.addScanIterator(new IteratorSetting(50, "wri", WholeRowIterator.class)); final Text colf = new Text(); Map<String, List<Integer>> scoresByUser = new HashMap<>(); for (Entry<Key, Value> entry : bs) { SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue()); Iterator<Entry<Key, Value>> iter = row.entrySet().iterator(); if (!iter.hasNext()) { // row was empty continue; } Entry<Key, Value> categoryEntry = iter.next(); categoryEntry.getKey().getColumnFamily(colf); if (!colf.equals(categoryText)) { throw new IllegalArgumentException("Unknown!"); } if (!categoryEntry.getValue().toString().equals("books")) { // not a book review continue; } if (!iter.hasNext()) { continue; } Entry<Key, Value> reviewScore = iter.next(); if (!iter.hasNext()) { continue; } Entry<Key, Value> reviewUserId = iter.next(); String userId = reviewUserId.getValue().toString(); if (userId.equals("unknown")) { // filter unknow user id continue; } List<Integer> scores = scoresByUser.get(userId); if (null == scores) { scores = new ArrayList<>(); scoresByUser.put(userId, scores); } scores.add(Float.valueOf(reviewScore.getValue().toString()).intValue()); } for (Entry<String, List<Integer>> entry : scoresByUser.entrySet()) { int sum = 0; for (Integer val : entry.getValue()) { sum += val; } System.out.println(entry.getKey() + " => " + new Float(sum) / entry.getValue().size()); } } finally { bs.close(); } }
From source file:net.bioclipse.opentox.api.Dataset.java
public static void main(String[] args) throws Exception { // String service = "http://194.141.0.136:8080/"; String service = "http://apps.ideaconsult.net:8080/ambit2/"; // List<String> sets = getListOfAvailableDatasets(service); // for (String set : sets) System.out.println(set); String dataset = createNewDataset(service, null); List<IMolecule> mols = new ArrayList<IMolecule>(); mols.add(cdk.fromSMILES("COC")); mols.add(cdk.fromSMILES("CNC")); mols.add(cdk.fromSMILES("CC")); addMolecules(dataset, mols);//from w w w . j a va 2 s . c o m // deleteDataset(dataset); }
From source file:com.bitsofproof.supernode.main.Main.java
public static void main(String[] args) throws Exception { log.info("bitsofproof supernode (c) 2013 bits of proof zrt."); log.trace("Spring context setup"); if (args.length == 0) { System.err.println(/*from w w w.j av a 2 s. c o m*/ "Usage: java com.bitsofproof.main.Main profile [profile...] -- [args...] [options...]"); return; } GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); List<String> a = new ArrayList<String>(); boolean profiles = true; for (String s : args) { if (s.equals("--")) { profiles = false; } else { if (profiles) { log.info("Loading profile: " + s); ctx.getEnvironment().addActiveProfile(s); } else { a.add(s); } } } ctx.load("classpath:context/server.xml"); ctx.load("classpath:context/*-profile.xml"); ctx.refresh(); ctx.getBean(App.class).start(a.toArray(new String[0])); }
From source file:de.unisb.cs.st.javalanche.mutation.runtime.jmx.MutationMxClient.java
public static void main(String[] args) throws IOException { List<Integer> noConnection = new ArrayList<Integer>(); boolean oneConnection = false; for (int i = 0; i < 100; i++) { boolean result = connect(i); if (!result) { noConnection.add(i); } else {/*from ww w. j a v a 2 s . c o m*/ oneConnection = true; System.out.println( "--------------------------------------------------------------------------------"); } } if (!oneConnection) { System.out.println("Got no connection for ids: " + noConnection); } analyzeDB(); }
From source file:com.gypsai.ClientFormLogin.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); httppostclient = new DefaultHttpClient(); httppostclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); try {/*from w w w .jav a2 s.c o m*/ String loginUrl = "http://www.cnsfk.com/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes"; //String loginUrl = "http://renren.com/PLogin.do"; String testurl = "http://www.baidu.com"; HttpGet httpget = new HttpGet(testurl); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); //System.out.println(istostring(entity.getContent())); System.out.println("Login form get: " + response.getStatusLine()); EntityUtils.consume(entity); System.out.println("Initial set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { // System.out.println("- " + cookies.get(i).toString()); } } HttpPost httpost = new HttpPost(loginUrl); String password = MD5.MD5Encode("luom1ng"); String redirectURL = "http://www.renren.com/home"; List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", "gypsai@foxmail.com")); nvps.add(new BasicNameValuePair("password", password)); // nvps.add(new BasicNameValuePair("origURL", redirectURL)); // nvps.add(new BasicNameValuePair("domain", "renren.com")); // nvps.add(new BasicNameValuePair("autoLogin", "true")); // nvps.add(new BasicNameValuePair("formName", "")); // nvps.add(new BasicNameValuePair("method", "")); // nvps.add(new BasicNameValuePair("submit", "")); httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); httpost.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.28 (KHTML, like Gecko) Chrome/26.0.1397.2 Safari/537.28"); //posthttpclient //DefaultHttpClient httppostclient = new DefaultHttpClient(); //postheader Header[] pm = httpost.getAllHeaders(); for (Header header : pm) { System.out.println("%%%%->" + header.toString()); } // response = httppostclient.execute(httpost); EntityUtils.consume(response.getEntity()); doget(); // // //httppostclient.getConnectionManager().shutdown(); //cookie List<Cookie> cncookies = httppostclient.getCookieStore().getCookies(); System.out.println("Post logon cookies:"); if (cncookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cncookies.size(); i++) { System.out.println("- " + cncookies.get(i).getName().toString() + " ---->" + cncookies.get(i).getValue().toString()); } } // submit(); //httpheader entity = response.getEntity(); Header[] m = response.getAllHeaders(); for (Header header : m) { //System.out.println("+++->"+header.toString()); } //System.out.println(response.getAllHeaders()); System.out.println(entity.getContentEncoding()); //statusline System.out.println("Login form get: " + response.getStatusLine()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources // httpclient.getConnectionManager().shutdown(); //httppostclient.getConnectionManager().shutdown(); } }
From source file:com.example.dlp.Redact.java
/** Command line application to redact strings, images using the Data Loss Prevention API. */ public static void main(String[] args) throws Exception { OptionGroup optionsGroup = new OptionGroup(); optionsGroup.setRequired(true);//from www .j a v a2s.c o m Option stringOption = new Option("s", "string", true, "redact string"); optionsGroup.addOption(stringOption); Option fileOption = new Option("f", "file path", true, "redact input file path"); optionsGroup.addOption(fileOption); Options commandLineOptions = new Options(); commandLineOptions.addOptionGroup(optionsGroup); Option minLikelihoodOption = Option.builder("minLikelihood").hasArg(true).required(false).build(); commandLineOptions.addOption(minLikelihoodOption); Option replaceOption = Option.builder("r").longOpt("replace string").hasArg(true).required(false).build(); commandLineOptions.addOption(replaceOption); Option infoTypesOption = Option.builder("infoTypes").hasArg(true).required(false).build(); infoTypesOption.setArgs(Option.UNLIMITED_VALUES); commandLineOptions.addOption(infoTypesOption); Option outputFilePathOption = Option.builder("o").hasArg(true).longOpt("outputFilePath").required(false) .build(); commandLineOptions.addOption(outputFilePathOption); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(commandLineOptions, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp(Redact.class.getName(), commandLineOptions); System.exit(1); return; } String replacement = cmd.getOptionValue(replaceOption.getOpt(), "_REDACTED_"); List<InfoType> infoTypesList = new ArrayList<>(); String[] infoTypes = cmd.getOptionValues(infoTypesOption.getOpt()); if (infoTypes != null) { for (String infoType : infoTypes) { infoTypesList.add(InfoType.newBuilder().setName(infoType).build()); } } Likelihood minLikelihood = Likelihood.valueOf( cmd.getOptionValue(minLikelihoodOption.getOpt(), Likelihood.LIKELIHOOD_UNSPECIFIED.name())); // string inspection if (cmd.hasOption("s")) { String source = cmd.getOptionValue(stringOption.getOpt()); redactString(source, replacement, minLikelihood, infoTypesList); } else if (cmd.hasOption("f")) { String filePath = cmd.getOptionValue(fileOption.getOpt()); String outputFilePath = cmd.getOptionValue(outputFilePathOption.getOpt()); redactImage(filePath, minLikelihood, infoTypesList, outputFilePath); } }
From source file:IrqaQuery.java
/** Simple command-line based search demo. */ public static void main(String[] args) throws Exception { String basedir = "/Users/bong/works/research/irqa"; // String basedir = "/home/bgshin/works/irqa"; List<String> exps = new ArrayList<>(); exps.add("_c_2048"); // exps.add("_c_1024"); // exps.add("_c_512"); // exps.add("_c_256"); // exps.add("_c_128"); // exps.add("_c_64"); // exps.add("_c_32"); // exps.add("_c_16"); // exps.add("_c_8"); // exps.add("_c_4"); // exps.add("_c_2"); // exps.add("_c_0"); for (int i = 0; i < exps.size(); i++) { String indexpath = exps.get(i); batch_query(basedir, indexpath); }//from ww w . j a v a2 s . c o m // pipeline ////////////////////////////////////////////////////////////// // JSONParser parser = new JSONParser(); // String lookup_sentfn = basedir+"/data/wikilookup_clean_sentence.json"; // Object obj1 = parser.parse(new FileReader(lookup_sentfn)); // JSONObject lookup_sent = (JSONObject) obj1; // // for (int i=0; i<exps.size(); i++) { // String indexpath = exps.get(i); // pipeline(basedir, indexpath, "dev", lookup_sent); // pipeline(basedir, indexpath, "test", lookup_sent); // pipeline(basedir, indexpath, "train", lookup_sent); // } // pipeline ////////////////////////////////////////////////////////////// }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step6HITPreparator.java
public static void main(String[] args) throws Exception { // input dir - list of xml query containers // step5-linguistic-annotation/ System.err.println("Starting step 6 HIT Preparation"); File inputDir = new File(args[0]); // output dir File outputDir = new File(args[1]); if (outputDir.exists()) { outputDir.delete();//from www .j av a 2 s .c o m } outputDir.mkdir(); List<String> queries = new ArrayList<>(); // iterate over query containers int countClueWeb = 0; int countSentence = 0; for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) { QueryResultContainer queryResultContainer = QueryResultContainer .fromXML(FileUtils.readFileToString(f, "utf-8")); if (queries.contains(f.getName()) || queries.size() == 0) { // groups contain only non-empty documents Map<Integer, List<QueryResultContainer.SingleRankedResult>> groups = new HashMap<>(); // split to groups according to number of sentences for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) { if (rankedResult.originalXmi != null) { byte[] bytes = new BASE64Decoder() .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes())); JCas jCas = JCasFactory.createJCas(); XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas()); Collection<Sentence> sentences = JCasUtil.select(jCas, Sentence.class); int groupId = sentences.size() / 40; if (rankedResult.originalXmi == null) { System.err.println("Empty document: " + rankedResult.clueWebID); } else { if (!groups.containsKey(groupId)) { groups.put(groupId, new ArrayList<>()); } } //handle it groups.get(groupId).add(rankedResult); countClueWeb++; } } for (Map.Entry<Integer, List<QueryResultContainer.SingleRankedResult>> entry : groups.entrySet()) { Integer groupId = entry.getKey(); List<QueryResultContainer.SingleRankedResult> rankedResults = entry.getValue(); // make sure the results are sorted // DEBUG // for (QueryResultContainer.SingleRankedResult r : rankedResults) { // System.out.print(r.rank + "\t"); // } Collections.sort(rankedResults, (o1, o2) -> o1.rank.compareTo(o2.rank)); // iterate over results for one query and group for (int i = 0; i < rankedResults.size() && i < TOP_RESULTS_PER_GROUP; i++) { QueryResultContainer.SingleRankedResult rankedResult = rankedResults.get(i); QueryResultContainer.SingleRankedResult r = rankedResults.get(i); int rank = r.rank; MustacheFactory mf = new DefaultMustacheFactory(); Mustache mustache = mf.compile("template/template.html"); String queryId = queryResultContainer.qID; String query = queryResultContainer.query; // make the first letter uppercase query = query.substring(0, 1).toUpperCase() + query.substring(1); List<String> relevantInformationExamples = queryResultContainer.relevantInformationExamples; List<String> irrelevantInformationExamples = queryResultContainer.irrelevantInformationExamples; byte[] bytes = new BASE64Decoder() .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes())); JCas jCas = JCasFactory.createJCas(); XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas()); List<generators.Sentence> sentences = new ArrayList<>(); List<Integer> paragraphs = new ArrayList<>(); paragraphs.add(0); for (WebParagraph webParagraph : JCasUtil.select(jCas, WebParagraph.class)) { for (Sentence s : JCasUtil.selectCovered(Sentence.class, webParagraph)) { String sentenceBegin = String.valueOf(s.getBegin()); generators.Sentence sentence = new generators.Sentence(s.getCoveredText(), sentenceBegin); sentences.add(sentence); countSentence++; } int SentenceID = paragraphs.get(paragraphs.size() - 1); if (sentences.size() > 120) while (SentenceID < sentences.size()) { if (!paragraphs.contains(SentenceID)) paragraphs.add(SentenceID); SentenceID = SentenceID + 120; } paragraphs.add(sentences.size()); } System.err.println("Output dir: " + outputDir); int startID = 0; int endID; for (int j = 0; j < paragraphs.size(); j++) { endID = paragraphs.get(j); int sentLength = endID - startID; if (sentLength > 120 || j == paragraphs.size() - 1) { if (sentLength > 120) { endID = paragraphs.get(j - 1); j--; } sentLength = endID - startID; if (sentLength <= 40) groupId = 40; else if (sentLength <= 80 && sentLength > 40) groupId = 80; else if (sentLength > 80) groupId = 120; File folder = new File(outputDir + "/" + groupId); if (!folder.exists()) { System.err.println("creating directory: " + outputDir + "/" + groupId); boolean result = false; try { folder.mkdir(); result = true; } catch (SecurityException se) { //handle it } if (result) { System.out.println("DIR created"); } } String newHtmlFile = folder.getAbsolutePath() + "/" + f.getName() + "_" + rankedResult.clueWebID + "_" + sentLength + ".html"; System.err.println("Printing a file: " + newHtmlFile); File newHTML = new File(newHtmlFile); int t = 0; while (newHTML.exists()) { newHTML = new File(folder.getAbsolutePath() + "/" + f.getName() + "_" + rankedResult.clueWebID + "_" + sentLength + "." + t + ".html"); t++; } mustache.execute(new PrintWriter(new FileWriter(newHTML)), new generators(query, relevantInformationExamples, irrelevantInformationExamples, sentences.subList(startID, endID), queryId, rank)) .flush(); startID = endID; } } } } } } System.out.println("Printed " + countClueWeb + " documents with " + countSentence + " sentences"); }
From source file:de.uni_koblenz.jgralab.utilities.tgmerge.TGMerge.java
/** * @param args//w ww .ja v a 2 s . c o m * @throws GraphIOException */ public static void main(String[] args) throws GraphIOException { CommandLine cmdl = processCommandLineOptions(args); String outputFilename = cmdl.getOptionValue('o').trim(); List<Graph> graphs = new LinkedList<>(); for (String g : cmdl.getArgs()) { graphs.add(GraphIO.loadGraphFromFile(g, new ConsoleProgressFunction("Loading"))); } TGMerge tgmerge = new TGMerge(graphs); Graph merged = tgmerge.merge(); GraphIO.saveGraphToFile(merged, outputFilename, new ConsoleProgressFunction("Saving")); }
From source file:com.linecorp.platform.channel.sample.Main.java
public static void main(String[] args) { BusinessConnect bc = new BusinessConnect(); /**/* w ww. j a v a2s .c o m*/ * Prepare the required channel secret and access token */ String channelSecret = System.getenv("CHANNEL_SECRET"); String channelAccessToken = System.getenv("CHANNEL_ACCESS_TOKEN"); if (channelSecret == null || channelSecret.isEmpty() || channelAccessToken == null || channelAccessToken.isEmpty()) { System.err.println("Error! Environment variable CHANNEL_SECRET and CHANNEL_ACCESS_TOKEN not defined."); return; } port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); /** * Define the callback url path */ post("/events", (request, response) -> { String requestBody = request.body(); /** * Verify whether the channel signature is valid or not */ String channelSignature = request.headers("X-LINE-CHANNELSIGNATURE"); if (channelSignature == null || channelSignature.isEmpty()) { response.status(400); return "Please provide valid channel signature and try again."; } if (!bc.validateBCRequest(requestBody, channelSecret, channelSignature)) { response.status(401); return "Invalid channel signature."; } /** * Parse the http request body */ ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance())); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); EventList events; try { events = objectMapper.readValue(requestBody, EventList.class); } catch (IOException e) { response.status(400); return "Invalid request body."; } ApiHttpClient apiHttpClient = new ApiHttpClient(channelAccessToken); /** * Process the incoming messages/operations one by one */ List<String> toUsers; for (Event event : events.getResult()) { switch (event.getEventType()) { case Constants.EventType.MESSAGE: toUsers = new ArrayList<>(); toUsers.add(event.getContent().getFrom()); // @TODO: We strongly suggest you should modify this to process the incoming message/operation async bc.sendTextMessage(toUsers, "You said: " + event.getContent().getText(), apiHttpClient); break; case Constants.EventType.OPERATION: if (event.getContent().getOpType() == Constants.OperationType.ADDED_AS_FRIEND) { String newFriend = event.getContent().getParams().get(0); Profile profile = bc.getProfile(newFriend, apiHttpClient); String displayName = profile == null ? "Unknown" : profile.getDisplayName(); toUsers = new ArrayList<>(); toUsers.add(newFriend); bc.sendTextMessage(toUsers, displayName + ", welcome to be my friend!", apiHttpClient); Connection connection = null; connection = DatabaseUrl.extract().getConnection(); toUsers = bc.getFriends(newFriend, connection); if (toUsers.size() > 0) { bc.sendTextMessage(toUsers, displayName + " just join us, let's welcome him/her!", apiHttpClient); } bc.addFriend(newFriend, displayName, connection); if (connection != null) { connection.close(); } } break; default: // Unknown type? } } return "Events received successfully."; }); get("/", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); attributes.put("message", "Hello World!"); return new ModelAndView(attributes, "index.ftl"); }, new FreeMarkerEngine()); }