use of com.opencsv.CSVWriter in project connect-utils by jcustenborder.
the class RstTemplateHelper method table.
public String table(Table table) {
try (StringWriter writer = new StringWriter()) {
try (IntentedWriter printWriter = new IntentedWriter(writer)) {
printWriter.write(String.format(".. csv-table:: %s\n", table.getTitle()));
printWriter.increase();
printWriter.write(String.format(":header: \"%s\"\n", Joiner.on("\", \"").join(table.getHeaders())));
printWriter.write(":widths: auto\n");
printWriter.println();
try (CSVWriter csvWriter = new CSVWriter(printWriter)) {
final List<String[]> rows = table.getRowData().stream().map(strings -> strings.toArray(new String[strings.size()])).collect(Collectors.toList());
csvWriter.writeAll(rows);
}
}
return writer.toString();
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
use of com.opencsv.CSVWriter in project SIMVA-SoS by SESoS.
the class RobotMain method main.
public static void main(String[] args) throws IOException {
RobotScenario robot = new RobotScenario(0);
Simulator sim = new Simulator(robot);
BaseChecker checker = new BaseChecker();
checker.init(sim.getScenario().getEndTick(), 3, BaseChecker.comparisonType.EQUAL_TO);
SPRTMethod sprt = new SPRTMethod(0.05, 0.05, 0.01);
sprt.setLessCheck();
for (int j = 0; j < 10; j++) {
String outputName = "robot_result/SIM_robot_" + (j + 1) + ".csv";
CSVWriter cw = new CSVWriter(new OutputStreamWriter(new FileOutputStream(outputName), "UTF-8"), ',', '"');
cw.writeNext(new String[] { "prob", "num_of_samples", "result" });
ArrayList<RobotResult> resList = new ArrayList<>();
for (int trial = 1; trial <= 200; trial++) {
for (int i = 1; i < 100; i++) {
double theta = 0.01 * i;
sprt.setExpression(theta);
while (!sprt.checkStopCondition()) {
sim.execute();
System.out.println(checker.evaluateSample(sim.getResult()));
int result = checker.evaluateSample(sim.getResult());
if (result == 1)
result = 0;
else
result = 1;
sprt.updateResult(result);
sim.reset();
}
// Result
boolean h0 = sprt.getResult();
int numSamples = sprt.getNumSamples();
sprt.reset();
if (h0)
System.out.print("T");
else
System.out.print("F");
if (resList.size() < 99)
resList.add(new RobotResult(h0, numSamples, theta));
else {
RobotResult res = resList.get(i - 1);
res.updateResult(numSamples);
resList.set(i - 1, res);
}
}
System.out.println();
}
for (RobotResult r : resList) {
System.out.print(".");
cw.writeNext(r.getArr());
}
System.out.println();
cw.close();
}
}
use of com.opencsv.CSVWriter in project SIMVA-SoS by SESoS.
the class Executor method Perform_Debug_Experiment.
public static void Perform_Debug_Experiment(NormalDistributor distributor, Simulator sim, String caseName) throws IOException {
int endTick = 6000;
for (double alpha_beta : ARR_ALPHA_BETA) {
Date nowDate = new Date();
SimpleDateFormat transFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String pre = transFormat.format(nowDate);
String outputName = caseName + "_result/" + pre + caseName + String.format("%.3f", alpha_beta) + "_debug.csv";
CSVWriter cw = new CSVWriter(new OutputStreamWriter(new FileOutputStream(outputName), "UTF-8"), ',', '"');
// Initialize Patient map
sim.getScenario().init();
// 매번 다른 distribution 이 필요함
ArrayList<Integer> list = new ArrayList<>();
list.clear();
list = distributor.getDistributionArray(500);
sim.setActionPlan(list);
// Simulation!
sim.execute();
SIMResult res = sim.getResult();
HashMap<Integer, DebugTick> debugTraces = sim.getDebugTraces();
sim.reset();
sim.setActionPlan(list);
cw.close();
}
}
use of com.opencsv.CSVWriter in project alf.io by alfio-event.
the class EventApiController method downloadSponsorScanExport.
@RequestMapping("/events/{eventName}/sponsor-scan/export.csv")
public void downloadSponsorScanExport(@PathVariable("eventName") String eventName, HttpServletResponse response, Principal principal) throws IOException {
Event event = loadEvent(eventName, principal);
List<TicketFieldConfiguration> fields = ticketFieldRepository.findAdditionalFieldsForEvent(event.getId());
response.setContentType("text/csv;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + eventName + "-sponsor-scan.csv");
try (ServletOutputStream out = response.getOutputStream();
CSVWriter writer = new CSVWriter(new OutputStreamWriter(out))) {
for (int marker : BOM_MARKERS) {
out.write(marker);
}
List<String> header = new ArrayList<>();
header.add("Username");
header.add("Timestamp");
header.add("Full name");
header.add("Email");
header.addAll(fields.stream().map(TicketFieldConfiguration::getName).collect(toList()));
writer.writeNext(header.toArray(new String[header.size()]));
userManager.findAllEnabledUsers(principal.getName()).stream().map(u -> Pair.of(u, userManager.getUserRole(u))).filter(p -> p.getRight() == Role.SPONSOR).flatMap(p -> sponsorScanRepository.loadSponsorData(event.getId(), p.getKey().getId(), SponsorScanRepository.DEFAULT_TIMESTAMP).stream().map(v -> Pair.of(v, ticketFieldRepository.findAllValuesForTicketId(v.getTicket().getId())))).map(p -> {
DetailedScanData data = p.getLeft();
Map<String, String> descriptions = p.getRight();
return Pair.of(data, fields.stream().map(x -> descriptions.getOrDefault(x.getName(), "")).collect(toList()));
}).map(p -> {
List<String> line = new ArrayList<>();
Ticket ticket = p.getLeft().getTicket();
SponsorScan sponsorScan = p.getLeft().getSponsorScan();
line.add(userManager.findUser(sponsorScan.getUserId()).getUsername());
line.add(sponsorScan.getTimestamp().toString());
line.add(ticket.getFullName());
line.add(ticket.getEmail());
line.addAll(p.getRight());
return line.toArray(new String[line.size()]);
}).forEachOrdered(writer::writeNext);
writer.flush();
out.flush();
}
}
use of com.opencsv.CSVWriter in project alf.io by alfio-event.
the class EventApiController method downloadAllTicketsCSV.
@RequestMapping("/events/{eventName}/export.csv")
public void downloadAllTicketsCSV(@PathVariable("eventName") String eventName, HttpServletRequest request, HttpServletResponse response, Principal principal) throws IOException {
List<String> fields = Arrays.asList(Optional.ofNullable(request.getParameterValues("fields")).orElse(new String[] {}));
Event event = loadEvent(eventName, principal);
Map<Integer, TicketCategory> categoriesMap = eventManager.loadTicketCategories(event).stream().collect(Collectors.toMap(TicketCategory::getId, Function.identity()));
ZoneId eventZoneId = event.getZoneId();
Predicate<String> contains = FIXED_FIELDS::contains;
response.setContentType("text/csv;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + eventName + "-export.csv");
try (ServletOutputStream out = response.getOutputStream();
CSVWriter writer = new CSVWriter(new OutputStreamWriter(out))) {
for (int marker : BOM_MARKERS) {
// UGLY-MODE_ON: specify that the file is written in UTF-8 with BOM, thanks to alexr http://stackoverflow.com/a/4192897
out.write(marker);
}
writer.writeNext(fields.stream().map(f -> {
if (f.startsWith(CUSTOM_FIELDS_PREFIX)) {
return f.substring(CUSTOM_FIELDS_PREFIX.length());
}
return f;
}).toArray(String[]::new));
eventManager.findAllConfirmedTicketsForCSV(eventName, principal.getName()).stream().map(t -> {
List<String> line = new ArrayList<>();
if (fields.contains("ID")) {
line.add(t.getUuid());
}
if (fields.contains("Creation")) {
line.add(t.getCreation().withZoneSameInstant(eventZoneId).toString());
}
if (fields.contains("Category")) {
line.add(categoriesMap.get(t.getCategoryId()).getName());
}
if (fields.contains("Event")) {
line.add(eventName);
}
if (fields.contains("Status")) {
line.add(t.getStatus().toString());
}
if (fields.contains("OriginalPrice")) {
line.add(MonetaryUtil.centsToUnit(t.getSrcPriceCts()).toString());
}
if (fields.contains("PaidPrice")) {
line.add(MonetaryUtil.centsToUnit(t.getFinalPriceCts()).toString());
}
if (fields.contains("Discount")) {
line.add(MonetaryUtil.centsToUnit(t.getDiscountCts()).toString());
}
if (fields.contains("VAT")) {
line.add(MonetaryUtil.centsToUnit(t.getVatCts()).toString());
}
if (fields.contains("ReservationID")) {
line.add(t.getTicketsReservationId());
}
if (fields.contains("Full Name")) {
line.add(t.getFullName());
}
if (fields.contains("First Name")) {
line.add(t.getFirstName());
}
if (fields.contains("Last Name")) {
line.add(t.getLastName());
}
if (fields.contains("E-Mail")) {
line.add(t.getEmail());
}
if (fields.contains("Locked")) {
line.add(String.valueOf(t.getLockedAssignment()));
}
if (fields.contains("Language")) {
line.add(String.valueOf(t.getUserLanguage()));
}
if (fields.contains("Confirmation")) {
line.add(t.getTicketReservation().getConfirmationTimestamp().withZoneSameInstant(eventZoneId).toString());
}
if (fields.contains("Billing Address")) {
line.add(t.getTicketReservation().getBillingAddress());
}
// obviously not optimized
Map<String, String> additionalValues = ticketFieldRepository.findAllValuesForTicketId(t.getId());
fields.stream().filter(contains.negate()).filter(f -> f.startsWith(CUSTOM_FIELDS_PREFIX)).forEachOrdered(field -> {
String customFieldName = field.substring(CUSTOM_FIELDS_PREFIX.length());
line.add(additionalValues.getOrDefault(customFieldName, "").replaceAll("\"", ""));
});
return line.toArray(new String[line.size()]);
}).forEachOrdered(writer::writeNext);
writer.flush();
out.flush();
}
}
Aggregations