text
stringlengths
10
2.72M
package evolutionYoutube; import java.util.List; import com.vaadin.ui.Button; import com.vaadin.ui.UI; import database.BD_general; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Grid; public class Lista_Categoria extends Lista_Categoria_ventana { /** * */ private static final long serialVersionUID = 1L; public Categorias _unnamed_Categorias_; //public Vector<Categoria> _unnamed_Categoria_ = new Vector<Categoria>(); public Lista_Categoria() { BD_general bd = new BD_general(); List<database.Categorias> categ = bd.Cargar_Categorias(); System.out.println(categ); Grid<database.Categorias> grid = new Grid<>(); grid.setItems(categ); grid.addColumn(database.Categorias::getNombre).setCaption("Categoría"); grid.addColumn(database.Categorias::getIcono).setCaption("Icono"); grid.addColumn(database.Categorias::getEdad).setCaption("Edad"); grid.setWidth("100%"); contenido.addComponent(grid); MyUI.setGrid(grid); crearcategoria.addClickListener(new Button.ClickListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { ((MyUI) UI.getCurrent()).crearcategoria(); } }); editarcategoria.addClickListener(new Button.ClickListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { ((MyUI) UI.getCurrent()).editarcategoria(grid.getSelectionModel().getFirstSelectedItem().get()); } }); eliminarcategoria.addClickListener(new Button.ClickListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { BD_general bd = new BD_general(); bd.eliminar_categoria(grid.getSelectionModel().getFirstSelectedItem().get().getId_categoria()); ((MyUI) UI.getCurrent()).Categorias(); } }); } }
package by.htp.train04.main; public class StationLogic { public Train[] sortNumTrain(Station station) { Train[] trains = station.getTrains(); int index = 0; Train minTrain; for (int i = 0; i < trains.length - 1; i++) { minTrain = trains[i]; index = i; for (int j = i + 1; j < trains.length; j++) { if (minTrain.getNumberTrain() > trains[j].getNumberTrain()) { minTrain = trains[j]; index = j; Train temp = trains[i]; trains[i] = minTrain; trains[index] = temp; } } } return trains; } public Train[] sortDestination(Station station) { Train[] trains = station.getTrains(); Train minTrain; Train minTrain2; int index; for (int i = 0; i < trains.length - 1; i++) { minTrain = trains[i]; index = i; for (int j = i + 1; j < trains.length; j++) { String str1 = minTrain.getDestination(); String str2 = trains[j].getDestination(); if (str1.compareTo(str2) > 0) { minTrain = trains[j]; index = j; } else if (str1.compareTo(str2) == 0) { minTrain2 = sortTime(minTrain, trains[j]); if (minTrain2 != minTrain) { index = j; } minTrain = minTrain2; } } Train temp = trains[i]; trains[i] = minTrain; trains[index] = temp; } return trains; } public Train sortTime(Train minTrain, Train trains) { if (minTrain.getDate().getHour() > trains.getDate().getHour()) { minTrain = trains; } if (minTrain.getDate().getHour() == trains.getDate().getHour()) { if (minTrain.getDate().getMinute() > trains.getDate().getMinute()) { minTrain = trains; } } return minTrain; } public Train infoTrain(Station station, int num) { Train[] trains = station.getTrains(); for (int i = 0; i < trains.length; i++) { if (trains[i].getNumberTrain() == num) { return trains[i]; } } return null; } }
@Stateless public class gestionReservation implements gestionResaLocal{ }
package th.ku.emailtemplate; import java.util.HashMap; import java.util.Map; public class Template { private String variableData; private String templateText; private Map<String,String> variables; public Template(String templateText){ this.templateText = templateText; this.variables = new HashMap<String, String>(); } public void set(String variable , String data) { this.variables.put(variable, data); } public String evaluate(){ String emilBody = templateText; for (Map.Entry<String,String> entry : variables.entrySet()){ String pattern ="\\$\\{"+ entry.getKey() + "\\}"; emilBody.replaceAll(pattern,entry.getValue()); } return emilBody; } private String replaceVariables() { String result = templateText; for (Map.Entry<String, String> entry : variables.entrySet()) { String regex = "\\$\\{" + entry.getKey() + "\\}"; result = result.replaceAll(regex, entry.getValue()); } return result; } private void checkForMissingValues(String result) { if (result.matches(".*\\$\\{.+\\}.*")) try { throw new MissingValueException(); } catch (MissingValueException e) { e.printStackTrace(); } } }
package io.t99.philesd; import io.t99.philesd.util.NumberBaseConverter; import io.t99.philesd.websocket.WebSocket; public class Philesd { public static void main(String[] args) { // for (byte b: "Hello".getBytes()) { // // System.out.println(b); // // } //WebSocket ws = new WebSocket(1200); //ws.establishServer(); //ws.write("Hello"); for (int i = 0; i < 8; i++) { System.out.println(i + "\t" + NumberBaseConverter.decToBin(i)); } } }
/* * FilterGenotypeTable */ package net.maizegenetics.dna.snp; import net.maizegenetics.dna.map.Chromosome; import net.maizegenetics.dna.map.PositionList; import net.maizegenetics.dna.map.PositionListBuilder; import net.maizegenetics.dna.snp.bit.BitStorage; import net.maizegenetics.dna.snp.bit.DynamicBitStorage; import net.maizegenetics.dna.snp.depth.AlleleDepth; import net.maizegenetics.dna.snp.depth.FilterAlleleDepth; import net.maizegenetics.dna.snp.genotypecall.GenotypeCallTable; import net.maizegenetics.dna.snp.genotypecall.GenotypeCallTableBuilder; import net.maizegenetics.taxa.TaxaList; import net.maizegenetics.taxa.TaxaListBuilder; import net.maizegenetics.taxa.Taxon; import net.maizegenetics.util.BitSet; import org.apache.log4j.Logger; import java.util.*; import net.maizegenetics.dna.map.Position; /** * Taxa and site filtering of GenotypeTables. The class essentially creates * views of the baseGenotypeTable through arrays for indirection. * * @author Terry Casstevens */ public class FilterGenotypeTable implements GenotypeTable { private static final long serialVersionUID = -5197800047652332969L; private static final Logger myLogger = Logger.getLogger(FilterGenotypeTable.class); private final boolean myIsTaxaFilter; private final boolean myIsSiteFilter; private final boolean myIsSiteFilterByRange; private final GenotypeTable myBaseAlignment; private final TaxaList myTaxaList; private final int[] myTaxaRedirect; private final int[] mySiteRedirect; private final int myRangeStart; private final int myRangeEnd; private Chromosome[] myChromosomes; private int[] myChromosomeOffsets; private PositionList myPositionList; private AlleleDepth myAlleleDepth = null; private final GenotypeCallTable myGenotype; private final Map<WHICH_ALLELE, BitStorage> myBitStorage = new HashMap<>(); private FilterGenotypeTable(GenotypeTable a, TaxaList subList, int[] taxaRedirect, FilterGenotypeTable original) { myTaxaList = subList; if (myTaxaList.numberOfTaxa() != taxaRedirect.length) { throw new IllegalArgumentException("FilterGenotypeTable: init: subList should be same size as taxaRedirect."); } myIsTaxaFilter = true; myBaseAlignment = a; myTaxaRedirect = taxaRedirect; if (original == null) { myIsSiteFilter = false; myIsSiteFilterByRange = false; mySiteRedirect = null; myRangeStart = -1; myRangeEnd = -1; myChromosomes = myBaseAlignment.chromosomes(); myChromosomeOffsets = myBaseAlignment.chromosomesOffsets(); } else { myIsSiteFilter = original.isSiteFilter(); myIsSiteFilterByRange = original.isSiteFilterByRange(); mySiteRedirect = original.getSiteRedirect(); myRangeStart = original.getRangeStart(); myRangeEnd = original.getRangeEnd(); myChromosomes = original.chromosomes(); myChromosomeOffsets = original.chromosomesOffsets(); } if (myIsSiteFilter) { myGenotype = GenotypeCallTableBuilder.getFilteredInstance(myBaseAlignment.genotypeMatrix(), numberOfTaxa(), myTaxaRedirect, numberOfSites(), mySiteRedirect); } else { myGenotype = GenotypeCallTableBuilder.getFilteredInstance(myBaseAlignment.genotypeMatrix(), numberOfTaxa(), myTaxaRedirect, numberOfSites(), myRangeStart, myRangeEnd); } } /** * This returns FilterGenotypeTable with only specified subTaxaList. * Defaults to retain unknown taxa. * * @param a alignment * @param subTaxaList subset id group * * @return filter alignment */ public static GenotypeTable getInstance(GenotypeTable a, TaxaList subTaxaList) { return getInstance(a, subTaxaList, true); } /** * This returns FilterGenotypeTable with only specified subTaxaList. If * retainUnknownTaxa is true then Alignment will return unknown values for * missing taxa. * * @param a alignment * @param subTaxaList subset id group * @param retainUnknownTaxa whether to retain unknown taxa * * @return filter alignment */ public static GenotypeTable getInstance(GenotypeTable a, TaxaList subTaxaList, boolean retainUnknownTaxa) { GenotypeTable baseAlignment = a; FilterGenotypeTable original = null; if (baseAlignment instanceof FilterGenotypeTable) { original = (FilterGenotypeTable) a; baseAlignment = ((FilterGenotypeTable) a).getBaseAlignment(); } List<Integer> taxaRedirectList = new ArrayList<Integer>(); List<Taxon> idList = new ArrayList<Taxon>(); boolean noNeedToFilter = true; if (subTaxaList.numberOfTaxa() != a.numberOfTaxa()) { noNeedToFilter = false; } for (int i = 0, n = subTaxaList.numberOfTaxa(); i < n; i++) { int ion = a.taxa().indexOf(subTaxaList.get(i)); if (ion != i) { noNeedToFilter = false; } if (ion == -1) { if (retainUnknownTaxa) { taxaRedirectList.add(-1); idList.add(subTaxaList.get(i)); } } else { if (a instanceof FilterGenotypeTable) { taxaRedirectList.add(((FilterGenotypeTable) a).translateTaxon(ion)); } else { taxaRedirectList.add(ion); } idList.add(a.taxa().get(ion)); } } if (noNeedToFilter) { return a; } int[] taxaRedirect = new int[taxaRedirectList.size()]; for (int j = 0, n = taxaRedirectList.size(); j < n; j++) { taxaRedirect[j] = (int) taxaRedirectList.get(j); } TaxaList resultTaxaList = new TaxaListBuilder().addAll(idList).build(); return new FilterGenotypeTable(baseAlignment, resultTaxaList, taxaRedirect, original); } /** * Removes specified IDs. * * @param a alignment to filter * @param subTaxaList specified IDs * * @return Filtered Alignment */ public static GenotypeTable getInstanceRemoveIDs(GenotypeTable a, TaxaList subTaxaList) { TaxaListBuilder result = new TaxaListBuilder(); TaxaList current = a.taxa(); for (int i = 0, n = current.numberOfTaxa(); i < n; i++) { if (subTaxaList.indexOf(current.get(i)) < 0) { result.add(current.get(i)); } } return FilterGenotypeTable.getInstance(a, result.build()); } /** * Constructor * * @param a base alignment * @param startSite start site (included) * @param endSite end site (included) */ private FilterGenotypeTable(GenotypeTable a, int startSite, int endSite, FilterGenotypeTable original) { myTaxaList = original == null ? a.taxa() : original.taxa(); if (startSite > endSite) { throw new IllegalArgumentException("FilterGenotypeTable: init: start site: " + startSite + " is larger than end site: " + endSite); } if ((startSite < 0) || (startSite > a.numberOfSites() - 1)) { throw new IllegalArgumentException("FilterGenotypeTable: init: start site: " + startSite + " is out of range."); } if ((endSite < 0) || (endSite > a.numberOfSites() - 1)) { throw new IllegalArgumentException("FilterGenotypeTable: init: end site: " + endSite + " is out of range."); } myBaseAlignment = a; myIsSiteFilterByRange = true; myIsSiteFilter = false; myRangeStart = startSite; myRangeEnd = endSite; mySiteRedirect = null; getLociFromBase(); if (original == null) { myIsTaxaFilter = false; myTaxaRedirect = null; } else { myIsTaxaFilter = original.isTaxaFilter(); myTaxaRedirect = original.getTaxaRedirect(); } if (myIsSiteFilter) { myGenotype = GenotypeCallTableBuilder.getFilteredInstance(myBaseAlignment.genotypeMatrix(), numberOfTaxa(), myTaxaRedirect, numberOfSites(), mySiteRedirect); } else { myGenotype = GenotypeCallTableBuilder.getFilteredInstance(myBaseAlignment.genotypeMatrix(), numberOfTaxa(), myTaxaRedirect, numberOfSites(), myRangeStart, myRangeEnd); } } /** * Constructor * * @param a base alignment * @param subSites site to include */ private FilterGenotypeTable(GenotypeTable a, int[] subSites, FilterGenotypeTable original) { myTaxaList = original == null ? a.taxa() : original.taxa(); myBaseAlignment = a; myIsSiteFilter = true; myIsSiteFilterByRange = false; if ((subSites == null) || (subSites.length == 0)) { mySiteRedirect = new int[0]; } else { mySiteRedirect = new int[subSites.length]; Arrays.sort(subSites); System.arraycopy(subSites, 0, mySiteRedirect, 0, subSites.length); } myRangeStart = -1; myRangeEnd = -1; getLociFromBase(); if (original == null) { myIsTaxaFilter = false; myTaxaRedirect = null; } else { myIsTaxaFilter = original.isTaxaFilter(); myTaxaRedirect = original.getTaxaRedirect(); } if (myIsSiteFilter) { myGenotype = GenotypeCallTableBuilder.getFilteredInstance(myBaseAlignment.genotypeMatrix(), numberOfTaxa(), myTaxaRedirect, numberOfSites(), mySiteRedirect); } else { myGenotype = GenotypeCallTableBuilder.getFilteredInstance(myBaseAlignment.genotypeMatrix(), numberOfTaxa(), myTaxaRedirect, numberOfSites(), myRangeStart, myRangeEnd); } } public static FilterGenotypeTable getInstance(GenotypeTable a, int[] subSites) { if (a instanceof FilterGenotypeTable) { FilterGenotypeTable original = (FilterGenotypeTable) a; GenotypeTable baseAlignment = ((FilterGenotypeTable) a).getBaseAlignment(); if (original.isSiteFilter()) { int[] newSubSites = new int[subSites.length]; for (int i = 0; i < subSites.length; i++) { newSubSites[i] = original.translateSite(subSites[i]); } return new FilterGenotypeTable(baseAlignment, newSubSites, original); } else if (original.isSiteFilterByRange()) { int[] newSubSites = new int[subSites.length]; for (int i = 0; i < subSites.length; i++) { newSubSites[i] = original.translateSite(subSites[i]); } return new FilterGenotypeTable(baseAlignment, newSubSites, original); } else if (original.isTaxaFilter()) { return new FilterGenotypeTable(baseAlignment, subSites, original); } else { throw new IllegalStateException("FilterGenotypeTable: getInstance: original not in known state."); } } else { return new FilterGenotypeTable(a, subSites, null); } } public static FilterGenotypeTable getInstance(GenotypeTable a, List<String> siteNamesToKeep) { return getInstance(a, siteNamesToKeep.toArray(new String[siteNamesToKeep.size()])); } public static FilterGenotypeTable getInstance(GenotypeTable a, String[] siteNamesToKeep) { Arrays.sort(siteNamesToKeep); int[] temp = new int[siteNamesToKeep.length]; int count = 0; for (int i = 0, n = a.numberOfSites(); i < n; i++) { if (Arrays.binarySearch(siteNamesToKeep, a.siteName(i)) >= 0) { temp[count++] = i; if (count == siteNamesToKeep.length) { break; } } } int[] result = null; if (count == siteNamesToKeep.length) { result = temp; } else { result = new int[count]; System.arraycopy(temp, 0, result, 0, count); } return getInstance(a, result); } public static FilterGenotypeTable getInstanceRemoveSiteNames(GenotypeTable a, List<String> siteNamesToRemove) { return getInstance(a, siteNamesToRemove.toArray(new String[siteNamesToRemove.size()])); } public static FilterGenotypeTable getInstanceRemoveSiteNames(GenotypeTable a, String[] siteNamesToRemove) { Arrays.sort(siteNamesToRemove); int[] temp = new int[a.numberOfSites()]; int count = 0; for (int i = 0, n = a.numberOfSites(); i < n; i++) { if (Arrays.binarySearch(siteNamesToRemove, a.siteName(i)) < 0) { temp[count++] = i; } } int[] result = null; if (count == temp.length) { result = temp; } else { result = new int[count]; System.arraycopy(temp, 0, result, 0, count); } return getInstance(a, result); } public static FilterGenotypeTable getInstance(GenotypeTable a, PositionList subPositionList) { int[] temp = new int[subPositionList.size()]; int count = 0; PositionList positionList = a.positions(); for (Position position: subPositionList) { int index = positionList.indexOf(position); if (index >= 0) { temp[count++] = index; } } int[] result = null; if (count == subPositionList.size()) { result = temp; } else { result = new int[count]; System.arraycopy(temp, 0, result, 0, count); } return getInstance(a, result); } public static FilterGenotypeTable getInstance(GenotypeTable a, String chromosome, int startPhysicalPos, int endPhysicalPos) { return getInstance(a, a.chromosome(chromosome), startPhysicalPos, endPhysicalPos); } public static FilterGenotypeTable getInstance(GenotypeTable a, Chromosome chromosome, int startPhysicalPos, int endPhysicalPos) { int startSite = a.siteOfPhysicalPosition(startPhysicalPos, chromosome); if (startSite < 0) { startSite = -(startSite + 1); } int endSite = a.siteOfPhysicalPosition(endPhysicalPos, chromosome); if (endSite < 0) { endSite = -(endSite + 2); } if (startSite > endSite) { myLogger.warn("getInstance: start site: " + startSite + " from physical pos: " + startPhysicalPos + " is larger than end site: " + endSite + " from physical pos: " + endPhysicalPos); return null; } return getInstance(a, startSite, endSite); } public static FilterGenotypeTable getInstance(GenotypeTable a, Chromosome chromosome) { int[] endStart = a.firstLastSiteOfChromosome(chromosome); return getInstance(a, endStart[0], endStart[1]); } /** * Factory method that returns a FilterGenotypeTable viewing sites between * start site and end site inclusive. * * @param a alignment * @param startSite start site * @param endSite end site * * @return Filter Alignment */ public static FilterGenotypeTable getInstance(GenotypeTable a, int startSite, int endSite) { if (a instanceof FilterGenotypeTable) { FilterGenotypeTable original = (FilterGenotypeTable) a; GenotypeTable baseAlignment = ((FilterGenotypeTable) a).getBaseAlignment(); if (original.isSiteFilter()) { int[] subSites = new int[endSite - startSite + 1]; int[] originalSites = original.getSiteRedirect(); for (int i = startSite; i <= endSite; i++) { subSites[i - startSite] = originalSites[i]; } return new FilterGenotypeTable(baseAlignment, subSites, original); } else if (original.isSiteFilterByRange()) { return new FilterGenotypeTable(baseAlignment, original.translateSite(startSite), original.translateSite(endSite), original); } else if (original.isTaxaFilter()) { return new FilterGenotypeTable(baseAlignment, startSite, endSite, original); } else { throw new IllegalStateException("FilterGenotypeTable: getInstance: original not in known state."); } } else { return new FilterGenotypeTable(a, startSite, endSite, null); } } @Override public byte genotype(int taxon, int site) { return myGenotype.genotype(taxon, site); } @Override public byte[] genotypeRange(int taxon, int startSite, int endSite) { return myGenotype.genotypeRange(taxon, startSite, endSite); } @Override public byte genotype(int taxon, Chromosome chromosome, int physicalPosition) { return myGenotype.genotype(taxon, myPositionList.siteOfPhysicalPosition(physicalPosition, chromosome)); } public int translateSite(int site) { if (myIsSiteFilterByRange) { return site + myRangeStart; } else if (myIsSiteFilter) { return mySiteRedirect[site]; } else { return site; } } /** * Returns site of this FilterGenotypeTable based on given site from * embedded Alignment. * * @param site site * @return site in this alignment */ public int reverseTranslateSite(int site) { if (myIsSiteFilterByRange) { return site - myRangeStart; } else if (myIsSiteFilter) { return Arrays.binarySearch(mySiteRedirect, site); } else { return site; } } /** * Returns sites from original alignment that are viewable (not filtered) by * this filter alignment. * * @return list of sites */ public int[] getBaseSitesShown() { int numSites = numberOfSites(); int[] result = new int[numSites]; for (int i = 0; i < numSites; i++) { result[i] = translateSite(i); } return result; } public int translateTaxon(int taxon) { if (myIsTaxaFilter) { return myTaxaRedirect[taxon]; } else { return taxon; } } private void getLociFromBase() { if ((!myIsSiteFilter) && (!myIsSiteFilterByRange)) { myChromosomes = myBaseAlignment.chromosomes(); myChromosomeOffsets = myBaseAlignment.chromosomesOffsets(); return; } int numSites = numberOfSites(); List<Chromosome> chromosomes = new ArrayList<Chromosome>(); List<Integer> offsets = new ArrayList<Integer>(); for (int i = 0; i < numSites; i++) { Chromosome current = chromosome(i); if (!chromosomes.contains(current)) { chromosomes.add(current); offsets.add(i); } } myChromosomes = new Chromosome[chromosomes.size()]; chromosomes.toArray(myChromosomes); myChromosomeOffsets = new int[offsets.size()]; for (int i = 0; i < offsets.size(); i++) { myChromosomeOffsets[i] = (Integer) offsets.get(i); } } @Override public int indelSize(int site) { return myBaseAlignment.indelSize(translateSite(site)); } @Override public Chromosome chromosome(int site) { return myBaseAlignment.chromosome(translateSite(site)); } @Override public int chromosomalPosition(int site) { return myBaseAlignment.chromosomalPosition(translateSite(site)); } @Override public String chromosomeName(int site) { return myBaseAlignment.chromosomeName(translateSite(site)); } @Override public Chromosome chromosome(String name) { return myBaseAlignment.chromosome(name); } @Override public Chromosome[] chromosomes() { return myChromosomes; } @Override public int numChromosomes() { return myChromosomes.length; } @Override public int[] chromosomesOffsets() { return myChromosomeOffsets; } @Override public int[] firstLastSiteOfChromosome(Chromosome chromosome) { for (int i = 0; i < numChromosomes(); i++) { if (chromosome.equals(myChromosomes[i])) { int end = 0; if (i == numChromosomes() - 1) { end = numberOfSites() - 1; } else { end = myChromosomeOffsets[i + 1] - 1; } return new int[]{myChromosomeOffsets[i], end}; } } throw new IllegalArgumentException("FilterGenotypeTable: getStartAndEndOfLocus: this locus not defined: " + chromosome.getName()); } @Override public float[][] siteScores() { if (!myBaseAlignment.hasSiteScores()) { return null; } int numSites = numberOfSites(); int numSeqs = numberOfTaxa(); float[][] result = new float[numSeqs][numSites]; for (int i = 0; i < numSites; i++) { for (int j = 0; j < numSeqs; j++) { int taxaIndex = translateTaxon(j); if (taxaIndex == -1) { result[j][i] = -9; } else { result[j][i] = myBaseAlignment.siteScore(taxaIndex, translateSite(i)); } } } return result; } @Override public byte referenceAllele(int site) { return myBaseAlignment.referenceAllele(translateSite(site)); } @Override public int numberOfSites() { if (myIsSiteFilterByRange) { return myRangeEnd - myRangeStart + 1; } else if (myIsSiteFilter) { return mySiteRedirect.length; } else { return myBaseAlignment.numberOfSites(); } } @Override public String siteName(int site) { return myBaseAlignment.siteName(translateSite(site)); } @Override public boolean hasReference() { return myBaseAlignment.hasReference(); } @Override public boolean isIndel(int site) { return myBaseAlignment.isIndel(translateSite(site)); } @Override public int siteOfPhysicalPosition(int physicalPosition, Chromosome chromosome) { int temp = myBaseAlignment.siteOfPhysicalPosition(physicalPosition, chromosome); if (temp < 0) { temp = -(temp + 1); return -(reverseTranslateSite(temp) + 1); } return reverseTranslateSite(temp); } @Override public int siteOfPhysicalPosition(int physicalPosition, Chromosome chromosome, String snpName) { int temp = myBaseAlignment.siteOfPhysicalPosition(physicalPosition, chromosome, snpName); if (temp < 0) { temp = -(temp + 1); return -(reverseTranslateSite(temp) + 1); } return reverseTranslateSite(temp); } public GenotypeTable getBaseAlignment() { return myBaseAlignment; } public boolean isTaxaFilter() { return myIsTaxaFilter; } public boolean isSiteFilter() { return myIsSiteFilter; } public boolean isSiteFilterByRange() { return myIsSiteFilterByRange; } protected int[] getTaxaRedirect() { return myTaxaRedirect; } protected int[] getSiteRedirect() { return mySiteRedirect; } protected int getRangeStart() { return myRangeStart; } protected int getRangeEnd() { return myRangeEnd; } @Override public byte[] genotypeArray(int taxon, int site) { return myGenotype.genotypeArray(taxon, site); } @Override public byte[] genotypeAllTaxa(int site) { return myGenotype.genotypeForAllTaxa(site); } @Override public byte[] genotypeAllSites(int taxon) { return myGenotype.genotypeAllSites(taxon); } @Override public BitSet allelePresenceForAllSites(int taxon, WHICH_ALLELE allele) { return bitStorage(allele).allelePresenceForAllSites(taxon); } @Override public long[] allelePresenceForSitesBlock(int taxon, WHICH_ALLELE allele, int startBlock, int endBlock) { return bitStorage(allele).allelePresenceForSitesBlock(taxon, startBlock, endBlock); } @Override public String genotypeAsString(int taxon, int site) { return myGenotype.genotypeAsString(taxon, site); } @Override public String[] genotypeAsStringArray(int taxon, int site) { return myGenotype.genotypeAsStringArray(taxon, site); } @Override public byte[] referenceAlleleForAllSites() { if ((myIsSiteFilterByRange) || (myIsSiteFilter)) { byte[] result = new byte[numberOfSites()]; for (int i = 0, n = numberOfSites(); i < n; i++) { result[i] = referenceAllele(i); } return result; } else { return myBaseAlignment.referenceAlleleForAllSites(); } } @Override public boolean isHeterozygous(int taxon, int site) { return myGenotype.isHeterozygous(taxon, site); } @Override public int[] physicalPositions() { if ((myIsSiteFilterByRange) || (myIsSiteFilter)) { int numSites = numberOfSites(); int[] result = new int[numSites]; for (int i = 0; i < numSites; i++) { result[i] = chromosomalPosition(i); } return result; } else { return myBaseAlignment.physicalPositions(); } } @Override public TaxaList taxa() { return myTaxaList; } @Override public int numberOfTaxa() { return myTaxaList.numberOfTaxa(); } @Override public float siteScore(int taxon, int site) { int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { return Float.NaN; } else { return myBaseAlignment.siteScore(taxaIndex, translateSite(site)); } } @Override public boolean hasSiteScores() { return myBaseAlignment.hasSiteScores(); } @Override public SITE_SCORE_TYPE siteScoreType() { return myBaseAlignment.siteScoreType(); } @Override public String genomeVersion() { return myBaseAlignment.genomeVersion(); } @Override public boolean isPositiveStrand(int site) { return myBaseAlignment.isPositiveStrand(translateSite(site)); } @Override public boolean isPhased() { return myGenotype.isPhased(); } @Override public boolean retainsRareAlleles() { return myGenotype.retainsRareAlleles(); } @Override public String[][] alleleDefinitions() { return alleleDefinitions(); } @Override public String[] alleleDefinitions(int site) { return alleleDefinitions(site); } @Override public String genotypeAsString(int site, byte value) { return myGenotype.genotypeAsString(site, value); } @Override public int maxNumAlleles() { return myGenotype.maxNumAlleles(); } @Override public byte[] alleles(int site) { return myGenotype.alleles(site); } @Override public int[][] allelesSortedByFrequency(int site) { return myGenotype.allelesSortedByFrequency(site); } @Override public double majorAlleleFrequency(int site) { return myGenotype.majorAlleleFrequency(site); } @Override public int heterozygousCount(int site) { return myGenotype.heterozygousCount(site); } @Override public boolean isPolymorphic(int site) { return myGenotype.isPolymorphic(site); } @Override public int totalGametesNonMissingForSite(int site) { return myGenotype.totalGametesNonMissingForSite(site); } @Override public int totalNonMissingForSite(int site) { return myGenotype.totalNonMissingForSite(site); } @Override public int minorAlleleCount(int site) { return myGenotype.minorAlleleCount(site); } @Override public double minorAlleleFrequency(int site) { return myGenotype.minorAlleleFrequency(site); } @Override public int majorAlleleCount(int site) { return myGenotype.majorAlleleCount(site); } @Override public byte majorAllele(int site) { return myGenotype.majorAllele(site); } @Override public byte minorAllele(int site) { return myGenotype.minorAllele(site); } @Override public Object[][] genosSortedByFrequency(int site) { return myGenotype.genosSortedByFrequency(site); } @Override public int totalGametesNonMissingForTaxon(int taxon) { return myGenotype.totalGametesNonMissingForTaxon(taxon); } @Override public int totalNonMissingForTaxon(int taxon) { return myGenotype.totalNonMissingForTaxon(taxon); } @Override public int heterozygousCountForTaxon(int taxon) { return myGenotype.heterozygousCountForTaxon(taxon); } @Override public boolean hasDepth() { return myBaseAlignment.hasDepth(); } @Override public AlleleDepth depth() { if (myAlleleDepth == null) { myAlleleDepth = new FilterAlleleDepth(myBaseAlignment.depth(), this); } return myAlleleDepth; } @Override public int[] depthForAlleles(int taxon, int site) { int taxaIndex = translateTaxon(taxon); if (taxaIndex == -1) { return null; } else { return myBaseAlignment.depthForAlleles(taxaIndex, translateSite(site)); } } @Override public byte[] allelesBySortType(ALLELE_SORT_TYPE scope, int site) { if (scope == ALLELE_SORT_TYPE.Frequency) { return alleles(site); } else { return myBaseAlignment.allelesBySortType(scope, translateSite(site)); } } @Override public BitSet allelePresenceForAllTaxa(int site, WHICH_ALLELE allele) { return bitStorage(allele).allelePresenceForAllTaxa(site); } @Override public BitSet haplotypeAllelePresenceForAllSites(int taxon, boolean firstParent, WHICH_ALLELE allele) { return bitStorage(allele).haplotypeAllelePresenceForAllSites(taxon, firstParent); } @Override public BitSet haplotypeAllelePresenceForAllTaxa(int site, boolean firstParent, WHICH_ALLELE allele) { return bitStorage(allele).haplotypeAllelePresenceForAllTaxa(site, firstParent); } @Override public long[] haplotypeAllelePresenceForSitesBlock(int taxon, boolean firstParent, WHICH_ALLELE allele, int startBlock, int endBlock) { return bitStorage(allele).haplotypeAllelePresenceForSitesBlock(taxon, firstParent, startBlock, endBlock); } @Override public String genotypeAsStringRange(int taxon, int startSite, int endSite) { return myGenotype.genotypeAsStringRange(taxon, startSite, endSite); } @Override public String genotypeAsStringRow(int taxon) { return myGenotype.genotypeAsStringRow(taxon); } @Override public byte[] referenceAlleles(int startSite, int endSite) { if (!hasReference()) { return null; } byte[] result = new byte[endSite - startSite]; for (int i = startSite; i < endSite; i++) { result[i] = referenceAllele(i); } return result; } @Override public int chromosomeSiteCount(Chromosome chromosome) { int[] startEnd = firstLastSiteOfChromosome(chromosome); return startEnd[1] - startEnd[0] + 1; } @Override public boolean isAllPolymorphic() { return myGenotype.isAllPolymorphic(); } @Override public String majorAlleleAsString(int site) { return myGenotype.majorAlleleAsString(site); } @Override public String minorAlleleAsString(int site) { return myGenotype.minorAlleleAsString(site); } @Override public byte[] minorAlleles(int site) { return myGenotype.minorAlleles(site); } @Override public String taxaName(int index) { return myTaxaList.taxaName(index); } @Override public GenotypeTable[] compositeAlignments() { return new GenotypeTable[]{this}; } @Override public String diploidAsString(int site, byte value) { return myGenotype.diploidAsString(site, value); } @Override public Object[][] genoCounts() { return myGenotype.genoCounts(); } @Override public Object[][] majorMinorCounts() { return myGenotype.majorMinorCounts(); } @Override public BitStorage bitStorage(WHICH_ALLELE allele) { BitStorage result = myBitStorage.get(allele); if (result != null) { return result; } switch (allele) { case Major: result = new DynamicBitStorage(myGenotype, allele, myGenotype.majorAlleleForAllSites()); break; case Minor: result = new DynamicBitStorage(myGenotype, allele, myGenotype.minorAlleleForAllSites()); break; default: myLogger.warn("bitStorage: Unsupported allele: " + allele); return null; } myBitStorage.put(allele, result); return result; } @Override public PositionList positions() { if (myPositionList == null) { PositionListBuilder pLB = new PositionListBuilder(); PositionList basePL = getBaseAlignment().positions(); for (int i = 0; i < numberOfSites(); i++) { pLB.add(basePL.get(translateSite(i))); } myPositionList = pLB.build(); } return myPositionList; } @Override public GenotypeCallTable genotypeMatrix() { return myGenotype; } }
package com.example.stoom.model; import javax.validation.constraints.Max; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; public class AddressRequest { @Size(max= 100) @NotBlank(message = "Nome da rua obrigatório") private String streetName; @Size(max= 20) @NotBlank(message = "Número obrigatório") private String number; @Size(max= 30) private String complement; @Size(max= 100) @NotBlank(message = "Bairro obrigatório") private String neighbourhood; @Size(max= 100) @NotBlank(message = "Cidade obrigatório") private String city; @Size(max= 100) @NotBlank(message = "Estado obrigatório") private String state; @Size(max= 100) @NotBlank(message = "País obrigatório") private String country; @Size(max= 25) @NotBlank(message = "CEP obrigatório") private String zipCode; private String latitude; private String longitude; public AddressRequest(@Size(max = 100) @NotBlank(message = "Nome da rua obrigatório") String streetName, @Size(max = 20) @NotBlank(message = "Número obrigatório") String number, @Size(max = 30) String complement, @Size(max = 100) @NotBlank(message = "Bairro obrigatório") String neighbourhood, @Size(max = 100) @NotBlank(message = "Cidade obrigatório") String city, @Size(max = 100) @NotBlank(message = "Estado obrigatório") String state, @Size(max = 100) @NotBlank(message = "País obrigatório") String country, @Size(max = 25) @NotBlank(message = "CEP obrigatório") String zipCode, String latitude, String longitude) { this.streetName = streetName; this.number = number; this.complement = complement; this.neighbourhood = neighbourhood; this.city = city; this.state = state; this.country = country; this.zipCode = zipCode; this.latitude = latitude; this.longitude = longitude; } public String getStreetName() { return streetName; } public void setStreetName(String streetName) { this.streetName = streetName; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getComplement() { return complement; } public void setComplement(String complement) { this.complement = complement; } public String getNeighbourhood() { return neighbourhood; } public void setNeighbourhood(String neighbourhood) { this.neighbourhood = neighbourhood; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } }
// PSEUDOCODE /* * This class class will have 4 buttons each a different direction. * It will also have a circle shape that will respond to the button presses * by going in that specific direction. */ package application; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.geometry.Pos; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.shape.Circle; public class Main extends Application { @Override public void start(Stage primaryStage) { Pane pane = new Pane(); //Hold buttons in a Hbox HBox hBox = new HBox(); hBox.setSpacing(5); hBox.setAlignment(Pos.CENTER); Button left = new Button("Left"); Button right = new Button("Right"); Button up = new Button("Up"); Button down = new Button("Down"); hBox.getChildren().add(left); hBox.getChildren().add(right); hBox.getChildren().add(up); hBox.getChildren().add(down); //Set pane BorderPane borderPane = new BorderPane(); borderPane.setCenter(pane); borderPane.setBottom(hBox); BorderPane.setAlignment(hBox, Pos.CENTER); //create and set properties for the ball Circle ball = new Circle(50,50,25); ball.setStyle("-fx-stroke: black; -fx-fill: transparent;"); pane.getChildren().add(ball); //Create and register handlers for each button using lambda expression left.setOnAction((ActionEvent e) -> { if(ball.getBoundsInLocal().getMinX() >= 0 ) { ball.setCenterX(ball.getCenterX()-20); } }); right.setOnAction((ActionEvent e) -> { if(ball.getBoundsInLocal().getMaxX() <= 350) { ball.setCenterX(ball.getCenterX()+20); } }); up.setOnAction((ActionEvent e) -> { if(ball.getBoundsInLocal().getMaxY() >= 50) { ball.setCenterY(ball.getCenterY()-20); } }); down.setOnAction((ActionEvent e) -> { if(ball.getBoundsInLocal().getMinY() <= 150) { ball.setCenterY(ball.getCenterY()+20); } }); //Create a scene and place it in the stage Scene scene = new Scene(borderPane, 350,200); primaryStage.setTitle("Shapes in Grid"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
package org.os.dbkernel.fdb.fdbtracemerger; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.Instant; import java.time.ZoneId; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class Parameters extends AbstractParameters { public static final int QUE_CAPACITY_DEFAULT = 1000; public static final String OUTPUT_PATH_DEFAULT = "-"; public static final DateTimeFormatter BASE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSSSSS]"); private final List<String> SRC_LIST_DEFAULT = Arrays.asList(new String[] {"."}); public final ArrayList<String> srcList = new ArrayList<>(); private class Parser extends AbstractParser { protected Parser(final Iterator<String> iter) { super(iter); } void consumeSwitch(final String sw) { if (sw.equals("o")) { outputPath = checkNext(outputPath, sw); } else if (sw.equals("from")) { timeFromStr = checkNext(timeFromStr, sw);; } else if (sw.equals("to")) { timeToStr = checkNext(timeToStr, sw);; } else if (sw.equals("help") || sw.equals("?")) { isToHelp = true; } else if (sw.equals("tz")) { if (timeZone != null) { throw new IllegalArgumentException("Duplicated " + sw); } if (! argsIter.hasNext()) { throw new IllegalArgumentException("No value for " + sw); } timeZone = ZoneId.of(argsIter.next()); } else { throw new IllegalArgumentException("Unknown switch " + sw); } } void consumeArg(final String arg) { srcList.add(arg); } } String outputPath = null; ZoneId timeZone = null; boolean isToHelp = false; private String timeFromStr = null; private String timeToStr = null; DateTimeFormatter timeFormatter = null; Instant timeFrom = null; Instant timeTo = null; @Override AbstractParser getParser(final Iterator<String> iter) { return new Parser(iter); } @Override void init() { srcList.clear(); timeTo = null; timeFrom = null; timeFormatter = null; outputPath = null; timeToStr = null; timeFromStr = null; timeZone = null; } @Override void fillOther() { timeFormatter = BASE_TIME_FORMATTER.withZone(getTimeZone()); timeFrom = timeFromStr != null ? timeFormatter.parse(timeFromStr, Instant::from) : null; timeTo = timeToStr != null ? timeFormatter.parse(timeToStr, Instant::from) : null; } public List<String> getSrcList() { return srcList.isEmpty() ? SRC_LIST_DEFAULT : srcList; } public String getOutputPath() { return outputPath != null ? outputPath : OUTPUT_PATH_DEFAULT; } public ZoneId getTimeZone() { return timeZone != null ? timeZone : ZoneId.systemDefault(); } public DateTimeFormatter getTimeFormatter() { return timeFormatter; } static void printUsage() throws IOException { System.out.println( "Merge several foundationdb trace files into a single file ordered by time\n" + "Usage: java -jar fdb-trace-merger {options}... {files-or-directories}...\n" + "\n" + "Options are:\n" + "-help Print this information\n" + "-from DateTime Print only the log contents with the time greater or equal to the specified time.\n" + " The time must be in the format \"yyyy-MM-dd HH:mm:ss[.SSSSSS]\" and includer in quotas.\n" + "-to DateTime Print only the log contents with the time less than the specified time.\n" + " The time must be in the format \"yyyy-MM-dd HH:mm:ss[.SSSSSS]\" and includer in quotas.\n" + "-o FileName Output to the file specified. \"-o -\" means the standard output (default)\n" + "-tz TimeZoneName Print the time with the specified timezone. \n" + " see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\n" + " for the list of timezone names supported\n" + " By default, uses the local timezone\n" + "\n" + "Files-or-directories - a list of pathes.\n" + " If the path represents a file, then FdbTraceMerger considers this file as a fdb trace.\n" + " If the path represents a directory, then FdbTraceMerger searches all trace files \n" + " in the directory and all its subdirectories recursively whith the pattern\n" + " \"trace.*.xml\".\n" + " Running without Files-or-directories specifued FdbTraceMerger searches all trace \n" + " files under the current directory\n" + "\n" + "Examples:\n" + "\n" + "java -jar fdb-trace-merger-3.52.29.10.jar\n" + " merge all trace files from the current directory and all its subdirectories recursively\n" + " and print list of events to the standard output\n" + "\n" + "java -jar fdb-trace-merger-3.52.29.10.jar -tz UTC -o events.log traces/trace.192.168.56.1??.*.xml\n" + " merge all trace files in the traces subdirectory from the hosts with ip addresses\n" + " trace.192.168.56.1?? and print list of events to events.log. All timestamps are \n" + " printed with the UTC timezone\n" ); } }
class Solution { public int subarraySum(int[] nums, int k) { HashMap<Integer, Integer> arrSums = new HashMap(); arrSums.put(0, 1); int sum = 0, result = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; //if (arrSums.containsKey(sum - k)) result += arrSums.getOrDefault(sum - k, 0); arrSums.put(sum, arrSums.getOrDefault(sum, 0) + 1); } return result; } }
public class Manager extends Common { public void DeleteClerck() { } public void Permission() { } }
package com.ipincloud.iotbj.srv.domain; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Time; import java.sql.Date; import java.sql.Timestamp; import com.alibaba.fastjson.annotation.JSONField; //(Algorithmalarm)报警记录 //generate by redcloud,2020-07-24 19:59:20 public class Algorithmalarm implements Serializable { private static final long serialVersionUID = 9L; // 主键id private Long id ; // 报警时间 @JSONField(name = "alarm_time") private Long alarmTime ; // 算法id @JSONField(name = "algorithm_id") private Long algorithmId ; // 算法名称 @JSONField(name = "algorithm_name") private String algorithmName ; // 摄像机id @JSONField(name = "camera_id") private Long cameraId ; // 摄像机名称 @JSONField(name = "camera_name") private String cameraName ; // 状态 private String state ; // 报警描述 private String describion ; // 区域 private String region ; // 报警图片 @JSONField(name = "alarm_img") private String alarmImg ; // 预警等级 private String grade ; // 创建时间 private Long indate ; public Long getId() { return id ; } public void setId(Long id) { this.id = id; } public Long getAlarmTime() { return alarmTime ; } public void setAlarmTime(Long alarmTime) { this.alarmTime = alarmTime; } public Long getAlgorithmId() { return algorithmId ; } public void setAlgorithmId(Long algorithmId) { this.algorithmId = algorithmId; } public String getAlgorithmName() { return algorithmName ; } public void setAlgorithmName(String algorithmName) { this.algorithmName = algorithmName; } public Long getCameraId() { return cameraId ; } public void setCameraId(Long cameraId) { this.cameraId = cameraId; } public String getCameraName() { return cameraName ; } public void setCameraName(String cameraName) { this.cameraName = cameraName; } public String getState() { return state ; } public void setState(String state) { this.state = state; } public String getDescribion() { return describion ; } public void setDescribion(String describion) { this.describion = describion; } public String getRegion() { return region ; } public void setRegion(String region) { this.region = region; } public String getAlarmImg() { return alarmImg ; } public void setAlarmImg(String alarmImg) { this.alarmImg = alarmImg; } public String getGrade() { return grade ; } public void setGrade(String grade) { this.grade = grade; } public Long getIndate() { return indate ; } public void setIndate(Long indate) { this.indate = indate; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; import java.util.StringTokenizer; public class bj1260 { static int grahp[][]; static StringBuilder sbDfs = new StringBuilder(); static StringBuilder sbBfs = new StringBuilder(); // static boolean visited[]; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine(), " "); int node = Integer.parseInt(st.nextToken()); int edge = Integer.parseInt(st.nextToken()); int start = Integer.parseInt(st.nextToken()); grahp = new int[node + 1][node + 1]; boolean visited[] = new boolean[node + 1]; for (int i = 0; i < edge; i++) { st = new StringTokenizer(br.readLine(), " "); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); grahp[x][y] = 1; grahp[y][x] = 1; } dfs(start, visited); visited = new boolean[node + 1]; bfs(start, visited); System.out.println(sbDfs); System.out.println(sbBfs); } static void dfs(int start, boolean[] visited) { visited[start] = true; sbDfs.append(start).append(" "); for (int i = 1; i < grahp.length; i++) { if (grahp[start][i] == 1 && !visited[i]) { dfs(i, visited); } } } static void bfs(int start, boolean[] visited) { Queue<Integer> que = new LinkedList<>(); que.add(start); visited[start] = true; while (!que.isEmpty()) { int node = que.poll(); sbBfs.append(node).append(" "); for (int i = 1; i < grahp.length; i++) { if (grahp[node][i] == 1 && !visited[i]) { que.add(i); visited[i] = true; } } } } }
package basic.第三章; import java.util.Scanner; /** * 循环小数(Repeating Decimals) * 题目: * 输出a/b的循环小数表示以及循环节长度 * Created by Administrator on 2018/4/12. * <p> * 第一步:先算出 a/b 的 商 * 第二步:算出 a%b 的余数 * 第三步:循环计算 (余数远远小于除数,所以需要将余数扩大10倍,然后再被除数相除,然后循环) * * @author 丹丘生 */ public class RepeatingDecimals { static int[] arr = new int[3000 + 5]; static int[] tep = new int[3000 + 5]; public static void main(String[] args) { Scanner read = new Scanner(System.in); int a = read.nextInt(); int b = read.nextInt(); // 得商 int x = a / b; // 得余数 int temp = a % b; // temp变量用于标记循环小数的开始, 在temp之前的都不是循环小数 // 得到剩余待除 a = a % b * 10; int index = 0; while (tep[temp] == 0) { // 如果当前的余数没有相同的 int yu = a / b; // 得商 arr[++index] = yu; // 存储该商 tep[temp] = index; // 存储余数的下标 temp = a % b; // 得余数 a = a % b * 10; // 得到剩余待除 } //arr[1]=1 arr[2]=6 //temp[1]= 1 temp[4]=2 //temp=4 index=2 System.out.print(x + "."); if (a == 0) {// 如果被整除 for (int i = 1; i < index; i++) System.out.print(arr[i]); System.out.println("(0)"); System.out.println(1); return; } // 如果没有整除 for (int i = 1; i < tep[temp]; i++) { // 在之前的不是循环小数 System.out.print(arr[i]); } System.out.print("("); for (int i = tep[temp]; i <= index && i <= tep[temp] + 100; i++) { System.out.print(arr[i]); } System.out.println(")"); System.out.println(index - tep[temp] + 1); } }
/* * ============================================================================ * = COPYRIGHT * PAX TECHNOLOGY, Inc. PROPRIETARY INFORMATION * This software is supplied under the terms of a license agreement or * nondisclosure agreement with PAX Technology, Inc. and may not be copied * or disclosed except in accordance with the terms in that agreement. * Copyright (C) 2009-2020 PAX Technology, Inc. All rights reserved. * ============================================================================ */ package com.xzm.app.model; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import org.hibernate.validator.constraints.Length; @Entity(name="role") public class Role extends BaseModel{ private static final long serialVersionUID = 1L; @Length(max=255) @Column(name="name",nullable=false,unique=true,columnDefinition="varchar(255)") private String name; @OneToMany @JoinTable(name="role_authorities",joinColumns={@JoinColumn(name="role_id")},inverseJoinColumns={@JoinColumn(name="authority_id")}) private Set<Authority> authorities; public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Authority> getAuthorities() { return authorities; } public void setAuthorities(Set<Authority> authorities) { this.authorities = authorities; } }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ActiveEon Team * http://www.activeeon.com/ * Contributor(s): * * ################################################################ * $$ACTIVEEON_INITIAL_DEV$$ */ package org.ow2.proactive.resourcemanager.nodesource.infrastructure; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import org.apache.log4j.Logger; import org.objectweb.proactive.core.config.CentralPAPropertyRepository; import org.objectweb.proactive.core.ssh.SSHClient; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.utils.OperatingSystem; import org.ow2.proactive.resourcemanager.core.properties.PAResourceManagerProperties; import org.ow2.proactive.resourcemanager.utils.RMLoggers; /** * A class where static utility methods are welcome */ public class Utils { private static final Logger logger = ProActiveLogger.getLogger(RMLoggers.NODESOURCE); /** * Execute a specific command on a remote host through SSH * * @param host the remote host on which to execute the command * @param cmd the command to execute on the remote host * @param sshOptions the options that will be passed to the ssh command * @return the Process in which the SSH command is running; * NOT the actual process on the remote host, although it can be used * to read the remote process' output. * @throws IOException SSH command execution failed */ public static Process runSSHCommand(InetAddress host, String cmd, String sshOptions) throws IOException { // build the SSH command using ProActive's SSH client: // will recover keys/identities if they exist String sshCmd = null; StringBuilder sb = new StringBuilder(); //building path to java executable String javaHome = System.getProperty("java.home"); if (javaHome.contains(" ")) { switch (OperatingSystem.getOperatingSystem()) { case unix: javaHome = javaHome.replace(" ", "\\ "); break; case windows: sb.append("\""); break; } } sb.append(javaHome); sb.append(File.separator); sb.append("bin"); sb.append(File.separator); sb.append("java"); if (javaHome.contains(" ")) { switch (OperatingSystem.getOperatingSystem()) { case windows: sb.append("\""); break; } } //building classpath sb.append(" -cp "); final String rmHome = PAResourceManagerProperties.RM_HOME.getValueAsString().trim(); final boolean containsSpace = rmHome.contains(" "); if (containsSpace) { sb.append("\""); } sb.append(rmHome); sb.append(File.separator); sb.append("dist"); sb.append(File.separator); sb.append("lib"); sb.append(File.separator); sb.append("ProActive.jar"); if (containsSpace) { sb.append("\""); } sb.append(" "); //mandatory property //exe's name sb.append(SSHClient.class.getName()); //SSH options supplied by user from cli|gui sb.append(" "); sb.append(sshOptions); sb.append(" "); //target machine sb.append(host.getHostName()); //the command sb.append(" \""); sb.append(cmd); sb.append("\""); sshCmd = sb.toString(); logger.info("Executing SSH command: '" + sshCmd + "'"); Process p = null; // start the SSH command in a new process and not a thread: // easier killing, prevents the client from polluting stdout switch (OperatingSystem.getOperatingSystem()) { case unix: p = Runtime.getRuntime().exec( new String[] { CentralPAPropertyRepository.PA_GCMD_UNIX_SHELL.getValue(), "-c", sshCmd }); break; case windows: p = Runtime.getRuntime().exec(sshCmd); break; } return p; } /** * Extract the stacktrace of a throwable object and returns it as a String * @param t The throwable object from which one the stacktrace is going to be extracted * @return the stacktrace of the parameter as a String */ public static String getStacktrace(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); String result = sw.toString(); pw.close(); return result; } /** * Extracts process errput and returns it * @param p the remote process frow which one errput will be extracted. * @return the remote process' errput */ static String extractProcessErrput(Process p) { BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream())); StringBuilder sb = new StringBuilder(); String line = null; try { String lf = System.getProperty("line.separator"); while (br.ready()) { if ((line = br.readLine()) != null) { sb.append(line); sb.append(lf); } } } catch (IOException e) { sb.append("Cannot extract process errput"); } finally { try { br.close(); } catch (IOException e) { logger.debug("Cannot close process error stream", e); } } return sb.toString(); } /** * Extracts process output and returns it * @param p the remote process frow which one output will be extracted. * @return the remote process' output */ static String extractProcessOutput(Process p) { BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; try { String lf = System.getProperty("line.separator"); while (br.ready()) { if ((line = br.readLine()) != null) { sb.append(line); sb.append(lf); } } } catch (IOException e) { sb.append("Cannot extract process output"); } finally { try { br.close(); } catch (IOException e) { logger.debug("Cannot close process output stream", e); } } return sb.toString(); } }
import java.util.Objects; public class OutputPair { private int output1; private int output2; OutputPair() { } OutputPair(int output1, int output2) { this.output1 = output1; this.output2 = output2; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OutputPair that = (OutputPair) o; return output1 == that.output1 && output2 == that.output2; } @Override public int hashCode() { return Objects.hash(output1, output2); } public int getOutput1() { return output1; } public int getOutput2() { return output2; } @Override public String toString() { return output1+","+output2; } }
package Supermercado; import java.util.ArrayList; import java.util.Collection; public class Venda { private final int idVenda; private static int totalIDVenda; private final Collection produtosCompra = new ArrayList(); private float valorTotal = 0; private float troco; private String formaPagamento; private final int idCaixa; private final String loginFuncionario; public Venda(int idCaixa, String loginFuncionario) { Venda.totalIDVenda++; this.idVenda = totalIDVenda; this.idCaixa = idCaixa; this.loginFuncionario = loginFuncionario; } public Collection getProdutosCompra(){ return this.produtosCompra; } public String getLoginFuncionario(){ return this.loginFuncionario; } public int getIdCaixa(){ return this.idCaixa; } public void adicionarProdutoVenda(Item item) { produtosCompra.add(item); valorTotal += item.getValorTotal(); } public void removerProdutoVenda(Item item) { produtosCompra.remove(item); valorTotal -= item.getValorTotal(); } public float getValorTotal() { return this.valorTotal; } public float getTroco() { return this.troco; } public float getIdVenda() { return this.idVenda; } public String getFormaPagamento() { return this.formaPagamento; } public boolean finalizarVenda(int senha){ Cartao cartao = new Cartao(); if (cartao.validarCartao(senha)){ this.troco = 0; this.formaPagamento = "Cartao"; return true; } return false; } public float calcularTroco(float valor){ troco = valor - this.valorTotal; if(troco >= 0){ this.formaPagamento = "Dinheiro"; return troco; } return -1; } }
package lollypop_tips.saulmm.lollipoptips; import android.app.ActivityOptions; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Outline; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.squareup.picasso.Picasso; import java.util.List; import lollypop_tips.saulmm.lollipoptips.entities.Result; import lollypop_tips.saulmm.lollipoptips.entities.User; import lollypop_tips.saulmm.lollipoptips.entities.UserEntities; import lollypop_tips.saulmm.lollipoptips.tools.TextTools; public class MainActivity extends Activity { public static SparseArray<Bitmap> photoCache = new SparseArray<Bitmap>(1); private List<Result> users; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Configure the FAB button int size = getResources().getDimensionPixelSize(R.dimen.fab_size); Outline outline = new Outline(); outline.setOval(0, 0, size, size); findViewById(R.id.fab).setOutline(outline); // Get the data from a file Gson gson = new Gson (); String jsonUsers = TextTools.getFileContent(R.raw.users, this); users = gson.fromJson(jsonUsers, UserEntities.class).getResults(); // Setup the gridview and te adapter GridView gridview = (GridView) findViewById(R.id.user_grid); gridview.setOnItemClickListener(userClickListener); gridview.setAdapter (new UserAdapter(this, users)); } // Adapter OnItemClick event private AdapterView.OnItemClickListener userClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Intent detailIntent = new Intent(MainActivity.this, DetailActivity.class); detailIntent.putExtra("user", users.get(i).getUser()); detailIntent.putExtra("position", i); ImageView userImage = (ImageView) view.findViewById(R.id.user_image); ((ViewGroup) userImage.getParent()).setTransitionGroup(false); photoCache.put(R.drawable.photo1, ((BitmapDrawable) userImage.getDrawable()).getBitmap()); // Setup the transition to the detail activity ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(MainActivity.this, view, "photo" + i); startActivity(detailIntent, options.toBundle()); } }; public void onFabClicked(View view) { Toast.makeText(this, "Omg, you pressed that button...", Toast.LENGTH_LONG).show(); } } class UserAdapter extends BaseAdapter { private Context mContext; private List<Result> users; public UserAdapter(Context c, List<Result> users) { mContext = c; this.users = users; } class ViewHolder { TextView userTitle; ImageView userImage; } @Override public int getCount() { return users.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { // inflate the layout convertView = LayoutInflater.from(mContext).inflate(R.layout.user_card, null); // Set up the view holder viewHolder = new ViewHolder(); viewHolder.userTitle = (TextView) convertView.findViewById(R.id.user_name); viewHolder.userImage = (ImageView) convertView.findViewById(R.id.user_image); // store the viewholder with the view convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } User currentUser = users.get(position).getUser(); viewHolder.userTitle.setText(currentUser.getName().getFirst()); // Load the user image asynchronously Picasso.with(mContext) .load(currentUser.getPicture()) .placeholder(R.drawable.placeholder) .into(viewHolder.userImage); // Set the proper view name to get the transition well managed convertView.setViewName("photo" + position); return convertView; } }
/** * MIT License * <p> * Copyright (c) 2019-2022 nerve.network * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package network.nerve.converter.heterogeneouschain.eth.helper; import io.nuls.core.core.annotation.Autowired; import io.nuls.core.core.annotation.Component; import network.nerve.converter.heterogeneouschain.eth.model.EthSimpleBlockHeader; import network.nerve.converter.heterogeneouschain.eth.storage.EthBlockHeaderStorageService; import java.util.concurrent.ConcurrentHashMap; /** * 本地ETH区块操作器 * * @author: Mimi * @date: 2020-02-20 */ @Component public class EthLocalBlockHelper { @Autowired private EthBlockHeaderStorageService ethBlockStorageService; private static final String BLOCK_HEADER_KEY = "LOCAL_BLOCK_HEADER"; private static final ConcurrentHashMap<String, EthSimpleBlockHeader> localBlockHeaderMaps = new ConcurrentHashMap<>(); public EthSimpleBlockHeader getLatestLocalBlockHeader() { EthSimpleBlockHeader localBlockHeader = localBlockHeaderMaps.get(BLOCK_HEADER_KEY); if (localBlockHeader == null) { localBlockHeader = this.findLatest(); if(localBlockHeader != null) { localBlockHeaderMaps.putIfAbsent(BLOCK_HEADER_KEY, localBlockHeader); } } return localBlockHeader; } /** * 保存本地最新区块 */ public void saveLocalBlockHeader(EthSimpleBlockHeader blockHeader) throws Exception { localBlockHeaderMaps.put(BLOCK_HEADER_KEY, blockHeader); ethBlockStorageService.save(blockHeader); } /** * 查询本地数据库中最新区块 */ private EthSimpleBlockHeader findLatest() { EthSimpleBlockHeader blockHeader = ethBlockStorageService.findLatest(); return blockHeader; } /** * 根据高度查询区块 */ public EthSimpleBlockHeader findByHeight(long height) { return ethBlockStorageService.findByHeight(height); } public void deleteByHeight(Long localBlockHeight) throws Exception { ethBlockStorageService.deleteByHeight(localBlockHeight); } public void deleteByHeightAndUpdateMemory(Long localBlockHeight) throws Exception { this.deleteByHeight(localBlockHeight); // 缓存上一区块为本地最新区块 EthSimpleBlockHeader blockHeader = findByHeight(localBlockHeight - 1); if (blockHeader != null) { localBlockHeaderMaps.put(BLOCK_HEADER_KEY, blockHeader); } else { localBlockHeaderMaps.remove(BLOCK_HEADER_KEY); } } public void deleteAllLocalBlockHeader() throws Exception { EthSimpleBlockHeader localBlockHeader = this.getLatestLocalBlockHeader(); while(localBlockHeader != null) { this.deleteByHeightAndUpdateMemory(localBlockHeader.getHeight()); localBlockHeader = this.getLatestLocalBlockHeader(); } } }
package other; import java.util.Scanner; /** * 河内塔 * * @author danqiusheng * @since 2019-03-10 */ public class TowersOfHanoi { static int count = 0; public static void main(String[] args) { Scanner read = new Scanner(System.in); int n = read.nextInt(); hanoi(n, 'A', 'B', 'C'); // 初始化,三个柱子 } public static void hanoi(int n, char a, char b, char c) {// 第几个盘子, 参数意思,from temp to 通过temp将from的盘子转移到to; if (n == 1) { System.out.printf("第%d次: %c---to--%c\n", ++count, a, c); } else { hanoi(n - 1, a, c, b); System.out.printf("第%d次: %c---to--%c\n", ++count, a, c); hanoi(n - 1, b, a, c); } } }
package gov.nih.nci.ctrp.importtrials.util; import com.google.common.io.Resources; import gov.nih.nci.ctrp.importtrials.dto.*; import gov.nih.nci.ctrp.importtrials.dto.ctgov.ClinicalStudy; import gov.nih.nci.ctrp.importtrials.studyprotocolenum.StudyStatusCode; import org.apache.commons.lang3.time.DateUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.net.URL; import java.nio.charset.Charset; import java.util.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * Reshma Koganti */ @RunWith(Parameterized.class) public class ImportTrialStringUtilsExtractOverallStatusTest { @Parameterized.Parameter(value = 0) public String inputValue; @Parameterized.Parameter(value = 1) public StudyProtocolIdentityDTO dto; @Parameterized.Parameter(value = 2) public boolean expectedValue; @Parameterized.Parameter(value = 3) public String expectedStatus; @Parameterized.Parameters public static Collection<Object[]> data() { Collection<Object[]> params = new ArrayList<Object[]>(); StudyProtocolIdentityDTO dto = new StudyProtocolIdentityDTO(); dto.setStudyProtocolId("1"); params.add(new Object[] {"NCT03087968.xml", dto, true, "Recruiting" }); params.add(new Object[] {"NCT03087968.xml", new StudyProtocolIdentityDTO(), false, "Recruiting" }); params.add(new Object[] {"NCT03087969.xml", dto, true, "Available" }); params.add(new Object[] {"NCT03087969.xml", new StudyProtocolIdentityDTO(), true, "Available" }); params.add(new Object[] {"NCT03511430.xml", dto, true, "Enrolling by invitation" }); params.add(new Object[] {"NCT03511430.xml", new StudyProtocolIdentityDTO(), false, "Enrolling by invitation" }); params.add(new Object[] {"NCT03511547.xml", dto, true, "Withdrawn" }); params.add(new Object[] {"NCT03511547.xml", new StudyProtocolIdentityDTO(), true, "Withdrawn" }); return params; } @Test public void testExtractOverallStatus() throws Exception { URL resourceUrl = Resources.getResource(inputValue); String testXML = Resources.toString(resourceUrl, Charset.defaultCharset()); ClinicalStudy study = ImportTrialUtils.unmarshallXML(testXML, ClinicalStudy.class); StudyOverallStatusDTO status = ClinicalStudyConverter.extractOverallStatusDTO(study, dto); assertNotNull(status); assertEquals(status.getStatusCode().toString(), StudyStatusCode.getByCtGovCode(expectedStatus).toString().toUpperCase()); assertEquals(expectedValue, DateUtils.isSameDay(new Date(), status.getStatusDate())); } }
package com.example.isvirin.storeclient.data.entity.daoconverter; public enum BrandType { TEXT, LIST, PICTURE }
package com.inheritance; public class OverloadingDemo { public static void main(String[] args) { Shape s=new Shape(); System.out.println("Area of square "+s.area(20)); System.out.println("Area of Rectangle "+s.area(10,20)); } }
package com.demo.decorator.ComputerMeal; /** * @author: Maniac Wen * @create: 2020/3/30 * @update: 10:02 * @version: V1.0 * @detail: **/ public abstract class Computer { //获得商品信息 protected abstract String getMsg(); //获得商品价格 protected abstract int getPrice(); }
package com.java8.files; import java.io.FileWriter; import java.io.IOException; /** * @author Neeraj Kumar * * ARM can reduce the verbosity in the previous example * FileWriterExample.java. Rather than using both the try and finally * blocks, we can use a special form of the try block with a resource * attached to it. Then the Java compiler takes care of automatically * inserting the finally block and the call to the close() method. * * * */ public class FileWriterARM implements AutoCloseable { FileWriter writer; public FileWriterARM(String fileName) throws IOException { this.writer = new FileWriter(fileName); } public void write(String message) throws IOException { writer.write(message); } public static void main(String[] args) throws IOException, Exception { try (FileWriterARM fwArm = new FileWriterARM("/home/neeraj/Development/fileWriterArm.txt")) { fwArm.write("Writing to file with AutoClosable implementation"); } } @Override public void close() throws Exception { writer.close(); } }
package YouTubeTutorial; public class LessonThree { public static void main(String[] args) { int randomNumber = (int)(Math.random() * 50); System.out.println(randomNumber); if (randomNumber < 25) { System.out.println("Random number is less than 25"); } else if (randomNumber > 50) { System.out.println(randomNumber + " is greater than 50"); } } }
package com.project.database; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import com.project.model.Party; import com.project.model.Post; public class DatabaseAccess { private Connection currentCon = null; public Party getPartyById(int id) { Party party = null; try { currentCon = new ClientSpecificDataConnectionManager().getConnection(); String query = "select * from party where id = ?"; PreparedStatement pst = currentCon.prepareStatement(query); pst.setInt(1, id); ResultSet rs = pst.executeQuery(); while (rs.next()) { party = new Party(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return party; } public ArrayList<Party> getAllParties() { ArrayList<Party> parties = new ArrayList<>(); try { currentCon = new ClientSpecificDataConnectionManager().getConnection(); String query = "select * from party"; PreparedStatement pst = currentCon.prepareStatement(query); ResultSet rs = pst.executeQuery(); while(rs.next()) { Party party = getPartyById(rs.getInt(1)); parties.add(party); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return parties; } public Party createParty(Party party) { int maxId = getMaxId(party); party.setId(maxId+1); try { currentCon = new ClientSpecificDataConnectionManager().getConnection(); String query = "insert into party values (?,?,?,?,?)"; PreparedStatement pst = currentCon.prepareStatement(query); pst.setInt(1, party.getId()); pst.setString(2, party.getName()); pst.setString(3,party.getOrganizer()); pst.setString(4, party.getDate()); pst.setString(5, party.getPlace()); int row = pst.executeUpdate(); if(row != 0) { System.out.println("Party Successfully created into the database"); }else { System.out.println("There is some error in the createParty function"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return party; } private int getMaxId(Party party) { int maxId = 0; try { currentCon = new ClientSpecificDataConnectionManager().getConnection(); String query = "select max(Id) from party"; PreparedStatement pst = currentCon.prepareStatement(query); ResultSet rs = pst.executeQuery(); while(rs.next()) { maxId = rs.getInt(1); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return maxId; } public int loadAllPosts(ArrayList<Post> posts) { int count = 0; try { currentCon = new ClientSpecificDataConnectionManager().getConnection(); String query = "Insert into post values (?,?,?,?)"; PreparedStatement pst = currentCon.prepareStatement(query); for(Post p : posts) { pst.setLong(1,p.getId()); pst.setLong(2, p.getUserId()); pst.setString(3, p.getTitle()); pst.setString(4, p.getBody()); count += pst.executeUpdate(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return count; } }
package com.yjn.haoba.domain; import java.util.Date; public class User { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column user_tb.userId * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ private String userid; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column user_tb.nickName * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ private String nickname; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column user_tb.email * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ private String email; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column user_tb.passwd * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ private String passwd; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column user_tb.createTime * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ private Date createtime; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column user_tb.status * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ private Integer status; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column user_tb.userId * * @return the value of user_tb.userId * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ public String getUserid() { return userid; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column user_tb.userId * * @param userid the value for user_tb.userId * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ public void setUserid(String userid) { this.userid = userid == null ? null : userid.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column user_tb.nickName * * @return the value of user_tb.nickName * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ public String getNickname() { return nickname; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column user_tb.nickName * * @param nickname the value for user_tb.nickName * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ public void setNickname(String nickname) { this.nickname = nickname == null ? null : nickname.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column user_tb.email * * @return the value of user_tb.email * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ public String getEmail() { return email; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column user_tb.email * * @param email the value for user_tb.email * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ public void setEmail(String email) { this.email = email == null ? null : email.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column user_tb.passwd * * @return the value of user_tb.passwd * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ public String getPasswd() { return passwd; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column user_tb.passwd * * @param passwd the value for user_tb.passwd * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ public void setPasswd(String passwd) { this.passwd = passwd == null ? null : passwd.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column user_tb.createTime * * @return the value of user_tb.createTime * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ public Date getCreatetime() { return createtime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column user_tb.createTime * * @param createtime the value for user_tb.createTime * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ public void setCreatetime(Date createtime) { this.createtime = createtime; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column user_tb.status * * @return the value of user_tb.status * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ public Integer getStatus() { return status; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column user_tb.status * * @param status the value for user_tb.status * * @mbggenerated Fri Mar 08 20:51:11 CST 2013 */ public void setStatus(Integer status) { this.status = status; } }
package com.trump.auction.trade.model; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data public class ProductPic implements Serializable{ private static final long serialVersionUID = -7315438062272532712L; /** * 主键,不为空 */ private Integer id; /** * 图片路径 */ private String picUrl; /** * 规格id */ private Integer skuId; /** * 颜色ID */ private Integer colorId; /** * 商品id */ private Integer productId; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date updateTime; /** * 图片类型 0详情 1商品 2.商品缩略图 3.质保图片 */ private String picType; /** * 操作人id */ private String userId; /** * 操作人ip */ private String userIp; }
package be.openclinic.datacenter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Vector; import webcab.lib.statistics.pdistributions.NormalProbabilityDistribution; import webcab.lib.statistics.statistics.BasicStatistics; import be.mxs.common.util.db.MedwanQuery; import be.mxs.common.util.system.ScreenHelper; public class ExporterActivity extends Exporter { public void export(){ if(!mustExport(getParam())){ return; } if(getParam().equalsIgnoreCase("activity.1")){ //Export a summary of all ICD-10 based KPGS codes per month //First find first month for which a summary must be provided StringBuffer sb = new StringBuffer("<activities>"); String firstMonth = MedwanQuery.getInstance().getConfigString("datacenterFirstActivitySummaryMonth","0"); if(firstMonth.equalsIgnoreCase("0")){ //Find oldest diagnosis Connection oc_conn = MedwanQuery.getInstance().getAdminConnection(); try { PreparedStatement ps = oc_conn.prepareStatement("select count(*) total,min(accesstime) as firstMonth from AccessLogs"); ResultSet rs = ps.executeQuery(); if(rs.next() && rs.getInt("total")>0){ firstMonth=new SimpleDateFormat("yyyyMM").format(rs.getDate("firstMonth")); } rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { oc_conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } try { boolean bFound=false; Date lastDay=new Date(new SimpleDateFormat("yyyyMMdd").parse(new SimpleDateFormat("yyyyMM").format(new Date())+"01").getTime()-1); Date firstDay=new SimpleDateFormat("yyyyMMdd").parse(firstMonth+"01"); if(firstDay.before(ScreenHelper.parseDate("01/01/2000"))){ firstDay=ScreenHelper.parseDate("01/01/2000"); } int firstYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(firstDay)); int lastYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(lastDay)); for(int n=firstYear;n<=lastYear;n++){ int firstmonth=1; if(n==firstYear){ firstmonth=Integer.parseInt(new SimpleDateFormat("MM").format(firstDay));; } int lastmonth=12; if(n==lastYear){ lastmonth=Integer.parseInt(new SimpleDateFormat("MM").format(lastDay));; } for(int i=firstmonth;i<=lastmonth;i++){ //Find all diagnoses for this month Date begin = ScreenHelper.parseDate("01/"+i+"/"+n); Date end = ScreenHelper.parseDate(i==12?"01/01/"+(n+1):"01/"+(i+1)+"/"+n); Connection oc_conn = MedwanQuery.getInstance().getAdminConnection(); try { Vector m = new Vector(); PreparedStatement ps = oc_conn.prepareStatement("select count(*) total, userid from accesslogs where accesstime>=? and accesstime<? and accesscode like 'A.%' group by userid"); ps.setTimestamp(1,new java.sql.Timestamp(begin.getTime())); ps.setTimestamp(2,new java.sql.Timestamp(end.getTime())); ResultSet rs = ps.executeQuery(); while(rs.next()){ m.add(rs.getDouble("total")); bFound=true; } if(m.size()>0){ double[] measurements = new double[m.size()]; for(int q=0;q<m.size();q++){ measurements[q]=(Double)m.elementAt(q); } BasicStatistics basicStatistics = new BasicStatistics(measurements); sb.append("<activity type='A' users='"+m.size()+"' mean='"+basicStatistics.arithmeticMean()+"' median='"+basicStatistics.median()+"' meanDeviation='"+basicStatistics.meanDeviation()+"' month='"+i+"' year='"+n+"'/>"); } rs.close(); ps.close(); m = new Vector(); ps = oc_conn.prepareStatement("select count(*) total, userid from accesslogs where accesstime>=? and accesstime<? and accesscode like 'M.%' group by userid"); ps.setTimestamp(1,new java.sql.Timestamp(begin.getTime())); ps.setTimestamp(2,new java.sql.Timestamp(end.getTime())); rs = ps.executeQuery(); while(rs.next()){ m.add(rs.getDouble("total")); bFound=true; } if(m.size()>0){ double[]measurements = new double[m.size()]; for(int q=0;q<m.size();q++){ measurements[q]=(Double)m.elementAt(q); } BasicStatistics basicStatistics = new BasicStatistics(measurements); sb.append("<activity type='M' users='"+m.size()+"' mean='"+basicStatistics.arithmeticMean()+"' median='"+basicStatistics.median()+"' meanDeviation='"+basicStatistics.meanDeviation()+"' month='"+i+"' year='"+n+"'/>"); } rs.close(); ps.close(); m = new Vector(); ps = oc_conn.prepareStatement("select count(*) total, userid from accesslogs where accesstime>=? and accesstime<? and accesscode like 'T.%' group by userid"); ps.setTimestamp(1,new java.sql.Timestamp(begin.getTime())); ps.setTimestamp(2,new java.sql.Timestamp(end.getTime())); rs = ps.executeQuery(); while(rs.next()){ m.add(rs.getDouble("total")); bFound=true; } if(m.size()>0){ double[] measurements = new double[m.size()]; for(int q=0;q<m.size();q++){ measurements[q]=(Double)m.elementAt(q); } BasicStatistics basicStatistics = new BasicStatistics(measurements); sb.append("<activity type='T' users='"+m.size()+"' mean='"+basicStatistics.arithmeticMean()+"' median='"+basicStatistics.median()+"' meanDeviation='"+basicStatistics.meanDeviation()+"' month='"+i+"' year='"+n+"'/>"); } rs.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { oc_conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } if(bFound){ sb.append("</activities>"); exportSingleValue(sb.toString(), "activity.1"); MedwanQuery.getInstance().setConfigString("datacenterFirstActivitySummaryMonth", new SimpleDateFormat("yyyyMM").format(new Date(lastDay.getTime()+2))); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package com.karya.bean; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; public class PurItemsOrderReceiveBean { private int poitrecId; @NotNull @NotEmpty(message = "Please enter the purchase order") private String puOrder; @NotNull @NotEmpty(message = "Please enter the date") private String date; @NotNull @NotEmpty(message = "Please enter required by date") private String reqbyDate; @NotNull @NotEmpty(message = "Please enter the supplier name") private String supName; @NotNull @NotEmpty(message = "Please enter the project name") private String projectName; @NotNull @NotEmpty(message = "Please enter the quantity") private String quantity; @NotNull @NotEmpty(message = "Please enter the received quantity") private String receivedQty; @NotNull @NotEmpty(message = "Please enter the quantity to receive") private String qtytoReceive; @NotNull @NotEmpty(message = "Please enter the warehouse name") private String warehouseName; @NotNull @NotEmpty(message = "Please enter the itemcode") private String itemCode; @NotNull @NotEmpty(message = "Please enter the description") private String description; @NotNull @NotEmpty(message = "Please enter the brand name") private String brandName; @NotNull @NotEmpty(message = "Please enter the company") private String company; public int getPoitrecId() { return poitrecId; } public void setPoitrecId(int poitrecId) { this.poitrecId = poitrecId; } public String getPuOrder() { return puOrder; } public void setPuOrder(String puOrder) { this.puOrder = puOrder; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getReqbyDate() { return reqbyDate; } public void setReqbyDate(String reqbyDate) { this.reqbyDate = reqbyDate; } public String getSupName() { return supName; } public void setSupName(String supName) { this.supName = supName; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getQuantity() { return quantity; } public void setQuantity(String quantity) { this.quantity = quantity; } public String getReceivedQty() { return receivedQty; } public void setReceivedQty(String receivedQty) { this.receivedQty = receivedQty; } public String getQtytoReceive() { return qtytoReceive; } public void setQtytoReceive(String qtytoReceive) { this.qtytoReceive = qtytoReceive; } public String getWarehouseName() { return warehouseName; } public void setWarehouseName(String warehouseName) { this.warehouseName = warehouseName; } public String getItemCode() { return itemCode; } public void setItemCode(String itemCode) { this.itemCode = itemCode; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } }
package com.ut.database.entity; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; import android.support.annotation.NonNull; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * author : chenjiajun * time : 2018/12/25 * desc : */ @Entity public class LockMessage implements Serializable { @NonNull @PrimaryKey private String lockMac;// "123", private long id;// 4, private String name;// "4", private String lockName;// "蓝牙锁", private String description;// "4", private int type;// 1, private int unReadCount;// 3, private long createTime;// 1544595271000 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLockName() { return lockName; } public void setLockName(String lockName) { this.lockName = lockName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLockMac() { return lockMac; } public void setLockMac(String lockMac) { this.lockMac = lockMac; } public int getType() { return type; } public void setType(int type) { this.type = type; } public long getId() { return id; } public void setId(long id) { this.id = id; } public int getUnReadCount() { return unReadCount; } public void setUnReadCount(int unReadCount) { this.unReadCount = unReadCount; } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } public String createTimeformat() { return new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.getDefault()).format(new Date(createTime)); } }
package org.apache.hadoop.hdfs.server.blockmanagement; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Random; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.server.namenode.persistance.storage.StorageFactory; import org.junit.Test; /** * Test to validate the getBlockLocations functionality in the readerNN * * Tests the following functionality: 1. Start a writerNN with datanodes 2. * Start a readerNN without datanodes 3. Write a file (with blocks) on the * writerNN and the datanodes 4. Read that file from the readerNN (with tokens * disabled) 5. Read that file from the readerNN (with tokens enabled) * * @author wmalik */ public class TestGetBlockLocations { private static final int BLOCK_SIZE = 1024; private static final int FILE_SIZE = 2 * BLOCK_SIZE; private final byte[] rawData = new byte[FILE_SIZE]; { Random r = new Random(); r.nextBytes(rawData); } private void createFile(FileSystem fs, Path filename) throws IOException { FSDataOutputStream out = fs.create(filename); out.write(rawData); out.close(); } // read a file using blockSeekTo() private boolean checkFile1(FSDataInputStream in) { byte[] toRead = new byte[FILE_SIZE]; int totalRead = 0; int nRead = 0; try { while ((nRead = in.read(toRead, totalRead, toRead.length - totalRead)) > 0) { totalRead += nRead; } } catch (IOException e) { e.printStackTrace(System.err); return false; } assertEquals("Cannot read file.", toRead.length, totalRead); return checkFile(toRead); } // read a file using fetchBlockByteRange() private boolean checkFile2(FSDataInputStream in) { byte[] toRead = new byte[FILE_SIZE]; try { assertEquals("Cannot read file", toRead.length, in.read(0, toRead, 0, toRead.length)); } catch (IOException e) { return false; } return checkFile(toRead); } private boolean checkFile(byte[] fileToCheck) { if (fileToCheck.length != rawData.length) { return false; } for (int i = 0; i < fileToCheck.length; i++) { if (fileToCheck[i] != rawData[i]) { return false; } } return true; } // get a conf for testing /** * @param numDataNodes * @param tokens enable tokens? * @return * @throws IOException */ private static Configuration getConf(int numDataNodes, boolean tokens) throws IOException { Configuration conf = new Configuration(); if (tokens) { conf.setBoolean(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, true); } conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE); conf.setInt("io.bytes.per.checksum", BLOCK_SIZE); conf.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1); conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, numDataNodes); conf.setInt("ipc.client.connect.max.retries", 0); conf.setBoolean("dfs.support.append", true); return conf; } private MiniDFSCluster startCluster(boolean tokens) throws IOException { MiniDFSCluster cluster = null; int numDataNodes = 2; Configuration conf = getConf(numDataNodes, tokens); StorageFactory.setConfiguration(conf); cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDataNodes).numNameNodes(1).build(); cluster.waitActive(); assertEquals(numDataNodes, cluster.getDataNodes().size()); return cluster; } @Test public void testReadNnWithoutTokens() throws Exception { MiniDFSCluster cluster = null; try { cluster = startCluster(false); FileSystem fs = cluster.getFileSystem(); //create some directories Path filePath1 = new Path("/testDir1"); Path filePath2 = new Path("/testDir2"); Path filePath3 = new Path("/testDir3"); assertTrue(fs.mkdirs(filePath1)); assertTrue(fs.mkdirs(filePath2)); assertTrue(fs.mkdirs(filePath3)); //check if the directories were created successfully FileStatus lfs = fs.getFileStatus(filePath1); assertTrue(lfs.getPath().getName().equals("testDir1")); //write a new file on the writeNn and confirm if it can be read Path fileTxt = new Path("/file.txt"); createFile(fs, fileTxt); FSDataInputStream in1 = fs.open(fileTxt); assertTrue(checkFile1(in1)); //try to read the file from the readNn (calls readerFsNamesystem.getBlockLocations under the hood) FSDataInputStream in2 = fs.open(fileTxt); assertTrue(checkFile1(in2)); fs.close(); } finally { if (cluster != null) { cluster.shutdown(); } } } @Test public void testReadNnWithTokens() throws Exception { MiniDFSCluster cluster = null; try { cluster = startCluster(true); //use tokens FileSystem fs = cluster.getFileSystem(); //create some directories Path filePath1 = new Path("/testDir1"); Path filePath2 = new Path("/testDir2"); Path filePath3 = new Path("/testDir3"); assertTrue(fs.mkdirs(filePath1)); assertTrue(fs.mkdirs(filePath2)); assertTrue(fs.mkdirs(filePath3)); //check if the directories were created successfully FileStatus lfs = fs.getFileStatus(filePath1); assertTrue(lfs.getPath().getName().equals("testDir1")); //write a new file on the writeNn and confirm if it can be read Path fileTxt = new Path("/file.txt"); createFile(fs, fileTxt); FSDataInputStream in1 = fs.open(fileTxt); assertTrue(checkFile1(in1)); //try to read the file from the readNn (calls readerFsNamesystem.getBlockLocations under the hood) FSDataInputStream in2 = fs.open(fileTxt); assertTrue(checkFile1(in2)); } finally { if (cluster != null) { cluster.shutdown(); } } } }
package com.zantong.mobilecttx.widght; import android.content.Context; import android.content.res.TypedArray; import android.text.InputFilter; import android.text.InputType; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.zantong.mobilecttx.R; /** * 办卡输入框样式 */ public class CttxEditText extends LinearLayout { private TextView mTitle; private EditText mContent; private ImageView mImgFlag; private LinearLayout layout; private String strTitle; private String strContent; private String strContentHint; public CttxEditText(Context context) { super(context); } public CttxEditText(Context context, AttributeSet attrs) { super(context, attrs); initView(context, attrs); } public CttxEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context, attrs); } private void initView(Context context, AttributeSet attrs) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.view_edittext, this, true); layout = (LinearLayout) view.findViewById(R.id.view_edittext_layout); mTitle = (TextView) view.findViewById(R.id.view_edittext_title); mContent = (EditText) view.findViewById(R.id.view_edittext_content); mImgFlag = (ImageView) view.findViewById(R.id.view_edittext_flag); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CttxEditText); strTitle = typedArray.getString(R.styleable.CttxEditText_titletext); strContent = typedArray.getString(R.styleable.CttxEditText_contenttext); strContentHint = typedArray.getString(R.styleable.CttxEditText_hinttext); //设置输入类型 int inputType = typedArray.getInt(R.styleable.CttxEditText_contentinputtype, -1); if (inputType == 0) {//不限制 mContent.setInputType(InputType.TYPE_CLASS_TEXT); } else if (inputType == 1) {//数字 mContent.setInputType(InputType.TYPE_CLASS_NUMBER); } else if (inputType == 2) {//字母或数字 mContent.setInputType(InputType.TYPE_NUMBER_VARIATION_NORMAL); // mContent.setKeyListener(DigitsKeyListener.getInstance("1234567890qwertyuiopasdfghjklzxcvbnm")); } else if (inputType == 3) {//数字或X(身份证号) mContent.setInputType(InputType.TYPE_NUMBER_VARIATION_NORMAL); // mContent.setKeyListener(DigitsKeyListener.getInstance("1234567890Xx")); } else if (inputType == 4) {//纯字母 mContent.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS); // mContent.setKeyListener(DigitsKeyListener.getInstance("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLXCVBNM")); } //设置限制字符、 mContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(typedArray.getInt(R.styleable.CttxEditText_contentlength, 16))}); boolean isVisibleImg = typedArray.getBoolean(R.styleable.CttxEditText_imgflag, false); mImgFlag.setVisibility(isVisibleImg ? View.VISIBLE : View.GONE); boolean editEnable = typedArray.getBoolean(R.styleable.CttxEditText_edit_enable, true); if (!editEnable) { mContent.setFocusable(false); mContent.setFocusableInTouchMode(false); } typedArray.recycle(); if (TextUtils.isEmpty(strTitle)) { strTitle = ""; } mTitle.setText(strTitle); if (TextUtils.isEmpty(strContentHint)) { strContentHint = ""; } mContent.setHint(strContentHint); if (TextUtils.isEmpty(strContent)) { strContent = ""; } mContent.setText(strContent); } public void setImgFlag(boolean isVisible) { mImgFlag.setVisibility(isVisible ? View.VISIBLE : View.GONE); } /** * 设置输入框内容 */ public void setContentText(String content) { mContent.setText(content); } /** * 获取输入内容 */ public String getContentText() { return mContent.getText().toString().trim(); } }
package sr.hakrinbank.intranet.api.controller; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import sr.hakrinbank.intranet.api.dto.ListedPersonGreyDto; import sr.hakrinbank.intranet.api.dto.ResponseDto; import sr.hakrinbank.intranet.api.mapping.ListedPersonGreyToDtoMap; import sr.hakrinbank.intranet.api.model.ListedPersonGrey; import sr.hakrinbank.intranet.api.model.Nationality; import sr.hakrinbank.intranet.api.service.ListedPersonGreyService; import sr.hakrinbank.intranet.api.service.NationalityService; import sr.hakrinbank.intranet.api.util.Constant; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping(value = "/api/listedpersongrey") public class ListedPersonGreyController { @Autowired private ListedPersonGreyService listedPersonGreyService; @Autowired private NationalityService nationalityService; //-------------------Retrieve All ListedPersonGrey-------------------------------------------------------- @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listAllListedPersonGrey() { List<ListedPersonGrey> ListedPersonGrey = listedPersonGreyService.findAllActiveListedPersonGrey(); if(ListedPersonGrey.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapListedPersonGreyToDto(ListedPersonGrey), null), HttpStatus.OK); } //-------------------Retrieve All ListedPersonGrey By Search-------------------------------------------------------- @RequestMapping(value = "search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> listListedPersonGreyBySearchQuery(@RequestParam String qry) { List<ListedPersonGrey> ListedPersonGrey = listedPersonGreyService.findAllActiveListedPersonGreyBySearchQuery(qry); if(ListedPersonGrey.isEmpty()){ return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT); } return new ResponseEntity<ResponseDto>(new ResponseDto(mapListedPersonGreyToDto(ListedPersonGrey), mapListedPersonGreyToDto(ListedPersonGrey).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK); } //-------------------Retrieve All ListedPersonGrey With Pagination-------------------------------------------------------- // @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) // public ResponseEntity<Page<ListedPersonGrey>> listAllListedPersonGrey(Pageable pageable) { // Page<ListedPersonGrey> ListedPersonGrey = listedPersonGreyService.findAllListedPersonGreyByPage(pageable); // return new ResponseEntity<Page<ListedPersonGrey>>(ListedPersonGrey, HttpStatus.OK); // } //-------------------Retrieve Single ListedPersonGrey-------------------------------------------------------- @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ListedPersonGrey> getListedPersonGrey(@PathVariable("id") long id) { System.out.println("Fetching ListedPersonGrey with id " + id); ListedPersonGrey ListedPersonGrey = listedPersonGreyService.findById(id); if (ListedPersonGrey == null) { System.out.println("ListedPersonGrey with id " + id + " not found"); return new ResponseEntity<ListedPersonGrey>(HttpStatus.NOT_FOUND); } return new ResponseEntity<ListedPersonGrey>(ListedPersonGrey, HttpStatus.OK); } //-------------------Create a ListedPersonGrey-------------------------------------------------------- @RequestMapping(value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> createListedPersonGrey(@RequestBody ListedPersonGreyDto listedPersonGreyDto) { System.out.println("Creating ListedPersonGrey with name " + listedPersonGreyDto.getLastName()); if (listedPersonGreyDto.getId() != null) { System.out.println("A ListedPersonGrey with id " + listedPersonGreyDto.getId() + " already exist"); return new ResponseEntity<ResponseDto>(new ResponseDto(null, "A ListedPersonGrey with id " + listedPersonGreyDto.getId() + " already exist"), HttpStatus.CONFLICT); } mapAndUpdateListedPersonGrey(listedPersonGreyDto); return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_SAVED), HttpStatus.CREATED); } //------------------- Update a ListedPersonGrey -------------------------------------------------------- @RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ResponseDto> updateListedPersonGrey(@PathVariable("id") long id, @RequestBody ListedPersonGreyDto listedPersonGreyDto) { System.out.println("Updating ListedPersonGrey " + id); ListedPersonGrey currentListedPersonGrey = listedPersonGreyService.findById(id); if (currentListedPersonGrey == null) { System.out.println("ListedPersonGrey with id " + id + " not found"); return new ResponseEntity<ResponseDto>(new ResponseDto(null, "ListedPersonGrey with id " + id + " not found"), HttpStatus.NOT_FOUND); } mapAndUpdateListedPersonGrey(listedPersonGreyDto); return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_UPDATED), HttpStatus.OK); } //------------------- Delete a ListedPersonGrey -------------------------------------------------------- @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public ResponseEntity<ResponseDto> deleteListedPersonGrey(@PathVariable("id") long id) { System.out.println("Fetching & Deleting ListedPersonGrey with id " + id); ListedPersonGrey ListedPersonGrey = listedPersonGreyService.findById(id); if (ListedPersonGrey == null) { System.out.println("Unable to delete. ListedPersonGrey with id " + id + " not found"); return new ResponseEntity<ResponseDto>(new ResponseDto(null, "Unable to delete. ListedPersonGrey with id " + id + " not found"), HttpStatus.NOT_FOUND); } ListedPersonGrey.setDeleted(true); listedPersonGreyService.updateListedPersonGrey(ListedPersonGrey); return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_DELETED), HttpStatus.OK); } //------------------- HELPER METHODS -------------------------------------------------------- public static List<ListedPersonGreyDto> mapListedPersonGreyToDto(List<ListedPersonGrey> listedPersonGreys) { List<ListedPersonGreyDto> listedPersonGreyDtos = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addMappings(new ListedPersonGreyToDtoMap()); for(ListedPersonGrey listedPersonGreyItem: listedPersonGreys){ ListedPersonGreyDto listedPersonGreyDto = modelMapper.map(listedPersonGreyItem, ListedPersonGreyDto.class); if(listedPersonGreyItem.getNationality() != null) listedPersonGreyDto.setNationalityName(listedPersonGreyItem.getNationality().getName()); listedPersonGreyDtos.add(listedPersonGreyDto); } return listedPersonGreyDtos; } private void mapAndUpdateListedPersonGrey(ListedPersonGreyDto listedPersonGreyDto) { ModelMapper modelMapper = new ModelMapper(); ListedPersonGrey listedPersonGrey = modelMapper.map(listedPersonGreyDto, ListedPersonGrey.class); Nationality nationality = nationalityService.findById(listedPersonGreyDto.getNationality()); Nationality noNationality = nationalityService.findById(Constant.GEEN_ID); if (Long.valueOf(listedPersonGreyDto.getNationality()) != null) { listedPersonGrey.setNationality(nationality); } else { listedPersonGrey.setNationality(noNationality); } listedPersonGreyService.updateListedPersonGrey(listedPersonGrey); } }
package me.kpali.wolfflow.core.model; /** * 任务流上下文 * * @author kpali */ public class TaskFlowContextKey { public static final String TASK_FLOW_ID = "taskFlowId"; public static final String IS_ROLLBACK = "isRollback"; public static final String FROM_TASK_ID = "fromTaskId"; public static final String TO_TASK_ID = "toTaskId"; public static final String LOG_ID = "logId"; public static final String PARAMS = "params"; public static final String DELIVERY_CONTEXT = "deliveryContext"; public static final String EXECUTE_TASK_FLOW = "executeTaskFlow"; public static final String ROLLBACK_TASK_FLOW = "rollbackTaskFlow"; public static final String TASK_CONTEXTS = "taskContexts"; public static final String EXECUTED_BY_NODE = "executedByNode"; }
package redisOperation; import org.junit.Before; import org.junit.Test; import redis.clients.jedis.Jedis; import java.util.*; import static java.lang.System.*; public class RedisOps { Jedis jedis; @Before public void setup (){ jedis = new Jedis("localhost"); } /** * redis存储初级的字符串 */ @Test public void testBasicString() { //添加数据 jedis.set("name", "jane"); out.println(jedis.get("name")); //修改数据 // 1: 追加 jedis.append("name"," lee"); out.println(jedis.get("name")); // 2: 覆写 jedis.set("name", " Lee Jane"); out.println(jedis.get("name")); //删除key对应的记录 jedis.del("name"); out.println(jedis.get("name")); /** * mset相当于 * jedis.set("name","meepo"); * jedis.set("dota","poofu"); */ jedis.mset("name","meepo","dota","poofu"); out.println(jedis.mget("name","dota")); } /** * redis 操作map */ @Test public void testMap() { Map<String, String> user = new HashMap<>(); user.put("name","meepo"); user.put("pwd","password"); user.put("gender", "female"); jedis.hmset("user", user); List<String> name = jedis.hmget("user", "pwd"); out.println(name); /* 删除键值 */ jedis.hdel("user", "pwd"); out.println(jedis.hget("user", "pwd")); //null out.println(jedis.hlen("user")); // 2 out.println(jedis.exists("user"));// yes out.println(jedis.hexists("user","pwd")); // no out.println(jedis.hkeys("user"));// name gender out.println(jedis.hvals("user"));// meepo female //便利键值 jedis.hkeys("user").forEach(out::println); // name gender } /** * 操作list */ @Test public void testList() { jedis.lpush("java framework","spring"); jedis.lpush("java framework", "spring-boot"); jedis.lpush("java framework", "spring-cloud"); out.println(jedis.lrange("java framework", 0, -1)); } /** * 操作set */ @Test public void testSet() { jedis.sadd("sname","meepo"); jedis.sadd("sname","poofu"); jedis.sadd("sname","noname"); jedis.sadd("sname","dota"); //移除 jedis.srem("sname","noname"); out.println(jedis.smembers("sname")); // meepo poofu dota out.println(jedis.sismember("sname", "noname") + " : " + jedis.sismember("sname", "dota")); // false : true out.println(jedis.srandmember("sname")); // 返回一个随机成员 out.println(jedis.scard("sname")); // 3 返回元素个数 } @Test public void test() throws InterruptedException { //向key中传入通配符 out.println(jedis.keys("*")); // get all keys out.println(jedis.keys("*name")); // get keys ending with name out.println(jedis.del("snaddd")); // delete key snaddd success : 1 failure (or does not exist): 0 jedis.setex("timekey", 10, "min"); // set life time to key , unit: s Thread.sleep(5000); out.println(jedis.ttl("timekey")); // return 5 s jedis.setex("timekey", 100, "min"); out.println(jedis.exists("timekey")); // check if the key exists here yes and return true jedis.rename("timekey", "key"); // rename the key out.println(jedis.get("timekey")); // now that timekey is renamed as key , here comes out null out.println(jedis.get("key")); // the key is the old timekey ,so its value is min //jedis 排序 jedis.del("a"); jedis.lpush("a", "100"); jedis.lpush("a", "0"); jedis.lpush("a", "120"); jedis.lpush("a", "100"); jedis.lpush("a", "90"); out.println(jedis.lrange("a", 0, -1)); out.println(jedis.sort("a")); out.println(jedis.lrange("a", 0, -1)); } }
package se.fam_karlsson.system.recipes.services; import org.jboss.logging.Logger; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ws.rs.HEAD; import javax.ws.rs.Path; import javax.ws.rs.core.Response; @Stateless @Path("status") public class StatusServiceBean { private transient Logger itsLog = Logger.getLogger(StatusServiceBean.class); @HEAD @Path("/ping") @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public Response getStatus() { itsLog.trace("Status Ping received!"); return Response.ok().build(); } }
package com.atguigu.springcloud.config; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Configuration; /** * @author Yue_ * @create 2020-12-01-17:23 */ @Configuration @MapperScan({"com.atguigu.springcloud.dao"}) public class MyBatisConfig { }
import java.util.HashMap; import java.util.Map; public class CourseWithNumber { private Map<String,Double> courseAndNumberList = new HashMap<>(); public CourseWithNumber(Map<String,Double> courseAndNumberList) { this.courseAndNumberList = courseAndNumberList; } public Map<String, Double> getCourseAndNumberList() { return new HashMap<>(courseAndNumberList); } }
package plugins.fmp.fmpTools; import java.awt.Point; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.attribute.FileTime; import java.util.ArrayList; import org.apache.poi.ss.util.CellReference; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import icy.gui.frame.progress.ProgressFrame; import plugins.fmp.fmpSequence.Experiment; import plugins.fmp.fmpSequence.XYTaSeries; public class XLSExportMoveResults extends XLSExport { public void exportToFile(String filename, XLSExportOptions opt) { System.out.println("XLS move output"); options = opt; ProgressFrame progress = new ProgressFrame("Export data to Excel"); try { XSSFWorkbook workbook = new XSSFWorkbook(); workbook.setMissingCellPolicy(Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); int col_max = 0; int col_end = 0; int iSeries = 0; options.experimentList.readInfosFromAllExperiments(); expAll = options.experimentList.getStartAndEndFromAllExperiments(); expAll.step = options.experimentList.experimentList.get(0).vSequence.analysisStep; listOfStacks = new ArrayList <XLSNameAndPosition> (); progress.setMessage( "Load measures..."); progress.setLength(options.experimentList.experimentList.size()); for (Experiment exp: options.experimentList.experimentList) { String charSeries = CellReference.convertNumToColString(iSeries); if (options.xyCenter) col_end = xlsExportToWorkbook(exp, workbook, col_max, charSeries, EnumXLSExportItems.XYCENTER); if (options.distance) col_end = xlsExportToWorkbook(exp, workbook, col_max, charSeries, EnumXLSExportItems.DISTANCE); if (options.alive) col_end = xlsExportToWorkbook(exp, workbook, col_max, charSeries, EnumXLSExportItems.ISALIVE); if (col_end > col_max) col_max = col_end; iSeries++; progress.incPosition(); } if (options.transpose && options.pivot) { progress.setMessage( "Build pivot tables... "); String sourceSheetName = null; if (options.alive) sourceSheetName = EnumXLSExportItems.ISALIVE.toString(); else if (options.xyCenter) sourceSheetName = EnumXLSExportItems.XYCENTER.toString(); else if (options.distance) sourceSheetName = EnumXLSExportItems.DISTANCE.toString(); xlsCreatePivotTables(workbook, sourceSheetName); } progress.setMessage( "Save Excel file to disk... "); FileOutputStream fileOut = new FileOutputStream(filename); workbook.write(fileOut); fileOut.close(); workbook.close(); } catch (IOException e) { e.printStackTrace(); } progress.close(); System.out.println("XLS output finished"); } private static ArrayList <ArrayList<Double>> getDataFromCages(Experiment exp, EnumXLSExportItems option) { ArrayList <ArrayList<Double >> arrayList = new ArrayList <ArrayList <Double>> (); for (XYTaSeries posxyt: exp.vSequence.cages.flyPositionsList) { switch (option) { case DISTANCE: arrayList.add(posxyt.getDoubleArrayList(EnumArrayListType.distance)); break; case ISALIVE: arrayList.add(posxyt.getDoubleArrayList(EnumArrayListType.isalive)); // TODO add threshold to cleanup data? break; case XYCENTER: default: arrayList.add(posxyt.getDoubleArrayList(EnumArrayListType.xyPosition)); break; } } return arrayList; } public int xlsExportToWorkbook(Experiment exp, XSSFWorkbook workBook, int col0, String charSeries, EnumXLSExportItems xlsExportOption) { ArrayList <ArrayList<Double >> arrayList = getDataFromCages(exp, xlsExportOption); XSSFSheet sheet = workBook.getSheet(xlsExportOption.toString()); if (sheet == null) sheet = workBook.createSheet(xlsExportOption.toString()); Point pt = new Point(col0, 0); if (options.collateSeries) { pt = getStackColumnPosition(exp, pt); } pt = writeGlobalInfos(exp, sheet, pt, options.transpose, xlsExportOption); pt = writeHeader(exp, sheet, pt, xlsExportOption, options.transpose, charSeries); pt = writeData(exp, sheet, pt, xlsExportOption, arrayList, options.transpose, charSeries); return pt.x; } private Point writeGlobalInfos(Experiment exp, XSSFSheet sheet, Point pt, boolean transpose, EnumXLSExportItems option) { int col0 = pt.x; XLSUtils.setValue(sheet, pt, transpose, "expt"); pt.x++; XLSUtils.setValue(sheet, pt, transpose, "name"); File file = new File(exp.vSequence.getFileName(0)); String path = file.getParent(); pt.x++; XLSUtils.setValue(sheet, pt, transpose, path); pt.y++; pt.x=col0; Point pt1 = pt; XLSUtils.setValue(sheet, pt, transpose, "n_cages"); pt1.x++; XLSUtils.setValue(sheet, pt, transpose, exp.vSequence.cages.flyPositionsList.size()); switch (option) { case DISTANCE: break; case ISALIVE: pt1.x++; XLSUtils.setValue(sheet, pt, transpose, "threshold"); pt1.x++; XLSUtils.setValue(sheet, pt, transpose, exp.vSequence.cages.detect.threshold); break; case XYCENTER: default: break; } pt.x=col0; pt.y++; return pt; } private Point writeHeader (Experiment exp, XSSFSheet sheet, Point pt, EnumXLSExportItems xlsExportOption, boolean transpose, String charSeries) { int col0 = pt.x; pt = writeGenericHeader(exp, sheet, xlsExportOption, pt, transpose, charSeries); switch (xlsExportOption) { case DISTANCE: for (XYTaSeries posxyt: exp.vSequence.cages.flyPositionsList) { String name0 = posxyt.getName(); XLSUtils.setValue(sheet, pt, transpose, name0); pt.x++; } break; case ISALIVE: for (XYTaSeries posxyt: exp.vSequence.cages.flyPositionsList) { String name0 = posxyt.getName(); XLSUtils.setValue(sheet, pt, transpose, name0); pt.x++; XLSUtils.setValue(sheet, pt, transpose, name0); pt.x++; } break; case XYCENTER: default: for (XYTaSeries posxyt: exp.vSequence.cages.flyPositionsList) { String name0 = posxyt.getName(); XLSUtils.setValue(sheet, pt, transpose, name0+".x"); pt.x++; XLSUtils.setValue(sheet, pt, transpose, name0+".y"); pt.x++; } break; } pt.x = col0; pt.y++; return pt; } private Point writeData (Experiment exp, XSSFSheet sheet, Point pt, EnumXLSExportItems option, ArrayList <ArrayList<Double >> dataArrayList, boolean transpose, String charSeries) { int col0 = pt.x; int row0 = pt.y; if (charSeries == null) charSeries = "t"; int startFrame = (int) exp.vSequence.analysisStart; int endFrame = (int) exp.vSequence.analysisEnd; int step = expAll.step; FileTime imageTime = exp.vSequence.getImageModifiedTime(startFrame); long imageTimeMinutes = imageTime.toMillis()/ 60000; if (options.absoluteTime && (col0 ==0)) { imageTimeMinutes = expAll.fileTimeImageLastMinutes; long diff = getnearest(imageTimeMinutes-expAll.fileTimeImageFirstMinutes, step)/ step; imageTimeMinutes = expAll.fileTimeImageFirstMinutes; pt.x = col0; for (int i = 0; i<= diff; i++) { long diff2 = getnearest(imageTimeMinutes-expAll.fileTimeImageFirstMinutes, step); pt.y = (int) (diff2/step + row0); XLSUtils.setValue(sheet, pt, transpose, "t"+diff2); imageTimeMinutes += step; } } // if (dataArrayList.size() == 0) { // pt.x = columnOfNextSeries(exp, option, col0); // return pt; // } for (int currentFrame=startFrame; currentFrame< endFrame; currentFrame+= step * options.pivotBinStep) { pt.x = col0; long diff0 = (currentFrame - startFrame)/step; imageTime = exp.vSequence.getImageModifiedTime(currentFrame); imageTimeMinutes = imageTime.toMillis()/ 60000; if (options.absoluteTime) { long diff = getnearest(imageTimeMinutes-expAll.fileTimeImageFirstMinutes, step); pt.y = (int) (diff/step + row0); diff0 = diff; //getnearest(imageTimeMinutes-exp.fileTimeImageFirst.toMillis()/60000, step); } else { pt.y = (int) diff0 + row0; } //XLSUtils.setValue(sheet, pt, transpose, "t"+diff0); pt.x++; XLSUtils.setValue(sheet, pt, transpose, imageTimeMinutes); pt.x++; if (exp.vSequence.isFileStack()) { XLSUtils.setValue(sheet, pt, transpose, getShortenedName(exp.vSequence, currentFrame) ); } pt.x++; int t = (currentFrame - startFrame)/step; switch (option) { case DISTANCE: for (int idataArray=0; idataArray < dataArrayList.size(); idataArray++ ) { XLSUtils.setValue(sheet, pt, transpose, dataArrayList.get(idataArray).get(t)); pt.x++; XLSUtils.setValue(sheet, pt, transpose, dataArrayList.get(idataArray).get(t)); pt.x++; } break; case ISALIVE: for (int idataArray=0; idataArray < dataArrayList.size(); idataArray++ ) { Double value = dataArrayList.get(idataArray).get(t); if (value > 0) { XLSUtils.setValue(sheet, pt, transpose, value ); pt.x++; XLSUtils.setValue(sheet, pt, transpose, value); pt.x++; } else pt.x += 2; } break; case XYCENTER: default: for (int iDataArray=0; iDataArray < dataArrayList.size(); iDataArray++ ) { int iarray = t*2; XLSUtils.setValue(sheet, pt, transpose, dataArrayList.get(iDataArray).get(iarray)); pt.x++; XLSUtils.setValue(sheet, pt, transpose, dataArrayList.get(iDataArray).get(iarray+1)); pt.x++; } break; } } pt.x = columnOfNextSeries(exp, option, col0); return pt; } private int columnOfNextSeries(Experiment exp, EnumXLSExportItems option, int currentcolumn) { int n = 2; int value = currentcolumn + exp.vSequence.cages.cageLimitROIList.size() * n + 3; return value; } }
package scolarite; public class NbEtudiantsException extends Exception{ private int nbErr; public NbEtudiantsException(int nbErr) { this.nbErr = nbErr; } public String toString() { return "Nb etudiants erroné : "+nbErr; } }
import java.util.Scanner; public class unique { public static void main(String[] args) { int n;int s=0; Scanner sc=new Scanner(System.in); n=sc.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); } for(int j=0;j<n;j++) { if(frequency(arr,arr[j])==false) { s=s+arr[j]; } } System.out.print(s); } public static boolean frequency(int a[],int k) { int c=0; for(int i=0;i<a.length;i++) { if(a[i]==k) { c++; } } if(c>1) { return true; } else { return false; } } }
package io.snice.buffer; import org.hamcrest.MatcherAssert; import org.junit.Test; import java.util.function.Consumer; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; public abstract class AbstractReadWritableBufferTest extends AbstractReadableBufferTest { abstract ReadWriteBuffer createWritableBuffer(final int capacity); protected ReadWriteBuffer createWritableBuffer(final int capacity, final int offset, final int length) { return (ReadWriteBuffer)createBuffer(new byte[capacity], offset, length); } @Test public void testWriteFiveOctetLong() throws Exception { final WritableBuffer buffer = createWritableBuffer(100); buffer.writeFiveOctets(123); buffer.write(777); buffer.write("hello"); final var b = buffer.build(); assertThat(b.capacity(), is(5 + 4 + "hello".getBytes("UTF-8").length)); assertThat(b.getLongFromFiveOctets(0), is(123L)); assertThat(b.getInt(0 + 5), is(777)); } @Test public void testCapacity() { assertThat(createWritableBuffer(10).capacity(), is(10)); assertThat(createWritableBuffer(10, 2, 4).capacity(), is(4)); } @Test public void testIsWritable() { final ReadWriteBuffer buffer = createWritableBuffer(10); assertThat(buffer.hasWritableBytes(), is(true)); assertThat(buffer.hasReadableBytes(), is(false)); assertThat(buffer.getWritableBytes(), is(10)); } @Test public void testWriteIntAsString() { final ReadWriteBuffer buffer = createWritableBuffer(100); buffer.writeAsString(0); buffer.write((byte) ' '); buffer.writeAsString(10); buffer.write((byte) ' '); buffer.writeAsString(100); buffer.write((byte) ' '); buffer.writeAsString(9712); assertThat(buffer.toString(), is("0 10 100 9712")); } @Test public void testWriteLongAsString() { final ReadWriteBuffer buffer = createWritableBuffer(100); buffer.writeAsString(0L); buffer.write((byte) ' '); buffer.writeAsString(10L); buffer.write((byte) ' '); buffer.writeAsString(100L); buffer.write((byte) ' '); buffer.writeAsString(9712L); assertThat(buffer.toString(), is("0 10 100 9712")); } /** * If you of a new {@link WritableBuffer} with a certain capacity it is at that point * considered "empty" and as such, you should not be able to actually read until you have * written to the certain areas. */ @Test public void testReadShouldNotWork() { final ReadWriteBuffer buffer = createWritableBuffer(100); testLotsOfWritesAndReads(buffer); // now, if we reset the writer index we should be able to do it // all over again... buffer.setWriterIndex(0); testLotsOfWritesAndReads(buffer); } private static void testLotsOfWritesAndReads(final ReadWriteBuffer buffer) { assertThat(buffer.hasReadableBytes(), is(false)); assertThat(buffer.isEmpty(), is(true)); ensureNoReadWorks(buffer); // let's write one byte and read it back... buffer.write((byte)'a'); assertThat(buffer.readByte(), is((byte)'a')); // but now, after reading that byte, we should no longer be able to // read again... ensureNoReadWorks(buffer); // write some more... buffer.write((byte)'a'); buffer.write((byte)'b'); buffer.write((byte)'c'); buffer.write((byte)'d'); assertThat(buffer.readBytes(4).toString(), is("abcd")); ensureNoReadWorks(buffer); buffer.writeAsString(888); buffer.write(999); assertThat(buffer.readBytes(3).toString(), is("888")); assertThat(buffer.readInt(), is(999)); ensureNoReadWorks(buffer); } private static void ensureNoReadWorks(final ReadWriteBuffer buffer) { ensureDoesntWork(buffer, b -> b.readByte()); ensureDoesntWork(buffer, b -> b.readUnsignedByte()); ensureDoesntWork(buffer, b -> b.readInt()); ensureDoesntWork(buffer, b -> b.readUnsignedInt()); ensureDoesntWork(buffer, b -> b.readBytes(1)); ensureDoesntWork(buffer, b -> b.readBytes(10)); } @Test public void testWriteThenRead() { final ReadWriteBuffer buffer = createWritableBuffer(100); buffer.write(512); buffer.write(123); assertThat(buffer.hasReadableBytes(), is(true)); assertThat(buffer.getReadableBytes(), is(2 * 4)); assertThat(buffer.readInt(), is(512)); assertThat(buffer.readInt(), is(123)); assertThat(buffer.hasReadableBytes(), is(false)); } @Test public void testSetBits() { final ReadWriteBuffer buffer = (ReadWriteBuffer)createBuffer(new byte[100]); for (int i = 0; i < 10; ++i) { ensureBits(buffer, i); } // now that we have actually turned on all bits in the array // we should be able to read out assertThat(buffer.readInt(), is(-1)); // because all bits are set so signed int should be -2 assertThat(buffer.readInt(), is(-1)); } @Test public void testSetBits2() { // 97 binary is 1100001, let's set those bits // and sure we can read out 97 final ReadWriteBuffer buffer = (ReadWriteBuffer)createBuffer(new byte[4]); buffer.setBit0(3, true); buffer.setBit5(3, true); buffer.setBit6(3, true); int value = buffer.getInt(0); assertThat(value, is(97)); // then set the same pattern in the first byte buffer.setBit0(0, true); buffer.setBit5(0, true); buffer.setBit6(0, true); // when then if we just read that byte, it should also // be integer 97 when converted value = buffer.getByte(0); assertThat(value, is(97)); // then let's make an integer our of only three bytes value = buffer.getIntFromThreeOctets(1); assertThat(value, is(97)); // let's flip those bits in the first byte back // and then read byte after byte and only the // last one should be 97 buffer.setBit0(0, false); buffer.setBit5(0, false); buffer.setBit6(0, false); assertThat(buffer.readByte(), is((byte)0)); assertThat(buffer.readByte(), is((byte)0)); assertThat(buffer.readByte(), is((byte)0)); assertThat(buffer.readByte(), is((byte)97)); // finally check so the bit pattern are "checkable" assertThat(buffer.getBit0(3), is(true)); assertThat(buffer.getBit1(3), is(false)); assertThat(buffer.getBit2(3), is(false)); assertThat(buffer.getBit3(3), is(false)); assertThat(buffer.getBit4(3), is(false)); assertThat(buffer.getBit5(3), is(true)); assertThat(buffer.getBit6(3), is(true)); assertThat(buffer.getBit7(3), is(false)); } private static void ensureBits(final ReadWriteBuffer buffer, final int index) { ensureAllBits(buffer, index, false); // just making sure that the short-hand versions // is actually working. buffer.setBit0(index, true); buffer.setBit1(index, true); buffer.setBit2(index, true); buffer.setBit3(index, true); buffer.setBit4(index, true); buffer.setBit5(index, true); buffer.setBit6(index, true); buffer.setBit7(index, true); assertThat(buffer.getBit0(index), is(true)); assertThat(buffer.getBit1(index), is(true)); assertThat(buffer.getBit2(index), is(true)); assertThat(buffer.getBit3(index), is(true)); assertThat(buffer.getBit4(index), is(true)); assertThat(buffer.getBit5(index), is(true)); assertThat(buffer.getBit6(index), is(true)); assertThat(buffer.getBit7(index), is(true)); // which should really be the same as above but who knows, // copy-paste errors are easy to make ensureAllBits(buffer, index, true); } private static void ensureAllBits(final Buffer buffer, final int index, final boolean on) { for (int bit = 0; bit < 8; ++bit) { assertThat(buffer.getBit(index, bit), is(on)); } } @Test public void testZeroOut() { ensureZeroOut('a', 150, 50, 50); ensureZeroOut('b', 50, 10, 10); ensureZeroOut('c', 10, 0, 1); // boundary testing ensureZeroOut('c', 10, 9, 1); // boundary testing ensureZeroOut('c', 10, 9, 0); // doesn't make sense but should work } private void ensureZeroOut(final char b, final int byteArrayLength, final int offset, final int length) { final ReadWriteBuffer buffer = (ReadWriteBuffer)createBuffer(new byte[byteArrayLength], offset, length); buffer.zeroOut((byte)b); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; ++i) { sb.append(b); } final String expected = sb.toString(); final String actual = buffer.toString(); assertThat(actual, is(expected)); for (int i = 0; i < length; ++i) { assertThat(buffer.getByte(i), is((byte)b)); } } @Test public void testBuild() throws Exception { final int capacity = 100; final ReadWriteBuffer buffer = createWritableBuffer(capacity); buffer.write("hello world"); // build it and make sure that the new buffer is indeed 100% immutble // and that our old writable buffer cannot affect it in anyway... final Buffer immutable = buffer.build(); assertThat(immutable.toString(), is("hello world")); assertThat(immutable.toReadableBuffer().readUntilWhiteSpace().toString(), is(("hello"))); assertThat(immutable.slice(immutable.indexOfWhiteSpace()).toString(), is("hello")); assertThat(immutable.slice(immutable.indexOfWhiteSpace() + 1, immutable.capacity()).toString(), is("world")); ensureDoesntWork(buffer, b -> b.setByte(1, (byte)'a')); ensureDoesntWork(buffer, b -> b.setByte(0, (byte)'a')); ensureDoesntWork(buffer, b -> b.write("asdf")); ensureDoesntWork(buffer, b -> b.write(5)); ensureDoesntWork(buffer, b -> b.write(5L)); ensureDoesntWork(buffer, b -> b.readByte()); // you can't mess with the reader & writer index either // going beyond the capacity (hence the +1 below) just to test // that boundary as well for (int i = 0; i < capacity + 1; ++i) { final int index = i; ensureDoesntWork(buffer, b -> b.setReaderIndex(index)); ensureDoesntWork(buffer, b -> b.setWriterIndex(index)); } } @Test public void testThreeOctetInt() { ensureWriteThreeOctetInt(0); ensureWriteThreeOctetInt(7); ensureWriteThreeOctetInt(10); // if we have an int where any of the bits in the top byte is set, those will // effectively cutoff, leaving the lower 24 bits only. So, if we write the // max value, then when we should only have 24 "on" bits left. ensureWriteThreeOctetInt(Integer.MAX_VALUE, 0b111111111111111111111111); ensureNegativeNumbersThreeOctetIntsNotPossible(-1); //boundary ensureNegativeNumbersThreeOctetIntsNotPossible(-2); ensureNegativeNumbersThreeOctetIntsNotPossible(Integer.MIN_VALUE); //boundary } @Test public void testSetUnsignedInt() { final ReadWriteBuffer buffer = (ReadWriteBuffer)createBuffer(new byte[100]); buffer.setUnsignedInt(0, 100); assertThat(buffer.getUnsignedInt(0), is(100L)); assertThat(buffer.readUnsignedInt(), is(100L)); } private void ensureNegativeNumbersThreeOctetIntsNotPossible(final int value) { try { final ReadWriteBuffer buffer = createWritableBuffer(100); buffer.writeThreeOctets(value); fail("Expected to fail with an IllegalArgumentException"); } catch (final IllegalArgumentException e) { // expected } } private void ensureWriteThreeOctetInt(final int value, final int expected) { final ReadWriteBuffer buffer = createWritableBuffer(3); buffer.writeThreeOctets(value); assertThat(buffer.getIntFromThreeOctets(0), is(expected)); assertThat(buffer.toReadableBuffer().readIntFromThreeOctets(), is(expected)); } private void ensureWriteThreeOctetInt(final int value) { ensureWriteThreeOctetInt(value, value); } @Test public void testSetInt() { final ReadWriteBuffer buffer = (ReadWriteBuffer)createBuffer(new byte[100]); buffer.setInt(0, 100); assertThat(buffer.getInt(0), is(100)); assertThat(buffer.readInt(), is(100)); buffer.setUnsignedInt(12, 1234567); assertThat(buffer.getInt(12), is(1234567)); } @Test public void writeNumbers() { final ReadWriteBuffer buffer = createWritableBuffer(100); buffer.write(567); buffer.write(789); buffer.write(Integer.MAX_VALUE); buffer.write(-1); assertThat(buffer.readInt(), is(567)); assertThat(buffer.readInt(), is(789)); assertThat(buffer.readInt(), is(Integer.MAX_VALUE)); assertThat(buffer.readInt(), is(-1)); buffer.write(10L); assertThat(buffer.readLong(), is(10L)); buffer.write(Long.MAX_VALUE); assertThat(buffer.readLong(), is(Long.MAX_VALUE)); // -7 because you know, why not... buffer.write(Long.MAX_VALUE - 7); assertThat(buffer.readLong(), is(Long.MAX_VALUE - 7)); buffer.write(9999999999L); assertThat(buffer.readLong(), is(9999999999L)); buffer.write(99999999999L); assertThat(buffer.readLong(), is(99999999999L)); buffer.write(-1L); assertThat(buffer.readLong(), is(-1L)); } /** * Helper method to ensure that if the operation is performed, we blow up on an {@link IllegalArgumentException} * */ private static void ensureDoesntWork(final ReadWriteBuffer b, final Consumer<ReadWriteBuffer> operation) { try { operation.accept(b); fail("Expected to blow up on a " + IndexOutOfBoundsException.class.getName()); } catch (final IndexOutOfBoundsException e) { // expected } } }
package ru.avokin.swing.codeviewer.model; import ru.avokin.highlighting.HighlightedCodeBlock; import ru.avokin.utils.StringUtils; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; import java.util.Collections; import java.util.List; /** * User: Andrey Vokin * Date: 29.09.2010 */ public class CodeViewerModel extends PlainDocument { private final List<LinePosition> linePositionList; private List<LinePosition> lineNumbersLinePositionList; private final LineNumberPosition lineNumberPosition; private final List<HighlightedCodeBlock> highlightedCodeBlockList; private int theLongestLineLength; public CodeViewerModel(List<HighlightedCodeBlock> highlightedCodeBlockList, String text, LineNumberPosition lineNumberPosition) { try { getContent().insertString(0, text); } catch (BadLocationException ignored) { } this.lineNumberPosition = lineNumberPosition; this.highlightedCodeBlockList = Collections.unmodifiableList(highlightedCodeBlockList); linePositionList = StringUtils.prepareLinePositions(text); for (LinePosition lp : linePositionList) { int length = lp.getRight() - lp.getLeft(); if (length > theLongestLineLength) { theLongestLineLength = length; } } } public LineNumberPosition getLineNumberPosition() { return lineNumberPosition; } public int getTheLongestLineLength() { return theLongestLineLength; } public int getLineCount() { return linePositionList.size(); } public List<HighlightedCodeBlock> getHighlightedCodeBlockList() { return highlightedCodeBlockList; } public List<LinePosition> getLinePositionList() { return linePositionList; } public List<LinePosition> getLineNumbersLinePositionList() { return lineNumbersLinePositionList; } public void setLineNumbersLinePositionList(List<LinePosition> lineNumbersLinePositionList) { this.lineNumbersLinePositionList = lineNumbersLinePositionList; } public String getText() { String result = null; try { result = getText(0, getLength()); } catch (BadLocationException ignored) { } return result; } }
package com.example.teeshirt.add; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends ActionBarActivity { private EditText pass; private Button btn, btn2; private CheckBox check1, check2, check3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); addListener(); btn2Click(); checkBoxListener(); } /* public void onButtonClick(View v){ EditText e1 = (EditText)findViewById(R.id.editText); EditText e2 = (EditText)findViewById(R.id.editText2); TextView t1 = (TextView)findViewById(R.id.textView); int num1 = Integer.parseInt(e1.getText().toString()); int num2 = Integer.parseInt(e2.getText().toString()); int sum = num1 + num2; t1.setText(Integer.toString(sum)); }*/ public void addListener(){ pass = (EditText)findViewById(R.id.pass); btn = (Button)findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, pass.getText(),Toast.LENGTH_SHORT).show(); } }); } public void btn2Click(){ check1 = (CheckBox)findViewById(R.id.checkBox); check2 = (CheckBox)findViewById(R.id.checkBox2); check3 = (CheckBox)findViewById(R.id.checkBox3); btn2 = (Button)findViewById(R.id.btn2); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { StringBuffer result = new StringBuffer(); result.append("Whiskey : ").append(check1.isChecked()); result.append("\nBrandy : ").append(check2.isChecked()); result.append("\nWine : ").append(check3.isChecked()); Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show(); } }); } public void checkBoxListener(){ check1 = (CheckBox)findViewById(R.id.checkBox); check1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (((CheckBox)v).isChecked()){ Toast.makeText(MainActivity.this,"You have selected Whiskey", Toast.LENGTH_LONG).show(); } } }); } }
package com.shangdao.phoenix.entity.pictureturn; import com.fasterxml.jackson.annotation.JsonIgnore; import com.shangdao.phoenix.entity.entityManager.EntityManager; import com.shangdao.phoenix.entity.interfaces.ILogEntity; import com.shangdao.phoenix.entity.state.State; import com.shangdao.phoenix.entity.user.User; import com.shangdao.phoenix.service.FileUploadService.OssImage; import javax.persistence.*; import java.util.Date; import java.util.List; import java.util.Set; @Entity @Table(name = "picture_turns") public class PictureTurns implements ILogEntity<PictureTurnsLog, PictureTurnsFile, PictureTurnsNotice> { @Transient public static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private long id; @ManyToOne @JoinColumn(name = "entity_manager_id") private EntityManager entityManager; @Column(name = "name" ,unique = true) private String name; @Column(name = "deleted_at") @JsonIgnore private Date deletedAt; @ManyToOne @JoinColumn(name = "state_id") private State state; @Transient private List<OssImage> uploadFiles; @Transient private String note; @OneToMany(mappedBy = "entity") @JsonIgnore private Set<PictureTurnsLog> logs; @OneToMany(mappedBy = "entity") @JsonIgnore private Set<PictureTurnsFile> files; @OneToMany(mappedBy = "entity") @JsonIgnore private Set<PictureTurnsNotice> notices; @Column(name = "created_at") @JsonIgnore private Date createdAt; @OneToOne @JoinColumn(name = "created_by") @JsonIgnore private User createdBy; @Column(name = "last_modified_at") private Date lastModifiedAt; @Column(name = "sort") private Integer sort; @Enumerated(EnumType.STRING) @Column(name = "turn_type") private PictureTurnType turnType; @Column(name = "click_times") private Long clickTimes; @Enumerated(EnumType.STRING) @Column(name = "turn_status") private PictureTurnStatus turnStatus; @Column(name = "jump_url") private String jumpUrl; public String getJumpUrl() { return jumpUrl; } public void setJumpUrl(String jumpUrl) { this.jumpUrl = jumpUrl; } public PictureTurnStatus getTurnStatus() { return turnStatus; } public void setTurnStatus(PictureTurnStatus turnStatus) { this.turnStatus = turnStatus; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public PictureTurnType getTurnType() { return turnType; } public void setTurnType(PictureTurnType turnType) { this.turnType = turnType; } public Long getClickTimes() { return clickTimes; } public void setClickTimes(Long clickTimes) { this.clickTimes = clickTimes; } @Override public long getId() { return id; } @Override public void setId(long id) { this.id = id; } @Override public EntityManager getEntityManager() { return entityManager; } @Override public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public Date getDeletedAt() { return deletedAt; } @Override public void setDeletedAt(Date deletedAt) { this.deletedAt = deletedAt; } @Override public State getState() { return state; } @Override public void setState(State state) { this.state = state; } @Override public List<OssImage> getUploadFiles() { return uploadFiles; } public void setUploadFiles(List<OssImage> uploadFiles) { this.uploadFiles = uploadFiles; } @Override public String getNote() { return note; } public void setNote(String note) { this.note = note; } @Override public Set<PictureTurnsLog> getLogs() { return logs; } public void setLogs(Set<PictureTurnsLog> logs) { this.logs = logs; } @Override public Set<PictureTurnsFile> getFiles() { return files; } public void setFiles(Set<PictureTurnsFile> files) { this.files = files; } @Override public Set<PictureTurnsNotice> getNotices() { return notices; } public void setNotices(Set<PictureTurnsNotice> notices) { this.notices = notices; } @Override public Date getCreatedAt() { return createdAt; } @Override public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } @Override public User getCreatedBy() { return createdBy; } @Override public void setCreatedBy(User createdBy) { this.createdBy = createdBy; } @Override public Date getLastModifiedAt() { return lastModifiedAt; } public void setLastModifiedAt(Date lastModifiedAt) { this.lastModifiedAt = lastModifiedAt; } public enum PictureTurnType{ WEB, APP; } public enum PictureTurnStatus{ SHELVES, //上架中 THESHELVES //下架中 } }
package Datos; import java.util.List; import Negocio.Socio; public interface SociosManager { public List<Socio> getAllSocios(); public void addSocio(Socio newSocio); public void editSocio(int idSocio, Socio modifiedSocio) throws Exception; public void deleteSocio(int idSocio); public List<String> getAllSociosEmails(); }
package com.niksoftware.snapseed.core.filterparameters; import android.content.Context; public class CropAndRotateFilterParameter extends FilterParameter { private static final int[] FILTER_PARAMETERS = new int[]{42, 41, 40, 43, 44, 45, 46}; public int getFilterType() { return 20; } protected int[] getAutoParams() { return FILTER_PARAMETERS; } public int getDefaultValue(int param) { return param == 42 ? 1 : 0; } public int getMaxValue(int param) { return param == 42 ? 9 : Integer.MAX_VALUE; } public int getMinValue(int param) { return param == 42 ? 0 : Integer.MIN_VALUE; } public int getDefaultParameter() { return 42; } public String getParameterDescription(Context context, int parameterType, Object parameterValue) { if (parameterType != 42) { return super.getParameterDescription(context, parameterType, parameterValue); } if (parameterValue == null) { return "*UNKNOWN*"; } switch (((Integer) parameterValue).intValue()) { case 0: return context.getString(R.string.crop_free); case 1: return context.getString(R.string.crop_original); case 2: return context.getString(R.string.crop_1x1); case 3: return context.getString(R.string.crop_din); case 4: return context.getString(R.string.crop_3x2); case 5: return context.getString(R.string.crop_4x3); case 6: return context.getString(R.string.crop_5x4); case 7: return context.getString(R.string.crop_7x5); case 8: return context.getString(R.string.crop_16x9); default: return "*UNKNOWN*"; } } }
package com.zym.blog.model.example; import java.util.ArrayList; import java.util.List; public class RightExample { protected String pk_name = "right_id"; protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public RightExample() { oredCriteria = new ArrayList<Criteria>(); } public void setPk_name(String pk_name) { this.pk_name = pk_name; } public String getPk_name() { return pk_name; } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andRightIdIsNull() { addCriterion("right_id is null"); return (Criteria) this; } public Criteria andRightIdIsNotNull() { addCriterion("right_id is not null"); return (Criteria) this; } public Criteria andRightIdEqualTo(Integer value) { addCriterion("right_id =", value, "rightId"); return (Criteria) this; } public Criteria andRightIdNotEqualTo(Integer value) { addCriterion("right_id <>", value, "rightId"); return (Criteria) this; } public Criteria andRightIdGreaterThan(Integer value) { addCriterion("right_id >", value, "rightId"); return (Criteria) this; } public Criteria andRightIdGreaterThanOrEqualTo(Integer value) { addCriterion("right_id >=", value, "rightId"); return (Criteria) this; } public Criteria andRightIdLessThan(Integer value) { addCriterion("right_id <", value, "rightId"); return (Criteria) this; } public Criteria andRightIdLessThanOrEqualTo(Integer value) { addCriterion("right_id <=", value, "rightId"); return (Criteria) this; } public Criteria andRightIdIn(List<Integer> values) { addCriterion("right_id in", values, "rightId"); return (Criteria) this; } public Criteria andRightIdNotIn(List<Integer> values) { addCriterion("right_id not in", values, "rightId"); return (Criteria) this; } public Criteria andRightIdBetween(Integer value1, Integer value2) { addCriterion("right_id between", value1, value2, "rightId"); return (Criteria) this; } public Criteria andRightIdNotBetween(Integer value1, Integer value2) { addCriterion("right_id not between", value1, value2, "rightId"); return (Criteria) this; } public Criteria andRightTypeIsNull() { addCriterion("right_type is null"); return (Criteria) this; } public Criteria andRightTypeIsNotNull() { addCriterion("right_type is not null"); return (Criteria) this; } public Criteria andRightTypeEqualTo(Integer value) { addCriterion("right_type =", value, "rightType"); return (Criteria) this; } public Criteria andRightTypeNotEqualTo(Integer value) { addCriterion("right_type <>", value, "rightType"); return (Criteria) this; } public Criteria andRightTypeGreaterThan(Integer value) { addCriterion("right_type >", value, "rightType"); return (Criteria) this; } public Criteria andRightTypeGreaterThanOrEqualTo(Integer value) { addCriterion("right_type >=", value, "rightType"); return (Criteria) this; } public Criteria andRightTypeLessThan(Integer value) { addCriterion("right_type <", value, "rightType"); return (Criteria) this; } public Criteria andRightTypeLessThanOrEqualTo(Integer value) { addCriterion("right_type <=", value, "rightType"); return (Criteria) this; } public Criteria andRightTypeIn(List<Integer> values) { addCriterion("right_type in", values, "rightType"); return (Criteria) this; } public Criteria andRightTypeNotIn(List<Integer> values) { addCriterion("right_type not in", values, "rightType"); return (Criteria) this; } public Criteria andRightTypeBetween(Integer value1, Integer value2) { addCriterion("right_type between", value1, value2, "rightType"); return (Criteria) this; } public Criteria andRightTypeNotBetween(Integer value1, Integer value2) { addCriterion("right_type not between", value1, value2, "rightType"); return (Criteria) this; } public Criteria andRightTypeDescIsNull() { addCriterion("right_type_desc is null"); return (Criteria) this; } public Criteria andRightTypeDescIsNotNull() { addCriterion("right_type_desc is not null"); return (Criteria) this; } public Criteria andRightTypeDescEqualTo(String value) { addCriterion("right_type_desc =", value, "rightTypeDesc"); return (Criteria) this; } public Criteria andRightTypeDescNotEqualTo(String value) { addCriterion("right_type_desc <>", value, "rightTypeDesc"); return (Criteria) this; } public Criteria andRightTypeDescGreaterThan(String value) { addCriterion("right_type_desc >", value, "rightTypeDesc"); return (Criteria) this; } public Criteria andRightTypeDescGreaterThanOrEqualTo(String value) { addCriterion("right_type_desc >=", value, "rightTypeDesc"); return (Criteria) this; } public Criteria andRightTypeDescLessThan(String value) { addCriterion("right_type_desc <", value, "rightTypeDesc"); return (Criteria) this; } public Criteria andRightTypeDescLessThanOrEqualTo(String value) { addCriterion("right_type_desc <=", value, "rightTypeDesc"); return (Criteria) this; } public Criteria andRightTypeDescLike(String value) { addCriterion("right_type_desc like", value, "rightTypeDesc"); return (Criteria) this; } public Criteria andRightTypeDescNotLike(String value) { addCriterion("right_type_desc not like", value, "rightTypeDesc"); return (Criteria) this; } public Criteria andRightTypeDescIn(List<String> values) { addCriterion("right_type_desc in", values, "rightTypeDesc"); return (Criteria) this; } public Criteria andRightTypeDescNotIn(List<String> values) { addCriterion("right_type_desc not in", values, "rightTypeDesc"); return (Criteria) this; } public Criteria andRightTypeDescBetween(String value1, String value2) { addCriterion("right_type_desc between", value1, value2, "rightTypeDesc"); return (Criteria) this; } public Criteria andRightTypeDescNotBetween(String value1, String value2) { addCriterion("right_type_desc not between", value1, value2, "rightTypeDesc"); return (Criteria) this; } public Criteria andRightNameIsNull() { addCriterion("right_name is null"); return (Criteria) this; } public Criteria andRightNameIsNotNull() { addCriterion("right_name is not null"); return (Criteria) this; } public Criteria andRightNameEqualTo(String value) { addCriterion("right_name =", value, "rightName"); return (Criteria) this; } public Criteria andRightNameNotEqualTo(String value) { addCriterion("right_name <>", value, "rightName"); return (Criteria) this; } public Criteria andRightNameGreaterThan(String value) { addCriterion("right_name >", value, "rightName"); return (Criteria) this; } public Criteria andRightNameGreaterThanOrEqualTo(String value) { addCriterion("right_name >=", value, "rightName"); return (Criteria) this; } public Criteria andRightNameLessThan(String value) { addCriterion("right_name <", value, "rightName"); return (Criteria) this; } public Criteria andRightNameLessThanOrEqualTo(String value) { addCriterion("right_name <=", value, "rightName"); return (Criteria) this; } public Criteria andRightNameLike(String value) { addCriterion("right_name like", value, "rightName"); return (Criteria) this; } public Criteria andRightNameNotLike(String value) { addCriterion("right_name not like", value, "rightName"); return (Criteria) this; } public Criteria andRightNameIn(List<String> values) { addCriterion("right_name in", values, "rightName"); return (Criteria) this; } public Criteria andRightNameNotIn(List<String> values) { addCriterion("right_name not in", values, "rightName"); return (Criteria) this; } public Criteria andRightNameBetween(String value1, String value2) { addCriterion("right_name between", value1, value2, "rightName"); return (Criteria) this; } public Criteria andRightNameNotBetween(String value1, String value2) { addCriterion("right_name not between", value1, value2, "rightName"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.training.utils; import java.sql.SQLException; import java.util.List; import com.training.entity.Donor; public interface DAO { public int add(Donor donor) throws SQLException; public List<Donor> getAllDonors() throws SQLException; public List<Donor> searchDonorByLocationAndGroup(String location,String group) throws SQLException; public List<String> searchDonorByLocation(String location) throws SQLException; public int updateDonor(String propertyName,String newVal,long id) throws SQLException; public List<String> getAllLocations() throws SQLException; }
public class StringS{ public static void main(String[] args){ String s = args[0]; int count = 0; while(!StdIn.isEmpty()){ String read = StdIn.readString(); for(int i = 0; i < read.length(); i++){ if(read.equals(s)){ count++; } } } System.out.println(count/3); } }
package com.uchain.networkmanager.message; public enum MessageType { Version(0), BlockProduced(1), GetBlocks(2), Block(3), Blocks(4), Inventory(5),Getdata(6), Transactions(7), RPCCommand(8); private int value; private MessageType(int value) { this.value = value; } public static int getMessageTypeByType(MessageType messageType) { for (MessageType c : MessageType.values()) { if (c.value == messageType.value) { return c.value; } } return 100; } public static String getMessageTypeStringByType(MessageType messageType) { for (MessageType c : MessageType.values()) { if (c.value == messageType.value) { return c.toString(); } } return ""; } public static MessageType getMessageTypeByValue(byte value) { for (MessageType c : MessageType.values()) { if ((byte)c.value == value) { return c; } } return null; } }
package hackerrankq; public class StringMerger { public static String stringMerger(String s1, String s2) { StringBuilder mergedString = new StringBuilder(); int len1 = s1.length(); int len2 = s2.length(); for (int i = 0; i < len1 || i < len2; i++) { if (i < len1) { mergedString.append(s1.charAt(i)); } if (i < len2) { mergedString.append(s2.charAt(i)); } } return mergedString.toString(); } public static void main(String[] args) { String tester1 = "123"; String tester2 = "789"; System.out.println(stringMerger(tester1, tester2)); } }
package seedu.project.storage; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static seedu.project.testutil.TypicalTasks.FEEDBACK; import static seedu.project.testutil.TypicalTasks.LECTURE; import static seedu.project.testutil.TypicalTasks.TUTORIAL; import static seedu.project.testutil.TypicalTasks.getTypicalProject; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import seedu.project.commons.exceptions.DataConversionException; import seedu.project.model.project.Project; import seedu.project.model.project.ReadOnlyProject; public class JsonProjectStorageTest { private static final Path TEST_DATA_FOLDER = Paths.get("src", "test", "data", "JsonProjectStorageTest"); @Rule public ExpectedException thrown = ExpectedException.none(); @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Test public void readProject_nullFilePath_throwsNullPointerException() throws Exception { thrown.expect(NullPointerException.class); readProject(null); } private java.util.Optional<ReadOnlyProject> readProject(String filePath) throws Exception { return new JsonProjectStorage(Paths.get(filePath)).readProject(addToTestDataPathIfNotNull(filePath)); } private Path addToTestDataPathIfNotNull(String prefsFileInTestDataFolder) { return prefsFileInTestDataFolder != null ? TEST_DATA_FOLDER.resolve(prefsFileInTestDataFolder) : null; } @Test public void read_missingFile_emptyResult() throws Exception { assertFalse(readProject("NonExistentFile.json").isPresent()); } @Test public void read_notJsonFormat_exceptionThrown() throws Exception { thrown.expect(DataConversionException.class); readProject("notJsonFormatProject.json"); // IMPORTANT: Any code below an exception-throwing line (like the one above) // will be ignored. // That means you should not have more than one exception test in one method } @Test public void readProject_invalidTaskProject_throwDataConversionException() throws Exception { thrown.expect(DataConversionException.class); readProject("invalidTask.json"); } @Test public void readProject_invalidAndValidTaskProject_throwDataConversionException() throws Exception { thrown.expect(DataConversionException.class); readProject("invalidAndValidTask.json"); } @Test public void readAndSaveProject_allInOrder_success() throws Exception { Path filePath = testFolder.getRoot().toPath().resolve("TempProject.json"); Project original = getTypicalProject(); JsonProjectStorage jsonProjectStorage = new JsonProjectStorage(filePath); // Save in new file and read back jsonProjectStorage.saveProject(original, filePath); ReadOnlyProject readBack = jsonProjectStorage.readProject(filePath).get(); assertEquals(original.getTaskList(), new Project(readBack).getTaskList()); // Modify data, overwrite exiting file, and read back original.addTask(LECTURE); original.removeTask(FEEDBACK); jsonProjectStorage.saveProject(original, filePath); readBack = jsonProjectStorage.readProject(filePath).get(); assertEquals(original.getTaskList(), new Project(readBack).getTaskList()); // Save and read without specifying file path original.addTask(TUTORIAL); jsonProjectStorage.saveProject(original); // file path not specified readBack = jsonProjectStorage.readProject().get(); // file path not specified assertEquals(original.getTaskList(), new Project(readBack).getTaskList()); } @Test public void saveProject_nullProject_throwsNullPointerException() { thrown.expect(NullPointerException.class); saveProject(null, "SomeFile.json"); } /** * Saves {@code project} at the specified {@code filePath}. */ private void saveProject(ReadOnlyProject project, String filePath) { try { new JsonProjectStorage(Paths.get(filePath)).saveProject(project, addToTestDataPathIfNotNull(filePath)); } catch (IOException ioe) { throw new AssertionError("There should not be an error writing to the file.", ioe); } } @Test public void saveProject_nullFilePath_throwsNullPointerException() { thrown.expect(NullPointerException.class); saveProject(new Project(), null); } }
package com.androidsample.wearableapp; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.google.android.gms.wearable.DataEvent; import com.google.android.gms.wearable.DataEventBuffer; import com.google.android.gms.wearable.DataMap; import com.google.android.gms.wearable.DataMapItem; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.WearableListenerService; /** * This service is responsible for receiving messages and data maps from android wear. * Starting and stopping this service will done automatically by Google Play Services. * <p> * IF there is any change in DataMap than {@link #onDataChanged(DataEventBuffer)} will be called. * IF there is any new message than {@link #onMessageReceived(MessageEvent)} will be called. */ public class WearService extends WearableListenerService { public static final String TRACKING_STATUS_ACTION = "step.tracking.status"; public static final String TRACKING_COUNT_ACTION = "step.tracking.count"; private static final String STEP_COUNT_MESSAGES_PATH = "/StepCount"; private static final String STEP_TRACKING_STATUS_PATH = "/TrackingStatus"; @Override public void onDataChanged(DataEventBuffer dataEventBuffer) { super.onDataChanged(dataEventBuffer); //This method will call while any changes in data map occurs from watch side //This is data map. So, message delivery is guaranteed. for (DataEvent dataEvent : dataEventBuffer) { //Check for only those data who changed if (dataEvent.getType() == DataEvent.TYPE_CHANGED) { DataMap dataMap = DataMapItem.fromDataItem(dataEvent.getDataItem()).getDataMap(); //Check if the data map path matches with the step tracking status path String path = dataEvent.getDataItem().getUri().getPath(); if (path.equals(STEP_TRACKING_STATUS_PATH)) { //Read the values boolean isTracking = dataMap.getBoolean("status"); long timeStamp = dataMap.getLong("status-time"); //send broadcast to update the UI in MainActivity based on the tracking status Intent intent = new Intent(TRACKING_STATUS_ACTION); intent.putExtra("status", isTracking); intent.putExtra("status-time", timeStamp); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); Log.d("Tracking status: ", isTracking + " Time: " + timeStamp); } } } } @Override public void onMessageReceived(MessageEvent messageEvent) { //This method will call while any message is posted by the watch to the phone. //This is message api, so if the phone is not connected message will be lost. //No guarantee of the message delivery //check path of the message if (messageEvent.getPath().equalsIgnoreCase(STEP_COUNT_MESSAGES_PATH)) { //Extract the values String stepCount = new String(messageEvent.getData()); Log.d("Step count: ", stepCount + " "); //send broadcast to update the UI in MainActivity based on the tracking status Intent intent = new Intent(TRACKING_COUNT_ACTION); intent.putExtra("step-count", stepCount); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } else { super.onMessageReceived(messageEvent); } } }
/* * ID: nareddyt * LANG: JAVA * TASK: mirrors */ import java.awt.Point; import java.io.*; import java.util.*; public class P1_Mirrors { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader("mirrors.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("mirrors.out"))); StringTokenizer st = new StringTokenizer(f.readLine()); int lines = Integer.parseInt(st.nextToken()); Point barn = new Point(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())); // Stores all fences in new arrayList along with the orientation ArrayList<Point> fPos = new ArrayList<Point>(); ArrayList<String> fOrient = new ArrayList<String>(); for (int i = 0; i < lines; i++) { st = new StringTokenizer(f.readLine()); Point newPoint = new Point(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())); fPos.add(newPoint); fOrient.add(st.nextToken()); } // Gets the maximum value of X and Y int xMax = (int) barn.getX(); int yMax = (int) barn.getY(); for (int i = 0; i < fPos.size(); i++) { if (fPos.get(i).getX() > xMax) { xMax = (int) fPos.get(i).getX(); } if (fPos.get(i).getY() > yMax) { yMax = (int) fPos.get(i).getY(); } } int x; int y; // Now the Logic Starts... int changed = -1; int answer = -99; int index; for (int i = 0; i <= fPos.size(); i++) { x = 0; y = 0; String direction = "right"; index = 0; while (x >= 0 && x <= xMax && y >= 0 && y <= yMax) { if (x == (int) barn.getX() && y == (int) barn.getY()) { answer = changed; break; } else { if (direction.equals("right")) { x++; } else if (direction.equals("up")) { y++; } else if (direction.equals("left")) { x--; } else if (direction.equals("down")) { y--; } else throw new IllegalArgumentException("Check direction"); if (fPos.contains(new Point(x, y))) { index = fPos.indexOf(new Point(x, y)); String orient = fOrient.get(index); if (orient.equals("/")) { if (direction.equals("right")) { direction = "up"; } else if (direction.equals("up")) { direction = "right"; } else if (direction.equals("left")) { direction = "down"; } else if (direction.equals("down")) { direction = "left"; } else throw new IllegalArgumentException("Check direction inside /"); } else { if (direction.equals("right")) { direction = "down"; } else if (direction.equals("up")) { direction = "left"; } else if (direction.equals("left")) { direction = "up"; } else if (direction.equals("down")) { direction = "right"; } else throw new IllegalArgumentException("Check direction inside \\"); } } } }// end of while loop if (answer == changed) { break; } changed++; if (fOrient.get(changed).equals("/")) { fOrient.set(changed, "\\"); } else { fOrient.set(changed, "/"); } if (changed == 0) { // do nothing } else // sets previous change back { if (fOrient.get(changed - 1).equals("/")) { fOrient.set(changed - 1, "\\"); } else { fOrient.set(changed - 1, "/"); } } } if (changed == answer) { out.println(++answer); } else { out.println("-1"); } out.close(); System.exit(0); } }
package pro.likada.service.serviceImpl; import org.primefaces.model.TreeNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pro.likada.dao.ProductGroupDAO; import pro.likada.model.ProductGroup; import pro.likada.service.ProductGroupService; import pro.likada.util.TreeNodeUtil; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Created by bumur on 14.02.2017. */ @Named("productGroupService") @Transactional public class ProductGroupServiceImpl implements ProductGroupService, Serializable { private static final Logger LOGGER = LoggerFactory.getLogger(ProductGroupServiceImpl.class); @Inject private ProductGroupDAO productGroupDAO; @Override public ProductGroup findById(long id) { return productGroupDAO.findById(id); } @Override public void save(ProductGroup productGroup) { productGroupDAO.save(productGroup); } @Override public void deleteById(Long id) { productGroupDAO.deleteById(id); } @Override public List<ProductGroup> getProductGroupsByParentId(Long id) { return productGroupDAO.getProductGroupsByParentId(id); } @Override public List<ProductGroup> getAllProductGroups() { return productGroupDAO.getAllProductGroups(); } @Override public TreeNode fillTreeNodeValues(List<ProductGroup> productGroups, ProductGroup productGroupAll,TreeNode root) { List<TreeNode> nodes = new ArrayList<TreeNode>(); ProductGroup gg_root = new ProductGroup(); gg_root.setTitle("Все группы"); gg_root.setId((long) 0); root = new TreeNodeUtil(gg_root, null); TreeNode node_all = new TreeNodeUtil(productGroupAll, root); nodes.add(node_all); TreeNode slut_node = null; for (int i = 0; i < productGroups.size(); i++) { if (productGroups.get(i).getParentId() != null) { if (productGroups.get(i).getParentId().equals(new Long(0))) { slut_node = new TreeNodeUtil(productGroups.get(i), root); slut_node.setExpanded(true); nodes.add(slut_node); } else { for (int n = 0; n < nodes.size(); n++) { if (nodes.get(n).getData() != null) { if (productGroups.get(i).getParentId().equals(((ProductGroup) nodes.get(n).getData()).getId())) { slut_node = new TreeNodeUtil(productGroups.get(i), nodes.get(n)); nodes.add(slut_node); } } } } } } slut_node=null; return root; } @Override public List<TreeNode> getExpandedProductGroupTreeNodeToList(TreeNode treeNode) { if (treeNode != null) { int level = 0; List<TreeNode> nodes = new ArrayList<TreeNode>(); expandedTreeNodeToList(treeNode, nodes, level); return nodes; } return null; } @Override public void expandedTreeNodeToList(TreeNode root, List<TreeNode> nodes, int level) { if (root != null && nodes != null) { int l = level + 1; List<TreeNode> childs = root.getChildren(); for (TreeNode treeNode:childs) { TreeNodeUtil treeNodeUtil = (TreeNodeUtil) treeNode; treeNodeUtil.setLevel(l); nodes.add(treeNodeUtil); expandedTreeNodeToList(treeNodeUtil, nodes, l); } } } @Override public Long getMinValueOfProductParentId() { return productGroupDAO.getMinValueOfProductParentId(); } @Override public Long getMinValueOfProductId() { return productGroupDAO.getMinValueOfProductId(); } @Override public TreeNode addNewGroupToTreeNode(TreeNode parentNode, ProductGroup newProductGroup) { TreeNode newTreeNode=new TreeNodeUtil(newProductGroup,parentNode); return newTreeNode; } }
package org.digdata.swustoj.hibernate.template; import org.digdata.swustoj.base.BaseTemplate; import org.digdata.swustoj.hibernate.entiy.UserRole; public interface UserRoleTemplate extends BaseTemplate<UserRole> { }
package com.stk123.task.strategy; import java.sql.Connection; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.stk123.model.Ene; import com.stk123.model.Index; import com.stk123.model.K; import com.stk123.common.util.EmailUtils; import com.stk123.task.tool.TaskUtils; public class Strategy1 extends Strategy { @Override public void run(Connection conn, String today) throws Exception { List<Index> results = new ArrayList<Index>(); for(Index index : indexs){ if(index.isStop(today))continue; K k = index.getK(today); if(k==null)continue; if(index.getTotalMarketValue() >= 500)continue; if(index.getStk()!=null && index.getStk().getTotalCapital() != null){ if(index.getStk().getTotalCapital() /10000.0 >= 10)continue; } K yk = k.before(1); double ma60 = k.getMA(K.Close, 60); double yma60 = yk.getMA(K.Close, 60); if(ma60 >= yma60){ //if(k.getClose() <= k.getOpen()){ //if(k.getClose() >= ma60 * 0.94 && k.getLow() <= ma60 * 1.05){ //if(k.getVolumn() <= yk.getVolumn()){ K kh = k.getKByHVV(20); K kh2 = kh.getKByHVV(60); if(kh.getDate().equals(kh2.getDate())){ int cnt = k.getKCountWithCondition(20, new K.Condition() { public boolean pass(K k) throws Exception { return k.getClose() <= k.getMA(K.Close, 20); } }); if(log){ System.out.println("ccc="+(cnt<=6)); } if(cnt <= 6){ cnt = k.getKCountWithCondition(60, new K.Condition() { public boolean pass(K k) throws Exception { Ene ene = k.getEne(); return k.getHigh() > ene.getUpper() || k.getLow() < ene.getLower(); } }); if(log){ System.out.println("bbb="+(cnt>=12)); } if(cnt >= 12){ index.changePercent = cnt; cnt = k.getKCountWithCondition(20, new K.Condition() { public boolean pass(K k) throws Exception { return k.getVolumn() > k.getMA(K.Volumn, 10) * 1.3; } }); //System.out.println(cnt); if(log){ System.out.println("aaa="+(cnt>=5)); } if(cnt >= 5){ //连续波段性 if(k.hasHighVolumn(1.4)){ cnt = k.getKCountWithCondition(5, new K.Condition() { public boolean pass(K k) throws Exception { Ene ene = k.getEne(); return k.getLow()*0.97 <= ene.getLower(); } }); if(cnt > 0){ cnt = k.getKCountWithCondition(3, new K.Condition() { public boolean pass(K k) throws Exception { Ene ene = k.getEne(); return k.getHigh() >= ene.getUpper(); } }); if(cnt == 0){ results.add(index); } } } } } } } //} //} //} } } if(results.size() > 0){ Collections.sort(results, new Comparator<Index>(){ @Override public int compare(Index o1, Index o2) { int i = (int)((o2.changePercent - o1.changePercent)*10000); return i; }}); /*for(Index index : results){ System.out.println(index.getCode()+","+index.getName()+",change="+index.changePercent); }*/ EmailUtils.sendAndReport("模型1-60日均线上升且活跃放量,个数:"+results.size()+",日期:"+today,TaskUtils.createHtmlTable(today, results)); } } }
package edu.asu.commons.event; /** * $Id$ * * Marks all classes capable of generating Events and dispatching them to * interested subscribers. * * @author alllee * @version $Revision$ */ public interface EventGenerator { /** * Subscribes the given EventHandler to this EventGenerator, signifying * that all events generated from this EventGenerator should be conveyed to * the given EventHandler. */ public void subscribe(EventHandler<Event> handler); /** * Subscribes the given EventHandler to this EventGenerator, signifying * that all events generated from this EventGenerator satisfying the * given EventConstraint should be conveyed to the given EventHandler. */ public void subscribe(EventHandler<Event> handler, EventConstraint constraint); /** * Unsubscribes the given EventHandler from this EventGenerator. */ public void unsubscribe(EventHandler<Event> handler); }
import org.codehaus.jackson.map.ObjectMapper; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.virgil.hibernate.Department; import org.virgil.hibernate.Employee; import org.virgil.hibernate.TreeNode; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by virgil on 2017/3/2. */ public class TestAction1 { private static SessionFactory sessionFactory = null; ObjectMapper mapper = new ObjectMapper(); static { //读取classpath中applicationContext.xml配置文件 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); //获取session中配置的sessionFactory对象 sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory"); } private TreeNode initData() { TreeNode rootNode = new TreeNode("micmiu.com"); // 一级 TreeNode node0 = new TreeNode("Michael"); node0.setParent(rootNode); rootNode.getChildren().add(node0); // 二级 TreeNode node0_0 = new TreeNode("J2EE"); node0_0.setParent(node0); node0.getChildren().add(node0_0); // 二级 TreeNode node0_1 = new TreeNode("SOA"); node0_1.setParent(node0); node0.getChildren().add(node0_1); // 二级 TreeNode node0_2 = new TreeNode("NoSQL"); node0_2.setParent(node0); node0.getChildren().add(node0_2); // 二级 TreeNode node0_3 = new TreeNode("编程语言"); node0_3.setParent(node0); node0.getChildren().add(node0_3); // 三级 TreeNode node0_3_0 = new TreeNode("Java"); node0_3_0.setParent(node0_3); node0_3.getChildren().add(node0_3_0); TreeNode node0_3_1 = new TreeNode("Groovy"); node0_3_1.setParent(node0_3); node0_3.getChildren().add(node0_3_1); TreeNode node0_3_2 = new TreeNode("javascript"); node0_3_2.setParent(node0_3); node0_3.getChildren().add(node0_3_2); // 一级 TreeNode node1 = new TreeNode("Hazel"); node1.setParent(rootNode); rootNode.getChildren().add(node1); // 二级 TreeNode node1_0 = new TreeNode("life"); node1_0.setParent(node1); node1.getChildren().add(node1_0); // 二级 TreeNode node1_1 = new TreeNode("美食"); node1_1.setParent(node1); node1.getChildren().add(node1_1); // 二级 TreeNode node1_2 = new TreeNode("旅游"); node1_2.setParent(node1); node1.getChildren().add(node1_2); return rootNode; } private void printNode(TreeNode node, int level) { String preStr = ""; for (int i = 0; i < level; i++) { preStr += "|----"; } System.out.println(preStr + node.getName()); for (TreeNode children : node.getChildren()) { printNode(children, level + 1); } } @Test public void testSave1() { Session session = sessionFactory.openSession(); TreeNode rootNode = initData(); System.out.println(rootNode.getName()); //开始事务 Transaction t = session.beginTransaction(); try { session.save(rootNode); t.commit(); } catch (RuntimeException e) { //有异常则回滚事务 t.rollback(); e.printStackTrace(); } finally { //关闭session session.close(); } System.out.println("========>测试添加 end <========"); // 读取添加的数据 testRead(); } public void testRead() { System.out.println("========>读取 start <========"); Session session = sessionFactory.openSession(); session.beginTransaction(); System.out.println("-----> get root node:"); TreeNode rootNode = (TreeNode) session.get(TreeNode.class, 1); System.out.println("-----> 输出树形结构如下:"); printNode(rootNode, 0); session.getTransaction().commit(); session.close(); System.out.println("========>读取 end <========"); } @Test public void testSave() { //创建一个部门对象 Department d1 = new Department(); d1.setDname("sxx我还要"); //创建两个员工对象 Employee e1 = new Employee(); e1.setName("vv1"); Employee e2 = new Employee(); e2.setName("vv2"); //设置对象关联 d1.getEmployeeList().add(e1); d1.getEmployeeList().add(e2); e1.setDepartment(d1); e2.setDepartment(d1); //获取Session Session session = sessionFactory.openSession(); //开始事务 Transaction t = session.beginTransaction(); try { //添加数据 session.save(d1); session.save(e1); session.save(e2); //提交事务 t.commit(); } catch (RuntimeException e) { //有异常则回滚事务 t.rollback(); e.printStackTrace(); } finally { //关闭session session.close(); } } @Test public void testList() { //获取Session Session session = sessionFactory.openSession(); //开始事务 Transaction t = session.beginTransaction(); String hql = "from TreeNode where parent = 1"; Query query = session.createQuery(hql); List<TreeNode> list = query.list(); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i).getName()); System.out.println(list.get(i).getParent().getName()); Set<TreeNode> nodes = list.get(i).getChildren(); System.out.println("**********"); for (TreeNode node : nodes) { System.out.println(node.getName()); } } // String hql = "from Department"; // Query query = session.createQuery(hql); // List<Department> list = query.list(); // for (int i = 0; i < list.size(); i++) { // System.out.println(list.get(i).getId()); // List<Employee> employeeList = list.get(i).getEmployeeList(); // for (Employee ee : employeeList) { // System.out.println(ee.getName()); // } // } t.commit(); } }
public class Human { protected String name = ""; protected int strength = 50; protected int stealth =3; protected int health =100; protected int intelligence =3; public Human() { } public Human(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getStrangth() { return strength; } public void setStrangth(int strength) { this.strength = strength; } public int getStealth() { return stealth; } public void setStealth(int stealth) { this.stealth = stealth; } public int getHealth() { return health; } public void setHealth(int health) { this.health = health; } public void attack(Human human) { human.setHealth(human.getHealth()-strength); } }
/* * Copyright 2017 Goldman Sachs. * 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.gs.tablasco.files; import java.io.File; /** * A strategy for determining the expected results and verification output directories for a given test class. */ public interface DirectoryStrategy { /** * Returns the expected results directory for a given test class. * @param testClass the test class * @return the expected results directory */ File getExpectedDirectory(Class<?> testClass); /** * Returns the verification output directory for a given test class. * @param testClass the test class * @return the verification output directory */ File getOutputDirectory(Class<?> testClass); /** * Returns the actual results directory for a given test class. * @param testClass the test class * @return the verification output directory */ File getActualDirectory(Class<?> testClass); }
/** */ package com.akgundemirbas.mdd.gui.tests; import com.akgundemirbas.mdd.gui.GuiFactory; import com.akgundemirbas.mdd.gui.VerticalLayout; import junit.textui.TestRunner; /** * <!-- begin-user-doc --> * A test case for the model object '<em><b>Vertical Layout</b></em>'. * <!-- end-user-doc --> * @generated */ public class VerticalLayoutTest extends LayoutTest { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static void main(String[] args) { TestRunner.run(VerticalLayoutTest.class); } /** * Constructs a new Vertical Layout test case with the given name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public VerticalLayoutTest(String name) { super(name); } /** * Returns the fixture for this Vertical Layout test case. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected VerticalLayout getFixture() { return (VerticalLayout)fixture; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#setUp() * @generated */ @Override protected void setUp() throws Exception { setFixture(GuiFactory.eINSTANCE.createVerticalLayout()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#tearDown() * @generated */ @Override protected void tearDown() throws Exception { setFixture(null); } } //VerticalLayoutTest
package com.test.thread; /** * Created with IntelliJ IDEA. * User: wuzbin * Date: 13-4-18 * Time: 下午5:21 * To change this template use File | Settings | File Templates. */ public class InterruptTest { public static Thread t1 = new Thread(new Runnable() { @Override public void run() { int i = 0; while (i++<20) { System.out.println("t1-" + t4.getState() + "----" + t4.isInterrupted()); Thread.yield(); } } }); public static Thread t2 = new Thread(new Runnable() { @Override public void run() { int i = 0; while (i++<20) { System.out.println("t2-" + t4.getState() + "----" + t4.isInterrupted()); Thread.yield(); } } }); public static Thread t3 = new Thread(new Runnable() { @Override public void run() { int i = 0; while (i++<20) { System.out.println("t3-" + t4.getState() + "----" + t4.isInterrupted()); Thread.yield(); } } }); public static Thread t4 = new Thread(new Runnable() { @Override public void run() { int i = 0; while (i++<20) { System.out.println("t4-" + t4.getState() + "----" + t4.isInterrupted()); Thread.yield(); } } }); public static void main(String[] args) { t2.start(); t1.start(); t3.start(); t4.start(); } }
package com.base.spring.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; public class UserAuthProvider implements UserDetailsService { @Autowired private UserDao userDao; public UserAuthProvider() { } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userDao.findByUsername(username); user.setRoles(); return user; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } }
package com.generic.core.services.service; public interface UserInterestsServiceI { }
/* * 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 unt.herrera.prog2.tp5; import java.time.LocalDate; /** * * @author jonas */ public class GestorRolEnTrabajo implements IGestorRolesEnTrabajos { // siempre para crear un solo gestor private static GestorRolEnTrabajo gestor; private GestorRolEnTrabajo(){} public static GestorRolEnTrabajo crear(){ if(gestor==null){ gestor = new GestorRolEnTrabajo(); } return gestor; } @Override public RolEnTrabajo nuevoRolEnTrabajo(LocalDate fechaDesde, Profesor unProfesor,Rol unRol){ if(fechaDesde!=null && unProfesor!=null && unRol!=null){ //Si los parametros recibidos son validos entonces crea un nuevo rol RolEnTrabajo nuevoRol= new RolEnTrabajo(fechaDesde, unProfesor, unRol); return nuevoRol; // retorna el rol creado }else System.out.println("Los parametros recibidos son incorrectos"); return null; // de lo contrario retornara siempre null } }
/** * Copyright (c) 2012, Institute of Telematics, Institute of Information Systems (Dennis Pfisterer, Sven Groppe, Andreas Haller, Thomas Kiencke, Sebastian Walther, Mario David), University of Luebeck * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * - Neither the name of the University of Luebeck nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package p2p.distribution.strategies; import p2p.distribution.CombinationDistribution; import p2p.distribution.DistributionFactory; /** * The Class ThreeKeyDistribution is a distribution strategy where all three * elements of the triple is stored within the key. Only one possible * combinations are stored h(spo) */ public class SevenKeyDistribution extends CombinationDistribution { public final static int STRATEGY_ID = 7; public SevenKeyDistribution() { super(); strategies.add(DistributionFactory.create(1)); strategies.add(DistributionFactory.create(2)); strategies.add(DistributionFactory.create(3)); } @Override public String toString() { return "7: SevenKeyStrategy [h(S),h(P),h(O),h(SP),h(SO),h(PO),h(SPO)]"; } @Override public int getStrategyID() { return STRATEGY_ID; } }
package forms; import core.ActionManager; import core.ActionNote; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.CheckBox; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import storage.DatabaseManager; import users.*; import users.userTypes.*; public class AddUserForm { private Stage stage; private Scene scene; private Session session; private DatabaseManager databaseManager; private ActionManager actionManager; //int openUserCardID=-1; @FXML private TextField nameTextField; @FXML private TextField surnameTextField; @FXML private TextField userTypeTextField; @FXML private TextField phoneNumberTextField; @FXML private TextField addressTextField; @FXML private CheckBox checkBoxPriv1; @FXML private CheckBox checkBoxPriv2; @FXML private CheckBox checkBoxPriv3; /** * Initialization and run new scene on the primary stage */ void startForm(Stage primaryStage, Session currentSession, DatabaseManager databaseManager, ActionManager actionManager) throws Exception { this.stage = primaryStage; this.session = currentSession; this.databaseManager = databaseManager; this.actionManager = actionManager; sceneInitialization(); stage.setScene(scene); stage.show(); } /** * Initialization scene and scene's elements */ private void sceneInitialization() throws Exception { FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLFiles/addUserForm.fxml")); loader.setController(this); GridPane root = loader.load(); this.scene = new Scene(root, 700, 700); nameTextField = (TextField) scene.lookup("#nameField"); surnameTextField = (TextField) scene.lookup("#surnameField"); userTypeTextField = (TextField) scene.lookup("#userTypeField"); phoneNumberTextField = (TextField) scene.lookup("#phoneNumberField"); addressTextField = (TextField) scene.lookup("#addressField"); checkBoxPriv1 = (CheckBox) scene.lookup("#checkBoxPriv1"); checkBoxPriv2 = (CheckBox) scene.lookup("#checkBoxPriv2"); checkBoxPriv3 = (CheckBox) scene.lookup("#checkBoxPriv3"); } /** * Click on button "Save" event * button for collecting information from the textFields and create a new UserCard */ @FXML public void save() throws Exception { UserCard newUserCard = null; String surname = "None"; String name = "None"; String phoneNumber = "none"; String address = "none"; if (!surnameTextField.getText().isEmpty()) { surname = surnameTextField.getText(); } if (!nameTextField.getText().isEmpty()) { name = nameTextField.getText(); } if (!phoneNumberTextField.getText().isEmpty()) { phoneNumber = phoneNumberTextField.getText(); } if (!addressTextField.getText().isEmpty()) { address = phoneNumberTextField.getText(); } if (session.getUser().isHasEditingLibrarianPerm()) { if (userTypeTextField.getText().toLowerCase().equals("librarian")) { newUserCard = new UserCard(name, surname, new Librarian(), phoneNumber, address); databaseManager.saveUserCard(newUserCard); if (checkBoxPriv1.isSelected()) { ((Librarian) newUserCard.userType).setPriv1(); databaseManager.saveUserCard(newUserCard); } if (checkBoxPriv2.isSelected()) { ((Librarian) newUserCard.userType).setPriv2(); databaseManager.saveUserCard(newUserCard); } if (checkBoxPriv3.isSelected()) { ((Librarian) newUserCard.userType).setPriv3(); databaseManager.saveUserCard(newUserCard); } } else { System.err.println("No permission"); } }else { if (userTypeTextField.getText().toLowerCase().equals("faculty")) { newUserCard = new UserCard(name, surname, new Faculty(), phoneNumber, address); } else if (userTypeTextField.getText().toLowerCase().equals("student")) { newUserCard = new UserCard(nameTextField.getText(), surname, new Student(), phoneNumber, address); } else if (userTypeTextField.getText().toLowerCase().equals("ta")) { newUserCard = new UserCard(nameTextField.getText(), surname, new TA(), phoneNumber, address); } else if (userTypeTextField.getText().toLowerCase().equals(("visitingprofessor"))) { newUserCard = new UserCard(nameTextField.getText(), surname, new VisitingProfessor(), phoneNumber, address); } else if (userTypeTextField.getText().toLowerCase().equals("professor")) { newUserCard = new UserCard(nameTextField.getText(), surname, new Professor(), phoneNumber, address); } else if (userTypeTextField.getText().toLowerCase().equals("instructor")) { newUserCard = new UserCard(nameTextField.getText(), surname, new Instructor(), phoneNumber, address); } else { newUserCard = new UserCard(name, surname, new Student(), phoneNumber, address); } databaseManager.saveUserCard(newUserCard); databaseManager.saveUserCard(newUserCard); actionManager.actionNotes.add(new ActionNote(session.userCard, session.day, session.month, ActionNote.ADD_USER_ACTION_ID, newUserCard)); databaseManager.update(); this.back(); } } /** * Click ob button "back" event * button for coming back to the EditForm * * @throws Exception */ @FXML public void back() throws Exception { EditForm mainForm = new EditForm(); mainForm.startForm(stage, session, databaseManager, actionManager); } }
package com.platform.web.rest; import com.platform.Application; import com.platform.domain.Presencestatus; import com.platform.repository.PresencestatusRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.hamcrest.Matchers.hasItem; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; import javax.inject.Inject; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the PresencestatusResource REST controller. * * @see PresencestatusResource */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration @IntegrationTest public class PresencestatusResourceTest { private static final String DEFAULT_PRESENCE_STATUS_NAME = "AAAAA"; private static final String UPDATED_PRESENCE_STATUS_NAME = "BBBBB"; @Inject private PresencestatusRepository presencestatusRepository; @Inject private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Inject private PageableHandlerMethodArgumentResolver pageableArgumentResolver; private MockMvc restPresencestatusMockMvc; private Presencestatus presencestatus; @PostConstruct public void setup() { MockitoAnnotations.initMocks(this); PresencestatusResource presencestatusResource = new PresencestatusResource(); ReflectionTestUtils.setField(presencestatusResource, "presencestatusRepository", presencestatusRepository); this.restPresencestatusMockMvc = MockMvcBuilders.standaloneSetup(presencestatusResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setMessageConverters(jacksonMessageConverter).build(); } @Before public void initTest() { presencestatus = new Presencestatus(); presencestatus.setPresenceStatusName(DEFAULT_PRESENCE_STATUS_NAME); } @Test @Transactional public void createPresencestatus() throws Exception { int databaseSizeBeforeCreate = presencestatusRepository.findAll().size(); // Create the Presencestatus restPresencestatusMockMvc.perform(post("/api/presencestatuss") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(presencestatus))) .andExpect(status().isCreated()); // Validate the Presencestatus in the database List<Presencestatus> presencestatuss = presencestatusRepository.findAll(); assertThat(presencestatuss).hasSize(databaseSizeBeforeCreate + 1); Presencestatus testPresencestatus = presencestatuss.get(presencestatuss.size() - 1); assertThat(testPresencestatus.getPresenceStatusName()).isEqualTo(DEFAULT_PRESENCE_STATUS_NAME); } @Test @Transactional public void getAllPresencestatuss() throws Exception { // Initialize the database presencestatusRepository.saveAndFlush(presencestatus); // Get all the presencestatuss restPresencestatusMockMvc.perform(get("/api/presencestatuss")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.[*].id").value(hasItem(presencestatus.getId().intValue()))) .andExpect(jsonPath("$.[*].presenceStatusName").value(hasItem(DEFAULT_PRESENCE_STATUS_NAME.toString()))); } @Test @Transactional public void getPresencestatus() throws Exception { // Initialize the database presencestatusRepository.saveAndFlush(presencestatus); // Get the presencestatus restPresencestatusMockMvc.perform(get("/api/presencestatuss/{id}", presencestatus.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(presencestatus.getId().intValue())) .andExpect(jsonPath("$.presenceStatusName").value(DEFAULT_PRESENCE_STATUS_NAME.toString())); } @Test @Transactional public void getNonExistingPresencestatus() throws Exception { // Get the presencestatus restPresencestatusMockMvc.perform(get("/api/presencestatuss/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updatePresencestatus() throws Exception { // Initialize the database presencestatusRepository.saveAndFlush(presencestatus); int databaseSizeBeforeUpdate = presencestatusRepository.findAll().size(); // Update the presencestatus presencestatus.setPresenceStatusName(UPDATED_PRESENCE_STATUS_NAME); restPresencestatusMockMvc.perform(put("/api/presencestatuss") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(presencestatus))) .andExpect(status().isOk()); // Validate the Presencestatus in the database List<Presencestatus> presencestatuss = presencestatusRepository.findAll(); assertThat(presencestatuss).hasSize(databaseSizeBeforeUpdate); Presencestatus testPresencestatus = presencestatuss.get(presencestatuss.size() - 1); assertThat(testPresencestatus.getPresenceStatusName()).isEqualTo(UPDATED_PRESENCE_STATUS_NAME); } @Test @Transactional public void deletePresencestatus() throws Exception { // Initialize the database presencestatusRepository.saveAndFlush(presencestatus); int databaseSizeBeforeDelete = presencestatusRepository.findAll().size(); // Get the presencestatus restPresencestatusMockMvc.perform(delete("/api/presencestatuss/{id}", presencestatus.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<Presencestatus> presencestatuss = presencestatusRepository.findAll(); assertThat(presencestatuss).hasSize(databaseSizeBeforeDelete - 1); } }
package io.qtechdigital.onlineTutoring.mapper.user.impl; import io.qtechdigital.onlineTutoring.mapper.user.UserMapper; import io.qtechdigital.onlineTutoring.dto.auth.AuthenticatedUserDto; import io.qtechdigital.onlineTutoring.dto.security.RoleShortDto; import io.qtechdigital.onlineTutoring.dto.user.response.UserShortDto; import io.qtechdigital.onlineTutoring.mapper.role.RoleMapper; import io.qtechdigital.onlineTutoring.model.User; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; @Service public class UserMapperImpl implements UserMapper { private final RoleMapper roleMapper; public UserMapperImpl(RoleMapper roleMapper) { this.roleMapper = roleMapper; } @Override public AuthenticatedUserDto toAuthenticatedUserDto(User user, String token) { AuthenticatedUserDto authenticatedUserDto = new AuthenticatedUserDto(); List<RoleShortDto> roles = user.getRoles() .stream() .map(roleMapper::toRoleShortDto) .collect(Collectors.toList()); UserShortDto userSimplifiedDto = toUserShortDto(user); authenticatedUserDto.setRoles(roles); authenticatedUserDto.setUser(userSimplifiedDto); authenticatedUserDto.setToken(token); return authenticatedUserDto; } private UserShortDto toUserShortDto(User user) { UserShortDto userSimplifiedDto = new UserShortDto(); userSimplifiedDto.setId(user.getId()); userSimplifiedDto.setEmail(user.getEmail()); userSimplifiedDto.setLastName(user.getLastName()); userSimplifiedDto.setFirstName(user.getFirstName()); return userSimplifiedDto; } }
package com.soy.seckill.dao.cache; import com.soy.seckill.dao.SeckillDao; import com.soy.seckill.entity.Seckill; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*; /** * Created by Soy on 2016/12/15. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring/spring-dao.xml") public class RedisDaoTest { @Autowired private RedisDao redisDao; @Autowired private SeckillDao seckillDao; @Test public void putSeckill() throws Exception { int seckillId = 1002; Seckill seckill = seckillDao.queryById(seckillId); if(seckill!=null) { String msg = redisDao.putSeckill(seckill); System.out.println(msg); } } @Test public void getSeckill() throws Exception { int seckillId = 1002; Seckill seckill = redisDao.getSeckill(seckillId); if(seckill!=null){ System.out.println(seckill); } } @Test public void testRedis(){ int seckillId = 1003; Seckill seckill = redisDao.getSeckill(seckillId); if(seckill==null){ seckill = seckillDao.queryById(seckillId); if(seckill!=null){ String msg = redisDao.putSeckill(seckill); System.out.println(msg); seckill = redisDao.getSeckill(seckillId); System.out.println(seckill); } } } }
package com.gr.cinema.domain; public class Show { private String showId; private String movieId; private String theaterId; private String showStartTimes; public String getMovieId() { return movieId; } public void setMovieId(String movieId) { this.movieId = movieId; } public String getTheaterId() { return theaterId; } public void setTheaterId(String theaterId) { this.theaterId = theaterId; } public String getShowStartTimes() { return showStartTimes; } public void setShowStartTimes(String showStartTimes) { this.showStartTimes = showStartTimes; } public String getShowId() { return showId; } public void setShowId(String showId) { this.showId = showId; } public void reset() { showId = null; movieId = null; theaterId = null; showStartTimes = null; } }
package com.example.android.addmusic; /** * {@link Song} represents a song that the user wants to listen. * It contains the name of the song, the interpreter, the url for the youtube video clip and an image for that word. */ public class Song { /** Name of the song */ private String mName; /** Singer or group that interpret the song*/ private String mInterpreter; /** * Create a new Song object. * * @param name is the title of the song * @param interpreter is who interprets the song */ public Song(String name, String interpreter) { mName = name; mInterpreter = interpreter; } /** * Get the name of the song. */ public String getName() { return mName; } /** * Get the interpreter of the song. */ public String getInterpreter() { return mInterpreter; } }
package org.mini2Dx.libgdx; import com.badlogic.gdx.Gdx; import org.mini2Dx.core.JvmPlatformUtils; public abstract class LibgdxPlatformUtils extends JvmPlatformUtils { @Override public void exit(boolean ignorePlatformRestrictions) { Gdx.app.exit(); } }
/* * 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 latihanjavafx; /** * * @author Fifi Agustina */ public class FrameIdealTubuh extends javax.swing.JFrame { /** * Creates new form FrameIdealTubuh */ public FrameIdealTubuh() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jeniskelamin = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); idnama = new javax.swing.JTextField(); idtinggi = new javax.swing.JTextField(); idberat = new javax.swing.JTextField(); rdblaki = new javax.swing.JRadioButton(); rdbperempuan = new javax.swing.JRadioButton(); buttonhitung = new javax.swing.JButton(); buttonulang = new javax.swing.JButton(); buttonkeluar = new javax.swing.JButton(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); idideal = new javax.swing.JTextField(); idhasil = new javax.swing.JTextField(); idsaran = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(null); jPanel1.setBackground(new java.awt.Color(102, 255, 255)); jPanel1.setLayout(null); jLabel1.setText("Aplikasi cek ideal"); jPanel1.add(jLabel1); jLabel1.setBounds(240, 20, 140, 20); jLabel2.setText("Nama"); jPanel1.add(jLabel2); jLabel2.setBounds(78, 67, 80, 30); jLabel3.setText("Tinggi"); jPanel1.add(jLabel3); jLabel3.setBounds(77, 108, 90, 30); jLabel4.setText("Berat"); jPanel1.add(jLabel4); jLabel4.setBounds(77, 145, 90, 20); jLabel5.setText("Jenis Kelamin"); jPanel1.add(jLabel5); jLabel5.setBounds(78, 173, 120, 30); idnama.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { idnamaActionPerformed(evt); } }); jPanel1.add(idnama); idnama.setBounds(227, 59, 262, 31); jPanel1.add(idtinggi); idtinggi.setBounds(227, 101, 227, 28); idberat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { idberatActionPerformed(evt); } }); jPanel1.add(idberat); idberat.setBounds(227, 137, 227, 30); jeniskelamin.add(rdblaki); rdblaki.setText("Laki-laki"); rdblaki.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rdblakiActionPerformed(evt); } }); jPanel1.add(rdblaki); rdblaki.setBounds(227, 179, 76, 23); jeniskelamin.add(rdbperempuan); rdbperempuan.setText("Perempuan"); rdbperempuan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rdbperempuanActionPerformed(evt); } }); jPanel1.add(rdbperempuan); rdbperempuan.setBounds(332, 179, 110, 20); buttonhitung.setText("Hitung"); buttonhitung.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonhitungActionPerformed(evt); } }); jPanel1.add(buttonhitung); buttonhitung.setBounds(232, 220, 80, 30); buttonulang.setText("Coba Ulang"); buttonulang.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonulangActionPerformed(evt); } }); jPanel1.add(buttonulang); buttonulang.setBounds(324, 220, 100, 30); buttonkeluar.setText("Keluar"); buttonkeluar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonkeluarActionPerformed(evt); } }); jPanel1.add(buttonkeluar); buttonkeluar.setBounds(437, 220, 80, 30); jLabel6.setText("cm"); jPanel1.add(jLabel6); jLabel6.setBounds(472, 108, 50, 30); jLabel7.setText("kg"); jPanel1.add(jLabel7); jLabel7.setBounds(472, 145, 50, 40); jLabel8.setText("Berat Badan Ideal Anda adalah"); jPanel1.add(jLabel8); jLabel8.setBounds(78, 280, 220, 20); jLabel9.setText("Hasil Analisa Kesehatan"); jPanel1.add(jLabel9); jLabel9.setBounds(78, 322, 260, 20); idideal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ididealActionPerformed(evt); } }); jPanel1.add(idideal); idideal.setBounds(282, 280, 60, 30); idhasil.setText("?"); jPanel1.add(idhasil); idhasil.setBounds(78, 347, 450, 32); idsaran.setText("?"); jPanel1.add(idsaran); idsaran.setBounds(78, 385, 450, 31); jLabel10.setText("kg"); jPanel1.add(jLabel10); jLabel10.setBounds(350, 280, 50, 20); getContentPane().add(jPanel1); jPanel1.setBounds(0, 0, 620, 440); pack(); }// </editor-fold>//GEN-END:initComponents private void rdbperempuanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdbperempuanActionPerformed // TODO add your handling code here: }//GEN-LAST:event_rdbperempuanActionPerformed private void rdblakiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdblakiActionPerformed // TODO add your handling code here: }//GEN-LAST:event_rdblakiActionPerformed private void idnamaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idnamaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_idnamaActionPerformed private void ididealActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ididealActionPerformed // TODO add your handling code here: }//GEN-LAST:event_ididealActionPerformed private void idberatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idberatActionPerformed // TODO add your handling code here: }//GEN-LAST:event_idberatActionPerformed private void buttonkeluarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonkeluarActionPerformed // TODO add your handling code here: dispose(); System.exit(0); }//GEN-LAST:event_buttonkeluarActionPerformed private void buttonulangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonulangActionPerformed // TODO add your handling code here: idnama.setText(""); idberat.setText(""); idtinggi.setText(""); idideal.setText(""); idhasil.setText(""); idsaran.setText(""); jeniskelamin.clearSelection(); }//GEN-LAST:event_buttonulangActionPerformed private void buttonhitungActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonhitungActionPerformed // TODO add your handling code here: double h = 0; double t = Double.valueOf(idtinggi.getText()); double b = Double.valueOf(idberat.getText()); String nama = idnama.getText(); if(rdblaki.isSelected()){ h = (t-100); }//GEN-LAST:event_buttonhitungActionPerformed else if (rdbperempuan.isSelected()){ h = (t-104); } String temp = Double.toString(h); if(h<b){ idideal.setText(temp); idhasil.setText("Maaf "+nama+"sepertinya anda Overweight"); idsaran.setText("Sebaiknya "+nama+"melakukan olahraga secara teratur dan pola makan yang sehat"); } else if(h>b){ idideal.setText(temp); idhasil.setText("Maaf "+nama+" sepertinya anda Underweight"); idsaran.setText("Sebaiknya "+nama+" melakukan olahraga teratur dan pola makan sehat"); } else{ idideal.setText(temp); idhasil.setText("Tubuh anda ideal"); idsaran.setText("Tetap olahraga secara teratur dan jaga pola makan"); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FrameIdealTubuh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FrameIdealTubuh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FrameIdealTubuh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FrameIdealTubuh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FrameIdealTubuh().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton buttonhitung; private javax.swing.JButton buttonkeluar; private javax.swing.JButton buttonulang; private javax.swing.JTextField idberat; private javax.swing.JTextField idhasil; private javax.swing.JTextField idideal; private javax.swing.JTextField idnama; private javax.swing.JTextField idsaran; private javax.swing.JTextField idtinggi; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.ButtonGroup jeniskelamin; private javax.swing.JRadioButton rdblaki; private javax.swing.JRadioButton rdbperempuan; // End of variables declaration//GEN-END:variables }
package com.dungkk.gasorder.fragment; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.dungkk.gasorder.MainActivity; import com.dungkk.gasorder.adapter.MainSliderAdapter; import com.dungkk.gasorder.passingObjects.location; import android.widget.ImageButton; import android.widget.LinearLayout; import com.dungkk.gasorder.R; import com.example.bannerslider.Slider; import java.io.IOException; public class FragmentMain extends Fragment implements View.OnClickListener{ private FragmentTransaction transaction; private LinearLayout layout_order, layout_product, layout_tips; private View view; private Slider slider; private String[] arrslides; @Override public void onResume() { super.onResume(); if(getView() == null){ return; } getView().setFocusableInTouchMode(true); getView().requestFocus(); getView().setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){ System.exit(0); return true; } return false; } }); } @Nullable @Override public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.layout_main, container, false); setSlider(view); layout_order = view.findViewById(R.id.layout_order); layout_product = view.findViewById(R.id.layout_product); layout_tips = view.findViewById(R.id.layout_tips); layout_order.setOnClickListener(this); layout_product.setOnClickListener(this); layout_tips.setOnClickListener(this); return view; } private void replaceFragment(Fragment fragment){ FragmentManager manager = getFragmentManager(); transaction = manager.beginTransaction(); transaction.replace(R.id.content_main, fragment, FragmentMain.class.getSimpleName()) .addToBackStack(FragmentMain.class.getSimpleName()) .commit(); } private void setSlider(View view) { slider = view.findViewById(R.id.banner_slider1); slider.setInterval(2000); slider.setIndicatorSize(24); slider.setAnimateIndicators(true); slider.showIndicators(); slider.setSelectedSlideIndicator(ContextCompat.getDrawable(getContext(), R.drawable.selected_slide_indicator)); slider.setUnSelectedSlideIndicator(ContextCompat.getDrawable(getContext(), R.drawable.unselected_slide_indicator)); arrslides = getDataFromAsset(); slider.setAdapter(new MainSliderAdapter(arrslides)); slider.setSelectedSlide(0); slider.setLoopSlides(true); } private String[] getDataFromAsset() { String[] data = null; try { data = getActivity().getAssets().list("slide"); } catch (IOException e) { e.printStackTrace(); } return data; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.layout_order: replaceFragment(new FragmentOrder()); break; case R.id.layout_product: replaceFragment(new FragmentProducts()); break; case R.id.layout_tips: replaceFragment(new FragmentTips()); break; } } }
package com.wangcheng.base; public class HashCodeTest { public static void main(StringTest[] args) { String s = new String("ab"); System.out.println(s); System.out.println(s.hashCode()); } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.06.17 at 11:12:47 PM CEST // package io.spring.guides.gs_producing_web_service; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="id" type="{http://spring.io/guides/gs-producing-web-service}string_3_50"/> * &lt;element name="swiftBankeDuznika" type="{http://spring.io/guides/gs-producing-web-service}swiftType"/> * &lt;element name="obracunskiRacunBankeDuznika" type="{http://spring.io/guides/gs-producing-web-service}obracunskiRacunType"/> * &lt;element name="swiftBankePoverioca" type="{http://spring.io/guides/gs-producing-web-service}swiftType"/> * &lt;element name="obracunskiRacunBankePoverioca" type="{http://spring.io/guides/gs-producing-web-service}obracunskiRacunType"/> * &lt;element name="ukupanIznos" type="{http://spring.io/guides/gs-producing-web-service}decimal_15_2"/> * &lt;element name="sifraValute" type="{http://spring.io/guides/gs-producing-web-service}string_1_3"/> * &lt;element name="datum" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;element name="datumValute" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;element name="getM102Stavka" type="{http://spring.io/guides/gs-producing-web-service}m102StavkaType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "id", "swiftBankeDuznika", "obracunskiRacunBankeDuznika", "swiftBankePoverioca", "obracunskiRacunBankePoverioca", "ukupanIznos", "sifraValute", "datum", "datumValute", "getM102Stavka" }) @XmlRootElement(name = "getM102Request") public class GetM102Request { @XmlElement(required = true) protected String id; @XmlElement(required = true) protected String swiftBankeDuznika; @XmlElement(required = true) protected String obracunskiRacunBankeDuznika; @XmlElement(required = true) protected String swiftBankePoverioca; @XmlElement(required = true) protected String obracunskiRacunBankePoverioca; @XmlElement(required = true) protected BigDecimal ukupanIznos; @XmlElement(required = true) protected String sifraValute; @XmlElement(required = true) @XmlSchemaType(name = "date") protected XMLGregorianCalendar datum; @XmlElement(required = true) @XmlSchemaType(name = "date") protected XMLGregorianCalendar datumValute; @XmlElement(required = true) protected List<M102StavkaType> getM102Stavka; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the swiftBankeDuznika property. * * @return * possible object is * {@link String } * */ public String getSwiftBankeDuznika() { return swiftBankeDuznika; } /** * Sets the value of the swiftBankeDuznika property. * * @param value * allowed object is * {@link String } * */ public void setSwiftBankeDuznika(String value) { this.swiftBankeDuznika = value; } /** * Gets the value of the obracunskiRacunBankeDuznika property. * * @return * possible object is * {@link String } * */ public String getObracunskiRacunBankeDuznika() { return obracunskiRacunBankeDuznika; } /** * Sets the value of the obracunskiRacunBankeDuznika property. * * @param value * allowed object is * {@link String } * */ public void setObracunskiRacunBankeDuznika(String value) { this.obracunskiRacunBankeDuznika = value; } /** * Gets the value of the swiftBankePoverioca property. * * @return * possible object is * {@link String } * */ public String getSwiftBankePoverioca() { return swiftBankePoverioca; } /** * Sets the value of the swiftBankePoverioca property. * * @param value * allowed object is * {@link String } * */ public void setSwiftBankePoverioca(String value) { this.swiftBankePoverioca = value; } /** * Gets the value of the obracunskiRacunBankePoverioca property. * * @return * possible object is * {@link String } * */ public String getObracunskiRacunBankePoverioca() { return obracunskiRacunBankePoverioca; } /** * Sets the value of the obracunskiRacunBankePoverioca property. * * @param value * allowed object is * {@link String } * */ public void setObracunskiRacunBankePoverioca(String value) { this.obracunskiRacunBankePoverioca = value; } /** * Gets the value of the ukupanIznos property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getUkupanIznos() { return ukupanIznos; } /** * Sets the value of the ukupanIznos property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setUkupanIznos(BigDecimal value) { this.ukupanIznos = value; } /** * Gets the value of the sifraValute property. * * @return * possible object is * {@link String } * */ public String getSifraValute() { return sifraValute; } /** * Sets the value of the sifraValute property. * * @param value * allowed object is * {@link String } * */ public void setSifraValute(String value) { this.sifraValute = value; } /** * Gets the value of the datum property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDatum() { return datum; } /** * Sets the value of the datum property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDatum(XMLGregorianCalendar value) { this.datum = value; } /** * Gets the value of the datumValute property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDatumValute() { return datumValute; } /** * Sets the value of the datumValute property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDatumValute(XMLGregorianCalendar value) { this.datumValute = value; } /** * Gets the value of the getM102Stavka property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the getM102Stavka property. * * <p> * For example, to add a new item, do as follows: * <pre> * getGetM102Stavka().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link M102StavkaType } * * */ public List<M102StavkaType> getGetM102Stavka() { if (getM102Stavka == null) { getM102Stavka = new ArrayList<M102StavkaType>(); } return this.getM102Stavka; } }
/* * Copyright 2002-2023 the original author or authors. * * 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 * * https://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.springframework.aot.hint.support; import java.util.function.Consumer; import org.junit.jupiter.api.Test; import org.springframework.aot.hint.ResourceHints; import org.springframework.aot.hint.ResourcePatternHint; import org.springframework.aot.hint.ResourcePatternHints; import org.springframework.aot.hint.support.FilePatternResourceHintsRegistrar.Builder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link FilePatternResourceHintsRegistrar}. * * @author Stephane Nicoll */ class FilePatternResourceHintsRegistrarTests { private final ResourceHints hints = new ResourceHints(); @Test void configureWithNoClasspathLocation() { assertThatIllegalArgumentException().isThrownBy(FilePatternResourceHintsRegistrar::forClassPathLocations) .withMessageContaining("At least one classpath location should be specified"); } @Test void configureWithInvalidFilePrefix() { Builder builder = FilePatternResourceHintsRegistrar.forClassPathLocations(""); assertThatIllegalArgumentException().isThrownBy(() -> builder.withFilePrefixes("test*")) .withMessageContaining("cannot contain '*'"); } @Test void configureWithInvalidFileExtension() { Builder builder = FilePatternResourceHintsRegistrar.forClassPathLocations(""); assertThatIllegalArgumentException().isThrownBy(() -> builder.withFileExtensions("txt")) .withMessageContaining("should start with '.'"); } @Test void registerWithSinglePattern() { FilePatternResourceHintsRegistrar.forClassPathLocations("") .withFilePrefixes("test").withFileExtensions(".txt") .registerHints(this.hints, null); assertThat(this.hints.resourcePatternHints()).singleElement() .satisfies(includes("/", "test*.txt")); } @Test void registerWithMultipleFilePrefixes() { FilePatternResourceHintsRegistrar.forClassPathLocations("") .withFilePrefixes("test").withFilePrefixes("another") .withFileExtensions(".txt") .registerHints(this.hints, null); assertThat(this.hints.resourcePatternHints()).singleElement() .satisfies(includes("/", "test*.txt", "another*.txt")); } @Test void registerWithMultipleClasspathLocations() { FilePatternResourceHintsRegistrar.forClassPathLocations("").withClasspathLocations("META-INF") .withFilePrefixes("test").withFileExtensions(".txt") .registerHints(this.hints, null); assertThat(this.hints.resourcePatternHints()).singleElement() .satisfies(includes("/", "test*.txt", "META-INF", "META-INF/test*.txt")); } @Test void registerWithMultipleFileExtensions() { FilePatternResourceHintsRegistrar.forClassPathLocations("") .withFilePrefixes("test").withFileExtensions(".txt").withFileExtensions(".conf") .registerHints(this.hints, null); assertThat(this.hints.resourcePatternHints()).singleElement() .satisfies(includes("/", "test*.txt", "test*.conf")); } @Test void registerWithClasspathLocationWithoutTrailingSlash() { FilePatternResourceHintsRegistrar.forClassPathLocations("META-INF") .withFilePrefixes("test").withFileExtensions(".txt") .registerHints(this.hints, null); assertThat(this.hints.resourcePatternHints()).singleElement() .satisfies(includes("/", "META-INF", "META-INF/test*.txt")); } @Test void registerWithClasspathLocationWithLeadingSlash() { FilePatternResourceHintsRegistrar.forClassPathLocations("/") .withFilePrefixes("test").withFileExtensions(".txt") .registerHints(this.hints, null); assertThat(this.hints.resourcePatternHints()).singleElement() .satisfies(includes("/", "test*.txt")); } @Test void registerWithClasspathLocationUsingResourceClasspathPrefix() { FilePatternResourceHintsRegistrar.forClassPathLocations("classpath:META-INF") .withFilePrefixes("test").withFileExtensions(".txt") .registerHints(this.hints, null); assertThat(this.hints.resourcePatternHints()).singleElement() .satisfies(includes("/", "META-INF", "META-INF/test*.txt")); } @Test void registerWithClasspathLocationUsingResourceClasspathPrefixAndTrailingSlash() { FilePatternResourceHintsRegistrar.forClassPathLocations("classpath:/META-INF") .withFilePrefixes("test").withFileExtensions(".txt") .registerHints(this.hints, null); assertThat(this.hints.resourcePatternHints()).singleElement() .satisfies(includes("/", "META-INF", "META-INF/test*.txt")); } @Test void registerWithNonExistingLocationDoesNotRegisterHint() { FilePatternResourceHintsRegistrar.forClassPathLocations("does-not-exist/") .withClasspathLocations("another-does-not-exist/") .withFilePrefixes("test").withFileExtensions(".txt") .registerHints(this.hints, null); assertThat(this.hints.resourcePatternHints()).isEmpty(); } private Consumer<ResourcePatternHints> includes(String... patterns) { return hint -> { assertThat(hint.getIncludes().stream().map(ResourcePatternHint::getPattern)) .containsExactlyInAnyOrder(patterns); assertThat(hint.getExcludes()).isEmpty(); }; } }
package com.stack; import java.util.Stack; /* 逆序栈 * 要求:使用递归思想和栈操作实现 */ public class ReverseStack<E> { protected Stack<E> s; public ReverseStack(Stack<E> s) { this.s=s; } public void reverse() { if(s.isEmpty()) { return; } E temp = getBottomElement(); reverse(); s.push(temp); } private E getBottomElement() { E temp = s.pop(); if(s.isEmpty()) { return temp; }else { E last = getBottomElement(); s.push(temp); return last; } } }
/* * Copyright 2014-2023 JKOOL, LLC. * * 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.jkoolcloud.jesl.net.security; import java.io.StringReader; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * JESL access request implementation, which encapsulates JESL authentication request message. * * @version $Revision: 1 $ */ public class AccessRequest { private static final String ROOT_TAG = "access-request"; private static final String TOKEN_TAG = "token"; private static final String ROOT_ELMT = "<" + ROOT_TAG + ">"; private String token; /** * Create access request with a given access token * * @param token * access token */ public AccessRequest(String token) { this.token = token; } /** * Get access token associated with this request * * @return access token associated with this request */ public String getToken() { return token; } /** * Generate access request message * * @return access request message */ public String generateMsg() { StringBuilder msg = new StringBuilder(); msg.append("<").append(ROOT_TAG).append(">"); msg.append("<").append(TOKEN_TAG).append(">").append(token).append("</").append(TOKEN_TAG).append(">"); msg.append("</").append(ROOT_TAG).append(">"); return msg.toString(); } /** * Parse and create access request from a given string * * @param msg * access request message * @return access request object instance */ public static AccessRequest parseMsg(String msg) { try { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); AccessRequestParserHandler handler = new AccessRequestParserHandler(); parser.parse(new InputSource(new StringReader(msg)), handler); return handler.req; } catch (Exception e) { throw new SecurityException("Failed to create AccessRequest from message", e); } } /** * Is a given string message an access request message * * @param msg * access request message * @return true if given string is an access request message, false otherwise */ public static boolean isAccessRequest(String msg) { return (msg != null && msg.length() > ROOT_ELMT.length() && msg.startsWith(ROOT_ELMT, 0)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// protected static class AccessRequestParserHandler extends DefaultHandler { public AccessRequest req; protected String token; protected StringBuilder elmtValue = new StringBuilder(); @Override public void endDocument() throws SAXException { req = new AccessRequest(token); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { elmtValue.setLength(0); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (TOKEN_TAG.equals(qName)) { token = elmtValue.toString(); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { elmtValue.append(ch, start, length); } } }
public class ATM { private BankNetwork network; private Keyboard keyboard; private NFCReader nfcReader; private CardReader cardReader; private Printer printer; private CashDispenser cashDispenser; private Screen screen; public ATM() { network = new BankNetwork(); keyboard = new Keyboard(); nfcReader = new NFCReader(); cardReader = new CardReader(); printer = new Printer(); cashDispenser = new CashDispenser(); screen = new Screen(); } private void deposit() { screen.depositCash(); try { network.changeBalance(false, keyboard.getEnteredAmount()); } catch (Exception e) { screen.invalidWithdrawCash(); } //it will never throw } private void withdrawal() { screen.withdrawCash(); double amount = keyboard.getEnteredAmount(); try { network.changeBalance(false, -amount); cashDispenser.dispenseCash(amount); } catch (Exception e) { screen.invalidWithdrawCash(); } } private void checkBalance() { //checks balance of current card number screen.accountSelect(); int c = keyboard.getSelectedOption(2); screen.checkBalance(network.getBalance(c != 1)); } private void depositCheque() { screen.depositCheque(); try { network.changeBalance(false, keyboard.getEnteredAmount()); } catch (Exception e) { screen.invalidWithdrawCash(); } //it will never throw } public boolean run() { boolean ifCard = false; screen.initialScreen(); int choice = keyboard.getSelectedOption(2); switch (choice) { case 1: ifCard = true; screen.accountNumber(); cardReader.validateCard(keyboard.getEnteredNumber()); screen.cardVerification(); network.verifyPin(cardReader.getCardNumber(), keyboard.getEnteredPin()); break; case 2: screen.accountNumber(); nfcReader.validateNFC(keyboard.getEnteredNumber()); screen.phoneVerification(); network.verifyPin(nfcReader.getNFCNumber(), keyboard.getEnteredPin()); } screen.validated(); boolean go = true; while (go) { screen.displayMenu(); choice = keyboard.getSelectedOption(6); switch (choice) { case 1: //deposit cash deposit(); break; case 2: //deposit chequhqe depositCheque(); break; case 3: //withd cash withdrawal(); break; case 4: //check balance checkBalance(); break; case 5: //trasfera b double amount; screen.transferFunds1(); choice = keyboard.getSelectedOption(2); screen.transferFunds2(); amount = keyboard.getEnteredAmount(); try { network.changeBalance(choice != 1, -amount); } catch (Exception e) { screen.invalidWithdrawCash(); } try { network.changeBalance(choice == 1, amount); } catch (Exception e) { screen.invalidWithdrawCash(); } break; case 6: //exit go = false; } } screen.printDetails(); choice = keyboard.getSelectedOption(3); if (choice == 1) { int accountNumber = ifCard ? cardReader.getCardNumber() : nfcReader.getNFCNumber(); printer.printReceipt(accountNumber, network.getBalance(false), network.getBalance(true)); } if (choice == 3) { return false; } if (ifCard) { screen.returnCard(); cardReader.returnCard(); } screen.done(); return true; } //private viewTransactions() {} public static void main (String[] args) { ATM atm = new ATM(); while(atm.run()); } }
public class BattleSystem { public BattleSystem(){ } public int dealtDamage(UserChar u, Enemy e, int t){ int str = 0, def = 0, dmg; if(t == 0){ // enemy's turn str = e.returnStr(); def = u.returnDef(); } else if(t == 1){ // player's turn str = u.returnStr(); def = e.returnDef(); } dmg = str - def; if(dmg < 0) { // if damage is negative dmg = 0; } if(t == 0){ // enemy deals damage u.sustainDamage(dmg); } else if(t == 1){ // player deals damage e.sustainDamage(dmg); } return dmg; } public int dodgeAttack(UserChar u, Enemy e, int t){ int spd1 = 0, spd2 = 1; // indicators speeds for player and enemy double chance; // holds value for chance of missing/attacking double rand = Math.random(); // holds random value to compare with chance if(t == 0){ // if enemy's turn // if player has no speed or enemy has more spd than player if(u.returnSpd() == 0 || e.returnSpd() >= u.returnSpd()){ return 1; } // enemy's spd / player's spd spd1 = e.returnSpd(); spd2 = u.returnSpd(); } else if (t == 1){ // if player's turn // if enemy has no speed or player has more spd than player if(e.returnSpd() == 0 || u.returnSpd() >= e.returnSpd()){ return 1; } // player's spd / enemy's spd spd1 = u.returnSpd(); spd2 = e.returnSpd(); } chance = (double)spd1 / (double)spd2; if(chance < rand){ // if attack misses return 0; } return 1; // attack went through } }
package kr.or.ddit.riskboard.controller; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import kr.or.ddit.profile_file.service.IProfileFileService; import kr.or.ddit.project.service.IProjectService; import kr.or.ddit.riskboard.service.IRiskboardService; import kr.or.ddit.timeline.service.ITimelineService; import kr.or.ddit.vo.ProfileFileVO; import kr.or.ddit.vo.ProjectParticipantsVO; import kr.or.ddit.vo.Project_ProjectParticipantsVO; import kr.or.ddit.vo.RiskJoinVO; import kr.or.ddit.vo.RiskboardCommentVO; import kr.or.ddit.vo.RiskboardVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.sun.org.apache.bcel.internal.generic.Select; @Controller @RequestMapping("user/riskboard") public class RiskboardController{ @Autowired private IRiskboardService riskboardservice; @Autowired private IProfileFileService profileservice; @Autowired private IProjectService projectService; @Autowired private ITimelineService timelineService; @RequestMapping("riskboardList") public ModelAndView riskList(HttpServletRequest request, ModelAndView modelView, Map<String, String>params, @RequestParam String project_no, String risk_no) throws Exception{ params.put("project_no", project_no); List<RiskJoinVO> riskboardList = this.riskboardservice.riskboardList(params); Map<String, String> projectInfo = projectService.selectProjectInfo(params); modelView.addObject("breadcrumb_title", "프로젝트"); modelView.addObject("breadcrumb_first", "위험 관리 게시판"); modelView.addObject("breadcrumb_first_url", request.getContextPath() + "/user/riskboard/riskboardList.do?project_no=" + project_no); modelView.addObject("riskboardList", riskboardList); modelView.addObject("projectInfo", projectInfo); modelView.setViewName("user/riskboard/riskboardList"); return modelView; } @RequestMapping("riskboardForm") public ModelAndView riskboardForm(HttpServletRequest request, ModelAndView modelView, String project_no) throws Exception{ modelView.addObject("breadcrumb_title" , "프로젝트"); modelView.addObject("breadcrumb_first", "위험 관리 게시판"); modelView.addObject("breadcrumb_first_url", request.getContextPath() + "/user/riskboard/riskboardList.do?project_no=" + project_no); modelView.addObject("breadcrumb_second", "위험 관리 게시글 등록"); modelView.setViewName("user/riskboard/riskboardForm"); return modelView; } @RequestMapping("riskboardView") public ModelAndView riskboardView(ModelAndView modelView, String risk_no, String mem_id, String project_no, String risk_errorstatus, HttpServletRequest request) throws Exception{ modelView.addObject("breadcrumb_title", "프로젝트"); modelView.addObject("breadcrumb_first", "위험 관리 게시판"); modelView.addObject("breadcrumb_first_url", request.getContextPath() + "/user/riskboard/riskboardList.do?project_no=" + project_no); modelView.addObject("breadcrumb_second", "위험 관리 게시글 보기"); Map<String, String> params = new HashMap<String, String>(); params.put("risk_no", risk_no); params.put("mem_id", mem_id); params.put("project_no", project_no); params.put("risk_errorstatus", risk_errorstatus); RiskboardVO riskboardInfo = riskboardservice.riskboardInfo(params); List<RiskboardCommentVO> commentList = riskboardservice.commentList(params); riskboardservice.updateHit(params); ProfileFileVO profileInfo = profileservice.selectProfileFileInfo(params); modelView.addObject("profileInfo", profileInfo); modelView.addObject("commentList", commentList); modelView.addObject("riskboardInfo", riskboardInfo); return modelView; } @RequestMapping("insertRiskboard") public String insertRiskboard(HttpServletRequest request, HttpServletResponse response, String risk_title, String risk_content, String project_no, String mem_id, String risk_errorstatus, String timeline_title, String timeline_content, String timeline_tag, String timeline_category)throws Exception{ Map<String, String> no = new HashMap<String, String>(); no.put("project_no", project_no); RiskboardVO riskboardInfo = new RiskboardVO(); riskboardInfo.setProject_no(project_no); riskboardInfo.setMem_id(mem_id); riskboardInfo.setRisk_title(risk_title); riskboardInfo.setRisk_content(risk_content); riskboardInfo.setRisk_errorstatus(risk_errorstatus); riskboardservice.insertRiskboard(riskboardInfo); Map<String, String> projectInfo = projectService.selectProjectInfo(no); List<String> list = new ArrayList<String>(); if (projectInfo.get("PL") != null) { list.add(String.valueOf(projectInfo.get("PL"))); } if (projectInfo.get("DA") != null) { list.add(String.valueOf(projectInfo.get("DA"))); } if (projectInfo.get("TA") != null) { list.add(String.valueOf(projectInfo.get("TA"))); } if (projectInfo.get("UA") != null) { list.add(String.valueOf(projectInfo.get("UA"))); } if (projectInfo.get("AA") != null) { list.add(String.valueOf(projectInfo.get("AA"))); } if (projectInfo.get("MEM_ID") != null) { list.add(String.valueOf(projectInfo.get("MEM_ID"))); } for (int i = 0; i < list.size(); i++) { Map<String, String> params = new HashMap<String, String>(); params.put("mem_id",list.get(i)); params.put("project_no", project_no); params.put("timeline_title", "위험요소 발생"); params.put("timeline_content", "새로운 위험요소가 등록되었습니다"); params.put("timeline_tag", "RISK"); params.put("timeline_category", "N"); timelineService.insertTimeline(params); } String taskResult = null; String message = null; taskResult = "success"; message = URLEncoder.encode("게시글이 정상적으로 등록되었습니다.", "UTF-8"); return "redirect:/user/riskboard/riskboardList.do?project_no=" + project_no + "&taskResult=" + taskResult + "&message" + message; } @RequestMapping("updateRiskboard") public String updateRiskboard(RiskboardVO riskboardInfo, String project_no)throws Exception{ int chk = riskboardservice.updateRiskboard(riskboardInfo); String taskResult = null; String message = null; if (chk > 0){ taskResult = "success"; message = URLEncoder.encode("게시글이 정상적으로 수정되었습니다", "UTF-8"); }else{ taskResult = "warning"; message = URLEncoder.encode("게시글 수정에 실패했습니다", "UTF-8"); } return "redirect:/user/riskboard/riskboardList.do?taskResult=" + taskResult + "&message=" + message + "&project_no=" + project_no; } @RequestMapping("deleteRiskboard") public String deleteRiskboard(String risk_no, String project_no) throws Exception{ Map<String, String> params = new HashMap<String, String>(); params.put("risk_no", risk_no); params.put("project_no", project_no); int chk = riskboardservice.deleteRiskboard(params); String taskResult = null; String message = null; if (chk > 0) { taskResult = "success"; message = URLEncoder.encode("게시글이 정상적으로 삭제되었습니다.", "UTF-8"); } else { taskResult = "warning"; message = URLEncoder.encode("게시글 삭제에 실패했습니다.", "UTF-8"); } return "redirect:/user/riskboard/riskboardList.do?taskResult=" + taskResult + "&message=" + message + "&project_no=" + project_no; } @RequestMapping("insertriskComment") public String insertissueComment(RiskboardCommentVO riskcommentInfo ,String project_no) throws Exception{ int chk = riskboardservice.insertComment(riskcommentInfo); String taskResult = null; String message = null; if (chk > 0){ taskResult = "success"; message = URLEncoder.encode("댓글이 정상적으로 등록되었습니다.", "UTF-8"); }else{ taskResult = "warning"; message = URLEncoder.encode("댓글 등록에 실패했습니다", "UTF-8"); } return "redirect:/user/riskboard/riskboardView.do?taskResult=" + taskResult + "&message=" + message + "&risk_no=" + riskcommentInfo.getRisk_no() + "&mem_id=" + riskcommentInfo.getMem_id() + "&project_no=" + project_no; } @RequestMapping("updateriskComment") public String updateriskComment(String comment_seq, String risk_no, String mem_id, String comment_content, String project_no) throws Exception{ Map<String, String> params = new HashMap<String, String>(); params.put("comment_seq", comment_seq); params.put("comment_content", comment_content); params.put("project_no", project_no); int chk = riskboardservice.updateComment(params); String taskResult = null; String message = null; if (chk > 0) { taskResult = "success"; message = URLEncoder.encode("댓글이 정상적으로 수정되었습니다.", "UTF-8"); } else { taskResult = "warning"; message = URLEncoder.encode("댓글 수정에 실패했습니다.", "UTF-8"); } return "redirect:/user/riskboard/riskboardView.do?taskResult=" + taskResult + "&message=" + message + "&risk_no=" + risk_no + "&mem_id=" + mem_id + "&project_no=" + project_no; } @RequestMapping("deleteriskComment") public String deleteriskComment(String comment_seq, String risk_no, String mem_id, String project_no) throws Exception{ Map<String, String> params = new HashMap<String, String>(); params.put("comment_seq", comment_seq); params.put("project_no", project_no); int chk = riskboardservice.deleteComment(params); String taskResult = null; String message = null; if (chk > 0) { taskResult = "success"; message = URLEncoder.encode("댓글이 정상적으로 삭제되었습니다.", "UTF-8"); } else { taskResult = "warning"; message = URLEncoder.encode("댓글 삭제에 실패했습니다.", "UTF-8"); } return "redirect:/user/riskboard/riskboardView.do?taskResult" + taskResult + "&message" + message + "&risk_no=" + risk_no + "&mem_id=" + mem_id + "&project_no=" + project_no ; } @RequestMapping("updateErrorStatus") public String updateErrorStatus (HttpServletRequest request, HttpServletResponse response, RiskboardVO riskboardInfo, String risk_errorstatus, String project_no, String mem_id, String timeline_content, String timeline_category, String timeline_tag, String timeline_title) throws Exception{ int chk = riskboardservice.updateErrorStatus(riskboardInfo); String taskResult = null; String message = null; if (chk > 0){ taskResult = "success"; message = URLEncoder.encode("게시글이 정상적으로 수정되었습니다", "UTF-8"); }else{ taskResult = "warning"; message = URLEncoder.encode("게시글 수정에 실패했습니다", "UTF-8"); } Map<String, String> no = new HashMap<String, String>(); no.put("project_no", project_no); Map<String, String> projectInfo = projectService.selectProjectInfo(no); List<String> list = new ArrayList<String>(); if (projectInfo.get("PL") != null) { list.add(String.valueOf(projectInfo.get("PL"))); } if (projectInfo.get("DA") != null) { list.add(String.valueOf(projectInfo.get("DA"))); } if (projectInfo.get("TA") != null) { list.add(String.valueOf(projectInfo.get("TA"))); } if (projectInfo.get("UA") != null) { list.add(String.valueOf(projectInfo.get("UA"))); } if (projectInfo.get("AA") != null) { list.add(String.valueOf(projectInfo.get("AA"))); } if (projectInfo.get("MEM_ID") != null) { list.add(String.valueOf(projectInfo.get("MEM_ID"))); } for (int i = 0; i < list.size(); i++) { Map<String, String> params = new HashMap<String, String>(); params.put("mem_id", list.get(i)); params.put("project_no", project_no); params.put("timeline_title", "위험요소 해결" ); params.put("timeline_content", "위험요소가 해결되었습니다"); params.put("timeline_tag", "RISK"); params.put("timeline_category", "Y"); timelineService.insertTimeline(params); } return "redirect:/user/riskboard/riskboardList.do?taskResult=" + taskResult + "&message=" + message + "&project_no=" + project_no; } }
package com.lipnus.gleam.etc; import android.content.Context; import android.graphics.drawable.ColorDrawable; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.Hashtable; import java.util.Map; /** * Created by Sunpil on 2017-02-26. */ public class VolleyConnect { //resonse 리스너(즉각 결과가 나오는게 아니고, 접속이 끝나야 결과가 나오므로 호출하는 곳에서는 리스너로 받아야 한다) IVolleyResult mResultCallback = null; Context context; //이걸 호출한 곳의컨텍스트 private String UPLOAD_URL; //접속주소 private Map<String,String> params = new Hashtable<String, String>(); //post할 데이터들을 모아놓은 MAP private int dialongOption; //생성자 public VolleyConnect(IVolleyResult resultCallback, Context context, String url, Map<String, String> parmas){ mResultCallback = resultCallback; this.context = context; this.UPLOAD_URL = url; this.params = parmas; //다이얼로그는 보임 this.dialongOption = 0; ConnectServer(); } //Dialong에 대한 옵션을 지정하고 싶을 때 호출하는 생성자 public VolleyConnect(IVolleyResult resultCallback, Context context, String url, Map<String, String> parmas, int dialogOption){ mResultCallback = resultCallback; this.context = context; this.UPLOAD_URL = url; this.params = parmas; this.dialongOption = dialogOption; ConnectServer(); } //volley를 이용하여 서버에 접속 private void ConnectServer(){ final CustomDialog customDialog = new CustomDialog(context); //커스터마이징 프로그래스다이얼로그 customDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); //다이얼로그 뒷배경투명처리 if(dialongOption==0){ customDialog.setCancelable(false);//끌 수 없다 customDialog.show(); // 보여주기 }else if(dialongOption ==1) { customDialog.setCanceledOnTouchOutside(false); //바깥을 눌러서는 꺼지지 않음 customDialog.setCancelable(true);//취소누르면 꺼짐 customDialog.show(); // 보여주기 }else if(dialongOption==2){ //Dialong사용하지 않음 } StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL, new Response.Listener<String>() { @Override public void onResponse(String s) { customDialog.dismiss(); //결과값은 s; //결과값을 리스너를 통해 전달 if(mResultCallback != null){ mResultCallback.notifySuccess(s); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { customDialog.dismiss(); //결과값을 리스너를 통해 전달 if(mResultCallback != null){ mResultCallback.notifyError(volleyError); } } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { //보내는 부분 return params; } }; //Creating a Request Queue RequestQueue requestQueue = Volley.newRequestQueue(context); //Adding request to the queue requestQueue.add(stringRequest); } }
package redempt.crunch.exceptions; public class ExpressionEvaluationException extends RuntimeException { public ExpressionEvaluationException(String message) { super(message); } }
package edu.mit.cameraCulture.vblocks.predefined; import java.util.Random; import java.util.Vector; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.imgproc.Imgproc; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Rect; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import edu.mit.cameraCulture.vblocks.EngineActivity; import edu.mit.cameraCulture.vblocks.Module; import edu.mit.cameraCulture.vblocks.ModuleTouchListener; import edu.mit.cameraCulture.vblocks.Sample; public class Grader extends Module { public static final String REGISTER_SERVICE_NAME = "Grader"; private int appState; private ModuleTouchListener listener; private Mat baseMatBW; private Mat tempMat; private int[] image8888; private int imgWidth; private int imgHeight; // vector<questions < fill boxes < box corners > > > private Vector<Vector<Vector<Point>>> questions; private Vector<Integer> teacherAnsw; private Vector<Integer> studentAnsw; private Random rand; private int histBase[]; private int histTarg[]; private int studentGrade; private GraderView view; public Grader() { super(REGISTER_SERVICE_NAME); } private static void decodeYUV420SP(int[] rgb, byte[] yuv420sp, int width, int height) { final int frameSize = width * height; for (int j = 0, yp = 0; j < height; j++) { int uvp = frameSize + (j >> 1) * width, u = 0, v = 0; for (int i = 0; i < width; i++, yp++) { int y = (0xff & ((int) yuv420sp[yp])) - 16; if (y < 0) y = 0; if ((i & 1) == 0) { v = (0xff & yuv420sp[uvp++]) - 128; u = (0xff & yuv420sp[uvp++]) - 128; } int y1192 = 1192 * y; int r = (y1192 + 1634 * v); int g = (y1192 - 833 * v - 400 * u); int b = (y1192 + 2066 * u); if (r < 0) r = 0; else if (r > 262143) r = 262143; if (g < 0) g = 0; else if (g > 262143) g = 262143; if (b < 0) b = 0; else if (b > 262143) b = 262143; rgb[yp] = 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) & 0xff00) | ((b >> 10) & 0xff); } } } @Override public ExecutionCode execute(Sample image) { // convert image to RGB if (image8888 == null) { imgWidth = image.getWidth(); imgHeight = image.getHeight(); image8888 = new int[imgWidth * imgHeight]; } synchronized (image8888) { decodeYUV420SP(image8888, image.getImageData(), imgWidth, imgHeight); } view.postInvalidate(); // Log.d("Grader","executed"); return null; } @Override public ModuleTouchListener getModuleTouchListener() { return listener; } public void onCreate(EngineActivity context) { super.onCreate(context); tempMat = new Mat(); baseMatBW = new Mat(); questions = new Vector<Vector<Vector<Point>>>(); teacherAnsw = new Vector<Integer>(); studentAnsw = new Vector<Integer>(); studentGrade = -1; rand = new Random(); histBase = new int[2]; histTarg = new int[2]; appState = 0; view = new GraderView(context); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); context.getLayout().addView(view, lp); } @Override public void onDestroyModule() { super.onDestroyModule(); } @Override public String getName() { return "Grader"; } public static String getModuleName() { return "Grader"; } @Override protected void onHandleIntent(Intent intent) { } public static final Parcelable.Creator<Grader> CREATOR = new Parcelable.Creator<Grader>() { public Grader createFromParcel(Parcel in) { Log.v("ParcelableTest", "Creating from parcel"); return new Grader(); } public Grader[] newArray(int size) { return new Grader[size]; } }; private float calHistogramDiff(int[] histBase, int[] histTarg, float divVal) { float val = (float) Math.sqrt((histBase[0] - histTarg[0]) * (histBase[0] - histTarg[0]) + (histBase[1] - histTarg[1]) * (histBase[1] - histTarg[1])); return (val / divVal); } private float getHist(Mat bwMat, int[] hist, Vector<Point> sqPoints) { int i0 = 0; int i1 = 0; int minX = (int) sqPoints.get(0).x; if (minX > sqPoints.get(1).x) minX = (int) sqPoints.get(1).x; int maxX = (int) sqPoints.get(0).x; if (maxX < sqPoints.get(1).x) maxX = (int) sqPoints.get(1).x; int minY = (int) sqPoints.get(0).y; if (minY > sqPoints.get(1).y) minY = (int) sqPoints.get(1).y; int maxY = (int) sqPoints.get(0).y; if (maxY < sqPoints.get(1).y) maxY = (int) sqPoints.get(1).y; for (int i = minX; i < maxX; i++) { for (int j = minY; j < maxY; j++) { if (bwMat.get(j, i)[0] > 50.0) i1++; else i0++; } } hist[0] = i0; hist[1] = i1; return (maxX - minX) * (maxY - minY); } private int getStudentGrade(Mat img) { float qVal = -1; int maxQ = 0; float maxQVal = -1; int grade = 0; studentAnsw.clear(); for (int i = 0; i < questions.size(); i++) { Vector<Vector<Point>> ques = questions.get(i); maxQVal = -1; qVal = -1; maxQ = 0; for (int j = 0; j < ques.size(); j++) { float rectArea = 1.0f * getHist(img, histTarg, ques.get(j)); getHist(baseMatBW, histBase, ques.get(j)); qVal = calHistogramDiff(histBase, histTarg, rectArea); if (qVal > maxQVal) { maxQ = j; maxQVal = qVal; } } studentAnsw.add(new Integer(maxQ)); if (maxQ == teacherAnsw.get(i).intValue()) grade++; // teacherAnsw.add(new Integer(maxQ)); } Log.d("grader", "student grade = " + grade); return grade; } private void getTeacherAnsw(Mat img) { float qVal = -1; int maxQ = 0; float maxQVal = -1; teacherAnsw.clear(); for (int i = 0; i < questions.size(); i++) { Vector<Vector<Point>> ques = questions.get(i); maxQVal = -1; qVal = -1; maxQ = 0; for (int j = 0; j < ques.size(); j++) { float rectArea = 1.0f * getHist(img, histTarg, ques.get(j)); getHist(baseMatBW, histBase, ques.get(j)); qVal = calHistogramDiff(histBase, histTarg, rectArea); if (qVal > maxQVal) { maxQ = j; maxQVal = qVal; } } teacherAnsw.add(new Integer(maxQ)); } } class GraderView extends View { private Vector<Integer> qColors; private int displayW; // button corners private Vector<Point> actionButton; private int actBColor; private Vector<Point> nextQbutton; private int nQBColor; private Point center; private Point lineP1; private Point lineP2; private int gScalar; private int rScalar; private Point textPos; private Rect imgSize; private Rect screenSize; // for touch interaction private Vector<Point> q; private Bitmap background; private Paint paint; private Bitmap bkCopy; private int touchState; public GraderView(Context context) { super(context); displayW = getWidth(); qColors = new Vector<Integer>(); actBColor = Color.rgb(255, 0, 0); nQBColor = Color.rgb(0, 255, 0); center = new Point(); lineP1 = new Point(); lineP2 = new Point(); rScalar = Color.rgb(250, 0, 0); gScalar = Color.rgb(0, 250, 0); textPos = new Point(0, 50); q = new Vector<Point>(); paint = new Paint(); touchState = 0; listener = new ModuleTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int imgX = (int) (imgWidth * (1.0 * event.getX() / getWidth())); int imgY = (int) (imgHeight * (1.0 * event.getY() / getHeight())); int x = (int) event.getX(); int y = (int) event.getY(); Log.d("Grader", "touch = " + x + "," + y + " of " + imgWidth + "," + imgHeight); if (appState == 0) { if (insideButton(actionButton, x, y)) { if (image8888 != null) { imgSize = new Rect(0, 0, imgWidth, imgHeight); background = Bitmap.createBitmap(image8888, imgWidth, imgHeight, Bitmap.Config.ARGB_8888); Mat gray = new Mat(); Mat img = new Mat(); Utils.bitmapToMat(background, img); Imgproc.cvtColor(img, gray, Imgproc.COLOR_RGB2GRAY); Imgproc.threshold(gray, baseMatBW, 5, 200, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU); questions.add(new Vector<Vector<Point>>()); qColors.add(new Integer(Color.rgb( rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)))); appState = 1; Log.d("Grader", "to state 1"); view.postInvalidate(); } } } else if (appState == 1) { if (((event.getAction() == MotionEvent.ACTION_DOWN) || (event .getAction() == MotionEvent.ACTION_POINTER_DOWN))) { if (insideButton(actionButton, x, y)) { appState = 2; view.postInvalidate(); } else if (insideButton(nextQbutton, x, y)) { questions.add(new Vector<Vector<Point>>()); qColors.add(new Integer(Color.rgb( rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)))); Log.d("Grader", "new Q created"); view.postInvalidate(); } else { if (touchState == 0) { touchState = 1; q = new Vector<Point>(); q.add(new Point(imgX, imgY)); } else { touchState = 0; q.add(new Point(imgX, imgY)); Vector<Vector<Point>> lastQ = questions .get(questions.size() - 1); lastQ.add(q); Log.d("Grader", "new field created"); } view.postInvalidate(); } } } else if (appState == 2) { if (insideButton(actionButton, x, y) && (teacherAnsw.size() == questions.size())) { appState = 3; view.postInvalidate(); } else if (insideButton(nextQbutton, x, y)) { background = Bitmap.createBitmap(image8888, imgWidth, imgHeight, Bitmap.Config.ARGB_8888); Mat gray = new Mat(); Mat img = new Mat(); Mat frameBW = new Mat(); Utils.bitmapToMat(background, img); Imgproc.cvtColor(img, gray, Imgproc.COLOR_RGB2GRAY); Imgproc.threshold(gray, frameBW, 5, 200, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU); getTeacherAnsw(frameBW); String anwsS = "("; for (int i = 0; i < questions.size(); i++) anwsS += (teacherAnsw.get(i).intValue() + 1) + ","; anwsS += ")"; Log.d("Grader", anwsS); view.postInvalidate(); } } else if (appState == 3) { if (insideButton(actionButton, x, y) && (teacherAnsw.size() == questions.size())) { background = Bitmap.createBitmap(image8888, imgWidth, imgHeight, Bitmap.Config.ARGB_8888); Mat gray = new Mat(); Mat img = new Mat(); Mat frameBW = new Mat(); Utils.bitmapToMat(background, img); Imgproc.cvtColor(img, gray, Imgproc.COLOR_RGB2GRAY); Imgproc.threshold(gray, frameBW, 5, 200, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU); studentGrade = getStudentGrade(frameBW); view.postInvalidate(); } } return true; } @Override public boolean onSingleTapConfirmed(MotionEvent arg0) { // TODO Auto-generated method stub return false; } @Override public boolean onDoubleTapEvent(MotionEvent arg0) { // TODO Auto-generated method stub return false; } @Override public boolean onDoubleTap(MotionEvent arg0) { // TODO Auto-generated method stub return false; } @Override public void onClick(View arg0) { // TODO Auto-generated method stub } }; this.setOnTouchListener(listener); } boolean insideButton(Vector<Point> corners, float x, float y) { if ((x > corners.get(0).x) && (x < corners.get(1).x) && (y > corners.get(0).y) && (y < corners.get(1).y)) return true; else return false; } protected void onDraw(Canvas canvas) { // Log.d("Grader","draw"); // if((image8888 != null) && (background == null)) background = // Bitmap.createBitmap(image8888, imgWidth, imgHeight, // Bitmap.Config.ARGB_8888); // if(background != null) background.setPixels(image8888, 0, 1, 0, // 0, imgWidth, imgHeight); // if (displayW != getWidth()) { int width = this.getWidth(); int height = this.getHeight(); actionButton = new Vector<Point>(); actionButton.add(new Point(width - 80, height - 80)); actionButton.add(new Point(width, height)); nextQbutton = new Vector<Point>(); nextQbutton.add(new Point(width - 160, height - 80)); nextQbutton.add(new Point(width - 80, height)); screenSize = new Rect(0, 0, width, height); } // if(image8888 != null) background = Bitmap.createBitmap(image8888, // imgWidth, imgHeight, Bitmap.Config.ARGB_8888); paint.setARGB(255, 255, 255, 255); if (appState == 0) { if (image8888 != null) { // canvas.drawBitmap(background, 0, 0, paint); paint.setColor(actBColor); paint.setStyle(Style.FILL); paint.setColor(rScalar); paint.setStrokeWidth(3); paint.setTextSize(10); canvas.drawText("Capture the blank sheet", (float) textPos.x, (float) textPos.y, paint); canvas.drawRect((float) actionButton.get(0).x, (float) actionButton.get(0).y, (float) actionButton.get(1).x, (float) actionButton.get(1).y, paint); // canvas.drawRect(0, 0, 80, 80,paint); } } else if (appState == 1) { canvas.drawBitmap(background, imgSize, screenSize, paint); paint.setStyle(Style.FILL); paint.setColor(actBColor); canvas.drawRect((float) actionButton.get(0).x, (float) actionButton.get(0).y, (float) actionButton.get(1).x, (float) actionButton.get(1).y, paint); paint.setColor(nQBColor); canvas.drawRect((float) nextQbutton.get(0).x, (float) nextQbutton.get(0).y, (float) nextQbutton.get(1).x, (float) nextQbutton.get(1).y, paint); paint.setColor(rScalar); paint.setStrokeWidth(3); paint.setTextSize(25); canvas.drawText("select the checkbox positions", (float) textPos.x, (float) textPos.y, paint); // draw the rects; drawQs(canvas); } else if (appState == 2) { paint.setStyle(Style.FILL); paint.setColor(actBColor); if (teacherAnsw.size() > 0) canvas.drawRect((float) actionButton.get(0).x, (float) actionButton.get(0).y, (float) actionButton.get(1).x, (float) actionButton.get(1).y, paint); paint.setColor(nQBColor); canvas.drawRect((float) nextQbutton.get(0).x, (float) nextQbutton.get(0).y, (float) nextQbutton.get(1).x, (float) nextQbutton.get(1).y, paint); paint.setColor(rScalar); paint.setStrokeWidth(3); paint.setTextSize(25); canvas.drawText("Capture teachers answers", (float) textPos.x, (float) textPos.y, paint); // draw the rects; drawQs(canvas); } else if (appState == 3) { paint.setStyle(Style.FILL); paint.setColor(actBColor); canvas.drawRect((float) actionButton.get(0).x, (float) actionButton.get(0).y, (float) actionButton.get(1).x, (float) actionButton.get(1).y, paint); drawQs(canvas); if (studentAnsw.size() == questions.size()) drawStudentRes(canvas); } // this.postInvalidateDelayed(60); } private void drawStudentRes(Canvas canvas) { float aspectX = (1.0f * screenSize.right) / (1.0f * imgWidth); float aspectY = (1.0f * screenSize.bottom) / (1.0f * imgHeight); Vector<Point> field; paint.setStyle(Style.STROKE); for (int i = 0; i < questions.size(); i++) { field = questions.get(i).get(studentAnsw.get(i).intValue()); if (studentAnsw.get(i).intValue() == teacherAnsw.get(i) .intValue()) { paint.setColor(gScalar); paint.setStrokeWidth(6); float centerX = (float) (aspectX * field.get(0).x + aspectX * field.get(1).x) / 2.0f; float centerY = (float) (aspectY * field.get(0).y + aspectY * field.get(1).y) / 2.0f; float radius = (float) (1.15f * (Math.abs(aspectX * field.get(0).x - aspectX * field.get(1).x) / 2.0f)); canvas.drawCircle(centerX, centerY, radius, paint); } else { lineP1.x = aspectX * field.get(0).x; lineP1.y = aspectY * field.get(1).y; lineP2.x = aspectX * field.get(1).x; lineP2.y = aspectY * field.get(0).y; paint.setColor(rScalar); paint.setStrokeWidth(6); canvas.drawLine((float) (aspectX * field.get(0).x), (float) (aspectY * field.get(0).y), (float) (aspectX * field.get(1).x), (float) (aspectY * field.get(1).y), paint); canvas.drawLine((float) lineP1.x, (float) lineP1.y, (float) lineP2.x, (float) lineP2.y, paint); } } String gradeString = "" + studentGrade + "|" + questions.size(); paint.setColor(rScalar); paint.setStrokeWidth(3); paint.setTextSize(50); canvas.drawText(gradeString, (float) textPos.x, (float) textPos.y, paint); } private void drawQs(Canvas canvas) { float aspectX = (1.0f * screenSize.right) / (1.0f * imgWidth); float aspectY = (1.0f * screenSize.bottom) / (1.0f * imgHeight); paint.setStyle(Style.STROKE); paint.setStrokeWidth(2); for (int i = 0; i < questions.size(); i++) { paint.setColor(qColors.get(i)); Vector<Vector<Point>> questFields = questions.get(i); for (int j = 0; j < questFields.size(); j++) { Vector<Point> field = questFields.get(j); if (field.size() > 1) { if ((teacherAnsw.size() > 0)) { if (teacherAnsw.get(i) != j) { canvas.drawRect( (float) (aspectX * field.get(0).x), (aspectY * (float) field.get(0).y), (float) (aspectX * field.get(1).x), (float) (aspectY * field.get(1).y), paint); } else { float centerX = (float) (aspectX * field.get(0).x + aspectX * field.get(1).x) / 2.0f; float centerY = (float) (aspectY * field.get(0).y + aspectY * field.get(1).y) / 2.0f; float radius = (float) Math.abs(aspectX * field.get(0).x - aspectX * field.get(1).x) / 2.0f; canvas.drawCircle(centerX, centerY, radius, paint); } } else canvas.drawRect((float) (aspectX * field.get(0).x), (aspectY * (float) field.get(0).y), (float) (aspectX * field.get(1).x), (float) (aspectY * field.get(1).y), paint); } } } } } }
package service; import com.sparsity.sparksee.algorithms.SinglePairShortestPathDijkstra; import com.sparsity.sparksee.gdb.*; /** * Created by qiaoruixiang on 14/06/2017. */ public class RouteGenerator { //private Context mContext; public RouteGenerator() { } /* public RouteGenerator(Context context) { mContext = context; } */ public String generateRoute(double fromLat, double fromLon, double toLat, double toLon, int day, int time) { String result = ""; Session session = SparkseeFactory.getInstance().getSession(); Graph g = session.getGraph(); Value value = new Value(); int poiType = g.findType("POI"); int poiIdType = g.findAttribute(poiType, "ID"); int poiDurationType = g.findAttribute(poiType, "DURATION"); int poiScoreType = g.findAttribute(poiType, "BASE_SCORE"); int poiHighlightType = g.findAttribute(poiType, "HIGHLIGHT"); int venueType = g.findType("VENUE"); int venueLatitudeType = g.findAttribute(venueType, "LATITUDE"); int venueLongitudeType = g.findAttribute(venueType, "LONGITUDE"); int categoryType = g.findType("CATEGORY"); int categoryNameType = g.findAttribute(categoryType, "NAME"); int stopType = g.findType("STOP"); int stopIdType = g.findAttribute(stopType, "ID"); int stopLatitudeType = g.findAttribute(stopType, "LATITUDE"); int stopLongitudeType = g.findAttribute(stopType, "LONGITUDE"); int scoringType = g.findType("SCORING"); int scoringScoreType = g.findAttribute(scoringType, "SCORE"); int runType = g.findType("RUN"); int runDayType = g.findAttribute(runType, "DAY"); int runOpenType = g.findAttribute(runType, "OPEN_TIME"); int runCloseType = g.findAttribute(runType, "CLOSE_TIME"); int routeType = g.findType("ROUTE"); int routeDurationType = g.findAttribute(routeType, "DURATION"); int routeModeType = g.findAttribute(routeType, "MODE"); int routeIdType = g.findAttribute(routeType, "ROUTE_ID"); int auxiliaryType = g.findType("AUXILIARY"); int auxiliaryNameType = g.findAttribute(auxiliaryType, "NAME"); int auxiliaryLatitudeType = g.findAttribute(auxiliaryType, "LATITUDE"); int auxiliaryLongitudeType = g.findAttribute(auxiliaryType, "LONGITUDE"); long src = g.findObject(auxiliaryNameType, value.setString("start")); long dst = g.findObject(auxiliaryNameType, value.setString("end")); g.setAttribute(src, auxiliaryLatitudeType, value.setDouble(fromLat)); g.setAttribute(src, auxiliaryLongitudeType, value.setDouble(fromLon)); g.setAttribute(dst, auxiliaryLatitudeType, value.setDouble(toLat)); g.setAttribute(dst, auxiliaryLongitudeType, value.setDouble(toLon)); CustomDijkstraCost dijkstraCostCalculator = new CustomDijkstraCost(day, time); SinglePairShortestPathDijkstra spDijkstra = new SinglePairShortestPathDijkstra(session, src, dst); spDijkstra.setDynamicEdgeCostCallback(dijkstraCostCalculator); spDijkstra.addEdgeType(routeType, EdgesDirection.Outgoing); spDijkstra.addNodeType(stopType); spDijkstra.addNodeType(auxiliaryType); spDijkstra.run(); if (spDijkstra.exists()) { System.out.println("Cost: " + spDijkstra.getCost()); OIDList pathAsNodes; pathAsNodes = spDijkstra.getPathAsNodes(); System.out.println("Route size " + pathAsNodes.count()); OIDListIterator pathIt; pathIt = pathAsNodes.iterator(); while (pathIt.hasNext()) { long nodeid; nodeid = pathIt.next(); System.out.println(" -> " + nodeid); //System.out.println(nodeid); } } spDijkstra.close(); System.out.println(" Route Finish"); return result; } }
package org.bookmanagement.service; import org.bookmanagement.entity.UserEntity; import org.bookmanagement.repository.UserRepository; import org.bookmanagement.request.UserLoginRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserRepository userRepository; public UserEntity validateUser(UserLoginRequest userLoginRequest){ return userRepository.findByUserNameAndPassword(userLoginRequest.getUserName(), userLoginRequest.getPassword()); } }
package com.fwo.hp.fwo.app.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by ana.j.saragossa on 10/24/17. */ public class Extract { @SerializedName("translation") @Expose private String translation; @SerializedName("actualQuery") @Expose private String actualQuery; @SerializedName("resultType") @Expose private String resultType; @SerializedName("transliteration") @Expose private String transliteration; @SerializedName("synonyms") @Expose private List<String> synonyms; @SerializedName("sourceLanguage") @Expose private String sourceLanguage; public String getActualQuery() { return actualQuery; } public void setActualQuery(String actualQuery) { this.actualQuery = actualQuery; } public String getResultType() { return resultType; } public void setResultType(String resultType) { this.resultType = resultType; } public String getSourceLanguage() { return sourceLanguage; } public void setSourceLanguage(String sourceLanguage) { this.sourceLanguage = sourceLanguage; } public List<String> getSynonyms() { return synonyms; } public void setSynonyms(List<String> synonyms) { this.synonyms = synonyms; } public String getTranslation() { return translation; } public void setTranslation(String translation) { this.translation = translation; } public String getTransliteration() { return transliteration; } public void setTransliteration(String transliteration) { this.transliteration = transliteration; } }
import java.util.Scanner; public class MyStringMethods { //class variable declarations private String myStr=""; /************************************** * Prompts the user to input a string.* **************************************/ public void readString() { Scanner Keyboard = new Scanner(System.in); System.out.print("> "); myStr = Keyboard.nextLine(); Keyboard.close(); } /************************************************************************* * Changes the value of myStr to a new string specified by the programmer* *************************************************************************/ public void setString(String s) { myStr = s; } /*************************************************************************** * Counts the amount of substrings specified by the programmer within myStr* ***************************************************************************/ public int countOccurrences(String subString) { int stringPosition = 0; int counter = 0; while (stringPosition != -1) // Loops until the subString cannot be found within myStr { stringPosition = myStr.indexOf(subString, stringPosition); if(stringPosition != -1) { counter++; stringPosition = stringPosition + subString.length(); // Moves the position to the next string if indexOf finds the substring within myStr } } return counter; } /*************************************************************************** * Counts the amount of characters specified by the programmer within myStr* ***************************************************************************/ public int countOccurrences(char c) { int charPosition = 0; int counter = 0; while (charPosition != -1) // Loops until c cannot be found within myStr { charPosition = myStr.indexOf(c, charPosition); if(charPosition != -1) { counter++; charPosition++; // Moves the position to the next character if indexOf finds the character within the myStr } } return counter; } /*************************************************** * Counts the amount of upper case letters in myStr* ***************************************************/ int countUpperCaseLetters() { int counter = 0; for(int charPosition = 0; charPosition < myStr.length(); charPosition++) //Loops exactly enough times to evaluate every character in myStr { if (Character.isUpperCase(myStr.charAt(charPosition)) == true) //If the current character is upper case, counter is incremented by 1 { counter++; } } return counter; } /*************************************************** * Counts the amount of lower case letters in myStr* ***************************************************/ int countLowerCaseLetters() { int counter = 0; for(int charPosition = 0; charPosition < myStr.length(); charPosition++) //Loops exactly enough times to evaluate every character in myStr { if (Character.isLowerCase(myStr.charAt(charPosition)) == true) //If the current character is lower case, counter is incremented by 1 { counter++; } } return counter; } /******************************************************************* * Outputs a formatted printout counting the number of substrings, * * characters, upper case letter and lower case letter within myStr* *******************************************************************/ public void printCounts(String s, char c) { System.out.println("***************************************"); System.out.println("Analyzing: myStr="+myStr); System.out.println("Number of "+s + " is "+ countOccurrences(s)); System.out.println("Number of "+c + " is "+ countOccurrences(c)); System.out.println("Number of Upper case letters="+ countUpperCaseLetters()); System.out.println("Number of Lower case letters="+ countLowerCaseLetters()); } public static void main(String[] args) { MyStringMethods msm = new MyStringMethods(); msm.readString(); msm.printCounts("big", 'a'); msm.setString("Parked in a van down by the river bank .... The van had was near a lot of other vans"); msm.printCounts("van", 'a'); MyStringMethods msm2 = new MyStringMethods(); msm2.setString("the elephant in the room wouldn't budge"); msm2.printCounts("the", 'i'); } }
package com.esum.framework.core.component.rule.processor; import com.esum.framework.core.component.ComponentException; /** * RuleProcessing. * * 수신한 메시지에 대한 Header Parsing Rule을 적용할 수 있으며, 각각의 컴포넌트에서 * Rule파싱을 사용할 수 있도록 정의할 수 있다. */ public interface IRuleProcessor { public <T> T preProcess(Object[] params) throws ComponentException; public <T> T postProcess(Object[] params) throws ComponentException; public <T> T splitProcess(Object[] params) throws ComponentException; public <T> T responseProcess(Object[] params) throws ComponentException; }
package com.clc.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import com.clc.dao.EmployeeDaoServiceSecurity; // //@EnableWebSecurity //public class SecurityConfig extends WebSecurityConfigurerAdapter { // // @Autowired // private UserDetailsService userDetailsService; // // // // public SecurityConfig(UserDetailsService userDetailsService) { // super(); // this.userDetailsService = new EmployeeDaoServiceSecurity(); // } // // @Bean // public BCryptPasswordEncoder passwordEncoder() { // return new BCryptPasswordEncoder(); // }; // // @Override // protected void configure(AuthenticationManagerBuilder auth) throws Exception { // //// auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); // // auth.inMemoryAuthentication() // .withUser("admin").password(passwordEncoder().encode("admin123")).roles("admin"); // } // // @Override // protected void configure(HttpSecurity http) throws Exception { // http.authorizeRequests().anyRequest().hasAnyRole("admin") // .and() // .authorizeRequests().antMatchers("/login**").permitAll() // .and() // .formLogin().permitAll() // .and() // .logout().logoutSuccessUrl("/login").permitAll() // .and() // .csrf().disable(); // // } // }
package DataStructures.arrays; /** You are given an n x n square 2D matrix that represents the pixels of an image. Rotate it by 90 degrees in the clockwise direction. Example: Input Matrix: 1 0 0 1 Output: 0 1 1 0 */ public class RotateMatrix { public static void rotateMatrix90(int a[][]) { if(a == null || a.length == 0) return; int rL= a.length; int cL = a[0].length; //transpose for(int i=0; i < rL; i++) { for(int j = i+1; j < cL; j++) { int t = a[j][i]; a[j][i] = a[i][j]; a[i][j] = t; } } //swap columns for(int j=0; j < cL/2; j++) { for(int i = 0; i < rL; i++) { int t = a[i][j]; a[i][j] = a[i][cL-j-1]; a[i][cL-j-1] = t; } } } //my firecode solution public static int[][] rotate1(int[][] matrix) { //transpose for (int i = 0; i < matrix.length; i++) { for (int j = i + 1; j < matrix[0].length; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } //swap columns int end = matrix[0].length - 1; for (int i = 0; i < matrix[0].length / 2; i++) { for (int j = 0; j < matrix.length; j++) { int temp = matrix[j][i]; matrix[j][i] = matrix[j][end]; matrix[j][end] = temp; } end--; } return matrix; } //firecode solution public static int[][] rotate(int[][] matrix) { int n = matrix.length; for (int i = 0; i < n / 2; i++) { for (int j = 0; j < Math.ceil(((double) n) / 2.); j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[n-1-j][i]; matrix[n-1-j][i] = matrix[n-1-i][n-1-j]; matrix[n-1-i][n-1-j] = matrix[j][n-1-i]; matrix[j][n-1-i] = temp; } } return matrix; } public static void rotateOneElement(int a[][]) { if(a == null || a.length == 0) return; int rL = a.length; int cL = a[0].length; int T = 0; int R = cL - 1; int B = rL - 1; int L = 0; int next = 0; int temp = 0; while(T <= B && L <= R) { if(next == 0) { temp = a[T+1][T]; for(int i = L; i <= R; i++) { int t = a[T][i]; a[T][i] = temp; temp = t; } T++; } else if(next == 1) { for(int i = T; i <= B; i++) { int t = a[i][R]; a[i][R] = temp; temp = t; } R--; } else if(next == 2) { for(int i = R; i >= L; i--) { int t = a[B][i]; a[B][i] = temp; temp = t; } B--; } else if(next == 3) { for(int i = B; i >= T; i--) { int t = a[i][L]; a[i][L] = temp; temp = t; } L++; } next = (next + 1) % 4; int e = T; if((T == e) && ( B == e) && (L == e) && (R == e)) break; } System.out.println(a); } public static void main(String ar[]) { int a[][] = { {2,8,5,1,7}, {9,12,10,11,6}, {5,4,3,2,1}, {8,1,2,10,9}, {0,5,6,2,3} }; //RotateMatrix.rotateMatrix90(a); RotateMatrix.rotateOneElement(a); } }
package _DAO; import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import _DTO.Book; import _DTO.BuyList; import _DTO.CartList; import _DTO.Review; public class BookDAO { private BookDAO() {} private static BookDAO dao = new BookDAO(); public static BookDAO getInstance() { return dao; } public void bookInsert(Book book) { Connection conn = null; PreparedStatement ps = null; String sql = "insert into book(no, name, genre, writer, publish, content, price, imgfile, bookfile) " + "values(book_seq.nextval, ?, ?, ?,?,?,?,?,?)"; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setString(1, book.getName()); ps.setString(2, book.getGenre()); ps.setString(3, book.getWriter()); ps.setString(4, book.getPublish()); ps.setString(5, book.getContent()); ps.setInt(6, book.getPrice()); ps.setString(7, book.getImgFile()); ps.setString(8, book.getBookFile()); int n = ps.executeUpdate(); if(n != 0) { DBConn.commit(conn); } } catch (Exception e) { e.printStackTrace(); } finally { DBConn.close(ps); DBConn.close(conn); } } public List<Book> bookSelectAll() { List<Book> list = new ArrayList<Book>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = "select * from book order by no"; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { Book book = new Book(); book.setNo(rs.getInt("no")); book.setName(rs.getString("name")); book.setGenre(rs.getString("genre")); book.setWriter(rs.getString("writer")); book.setPublish(rs.getString("publish")); book.setContent(rs.getString("content")); book.setRead_count(rs.getInt("read_count")); book.setReply_count(rs.getInt("reply_count")); book.setPrice(rs.getInt("price")); book.setScore(rs.getInt("score")); book.setBuyCount(rs.getInt("buycount")); book.setImgFile(rs.getString("imgfile")); book.setBookFile(rs.getString("bookfile")); list.add(book); } } catch (Exception e) { e.printStackTrace(); } finally { DBConn.close(rs); DBConn.close(ps); DBConn.close(conn); } return list; } public List<Book> bookSelectTop(){ List<Book> list = new ArrayList<Book>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = "select "; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { } } catch (Exception e) { e.printStackTrace(); } finally { DBConn.close(rs); DBConn.close(ps); DBConn.close(conn); } return list; } public List<Book> bookSelectPage(int start, int pageSize){ Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql ="select * from " +"(select rownum as rn, a.* " +"from (select * from book order by no) a " +"where rownum<=?)b " +"where b.rn>=?"; List<Book> blist = new ArrayList<Book>(); try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setInt(1, start+pageSize); ps.setInt(2, start+1); rs = ps.executeQuery(); while (rs.next()) { Book book = new Book(); book.setNo(rs.getInt("no")); book.setName(rs.getString("name")); book.setGenre(rs.getString("genre")); book.setWriter(rs.getString("writer")); book.setPublish(rs.getString("publish")); book.setContent(rs.getString("content")); book.setRead_count(rs.getInt("read_count")); book.setReply_count(rs.getInt("reply_count")); book.setPrice(rs.getInt("price")); book.setScore(rs.getInt("score")); book.setBuyCount(rs.getInt("buycount")); book.setImgFile(rs.getString("imgfile")); book.setBookFile(rs.getString("bookfile")); blist.add(book); } } catch (Exception e) { e.printStackTrace(); } finally { DBConn.close(rs); DBConn.close(ps); DBConn.close(conn); } return blist; } public List<String> bookSelectGenre(){ List<String> genreArr = new ArrayList<String>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = "select distinct genre from book"; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { String genre = rs.getString(1); genreArr.add(genre); } } catch (Exception e) { e.printStackTrace(); } finally { DBConn.close(rs); DBConn.close(ps); DBConn.close(conn); } return genreArr; } public int getTotalBook() { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = "select count(*) from book"; int count = -1; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { count = rs.getInt(1); } } catch (Exception e) { e.printStackTrace(); } finally { DBConn.close(rs); DBConn.close(ps); DBConn.close(conn); } return count; } public Book getbook(int bookno) { Book book=null; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = "select * from book where no=?"; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setInt(1, bookno); rs = ps.executeQuery(); System.out.println(rs); while (rs.next()) { book=new Book(); book.setNo(rs.getInt("no")); book.setName(rs.getString("name")); book.setGenre(rs.getString("genre")); book.setWriter(rs.getString("writer")); book.setPublish(rs.getString("publish")); book.setContent(rs.getString("content")); book.setRead_count(rs.getInt("read_count")); book.setReply_count(rs.getInt("reply_count")); book.setPrice(rs.getInt("price")); book.setScore(rs.getInt("score")); book.setBuyCount(rs.getInt("buycount")); book.setImgFile(rs.getString("imgfile")); book.setBookFile(rs.getString("bookfile")); } } catch (Exception ex) { ex.printStackTrace(); } finally { DBConn.close(rs); DBConn.close(ps); DBConn.close(conn); } System.out.println(book); return book; } public void getBookbuy(int uno, int bno) { Connection conn = null; PreparedStatement ps = null; String sql = "insert into buylist(uno,no,currdate)" + "values(?,?,SYSDATE)"; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setInt(1, uno); ps.setInt(2, bno); int n = ps.executeUpdate(); if(n != 0) { DBConn.commit(conn); System.out.println("구매완료"); } } catch (Exception e) { e.printStackTrace(); } finally { DBConn.close(ps); DBConn.close(conn); } } public int getUserPoint(String u_id) { //세션에 있는 유저 아이디 Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = "select u_point from member where u_id=?"; int n = 0; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setString(1, u_id); System.out.println(); rs = ps.executeQuery(); while(rs.next()){ n = rs.getInt(1); } //member = new member(); //member.setU_point(rs.getInt(1)); } catch (Exception e) { e.printStackTrace(); } finally { DBConn.close(ps); DBConn.close(conn); } return n; } public void getBuy(int bprice, String u_id) { //유저 아이디와 책 가격을 가져옴 Connection conn = null; PreparedStatement ps = null; String sql = "update member set u_point=" + "u_point-? " + "where u_id=?"; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setInt(1, bprice); ps.setString(2, u_id); int n = ps.executeUpdate(); if(n==1) { DBConn.commit(conn); } } catch (Exception e) { // TODO: handle exception } finally { DBConn.close(ps); DBConn.close(conn); } } public int getuno(String u_id) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = "select uno from member where u_id=?"; int n=0; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setString(1, u_id); rs = ps.executeQuery(); while(rs.next()){ n = rs.getInt(1); } } catch (Exception e) { // TODO: handle exception } finally { DBConn.close(ps); DBConn.close(conn); } return n; } public List<BuyList> buylistSelectAll(int uno) { //회원번호로 구매한책,날짜가져옴 List<BuyList> buylist = new ArrayList<BuyList>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = "select b.imgfile, b.name, b.bookfile, m.u_name, l.currdate, b.genre, b.price, b.publish from book b, member m, buylist l where l.no = b.no and m.uno = l.uno and l.uno = ?"; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setInt(1, uno); rs = ps.executeQuery(); while (rs.next()) { BuyList book = new BuyList(); book.setImgfile(rs.getString("imgfile")); book.setName(rs.getString("name")); book.setBookfile(rs.getString("bookfile")); book.setU_name(rs.getString("u_name")); book.setCurrdate(rs.getDate("currdate")); book.setGenre(rs.getString("genre")); book.setPrice(rs.getInt("price")); book.setPublish(rs.getString("publish")); File f = new File("C:/Users/whaks/Desktop/개발/CODE/BusanIT_Project2/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Team_Project/upload/"+rs.getString("bookfile")); book.setBooksize((int) f.length()); buylist.add(book); } } catch (Exception e) { e.printStackTrace(); } finally { DBConn.close(rs); DBConn.close(ps); DBConn.close(conn); } return buylist; } public List<CartList> BasketlistSelectAll(int uno) { //찜 목록 에서 표현해줄 데이터값. List<CartList> cartlist = new ArrayList<CartList>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = "select b.imgfile, b.name, b.bookfile, m.u_name, l.currdate, b.genre, b.price, b.publish from book b, member m, cartlist l where l.no = b.no and m.uno = l.uno and l.uno = ?"; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setInt(1, uno); rs = ps.executeQuery(); while (rs.next()) { CartList book = new CartList(); book.setImgfile(rs.getString("imgfile")); book.setName(rs.getString("name")); book.setBookfile(rs.getString("bookfile")); book.setU_name(rs.getString("u_name")); book.setCurrdate(rs.getDate("currdate")); book.setGenre(rs.getString("genre")); book.setPrice(rs.getInt("price")); book.setPublish(rs.getString("publish")); File f = new File("C:/Users/whaks/Desktop/개발/CODE/BusanIT_Project2/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Team_Project/upload/"+rs.getString("bookfile")); book.setBooksize((int) f.length()); cartlist.add(book); } } catch (Exception e) { e.printStackTrace(); } finally { DBConn.close(rs); DBConn.close(ps); DBConn.close(conn); } return cartlist; } public void getCartInsert(int uno,int no) { Connection conn = null; PreparedStatement ps = null; String sql = "insert into cartlist(uno,no,currdate)" + "values(?,?,SYSDATE)"; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setInt(1, uno); ps.setInt(2, no); int n = ps.executeUpdate(); if(n!=0) { DBConn.commit(conn); } } catch (Exception e) { e.printStackTrace(); } finally { DBConn.close(ps); DBConn.close(conn); } } public int bookReviewInsert(int uno, int no, String u_id, String r_content,int score) { //리뷰 등록후 업데이트해줘야할 그책의 평균값 리턴 Connection conn = null; PreparedStatement ps = null; Connection conn2 = null; PreparedStatement ps2 = null; ResultSet rs = null; int n = 0; int avg=0; String sql = "insert into review(rno,uno,no,u_id,r_content,r_date,score)" + "values(rno_seq.nextval,?,?,?,?,SYSDATE,?)"; String sql2 = "select avg(score) from review where no=?"; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setInt(1, uno); ps.setInt(2, no); ps.setString(3, u_id); ps.setString(4, r_content); ps.setInt(5, score); n = ps.executeUpdate(); if(n==1) {//insert 성공했을시에 평균값 구하기 시작 System.out.println("책 리뷰등록 성공하였습니다."); DBConn.commit(conn); conn2 = DBConn.getConnect(); ps2 = conn2.prepareStatement(sql2); ps2.setInt(1, no); rs = ps2.executeQuery(); while(rs.next()){ avg = rs.getInt(1); } } } catch (Exception e) { // TODO: handle exception } finally { DBConn.close(ps); DBConn.close(conn); } return avg; } public void bookScore(int avg, int no) { // 업데이트를 해줘야할 평균값과 그 책번호를 가지고 업데이트함 Connection conn = null; PreparedStatement ps = null; String sql = "update book set score=? where no=?"; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setInt(1, avg); ps.setInt(2, no); int n = ps.executeUpdate(); if(n!=0) { System.out.println("등록하신 책 점수가 평균으로 반영되었습니다"); DBConn.commit(conn); } } catch (Exception e) { // TODO: handle exception } finally { DBConn.close(ps); DBConn.close(conn); } } public List<Review> getReview(int bno) { //bno로 책 번호를 넣어서 그 책의 리뷰를 꺼내기 List<Review> list = new ArrayList<Review>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = "select * from review where no=? order by r_date"; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setInt(1, bno); rs = ps.executeQuery(); while (rs.next()) { Review review = new Review(); review.setRno(rs.getInt("rno")); review.setUno(rs.getInt("uno")); review.setNo(rs.getInt("no")); review.setU_id(rs.getString("u_id")); review.setR_content(rs.getString("r_content")); review.setR_date(rs.getDate("r_date")); review.setScore(rs.getInt("score")); list.add(review); } } catch (Exception e) { e.printStackTrace(); } finally { DBConn.close(rs); DBConn.close(ps); DBConn.close(conn); } return list; } public int getTotalReviewCount(int no) { int n=0; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = "select count(*) from review where no=?"; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setInt(1, no); rs = ps.executeQuery(); while (rs.next()) { n=rs.getInt(1); } } catch (Exception ex) { ex.printStackTrace(); } finally { DBConn.close(rs); DBConn.close(ps); DBConn.close(conn); } return n; } public List<Review> getReviewPage(int start, int size,int no){ List<Review> list=new ArrayList<Review>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql="select * from " +"(select rownum as rn, " +"a.* " +"from (select * from review where no=? order by r_date desc) a " +"where rownum<=?)b " +"where b.rn>=?" ; try { conn = DBConn.getConnect(); ps = conn.prepareStatement(sql); ps.setInt(1, no); ps.setInt(2, start+size); ps.setInt(3, start+1); rs = ps.executeQuery(); while (rs.next()) { Review review = new Review(); review.setRno(rs.getInt("rno")); review.setUno(rs.getInt("uno")); review.setNo(rs.getInt("no")); review.setU_id(rs.getString("u_id")); review.setR_content(rs.getString("r_content")); review.setR_date(rs.getDate("r_date")); review.setScore(rs.getInt("score")); list.add(review); } } catch (Exception ex) { ex.printStackTrace(); } finally { DBConn.close(rs); DBConn.close(ps); DBConn.close(conn); } return list; } }
package com.ConfigPoste.RecetteCuisine.RecetteCuisine.services; public class UploadFileResponse { private int id; private String fileName; private String uri; private String contentType; private long size; public UploadFileResponse(int idFile,String name, String fileDownloadUri, String content, long s) { fileName=name; uri=fileDownloadUri; contentType=content; size=s; id=idFile; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } }