text stringlengths 10 2.72M |
|---|
package com.rx.mvvm.aop.anno;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by wuwei
* 2021/3/22
* 佛祖保佑 永无BUG
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ArouterDestroy {
}
|
package service.impl;
import org.springframework.stereotype.Service;
import repository.RoleRepository;
import service.RoleService;
import javax.annotation.Resource;
import java.util.HashMap;
/**
* Created by xheart on 2016/8/14.
*/
@Service
public class RoleServiceImpl implements RoleService {
@Resource
private RoleRepository roleRepository;
@Override
public HashMap<String, Object> list(int pageNumber, int pageSize) {
HashMap<String,Object> page = new HashMap<String, Object>();
page.put("total",roleRepository.listCount());
page.put("rows",roleRepository.list(pageNumber,pageSize));
return page;
}
}
|
package uk.gov.hmcts.jsonstore;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.MissingNode;
public class JsonResourceStoreWithInheritance extends JsonStoreWithInheritance {
private String[] resourcePaths;
private ObjectMapper mapper = new ObjectMapper();
public JsonResourceStoreWithInheritance(String[] resourcePaths) {
super();
this.resourcePaths = resourcePaths;
}
public JsonResourceStoreWithInheritance(String[] resourcePaths, String idFieldName, String inheritanceFieldName) {
super(idFieldName, inheritanceFieldName);
this.resourcePaths = resourcePaths;
}
@Override
protected void buildObjectStore() throws Exception {
rootNode = buildObjectStoreInResourcePaths();
}
private JsonNode buildObjectStoreInResourcePaths() throws Exception {
ArrayNode store = new ArrayNode(null);
for (String resource : resourcePaths) {
JsonNode substore = null;
if (resource.toLowerCase().endsWith(".json"))
substore = buildObjectStoreInAResource(resource);
if (substore != null && !substore.equals(MissingNode.getInstance())) {
String guid = substore.get(GUID).asText();
validateGUID(guid);
if (substore.isArray()) {
for (int i = 0; i < substore.size(); i++)
store.add(substore.get(i));
} else
store.add(substore);
processedGUIDs.add(guid);
}
}
if (store.size() == 1)
return store.get(0);
return store;
}
private JsonNode buildObjectStoreInAResource(String resource) throws Exception {
try {
return mapper.readTree(this.getClass().getClassLoader().getResourceAsStream(resource));
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
|
package net.minecraft.network;
import net.minecraft.util.text.ITextComponent;
public interface INetHandler {
void onDisconnect(ITextComponent paramITextComponent);
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\network\INetHandler.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
package com.facebook.react.bridge;
import com.facebook.jni.HybridData;
import java.util.ArrayList;
public class ReadableNativeArray extends NativeArray implements ReadableArray {
private static int jniPassCounter;
private static boolean mUseNativeAccessor;
private Object[] mLocalArray;
private ReadableType[] mLocalTypeArray;
protected ReadableNativeArray(HybridData paramHybridData) {
super(paramHybridData);
}
private native ReadableNativeArray getArrayNative(int paramInt);
private native boolean getBooleanNative(int paramInt);
private native double getDoubleNative(int paramInt);
private native int getIntNative(int paramInt);
public static int getJNIPassCounter() {
return jniPassCounter;
}
private Object[] getLocalArray() {
// Byte code:
// 0: aload_0
// 1: getfield mLocalArray : [Ljava/lang/Object;
// 4: astore_1
// 5: aload_1
// 6: ifnull -> 11
// 9: aload_1
// 10: areturn
// 11: aload_0
// 12: monitorenter
// 13: aload_0
// 14: getfield mLocalArray : [Ljava/lang/Object;
// 17: ifnonnull -> 42
// 20: getstatic com/facebook/react/bridge/ReadableNativeArray.jniPassCounter : I
// 23: iconst_1
// 24: iadd
// 25: putstatic com/facebook/react/bridge/ReadableNativeArray.jniPassCounter : I
// 28: aload_0
// 29: aload_0
// 30: invokespecial importArray : ()[Ljava/lang/Object;
// 33: invokestatic b : (Ljava/lang/Object;)Ljava/lang/Object;
// 36: checkcast [Ljava/lang/Object;
// 39: putfield mLocalArray : [Ljava/lang/Object;
// 42: aload_0
// 43: monitorexit
// 44: aload_0
// 45: getfield mLocalArray : [Ljava/lang/Object;
// 48: areturn
// 49: astore_1
// 50: aload_0
// 51: monitorexit
// 52: aload_1
// 53: athrow
// Exception table:
// from to target type
// 13 42 49 finally
// 42 44 49 finally
// 50 52 49 finally
}
private ReadableType[] getLocalTypeArray() {
// Byte code:
// 0: aload_0
// 1: getfield mLocalTypeArray : [Lcom/facebook/react/bridge/ReadableType;
// 4: astore_1
// 5: aload_1
// 6: ifnull -> 11
// 9: aload_1
// 10: areturn
// 11: aload_0
// 12: monitorenter
// 13: aload_0
// 14: getfield mLocalTypeArray : [Lcom/facebook/react/bridge/ReadableType;
// 17: ifnonnull -> 54
// 20: getstatic com/facebook/react/bridge/ReadableNativeArray.jniPassCounter : I
// 23: iconst_1
// 24: iadd
// 25: putstatic com/facebook/react/bridge/ReadableNativeArray.jniPassCounter : I
// 28: aload_0
// 29: invokespecial importTypeArray : ()[Ljava/lang/Object;
// 32: invokestatic b : (Ljava/lang/Object;)Ljava/lang/Object;
// 35: checkcast [Ljava/lang/Object;
// 38: astore_1
// 39: aload_0
// 40: aload_1
// 41: aload_1
// 42: arraylength
// 43: ldc [Lcom/facebook/react/bridge/ReadableType;
// 45: invokestatic copyOf : ([Ljava/lang/Object;ILjava/lang/Class;)[Ljava/lang/Object;
// 48: checkcast [Lcom/facebook/react/bridge/ReadableType;
// 51: putfield mLocalTypeArray : [Lcom/facebook/react/bridge/ReadableType;
// 54: aload_0
// 55: monitorexit
// 56: aload_0
// 57: getfield mLocalTypeArray : [Lcom/facebook/react/bridge/ReadableType;
// 60: areturn
// 61: astore_1
// 62: aload_0
// 63: monitorexit
// 64: aload_1
// 65: athrow
// Exception table:
// from to target type
// 13 54 61 finally
// 54 56 61 finally
// 62 64 61 finally
}
private native ReadableNativeMap getMapNative(int paramInt);
private native String getStringNative(int paramInt);
private native ReadableType getTypeNative(int paramInt);
private native Object[] importArray();
private native Object[] importTypeArray();
private native boolean isNullNative(int paramInt);
public static void setUseNativeAccessor(boolean paramBoolean) {
mUseNativeAccessor = paramBoolean;
}
private native int sizeNative();
public ReadableNativeArray getArray(int paramInt) {
if (mUseNativeAccessor) {
jniPassCounter++;
return getArrayNative(paramInt);
}
return (ReadableNativeArray)getLocalArray()[paramInt];
}
public boolean getBoolean(int paramInt) {
if (mUseNativeAccessor) {
jniPassCounter++;
return getBooleanNative(paramInt);
}
return ((Boolean)getLocalArray()[paramInt]).booleanValue();
}
public double getDouble(int paramInt) {
if (mUseNativeAccessor) {
jniPassCounter++;
return getDoubleNative(paramInt);
}
return ((Double)getLocalArray()[paramInt]).doubleValue();
}
public Dynamic getDynamic(int paramInt) {
return DynamicFromArray.create(this, paramInt);
}
public int getInt(int paramInt) {
if (mUseNativeAccessor) {
jniPassCounter++;
return getIntNative(paramInt);
}
return ((Double)getLocalArray()[paramInt]).intValue();
}
public ReadableNativeMap getMap(int paramInt) {
if (mUseNativeAccessor) {
jniPassCounter++;
return getMapNative(paramInt);
}
return (ReadableNativeMap)getLocalArray()[paramInt];
}
public String getString(int paramInt) {
if (mUseNativeAccessor) {
jniPassCounter++;
return getStringNative(paramInt);
}
return (String)getLocalArray()[paramInt];
}
public ReadableType getType(int paramInt) {
if (mUseNativeAccessor) {
jniPassCounter++;
return getTypeNative(paramInt);
}
return getLocalTypeArray()[paramInt];
}
public boolean isNull(int paramInt) {
if (mUseNativeAccessor) {
jniPassCounter++;
return isNullNative(paramInt);
}
return (getLocalArray()[paramInt] == null);
}
public int size() {
if (mUseNativeAccessor) {
jniPassCounter++;
return sizeNative();
}
return (getLocalArray()).length;
}
public ArrayList<Object> toArrayList() {
StringBuilder stringBuilder;
ArrayList arrayList = new ArrayList();
for (int i = 0; i < size(); i++) {
switch (getType(i)) {
default:
stringBuilder = new StringBuilder("Could not convert object at index: ");
stringBuilder.append(i);
stringBuilder.append(".");
throw new IllegalArgumentException(stringBuilder.toString());
case null:
stringBuilder.add(getArray(i).toArrayList());
break;
case Map:
stringBuilder.add(getMap(i).toHashMap());
break;
case String:
stringBuilder.add(getString(i));
break;
case Number:
stringBuilder.add(Double.valueOf(getDouble(i)));
break;
case Boolean:
stringBuilder.add(Boolean.valueOf(getBoolean(i)));
break;
case Null:
stringBuilder.add(null);
break;
}
}
return (ArrayList<Object>)stringBuilder;
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\bridge\ReadableNativeArray.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package invertedFile;
import util.DefaultSearch;
import util.LoadRTree;
import util.ScoredObject;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.TreeSet;
import s2i.SpatialInvertedIndex;
import s2i.SpatioTreeHeapEntry;
import util.IFTuple;
import util.SpatioTextualObject;
import util.cache.MinHeap;
import util.config.Settings;
import util.experiment.ExperimentException;
import util.file.BufferedListStorage;
import util.file.ColumnFileException;
import util.file.EntryStorage;
import util.file.IntegerEntry;
import util.sse.Term;
import util.sse.Vector;
import util.sse.Vocabulary;
import util.statistics.DefaultStatisticCenter;
import util.statistics.StatisticCenter;
import xxl.core.cursors.Cursor;
import xxl.util.StarRTree;
/**
*
* @author Robos
*/
public class InvertedFileSearch extends DefaultSearch {
private final BufferedListStorage<IFTuple> cache;
private final String docLengthFile;
private HashMap<Integer, Integer> documentLength;
//maps term id (from termVocabulary) to the number of documents that has the term (document frequency of the term)
private EntryStorage<IntegerEntry> termInfo;
private final String termInfoFile;
private final int neighborhood;
private final StarRTree objectsOfInterest;
private final double radius;
public InvertedFileSearch(StatisticCenter statisticCenter, boolean debug, Vocabulary termVocabulary,
int numKeywords, int numResults, int numQueries, double alpha,
double spaceMaxValue, String queryType, String queryKeywords, int numMostFrequentTerms,
int numWarmUpQueries, String ifFile, int cacheSize, String docLengthFile,
String termInfoFile, int neighborhood, StarRTree objectsOfInterest, double radius) {
super(statisticCenter, debug, termVocabulary, numKeywords, numResults,
numQueries, alpha, spaceMaxValue, queryType, queryKeywords, numMostFrequentTerms, numWarmUpQueries);
this.cache = new BufferedListStorage<>(statisticCenter, "ifSearch",
ifFile, cacheSize, IFTuple.SIZE, IFTuple.FACTORY);
this.docLengthFile = docLengthFile;
this.termInfoFile = termInfoFile;
this.neighborhood = neighborhood;
this.objectsOfInterest = objectsOfInterest;
this.radius = radius;
}
@Override
public void open() throws ExperimentException {
try {
termVocabulary.open();
termInfo = new EntryStorage<>(statisticCenter, "termInfo",
termInfoFile, IntegerEntry.SIZE, IntegerEntry.FACTORY);
termInfo.open();
} catch (Exception e) {
throw new ExperimentException(e);
}
super.open();
try {
this.objectsOfInterest.open();
this.cache.open();
FileInputStream fileInputStream = new FileInputStream(docLengthFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
documentLength = (HashMap<Integer, Integer>) objectInputStream.readObject();
objectInputStream.close();
} catch (Exception e) {
throw new ExperimentException(e);
}
}
@Override
protected void collectStatistics(int count) {
long termInfoBlocksRead = statisticCenter.getCount("termInfo_blocksRead").getValue();
statisticCenter.getTally("avgTermInfo_blocksRead").update(termInfoBlocksRead / (double) count);
long mapBlocksRead = statisticCenter.getCount("ifSearch_map_blocksRead").getValue();
long ifBlocksRead = statisticCenter.getCount("ifSearch_blocksRead").getValue();
statisticCenter.getTally("avgIfSearch_map_blocksRead").update(mapBlocksRead / (double) count);
statisticCenter.getTally("avgIfSearch_blocksRead").update(ifBlocksRead / (double) count);
statisticCenter.getTally("avgPageFault").update((mapBlocksRead + ifBlocksRead) / (double) count);
long ifSearchListCacheFault = statisticCenter.getCount("ifSearchListCacheFault").getValue();
statisticCenter.getTally("avgIfSearchListCacheFault").update(ifSearchListCacheFault / (double) count);
long nodesAccessed = statisticCenter.getCount("nodesAccessed").getValue();
statisticCenter.getTally("avgNodesAccessed").update(nodesAccessed / (double) count);
long entriesAcessed = statisticCenter.getCount("ifSearchEntriesAccessed").getValue();
statisticCenter.getTally("avgIfSearchEntriesAccessed").update(entriesAcessed / (double) count);
}
@Override
protected int getDocumentFrequency(int termId) {
try {
IntegerEntry entry = termInfo.getEntry(termId);
return entry == null ? -1 : entry.getValue();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
protected int getTotalNumObjects() {
return documentLength.size();
}
@Override
protected Iterator<SpatioTextualObject> execute(double queryLatitude, double queryLongitude, double maxDist, String queryKeywords, int k, double alpha) throws ExperimentException {
try {
long time = System.currentTimeMillis();
System.out.println("Searching... " + queryKeywords + "");
TreeSet<SpatioTextualObject> topK = new TreeSet<>();
Vector queryVector = new Vector();
Vector.vectorize(queryVector, queryKeywords, termVocabulary);
double wq = Vector.computeQueryWeight(queryVector, getTotalNumObjects(), termInfo);
Cursor leaves = objectsOfInterest.query(1);
while (leaves.hasNext()) {
SpatioTreeHeapEntry leafEntry = new SpatioTreeHeapEntry(leaves.next());
Cursor interestPointer = objectsOfInterest.query(leafEntry.getMBR());
while (interestPointer.hasNext()) {
SpatioTreeHeapEntry point = new SpatioTreeHeapEntry(interestPointer.next());
ScoredObject obj = new ScoredObject(point.getId(),
point.getMBR().getCorner(false).getValue(0),
point.getMBR().getCorner(false).getValue(1));
if (neighborhood == 0) {
IFNearestSearch(queryVector, obj, wq);
} else if (neighborhood == 1) {
IFRangeSearch(queryVector, radius, obj, wq);
} else if (neighborhood == 2) {
IFInflueceSearch(queryVector, radius, obj, wq);
} else {
throw new ExperimentException("The neighborhood " + neighborhood + "' is not defined yet!!!");
}
if (topK.size() < k) {
topK.add(obj);
} else if (obj.getScore() > topK.first().getScore()
|| // keep the best objects, if they have the same scores, keeps the objects with smaller ids
(obj.getScore() == topK.first().getScore() && obj.getId() > topK.first().getId())) {
topK.pollFirst();
topK.add(obj);
}
}
interestPointer.close();
}
leaves.close();
statisticCenter.getTally("avgQueryProcessingTime").update(System.currentTimeMillis() - time);
return topK.descendingIterator();
} catch (Exception ex) {
throw new ExperimentException(ex);
}
}
public void influenceScore(ScoredObject object, FeatureEntry entry) {
double distToObject = DefaultSearch.euclideanDistance(object.getLatitude(), object.getLongitude(),
entry.feature.getLatitude(), entry.feature.getLongitude());
entry.textualScore = entry.textualScore * Math.pow(2, -distToObject / radius);
if ((entry.textualScore > object.getScore())) { //transformar em updateScore depois, se remover aquela verificação da distancia
object.setScore(entry.textualScore);
}
}
public void IFNearestSearch(Vector query, final ScoredObject p, double wq) throws IOException, ColumnFileException {
//Inicializa a distância com um valor bem grande
double minDistance = Double.MAX_VALUE;
Iterator terms = query.iterator();
MinHeap<FeatureEntry> heap = new MinHeap<>();
//Stores the first feature of each list in the heap. Each heap entry has a pointer to its source
while (terms.hasNext()) {
Term term = (Term) terms.next();
List<IFTuple> list = cache.getList(term.getTermId());
//sort list by id
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return (int) (((IFTuple) o1).getID() - ((IFTuple) o2).getID());
}
});
if (list != null && list.size() > 0) {
Iterator<IFTuple> it = list.iterator();
heap.add(new FeatureEntry(it.next(), it, term, wq));
}
}
//Get the entry with smallest id
FeatureEntry entry = nextEntry(heap);
while (entry != null && !heap.isEmpty()) {
FeatureEntry other = nextEntry(heap);
while (other != null && entry.feature.getID() == other.feature.getID()) {
//update the score of the feature
entry.incScore(other.textualScore);
other = nextEntry(heap);
}
minDistance = updateScoreNN(p, entry, minDistance);
entry = other;
}
if (entry != null) {
minDistance = updateScoreNN(p, entry, minDistance);
}
}
public void IFRangeSearch(Vector query, double radius, ScoredObject p, double wq) throws IOException, ColumnFileException {
Iterator terms = query.iterator();
MinHeap<FeatureEntry> heap = new MinHeap<>();
//Stores the first feature of each list in the heap. Each heap entry has a pointer to its source
while (terms.hasNext()) {
Term term = (Term) terms.next();
List<IFTuple> list = cache.getList(term.getTermId());
//sort list by id
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return (int) (((IFTuple) o1).getID() - ((IFTuple) o2).getID());
}
});
if (list != null && list.size() > 0) {
Iterator<IFTuple> it = list.iterator();
heap.add(new FeatureEntry(it.next(), it, term, wq));
}
}
//Get the entry with smallest id
FeatureEntry entry = nextEntry(heap);
while (entry != null && !heap.isEmpty()) {
FeatureEntry other = nextEntry(heap);
while (other != null && entry.feature.getID() == other.feature.getID()) {
//update the score of the feature
entry.incScore(other.textualScore);
other = nextEntry(heap);
}
updateScore(p, entry, radius);
entry = other;
}
if (entry != null) {
updateScore(p, entry, radius);
}
}
public void IFInflueceSearch(Vector query, double range, ScoredObject object, double wq) throws IOException, ColumnFileException {
Iterator terms = query.iterator();
MinHeap<FeatureEntry> heap = new MinHeap<>();
//Stores the first feature of each list in the heap. Each heap entry has a pointer to its source
while (terms.hasNext()) {
Term term = (Term) terms.next();
List<IFTuple> list = cache.getList(term.getTermId());
//sort list by id
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return (int) (((IFTuple) o1).getID() - ((IFTuple) o2).getID());
}
});
if (list != null && list.size() > 0) {
Iterator<IFTuple> it = list.iterator();
heap.add(new FeatureEntry(it.next(), it, term, wq)); //cria o feature e calcula o escore textual
}
}
//Get the entry with smallest id
FeatureEntry entry = nextEntry(heap);
while (entry != null && !heap.isEmpty()) {
FeatureEntry other = nextEntry(heap);
while (other != null && entry.feature.getID() == other.feature.getID()) {
//update the score of the feature
entry.incScore(other.textualScore);
other = nextEntry(heap);
}
influenceScore(object, entry);
entry = other;
}
if (entry != null) {
influenceScore(object, entry);
}
}
private static void updateScore(ScoredObject p, FeatureEntry entry, double radius) {
if ((DefaultSearch.euclideanDistance(p.getLatitude(), p.getLongitude(),
entry.feature.getLatitude(), entry.feature.getLongitude()) < radius) && (entry.textualScore > p.getScore())) {
p.setScore(entry.textualScore);
}
}
private double updateScoreNN(ScoredObject p, FeatureEntry entry, double minDistance) {
double distance = DefaultSearch.euclideanDistance(p.getLatitude(), p.getLongitude(),
entry.feature.getLatitude(), entry.feature.getLongitude());
if (distance < minDistance) {
minDistance = distance;
p.setScore(entry.textualScore);
} else if (distance == minDistance && entry.textualScore > p.getScore()) {
p.setScore(entry.textualScore);
}
return minDistance;
}
private FeatureEntry nextEntry(MinHeap<FeatureEntry> heap) {
FeatureEntry entry = heap.poll();
if (entry != null && entry.source.hasNext()) {
heap.add(new FeatureEntry(entry.source.next(), entry.source, entry.term, entry.queryLength));
}
return entry;
}
@Override
public void close() throws ExperimentException {
try {
termVocabulary.close();
termInfo.close();
objectsOfInterest.close();
} catch (Exception e) {
throw new ExperimentException();
}
}
private class FeatureEntry implements Comparable {
final Iterator<IFTuple> source;
final IFTuple feature;
final Term term;
final double queryLength;
double textualScore;
public FeatureEntry(IFTuple feature, Iterator<IFTuple> source, Term term, double queryLength) {
this.feature = feature;
this.term = term;
this.queryLength = queryLength;
this.source = source;
textualScore = SpatialInvertedIndex.textualPartialScore(term.getWeight(),
queryLength, feature.getTermImpact());
}
public void incScore(double partialScore) {
this.textualScore += partialScore;
}
@Override
public int compareTo(Object o) {
FeatureEntry other = (FeatureEntry) o;
return (int) (feature.getID() - other.feature.getID());
}
}
public static void main(String[] args) throws Exception {
Properties properties = Settings.loadProperties("framework.properties");
String prefix = properties.getProperty("experiment.folder");
Vocabulary vocabulary = new Vocabulary(prefix + "/" + properties.getProperty("if.vocabulary"));
DefaultStatisticCenter statistics = new DefaultStatisticCenter();
boolean debug = true;
StarRTree rTree = new StarRTree(statistics, "",
properties.getProperty("if.folder") + "/rtree",
Integer.parseInt(properties.getProperty("srtree.dimensions")),
Integer.parseInt(properties.getProperty("srtree.cacheSize")),
Integer.parseInt(properties.getProperty("disk.blockSize")),
Integer.parseInt(properties.getProperty("srtree.tree.minNodeCapacity")),
Integer.parseInt(properties.getProperty("srtree.tree.maxNodeCapacity")));
LoadRTree.load(rTree, properties.getProperty("dataset.objectsFile"));
InvertedFileSearch searching = new InvertedFileSearch(statistics,
debug, vocabulary,
Integer.parseInt(properties.getProperty("query.numKeywords")),
Integer.parseInt(properties.getProperty("query.numResults")),
Integer.parseInt(properties.getProperty("query.numQueries")),
0.0,
Double.parseDouble(properties.getProperty("dataset.spaceMaxValue")),
properties.getProperty("query.type"),
properties.getProperty("query.keywords"),
Integer.parseInt(properties.getProperty("query.numMostFrequentTerms")),
Integer.parseInt(properties.getProperty("query.numWarmUpQueries")),
prefix + "/ifList",
Integer.parseInt(properties.getProperty("if.cacheSize")),
prefix + "/" + properties.getProperty("if.docLengthFile"),
prefix + "/" + properties.getProperty("if.termInfoFile"),
Integer.parseInt(properties.getProperty("query.neighborhood")),
rTree,
Double.parseDouble(properties.getProperty("query.radius")));
searching.open();
searching.run();
searching.close();
System.out.println("\n\nStatistics:\n" + statistics.getStatus());
}
}
|
package com.utils;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Commons extends Setup {
protected RemoteWebDriver driver;
public Commons(RemoteWebDriver driver) {
this.driver=driver;
}
public void typeValue(By locator, String value) {
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(locator));
driver.findElement(locator).click();
driver.findElement(locator).clear();
driver.findElement(locator).sendKeys(value);
}
public void clickElement(By locator) {
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(locator));
driver.findElement(locator).click();
}
/**
* This method validates if the element displayed or not
* @param locator
* @return true/false
*/
public boolean isDisplayed(By locator) {
return driver.findElement(locator).isDisplayed();
}
public String getText(By locator) {
String text = driver.findElement(locator).getText();
return text;
}
}
|
package Modeles;
import java.util.ArrayList;
import Objets.Assists;
public class MAssists extends MDefaultTable<Assists>
{
private static final long serialVersionUID = 1L;
public MAssists()
{
super();
data = new ArrayList<Assists>();
String[] newheaders = {"Cours", "Assistant", "Type"};
setHeaders(newheaders);
}
public Object getValueAt(int rowIndex, int columnIndex)
{
switch(columnIndex)
{
case 0:
return data.get(rowIndex).getCourse();
case 1:
return data.get(rowIndex).getAssistant();
case 2:
return data.get(rowIndex).getAssistant().getTypeText();
default:
return null;
}
}
}
|
/*
* Sonar Codesize Plugin
* Copyright (C) 2010 Matthijs Galesloot
* dev@sonar.codehaus.org
*
* 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 org.sonar.plugins.codesize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.nio.charset.Charset;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.ArrayUtils;
import org.junit.Test;
public class LineCounterTest {
@Test
public void testLineCounter() {
LineCounter lineCounter = new LineCounter();
lineCounter.setDefaultCharset(Charset.defaultCharset());
SizingProfile profile = new SizingProfile(new PropertiesConfiguration());
for (FileSetDefinition fileSetDefinition : profile.getFileSetDefinitions()) {
int lines = lineCounter.calculateLinesOfCode(new File("."), fileSetDefinition);
String[] withLines = new String[] { "HTML", "Java", "XML", "Test" };
if (ArrayUtils.contains(withLines, fileSetDefinition.getName())) {
assertTrue(fileSetDefinition.getName(), lines > 0);
} else {
assertEquals(fileSetDefinition.getName(), 0, lines);
}
}
}
@Test
public void customProfile() {
LineCounter lineCounter = new LineCounter();
Configuration configuration = new PropertiesConfiguration();
configuration.setProperty(CodesizeConstants.SONAR_CODESIZE_PROFILE, "Java\nincludes=src/main/java/**/*.java\nexcludes=src/main/java/**/*.java");
SizingProfile profile = new SizingProfile(configuration);
int lines = lineCounter.calculateLinesOfCode(new File("."), profile.getFileSetDefinitions().get(0));
assertEquals(0, lines);
}
}
|
/*----------------------------------------------------------------
* Author: Cristina Scheibler
* Written: 7/16/2017
* Last updated: 7/17/2017
*
* Compilation: javac Percolation.java
*
*----------------------------------------------------------------*/
import edu.princeton.cs.algs4.WeightedQuickUnionUF;
public class Percolation {
private final int numberOfSites, sizeGrid;
private int numberOfOpenSites;
private boolean[][] sites;
private final WeightedQuickUnionUF wquUF;
/**
* Create n-by-n grid, with all sites blocked.
*
* Throws a IllegalArgumentException if n is <= 0.
*/
public Percolation(int n) {
// argument is outside its prescribed range
if (n <= 0)
throw new java.lang.IllegalArgumentException("Argument is outside its prescribed range (n>0)");
sizeGrid = n;
numberOfSites = n * n;
sites = new boolean[sizeGrid][sizeGrid];
// initialize all sites to be blocked (blocked == 0)
for (int i = 0; i < sizeGrid; i++) {
for (int j = 0; j < sizeGrid; j++) {
sites[i][j] = false;
}
}
// introducing two virtual sites
wquUF = new WeightedQuickUnionUF(numberOfSites + 2);
numberOfOpenSites = 0;
}
/**
* Convert the position from the Percolation's grid to the position on the
* weighted quick union array.
*
*/
private int xyTo1D(int row, int col) {
return sizeGrid * row + col + 1;
}
/**
* Open site (row, col) if it is not open already.
*
* Throws a IllegalArgumentException if row/col is < 1 and row/col is > n.
*/
public void open(int row, int col) {
// argument is outside its prescribed range
if (row < 1 || col < 1 || row > sizeGrid || col > sizeGrid)
throw new java.lang.IllegalArgumentException(
"Argument is outside its prescribed range (row/col >= 1 and row/col <= n)");
int i = row - 1;
int j = col - 1;
if (!sites[i][j]) {
sites[i][j] = true;
// check connection with top site
if (i == 0) {
if (!wquUF.connected(0, xyTo1D(i, j))) {
wquUF.union(0, xyTo1D(i, j));
}
}
// check connection with bottom site
if (i == sizeGrid-1) {
if (!wquUF.connected(numberOfSites + 1, xyTo1D(i, j))) {
wquUF.union(numberOfSites + 1, xyTo1D(i, j));
}
}
// check site on top
if (i > 0) {
// check if site is open
if (sites[i - 1][j])
wquUF.union(xyTo1D(i, j), xyTo1D(i - 1, j));
}
// check site on bottom
if (i < sizeGrid - 1) {
// check if site is open
if (sites[i + 1][j])
wquUF.union(xyTo1D(i, j), xyTo1D(i + 1, j));
}
// check site on right
if (j < sizeGrid - 1) {
// check if site is open
if (sites[i][j + 1])
wquUF.union(xyTo1D(i, j), xyTo1D(i, j + 1));
}
// check site on left
if (j > 0) {
// check if site is open
if (sites[i][j - 1])
wquUF.union(xyTo1D(i, j), xyTo1D(i, j - 1));
}
numberOfOpenSites++;
}
}
/**
* Return if site is open.
*
* Throws a IllegalArgumentException if row/col is < 1 and row/col is > n.
*/
public boolean isOpen(int row, int col) {
// argument is outside its prescribed range
if (row < 1 || col < 1 || row > sizeGrid || col > sizeGrid)
throw new java.lang.IllegalArgumentException(
"Argument is outside its prescribed range (row/col >= 1 and row/col <= n)");
return sites[row - 1][col - 1];
}
/**
* Return if site is (row, col) full? (open and connected to the top of the
* grid).
*
* Throws a IllegalArgumentException if row/col is < 1 and row/col is > n.
*/
public boolean isFull(int row, int col) {
// argument is outside its prescribed range
if (row < 1 || col < 1 || row > sizeGrid || col > sizeGrid)
throw new java.lang.IllegalArgumentException(
"Argument is outside its prescribed range (row/col >= 1 and row/col <= n)");
if (sites[row - 1][col - 1]) {
return wquUF.connected(0, xyTo1D(row - 1, col - 1));
}
return false;
}
/**
* Return number of open sites.
*
*/
public int numberOfOpenSites() {
return numberOfOpenSites;
}
/**
* Return if the system percolates.
*
*/
public boolean percolates() {
return wquUF.connected(0, numberOfSites + 1);
}
}
|
package com.kgitbank.spring.domain.chat.controller;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.kgitbank.spring.domain.chat.dto.ChattingRoom;
import com.kgitbank.spring.domain.chat.dto.ContactDto;
import com.kgitbank.spring.domain.chat.service.ChatService;
import com.kgitbank.spring.domain.model.MemberVO;
import com.kgitbank.spring.global.util.DateFormatUtils;
import lombok.AllArgsConstructor;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
@RequestMapping("/message")
@Controller
@AllArgsConstructor
@Log4j
public class ChatController {
@Setter(onMethod_ = {@Autowired})
private ChatService service;
@RequestMapping(value = {"", "/", "/{receiverId}"}, method = RequestMethod.GET)
public String getChatPage(@PathVariable(name = "receiverId", required = false) String receiverId, HttpSession session, Model model) {
// 로그인한 아이디 가져오기
String loginId = (String) session.getAttribute("user");
if (loginId == null) {
return "redirect:/";
}
int loginSeqId = service.selectMemberById(loginId).getSeqId();
// 최근 대화 상대 목록
List<ContactDto> friends = service.selectContactList(loginSeqId);
for (ContactDto c : friends) {
c.setSendDateStr(DateFormatUtils.changeDateToAgoStr(c.getSendDate()));
}
model.addAttribute("friends", friends);
log.info(friends);
if (receiverId == null) {
return "chat/standBy";
} else {
MemberVO receiver = service.selectMemberById(receiverId);
if (receiver == null) {
return "redirect:/message";
}
int receiverSeqId = receiver.getSeqId();
log.info(receiverSeqId);
ChattingRoom room = service.selectRoomIdByUserSeqIds(loginSeqId, receiverSeqId);
log.info(room);
if (room == null) { // 자기 자신에게 메시지를 보내는 경우
return "redirect:/message";
} else {
model.addAttribute("receiver", receiver);
model.addAttribute("roomId", room.getSeqId());
model.addAttribute("messages", service.selectMessageByRoomId(room.getSeqId())); // 이전에 대화했던 메시지 내용
}
}
return "chat/main";
}
}
|
package ohjelma.verkko;
import java.util.HashSet;
import java.util.Scanner;
import ohjelma.tietorakenteet.iHashMap;
import ohjelma.tietorakenteet.iHashSet;
/**
* Luo verkon annetuista solmuista / kaarista.
*
* @author kkivikat
*/
public class Verkko {
private HashSet<Kaari> kaaret;
private iHashMap<Integer, Solmu> solmut;
public Verkko(iHashMap solmut, HashSet kaaret) {
this.solmut = solmut;
this.kaaret = kaaret;
}
/**
* Alustaa verkon luomalla solmut, kaaret ja niiden yhteydet.
*
*/
public void omaVerkko() {
System.out.println("Monta solmua verkossa on?");
Scanner lukija = new Scanner(System.in);
int solmumaara = lukija.nextInt();
for (int i = 1; i < solmumaara + 1; i++) {
solmut.put(i, new Solmu(i));
}
System.out.println("Monta kaarta verkossa on?");
int kaarimaara = lukija.nextInt();
for (int i = 1; i < kaarimaara + 1; i++) {
System.out.println("Anna kaaren " + i + " lähtösolmu (1-" + solmumaara + ")");
int lahto = lukija.nextInt();
System.out.println("Anna kaaren " + i + " kohdesolmu (1-" + solmumaara + ")");
int kohde = lukija.nextInt();
System.out.println("Anna kaaren " + i + " pituus");
int pituus = lukija.nextInt();
kaaret.add(new Kaari(solmut.get(lahto).getSolmu(), solmut.get(kohde).getSolmu(), pituus));
}
}
// Testi 1, isompi verkko
public void teeIsoVerkko() {
Solmu eka = new Solmu(1);
Solmu toka = new Solmu(2);
Solmu kol = new Solmu(3);
Solmu nel = new Solmu(4);
Solmu viis = new Solmu(5);
Solmu kuus = new Solmu(6);
Solmu seitt = new Solmu(7);
Solmu kasi = new Solmu(8);
Solmu ysi = new Solmu(9);
Solmu kyba = new Solmu(10);
solmut.put(1, eka);
solmut.put(2, toka);
solmut.put(3, kol);
solmut.put(4, nel);
solmut.put(5, viis);
solmut.put(6, kuus);
solmut.put(7, seitt);
solmut.put(8, kasi);
solmut.put(9, ysi);
solmut.put(10, kyba);
Kaari kaari1 = new Kaari(eka, toka, 1);
Kaari kaari2 = new Kaari(eka, kol, 3);
Kaari kaari3 = new Kaari(kol, toka, 1);
Kaari kaari4 = new Kaari(nel, toka, 2);
Kaari kaari5 = new Kaari(nel, kuus, 2);
Kaari kaari6 = new Kaari(kuus, kasi, 2);
Kaari kaari7 = new Kaari(kasi, kyba, 10);
Kaari kaari8 = new Kaari(kol, viis, 2);
Kaari kaari9 = new Kaari(viis, seitt, 1);
Kaari kaari10 = new Kaari(seitt, ysi, 7);
Kaari kaari11 = new Kaari(ysi, kyba, 7);
Kaari kaari12 = new Kaari(viis, nel, 4);
Kaari kaari13 = new Kaari(viis, kuus, 2);
Kaari kaari14 = new Kaari(kuus, seitt, 3);
Kaari kaari15 = new Kaari(ysi, kuus, 3);
Kaari kaari16 = new Kaari(kasi, ysi, 2);
kaaret.add(kaari1);
kaaret.add(kaari2);
kaaret.add(kaari3);
kaaret.add(kaari4);
kaaret.add(kaari5);
kaaret.add(kaari6);
kaaret.add(kaari7);
kaaret.add(kaari8);
kaaret.add(kaari9);
kaaret.add(kaari10);
kaaret.add(kaari11);
kaaret.add(kaari12);
kaaret.add(kaari13);
kaaret.add(kaari14);
kaaret.add(kaari15);
kaaret.add(kaari16);
System.out.println("Oikeat loppupainot: " + "\n"
+ "0, 1, 3, 9, 5, 7, 6, 9, 11, 18");
System.out.println("");
}
/**
* **********************************************
*/
// Testi 2, pienempi verkko, paljon kaaria
public void teePieniVerkko1() {
Solmu eka = new Solmu(1);
Solmu toka = new Solmu(2);
Solmu kol = new Solmu(3);
Solmu nel = new Solmu(4);
Solmu viis = new Solmu(5);
solmut.put(1, eka);
solmut.put(2, toka);
solmut.put(3, kol);
solmut.put(4, nel);
solmut.put(5, viis);
Kaari kaari1 = new Kaari(eka, toka, 5);
Kaari kaari2 = new Kaari(eka, kol, 9);
Kaari kaari3 = new Kaari(kol, toka, 3);
Kaari kaari4 = new Kaari(toka, nel, 10);
Kaari kaari5 = new Kaari(kol, viis, 7);
Kaari kaari6 = new Kaari(viis, kol, 1);
Kaari kaari7 = new Kaari(nel, viis, 4);
Kaari kaari8 = new Kaari(kol, nel, 2);
Kaari kaari9 = new Kaari(toka, viis, 1);
kaaret.add(kaari1);
kaaret.add(kaari2);
kaaret.add(kaari3);
kaaret.add(kaari4);
kaaret.add(kaari5);
kaaret.add(kaari6);
kaaret.add(kaari7);
kaaret.add(kaari8);
kaaret.add(kaari9);
System.out.println("Oikeat loppupainot: " + "\n"
+ "0, 5, 7, 9, 6");
System.out.println("");
}
/**
* **********************************************
*/
// Testi 3, pieni verkko
public void teePieniVerkko2() {
Solmu eka = new Solmu(1);
Solmu toka = new Solmu(2);
Solmu kol = new Solmu(3);
solmut.put(1, eka);
solmut.put(2, toka);
solmut.put(3, kol);
Kaari kaari1 = new Kaari(eka, toka, 4);
Kaari kaari2 = new Kaari(eka, kol, 2);
Kaari kaari3 = new Kaari(toka, eka, 2);
Kaari kaari4 = new Kaari(toka, kol, 2);
Kaari kaari5 = new Kaari(kol, eka, 1);
Kaari kaari6 = new Kaari(kol, toka, 1);
kaaret.add(kaari1);
kaaret.add(kaari2);
kaaret.add(kaari3);
kaaret.add(kaari4);
kaaret.add(kaari5);
kaaret.add(kaari6);
System.out.println("Oikeat loppupainot: " + "\n"
+ "0, 3, 2");
System.out.println("");
}
/**
* **********************************************
*/
// Testi 4, Verkko negatiivisilla painoilla (Ei neg. sykliä)
public void teeNegPainollinenVerkko() {
Solmu eka = new Solmu(1);
Solmu toka = new Solmu(2);
Solmu kol = new Solmu(3);
Solmu nel = new Solmu(4);
Solmu viis = new Solmu(5);
solmut.put(1, eka);
solmut.put(2, toka);
solmut.put(3, kol);
solmut.put(4, nel);
solmut.put(5, viis);
Kaari kaari1 = new Kaari(eka, toka, 5);
Kaari kaari2 = new Kaari(eka, kol, 5);
Kaari kaari3 = new Kaari(toka, nel, 3);
Kaari kaari4 = new Kaari(toka, kol, -3);
Kaari kaari5 = new Kaari(kol, nel, 5);
Kaari kaari6 = new Kaari(kol, viis, 10);
Kaari kaari7 = new Kaari(nel, toka, 2);
Kaari kaari8 = new Kaari(viis, nel, -6);
kaaret.add(kaari1);
kaaret.add(kaari2);
kaaret.add(kaari3);
kaaret.add(kaari4);
kaaret.add(kaari5);
kaaret.add(kaari6);
kaaret.add(kaari7);
kaaret.add(kaari8);
System.out.println("Oikeat loppupainot: " + "\n"
+ "0, 5, 2, 6, 12");
System.out.println("");
}
/**
* **********************************************
*/
// Testi 5, negatiivinen sykli
public void teeSyklillinenVerkko() {
Solmu eka = new Solmu(1);
Solmu toka = new Solmu(2);
Solmu kol = new Solmu(3);
Solmu nel = new Solmu(4);
Solmu viis = new Solmu(5);
solmut.put(1, eka);
solmut.put(2, toka);
solmut.put(3, kol);
solmut.put(4, nel);
solmut.put(5, viis);
Kaari kaari1 = new Kaari(eka, toka, 5);
Kaari kaari2 = new Kaari(eka, kol, 5);
Kaari kaari3 = new Kaari(toka, nel, 3);
Kaari kaari4 = new Kaari(toka, kol, -3);
Kaari kaari5 = new Kaari(kol, nel, 5);
Kaari kaari6 = new Kaari(kol, viis, 10);
Kaari kaari7 = new Kaari(nel, toka, -3);
Kaari kaari8 = new Kaari(viis, nel, -6);
kaaret.add(kaari1);
kaaret.add(kaari2);
kaaret.add(kaari3);
kaaret.add(kaari4);
kaaret.add(kaari5);
kaaret.add(kaari6);
kaaret.add(kaari7);
kaaret.add(kaari8);
System.out.println("Oikeat loppupainot: " + "\n"
+ "Bellman: FALSE, sykli. Dijkstra: ei toimi, antaa vääriä painoja");
System.out.println("");
}
/**
* Palauttaa kaikki verkkoon kuuluvat kaaret.
*
*/
public HashSet<Kaari> getKaaret() {
return kaaret;
}
/**
* Palauttaa kaikki verkkoon kuuluvat solmut).
*
*/
public iHashMap<Integer, Solmu> getSolmut() {
return solmut;
}
} |
package cn.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller("helloController")
public class HelloController {
public HelloController() {
System.out.println("hello");
}
@RequestMapping("/hello")
@ResponseBody
public String hello() {
return "你好, 世界!!";
}
@RequestMapping("/demo")
@ResponseBody
public String demo() {
return "初始化完成";
}
}
|
/**
* Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro
* Copyright: 2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package seava.ad.business.impl.system;
import java.util.List;
import javax.persistence.EntityManager;
import seava.ad.business.api.system.IDataSourceService;
import seava.ad.domain.impl.system.DataSource;
import seava.ad.domain.impl.system.DataSourceField;
import seava.ad.domain.impl.system.DataSourceRpc;
import seava.j4e.business.service.entity.AbstractEntityService;
/**
* Repository functionality for {@link DataSource} domain entity. It contains
* finder methods based on unique keys as well as reference fields.
*
*/
public class DataSource_Service extends AbstractEntityService<DataSource>
implements
IDataSourceService {
public DataSource_Service() {
super();
}
public DataSource_Service(EntityManager em) {
super();
this.setEntityManager(em);
}
@Override
public Class<DataSource> getEntityClass() {
return DataSource.class;
}
/**
* Find by unique key
*/
public DataSource findByName(String name) {
return (DataSource) this.getEntityManager()
.createNamedQuery(DataSource.NQ_FIND_BY_NAME)
.setParameter("name", name).getSingleResult();
}
/**
* Find by unique key
*/
public DataSource findByModel(String model) {
return (DataSource) this.getEntityManager()
.createNamedQuery(DataSource.NQ_FIND_BY_MODEL)
.setParameter("model", model).getSingleResult();
}
/**
* Find by reference: fields
*/
public List<DataSource> findByFields(DataSourceField fields) {
return this.findByFieldsId(fields.getId());
}
/**
* Find by ID of reference: fields.id
*/
public List<DataSource> findByFieldsId(String fieldsId) {
return (List<DataSource>) this
.getEntityManager()
.createQuery(
"select distinct e from DataSource e, IN (e.fields) c where c.id = :fieldsId",
DataSource.class).setParameter("fieldsId", fieldsId)
.getResultList();
}
/**
* Find by reference: serviceMethods
*/
public List<DataSource> findByServiceMethods(DataSourceRpc serviceMethods) {
return this.findByServiceMethodsId(serviceMethods.getId());
}
/**
* Find by ID of reference: serviceMethods.id
*/
public List<DataSource> findByServiceMethodsId(String serviceMethodsId) {
return (List<DataSource>) this
.getEntityManager()
.createQuery(
"select distinct e from DataSource e, IN (e.serviceMethods) c where c.id = :serviceMethodsId",
DataSource.class)
.setParameter("serviceMethodsId", serviceMethodsId)
.getResultList();
}
}
|
package Quiz1;
import java.util.*;
public class Laptop {
Scanner s = new Scanner(System.in);
String brand;
String color;
String model;
String screen;
double weight;
public void setBrand() {
System.out.println("Enter the brand : ");
this.brand = s.next();
}
public void setColor() {
System.out.println("Enter the color : ");
this.color = s.next();;
}
public void setModel() {
System.out.println("Enter the model : ");
this.model = s.next();;
}
public void setScreen() {
System.out.println("Enter the screen : ");
this.screen = s.next();;
}
public void setWeight() {
System.out.println("Enter the weight : ");
this.weight = s.nextDouble();;
}
public String getBrand() {
return this.brand;
}
public String getColor() {
return this.color;
}
public String getModel() {
return this.model;
}
public String getScreen() {
return this.screen;
}
public double getWeight() {
return this.weight;
}
public void info() {
setBrand();
setColor();
setModel();
setScreen();
setWeight();
}
}
|
package de.ronnyritscher.projekt_codesnippetcollectionapp;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MainRecyclerViewAdapter extends RecyclerView.Adapter<MainRecyclerViewAdapter.MyViewHolder> {
private static final String TAG = MainRecyclerViewAdapter.class.getSimpleName();
//MyViewHolder (innerClass)
public static class MyViewHolder extends RecyclerView.ViewHolder{
//MEMBER: Wir benötigen Member
public TextView demoName;
public TextView demoDiscription;
public TextView demoClassName;
//CONSTRUCTOR
public MyViewHolder(@NonNull View itemView) {
super(itemView);
demoName = itemView.findViewById(R.id.tv_main_item_demoName);
demoDiscription = itemView.findViewById(R.id.tv_main_item_demoDescription);
demoClassName = itemView.findViewById(R.id.tv_main_item_demoClassName);
}
}
@NonNull
@Override
public MainRecyclerViewAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
//LayoutInflater
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_main_layout, null);
// wir erzeugen ein neuen VH und geben diesen zurück
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull MainRecyclerViewAdapter.MyViewHolder viewHolder, int i) {
// besogt die Daten aus der Array-Liste (MainActivity.demoArrayList)
// und fügt diese in die platzhalter der items der RV ein...
viewHolder.demoName.setText(MainActivity.demoArrayList.get(i).getName());
viewHolder.demoDiscription.setText(MainActivity.demoArrayList.get(i).getDescription());
viewHolder.demoClassName.setText(MainActivity.demoArrayList.get(i).getClassName());
//Hier können wir die einzelnen Elemente anklicken -> neue Activity starten
viewHolder.itemView.setOnClickListener( (v) -> {
Log.d(TAG, "PackageName: "+v.getContext().getPackageName());
Log.d(TAG, "activityToStart: " + v.getContext().getPackageName().concat(".").concat(viewHolder.demoClassName.getText().toString()));
//PackageName+Trennzeichen+ActivityName identifizieren
String activityToStart = v.getContext().getPackageName().concat(".").concat(viewHolder.demoClassName.getText().toString());
//String activityToStart = v.getContext().getPackageName().concat(".").concat(viewHolder.demoClassName.getText().toString());
try {
Class<?> activityToStartClass = Class.forName(activityToStart); //ClassObjekt aus dem String erhalten
Log.d(TAG, "activityToStartClass: "+activityToStartClass);
Intent intent = new Intent(v.getContext(), activityToStartClass); //Intent erzeugen
v.getContext().startActivity(intent); //start Activity
} catch (ClassNotFoundException ignored) {
Toast.makeText(v.getContext(), "ClassNotFoundException", Toast.LENGTH_SHORT).show();
}
// String activitiName = "AlertDialogDemoActivity.class";
// Class<?> myClass = Class.forName(activitiName);
//
// Intent intent = new Intent(v.getContext() , activitiName);
// v.getContext().startActivity(intent);
//viewHolder.itemView.getContext().startActivity(new Intent(viewHolder.itemView.getContext(), viewHolder.demoClassName));
});
}
@Override
public int getItemCount() {
return MainActivity.demoArrayList.size(); // Gibt die Größe der Liste an/zurück
}
}
|
package com.tencent.mm.plugin.freewifi.e;
import com.tencent.mm.plugin.freewifi.m;
import com.tencent.mm.sdk.platformtools.x;
public final class d {
private String bIQ;
private String bLe;
private int jkE;
/* synthetic */ d(byte b) {
this();
}
private d() {
}
public final synchronized boolean j(int i, String str, String str2) {
boolean z = true;
synchronized (this) {
boolean z2;
x.i("MicroMsg.FreeWifi.Protocol31Locker", "threeOneStartUpType=%d, apKey=%s, ticket=%s", new Object[]{Integer.valueOf(i), str, str2});
if (i == 1 || i == 2 || i == 3) {
z2 = true;
} else {
z2 = false;
}
if (z2) {
if (m.isEmpty(str) || m.isEmpty(str2)) {
z = false;
} else if (str.equals(this.bIQ) && str2.equals(this.bLe) && this.jkE != i) {
z = false;
} else {
this.jkE = i;
this.bIQ = str;
this.bLe = str2;
}
}
}
return z;
}
}
|
package com.github.jerrysearch.tns.console.draw;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.Ansi.Color;
import org.fusesource.jansi.AnsiConsole;
import com.github.jerrysearch.tns.console.util.LogEventTimeWheel;
import com.github.jerrysearch.tns.protocol.rpc.event.LogEvent;
import com.github.jerrysearch.tns.protocol.rpc.event.Operation;
public class ConsoleDraw implements Runnable {
private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
public void start() {
this.drawHead();
this.executor.scheduleWithFixedDelay(this, 1, 1, TimeUnit.SECONDS);
}
private long lastSeconds = System.currentTimeMillis() / 1000;
@Override
public void run() {
this.lastSeconds += 1; // 获取下个一秒发生的数据
long pollSeconds = this.lastSeconds;
boolean have = false;
while (true) {
LogEvent event = LogEventTimeWheel.getInstance().poll(pollSeconds);
if (null == event) {
if (!have) {
// 没取到值并且这次没有输出过event
this.drawEmpty();
}
return;
} else {
this.lastSeconds = event.getTimestamp() / 1000;
if (have) {
// 这一次输出的非第一行记录
this.drawEventWithEmptyTime(event);
} else {
// 这一次输出的第一行记录
this.drawEventWithCurrentTime(event);
}
have = true;
}
}
}
private void drawEventWithCurrentTime(LogEvent event) {
String cTime = this.formatTime(System.currentTimeMillis());
this.drawEvent(cTime, event);
}
private void drawEventWithEmptyTime(LogEvent event) {
this.drawEvent("", event);
}
private void drawEvent(String cTime, LogEvent event) {
long timestamp = event.getTimestamp();
String source = event.getSource();
Operation operation = event.getOperation();
List<String> attributes = event.getAttributes();
this.draw(cTime, this.formatTime(timestamp), source, operation.name(),
this.toJsonString(attributes));
}
private void drawEmpty() {
this.draw(this.formatTime(System.currentTimeMillis()), "*", "*", "*", "*");
}
private void drawHead() {
String tmp = "";
this.draw("cTime", "eTime", "source", "operation", "attributes");
this.draw(tmp, tmp, tmp, tmp, tmp);
}
private void draw(String cTime, String eTime, String source, String operation, String attributes) {
AnsiConsole.systemInstall();
System.out.println(Ansi.ansi().fg(Color.RED).a(String.format("%-12s", cTime))
.fg(Color.YELLOW).a(String.format("%-12s", eTime)).fg(Color.RED)
.a(String.format("%-25s", source)).fg(Color.GREEN)
.a(String.format("%-15s", operation)).fg(Color.BLUE).a(attributes).reset());
AnsiConsole.systemUninstall();
}
private String formatTime(long t) {
return String.format("%tT", t);
}
private String toJsonString(List<String> attributes) {
return Arrays.toString(attributes.toArray());
}
}
|
package org.hpe.df.utilities;
import org.ojai.store.Connection;
import org.ojai.store.DocumentStore;
import org.ojai.store.DriverManager;
import org.ojai.store.Query;
public class ViewDBRows {
public static void main(String[] args) {
String storeName = "/metrics";
DocumentStore store;
Connection connection = DriverManager.getConnection("ojai:mapr:");
if ( connection.storeExists(storeName) ) {
store = connection.getStore(storeName);
} else {
store = connection.createStore(storeName);
}
Query query = connection.newQuery()
.build();
store.find(query).forEach( doc -> {
System.out.println(doc.asJsonString());
});
}
}
|
package net.lin.www;
import com.google.gson.Gson;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
/**
* Created by Lin on 12/29/15.
*/
public class YelloPageCrawler
{
static String host = "";
String source;
String city;
int version = 1;
String filename;
String ypSaerchRawDataPath;
String ypContentRawDataPath;
String geoLocationTerm;
String analysisFilename = "data/";
public static void main(String[] args)
{
// imput data
String source = "";
String city = "New York";
String geoLocationTerm = "";
YelloPageCrawler yelloPageCrawler = new YelloPageCrawler(source, city, geoLocationTerm);
yelloPageCrawler.getVendors(yelloPageCrawler.analyseActivity());
}
YelloPageCrawler(String source, String city, String geoLocationTerm)
{
this.geoLocationTerm = geoLocationTerm;
this.source = source;
this.city = city;
this.filename = "./data/" + this.source + "/" + this.source + "_" + this.city + "_data_with_contact_info_v" + version + ".txt";
File file = new File(filename);
while(file.exists())
{
version ++;
this.filename = "./data/" + this.source + "/" + this.source +"_data_with_contact_info_v" + version + ".txt";
file = new File(filename);
}
System.out.println("Use File: " + filename);
this.ypSaerchRawDataPath = "./data/" + this.source + "/rawData/" + this.city + "/YellowPage/search/";
this.ypContentRawDataPath = "./data/" + this.source + "/rawData/" + this.city + "/YellowPage/content/";
this.analysisFilename = "./data/" + this.source + "/" + this.source + "_" + this.city + "_vendorAnalysis.txt";
}
public void getVendors(LinkedList<Vendor> vendorList)
{
Gson gson = new Gson();
int vendorCount = 0;
System.out.println("Vendor Number: " + vendorList.size());
System.out.println();
while(vendorCount < vendorList.size())
{
Vendor vendor = vendorList.get(vendorCount);
if(vendor.vendorName == null || vendor.vendorName.trim().equals(""))
{
System.out.println("vendorName is null: ");
vendor.print();
vendorCount ++;
continue;
}
System.out.println(vendorCount + " " + vendor.vendorName);
System.out.println("activity Num: " + vendor.activities.size());
String[] nameArray = vendor.vendorName.split(" ");
String url = "http://www.yellowpages.com/search?search_terms=";
for(int count = 0; count < nameArray.length; count++)
{
try
{
url = url + URLEncoder.encode(nameArray[count], "UTF-8");
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if((count + 1) < nameArray.length)
url = url + "+";
}
url = url + "&geo_location_terms=" + geoLocationTerm;
System.out.println(url);
getVendorYellowPage(vendor, url, vendorCount);
String vendorInJson = gson.toJson(vendor);
FileOperator.printFile_AddOn(filename, vendorInJson);
vendorCount++;
}
}
protected boolean getVendorYellowPage(Vendor vendor, String searchUrl, int vendorCount)
{
Document document = PageLoader.getPage(searchUrl);
if(document == null)
return false;
//Write raw data
String searchHtml = ypSaerchRawDataPath + vendorCount + "_search.html";
FileOperator.printFile_OverWrite(searchHtml, document.toString());
Element searchResultDiv = document.getElementsByClass("organic").first();
Element targetDiv = searchResultDiv.getElementsByClass("v-card").first();
Element h3 = targetDiv.getElementsByTag("h3").first();
Elements isExternal = h3.getElementsByClass("external-link");
String mainPageUrl = null;
if(isExternal != null && !isExternal.isEmpty())
mainPageUrl = host + targetDiv.select("a.track-more-info").attr("href");
else
mainPageUrl = host + targetDiv.getElementsByTag("h3").first().getElementsByTag("a").attr("href");
System.out.println(mainPageUrl);
document = PageLoader.getPage(mainPageUrl);
if(document == null)
return false;
//Write raw date
String contentHtml = ypContentRawDataPath + vendorCount + "_content.html";
FileOperator.printFile_OverWrite(contentHtml, document.toString());
//get info
Element businessCard = document.getElementsByClass("business-card").first();
vendor.yellowPageName = businessCard.getElementsByTag("h1").text();
System.out.println("vender name: " + vendor.vendorName);
System.out.println("yp vender name:" + vendor.yellowPageName);
vendor.yellowPageaddress = businessCard.getElementsByClass("street-address").text();
vendor.city_state = businessCard.getElementsByClass("city-state").text();
System.out.println("address: " + vendor.yellowPageaddress);
System.out.println("city: " + vendor.city_state);
vendor.phoneNumber = businessCard.getElementsByClass("phone").text();
System.out.println("phone number: " + vendor.phoneNumber);
Element footer = businessCard.getElementsByTag("footer").first();
Elements emailElements = footer.getElementsByClass("email-business");
if(emailElements != null && !emailElements.isEmpty())
{
String emailHref = emailElements.first().attr("href");
vendor.email = emailHref.substring(emailHref.indexOf(":") + 1);
}
System.out.println("email: " + vendor.email);
Elements websiteElements = footer.getElementsByClass("custom-link");
if(websiteElements != null && !websiteElements.isEmpty())
vendor.website = websiteElements.first().attr("href");
System.out.println("website: " + vendor.website);
System.out.println();
return true;
}
protected LinkedList<Activity> readGroupOnActivities()
{
LinkedList<Activity> activityList = new LinkedList<Activity>();
LinkedList<String> categories = new LinkedList<String>();
categories.add("Activities");
categories.add("Nightlife");
categories.add("Sightseeing");
categories.add("Classes");
categories.add("Tickets & Events");
Gson gson = new Gson();
for(String category : categories)
{
LinkedList<String> tempList = FileOperator.readFile("./data/" + source + "/Activity/" + source + "-" + city + "-" + category + "-1.txt");
for(String activityString : tempList)
{
Activity activity = gson.fromJson(activityString, Activity.class);
if(activity.city == null || activity.city.equals(""))
activity.city = city;
if(activity.source == null || activity.source.equals(""))
activity.source = source;
activityList.add(activity);
}
}
return activityList;
}
protected LinkedList<Activity> readActivities()
{
if(source == "Vimbly")
return readVimblyActivities();
else if(source == "GroupOn")
return readGroupOnActivities();
else if(source == "GiltCity")
return readGiltCityActivities();
else if(source == "Yelp")
return readYelpActivity();
else
{
System.out.println("No such source");
return null;
}
}
protected LinkedList<Activity> readYelpActivity()
{
LinkedList<Activity> activityLinkedList = new LinkedList<Activity>();
Gson gson = new Gson();
String category = "Discount";
LinkedList<String> activityStringList = FileOperator.readFile("./data/" + source + "/Activity/" + city + "/" + source + "-" + city + "-" + category + "-1.txt");
for(String activityString : activityStringList)
{
Activity activity = gson.fromJson(activityString, Activity.class);
activityLinkedList.add(activity);
}
return activityLinkedList;
}
protected LinkedList<Activity> readGiltCityActivities()
{
LinkedList<Activity> activitieList = new LinkedList<Activity>();
Gson gson = new Gson();
String cat = "null";
LinkedList<String> tempList = FileOperator.readFile("./data/" + source + "/Activity/" + city + "/" + source + "-" + city + "-" + cat + "-1.txt");
for(String activityString : tempList)
{
Activity activity = gson.fromJson(activityString, Activity.class);
activitieList.add(activity);
}
return activitieList;
}
/**
* Get Vimbly vendor information
* @return
*/
protected LinkedList<Activity> readVimblyActivities()
{
LinkedList<Activity> activitieList = new LinkedList<Activity>();
LinkedList<String> category = new LinkedList<String>();
category.add("date");
category.add("drink");
category.add("eat");
category.add("explore");
category.add("fight");
category.add("learn");
category.add("watch");
Gson gson = new Gson();
for(String cat : category)
{
LinkedList<String> tempList = FileOperator.readFile("./data/" + source + "/Activity/" + city + "/" + source + "-" + city + "-" + cat + "-v1.txt");
for(String activity : tempList)
{
Activity vimblyActivity = gson.fromJson(activity, Activity.class);
activitieList.add(vimblyActivity);
}
}
return activitieList;
}
public LinkedList<Vendor> analyseActivity()
{
int activityCount = 0;
int vendorCount = 0;
LinkedList<Activity> activityLinkedList = readActivities();
LinkedList<String> analysis = new LinkedList<String>();
activityCount = activityLinkedList.size();
System.out.println("Activity Number: " + activityCount);
analysis.add("Activity Number: " + activityCount);
HashMap<String, LinkedList<Activity>> vendorMap = new HashMap<String, LinkedList<Activity>>();
for(Activity v : activityLinkedList)
{
if(vendorMap.containsKey(v.vendorName))
vendorMap.get(v.vendorName).add(v);
else
{
LinkedList<Activity> tempList = new LinkedList<Activity>();
tempList.add(v);
vendorMap.put(v.vendorName, tempList);
}
}
LinkedList<Vendor> vendorLinkedList = new LinkedList<Vendor>();
for(Map.Entry entry : vendorMap.entrySet())
{
Vendor vendor = new Vendor();
vendor.vendorName = (String)entry.getKey();
vendor.activities = (LinkedList<Activity>) entry.getValue();
vendor.activityNum = vendor.activities.size();
vendorLinkedList.add(vendor);
}
Collections.sort(vendorLinkedList, new Comparator<Vendor>()
{
@Override
public int compare(Vendor o1, Vendor o2)
{
if(o1.activityNum < o2.activityNum)
return 1;
else if(o1.activityNum > o2.activityNum)
return -1;
else
return 0;
}
});
for(Vendor vendor : vendorLinkedList)
{
analysis.add(vendorCount + " " + vendor.vendorName + " : " + vendor.activityNum);
vendorCount++;
}
System.out.println("vendor Num: " + vendorCount);
analysis.addFirst("vendor Num: " + vendorCount);
FileOperator.printFile_OverWrite(analysisFilename, analysis);
return vendorLinkedList;
}
}
|
package Lab04.Zad3;
public class Main {
public static void main(String[] args) {
Editor editor = new Editor(500,500);
}
}
|
package ifl.games.runtime.Menus;
import ifl.games.runtime.ManagedScene;
/**
*** @author Brian Broyles - IFL Game Studio
**/
public abstract class ManagedMenuScene extends ManagedScene {
public ManagedMenuScene(float pLoadingScreenMinimumSecondsShown) {
super(pLoadingScreenMinimumSecondsShown);
}
@Override
public void onUnloadManagedScene() {
if(isLoaded) {
// For menus, we are disabling the reloading of resources.
// isLoaded = false;
onUnloadScene();
}
}
} |
package com.santander.bi.dtos;
import java.sql.Timestamp;
public class EstatusDTO {
private Integer idEstatus;
private String estatus;
private String descripcion;
//CAMPOS SEGUIMIENTO
private String habilitado="H";
private Timestamp fechaCreacion;
private String usuarioCreador;
private Timestamp fechaModificacion;
private String usuarioModifica;
public Integer getIdEstatus() {
return idEstatus;
}
public void setIdEstatus(Integer idEstatus) {
this.idEstatus = idEstatus;
}
public String getEstatus() {
return estatus;
}
public void setEstatus(String estatus) {
this.estatus = estatus;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getHabilitado() {
return habilitado;
}
public void setHabilitado(String habilitado) {
this.habilitado = habilitado;
}
public Timestamp getFechaCreacion() {
return fechaCreacion;
}
public void setFechaCreacion(Timestamp fechaCreacion) {
this.fechaCreacion = fechaCreacion;
}
public String getUsuarioCreador() {
return usuarioCreador;
}
public void setUsuarioCreador(String usuarioCreador) {
this.usuarioCreador = usuarioCreador;
}
public Timestamp getFechaModificacion() {
return fechaModificacion;
}
public void setFechaModificacion(Timestamp fechaModificacion) {
this.fechaModificacion = fechaModificacion;
}
public String getUsuarioModifica() {
return usuarioModifica;
}
public void setUsuarioModifica(String usuarioModifica) {
this.usuarioModifica = usuarioModifica;
}
}
|
package com.bierocratie.ui.view.catalog;
import com.bierocratie.model.catalog.Beer;
import com.bierocratie.model.catalog.Supplier;
import com.bierocratie.ui.NavigatorUI;
import com.bierocratie.ui.component.AbstractMenuBar;
import com.bierocratie.ui.component.OrderMenuBar;
import com.bierocratie.ui.view.AbstractBasicModelView;
import com.vaadin.addon.jpacontainer.JPAContainer;
import com.vaadin.addon.jpacontainer.JPAContainerFactory;
import com.vaadin.data.Container;
import com.vaadin.data.util.BeanItem;
import com.vaadin.data.util.filter.Compare;
import com.vaadin.external.org.slf4j.Logger;
import com.vaadin.external.org.slf4j.LoggerFactory;
import com.vaadin.ui.Button;
import com.vaadin.ui.Table;
public class SupplierView extends AbstractBasicModelView<Supplier> {
private static final Logger LOG = LoggerFactory.getLogger(SupplierView.class);
@Override
protected Class<Supplier> getClazz() {
return Supplier.class;
}
@Override
protected String getTableName() {
return "Brasseries & fournisseurs";
}
@Override
protected AbstractMenuBar getMenuBar() {
// FIXME @Inject
return new OrderMenuBar();
}
private JPAContainer<Beer> beers;
private Button addBeerButton;
private Table beerTable;
@Override
protected void buildAndBind() {
form.addComponent(binder.buildAndBind("Nom", "name"));
form.addComponent(binder.buildAndBind("Adresse", "address"));
form.addComponent(binder.buildAndBind("Email", "email"));
form.addComponent(binder.buildAndBind("Téléphone", "telephone"));
beers = JPAContainerFactory.make(Beer.class, "orderhelper");
beerTable = new Table("Bières", beers);
// TODO Ajouter une colonne pour chaque format
beerTable.setVisibleColumns(new String[]{"name", "description", "supplier"});
beerTable.setColumnHeader("name", "Nom");
beerTable.setColumnHeader("description", "Description");
beerTable.setColumnHeader("supplier", "Fournisseur");
beerTable.setEnabled(false);
beerTable.setPageLength(0);
binder.bind(beerTable, "beers");
form.addComponent(beerTable);
addBeerButton = new Button("Nouvelle bière");
addBeerButton.addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent clickEvent) {
getUI().getNavigator().navigateTo(NavigatorUI.BEER_VIEW + "/" + addBeerButton.getData());
}
});
form.addComponent(addBeerButton);
}
@Override
protected void updateForm(Supplier item) {
if ((boolean) addButton.getData()) {
addBeerButton.setEnabled(false);
} else {
addBeerButton.setEnabled(true);
addBeerButton.setData(item.getId());
refreshContainerFilters(item);
}
}
@Override
protected boolean isUpdateAuthorized(Supplier item) {
return true;
}
private void refreshContainerFilters(Supplier item) {
Container.Filter supplierFilter = new Compare.Equal("supplier", item);
beers.removeAllContainerFilters();
beers.addContainerFilter(supplierFilter);
}
@Override
protected void postSaveItemProcessing(Supplier item) {
}
@Override
protected void getMultiFormValues() {
}
@Override
protected void setItemValues(Supplier item) {
}
@Override
protected void postSaveItemsProcessing() {
}
@Override
protected BeanItem<Supplier> createNewBeanItem() {
Supplier newItem = new Supplier();
refreshContainerFilters(newItem);
return new BeanItem<>(newItem);
}
@Override
protected void createMultiSelectForm() {
}
@Override
protected BeanItem<Supplier> createCopiedBeanItem(Supplier item) {
Supplier copy = new Supplier();
copy.setName(item.getName());
copy.setCountry(item.getCountry());
copy.setAddress(item.getAddress());
copy.setTelephone(item.getTelephone());
copy.setEmail(item.getEmail());
copy.setType(item.getType());
return new BeanItem<>(copy);
}
@Override
protected void addDataToItem(Supplier item) throws Exception {
}
@Override
protected void preSaveItemProcessing(Supplier item) {
}
@Override
protected void setTableColumns() {
table.setVisibleColumns(new String[]{"name", "address", "email", "telephone"});
table.setColumnHeader("name", "Nom");
table.setColumnHeader("address", "Adresse");
table.setColumnHeader("email", "Email");
table.setColumnHeader("telephone", "Téléphone");
}
}
|
package com.dahua.design.creation.factory.simplefactory;
public class simplaFactoryTest {
public static void main(String[] args) {
AbstractPayWay ali = PayFactory.getPayWay("ali");
ali.pay();
AbstractPayWay tx = PayFactory.getPayWay("tx");
tx.pay();
}
}
|
package UserExamples;
import COMSETsystem.AgentModule;
import COMSETsystem.Intersection;
import COMSETsystem.ResourceAnalyzerModule;
public class Agent extends AgentModule {
public Agent(Intersection loc, ResourceAnalyzerModule resMod) {
super(loc, resMod);
}
@Override
//TODO Implement your own move() and other auxiliary methods
public Intersection move(Object resourseAnalysis) {
return null;
}
}
|
package babylanguage.babyapp.practicelanguagecommon;
import android.app.Dialog;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import babylanguage.babyapp.appscommon.services.AndroidHelper;
import services.AppConstants;
public class HelpDialogPro {
public static Dialog dialog;
public static boolean enableReward = false;
public static void showHelpDialog(final WordsGameActivity mContext){
dialog = new Dialog(mContext);
dialog.setTitle(R.string.help_dialog_title);
dialog.setContentView(R.layout.help_dialog_pro);
Button askFriendButton = dialog.findViewById(R.id.ask_friend);
askFriendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mContext.openShare();
dialog.dismiss();
}
});
Button addWordButton = dialog.findViewById(R.id.add_word);
addWordButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mContext.revealWord();
dialog.dismiss();
}
});
Button showAnswerButton = dialog.findViewById(R.id.show_answer);
showAnswerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mContext.showAnswer();
dialog.dismiss();
}
});
if(enableReward){
enableRewardButton();
}
dialog.getWindow().setLayout(((AndroidHelper.getContextWidth(mContext) / 100) * 90), LinearLayout.LayoutParams.WRAP_CONTENT);
AndroidHelper.setAddBanner(R.id.addWrapper, mContext, dialog, AppConstants.banner_unit_id);
dialog.show();
}
public static void enableRewardButton(){
enableReward = true;
if(dialog != null){
dialog.findViewById(R.id.reward_word).setEnabled(true);
}
}
public static void disableRewardButton(){
enableReward = false;
if(dialog != null){
dialog.findViewById(R.id.reward_word).setEnabled(false);
}
}
}
|
package com.osce.result;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName: ErrorContext
* @Description: 错误上下文,错误堆栈
* @Author yangtongbin
* @Date 2017/9/13 16:37
*/
public class ErrorContext {
/** 错误堆栈 */
private List<CommonError> errorStack = new ArrayList<CommonError>();
public ErrorContext(){
}
public ErrorContext(List<CommonError> errorStack) {
this.errorStack = errorStack;
}
public List<CommonError> getErrorStack() {
return errorStack;
}
public void setErrorStack(List<CommonError> errorStack) {
this.errorStack = errorStack;
}
public String toString() {
return JSON.toJSONString(this);
}
}
|
import java.util.Scanner;
class Toy
{
private int toyId,minAge,maxAge,price,quantity,refundableDeposit,rentalAmount;
private String toyName,toyType;
public Toy() {
}
public Toy(int toyId, String toyName, String toyType, int minAge, int maxAge, int price, int quantity,int rentalAmount, int refundableDeposit)
{
this.toyId=toyId;
this.toyName = toyName;
this.toyType = toyType;
this.minAge = minAge;
this.maxAge = maxAge;
this.price = price;
this.quantity = quantity;
this.rentalAmount = rentalAmount;
this.refundableDeposit = refundableDeposit;
}
public int getToyId() {
return toyId;
}
public void setToyId(int toyId) {
this.toyId = toyId;
}
public String getToyType() {
return toyType;
}
public void setToyType(String toyType) {
this.toyType = toyType;
}
public int getMinAge() {
return minAge;
}
public void setMinAge(int minAge) {
this.minAge = minAge;
}
public int getMaxAge() {
return maxAge;
}
public void setMaxAge(int maxAge) {
this.maxAge = maxAge;
}
public String getToyName() {
return toyName;
}
public void setToyName(String toyName) {
this.toyName = toyName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getRefundableDeposit() {
return refundableDeposit;
}
public void setRefundableDeposit(int refundableDeposit) {
this.refundableDeposit = refundableDeposit;
}
public int getRentalAmount() {
return rentalAmount;
}
public void setRentalAmount(int rentalAmount) {
this.rentalAmount = rentalAmount;
}
}
//------------------------------------------------------------------------
class Customer
{
private int customerId;
private String customerName;
private String email;
private String password;
private String address;
//public Customer(){
//
// }
public Customer(int customerId, String customerName, String email, String password, String address) {
// super();
this.customerId = customerId;
this.customerName = customerName;
this.password = password;
this.address = address;
this.email = email;
}
public String getPassword(){
return password;
}
public String getEmail(){
return email;
}
}
//------------------------------------------------------------------------
interface CustomerService
{
void rent(int toyId);
void display();
}
//-------------------------------------------------------------------------
class CustomerServiceImpl extends Toy implements CustomerService
{
public static Toy availableToys[]=new Toy[4];
public Toy customerToysRentalInfo[]=new Toy[2];
int k=0;
CustomerServiceImpl()
{
availableToys[0]=new Toy(120,"Rubber Ducky","Toy",1,3,200,200,20,200);
availableToys[1]=new Toy(130,"Car","Toy",1,5,100,30,20,100);
availableToys[2]=new Toy(150,"Kite","Toy",3,8,100,20,100,50);
availableToys[3]=new Toy(180,"Airplane","Toy",4,7,500,30,50,20);
}
public void rent(int toyd)
{
//k=0;
for(int j=0;j<4;j++){
if(toyd==availableToys[j].getToyId()){
customerToysRentalInfo[k]=availableToys[j];
}
}
}
public void display()
{
System.out.print("Toy Name: "+customerToysRentalInfo[k].getToyName()+"\n");
System.out.print("Toy Type: "+customerToysRentalInfo[k].getToyType()+"\n");
System.out.print("Quantity: "+customerToysRentalInfo[k].getQuantity()+"\n");
System.out.print("RentalAmount: "+customerToysRentalInfo[k].getRentalAmount());
}
}
//-------------------------------------------------------------------------
public class Source {
public static void main( String[] args )
{
Scanner sc=new Scanner(System.in);
CustomerServiceImpl c=new CustomerServiceImpl();
int n=sc.nextInt();
c.rent(n);
c.display();
}
}
|
package cn.com.itjh.api.resource;
import com.google.common.base.Joiner;
import com.google.common.net.HttpHeaders;
import com.wordnik.swagger.annotations.*;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.Status;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
/**
* REST endpoint for user manipulation.
*/
@Api(value = "users", description = "Endpoint for user management")
@Path("/users")
public class UsersEndpoint {
@OPTIONS
@ApiOperation(
value = "Returns resource options",
notes = "This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful retrieval of resource options"), @ApiResponse(code = 500, message = "Internal server error") })
public Response getUsersOptions() {
final String header = HttpHeaders.ALLOW;
final String value = Joiner.on(", ").join(RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS).toString();
return Response.noContent().header(header, value).build();
}
}
|
/*
* This software is licensed under the MIT License
* https://github.com/GStefanowich/MC-Server-Protection
*
* Copyright (c) 2019 Gregory Stefanowich
*
* 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:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* 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 net.theelm.sewingmachine.protection.screen;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.theelm.sewingmachine.protection.interfaces.ClientClaimData;
import net.theelm.sewingmachine.protection.objects.FrameData;
import net.theelm.sewingmachine.protection.objects.MapWidget;
import net.theelm.sewingmachine.protection.objects.MapWidget.MapChunk;
import net.theelm.sewingmachine.screens.SettingScreen;
import net.theelm.sewingmachine.screens.SettingScreenListWidget;
import net.theelm.sewingmachine.utilities.ColorUtils;
import net.theelm.sewingmachine.utilities.mod.Sew;
import net.theelm.sewingmachine.utilities.text.MessageUtils;
import net.theelm.sewingmachine.utilities.text.TextUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@Environment(EnvType.CLIENT)
public final class ProtectionClaimScreen extends SettingScreen {
private final int chunkX;
private final int chunkY;
private final FrameData frame;
private @Nullable MapWidget widget = null;
private @Nullable Text claimsText = null;
private int ticks = 0;
private int claims = -1;
protected ProtectionClaimScreen(@NotNull Text title) {
super(title, Sew.modIdentifier("textures/gui/settings_map.png"));
this.frame = new FrameData(
this.backgroundWidth,
this.backgroundHeight
);
this.chunkX = Math.round(this.frame.width() / (MapChunk.WIDTH * this.frame.scale()));
this.chunkY = Math.round(this.frame.height() / (MapChunk.WIDTH * this.frame.scale()));
}
@Override
protected void addButtons(@NotNull SettingScreenListWidget list) {
PlayerEntity player = this.client.player;
// Update the frame using our screens x/y positions
this.frame.x = this.x;
this.frame.y = this.y;
if (player == null)
this.widget = null;
else {
// Create the widget
this.widget = new MapWidget(this.client, player.getChunkPos(), this.frame, this.chunkX, this.chunkY);
// Register dynamic memory texture
this.client.getTextureManager()
.registerTexture(MapWidget.IDENTIFIER, this.widget.getTexture());
}
}
@Override
public void render(DrawContext context, int mouseX, int mouseY, float delta) {
context.drawTextWithShadow(this.textRenderer, "Left-click to Claim", 4, this.height - 24, ColorUtils.Argb.WHITE);
context.drawTextWithShadow(this.textRenderer, "Right-click to Unclaim", 4, this.height - 12, ColorUtils.Argb.WHITE);
// Run the parent render
super.render(context, mouseX, mouseY, delta);
if (this.widget != null) {
if (this.ticks-- <= 0) {
this.ticks = 60;
this.widget.update();
this.claims = -1;
}
ClientClaimData claimData = (ClientClaimData) this.client;
int current = claimData.getClaimedChunks();
if (this.claims != current) {
int limit = claimData.getMaxChunks();
this.claimsText = TextUtils.literal()
.append(MessageUtils.formatNumber(current, current >= limit ? Formatting.RED : Formatting.GREEN))
.append(" / ")
.append(MessageUtils.formatNumber(limit, Formatting.WHITE));
this.claims = current;
}
// Draw the owner tooltip if hovering over a chunk
MapChunk hovered = this.widget.render(context, mouseX, mouseY);
if (hovered != null)
context.drawTooltip(this.textRenderer, hovered.getName(), mouseX, mouseY);
// Draw the number of claims that a player has available
if (this.claimsText != null)
context.drawTextWithShadow(this.textRenderer, this.claimsText, this.x, this.y + this.backgroundHeight, ColorUtils.Argb.WHITE);
}
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
return (this.widget != null && this.widget.mouseClicked(mouseX, mouseY, button))
|| super.mouseClicked(mouseX, mouseY, button);
}
@Override
public boolean mouseReleased(double mouseX, double mouseY, int button) {
return (this.widget != null && this.widget.mouseReleased(mouseX, mouseY, button))
|| super.mouseReleased(mouseX, mouseY, button);
}
@Override
public boolean isMouseOver(double mouseX, double mouseY) {
return this.widget != null && this.widget.isMouseOverMap(mouseX, mouseY);
}
@Override
public void mouseMoved(double mouseX, double mouseY) {
if (this.widget != null)
this.widget.mouseMoved(mouseX, mouseY);
}
}
|
package br.com.ecommerce.pages.retaguarda.cadastros.produtos;
import static br.com.ecommerce.config.DriverFactory.getDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import br.com.ecommerce.config.BasePage;
import br.com.ecommerce.util.Log;
import br.com.ecommerce.util.Utils;
public class PageProduto extends BasePage {
public PageProduto() {
PageFactory.initElements(getDriver(), this);
}
@FindBy(xpath = "//h1")
private WebElement titleProdutos;
@FindBy(xpath = "//*[@href='/admin/products/new']")
private WebElement btNovo;
@FindBy(xpath = "//th[text()='Descrição']")
private WebElement labelDescricao;
@FindBy(xpath = "//th[text()='Nome']")
private WebElement labelNome;
@FindBy(xpath = "//tbody//../a[contains(.,'Imagens')]")
private WebElement btImagens;
@FindBy(xpath = "//tbody//../a[contains(.,'Categorias')]")
private WebElement btCategorias;
@FindBy(xpath = "//tbody//../a[contains(.,'Unidades')]")
private WebElement btUnidades;
@FindBy(xpath = "//tbody//../a[contains(.,'Remove')]")
private WebElement btRemove;
@FindBy(xpath = "//tbody//../a[contains(.,'Editar')]")
private WebElement btEditar;
@FindBy(xpath = "//*[@id='main-content']/section/div[2]['×']")
private WebElement msgSucesso;
public void navegarParaPageInclusaoProdutos() {
aguardarElementoVisivel(btNovo);
click(btNovo);
Log.info("Redirecionando para página de inclusão de produto");
}
public void navegarParaPageCategoriaProduto(String produto) {
aguardarElementoVisivel(btNovo);
By by = By.xpath("//tbody//../tr/td[contains(.,'"+produto+"')]//../td/a[contains(.,'Categorias')]");
click(getDriver().findElement(by));
Log.info("Redirecionando para página de categorias de produto");
}
public void navegarParaPageUnidadeProduto(String produto) {
aguardarElementoVisivel(btNovo);
By by = By.xpath("//tbody//../tr/td[contains(.,'"+produto+"')]//../td/a[contains(.,'Unidades')]");
exibeRegistroVisivel(by, btNovo);
click(getDriver().findElement(by));
Log.info("Redirecionando para página de unidade de produto");
}
public void navegarParaPaginaEdicaoProduto(String produto) {
aguardarElementoVisivel(btEditar);
By by = By.xpath("//tbody//../tr/td[contains(.,'"+produto+"')]//../td/a[contains(.,'Editar')]");
exibeRegistroVisivel(by, btNovo);
click(getDriver().findElement(by));
Log.info("Redirecionando para página de edição do produto ["+produto+"]");
}
public void ativarProduto(String produto) {
WebElement fillBtnInactive = null;
By by = By.xpath("//*[@id='main-content']//tr/td[contains(.,'"+produto+"')]//../td/a[contains(.,'Ativar')]");
exibeRegistroVisivel(by, btNovo);
Utils.wait(1000);
fillBtnInactive = getDriver().findElement(by);
Log.info("Ativando produto..");
click(fillBtnInactive);
Utils.wait(1000);
validaMsgAtivacao();
}
public void desativarProduto(String produto) {
WebElement fillBtnInactive = null;
By by = By.xpath("//*[@id='main-content']//tr/td[contains(.,'"+produto+"')]//../td/a[contains(.,'Desativar')]");
exibeRegistroVisivel(by, btNovo);
Utils.wait(1000);
fillBtnInactive = getDriver().findElement(by);
Log.info("Desativando produto..");
click(fillBtnInactive);
Utils.wait(1000);
validaMsgInativacao();
}
public void irParaPageImagensProduto(String produto) {
WebElement btImagem = null;
By by = By.xpath("//tbody//../td[contains(.,'"+produto+"')]//../td/a[contains(.,'Imagens')]");
btImagem = getDriver().findElement(by);
click(btImagem);
Log.info("Redirecionando para página de edição de imagens do produto produto..");
}
public void validaMsgAtivacao(){
Log.info("Validando mensagem de feedback de ativação...");
aguardarElementoVisivel(msgSucesso);
Utils.assertEquals(getTextElement(msgSucesso).replace("×", "").trim(), "Produto ativado com sucesso!");
Log.info("Mensagem de feedback validada.");
}
public void validaMsgInativacao(){
Log.info("Validando mensagem de feedback de inativação...");
aguardarElementoVisivel(msgSucesso);
Utils.assertEquals(getTextElement(msgSucesso).replace("×", "").trim(), "Produto desativado com sucesso!");
Log.info("Mensagem de feedback validada.");
}
public boolean isAtivo(String produto){
return isVisibility(By.xpath("//*[@id='main-content']//tr/td[contains(.,'"+produto+"')]//../td/a[contains(.,'Desativar')]"));
}
public boolean isInativo(String produto){
return isVisibility(By.xpath("//*[@id='main-content']//tr/td[contains(.,'"+produto+"')]//../td/a[contains(.,'Ativar')]"));
}
public void validaMsgSucessoInclusao(){
Log.info("Validando mensagem de feedback de sucesso...");
aguardarElementoVisivel(msgSucesso);
Utils.assertEquals(getTextElement(msgSucesso).replace("×", "").trim(), "Produto criado com sucesso.");
Log.info("Mensagem de feedback validada.");
}
public void validarProdutoNaListagem(String nome, String descricao) {
Log.info("Conferindo dados do produto ["+nome+"] na tela...");
By by = By.xpath("//*[@id='main-content']//tr/td[contains(.,'"+nome+"')]");
exibeRegistroVisivel(by, btNovo);
WebElement fillNome = getDriver().findElement(By.xpath("//*[@id='main-content']//tr/td[contains(.,'"+nome+"')]//../td[1]"));
WebElement fillDescricao = getDriver().findElement(By.xpath("//*[@id='main-content']//tr/td[contains(.,'"+nome+"')]//../td[2]"));
Utils.assertEquals(getTextElement(fillNome) , nome);
Utils.assertEquals(getTextElement(fillDescricao), descricao);
Log.info("Dados do produto ["+nome+"] conferidos com sucesso.");
}
public boolean isProdutoTesteAtivo(){
By by = By.xpath("//*[@id='main-content']//tr/td[contains(.,'Teste Produto')]//../td/a[contains(.,'Desativar')]");
if (isProdutoTeste()) {
if (isAtivo("Teste Produto")) {
if (!getDriver().findElement(by).isDisplayed()) {
pageDown(btNovo);
}
return true;
}
}
return false;
}
public boolean isProdutoTesteInativo(){
By by = By.xpath("//*[@id='main-content']//tr/td[contains(.,'Teste Produto')]//../td/a[contains(.,'Ativar')]");
if (isProdutoTeste()) {
if (isInativo("Teste Produto")) {
if (!getDriver().findElement(by).isDisplayed()) {
exibeRegistroVisivel(by, btNovo);
}
return true;
}
}
return false;
}
public boolean isProdutoTeste(){
return isVisibility(By.xpath("//*[@id='main-content']//tr/td[contains(.,'Teste Produto')]//../td[2]"));
}
public String getProdutoTesteAtivo(){
return getTextElement(getDriver().findElement(By.xpath("//*[@id='main-content']//tr/td[contains(.,'Teste Produto')]//../td[1]//../td/a[contains(.,'Desativar')]//../../td[1]"))).trim();
}
public String getProdutoTesteDesativado(){
return getTextElement(getDriver().findElement(By.xpath("//*[@id='main-content']//tr/td[contains(.,'Teste Produto')]//../td[1]//../td/a[contains(.,'Ativar')]//../../td[1]"))).trim();
}
public String getProdutoTeste(){
return getTextElement(getDriver().findElement(By.xpath("//*[@id='main-content']//tr/td[contains(.,'Teste Produto')]//../td[1]"))).trim();
}
public String getDescricaoProdutoTeste(){
return getTextElement(getDriver().findElement(By.xpath("//*[@id='main-content']//tr/td[contains(.,'"+getProdutoTeste()+"')]//../td[2]"))).trim();
}
public void validaMsgSucessoAlteracao(){
Log.info("Validando mensagem de feedback de sucesso...");
aguardarElementoVisivel(msgSucesso);
Utils.assertEquals(getTextElement(msgSucesso).replace("×", "").trim(), "Produto atualizado com sucesso.");
Log.info("Mensagem de feedback validada.");
}
public void validarProdutoRemovido(String produto) {
Utils.assertFalse("Produto ["+produto+"] ainda está sendo exibida na listagem de produtos", existsProdutos(produto));
Log.info("Produto ["+produto+"] removido com sucesso");
}
public void validarProdutoDesativado(String produto) {
Utils.assertFalse("Produto ["+produto+"] não foi desativado", isAtivo(produto));
Log.info("Produto ["+produto+"] desativado com sucesso");
}
public void validarProdutoAtivado(String produto) {
Utils.assertTrue("Produto ["+produto+"] não foi ativado", isAtivo(produto));
Log.info("Produto ["+produto+"] ativado com sucesso");
}
public void removerProduto(String produto) {
Log.info("Removendo produto ["+produto+"]...");
By by = By.xpath("//tbody//../tr/td[contains(.,'"+produto+"')]//../td[@class='last']/a[6]");
exibeRegistroVisivel(by, btNovo);
WebElement removerFuncionario = getDriver().findElement(by);
click(removerFuncionario);
confirmarAlerta();
validarMsgSucessoExclusao();
Log.info("Funcionario ["+produto+"] removido...");
}
public void validarMsgSucessoExclusao(){
Log.info("Validando mensagem de feedback de sucesso...");
aguardarElementoVisivel(msgSucesso);
Utils.assertEquals(getTextElement(msgSucesso).replace("×", "").trim(), "Produto removido com sucesso");
Log.info("Mensagem de feedback validada.");
}
public boolean existsProdutos(String produto){
Log.info("Verificando se o produto ["+produto+"] está cadastrado...");
By by = By.xpath("//tbody//../tr/td[contains(.,'"+produto+"')]");
exibeRegistroVisivel(by, btNovo);
return isVisibility(by);
}
public void verificarOrtografiaPageProdutos(){
Log.info("Verificando ortografia da página produtos...");
Utils.assertEquals(getTextElement(titleProdutos) , "Produtos");
Utils.assertEquals(getTextElement(labelNome) , "Nome");
Utils.assertEquals(getTextElement(labelDescricao), "Descrição");
Utils.assertEquals(getTextElement(btNovo) , "Novo(a)");
Utils.assertEquals(getTextElement(btImagens) , "Imagens");
Utils.assertEquals(getTextElement(btCategorias) , "Categorias");
Utils.assertEquals(getTextElement(btUnidades) , "Unidades");
Utils.assertEquals(getTextElement(btEditar) , "Editar");
Utils.assertEquals(getTextElement(btRemove) , "Remove");
Log.info("Ortografia validada com sucesso.");
}
}
|
package org.damienoreilly.zserv;
import org.damienoreilly.zserv.daemon.DaemonManagerCallbackHandler;
public interface ZservProcess extends Runnable {
void setZservName(String zservName);
void setZservBaseDir(String zservDir);
void setCallbackHandler(DaemonManagerCallbackHandler daemonManagerCallbackHandler);
String getZservName();
String getZservBaseDir();
Process getProcess();
void kill();
}
|
package com.darglk.todolist.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.darglk.todolist.entity.Task;
import com.darglk.todolist.entity.User;
import com.darglk.todolist.service.TaskService;
import com.darglk.todolist.service.UserService;
@Controller
@RequestMapping("/task")
@EnableWebSecurity
public class TaskController {
@Autowired
private TaskService taskService;
public void setTaskService(TaskService taskService) {
this.taskService = taskService;
}
@Autowired
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
@GetMapping("/list")
public String listTasks(Model model, @RequestParam(name="page", defaultValue="0", required=false) Integer page,
@RequestParam(name="searchTerm", defaultValue="", required=false) String searchTerm) {
User user = userService.getByUsername(SecurityContextHolder.getContext().getAuthentication().getName()).get(0);
fetchTasksAndPrepareModelAttributes(model, page, searchTerm, user);
return "list-tasks";
}
private void fetchTasksAndPrepareModelAttributes(Model model, Integer page, String searchTerm, User user) {
Pageable pageable = new PageRequest(page,3);
Page<Task> tasks = taskService.getTasksByUserId((long)user.getId(), searchTerm, pageable);
model.addAttribute("avatar", user.getAvatarUrl());
model.addAttribute("tasks", tasks);
model.addAttribute("page", page);
model.addAttribute("searchTerm", searchTerm);
}
@GetMapping("/new_task")
public String createTask(Model model) {
Task task = new Task();
model.addAttribute("task", task);
return "task-form";
}
@PostMapping("/saveTask")
public String saveTask(@Valid @ModelAttribute("task") Task task, BindingResult theBindingResult) {
User user = userService.getByUsername(SecurityContextHolder.getContext().getAuthentication().getName()).get(0);
if (theBindingResult.hasErrors()) {
return "task-form";
}
task.setUser(user);
taskService.saveTask(task);
return "redirect:/task/list";
}
@PostMapping("/remove_selected")
public String removeSelectedItems(@RequestParam("tasks[]") Integer[] tasksToDelete) {
for(Integer taskId : tasksToDelete) {
taskService.deleteTask(taskId);
}
return "redirect:/task/list";
}
@GetMapping("/showFormForUpdate")
public String updateTask(@RequestParam("taskId") int theId, Model theModel) {
Task task = taskService.getTask(theId);
theModel.addAttribute("task", task);
return "task-form";
}
@GetMapping("/delete")
public String deleteTask(@RequestParam("taskId") int theId) {
taskService.deleteTask(theId);
return "redirect:/task/list";
}
@GetMapping("/show")
public String showTask(@RequestParam("taskId") int theId, Model model) {
Task task = taskService.getTask(theId);
model.addAttribute("task", task);
return "show-task";
}
}
|
package br.ufs.livraria.modelo;
import java.io.Serializable;
import javax.persistence.*;
@Entity
public class Livro implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Integer id;
private String titulo;
private String sinopse;
private Integer edicao;
private Integer ano;
private String isbn;
private Integer estoque;
private String genero;
private String autor;
private String editora;
private Float preco;
public Livro() {
}
public Integer getId() {
return id;
}
public String getTitulo() {
return titulo;
}
public String getSinopse() {
return sinopse;
}
public Integer getEdicao() {
return edicao;
}
public Integer getAno() {
return ano;
}
public String getIsbn() {
return isbn;
}
public Integer getEstoque() {
return estoque;
}
public String getGenero() {
return genero;
}
public String getAutor() {
return autor;
}
public String getEditora() {
return editora;
}
public Float getPreco() {
return preco;
}
public void setId(Integer id) {
this.id = id;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public void setSinopse(String sinopse) {
this.sinopse = sinopse;
}
public void setEdicao(Integer edicao) {
this.edicao = edicao;
}
public void setAno(Integer ano) {
this.ano = ano;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public void setEstoque(Integer estoque) {
this.estoque = estoque;
}
public void setGenero(String genero) {
this.genero = genero;
}
public void setAutor(String autor) {
this.autor = autor;
}
public void setEditora(String editora) {
this.editora = editora;
}
public void setPreco(Float preco) {
this.preco = preco;
}
} |
package neo.ce;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import neo.ce.service.IVirtualService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpringScope {
public static void main(String[] args) {
try {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "spring-test.xml" });
//spring容器加载
context.start();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
while (!"exit".equals(s)) {
IVirtualService service = (IVirtualService)context.getBean("virtualService");
System.out.println("=============>" + service.hello(s));
s = br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
public class Alumnus extends CommunityMenber {
}
|
package controllers;
import battleships.Player;
import battleships.Utilities;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.GridPane;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;
import java.util.ResourceBundle;
public class PlacementPage implements Initializable {
@FXML
private Button nextPlacement;
@FXML
private Label name;
@FXML
private GridPane battleField;
@FXML
private GridPane availableShip;
@FXML
private CheckBox orientation;
@FXML
private Label ship1x1;
@FXML
private Label ship2x1;
@FXML
private Label ship3x1;
@FXML
private Label ship4x1;
private static final ImageView[] ships = new ImageView[4];
private boolean vertical = false;
private int dims;
private Label[] labels;
private boolean setRandomly = false;
private Player player = Utilities.getPlayer1();
private int turn = 1;
@FXML
private void toNextPlayer(ActionEvent event) throws IOException {
if (turn == 1 && player.getAvailableShips() == 0) {
battleField.getChildren().retainAll(battleField.getChildren().get(0));
player = Utilities.getPlayer2();
player.getGameBoard().prepareBoard(battleField);
turn = 2;
name.setText(Utilities.getPlayer2().getName());
nextPlacement.setText("Begin?");
for (int i = 0; i < 4; i++) {
ships[i].setVisible(true);
labels[3 - i].setText(String.valueOf(i + 1));
}
} else if (turn == 2 && player.getAvailableShips() == 0) {
Utilities.changeScene(event, "../FXML/game.fxml");
} else {
Utilities.raiseAlert(player.getName() + ", you didn't put all ships to board!");
}
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
labels = new Label[]{ship1x1, ship2x1, ship3x1, ship4x1};
name.setText(player.getName());
orientation.getStylesheets().add(Objects.requireNonNull(PlacementPage.class.getResource(
"../CSS/checkBox.css")).toExternalForm());
player.getGameBoard().prepareBoard(battleField);
for (int i = 0; i < 4; i++) {
ships[i] = new ImageView(Objects.requireNonNull(getClass().getResource("../images/1x1.png".replace(
"1x", (i + 1) + "x"))).toExternalForm());
availableShip.add(ships[i], 0, i);
int index = i;
// TODO: Make ImageView in DragAndDrop event not centered on cursor
ships[i].setOnDragDetected(event -> {
dims = index;
Dragboard db = ships[index].startDragAndDrop(TransferMode.MOVE);
ClipboardContent cbContent = new ClipboardContent();
if (index != 0 && vertical) {
cbContent.putImage(new
ImageView(Objects.requireNonNull(getClass().getResource("../images/1x1.png".replace(
"x1", "x" + (dims + 1)))).toExternalForm()).getImage());
} else {
cbContent.putImage(ships[index].getImage());
}
db.setContent(cbContent);
event.consume();
});
}
battleField.setOnDragOver(event -> {
if (event.getGestureSource() != battleField && event.getDragboard().hasImage()) {
event.acceptTransferModes(TransferMode.MOVE);
}
event.consume();
});
battleField.setOnDragDropped(event -> {
Node node = event.getPickResult().getIntersectedNode();
if (setRandomly) {
battleField.getChildren().retainAll(battleField.getChildren().get(0));
player.getGameBoard().setGameBoard();
player.setAvailableShips();
setRandomly = false;
}
Integer cIndex = GridPane.getColumnIndex(node);
Integer rIndex = GridPane.getRowIndex(node);
int x = cIndex == null ? 0 : cIndex;
int y = rIndex == null ? 0 : rIndex;
int shipNum = 1;
switch (dims) {
case 0 -> shipNum = 6 + Integer.parseInt(labels[dims].getText());
case 1 -> shipNum = 3 + Integer.parseInt(labels[dims].getText());
case 2 -> shipNum = 1 + Integer.parseInt(labels[dims].getText());
}
if (player.getGameBoard().addManually(y, x, dims + 1, vertical, shipNum)) {
player.getGameBoard().fillGridPane(false, battleField);
player.reduceAvailableShips();
labels[dims].setText(String.valueOf(Integer.parseInt(labels[dims].getText()) - 1));
if (labels[dims].getText().equals("0")) {
ships[dims].setVisible(false);
}
}
event.consume();
});
}
@FXML
private void SetRandomly() {
setRandomly = true;
player.getGameBoard().setRandomly(battleField);
player.noAvailableShips();
}
@FXML
private void setVertical() {
this.vertical = orientation.isSelected();
}
} |
package com.demo.test.domain;
import lombok.*;
import java.io.Serializable;
/**
* Token的Model类,可以增加字段提高安全性,例如时间戳、url签名
* “请求的API参数”+“时间戳”+“盐”进行MD5算法加密
*
* @author Jack
* @version 2.0 use now
* @date 2019/05/30 23:40 PM
* @date 2019/10/08 18:55 PM update
*/
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Builder
@ToString(exclude = {"id", "token", "timeStamp", "jwt", "signature"})
public class TokenModel implements Serializable {
private static final long serialVersionUID = -8055688942849382072L;
/**
* 用户id
*/
private long id;
/**
* 安全校验字段(接口参数+时间戳+加盐:取MD5生成) 必填
*/
private String signature;
/**
* 随机生成的uuid, 登录后由服务端生成并返回 选填
*/
private String token;
/**
* 时间戳,13位,比如:1532942172000
*/
private Long timeStamp;
/**
* token令牌 过期时间默认15day
*/
private String jwt;
/**
* 刷新token 过期时间可以设置为jwt的两倍,甚至更长,用于动态刷新token
*/
private String refreshJwt;
/**
* token过期时间戳
*/
private Long tokenPeriodTime;
public TokenModel() {}
public TokenModel(String signature) {
if (signature == null) {
throw new IllegalArgumentException("signature can not be null");
}
this.signature = signature;
}
public TokenModel(long id, String signature) {
if (signature == null) {
throw new IllegalArgumentException("signature can not be null");
}
this.id = id;
this.signature = signature;
}
public TokenModel(long id, String signature, Long timeStamp) {
if (signature == null) {
throw new IllegalArgumentException("signature can not be null");
}
this.id = id;
this.signature = signature;
this.timeStamp = timeStamp;
}
public TokenModel(long id, String token, String signature) {
if (token == null) {
throw new IllegalArgumentException("token can not be null");
}
this.id = id;
this.token = token;
this.signature = signature;
}
/**
* 重写哈希code timestamp 不予考虑, 因为就算timestamp不同也认为是相同的token
*/
@Override
public int hashCode() {
return signature.hashCode();
}
@Override
public boolean equals(Object object) {
if (object instanceof TokenModel) {
return ((TokenModel) object).signature.equals(this.signature);
}
return false;
}
} |
package com.baizhi.entity;
import java.util.Date;
public class Book {
private Integer book_id;
private String book_name;
private String author;
private String press;
private Date up_date;
private Double book_price;
private Double dang_price;
private String img;
private String description1;
private Integer book_salecount;
private Category category1;
private Category category2;
public Category getCategory1() {
return category1;
}
public void setCategory1(Category category1) {
this.category1 = category1;
}
public Category getCategory2() {
return category2;
}
public void setCategory2(Category category2) {
this.category2 = category2;
}
@Override
public String toString() {
return "Book [book_id=" + book_id + ", book_name=" + book_name
+ ", author=" + author + ", press=" + press + ", up_date="
+ up_date + ", book_price=" + book_price + ", dang_price="
+ dang_price + ", img=" + img + ", description1="
+ description1 + ", book_salecount=" + book_salecount
+ ", category1=" + category1 + ", category2=" + category2 + "]";
}
public String getDescription1() {
return description1;
}
public void setDescription1(String description1) {
this.description1 = description1;
}
public Integer getBook_salecount() {
return book_salecount;
}
public void setBook_salecount(Integer book_salecount) {
this.book_salecount = book_salecount;
}
public Integer getBook_id() {
return book_id;
}
public void setBook_id(Integer book_id) {
this.book_id = book_id;
}
public String getBook_name() {
return book_name;
}
public void setBook_name(String book_name) {
this.book_name = book_name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPress() {
return press;
}
public void setPress(String press) {
this.press = press;
}
public Date getUp_date() {
return up_date;
}
public void setUp_date(Date up_date) {
this.up_date = up_date;
}
public Double getBook_price() {
return book_price;
}
public void setBook_price(Double book_price) {
this.book_price = book_price;
}
public Double getDang_price() {
return dang_price;
}
public void setDang_price(Double dang_price) {
this.dang_price = dang_price;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getDescription() {
return description1;
}
public void setDescription(String description) {
this.description1 = description;
}
private String description;
}
|
package com.ymt.entity;
import java.io.File;
/**
* Created by sunsheng on 2017/5/10.
*/
public class Constant {
private static final String ROOT = System.getProperty("user.dir");
public static File getResultPath(){return new File(ROOT, "results/");}
public static File getMinicap() {
return new File(ROOT, "minicap");
}
public static File getMinicapBin() {
return new File(ROOT, "minicap/bin");}
public static File getMinicapSo() {
return new File(ROOT, "minicap/shared");
}
public static void main(String args[]){
System.out.println(Constant.getResultPath().getAbsolutePath());
System.out.print(Constant.getResultPath().getPath());
}
}
|
package com.cts.lifeengage.model;
import java.io.Serializable;
public class FNAProductFormTo implements Serializable{
private String productquestions;
private String productoptions;
private String preferredproduct;
public FNAProductFormTo(String productquestions, String productoptions,String preferredproduct) {
this.productquestions = productquestions;
this.productoptions = productoptions;
this.preferredproduct = preferredproduct;
}
public String getProductquestions() {
return productquestions;
}
public void setProductquestions(String productquestions) {
this.productquestions = productquestions;
}
public String getProductoptions() {
return productoptions;
}
public void setProductoptions(String productoptions) {
this.productoptions = productoptions;
}
public String getPreferredproduct() {
return preferredproduct;
}
public void setPreferredproduct(String preferredproduct) {
this.preferredproduct = preferredproduct;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.common.validator.impl;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.cmsfacades.languages.LanguageFacade;
import de.hybris.platform.commercefacades.storesession.data.LanguageData;
import java.util.Collections;
import java.util.function.BiConsumer;
import java.util.function.Function;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.validation.Errors;
import com.google.common.collect.Lists;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
@SuppressWarnings(
{ "rawtypes", "unchecked" })
public class DefaultLocalizedValidatorTest
{
private static final String CONTENT = "content";
private static final String FRENCH = "fr";
private static final String ENGLISH = "en";
private static final String SPANISH = "es";
@InjectMocks
private DefaultLocalizedValidator validator;
@Mock
private LanguageFacade languageFacade;
@Mock
private BiConsumer consumer;
@Mock
private Function function;
@Mock
private Errors errors;
@Mock
private LanguageData english;
@Mock
private LanguageData french;
@Mock
private LanguageData spanish;
@Before
public void setUp()
{
when(languageFacade.getLanguages()).thenReturn(Lists.newArrayList(english, french, spanish));
when(english.getIsocode()).thenReturn(ENGLISH);
when(english.isRequired()).thenReturn(Boolean.TRUE);
when(french.getIsocode()).thenReturn(FRENCH);
when(french.isRequired()).thenReturn(Boolean.FALSE);
when(spanish.getIsocode()).thenReturn(SPANISH);
when(spanish.isRequired()).thenReturn(Boolean.FALSE);
when(function.apply(ENGLISH)).thenReturn(CONTENT);
when(function.apply(FRENCH)).thenReturn(CONTENT);
when(function.apply(SPANISH)).thenReturn(CONTENT);
}
@Test
public void shouldNotValidateAll_NoLanguages()
{
when(languageFacade.getLanguages()).thenReturn(Collections.emptyList());
validator.validateAllLanguages(consumer, function, errors);
verifyZeroInteractions(consumer, function, errors);
}
@Test
public void shouldValidateAll()
{
validator.validateAllLanguages(consumer, function, errors);
verify(consumer, times(1)).accept(ENGLISH, CONTENT);
verify(function, times(1)).apply(ENGLISH);
verify(consumer, times(1)).accept(FRENCH, CONTENT);
verify(function, times(1)).apply(FRENCH);
verify(consumer, times(1)).accept(SPANISH, CONTENT);
verify(function, times(1)).apply(SPANISH);
}
@Test
public void shouldNotValidateRequired_NoRequiredLanguages()
{
when(english.isRequired()).thenReturn(Boolean.FALSE);
validator.validateRequiredLanguages(consumer, function, errors);
verifyZeroInteractions(consumer, function, errors);
}
@Test
public void shouldValidateRequiredOnly()
{
validator.validateRequiredLanguages(consumer, function, errors);
verify(consumer, times(1)).accept(ENGLISH, CONTENT);
verify(function, times(1)).apply(ENGLISH);
verify(consumer, times(0)).accept(FRENCH, CONTENT);
verify(function, times(0)).apply(FRENCH);
verify(consumer, times(0)).accept(SPANISH, CONTENT);
verify(function, times(0)).apply(SPANISH);
}
}
|
package com.supconit.kqfx.web.util;
/**
* 模块代码接口
* @author 贺秉廷
*
*/
public class ModuleCodeConstant {
/**
* 短信记录查询
*/
public static final String MODULE_DXJLCX_CODE = "IMESSAGE_PUB";
/**
* 短信记录模板管理
*/
public static final String MODULE_DXJLMB_CODE = "LSZHGL_TYDD_TYDD_DXXXT_DXMBGL";
/**
* 短信系统
*/
public static final String MODULE_DXXT_CODE = "LSZHGL_TYDD_TYDD_DXXXT";
}
|
/*
* Copyright (C) 2015 Miquel Sas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.qtplaf.library.database.providers;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import com.qtplaf.library.database.Field;
import com.qtplaf.library.database.Table;
import com.qtplaf.library.database.Types;
import com.qtplaf.library.database.Validator;
import com.qtplaf.library.database.Value;
import com.qtplaf.library.util.Alignment;
import com.qtplaf.library.util.xml.ParserHandler;
/**
* A handler to parse database members like fields, tables or views.
*
* @author Miquel Sas
*/
public class XMLDatabaseParserHandler extends ParserHandler {
/**
* The XML database provider that instantiated this handler.
*/
private XMLDatabaseProvider provider;
/**
* A flag that indicates if the current field being parsed has cleared the list of possible values, necessary if
* possible values are set through a field and then overwritten.
*/
private boolean fieldPossibleValuesCleared = false;
/**
* Constructor assigning the provider.
*
* @param provider The XML database provider.
*/
public XMLDatabaseParserHandler(XMLDatabaseProvider provider) {
super();
this.provider = provider;
}
/**
* Returns the parsed field.
*
* @return The parsed field.
* @throws UnsupportedOperationException If such an error occurs.
*/
public Field getField() {
Object object = getDeque().getLast();
if (object instanceof Field) {
return (Field) object;
}
throw new UnsupportedOperationException();
}
/**
* Returns the parsed table.
*
* @return The parsed table.
* @throws UnsupportedOperationException If such an error occurs.
*/
public Table getTable() {
Object object = getDeque().getLast();
if (object instanceof Table) {
return (Table) object;
}
throw new UnsupportedOperationException();
}
/**
* Called to notify an element start.
*/
@Override
public void elementStart(String namespace, String elementName, String path, Attributes attributes)
throws SAXException {
try {
// element: field
if (path.equals("field")) {
// Initialize the field to parse adding it to the deque.
getDeque().addFirst(new Field());
// Set field attributes
setFieldAttributes(getField(), attributes);
}
// element: field/possible-values/possible-value
if (path.equals("field/possible-values/possible-value")) {
addFieldPossibleValue(getField(), attributes);
}
// element: table
if (path.equals("table")) {
// Initialize the table to parse adding it to the deque.
getDeque().addFirst(new Table());
// Set table attributes
setTableAttributes(getTable(), attributes);
}
// element: table/fields/field
if (path.equals("table/fields/field")) {
// Initialize the field to parse and add it to the deque.
Field field = new Field();
getDeque().addFirst(field);
// If there is a master-field reference, instantiate it.
String smfield = attributes.getValue("master-field");
if (smfield != null) {
Field mfield = provider.getDatabase().getField(smfield);
if (mfield != null) {
field.put(mfield);
}
}
// Set declared attributes inherited from field.
setFieldAttributes(field, attributes);
// Set attributes not contained in the field.
// Set the flag that controls clearing possible values to false.
fieldPossibleValuesCleared = false;
}
// element: table/fields/field/possible-values
if (path.equals("table/fields/field/possible-values/possible-value")) {
Field field = (Field) getDeque().removeFirst();
if (!fieldPossibleValuesCleared) {
field.clearPossibleValues();
fieldPossibleValuesCleared = true;
}
addFieldPossibleValue(field, attributes);
}
} catch (Exception exc) {
throw new SAXException(exc);
}
}
/**
* Called to notify an element body.
*/
@Override
public void elementBody(String namespace, String elementName, String path, String text) throws SAXException {
// element: field/description
if (path.equals("field/description")) {
setFieldDescription(getField(), text);
}
}
/**
* Called to notify an element end.
*/
@Override
public void elementEnd(String namespace, String elementName, String path) throws SAXException {
// element: table/fields/field
if (path.equals("table/fields/field")) {
Field field = (Field) getDeque().removeFirst();
getTable().addField(field);
}
}
/**
* Read and set table attributes.
*
* @param table The table.
* @param attributes The attributes to read.
* @throws SAXException If such an error occurs.
*/
private void setTableAttributes(Table table, Attributes attributes) throws SAXException {
try {
String name = attributes.getValue("name");
if (name != null) {
table.setName(name);
}
String alias = attributes.getValue("alias");
if (alias != null) {
table.setAlias(alias);
}
String spersistent = attributes.getValue("persistent");
if (spersistent != null && !spersistent.isEmpty()) {
boolean persistent = Boolean.parseBoolean(spersistent);
table.setPersistent(persistent);
}
String spersistent_constraints = attributes.getValue("persistent-constraints");
if (spersistent_constraints != null && !spersistent_constraints.isEmpty()) {
boolean persistent_constraints = Boolean.parseBoolean(spersistent_constraints);
table.setPersistentConstraints(persistent_constraints);
}
String schema = attributes.getValue("schema");
if (schema != null) {
table.setSchema(schema);
}
String title = attributes.getValue("title");
if (title != null) {
table.setTitle(title);
}
String description = attributes.getValue("description");
if (description != null) {
table.setDescription(description);
}
} catch (Exception exc) {
throw new SAXException(exc);
}
}
/**
* Set the field description, called from an <i>elementBody</i> callback.
*
* @param field The field.
* @param text The text from the element body.
*/
private void setFieldDescription(Field field, String text) {
if (text != null && text.isEmpty()) {
field.setDescription(text);
}
}
/**
* Add a possible value to a field.
*
* @param field The field.
* @param attributes The parser attributes.
* @throws SAXException If such an error occurs.
*/
private void addFieldPossibleValue(Field field, Attributes attributes) throws SAXException {
try {
String svalue = attributes.getValue("value");
if (svalue != null && !svalue.isEmpty()) {
Value value = field.getDefaultValue();
value.fromStringUnformatted(svalue);
field.addPossibleValue(value);
}
} catch (Exception exc) {
throw new SAXException(exc);
}
}
/**
* Read and set attributes to the field, given we are reading a field element.
*
* @param field The field.
* @param attributes The attributes to read.
* @throws SAXException If such an error occurs.
*/
private void setFieldAttributes(Field field, Attributes attributes) throws SAXException {
try {
String name = attributes.getValue("name");
if (name != null) {
field.setName(name);
}
String alias = attributes.getValue("alias");
if (alias != null) {
field.setAlias(alias);
}
String stype = attributes.getValue("type");
if (stype != null) {
field.setType(Types.parseType(stype));
}
String slength = attributes.getValue("length");
if (slength != null && !slength.isEmpty()) {
int length = Integer.parseInt(slength);
field.setLength(length);
}
String sdecimals = attributes.getValue("decimals");
if (sdecimals != null && !sdecimals.isEmpty()) {
int decimals = Integer.parseInt(sdecimals);
field.setDecimals(decimals);
}
String spersistent = attributes.getValue("persistent");
if (spersistent != null && !spersistent.isEmpty()) {
boolean persistent = Boolean.parseBoolean(spersistent);
field.setPersistent(persistent);
}
String description = attributes.getValue("description");
if (description != null) {
field.setDescription(description);
}
String title = attributes.getValue("title");
if (title != null) {
field.setTitle(title);
}
String label = attributes.getValue("label");
if (label != null) {
field.setLabel(label);
}
String header = attributes.getValue("header");
if (header != null) {
field.setHeader(header);
}
String smaximumValue = attributes.getValue("maximum-value");
if (smaximumValue != null && !smaximumValue.isEmpty()) {
Value maximumValue = field.getDefaultValue();
maximumValue.fromStringUnformatted(smaximumValue);
field.setMaximumValue(maximumValue);
}
String sminimumValue = attributes.getValue("minimum-value");
if (sminimumValue != null && !sminimumValue.isEmpty()) {
Value minimumValue = field.getDefaultValue();
minimumValue.fromStringUnformatted(sminimumValue);
field.setMinimumValue(minimumValue);
}
String srequired = attributes.getValue("required");
if (srequired != null && !srequired.isEmpty()) {
boolean required = Boolean.parseBoolean(srequired);
field.setRequired(required);
}
String snullable = attributes.getValue("nullable");
if (snullable != null && !snullable.isEmpty()) {
boolean nullable = Boolean.parseBoolean(snullable);
field.setNullable(nullable);
}
String validatorClassName = attributes.getValue("validator");
if (validatorClassName != null && !validatorClassName.isEmpty()) {
Validator<Value> validator = getValidator(validatorClassName);
field.setValidator(validator);
}
String sinitialValue = attributes.getValue("initial-value");
if (sinitialValue != null && !sinitialValue.isEmpty()) {
Value initialValue = field.getDefaultValue();
initialValue.fromStringUnformatted(sinitialValue);
field.setInitialValue(initialValue);
}
String scurrentDateTimeOrTimestamp = attributes.getValue("current-date-time-or-timestamp");
if (scurrentDateTimeOrTimestamp != null && !scurrentDateTimeOrTimestamp.isEmpty()) {
boolean currentDateTimeOrTimestamp = Boolean.parseBoolean(scurrentDateTimeOrTimestamp);
field.setCurrentDateTimeOrTimestamp(currentDateTimeOrTimestamp);
}
String shorizontalAlignment = attributes.getValue("horizontal-alignment");
if (shorizontalAlignment != null && !shorizontalAlignment.isEmpty()) {
Alignment horizontalAlignment = Alignment.parseAlignment(shorizontalAlignment);
if (horizontalAlignment.isHorizontal()) {
field.setHorizontalAlignment(horizontalAlignment);
}
}
String sverticalAlignment = attributes.getValue("vertical-alignment");
if (sverticalAlignment != null && !sverticalAlignment.isEmpty()) {
Alignment verticalAlignment = Alignment.parseAlignment(sverticalAlignment);
if (verticalAlignment.isVertical()) {
field.setVerticalAlignment(verticalAlignment);
}
}
String sdisplayLength = attributes.getValue("display-length");
if (sdisplayLength != null && !sdisplayLength.isEmpty()) {
int displayLength = Integer.parseInt(sdisplayLength);
field.setDecimals(displayLength);
}
String suppercase = attributes.getValue("uppercase");
if (suppercase != null && !suppercase.isEmpty()) {
boolean uppercase = Boolean.parseBoolean(suppercase);
field.setUppercase(uppercase);
}
String sminimumWidth = attributes.getValue("minimum-width");
if (sminimumWidth != null && !sminimumWidth.isEmpty()) {
int minimumWidth = Integer.parseInt(sminimumWidth);
field.setMinimumWidth(minimumWidth);
}
String smaximumWidth = attributes.getValue("maximum-width");
if (smaximumWidth != null && !smaximumWidth.isEmpty()) {
int maximumWidth = Integer.parseInt(smaximumWidth);
field.setMaximumWidth(maximumWidth);
}
String spreferredWidth = attributes.getValue("preferred-width");
if (spreferredWidth != null && !spreferredWidth.isEmpty()) {
int preferredWidth = Integer.parseInt(spreferredWidth);
field.setPreferredWidth(preferredWidth);
}
String sautoSize = attributes.getValue("auto-size");
if (sautoSize != null && !sautoSize.isEmpty()) {
boolean autoSize = Boolean.parseBoolean(sautoSize);
field.setAutoSize(autoSize);
}
String swidthFactor = attributes.getValue("width-factor");
if (swidthFactor != null && !swidthFactor.isEmpty()) {
double widthFactor = Double.parseDouble(swidthFactor);
field.setWidthFactor(widthFactor);
}
String sfixedWidth = attributes.getValue("fixed-width");
if (sfixedWidth != null && !sfixedWidth.isEmpty()) {
boolean fixedWidth = Boolean.parseBoolean(sfixedWidth);
field.setFixedWidth(fixedWidth);
}
} catch (Exception exc) {
throw new SAXException(exc);
}
}
/**
* Returns the validator given its class name.
*
* @param className The class name.
* @return The validator.
* @throws NoSuchMethodException If such an error occurs.
* @throws SecurityException If such an error occurs.
* @throws ClassNotFoundException If such an error occurs.
* @throws InstantiationException If such an error occurs.
* @throws IllegalAccessException If such an error occurs.
* @throws IllegalArgumentException If such an error occurs.
* @throws InvocationTargetException If such an error occurs.
*/
private Validator<Value> getValidator(String className)
throws NoSuchMethodException,
SecurityException,
ClassNotFoundException,
InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
if (className == null) {
return null;
}
Constructor<?> constructor = Class.forName(className).getConstructor();
@SuppressWarnings("unchecked")
Validator<Value> validator = (Validator<Value>) constructor.newInstance();
return validator;
}
}
|
package edu.jspiders.beanwiringexplicit.util;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import edu.jspiders.beanwiringexplicit.beans.Student;
public class BeanWiringExplicitUtil
{
public static void main(String[] args)
{
// Create the container
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("springconfig.xml");
// Use the Bean
Student s = context.getBean(Student.class);
System.out.println("Student Info");
System.out.println("------------");
System.out.println(s);
System.out.println("------------");
System.out.println("Student Address");
System.out.println("---------------");
System.out.println(s.getAddr());
// close the container
context.close();
}
}
|
package com.traider.journal.Controllers;
import com.traider.journal.Coin;
import com.traider.journal.System.Binance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
@Controller
public class GreetingController {
@Autowired
Binance binance;
@GetMapping("/greeting")
public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
Binance binance = new Binance();
ArrayList<Coin> coins = binance.getUserBalance();
model.addAttribute("UserCoins", coins);
return "greeting";
}
@GetMapping("/coin/{name}")
public String coinInfo(@PathVariable String name, Model model) {
//Binance binance = new Binance();
System.out.println(name);
binance.getAllUserOrdersDone(name);
// model.addAttribute("UserCoins", coins);
return "greeting";
}
}
|
package com.chuxin.family.views.chat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import com.chuxin.family.global.CxGlobalParams;
import com.chuxin.family.models.GuessRequestMessage;
import com.chuxin.family.models.GuessResponseMessage;
import com.chuxin.family.models.Message;
import com.chuxin.family.models.Model;
import com.chuxin.family.resource.CxResourceDarwable;
import com.chuxin.family.utils.CxLog;
import com.chuxin.family.widgets.CxImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.chuxin.family.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
public class GuessEntry extends ChatLogEntry{
private String TAG = "GuessEntry";
private GuessRequestMessage mRequestMsg ;
private GuessResponseMessage mResponseMsg ;
private int[] fingerImg = new int[]{R.drawable.chat_btnguess_scissors, R.drawable.chat_btnguess_rock, R.drawable.chat_btnguess_paper}; // 猜拳的三种图片
int msgId; // 信息ID (定义在这,是因为重发时要使用)
String guess_id; // 猜拳id
int value1; // 自己出的拳
boolean isRequest; // 是否是guesss_request类型的消息
public GuessEntry(Message message, Context context, boolean isShowDate) {
super(message, context, isShowDate);
}
@Override
public boolean isOwner() {
return true;
}
@Override
public int getType() {
return ENTRY_TYPE_GUESS_REQUEST;
}
@Override
public View build(View view, ViewGroup parent) {
ChatLogAdapter tag = null;
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.cx_fa_view_chat_chatting_guess_row, null);
}
LinearLayout layer1 = (LinearLayout)view.findViewById(R.id.cx_fa_view_chat_chatting_guess_row__layer1);
LinearLayout layer2 = (LinearLayout)view.findViewById(R.id.cx_fa_view_chat_chatting_guess_row__layer2);
// 判断消息类型
if(mMessage instanceof GuessRequestMessage){
mRequestMsg = (GuessRequestMessage)mMessage;
isRequest = true;
}else if(mMessage instanceof GuessResponseMessage){
mResponseMsg = (GuessResponseMessage)mMessage;
isRequest = false;
}
// 处理Tag相关
int msgType ;
int msgCreatTimeStamp ;
if(isRequest){
msgType = mRequestMsg.getType();
msgId = mRequestMsg.getMsgId();
msgCreatTimeStamp = mRequestMsg.getCreateTimestamp();
}else{
msgType = mResponseMsg.getType();
msgId = mResponseMsg.getMsgId();
msgCreatTimeStamp = mResponseMsg.getCreateTimestamp();
}
if (tag == null) {
tag = new ChatLogAdapter();
}
tag.mChatType = msgType;
tag.mMsgId = msgId;
// 如果是自己发的,可能发送失败,需要重发。
if(isRequest){
reSendHandler(view, mRequestMsg, Message.MESSAGE_TYPE_GUESS_REQUEST); // 发起猜拳的消息重发
}else{
reSendHandler(view, mResponseMsg, Message.MESSAGE_TYPE_GUESS_RESPONSE); // 回拳的消息重发
}
headImgHandler(view); // 处理头像
setSendDate(view, msgCreatTimeStamp); // 处理显示时间
/* 处理显示界面 */
TextView title = (TextView)view.findViewById(R.id.cx_fa_view_chat_chatting_guess_row_title);
if(isRequest){
// 自己发起的猜拳 (类型: guess_request)
layer1.setVisibility(View.VISIBLE);
layer2.setVisibility(View.GONE);
title.setText(R.string.cx_fa_guess_start_title); // 设置标题
try {
guess_id = mRequestMsg.mData.getString("guess_id");
value1 = mRequestMsg.mData.getInt("value1");
} catch (JSONException e) {
CxLog.e(TAG, "获取guess_id 和 value1 错误:" + e.getMessage());
}
// 设置提示文字
TextView txt = (TextView)view.findViewById(R.id.cx_fa_view_chat_chatting_guess_row_text);
// 判断男女版 (1:老公 0:老婆 -1:未知 说明:除了1外,其它的都视为老公)
if(CxGlobalParams.getInstance().getVersion() !=0 ){
txt.setText(R.string.cx_fa_guess_start_info_husband); //老公版
}else{
txt.setText(R.string.cx_fa_guess_start_info_wife); //老婆版
}
}else{
// 自己的回复 (类型: guess_response)
layer1.setVisibility(View.GONE);
layer2.setVisibility(View.VISIBLE);
title.setText(R.string.cx_fa_guess_result_title); // 设置标题
int result = 0; // 比赛结果
int value2 = 0;
int send_success = 0; // 发送结果
//String sender = "";
try {
guess_id = mResponseMsg.mData.getString("guess_id");
value1 = mResponseMsg.mData.getInt("value1");
value2 = mResponseMsg.mData.getInt("value2");
result = mResponseMsg.mData.getInt("result");
send_success = mResponseMsg.mData.getInt("send_success");
//sender = mResponseMsg.mData.getString("sender");
} catch (JSONException e) {
CxLog.e(TAG, "获取guess_id 和 value1 错误:" + e.getMessage());
}
TextView winerInfo = (TextView)view.findViewById(R.id.cx_fa_view_chat_chatting_guess_row_result); // 显示谁赢了
LinearLayout guessResultPicLayout = (LinearLayout) view.findViewById(R.id.cx_fa_view_chat_chatting_guess_result_pic_layout); // 显示对决图片的容器
if(send_success==0){ // 发送中
winerInfo.setText(R.string.cx_fa_guess_waiting_result);
guessResultPicLayout.setVisibility(View.GONE);
}else if(send_success==2){ // 发送失败
winerInfo.setText(R.string.cx_fa_guess_reply_fail);
guessResultPicLayout.setVisibility(View.GONE);
}else{ // 发送成功
guessResultPicLayout.setVisibility(View.VISIBLE);
ImageView imgGuess1 = (ImageView) view.findViewById(R.id.cx_fa_view_chat_chatting_guess_pic_guess1);
ImageView imgGuess2 = (ImageView) view.findViewById(R.id.cx_fa_view_chat_chatting_guess_pic_guess2);
imgGuess1.setImageResource( fingerImg[value2-1] );
imgGuess2.setImageResource( fingerImg[value1-1] );
if(result==0){
winerInfo.setText(R.string.cx_fa_guess_result_tie); // 平局
}else {
int wo = 0; // 我
int ta = 0; // 他
// 判断男女版 (1:老公 0:老婆 -1:未知 说明:除了1外,其它的都视为老公)
if(CxGlobalParams.getInstance().getVersion() !=0 ){
wo = R.string.cx_fa_guess_result_win_wife; // 软件是老公版,我是老婆
ta = R.string.cx_fa_guess_result_win_husband;
}else{
wo = R.string.cx_fa_guess_result_win_husband; // 软件是老公婆,我是老公
ta = R.string.cx_fa_guess_result_win_wife;
}
if(result==1){
winerInfo.setText(wo); // 我赢了
}else{
winerInfo.setText(ta); // 他赢了
}
}
}
}
// 显示动画
ImageView gif = (ImageView)view.findViewById(R.id.cx_fa_view_chat_chatting_guess_row_pic);
AnimationDrawable anim = (AnimationDrawable) gif.getDrawable();
anim.stop();
anim.start();
view.setTag(tag);
return view;
}
/**
* 处理头像
* @param view
*/
private void headImgHandler(View view){
// 头像
CxImageView icon = (CxImageView) view.findViewById(R.id.cx_fa_view_chat_chatting_guess_row_icon);
/*icon.setImageResource(R.drawable.cx_fa_wf_icon_small);
icon.setImage(RkGlobalParams.getInstance().getIconBig(),
false, 44, mContext, "head", mContext);*/
icon.displayImage(ImageLoader.getInstance(),
CxGlobalParams.getInstance().getIconSmall(),
CxResourceDarwable.getInstance().dr_chat_icon_small_me, true,
CxGlobalParams.getInstance().getSmallImgConner());
icon.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CxLog.i(TAG, "click update owner headimage button");
ChatFragment.getInstance().updateHeadImage();
}
});
}
private void reSendHandler( View view, final Model model, final int msgType){
// 是否发送成功(如果发送成功,就把小红点隐藏)
final ImageButton reSendBtn = (ImageButton)view.findViewById(R.id.cx_fa_view_chat_chatting_guess_row__exclamation);
ProgressBar pb = (ProgressBar) view.findViewById(R.id.cx_fa_view_chat_chatting_guess_row_circleProgressBar); // 发送中的图标
if(mMessage.getSendSuccess()==0){ // 发送中
pb.setVisibility(View.VISIBLE);
reSendBtn.setVisibility(View.GONE);
}else{ // 发送完成
pb.setVisibility(View.GONE);
if(mMessage.getSendSuccess()==1){ // 发送成功
reSendBtn.setVisibility(View.GONE);
}else{ // 发送失败
reSendBtn.setVisibility(View.VISIBLE);
// 重复发送
reSendBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// resend message
new AlertDialog.Builder(ChatFragment.getInstance().getActivity())
.setTitle(R.string.cx_fa_alert_dialog_tip)
.setMessage(R.string.cx_fa_chat_resend_msg)
.setPositiveButton(R.string.cx_fa_chat_button_resend_text,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
reSendBtn.setVisibility(View.GONE);
if(isRequest){
String msg = guess_id + "," + value1;
ChatFragment.getInstance().reSendMessage( msg, msgType, msgId);
}else{
int value2 = 0;
int result = 0;
int oldMsgId = 0;
try{
value2 = model.mData.getInt("value2");
result = model.mData.getInt("result");
oldMsgId = model.mData.getInt("request_msg_id"); // 只要回拳失败时,才会有此属性
}catch(Exception e){
e.printStackTrace();
}
// 回拳时,
String msg2 = oldMsgId + "," + guess_id + "," + value1 + "," + value2 + "," + result ;
ChatFragment.getInstance().reSendMessage( msg2, msgType, msgId);
}
}
}).setNegativeButton(R.string.cx_fa_cancel_button_text, null).show();
}
});
}
}
}
/**
* 处理发送时间
* @param view
* @param creatTimeStamp
*/
private void setSendDate(View view , long creatTimeStamp){
// 设置消息时间
TextView dateStamp = (TextView)view.findViewById(R.id.cx_fa_view_chat_chatting_guess_row_datestamp);
TextView timeStamp = (TextView)view.findViewById(R.id.cx_fa_view_chat_chatting_guess_row_timestamp);
String format = view.getResources().getString(R.string.cx_fa_nls_reminder_period_time_format);
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date((long)(creatTimeStamp) * 1000));
String time = String.format(format, calendar);
timeStamp.setText(time);
if (mIsShowDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
String dateNow = dateFormat.format(new Date((long)(creatTimeStamp) * 1000));
dateStamp.setVisibility(View.VISIBLE);
dateStamp.setText(dateNow);
} else {
dateStamp.setVisibility(View.GONE);
}
}
}
|
package com.ftd.schaepher.coursemanagement.db;
import android.content.Context;
import android.test.InstrumentationTestCase;
import com.ftd.schaepher.coursemanagement.pojo.TableUserDepartmentHead;
import com.ftd.schaepher.coursemanagement.pojo.TableUserTeacher;
import com.ftd.schaepher.coursemanagement.pojo.TableUserTeachingOffice;
/**
* Created by Administrator on 2015/11/13.
*/
public class CourseDBHelperTest extends InstrumentationTestCase {
CourseDBHelper dbHelper;
Context context;
@Override
public void setUp() throws Exception {
super.setUp();
context = getInstrumentation().getTargetContext();
dbHelper = new CourseDBHelper(context);
}
/**
* 用户相关测试
*/
// 新建用户
public void testCreateUser() {
// 新建教师用户
TableUserTeacher teacher1 = new TableUserTeacher();
teacher1.setWorkNumber("00001");
teacher1.setPassword("00001");
teacher1.setName("西瓜1");
teacher1.setSex("男");
teacher1.setBirthday("19941226");
teacher1.setTelephone("110");
teacher1.setEmail("123456789@qq.com");
teacher1.setDepartment("计算机系");
dbHelper.insert(teacher1);
TableUserTeacher teacher2 = new TableUserTeacher("00002","00002","西瓜2","男",
"19941226","110","123456789@qq.com","计算机系");
dbHelper.insert(teacher2);
// 新建系负责人用户
TableUserDepartmentHead head1 = new TableUserDepartmentHead();
head1.setWorkNumber("00001");
head1.setPassword("00001");
head1.setName("冬瓜");
head1.setSex("男");
head1.setBirthday("19941226");
head1.setTelephone("112");
head1.setEmail("987654321@qq.com");
head1.setDepartment("计算机系");
dbHelper.insert(head1);
TableUserDepartmentHead head2 = new TableUserDepartmentHead("00002","00002","冬瓜","男",
"19941226","112","987654321@qq.com","计算机系");
dbHelper.insert(head2);
// 新建教学办用户
TableUserTeachingOffice office1 = new TableUserTeachingOffice();
office1.setWorkNumber("00001");
office1.setPassword("00001");
office1.setName("南瓜");
office1.setTelephone("119");
office1.setEmail("123459876@qq.com");
dbHelper.insert(office1);
TableUserTeachingOffice office2 = new TableUserTeachingOffice("00002","00002","南瓜",
"119","123459876@qq.com");
dbHelper.insert(office2);
}
// 根据工号查询用户
public void testFindById() {
TableUserTeacher teacher2;
String number = "3443";
teacher2 = dbHelper.findById(number, TableUserTeacher.class);
assertEquals("张三", teacher2.getName());
}
}
|
package com.example.amtis2;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.ArrayList;
public class HospitalList extends AppCompatActivity {
private ArrayList<Hospital> list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospital_list);
list.addAll(HospitalData.getListData());
RecyclerView rvHospital = findViewById(R.id.rv_hospital);
HospitalAdapter hospitalAdapter = new HospitalAdapter(list, this);
rvHospital.setHasFixedSize(true);
rvHospital.setAdapter(hospitalAdapter);
rvHospital.setLayoutManager(new LinearLayoutManager(this));
}
}
|
package com.smxknife.network.demo04;
import java.net.URI;
/**
* @author smxknife
* 2019-02-14
*/
public class URIUtil {
public static void output(URI uri) {
System.out.println("-----------------------------");
System.out.println("-- uri: " + uri);
System.out.printf("-- scheme: %s\r\n", uri.getScheme());
System.out.printf("-- path: %s\r\n", uri.getPath());
System.out.printf("-- authority: %s\r\n", uri.getAuthority());
System.out.printf("-- fragment: %s\r\n", uri.getFragment());
System.out.printf("-- host: %s\r\n", uri.getHost());
System.out.printf("-- port: %s\r\n", uri.getPort());
System.out.printf("-- query: %s\r\n", uri.getQuery());
System.out.printf("-- rawAuthority: %s\r\n", uri.getRawAuthority());
System.out.printf("-- rawQuery: %s\r\n", uri.getRawQuery());
System.out.printf("-- RawFragment: %s\r\n", uri.getRawFragment());
System.out.printf("-- RawPath: %s\r\n", uri.getRawPath());
System.out.printf("-- RawSchemeSpecificPart: %s\r\n", uri.getRawSchemeSpecificPart());
System.out.printf("-- RawUserInfo: %s\r\n", uri.getRawUserInfo());
System.out.printf("-- toString: %s\r\n", uri.toString());
System.out.printf("-- toASCIIString: %s\r\n", uri.toASCIIString());
System.out.println("-----------------------------");
}
}
|
package com.tencent.mm.plugin.account.ui;
import android.content.Context;
import android.widget.Toast;
import com.tencent.mm.kernel.g;
import com.tencent.mm.platformtools.x;
import com.tencent.mm.plugin.account.a.j;
import com.tencent.mm.plugin.account.friend.a.l;
import com.tencent.mm.plugin.account.model.b.a;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.ui.base.h;
final class ContactsSyncUI$a implements a {
final /* synthetic */ ContactsSyncUI ePH;
private boolean ePI;
private x.a ePJ = new 1(this);
public ContactsSyncUI$a(ContactsSyncUI contactsSyncUI, boolean z) {
this.ePH = contactsSyncUI;
this.ePI = z;
}
public final int cm(Context context) {
g.Eg();
if (!com.tencent.mm.kernel.a.Dw() || com.tencent.mm.kernel.a.Dr()) {
return 4;
}
if (this.ePI) {
String str = (String) g.Ei().DT().get(6, "");
if (bi.oW(str)) {
com.tencent.mm.sdk.platformtools.x.e("MicroMsg.ProcessorAddAccount", "not bind mobile phone");
return 2;
} else if (!l.XB()) {
return N(context, str);
} else {
h.a(context, j.contact_sync_add_account_alert, j.app_tip, j.app_ok, j.app_cancel, new 2(this, context, str), new 3(this, context));
return 5;
}
}
com.tencent.mm.sdk.platformtools.x.i("MicroMsg.ProcessorAddAccount", "no need to bind mobile");
x.a(this.ePH, this.ePJ);
return 0;
}
final int N(Context context, String str) {
if (context == null) {
return 1;
}
int a = x.a(context, str, this.ePJ);
if (a == 2) {
Toast.makeText(context, this.ePH.getString(j.contact_sync_add_account_failed), 1).show();
return 1;
} else if (a != 3) {
return 0;
} else {
Toast.makeText(context, this.ePH.getString(j.contact_sync_add_account_already_exist), 1).show();
return 1;
}
}
}
|
/**
* JSON 配列に関する処理 package
*/
package org.yipuran.gsonhelper.array; |
import java.util.TreeMap;
public class removeentry {
public static void main(String[] args) {
TreeMap<String, Integer> t1 = new TreeMap<String, Integer>();
t1.put("c",02);
t1.put("h",12);
t1.put("o",22);
t1.put("w",32);
t1.remove("d");
System.out.println(t1);
}
}
|
package org.ddth.dinoage.eclipse.ui.perferences;
import org.ddth.dinoage.eclipse.Activator;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.DirectoryFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.RadioGroupFieldEditor;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
public class PreferenceConnectionPage extends FieldEditorPreferencePage
implements IWorkbenchPreferencePage {
public PreferenceConnectionPage() {
super(GRID);
setPreferenceStore(Activator.getDefault().getPreferenceStore());
setDescription(null);
}
public void createFieldEditors() {
addField(new DirectoryFieldEditor("xxx", "&Directory preference:", getFieldEditorParent()));
addField(new BooleanFieldEditor("yyy", "&An example of a boolean preference", getFieldEditorParent()));
addField(new RadioGroupFieldEditor("zzz",
"An example of a multiple-choice preference", 1,
new String[][] { { "&Choice 1", "choice1" },
{ "C&hoice 2", "choice2" } }, getFieldEditorParent()));
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
*/
public void init(IWorkbench workbench) {
}
} |
package MethodSample;
import java.util.Scanner;
//생성자 메소드: 클래스간의 값을 주고 받거나 합니다.
//생성자는 상속이 되지 않습니다. 생성자는 클ㄹ래스명과 같은 이름을 사용.
//반환타입이 없다. 그래서 return을 사용하지 않는다.
//접근제한자는 public 이거나 생략가능하다.
//생성자 메서드는 오버로딩이 가능하다.
//프로그래머가 생성자 메소드를 작성하지않으면 JVM이 자동으로 만들어줍니다.
//생성자 메소드가 하나라도 없으면 그 때 만들어 줍니다.
// 그리고, 클래스에 클래스 변수에 값을 초기화할 목적으로 사용합니다.
//메소드 측면 비교
//1. 메소드는 객체의 동작에 해당하는 중괄호 { } 블럭을 사용합니다.
//2. 메소드를 호출하면 중괄호 블럭에 있는 모든 코드들이 일괄적으로 실행됩니다.
//3. 메소드는 필드를 읽고 수정하는 역할을 합니다.
//4. 또한 다른 객체를 생성하여 다양한 기능을 수행하기도 합니다.
//5. *** 메소드는 객체간의 데이터 전달의 수단으로 사용됩니다.
//6. 외부로부터 매개변수값을 받을 수 있고, 실행 후에 임의의 값을 반환할 수도 있습니다.
//7.
//문제] 2개의 숫자를 입력받아서 메소드에 전달하고, 그 결과를 리턴받아서 출력하는 로직을 작성하세요.
public class ConstructorSample {
//field area : 객체 고유의 데이터나 상태정보를 저장하는 곳
//선언형태는 변수와 비슷하지만, 필드를 변수라고 부르지 않습니다.
//클래스 변수는 생성자와 메소드내에서만 사용되고, 생성자와 메소드가 실행이 종료되면
//자동으로 소멸됩니다.
//
static int x;
static int y;
private int total;
private int sum2;
//생성자
public ConstructorSample() {
}
public ConstructorSample(int x, int y) {
this.x = x;
this.y = y;
}
//메소드
public int SUM(int n1, int n2) {
int total;
total = n1+n2;
return total;
}
private void Adder() {
sum2 = this.x + this.y;
}
private void display() {
System.out.println("생성자를 이용하여 메소드를 호출한 결과는 "+sum2);
}
public static void main(String[] args) {
ConstructorSample cs = new ConstructorSample(100, 50);
int n1, n2, sum;
Scanner sc = new Scanner(System.in);
System.out.println("첫번째 숫자를 입력해주세요.");
n1 = sc.nextInt();
System.out.println("두번째 숫자를 입력해주세요.");
n2 = sc.nextInt();
sum = cs.SUM(n1, n2);
System.out.println("합계는 "+sum);
//method를 만들어 접근하라.
cs.Adder();
cs.display();
}
}
//생성자
//자동차 클래스가 있습니다. 그 클래스에 색상과 가격을 생성자를 통하여 입력하고 출력하세요. |
package ThunderSmotch.testmod;
import net.minecraft.init.Blocks;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
@Mod(modid = Reference.MOD_ID, version = Reference.VERSION, useMetadata = true)
public class ExampleMod
{
@EventHandler
public void init(FMLInitializationEvent event)
{
// some example code
System.out.println("DIRT BLOCK >> "+Blocks.DIRT.getUnlocalizedName());
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent
public void onPlayerTick(TickEvent.PlayerTickEvent tick){
//do something
}
}
|
package org.dmonix.net;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dmonix.util.DateHandler;
/**
* Class with net related utility methods.
* <p>
* Copyright: Copyright (c) 2004
* </p>
* <p>
* Company: dmonix.org
* </p>
*
* @author Peter Nerg
* @since 1.0
*/
public abstract class NetUtil {
/** The logger instance for this class */
private static final Logger log = Logger.getLogger(NetUtil.class.getName());
/** Content type plain set in the HTTP header. */
public static final String CONTENT_TYPE_PLAIN = "text/plain";
/** Content type XML set in the HTTP header. */
public static final String CONTENT_TYPE_XML = "text/xml";
// ============================
// Character encoding set in the HTTP header.
// ============================
/**
* Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set.
*/
public static final String ENCODING_US_ASCII = "US-ASCII";
/** ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1. */
public static final String ENCODING_ISO_8859_1 = "ISO-8859-1";
/** Eight-bit UCS Transformation Format. */
public static final String ENCODING_UTF_8 = "UTF-8";
/** Sixteen-bit UCS Transformation Format, big-endian byte order. */
public static final String ENCODING_UTF_16BE = "UTF-16BE";
/** Sixteen-bit UCS Transformation Format, little-endian byte order. */
public static final String ENCODING_UTF_16LE = "UTF-16LE";
/**
* Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark.
*/
public static final String ENCODING_UTF_16 = "UTF-16";
/**
* The method returns the IP-address as seen by servers/clients outside the local LAN. <br>
* The method does not return the locally configured IP-address for the client, i.e. the IP-address configured for the client in the LAN.<br>
* Instead the method returns IP-address as perceived by servers outside the LAN.<br>
* This means that the method returns the IP-address of the proxy/firewall/gateway server.<br>
* The method attemps to contact <code>http://www.dmonix.org/getIP.jsp</code> to find out the IP-address.
*
* @return The IP-address
* @throws IOException
* @throws MalformedURLException
*/
public static String getExternalIPAddress() throws IOException, MalformedURLException {
String response = sendHTTPPostRequest("www.dmonix.org", "/getIP.jsp").toLowerCase().trim();
response = response.substring(response.indexOf("<h1>") + 4, response.indexOf("</h1>"));
return response;
}
/**
* Returns the date of the last modification for the remote file. <br>
* This is done by sending a <code>HTTP HEAD</code> request and read the <code>Last-Modified</code> parameter in the answer. <br>
* The date will be parsed using any of the pre-defined date formats in <code>org.dmonix.util.DateHandler</code>
*
* @param url
* The URL of the file
* @return The date, null if not possible to parse
* @throws IOException
*/
public static Date getModifiedDate(URL url) throws IOException {
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setRequestMethod("HEAD");
urlCon.setUseCaches(false);
urlCon.connect();
return DateHandler.getDate(urlCon.getHeaderField("Last-Modified"));
}
/**
* Returns the date of the last modification for the remote file. <br>
* This is done by sending a <code>HTTP HEAD</code> request and read the <code>Last-Modified</code> parameter in the answer.
*
* @param url
* The URL of the file
* @param dateFormat
* The date format to use for the parse
* @return The date, null if not possible to parse
* @throws IOException
*/
public static Date getModifiedDate(URL url, String dateFormat) throws IOException {
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setRequestMethod("HEAD");
urlCon.setUseCaches(false);
urlCon.connect();
return DateHandler.getDate(urlCon.getHeaderField("Last-Modified"), dateFormat);
}
/**
* Sets the system parameters used to determine the proxy. <br>
* The method sets system properties, i.e.the method only needs to be run once.
*
* @param proxyHost
* The host
* @param proxyPort
* The port
*/
public static void setProxy(String proxyHost, String proxyPort) {
System.setProperty("http.proxyHost", proxyHost);
System.setProperty("http.proxyPort", proxyPort);
}
/**
* Resets/removes the system parameters for the proxy host.
*/
public static void resetProxy() {
System.getProperties().remove(("http.proxyHost"));
System.getProperties().remove(("http.proxyPort"));
}
/**
* Sets the socket timeout.
*
* @param timeout
* socket timeout in millis
*/
public void setSocketTimeout(String timeout) {
System.setProperty("sun.net.client.defaultConnectTimeout", timeout);
System.setProperty("sun.net.client.defaultReadTimeout", timeout);
}
/**
* Resets/removes the socket timeout.
*/
public static void resetSocketTimeout() {
System.getProperties().remove(("sun.net.client.defaultConnectTimeout"));
System.getProperties().remove(("sun.net.client.defaultReadTimeout"));
}
/**
* Send a HTTP get request. <br>
* Default HTTP parameters are:
* <ul>
* <li>port = 80</li>
* <li>content type = text/plain</li>
* </ul>
*
* @param address
* The remote address
* @param file
* The remote file
* @return The response string from the remote server
* @throws IOException
* @throws MalformedURLException
*/
public static String sendHTTPGetRequest(String address, String file) throws IOException, MalformedURLException {
return sendHTTPGetRequest(address, 80, file, CONTENT_TYPE_PLAIN, "");
}
/**
* Send a HTTP get request.
*
* @param address
* The remote address
* @param port
* The remote port
* @param file
* The remote file
* @param contentType
* content type
* @param requestString
* The string to send
* @return The response string from the remote server
* @throws IOException
* @throws MalformedURLException
* @see #CONTENT_TYPE_PLAIN
* @see #CONTENT_TYPE_XML
*/
public static String sendHTTPGetRequest(String address, int port, String file, String contentType, String requestString) throws IOException,
MalformedURLException {
return sendRequest("HTTP", address, port, file, "GET", contentType, requestString);
}
/**
* Send a HTTP post request. <br>
* Default HTTP parameters are:
* <ul>
* <li>port = 80</li>
* <li>content type = text/plain</li>
* </ul>
*
* @param address
* The remote address
* @param file
* The remote file
* @return The response string from the remote server
* @throws IOException
* @throws MalformedURLException
*/
public static String sendHTTPPostRequest(String address, String file) throws IOException, MalformedURLException {
return sendHTTPPostRequest(address, 80, file, CONTENT_TYPE_PLAIN, "");
}
/**
* Send a HTTP post request.
*
* @param address
* The remote address
* @param port
* The remote port
* @param file
* The remote file
* @param contentType
* content type
* @param requestString
* The string to send
* @return The response string from the remote server
* @throws IOException
* @throws MalformedURLException
* @see #CONTENT_TYPE_PLAIN
* @see #CONTENT_TYPE_XML
*/
public static String sendHTTPPostRequest(String address, int port, String file, String contentType, String requestString) throws IOException,
MalformedURLException {
return sendRequest("HTTP", address, port, file, "POST", contentType, requestString);
}
/**
* Send a HTTPS get request. <br>
* Default HTTPS parameters are:
* <ul>
* <li>port = 80</li>
* <li>content type = text/plain</li>
* </ul>
*
* @param address
* The remote address
* @param file
* The remote file
* @return The response string from the remote server
* @throws IOException
* @throws MalformedURLException
*/
public static String sendHTTPSGetRequest(String address, String file) throws IOException, MalformedURLException {
return sendHTTPSGetRequest(address, 80, file, CONTENT_TYPE_PLAIN, "");
}
/**
* Send a HTTPS get request.
*
* @param address
* The remote address
* @param port
* The remote port
* @param file
* The remote file
* @param contentType
* content type
* @param requestString
* The string to send
* @return The response string from the remote server
* @throws IOException
* @throws MalformedURLException
* @see #CONTENT_TYPE_PLAIN
* @see #CONTENT_TYPE_XML
*/
public static String sendHTTPSGetRequest(String address, int port, String file, String contentType, String requestString) throws IOException,
MalformedURLException {
return sendRequest("HTTPS", address, port, file, "GET", contentType, requestString);
}
/**
* Send a HTTPS post request. <br>
* Default HTTPS parameters are:
* <ul>
* <li>port = 80</li>
* <li>content type = text/plain</li>
* </ul>
*
* @param address
* The remote address
* @param file
* The remote file
* @return The response string from the remote server
* @throws IOException
* @throws MalformedURLException
*/
public static String sendHTTPSPostRequest(String address, String file) throws IOException, MalformedURLException {
return sendHTTPSPostRequest(address, 80, file, CONTENT_TYPE_PLAIN, "");
}
/**
* Send a HTTPS post request.
*
* @param address
* The remote address
* @param port
* The remote port
* @param file
* The remote file
* @param contentType
* content type
* @param requestString
* The string to send
* @return The response string from the remote server
* @throws IOException
* @throws MalformedURLException
* @see #CONTENT_TYPE_PLAIN
* @see #CONTENT_TYPE_XML
*/
public static String sendHTTPSPostRequest(String address, int port, String file, String contentType, String requestString) throws IOException,
MalformedURLException {
return sendRequest("HTTPS", address, port, file, "POST", contentType, requestString);
}
/**
* Receive data from the server.<br>
* The SocketTimeoutException exception is propagated in order to let the sending class handle the exception and perhaps display an message to the user.
*
* @param httpURLCon
* The HttpURLConnection object
* @return The response
* @throws SocketTimeoutException
*/
private static String receive(HttpURLConnection httpURLCon) throws SocketTimeoutException {
String tmpStr = "";
StringBuffer stringBuf = new StringBuffer();
boolean errorInResponse = false;
try {
if (log.isLoggable(Level.FINER)) {
log.finer("==Header fields==");
Map<String, List<String>> map = httpURLCon.getHeaderFields();
for (String key : map.keySet()) {
log.finer(key + " : " + map.get(key));
}
log.finer("==End Header fields==");
}
BufferedReader inBuffer;
try {
inBuffer = new BufferedReader(new InputStreamReader(httpURLCon.getInputStream()));
} catch (SocketTimeoutException ex) {
throw ex;
} catch (Exception ex) {
log.log(Level.WARNING, "Cannot open response stream from server", ex);
inBuffer = new BufferedReader(new InputStreamReader(httpURLCon.getErrorStream()));
errorInResponse = true;
}
while ((tmpStr = inBuffer.readLine()) != null) {
stringBuf.append(tmpStr + "\n");
}
inBuffer.close();
inBuffer = null;
if (errorInResponse) {
log.warning("Error from server : \n" + stringBuf.toString());
return null;
}
if (log.isLoggable(Level.FINE))
log.fine("Response from server: \n" + stringBuf.toString());
} catch (SocketTimeoutException ex) {
log.log(Level.WARNING, "Socket timed out", ex);
throw ex;
} catch (Exception ex) {
log.log(Level.WARNING, "Error while receiving response", ex);
return null;
}
return stringBuf.toString();
}
private static String sendRequest(String protocol, String address, int port, String file, String requestMethod, String contentType, String requestString)
throws IOException, MalformedURLException {
URL url = new URL(protocol, address, port, file);
if (log.isLoggable(Level.FINE))
log.log(Level.FINE, "Connect to : " + url.toString());
HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
httpURLCon.setDoOutput(true);
httpURLCon.setDoInput(true);
httpURLCon.setRequestMethod(requestMethod);
if (requestString != null && requestString.length() > 0) {
httpURLCon.setRequestProperty("Content-Type", contentType);
httpURLCon.setRequestProperty("Content-Length", "" + requestString.length());
DataOutputStream dostream = new DataOutputStream(httpURLCon.getOutputStream());
if (log.isLoggable(Level.FINE))
log.fine("requestString : \n" + requestString + "\n" + "length=" + requestString.length());
dostream.writeBytes(requestString);
dostream.flush();
dostream.close();
}
return receive(httpURLCon);
}
}
|
package com.tencent.mm.plugin.mmsight.model.a;
import android.os.Looper;
import android.os.Message;
import com.tencent.mm.sdk.platformtools.ag;
class h$1 extends ag {
final /* synthetic */ h lij;
h$1(h hVar, Looper looper) {
this.lij = hVar;
super(looper);
}
public final void handleMessage(Message message) {
if (this.lij.lhY != null) {
this.lij.lhY.beh();
this.lij.lhY = null;
}
}
}
|
package de.zarncke.lib.id;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.base.Function;
import de.zarncke.lib.block.Running;
import de.zarncke.lib.coll.L;
import de.zarncke.lib.ctx.Context;
import de.zarncke.lib.err.GuardedTest;
import de.zarncke.lib.err.Warden;
import de.zarncke.lib.value.BiTypeMapping;
import de.zarncke.lib.value.Default;
import de.zarncke.lib.value.TypeNameMapping;
public class ResolvingTest extends GuardedTest {
static class Tid extends Unique<Tid> {
private static final long serialVersionUID = 1L;
public Tid(final Gid<Tid> id) {
super(id);
}
}
public static final Function<Gid<Tid>, Tid> T_RESOLVER = new Function<Gid<Tid>, Tid>() {
public Tid apply(final Gid<Tid> from) {
return new Tid(from);
}
};
public static final Function<Collection<? extends Gid<Tid>>, List<Tid>> T_LIST_RESOLVER = new Function<Collection<? extends Gid<Tid>>, List<Tid>>() {
public List<Tid> apply(final Collection<? extends Gid<Tid>> from) {
return Factory.getListByInteratingOverElements(from, Factory.forFunction(T_RESOLVER, Tid.class));
}
};
@Test
public void testFactory() {
Factory f = new Factory();
Assert.assertNull(f.get((Gid<?>) null));
f.register(Tid.class, T_RESOLVER);
Gid<Tid> id = Gid.ofUtf8("test", Tid.class);
Tid tid = f.get(id);
Assert.assertEquals(id, tid.getId());
Gid<String> sid = Gid.ofUtf8("test", String.class);
try {
f.get(sid);
Assert.fail("should be illegal");
} catch (IllegalArgumentException e) {
Warden.disregard(e);
}
}
@Test
public void testListFactory() {
Factory f = new Factory();
// f.register(Tid.class, T_RESOLVER);
f.registerForList(Tid.class, T_LIST_RESOLVER);
Gid<Tid> id = Gid.ofUtf8("test", Tid.class);
Gid<Tid> id2 = Gid.ofUtf8("test2", Tid.class);
// Tid tid = f.get(id);
// Assert.assertEquals(id, tid.getId());
List<Tid> tids = f.get(L.l(id, id2));
Assert.assertEquals(2, tids.size());
Assert.assertEquals(id, tids.get(0).getId());
Assert.assertEquals(id2, tids.get(1).getId());
}
@Test
public void testSimpleTypes() {
Factory f = new Factory();
Assert.assertNull(f.get((Gid<?>) null));
f.register(Long.class, Resolving.LONG_RESOLVER);
f.register(Integer.class, Resolving.INTEGER_RESOLVER);
f.register(String.class, Resolving.STRING_RESOLVER);
check(f, null);
check(f, Integer.valueOf(-5));
check(f, Integer.valueOf(5));
check(f, Long.valueOf(1000000000L));
check(f, "");
check(f, "hello world");
check(f, "hello\n,\täöüworld");
}
@Test
public void testCollectionTypes() {
final Factory f = new Factory();
Context.runWith(new Running() {
public void run() {
f.register(Collection.class, Resolving.COLLECTION_RESOLVER);
f.register(Tid.class, T_RESOLVER);
Collection<Tid> tids = Arrays.asList(new Tid[] { new Tid(id(1)), new Tid(id(2)), new Tid(id(3)) });
check(f, tids);
f.register(Long.class, Resolving.LONG_RESOLVER);
f.register(Integer.class, Resolving.INTEGER_RESOLVER);
f.register(String.class, Resolving.STRING_RESOLVER);
Collection<String> cs = Arrays.asList(new String[] { "Hello", "", "World", "!" });
Collection<Long> ls = Arrays.asList(new Long[] { Long.valueOf(1), Long.valueOf(-1), Long.valueOf(1000) });
check(f, cs);
check(f, ls);
}
}, Default.of(f, Resolver.class));
}
@Test
public void testClasses() {
final Factory f = new Factory();
f.register(Class.class, Resolving.CLASS_RESOLVER);
check(f, null);
check(f, String.class);
check(f, Tid.class);
check(f, Collection.class);
BiTypeMapping tnm = new BiTypeMapping();
tnm.assign(String.class, "S");
Context.runWith(new Running() {
public void run() {
Gid<?> id = check(f, String.class);
Assert.assertEquals("S", id.toUtf8String());
}
}, Default.of(tnm, TypeNameMapping.class));
check(f, String.class);
}
private Gid<Tid> id(final int id) {
return Gid.of(id, Tid.class);
}
private Gid<?> check(final Resolver r, final Object o) {
Gid<?> id = Resolving.getId(o);
Assert.assertEquals(o, r.get(id));
return id;
}
}
|
package com.bridgelabz.functionalprograms;
import java.util.*;
public class ZeroSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of Integers");
int numberOfIntegers = sc.nextInt();
int[] array = new int[numberOfIntegers];
System.out.println("Enter the integers");
for(int i=0;i< numberOfIntegers;i++) {
array[i] = sc.nextInt();
}
int count = 0;
ArrayList<ArrayList <Integer>> list = new ArrayList<ArrayList<Integer>>();
for(int i=0;i<numberOfIntegers-2;i++) {
for(int j=i+1;j<numberOfIntegers-1;j++) {
for(int k=j+1;k<numberOfIntegers;k++) {
if(array[i]+array[j]+array[k] == 0) {
count++;
ArrayList<Integer> triplet = new ArrayList<Integer>();
triplet.add(array[i]);
triplet.add(array[j]);
triplet.add(array[k]);
if(!list.contains(triplet)) list.add(triplet);
}
}
}
}
System.out.println("the number of triplets found : "+ count);
if(count >0) {
System.out.println("The triplets are : ");
for(int i=0;i<count;i++) System.out.println(list.get(i));
}
}
}
|
package com.goldenratio.test;
import static org.junit.Assert.*;
import org.junit.Test;
import com.goldenratio.proof.Main;
/**
* Patrick Culligan
*/
public class OutOfBoundsTest {
@Test
public void test() {
/**
* Test fails because it is outside the parameters
* of the acceptable boundary
*/
Main test = new Main();
int input = test.runProgram(Main.index);
//
assertEquals(26, input);
}
}
|
/**
* Created at 2007-12-13 by pony
*/
package com.allinpay.generator.ibatis.generator;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import com.allinpay.frameworkdao.ibatis.metadata.TableMetaData;
import com.allinpay.generator.ibatis.ICodeGenerator;
import com.allinpay.util.FileUtil;
import com.allinpay.util.StringUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
*
*/
public abstract class AbstractCodeGenerator implements ICodeGenerator {
/**
* Template file name, not include the file path.
*/
private String templateFile;
/**
* Generated file, only include the file path.
*/
private String generatedRootFilePath;
private String moduleFilePath;
/**
* model.
*/
protected Map model;
/**
* @return the templateFile
*/
public String getTemplateFile() {
return templateFile;
}
/**
* @param templateFile the templateFile to set
*/
public void setTemplateFile(String templateFile) {
this.templateFile = templateFile;
}
/**
* @return the generatedFilePath
*/
public String getGeneratedFilePath() {
return generatedRootFilePath;
}
/**
* @param generatedFilePath the generatedFilePath to set
*/
public void setGeneratedRootFilePath(String generatedFilePath) {
this.generatedRootFilePath = generatedFilePath;
}
/**
* @return the moduleFilePath
*/
public String getModuleFilePath() {
return moduleFilePath;
}
/**
* @param moduleFilePath the moduleFilePath to set
*/
public void setModuleFilePath(String moduleFilePath) {
this.moduleFilePath = moduleFilePath;
}
/**
* @return Returns the model.
*/
public Map getModel() {
return model;
}
/**
* @param model The model to set.
*/
public void setModel(Map model) {
this.model = model;
}
/**
* Read template.
* @param templateFilePath
* @return
* @throws IOException
*/
protected Template getTemplate(String templateFilePath) throws IOException {
Configuration conf = Configuration.getDefaultConfiguration();
conf.setEncoding(Locale.CHINA, "utf-8");
conf.setOutputEncoding("utf-8");
return conf.getTemplate(templateFilePath);
}
/**
* pkg diretory.
* @return
*/
protected String getPackageDir() {
String pkg = getRealPackageName();
String pkgDir = pkg.replaceAll("[.]", "/");
return pkgDir;
}
protected String getRealPackageName() {
String pkg = (String) getModel().get("prefixPackage");
if (!StringUtil.isEmpty(getPackageIdentifier())) {
pkg += "." + getPackageIdentifier();
}
pkg += "." + (String) getModel().get("lastPackageName");
return pkg;
}
public abstract File createEmptyGeneratedFile(String fileName);
public abstract String getPackageIdentifier();
public void register(Map model) {
this.model = model;
}
/* (non-Javadoc)
* @see com.allinpay.ibatis.generaotor.sqlmap.ICodeGenerator#generate(java.util.Map)
*/
public void generate(final Map model) {
this.model = model;
Writer writer = null;
FileWriter fw = null;
try {
writer = new CharArrayWriter();
Template template = getTemplate(getTemplateFile());
model.put("package", getRealPackageName());
template.process(model, writer);
writer.flush();
String filename = ((TableMetaData)model.get("tmd")).getJavaName();
File file = createEmptyGeneratedFile(filename);
file.delete();
OutputStream os = new FileOutputStream(file);
FileUtil.save(os, writer.toString().getBytes("utf-8"));
os.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != writer) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != fw) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|
package jdbc.step3.test;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
/*
* 디비 Access 하기위한 4단계 작업을 작성하는 로직..
* 1. 디비서버에 대한 파편적인 정보들(서버 실제값)을 상수로 지정
* -->
* 문제점
* 소스코드에 서버정보가 그대로 노출되어져 있다.
* 메타데이터화 시키자
* ::
* 해결책
* 2. 상수값과 추상메소드를 구성요소로 가지는 인터페이스를 별도의 모듈로 생성하고
* 그 안에 서버 정보를 메타데이터화 시키겠다.
* --->
*
* 3. 자바 진영에서 가장 많이 사용하는 Meta Data는
* properties파일이다.
* Key - Value값을 모두 스트링으로 저장할수 있다는 특징에 착안되어져
* 서버정보를 저장하는 메타데이터로 가장 많이 사용되어진다.
* config > db.properties
*/
public class JDBC4StepTest {
static String driver;
static String url;
static String user;
static String pass;
static String query;
public JDBC4StepTest() throws ClassNotFoundException, SQLException{
Class.forName(driver);
System.out.println("1. 드라이버 로딩 성공..");
Connection conn = DriverManager.getConnection(url, user, pass);
System.out.println("2. 디비 연결 성공..");
/*
String query = "INSERT INTO mytable (num, name, address) VALUES (?,?,?)";
PreparedStatement ps = conn.prepareStatement(query);//이때 값이 들어가진 않는다!!
System.out.println("3. PreparedStatement 생성..");
ps.setInt(1, 333);
ps.setString(2, "박나래");
ps.setString(3, "여의도");
//4. Query문 실행 메소드 -> executeUpdate(), executeQuery()
int row = ps.executeUpdate();
System.out.println(row+" row insert...ok");
String querydel = "DELETE FROM mytable WHERE num=?";
PreparedStatement ps1 = conn.prepareStatement(querydel);
System.out.println("3. PreparedStatement 생성..");
ps1.setInt(1, 333);
System.out.println(ps1.executeUpdate()+" row delete...ok");
//update문 실행...111인 사람의 이름과 주소를 변경 (정우재, 방배동)
String queryUpdate = "UPDATE mytable SET name=?, address=? WHERE num=?";
PreparedStatement ps2 = conn.prepareStatement(queryUpdate);
System.out.println("3. PreparedStatement 생성..");
ps2.setString(1, "정우재");
ps2.setString(2, "방배동");
ps2.setInt(3, 111);
System.out.println(ps2.executeUpdate()+" row update...ok");
*/
//mytable에 있는 모든 정보를 다 가져와서 출력
PreparedStatement ps3 = conn.prepareStatement(query);
System.out.println("3. PreparedStatement 생성..");
ResultSet rs = ps3.executeQuery();
System.out.println("================================================");
while(rs.next()) {
System.out.println(rs.getInt("num")+"\t"+rs.getString("name")+"\t"+rs.getString("address"));
}
System.out.println("================================================");
}
public static void main(String[] args) throws ClassNotFoundException, SQLException {
new JDBC4StepTest();
}
static {
//1. properties파일의 내용을 로드해온다.
try {
Properties p = new Properties();
p.load(new FileInputStream("src/config/db.properties"));//절대경로 보다는 상대경로
driver = p.getProperty("jdbc.mysql.driver");
url = p.getProperty("jdbc.mysql.url");
user = p.getProperty("jdbc.mysql.user");
pass = p.getProperty("jdbc.mysql.pass");
query = p.getProperty("jdbc.sql.selectAll");
} catch (Exception e) {
}
}
}
|
package com.tencent.mm.plugin.account.ui;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
class MobileInputUI$12 implements OnMenuItemClickListener {
final /* synthetic */ MobileInputUI eTe;
MobileInputUI$12(MobileInputUI mobileInputUI) {
this.eTe = mobileInputUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
MobileInputUI.b(this.eTe);
return true;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.commerceservices.attributeHandlers;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.commerceservices.model.OrganizationRolesAttribute;
import de.hybris.platform.commerceservices.organization.services.OrgUnitService;
import de.hybris.platform.core.model.security.PrincipalGroupModel;
import de.hybris.platform.core.model.user.EmployeeModel;
import java.util.HashSet;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
/**
* OrganizationRoleAttribute dynamic attribute handler unit test. This dynamic attribute is defined in Employee type.
*/
@UnitTest
public class OrganizationRolesAttributeTest
{
private static final String ORG_EMPLOYEE = "salesemployee";
private OrgUnitService orgUnitService;
private OrganizationRolesAttribute organizationRolesAttribute;
private EmployeeModel employeeModel;
private PrincipalGroupModel principalGroupModel;
private Set<PrincipalGroupModel> roles;
@Before
public void setUp()
{
orgUnitService = Mockito.mock(OrgUnitService.class);
organizationRolesAttribute = new OrganizationRolesAttribute();
organizationRolesAttribute.setOrgUnitService(orgUnitService);
employeeModel = new EmployeeModel();
principalGroupModel = new PrincipalGroupModel();
principalGroupModel.setUid(ORG_EMPLOYEE);
roles = new HashSet<PrincipalGroupModel>();
roles.add(principalGroupModel);
}
@Test(expected = IllegalArgumentException.class)
public void testAttributeHandlerForNull()
{
organizationRolesAttribute.get(null);
}
@Test
public void testAttributeHandler()
{
Mockito.when(orgUnitService.getRolesForEmployee(employeeModel)).thenReturn(roles);
Assert.assertEquals(principalGroupModel, organizationRolesAttribute.get(employeeModel).iterator().next());
}
} |
package com.yygame.common.utils;
import org.junit.Test;
/**
* @author yzy
*/
public class AesUtilTest {
@Test
public void testEncryptAndDecrypt() {
String key = "2d9472f8-18bb-4291-8d0b-7851e8088f3b";
String content = "B2A9EEC49B2C841B1D722046378F11DB";
String encode = AesUtil.encrypt(content, key);
System.out.println("编码后: " + encode);
String decode = AesUtil.encrypt(encode, key);
System.out.println("解码后: " + decode);
}
} |
package Test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import Model.Question;
class AnswerInputTest {
@Test
void test() {
String player1name = "checkGetRandomQuestionPlayer1", player2name = "checkGetRandomQuestionPlayer2", difficultEasy = "Easy";
Controller.GameManagement.SetBoard(player1name, player2name, difficultEasy);
Question currQuestion;
int correctAnswervalue = 1, wrongAnswervalue = -2, correctScore;
correctScore = correctAnswervalue + (3 * wrongAnswervalue);
try {
currQuestion = Controller.GameManagement.GetRandomQuestion();
Controller.GameManagement.AnswerInput(Controller.GameManagement.GetBoard().GetFirstPlayer().getFirstAnswerButton(), Controller.GameManagement.GetBoard().GetFirstPlayer(), currQuestion);
Controller.GameManagement.AnswerInput(Controller.GameManagement.GetBoard().GetFirstPlayer().getSecondAnswerButton(), Controller.GameManagement.GetBoard().GetFirstPlayer(), currQuestion);
Controller.GameManagement.AnswerInput(Controller.GameManagement.GetBoard().GetFirstPlayer().getThirdAnswerButton(), Controller.GameManagement.GetBoard().GetFirstPlayer(), currQuestion);
Controller.GameManagement.AnswerInput(Controller.GameManagement.GetBoard().GetFirstPlayer().getFourthAnswerButton(), Controller.GameManagement.GetBoard().GetFirstPlayer(), currQuestion);
Controller.GameManagement.AnswerInput(Controller.GameManagement.GetBoard().GetSecondPlayer().getFirstAnswerButton(), Controller.GameManagement.GetBoard().GetSecondPlayer(), currQuestion);
Controller.GameManagement.AnswerInput(Controller.GameManagement.GetBoard().GetSecondPlayer().getSecondAnswerButton(), Controller.GameManagement.GetBoard().GetSecondPlayer(), currQuestion);
Controller.GameManagement.AnswerInput(Controller.GameManagement.GetBoard().GetSecondPlayer().getThirdAnswerButton(), Controller.GameManagement.GetBoard().GetSecondPlayer(), currQuestion);
Controller.GameManagement.AnswerInput(Controller.GameManagement.GetBoard().GetSecondPlayer().getFourthAnswerButton(), Controller.GameManagement.GetBoard().GetSecondPlayer(), currQuestion);
if (Controller.GameManagement.GetBoard().GetFirstPlayer().getScore() != correctScore)
fail("Falit in claculating the First Player Score");
if (Controller.GameManagement.GetBoard().GetSecondPlayer().getScore() != correctScore)
fail("Falit in claculating the Second Player Score");
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
/*
* This software is licensed under the MIT License
* https://github.com/GStefanowich/MC-Server-Protection
*
* Copyright (c) 2019 Gregory Stefanowich
*
* 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:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* 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 net.theelm.sewingmachine.protection.mixins.World;
import net.theelm.sewingmachine.base.CoreMod;
import net.theelm.sewingmachine.protection.enums.ClaimPermissions;
import net.theelm.sewingmachine.protection.enums.ClaimRanks;
import net.theelm.sewingmachine.protection.enums.ClaimSettings;
import net.theelm.sewingmachine.exceptions.TranslationKeyException;
import net.theelm.sewingmachine.protection.interfaces.Claim;
import net.theelm.sewingmachine.protection.interfaces.ClaimsAccessor;
import net.theelm.sewingmachine.protection.interfaces.IClaimedChunk;
import net.theelm.sewingmachine.protection.objects.ClaimCache;
import net.theelm.sewingmachine.protection.utilities.ClaimChunkUtils.ClaimSlice;
import net.theelm.sewingmachine.protection.claims.ClaimantPlayer;
import net.theelm.sewingmachine.protection.claims.ClaimantTown;
import net.theelm.sewingmachine.utilities.ChunkUtils;
import net.theelm.sewingmachine.utilities.nbt.NbtUtils;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtElement;
import net.minecraft.nbt.NbtList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.BlockView;
import net.minecraft.world.HeightLimitView;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.WorldChunk;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;
@Mixin(Chunk.class)
public abstract class ChunkMixin implements BlockView, IClaimedChunk, Claim {
private final ClaimSlice[] claimSlices = new ClaimSlice[256];
// Town is a weak reference here but NOT in ClaimantPlayer, we only want to load the Town once from the Player
private WeakReference<ClaimantTown> chunkTown = null;
private ClaimantPlayer chunkPlayer = null;
@Shadow @Final
protected HeightLimitView heightLimitView;
@Shadow
public native void setNeedsSaving(boolean shouldSave);
@Override
public ClaimantTown updateTownOwner(@Nullable UUID owner, boolean fresh) {
ClaimantTown town = null;
if (owner != null)
town = this.getClaimCache().getTownClaim(owner);
// Make sure we have the towns permissions cached
this.chunkTown = (town == null ? null : new WeakReference<>(town));
if ( fresh )
this.setNeedsSaving(true);
return this.getTown();
}
private ClaimantTown loadTownReference(@NotNull ClaimantTown town) {
return (this.chunkTown = new WeakReference<>(town)).get();
}
@Override
public ClaimantPlayer updatePlayerOwner(@Nullable UUID owner, boolean fresh) {
this.chunkPlayer = ( owner == null ? null : this.getClaimCache().getPlayerClaim(owner));
if (fresh)
this.setNeedsSaving(true);
// If there is no player owner, there is no town
if (owner == null) {
// Reset the inner slices (SHOULD NOT RESET SPAWN)
this.resetSlices();
this.updateTownOwner(null, fresh);
}
return this.chunkPlayer;
}
public void resetSlices() {
ClaimSlice slice;
for (int i = 0; i < this.claimSlices.length; i++) {
if ((slice = this.claimSlices[i]) == null)
continue;
slice.reset();
}
this.setNeedsSaving(true);
}
@Override
public void updateSliceOwner(UUID owner, int slicePos, int yFrom, int yTo, boolean fresh) {
// If heights are invalid
if (this.heightLimitView.isOutOfHeightLimit(yFrom) || this.heightLimitView.isOutOfHeightLimit(yTo))
return;
ClaimSlice slice;
if ((slice = this.claimSlices[slicePos]) == null)
slice = (this.claimSlices[slicePos] = new ClaimSlice(this.getClaimCache(), this.heightLimitView, slicePos));
// Get upper and lower positioning
int yMax = Math.max(yFrom, yTo);
int yMin = Math.min(yFrom, yTo);
slice.insert(owner, yMax, yMin);
// Make sure the chunk gets saved
if ( fresh )
this.setNeedsSaving(true);
}
public UUID[] getSliceOwner(int slicePos, int yFrom, int yTo) {
ClaimSlice slice;
if ((slice = this.claimSlices[slicePos]) == null)
return new UUID[0];
// Get upper and lower positioning
int yMax = Math.max(yFrom, yTo);
int yMin = Math.min(yFrom, yTo);
// Get all owners
Set<UUID> owners = new HashSet<>();
for (int y = yMin; y <= yMax; y++) {
ClaimSlice.InnerClaim claim = slice.get(y);
if (claim != null)
owners.add(claim.getOwnerId());
}
return owners.toArray(new UUID[0]);
}
@Override
public @NotNull ClaimSlice[] getSlices() {
return this.claimSlices;
}
@Override
public void setSlices(@NotNull ClaimSlice[] slices) {
int c = slices.length;
for (int i = 0; i < c; i++)
this.claimSlices[i] = slices[i];
}
public @NotNull Claim getClaim(BlockPos blockPos) {
int slicePos = ChunkUtils.getPositionWithinChunk( blockPos );
ClaimSlice slice;
if ((slice = this.claimSlices[slicePos]) != null) {
// Get inside claim
ClaimSlice.InnerClaim inner = slice.get(blockPos.getY());
// If claim inner is not nobody
if (inner != null && inner.getOwnerId() != null && inner.isWithin(blockPos.getY()))
return inner;
}
return this;
}
@Override
public boolean canPlayerClaim(@NotNull ClaimantPlayer player, boolean stopIfClaimed) throws TranslationKeyException {
// If the chunk is owned, return false
if (this.chunkPlayer != null) {
if (stopIfClaimed)
throw new TranslationKeyException("claim.chunk.error.claimed");
return false;
}
// Check claims limit (If the player is spawn, always allow)
if (!player.getId().equals(CoreMod.SPAWN_ID) && !player.canClaim((Chunk)(Object) this))
throw new TranslationKeyException("claim.chunk.error.max");
return true;
}
@Override
public @Nullable ClaimCache getClaimCache() {
Chunk chunk = (Chunk)(Object)this;
World world = null;
// TODO: Alternative way of getting the World from the Chunk?
if (chunk instanceof WorldChunk worldChunk)
world = worldChunk.getWorld();
else if (this.heightLimitView instanceof World viewWorld)
world = viewWorld;
if (world.isClient()) {
return ((ClaimsAccessor) world).getClaimManager();
} else if (world != null)
return ((ClaimsAccessor) world.getServer()).getClaimManager();
return null;
}
@Override
public @Nullable UUID getOwnerId() {
if (this.chunkPlayer == null)
return null;
return this.chunkPlayer.getId();
}
@Override
public @Nullable UUID getOwnerId(@Nullable BlockPos pos) {
if (pos != null) {
int slicePos = ChunkUtils.getPositionWithinChunk(pos);
if (this.claimSlices[slicePos] != null) {
ClaimSlice slice = claimSlices[slicePos];
// Get the players Y position
ClaimSlice.InnerClaim claim = slice.get(pos);
// Check that the player is within the Y
if (claim != null && claim.isWithin(pos))
return claim.getOwnerId();
}
}
return this.getOwnerId();
}
@Override
public @Nullable ClaimantPlayer getOwner() {
return this.chunkPlayer;
}
@Override
public @Nullable UUID getTownId() {
ClaimantTown town;
if ((town = this.getTown()) == null)
return null;
return town.getId();
}
@Override
public @Nullable ClaimantTown getTown() {
if (( this.chunkPlayer == null ))
return null;
if (this.chunkTown == null) {
ClaimantTown playerTown;
if ((playerTown = this.chunkPlayer.getTown()) != null)
return this.loadTownReference(playerTown);
}
return (this.chunkTown == null ? null : this.chunkTown.get());
}
@Override
public boolean canPlayerDo(@Nullable UUID player, @Nullable ClaimPermissions perm) {
if (this.chunkPlayer == null || (player != null && player.equals(this.chunkPlayer.getId())))
return true;
ClaimantTown town;
if ( ((town = this.getTown()) != null ) && (player != null) && player.equals( town.getOwnerId() ) )
return true;
// Get the ranks of the user and the rank required for performing
ClaimRanks userRank = this.chunkPlayer.getFriendRank(player);
ClaimRanks permReq = this.chunkPlayer.getPermissionRankRequirement(perm);
// Return the test if the user can perform the action (If friend of chunk owner OR if friend of town and chunk owned by town owner)
return permReq.canPerform(userRank) || ((town != null) && (this.chunkPlayer.getId().equals(town.getOwnerId())) && permReq.canPerform(town.getFriendRank(player)));
}
@Override
public boolean canPlayerDo(@NotNull BlockPos pos, @Nullable UUID player, @Nullable ClaimPermissions perm) {
return this.getClaim(pos)
.canPlayerDo(player, perm);
}
@Override
public boolean isSetting(@NotNull ClaimSettings setting) {
if (this.chunkPlayer == null)
return setting.getDefault(this.getOwnerId());
return setting.hasSettingSet(this);
}
@Override
public boolean isSetting(@NotNull BlockPos pos, @NotNull ClaimSettings setting) {
if ( !setting.isEnabled() )
return setting.getDefault( this.getOwnerId() );
else
return this.getClaim( pos )
.isSetting( setting );
}
@Override
public @NotNull NbtList serializeSlices() {
NbtList serialized = new NbtList();
ClaimSlice slice;
for (int i = 0; i < this.claimSlices.length; i++) {
// Slice must be defined
if ((slice = this.claimSlices[i]) == null)
continue;
// Create a new tag to save the slice
NbtCompound sliceTag = new NbtCompound();
NbtList claimsTag = new NbtList();
// For all slice claims
Iterator<ClaimSlice.InnerClaim> claims = slice.getClaims();
while ( claims.hasNext() ) {
ClaimSlice.InnerClaim claim = claims.next();
// If bottom of world, or no owner
if ((claim.lower() == -1) || (claim.getOwnerId() == null))
continue;
// Save data to the tag
NbtCompound claimTag = new NbtCompound();
claimTag.putUuid("owner", claim.getOwnerId());
claimTag.putInt("upper", claim.upper());
claimTag.putInt("lower", claim.lower());
// Add tag to array
claimsTag.add(claimTag);
}
// Save data for slice
sliceTag.putInt("i", i);
sliceTag.put("claims", claimsTag);
// Save the tag
serialized.add(sliceTag);
}
return serialized;
}
@Override
public void deserializeSlices(@NotNull NbtList serialized) {
for (NbtElement tag : serialized) {
// Must be compound tags
if (!(tag instanceof NbtCompound sliceTag))
continue;
NbtList claimsTag = sliceTag.getList("claims", NbtElement.COMPOUND_TYPE);
int i = sliceTag.getInt("i");
for (NbtElement claimTag : claimsTag) {
UUID owner = NbtUtils.getUUID((NbtCompound) claimTag,"owner");
int upper = ((NbtCompound) claimTag).getInt("upper");
int lower = ((NbtCompound) claimTag).getInt("lower");
this.updateSliceOwner(owner, i, lower, upper, false);
}
}
}
}
|
package org.fuserleer.ledger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Objects;
import org.fuserleer.crypto.BLSKeyPair;
import org.fuserleer.crypto.BLSPublicKey;
import org.fuserleer.crypto.BLSSignature;
import org.fuserleer.crypto.CryptoException;
import org.fuserleer.crypto.Hash;
import org.fuserleer.serialization.DsonOutput;
import org.fuserleer.serialization.SerializerId2;
import org.fuserleer.serialization.DsonOutput.Output;
import org.fuserleer.utils.UInt256;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.primitives.Longs;
@SerializerId2("ledger.state.vote")
public final class StateVote extends Vote<StateKey<?, ?>, BLSKeyPair, BLSPublicKey, BLSSignature>
{
@JsonProperty("block")
@DsonOutput(Output.ALL)
private Hash block;
/** Carries the producer of the block for this state key.
* <br><br>
* The producer is agreed upon via the votes and included in the state certificate.
* As the state certificates are sent to remote shard groups, it allows validators in
* the other groups to maintain an accurate set of the validators present in all groups.
* Including the producer also promotes a correct re-play for syncing validators.
* <br><br>
* TODO check edge cases on this ...
* <br><br>
* if a block is sparsely populated it may not touch all other shard groups
* which may in turn leave "gaps" in remote validators knowledge the global validator set.
* This is particularly risky if the block producer is a new validator who doesn't produce another
* block for some time after the initial block and may cause a "vote power" discrepancy large enough
* to prevent validation of state certificates.
*/
@JsonProperty("producer")
@DsonOutput(Output.ALL)
private BLSPublicKey producer;
@JsonProperty("atom")
@DsonOutput(Output.ALL)
private Hash atom;
@JsonProperty("input")
@DsonOutput(Output.ALL)
private UInt256 input;
@JsonProperty("output")
@DsonOutput(Output.ALL)
private UInt256 output;
@JsonProperty("execution")
@DsonOutput(Output.ALL)
private Hash execution;
@SuppressWarnings("unused")
private StateVote()
{
// SERIALIZER
}
StateVote(final StateKey<?, ?> state, final Hash atom, final Hash block, final BLSPublicKey producer, final UInt256 input, final UInt256 output, final Hash execution)
{
super(state, Objects.requireNonNull(execution, "Execution is null").equals(Hash.ZERO) == false ? StateDecision.POSITIVE : StateDecision.NEGATIVE);
Objects.requireNonNull(atom, "Block is null");
Hash.notZero(block, "Block is ZERO");
Objects.requireNonNull(producer, "Producer is null");
Objects.requireNonNull(atom, "Atom is null");
Hash.notZero(atom, "Atom is ZERO");
this.atom = atom;
this.block = block;
this.producer = producer;
this.input = input;
this.output = output;
this.execution = execution;
}
public StateVote(final StateKey<?, ?> state, final Hash atom, final Hash block, final BLSPublicKey producer, final UInt256 input, final UInt256 output, final Hash execution, final BLSPublicKey owner)
{
super(state, Objects.requireNonNull(execution, "Execution is null").equals(Hash.ZERO) == false ? StateDecision.POSITIVE : StateDecision.NEGATIVE, owner);
Objects.requireNonNull(atom, "Block is null");
Hash.notZero(block, "Block is ZERO");
Objects.requireNonNull(producer, "Producer is null");
Objects.requireNonNull(atom, "Atom is null");
Hash.notZero(atom, "Atom is ZERO");
this.atom = atom;
this.block = block;
this.producer = producer;
this.input = input;
this.output = output;
this.execution = execution;
}
public StateVote(final StateKey<?, ?> state, final Hash atom, final Hash block, final BLSPublicKey producer, final UInt256 input, final UInt256 output, final Hash execution, final BLSPublicKey owner, final BLSSignature signature, BLSSignature aggregatable) throws CryptoException
{
super(state, Objects.requireNonNull(execution, "Execution is null").equals(Hash.ZERO) == false ? StateDecision.POSITIVE : StateDecision.NEGATIVE, owner, signature);
Objects.requireNonNull(atom, "Block is null");
Hash.notZero(block, "Block is ZERO");
Objects.requireNonNull(producer, "Producer is null");
Objects.requireNonNull(atom, "Atom is null");
Hash.notZero(atom, "Atom is ZERO");
this.atom = atom;
this.block = block;
this.producer = producer;
this.input = input;
this.output = output;
this.execution = execution;
}
public Hash getAtom()
{
return this.atom;
}
public Hash getBlock()
{
return this.block;
}
public BLSPublicKey getProducer()
{
return this.producer;
}
public long getHeight()
{
return Longs.fromByteArray(this.block.toByteArray());
}
public <T extends StateKey<?, ?>> T getState()
{
return (T) this.getObject();
}
public UInt256 getInput()
{
return this.input;
}
public UInt256 getOutput()
{
return this.output;
}
public Hash getExecution()
{
return this.execution;
}
@Override
Hash getTarget() throws CryptoException
{
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(this.getState().toByteArray());
baos.write(this.atom.toByteArray());
baos.write(this.block.toByteArray());
baos.write(this.producer.toByteArray());
baos.write(this.execution.toByteArray());
// TODO input AND output can be null??
if (this.output != null)
baos.write(this.output.toByteArray());
if (this.input != null)
baos.write(this.input.toByteArray());
return Hash.from(baos.toByteArray());
}
catch (IOException ioex)
{
throw new CryptoException(ioex);
}
}
}
|
package fr.projetcookie.boussole.providers;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import android.location.Location;
public class BaloonPositionFromServer extends BaloonPositionProvider {
boolean stillAlive=true;
private Location mLastLocation=new Location("baloon");
private String mServer="";
private static final int ID_GPS = 0;
private static final int ID_VAL_LAT = 0;
private static final int ID_VAL_LON = 1;
private static final int ID_VAL_ALT = 2;
public BaloonPositionFromServer(int t) {
super(t);
}
public BaloonPositionFromServer(int t, String server) {
super(t);
mServer=server;
}
public void run() {
while(stillAlive) {
/*
This was a triumph.
I'm making a note here: HUGE SUCCESS.
It's hard to overstate my satisfaction.
Aperture Science
We do what we must
because we can.
For the good of all of us.
Except the ones who are dead.
But there's no sense crying over every mistake.
You just keep on trying till you run out of cake.
And the Science gets done.
And you make a neat gun.
For the people who are still alive.
I'm not even angry.
I'm being so sincere right now.
Even though you broke my heart.
And killed me.
And tore me to pieces.
And threw every piece into a fire.
As they burned it hurt because I was so happy for you!
Now these points of data make a beautiful line.
And we're out of beta.
We're releasing on time.
So I'm GLaD. I got burned.
Think of all the things we learned
for the people who are still alive.
Go ahead and leave me.
I think I prefer to stay inside.
Maybe you'll find someone else to help you.
Maybe Black Mesa
THAT WAS A JOKE.
HAHA. FAT CHANCE.
Anyway, this cake is great.
It's so delicious and moist.
Look at me still talking
when there's Science to do.
When I look out there, it makes me GLaD I'm not you.
I've experiments to run.
There is research to be done.
On the people who are still alive.
And believe me I am still alive.
I'm doing Science and I'm still alive.
I feel FANTASTIC and I'm still alive.
While you're dying I'll be still alive.
And when you're dead I will be still alive.
STILL ALIVE (x2)
*/
try {
String request = mServer + (mServer.endsWith("/") ? "" : "/") + "bin/get.php?c=" + ID_GPS + "&t=0&n=1";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
response = httpclient.execute(new HttpGet(request));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();
JSONArray ja = new JSONArray(responseString);
double lat = ja.getJSONArray(ID_VAL_LAT).getJSONArray(0).getDouble(1);
double lon = ja.getJSONArray(ID_VAL_LON).getJSONArray(0).getDouble(1);
double alt = ja.getJSONArray(ID_VAL_ALT).getJSONArray(0).getDouble(1);
mLastLocation.setAltitude(alt);
mLastLocation.setLatitude(lat);
mLastLocation.setLongitude(lon);
} else{
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
try {
Thread.sleep(refresh_time);
} catch (InterruptedException e) {
e.printStackTrace();
stillAlive = false;
}
}
}
public void setServer(String newServer) {
mServer = newServer;
}
@Override
public float stahp() {
stillAlive=false;
return 0;
}
@Override
public Location getLocation() {
return mLastLocation;
}
}
|
package com.example.graeme.blockpuzzle;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
private Intent intent = null;
private SoundSystem soundSystem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
String menu[] = {"Car Puzzles", "Animal Puzzles", "Statistics"};
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_menu, menu);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
intent = new Intent(getApplicationContext(), carPuzzle.class);
startActivity(intent);
break;
case 1:
intent = new Intent(getApplicationContext(), animalPuzzle.class);
startActivity(intent);
break;
case 2:
intent = new Intent(getApplicationContext(), Statistics.class);
startActivity(intent);
break;
}
}
});
soundSystem = new SoundSystem(this);
}
@Override
protected void onPause(){
soundSystem.stop();
super.onPause();
}
protected void onResume(){
super.onResume();
soundSystem.start();
}
}
|
package com.hjl.demo.Utils.event;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
/**
* [description about this class]
*
* @author hujiao
* @version [Demo, 2016/04/06 11:40]
* @copyright Copyright 2010 RD information technology Co.,ltd.. All Rights Reserved.
*/
public class BaseActivity extends AppCompatActivity {
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
afterSetContentView();
}
@Override
public void setContentView(View view) {
super.setContentView(view);
afterSetContentView();
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
super.setContentView(view, params);
afterSetContentView();
}
/**
* setContentView之后调用, 进行view的初始化等操作
*/
private void afterSetContentView()
{
ViewUtils.inject(this);
init();
}
protected void init() {
}
}
|
package org.dummy.jdbc.sql;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
/**
* INSERT.
*/
public class Insert {
private String tab;
private List<String> cols = new ArrayList<>();
private List<String> vals = new ArrayList<>();
public Insert into(String tab) {
this.tab = tab;
return this;
}
public Insert value(String key, Object val) {
this.cols.add(key);
if(val instanceof String){
this.vals.add("\'" + val + "\'");
} else {
this.vals.add(String.valueOf(val));
}
return this;
}
public Insert cols(String... cols){
for(String col : cols){
this.cols.add(col);
}
return this;
}
public Insert values(Object... vals){
if(vals.length == 0 || vals.length % this.cols.size() != 0){
throw new IllegalStateException("Wrong tuple size");
}
for(Object val : vals){
if(val instanceof String){
this.vals.add("\'" + val + "\'");
} else {
this.vals.add(String.valueOf(val));
}
}
return this;
}
private StringJoiner getInnerJoiner(){
return new StringJoiner(",", "(", ")");
}
private StringJoiner getOuterJoiner(){
return new StringJoiner(",", "", "");
}
@SuppressWarnings("squid:ForLoopCounterChangedCheck")
private String getValuesClause(){
StringJoiner outer = getOuterJoiner();
StringJoiner inner;
for(int i = 0; i < this.vals.size(); ){
inner = getInnerJoiner();
for(int j = 0; j < this.cols.size(); j++){
inner.add(this.vals.get(i));
i++;
}
outer.add(inner.toString());
}
return outer.toString();
}
@Override
public String toString() {
return toString(" ");
}
public String toString(String delimiter) {
return "insert into " + delimiter + tab + delimiter +
"(" + cols.stream().collect(Collectors.joining(",")) + ")" + delimiter +
"values" + delimiter + getValuesClause();
}
}
|
package exceptions;
// Referenced classes of package exceptions:
// LexicalException
public class IllegalIntegerException extends LexicalException
{
public IllegalIntegerException()
{
this("Illegal Integer, no blank between interger and letters.");
}
public IllegalIntegerException(String s)
{
super("Illegal Integer, no blank between interger and letters.\n"+s);
}
}
|
package com.mybigday.rnthermalprinter;
import com.facebook.react.bridge.ReadableMap;
/**
* Created by pepper on 2017/11/22.
*/
public interface Printer {
void writeText(String text, ReadableMap property);
void writeQRCode(String content, ReadableMap property);
void writeImage(String path, ReadableMap property);
void writeFeed(int length);
void writeCut(ReadableMap property);
void startPrint();
void endPrint();
}
|
package com.trainining.day23.threads;
public class ThreadInference {
public static void main(String[] args) {
final Shared s = new Shared();
Thread t1 = new Thread() {
@Override
public void run() {
s.m1();
}
};
Thread t2 = new Thread() {
@Override
public void run() {
s.m1();
}
};
t1.start();
t2.start();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pasosServer.servlet;
import com.frame.JavaBeans.Frame;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pasosServer.ejb.AlarmaFacadeRemote;
import pasosServer.ejb.MaltratadorFacadeRemote;
import pasosServer.ejb.ProtegidoFacadeRemote;
import pasosServer.model.Alarma;
import pasosServer.model.Maltratador;
import pasosServer.model.Protegido;
/**
*
* @author Jesus Ruiz Oliva
*/
//@WebServlet(name = "FrameHandlerServlet", urlPatterns = {"/FrameHandlerServlet"})
public class FrameHandlerServlet extends HttpServlet {
@EJB
private AlarmaFacadeRemote alarmaFacade;
@EJB
private MaltratadorFacadeRemote maltratadorFacade;
@EJB
private ProtegidoFacadeRemote protegidoFacade;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/html;charset=UTF-8");
System.out.println("ENTRA SERVLET FRAME");
Frame frame = new Frame();
RequestDispatcher requestDispatcher;
String trama = request.getParameter("trama");
System.out.println("OBTENIDA TRAMA "+trama);
if (trama!=null && !trama.isEmpty()){
String typeFrame = trama.substring(1,3);
if (typeFrame.equals("ZN") || typeFrame.equals("TE")){
frame.setType(typeFrame);
trama = trama.substring(4);
} else if (typeFrame.startsWith("AU")){
frame.setType(trama.substring(1,5));
trama = trama.substring(6);
}
System.out.println("Trama para trocear: "+trama);
String[] trozos =trama.split("&");
System.out.println(trozos.toString()+"Tamaño: "+trozos.length);
for (int i=0; i<trozos.length; i++){
String trozo=trozos[i];
System.out.println("TROZO "+i+": "+trozo);
if(trozo != null && !trozo.isEmpty()){
if (trozo.substring(0, 2).equals("LD")){
frame.setLD(trozo.substring(2));
}
else if (trozo.substring(0, 2).equals("LH")){
frame.setLH(trozo.substring(2));
}
else if (trozo.substring(0, 2).equals("LN")){
frame.setLN(converterLongitud(trozo.substring(2)));
}
else if (trozo.substring(0, 2).equals("LT")){
frame.setLT(converterLatitud(trozo.substring(2)));
}
else if (trozo.substring(0, 2).equals("RD")){
frame.setRD(trozo.substring(2));
}
}
}
System.out.println("TIPO TRAMA: "+frame.getType());
if (frame.getType().equals("TE")){
//Almacenar en BD
Protegido protegido = protegidoFacade.findByimei(frame.getRD());
protegido.setLatitud(new BigInteger(frame.getLT()));
protegido.setLongitud(new BigInteger(frame.getLN()));
protegidoFacade.updateProtegido(protegido);
}
if (frame.getType().equals("ZN") || frame.getType().startsWith("AU")){
request.setAttribute("trama",frame);
System.out.println("Se va a enviar trama: "+frame);
requestDispatcher = getServletContext().getRequestDispatcher("/comet");
requestDispatcher.forward(request, response);
}
}
}
public String converterLatitud(String coordenada){
System.out.println("coordenda: " + coordenada);
int signo = Integer.parseInt(coordenada.substring(0,1));
float hh = Integer.parseInt(coordenada.substring(1,3));
float dd = Integer.parseInt(coordenada.substring(3,5));
float nnnn = Integer.parseInt(coordenada.substring(5));
float x = hh + dd/60 + nnnn/600000;
if (signo ==2){
x= -x;
}
System.out.println(Float.toString(x));
return Float.toString(x);
}
public String converterLongitud(String coordenada){
System.out.println("coordenda: " + coordenada);
int signo = Integer.parseInt(coordenada.substring(0,1));
float hh = Integer.parseInt(coordenada.substring(1,4));
float dd = Integer.parseInt(coordenada.substring(4,6));
float nnnn = Integer.parseInt(coordenada.substring(6));
float x = hh + dd/60 + nnnn/600000;
if (signo ==2){
x= -x;
}
System.out.println(Float.toString(x));
return Float.toString(x);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package com.test.mjp.ui.fragment.animaldetails;
import android.arch.lifecycle.ViewModelProvider;
import com.test.mjp.interact.AnimalDetailsFetchInteract;
import io.reactivex.annotations.NonNull;
public class AnimalDetailsViewModelFactory implements ViewModelProvider.Factory {
private AnimalDetailsFetchInteract animalDetailsFetchInteract;
public AnimalDetailsViewModelFactory(AnimalDetailsFetchInteract animalDetailsFetchInteract) {
this.animalDetailsFetchInteract = animalDetailsFetchInteract;
}
@NonNull
@Override
public AnimalDetailsViewModel create(@NonNull Class modelClass) {
return new AnimalDetailsViewModelImpl(animalDetailsFetchInteract);
}
}
|
package com.bb.superdemo;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
/**
* @author ethan
* @version 创建时间: 2017/7/24.
*/
public class ShapeIndicatorView extends View implements TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener {
private Paint mShapePaint;
private Path mShapePath;
private RectF mRectF;
private int mShapeHorizontalSpace;
private int mShapeColor = Color.GREEN;
private TabLayout mTabLayout;
private ViewPager mViewPager;
int strokeWidth = 0;
private Bitmap mSrcB;
private Bitmap mDstB;
public ShapeIndicatorView(Context context) {
this(context, null);
}
public ShapeIndicatorView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ShapeIndicatorView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initViews(context, attrs, defStyleAttr, 0);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ShapeIndicatorView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initViews(context, attrs, defStyleAttr, defStyleRes);
}
private void initViews(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ShapeIndicatorView, defStyleRes, 0);
mShapeHorizontalSpace = array.getInteger(R.styleable.ShapeIndicatorView_horizontalSpace, 0);
mShapeColor = array.getColor(R.styleable.ShapeIndicatorView_fullColor, Color.GREEN);
strokeWidth = array.getInteger(R.styleable.ShapeIndicatorView_strokeWidth, 0);
array.recycle();
mShapePaint = new Paint();
mShapePaint.setAntiAlias(true);
mShapePaint.setDither(true);
mShapePaint.setColor(mShapeColor);
}
public void setupWithTabLayout(final TabLayout tableLayout) {
mTabLayout = tableLayout;
tableLayout.setSelectedTabIndicatorColor(Color.TRANSPARENT);
tableLayout.setOnTabSelectedListener(this);
tableLayout.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
if (mTabLayout.getScrollX() != getScrollX())
scrollTo(mTabLayout.getScrollX(), mTabLayout.getScrollY());
}
});
ViewCompat.setElevation(this, ViewCompat.getElevation(mTabLayout));
tableLayout.post(new Runnable() {
@Override
public void run() {
if (mTabLayout.getTabCount() > 0)
onTabSelected(mTabLayout.getTabAt(0));
}
});
//清除Tab background
for (int tab = 0; tab < tableLayout.getTabCount(); tab++) {
View tabView = getTabViewByPosition(tab);
tabView.setBackgroundResource(0);
}
}
public void setupWithViewPager(ViewPager viewPager) {
mViewPager = viewPager;
viewPager.addOnPageChangeListener(this);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 绘制滑块
drawPath(canvas);
// 绘制背景
drawBackground(canvas);
}
/**
* 画一个圆角矩形的背景
* @param canvas
*/
private void drawBackground(Canvas canvas) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL);
paint.setDither(true);
paint.setStrokeWidth(strokeWidth);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
mSrcB = makeSrc(paint, width, height);
mDstB = makeDst(paint);
int sc = canvas.saveLayer(0, 0, width, height, null,
Canvas.MATRIX_SAVE_FLAG | Canvas.CLIP_SAVE_FLAG
| Canvas.HAS_ALPHA_LAYER_SAVE_FLAG
| Canvas.FULL_COLOR_LAYER_SAVE_FLAG
| Canvas.CLIP_TO_LAYER_SAVE_FLAG);
canvas.drawBitmap(mSrcB, 0, 0, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.XOR));
canvas.drawBitmap(mDstB, 0, 0, paint);
paint.setXfermode(null);
canvas.restoreToCount(sc);
}
/**
* 创建内圆bitmap
*/
private Bitmap makeDst(Paint paint) {
int width = getMeasuredWidth() - strokeWidth * 2;
int height = getMeasuredHeight() - strokeWidth * 2;
Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bm);
RectF left_rect = new RectF(height / 2 + strokeWidth, 0.f + strokeWidth * 2, width - height / 2, height);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(height / 2 + strokeWidth, height / 2 + strokeWidth, height / 2 - strokeWidth, paint);
canvas.drawRect(left_rect, paint);
canvas.drawCircle(width - height / 2 + strokeWidth, height / 2 + strokeWidth, height / 2 - strokeWidth, paint);
return bm;
}
/**
* 创建外圆bitmap
*/
static Bitmap makeSrc(Paint paint, int width, int height) {
Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bm);
RectF left_rect = new RectF(height / 2, 0.f, width - height / 2, height);
canvas.drawCircle(height / 2, height / 2, height / 2, paint);
canvas.drawRect(left_rect, paint);
canvas.drawCircle(width - height / 2, height / 2, height / 2, paint);
return bm;
}
/**
* 创建滑块bitmap
*/
Bitmap makeSubSrc( Paint paint) {
Bitmap bm = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bm);
RectF left_rect = new RectF(mRectF.left + mRectF.bottom / 2, mRectF.top, mRectF.right - mRectF.bottom / 2, mRectF.bottom);
canvas.drawCircle(mRectF.left + mRectF.bottom / 2, mRectF.bottom / 2, mRectF.bottom / 2, paint);
canvas.drawRect(left_rect, paint);
canvas.drawCircle(mRectF.right - mRectF.bottom / 2, mRectF.bottom / 2, mRectF.bottom / 2, paint);
return bm;
}
private void drawPath(Canvas canvas) {
if (mRectF == null || mRectF.isEmpty())
return;
int savePos = canvas.save();
Bitmap subBitmap = makeSubSrc(mShapePaint);
canvas.drawBitmap(subBitmap, 0, 0, mShapePaint);
canvas.restoreToCount(savePos);
}
private RectF generatePath(int position, float positionOffset) {
RectF range = new RectF();
View tabView = getTabViewByPosition(position);
if (tabView == null)
return null;
int left, top, right, bottom;
left = top = right = bottom = 0;
if (positionOffset > 0.f && position < mTabLayout.getTabCount() - 1) {
View nextTabView = getTabViewByPosition(position + 1);
left += (int) (nextTabView.getLeft() * positionOffset + tabView.getLeft() * (1.f - positionOffset));
right += (int) (nextTabView.getRight() * positionOffset + tabView.getRight() * (1.f - positionOffset));
left += mShapeHorizontalSpace;
right -= mShapeHorizontalSpace;
top = tabView.getTop() + getPaddingTop();
bottom = tabView.getBottom() - getPaddingBottom();
range.set(left, top, right, bottom);
} else {
left = tabView.getLeft() + mShapeHorizontalSpace;
right = tabView.getRight() - mShapeHorizontalSpace;
top = tabView.getTop() + getPaddingTop();
bottom = tabView.getBottom() - getPaddingBottom();
range.set(left, top, right, bottom);
if (range.isEmpty())
return range;
}
if (mShapePath == null)
mShapePath = new Path();
return range;
}
private View getTabViewByPosition(int position) {
if (mTabLayout != null && mTabLayout.getTabCount() > 0) {
ViewGroup tabStrip = (ViewGroup) mTabLayout.getChildAt(0);
return tabStrip != null ? tabStrip.getChildAt(position) : null;
}
return null;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
mRectF = generatePath(position, positionOffset);
invalidate();
}
@Override
public void onPageSelected(int position) {
if (mTabLayout.getSelectedTabPosition() != position)
mTabLayout.getTabAt(position).select();
}
@Override
public void onPageScrollStateChanged(int state) {
}
/**
* 当已经有一个ViewPager后,当TabLayout的tab改变的时候在onTabSelected方法直接调用ViewPager的
* setCurrentItem方法调用这个方法后会触发ViewPager的scroll事件也就是在onPageScrolled方法中调用
* generatePath方法来更新Path,如果没有ViewPager的话直接在onTabSelected的方法中调用generatePath
* 方法。
**/
@Override
public void onTabSelected(TabLayout.Tab tab) {
if (mViewPager != null) {
if (tab.getPosition() != mViewPager.getCurrentItem())
mViewPager.setCurrentItem(tab.getPosition());
} else {
mRectF = generatePath(tab.getPosition(), 0);
invalidate();
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
} |
package org.training.controller.commands.menu;
import org.training.constants.PageConstants;
import org.training.constants.URIConstants;
import org.training.controller.commands.Command;
import org.training.dao.impl.ItemDAOImpl;
import org.training.model.entities.Item;
import org.training.service.ItemService;
import org.training.service.impl.ItemServiceImpl;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.NumberFormat;
/**
* Created by nicko on 2/3/2017.
*/
public class AddItemCommand implements Command {
ItemService itemService = ItemServiceImpl.getInstance();
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("name");
try {
Double price = Double.parseDouble(request.getParameter("price"));
Integer weight = Integer.parseInt(request.getParameter("weight"));
if (!checkInput(price, weight, name)) {
request.setAttribute("error", "Invalid input");
return PageConstants.VIEW_ADDITEM_JSP;
}
Item item = new Item.Builder()
.setName(name)
.setPrice(price)
.setWeight(weight)
.build();
itemService.create(item);
} catch (NumberFormatException e) {
request.setAttribute("error", "Format error");
}
return PageConstants.VIEW_MENU_JSP;
}
private boolean checkInput(Double price, Integer weight, String name) {
if (price < 0 || weight < 0) {
return false;
}
if (name.trim().isEmpty()) {
return false;
}
return true;
}
}
|
package com.tencent.mm.plugin.collect.ui;
import com.tencent.mm.plugin.collect.a.a;
import com.tencent.mm.plugin.collect.ui.CollectMainUI.13;
import com.tencent.mm.plugin.wxpay.a$i;
import com.tencent.mm.protocal.c.atm;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.ui.base.l;
import com.tencent.mm.ui.base.n.c;
class CollectMainUI$13$1 implements c {
final /* synthetic */ 13 hYS;
CollectMainUI$13$1(13 13) {
this.hYS = 13;
}
public final void a(l lVar) {
a.aBC();
if (a.aBE()) {
lVar.add(0, 1, 0, a$i.collect_main_close_ring_tone);
} else {
lVar.add(0, 1, 0, a$i.collect_main_open_ring_tone);
}
if (this.hYS.eRE != null) {
for (int i = 0; i < this.hYS.eRE.size(); i++) {
atm atm = (atm) this.hYS.eRE.get(i);
if (!bi.oW(atm.bSc)) {
lVar.add(0, (i + 1) + 1, 0, atm.bSc);
}
}
}
}
}
|
package eg.edu.alexu.csd.oop.draw;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.Map;
public class AbstractShape implements Shape {
Point position = new Point();
Color color = new Color(000);
@Override
public void setPosition(Point position) {
// TODO Auto-generated method stub
this.position = position;
}
@Override
public Point getPosition() {
// TODO Auto-generated method stub
return position;
}
@Override
public void setProperties(Map<String, Double> properties) {
// TODO Auto-generated method stub
}
@Override
public Map<String, Double> getProperties() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setColor(Color color) {
// TODO Auto-generated method stub
this.color=color;
}
@Override
public Color getColor() {
// TODO Auto-generated method stub
return color;
}
@Override
public void setFillColor(Color color) {
// TODO Auto-generated method stub
}
@Override
public Color getFillColor() {
// TODO Auto-generated method stub
return null;
}
@Override
public void draw(Graphics canvas) {
// TODO Auto-generated method stub
}
public Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return null;
}
}
|
package queue;
import java.util.*;
public class Programmars_3 {
public static void main(String[] args){
Programmars_3 s = new Programmars_3();
int[] scoville = {1, 2, 3, 9, 10, 12};
int K = 7;
int answer = s.solution(scoville, K);
System.out.println(answer);
}
public int solution(int[] scoville, int K){
PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
});
for(int i=0; i < scoville.length; i++){
queue.offer(scoville[i]);
}
int answer = 0;
while(queue.peek() < K && queue.size() >= 2){
int new_scoville = queue.poll() + (queue.poll()*2);
queue.offer(new_scoville);
answer++;
}
if(queue.peek() < K){
answer = -1;
}
return answer;
}
}
|
package com.medplus.departmentinfo.service;
import java.util.List;
import com.medplus.departmentinfo.beans.DepartmentBean;
import com.medplus.departmentinfo.beans.EmployeeBean;
public interface DepartmentService {
public List<DepartmentBean> getALLDepartment();
public String updateDepartment(DepartmentBean departmentBean);
public String addDepartment(DepartmentBean departmentBean);
public DepartmentBean getDepartmentByID(int deptNo);
public List<EmployeeBean> getALLEmployeeByDeptNo(int deptNo);
}
|
//
// Este archivo ha sido generado por la arquitectura JavaTM para la implantación de la referencia de enlace (JAXB) XML v2.2.8-b130911.1802
// Visite <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Todas las modificaciones realizadas en este archivo se perderán si se vuelve a compilar el esquema de origen.
// Generado el: 2017.04.12 a las 12:06:14 PM CEST
//
package servicio.tipos;
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.XmlAttribute;
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>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="nombre" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="emision" maxOccurs="unbounded" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="titulo" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="url" type="{http://www.um.es/programasRTVE}tipoUrl"/>
* </sequence>
* <attribute name="fecha" use="required" type="{http://www.w3.org/2001/XMLSchema}date" />
* <attribute name="tiempo" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <pattern value="[0-9][0-9]:([0-5][0-9]):[0-5][0-9]"/>
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="productoAmazon" type="{http://www.um.es/programasRTVE}productoAmazon" maxOccurs="3" minOccurs="0"/>
* </sequence>
* <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="urlPrograma" use="required" type="{http://www.um.es/programasRTVE}tipoUrl" />
* <attribute name="urlImagen" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <pattern value="http://img.rtve.es/imagenes/.*\.(png|jpg|gif)"/>
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"nombre",
"emision",
"productoAmazon"
})
@XmlRootElement(name = "programa")
public class Programa {
@XmlElement(required = true)
protected String nombre;
protected List<Programa.Emision> emision;
protected List<ProductoAmazon> productoAmazon;
@XmlAttribute(name = "id", required = true)
protected String id;
@XmlAttribute(name = "urlPrograma", required = true)
protected String urlPrograma;
@XmlAttribute(name = "urlImagen", required = true)
protected String urlImagen;
/**
* Obtiene el valor de la propiedad nombre.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNombre() {
return nombre;
}
/**
* Define el valor de la propiedad nombre.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNombre(String value) {
this.nombre = value;
}
/**
* Gets the value of the emision 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 emision property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getEmision().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Programa.Emision }
*
*
*/
public List<Programa.Emision> getEmision() {
if (emision == null) {
emision = new ArrayList<Programa.Emision>();
}
return this.emision;
}
/**
* Gets the value of the productoAmazon 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 productoAmazon property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getProductoAmazon().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProductoAmazon }
*
*
*/
public List<ProductoAmazon> getProductoAmazon() {
if (productoAmazon == null) {
productoAmazon = new ArrayList<ProductoAmazon>();
}
return this.productoAmazon;
}
/**
* Obtiene el valor de la propiedad id.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Define el valor de la propiedad id.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Obtiene el valor de la propiedad urlPrograma.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUrlPrograma() {
return urlPrograma;
}
/**
* Define el valor de la propiedad urlPrograma.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUrlPrograma(String value) {
this.urlPrograma = value;
}
/**
* Obtiene el valor de la propiedad urlImagen.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUrlImagen() {
return urlImagen;
}
/**
* Define el valor de la propiedad urlImagen.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUrlImagen(String value) {
this.urlImagen = value;
}
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="titulo" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="url" type="{http://www.um.es/programasRTVE}tipoUrl"/>
* </sequence>
* <attribute name="fecha" use="required" type="{http://www.w3.org/2001/XMLSchema}date" />
* <attribute name="tiempo" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <pattern value="[0-9][0-9]:([0-5][0-9]):[0-5][0-9]"/>
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"titulo",
"url"
})
public static class Emision {
@XmlElement(required = true)
protected String titulo;
@XmlElement(required = true)
protected String url;
@XmlAttribute(name = "fecha", required = true)
@XmlSchemaType(name = "date")
protected XMLGregorianCalendar fecha;
@XmlAttribute(name = "tiempo", required = true)
protected String tiempo;
/**
* Obtiene el valor de la propiedad titulo.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitulo() {
return titulo;
}
/**
* Define el valor de la propiedad titulo.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitulo(String value) {
this.titulo = value;
}
/**
* Obtiene el valor de la propiedad url.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUrl() {
return url;
}
/**
* Define el valor de la propiedad url.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUrl(String value) {
this.url = value;
}
/**
* Obtiene el valor de la propiedad fecha.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getFecha() {
return fecha;
}
/**
* Define el valor de la propiedad fecha.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setFecha(XMLGregorianCalendar value) {
this.fecha = value;
}
/**
* Obtiene el valor de la propiedad tiempo.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTiempo() {
return tiempo;
}
/**
* Define el valor de la propiedad tiempo.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTiempo(String value) {
this.tiempo = value;
}
}
}
|
package com.vilio.mps.push.service;
import com.vilio.mps.common.dao.AppDao;
import com.vilio.mps.common.dao.MpsMessageReceiveInfoMapper;
import com.vilio.mps.common.pojo.App;
import com.vilio.mps.common.pojo.MpsReceiveMessageInfo;
import com.vilio.mps.common.service.BaseService;
import com.vilio.mps.common.service.CommonService;
import com.vilio.mps.exception.ErrorException;
import com.vilio.mps.glob.Constants;
import com.vilio.mps.glob.GlobDict;
import com.vilio.mps.push.dao.UmengDao;
import com.vilio.mps.push.pojo.Umeng;
import com.vilio.mps.util.DateUtil;
import com.vilio.mps.util.JudgeUtil;
import com.vilio.mps.util.UmengUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.log4j.Logger;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 类名: UmHH000804<br>
* 功能:友盟推送<br>
* 版本: 1.0<br>
* 日期: 2017年8月10日<br>
* 作者: wangxf<br>
* 版权:vilio<br>
* 说明:<br>
*/
@Service
public class UmHH000804 extends BaseService {
private static Logger logger = Logger.getLogger(UmHH000804.class);
@Resource
private AppDao appDao;
@Resource
private MpsMessageReceiveInfoMapper mpsMessageReceiveInfoMapper;
@Resource
private UmengDao umengDao;
@Resource
private CommonService commonService;
/**
* 参数验证
*
* @param body
*/
public void checkParamNoTransaction(Map<String, Object> body) throws ErrorException {
//校验必填字段
//信息发送方身份Id(如果没有则填写系统默认发送身份id)
checkField(ObjectUtils.toString(body.get("senderIdentityId")), "信息发送方身份标识", null, 100);
//信息接收方身份Id(下面的device_token)
//checkField(ObjectUtils.toString(body.get("receiverIdentityId")), "信息接收方身份标识", null, 100);
//消息来源系统
checkField(ObjectUtils.toString(body.get("senderSystem")), "消息来源系统", null, 18);
//请求流水号(后面可根据请求流水号查询推送业务)
checkField(ObjectUtils.toString(body.get("requestNo")), "请求流水号", null, 50);
//应用标识号
checkField(ObjectUtils.toString(body.get("appCode")), "应用标识号", null, 50);
//title
checkField(ObjectUtils.toString(body.get("title")), "通知标题", null, 500);
//text
checkField(ObjectUtils.toString(body.get("text")), "通知文字描述", null, 1000);
//系统类型
// checkField(ObjectUtils.toString(body.get("systemType")), "系统类型", null, 20);
// if (!GlobDict.system_type_android.getKey().equals(ObjectUtils.toString(body.get("systemType"))) &&
// !GlobDict.system_type_ios.getKey().equals(ObjectUtils.toString(body.get("systemType")))) {
// throw new ErrorException("9998", "系统类型错误");
// }
//device_tokens逗号分割,最大支持500个
checkField(ObjectUtils.toString(body.get("deviceTokens")), "", null, null);
String[] deviceTokens = ObjectUtils.toString(body.get("deviceTokens")).split(",");
if (deviceTokens.length > 500) {
throw new ErrorException("9998", "发送数必须小于500");
}
//校验非必填字段
//信息发送方名称
if (JudgeUtil.isNull(body.get("senderName")) && body.get("senderName").toString().length() > 255) {
throw new ErrorException("9998", "信息发送方名称超出长度限制");
}
//检查应用是否存在
checkField(ObjectUtils.toString(body.get("appCode")), "应用标识 ", null, 36);
App app = appDao.queryAppInfoByCode(ObjectUtils.toString(body.get("appCode")));
if (app == null) {
throw new ErrorException("0081", "");
}
if (GlobDict.app_status_disable.getKey().equals(app.getStatus())) {
//签名已停用
throw new ErrorException("0083", "");
} else if (GlobDict.app_status_delete.getKey().equals(app.getStatus())) {
//签名已删除
throw new ErrorException("0082", "");
} else if (!GlobDict.app_status_valid.getKey().equals(app.getStatus())) {
//不等于有效
throw new ErrorException("0084", "");
}
body.put("app", app);
if (GlobDict.system_type_android.getKey().equals(app.getSystemType())) {
//ticker(安卓必填)
checkField(ObjectUtils.toString(body.get("ticker")), "通知栏提示文字", null, 500);
} else if (GlobDict.system_type_ios.getKey().equals(app.getSystemType())) {
//subtitle(非必填)
if (JudgeUtil.isNull(body.get("subtitle")) && ObjectUtils.toString(body.get("subtitle")).length() > 500) {
throw new ErrorException("9998", "子标题长度超出限制");
}
}
}
/**
* 批量友盟发送流程处理
*
* @param head
* @param body
* @param resultMap
*/
public void busiServiceNoTransaction(Map<String, Object> head, Map<String, Object> body, Map<String, Object> resultMap) throws Exception {
//初始化入库
List<Umeng> umengs = ((UmHH000804) AopContext.currentProxy()).insertMsg(body);
App app = (App) body.get("app");
//发送到友盟
Map result = new HashMap();
//发送次数默认1
int sendNum = 1;
if (GlobDict.system_type_android.getKey().equals(app.getSystemType())) {
//安卓
result = UmengUtil.sendAndroidUnicast(app.getAppMasterSecret(), app.getAppKey(), ObjectUtils.toString(body.get("deviceTokens")),
ObjectUtils.toString(body.get("ticker")), ObjectUtils.toString(body.get("title")), ObjectUtils.toString(body.get("text")));
} else if (GlobDict.system_type_ios.getKey().equals(app.getSystemType())) {
//苹果
result = UmengUtil.sendIOSUnicast(app.getAppMasterSecret(), app.getAppKey(), ObjectUtils.toString(body.get("deviceTokens")),
ObjectUtils.toString(body.get("title")), ObjectUtils.toString(body.get("subtitle")), ObjectUtils.toString(body.get("text")));
}
String ret = result.get("ret").toString();
if (!GlobDict.send_succ.getKey().equals(result.get("sendStatus"))) {
logger.info("发送失败,重发一次" + result.toString());
sendNum += 1;
if (GlobDict.system_type_android.getKey().equals(app.getSystemType())) {
//安卓
result = UmengUtil.sendAndroidUnicast(app.getAppMasterSecret(), app.getAppKey(), ObjectUtils.toString(body.get("deviceTokens")),
ObjectUtils.toString(body.get("ticker")), ObjectUtils.toString(body.get("title")), ObjectUtils.toString(body.get("text")));
} else if (GlobDict.system_type_ios.getKey().equals(app.getSystemType())) {
//苹果
result = UmengUtil.sendIOSUnicast(app.getAppMasterSecret(), app.getAppKey(), ObjectUtils.toString(body.get("deviceTokens")),
ObjectUtils.toString(body.get("ticker")), ObjectUtils.toString(body.get("title")), ObjectUtils.toString(body.get("text")));
}
}
result.put("sendNum", sendNum);
//修改发送信息表
((UmHH000804) AopContext.currentProxy()).updateMsgStatus(umengs, result);
if (GlobDict.send_unknown.getKey().equals(result.get("sendStatus"))) {
throw new ErrorException("9992", "");
}
if (!GlobDict.send_succ.getKey().equals(result.get("sendStatus"))) {
throw new ErrorException("0067", "");
}
//设置返回信息,将传来的信息原样返回,并加入渠道返回信息
resultMap.putAll(body);
resultMap.putAll(result);
}
/**
* 修改发送状态
*
* @param umengs
* @param result
*/
@Transactional(propagation = Propagation.REQUIRED,
isolation = Isolation.READ_COMMITTED,
rollbackFor = Exception.class)
public void updateMsgStatus(List<Umeng> umengs, Map result) throws ErrorException {
List<MpsReceiveMessageInfo> mpsReceiveMessageInfos = new ArrayList<>();
String ret = ObjectUtils.toString(result.get("ret"));
Map data = result.get("data") == null ? new HashMap() : (Map) result.get("data");
String msgId = ObjectUtils.toString(data.get("msg_id"));
String taskId = ObjectUtils.toString(data.get("task_id"));
String errorCode = ObjectUtils.toString(data.get("error_code"));
for (Umeng umeng : umengs) {
MpsReceiveMessageInfo mpsReceiveMessageInfo = new MpsReceiveMessageInfo();
mpsReceiveMessageInfo.setSerialNo(umeng.getSerialNo());
mpsReceiveMessageInfos.add(mpsReceiveMessageInfo);
}
//修改表结构
Map mrmiParam = new HashMap();
mrmiParam.put("status", result.get("sendStatus"));
mrmiParam.put("sendTime", DateUtil.getCurrentDateTime());
mrmiParam.put("mpsReceiveMessageInfos", mpsReceiveMessageInfos);
int uret = mpsMessageReceiveInfoMapper.updateMessageReceiveInfoBatch(mrmiParam);
if (uret <= 0) {
throw new ErrorException("9997", "");
}
Map umengParam = new HashMap();
umengParam.put("chlRet", ret);
umengParam.put("chlRetData", data.toString());
umengParam.put("chlErrorCode", errorCode);
umengParam.put("sendStatus", result.get("sendStatus"));
umengParam.put("sendNum", ObjectUtils.toString(result.get("sendNum")));
umengParam.put("chlMsgId", msgId);
umengParam.put("taskId", taskId);
umengParam.put("umengs", umengs);
uret = umengDao.updateUmengBatch(umengParam);
if (uret <= 0) {
throw new ErrorException("9997", "");
}
}
/**
* 插入推送信息主表和信息子表
*
* @param body
*/
@Transactional(propagation = Propagation.REQUIRED,
isolation = Isolation.READ_COMMITTED,
rollbackFor = Exception.class)
public List<Umeng> insertMsg(Map<String, Object> body) throws ErrorException {
App app = (App) body.get("app");
List<MpsReceiveMessageInfo> mpsReceiveMessageInfos = new ArrayList<>();
List<Umeng> umengs = new ArrayList<>();
String[] deviceTokens = ObjectUtils.toString(body.get("deviceTokens")).split(",");
for (String deviceToken : deviceTokens) {
String seq = commonService.getSeq("SERIAL_NO", 12);
String serialNo = DateUtil.getCurrentDateTime() + seq;
MpsReceiveMessageInfo mpsReceiveMessageInfo = new MpsReceiveMessageInfo();
mpsReceiveMessageInfo.setSerialNo(serialNo);
mpsReceiveMessageInfo.setType(Constants.PUSH_TYPE_UMENG);
mpsReceiveMessageInfo.setSenderIdentityId(body.get("senderIdentityId").toString());
mpsReceiveMessageInfo.setSenderName(body.get("senderName") == null ? "" : body.get("senderName").toString());
mpsReceiveMessageInfo.setSenderSystem(body.get("senderSystem").toString());
mpsReceiveMessageInfo.setReceiverIdentityId(deviceToken);
mpsReceiveMessageInfo.setTitle(ObjectUtils.toString(body.get("title")));
mpsReceiveMessageInfo.setContent(ObjectUtils.toString(body.get("text")));
mpsReceiveMessageInfo.setRequestNo(body.get("requestNo").toString());
//状态初始化成功
mpsReceiveMessageInfo.setStatus(GlobDict.send_init.getKey());
Umeng umeng = new Umeng();
umeng.setSerialNo(serialNo);
umeng.setAppCode(ObjectUtils.toString(body.get("appCode")));
umeng.setTicker(ObjectUtils.toString(body.get("ticker")));
umeng.setSubtitle(ObjectUtils.toString(body.get("subtitle")));
umeng.setTitle(ObjectUtils.toString(body.get("title")));
umeng.setText(ObjectUtils.toString(body.get("text")));
umeng.setDeviceToken(deviceToken);
umeng.setSendStatus(GlobDict.send_init.getKey());
umeng.setTimelyNews(GlobDict.timely_news.getKey());
umeng.setSystemType(app.getSystemType());
mpsReceiveMessageInfos.add(mpsReceiveMessageInfo);
umengs.add(umeng);
}
//批量插入数据库
int ret = mpsMessageReceiveInfoMapper.insertMessageReceiveInfoBatch(mpsReceiveMessageInfos);
if (ret <= 0) {
throw new ErrorException("9997", "");
}
ret = umengDao.insertUmengBatch(umengs);
if (ret <= 0) {
throw new ErrorException("9997", "");
}
return umengs;
}
}
|
/*
* 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 Unit05;
/**
*
* @author CongThanh
*/
public class Dog extends Animal {
@Override
public void run() {
System.out.println("Di chuyen bang 4 chan.");
}
public void eat() {
System.out.println("Gam xuong");
}
}
|
package com.kps.dsk;
/**
* An enumeration describing DirectShow video renderer filters.
*
* @author KPS
*/
public enum DSVideoRendererType {
/**
* Video Mixing Renderer 7. Uses DirectDraw 7. Requires Windows XP or later.
*/
VMR7,
/**
* Video Mixing Renderer 9. Uses Direct3D 9. Requires Windows XP or later.
*/
VMR9,
/**
* Enhanced Video Renderer. Uses Direct3D 9. Requires Windows Vista or later.
*/
EVR
}
|
package War;
public class Card {
private int value;
private String name;
private String rank;
private String suit;
// public static String[] suits = {
// "Clubs", "Diamonds", "Hearts", "Spades"};
public Card(int val, String suitVal) {
this.value = val;
this.suit = suitVal;
this.name = this.findRank(value) + " of " + this.suit;
}
public void describe() {
System.out.println(name);
}
private String findRank(int value) {
if (value == 2) {
rank = "Two";
} else if (value== 3) {
rank = "Three";
} else if (value == 4) {
rank = "Four";
} else if (value == 5) {
rank = "Five";
} else if (value == 6) {
rank = "Six";
} else if (value == 7) {
rank = "Seven";
} else if (value == 8) {
rank = "Eight";
} else if (value == 9) {
rank = "Nine";
} else if (value == 10) {
rank = "Ten";
} else if (value == 11) {
rank = "Jack";
} else if (value == 12) {
rank = "Queen";
} else if (value == 13) {
rank = "King";
} else if (value == 14) {
rank = "Ace";
}
return rank;
}
public int getValue() {
return this.value;
}
public void setValue(int value) {
this.value = value;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getRank() {
return this.rank;
}
public void setRank(String rank) {
this.rank = rank;
}
}
|
package com.example.choupisport;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class ExercicesTableDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "exercicestable.db";
private static final int DATABASE_VERSION = 1;
public ExercicesTableDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Méthode appelée pendant la création de la base de données
@Override
public void onCreate(SQLiteDatabase database) {
ExercicesTable.onCreate(database);
ExercicesTable.init(database);
}
// Méthode appelée pendant une mise a jour de la base de
// données, par exemple vous augmentez sa version
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
ExercicesTable.onUpgrade(database, oldVersion, newVersion);
}
}
|
package com.rsm.yuri.projecttaxilivredriver.historictravelslist;
import com.rsm.yuri.projecttaxilivredriver.historictravelslist.events.HistoricTravelListEvent;
import com.rsm.yuri.projecttaxilivredriver.main.entities.Travel;
public interface HistoricTravelsListPresenter {
void onPause();
void onResume();
void onCreate();
void onDestroy();
void onEventMainThread(HistoricTravelListEvent event);
void getUrlPhotoMapFromTravel(Travel travel);
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.common.predicate;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import de.hybris.bootstrap.annotations.UnitTest;
import org.junit.Test;
@UnitTest
public class ValidIntegerPredicateTest
{
private final ValidIntegerPredicate predicate = new ValidIntegerPredicate();
@Test
public void nonNumbersWillFail()
{
final boolean result = predicate.test("sdfgsdfgs");
assertThat("sdfgsdfgs is not an Integer", result, equalTo(false));
}
@Test
public void nonIntegerWillFail()
{
final boolean result = predicate.test("123.45");
assertThat("123.45 is not an Integer", result, equalTo(false));
}
@Test
public void integersWillPass()
{
final boolean result = predicate.test("-34");
assertThat("-34 is an Integer", result, equalTo(true));
}
@Test
public void integersWillFailIfLessThanMin()
{
predicate.setMin(10);
final boolean result = predicate.test("9");
assertThat("9 is lower than minimum 10", result, equalTo(false));
}
@Test
public void integersWillFailIfGreaterThanMax()
{
predicate.setMax(10);
final boolean result = predicate.test("19");
assertThat("19 is greater than maximum 10", result, equalTo(false));
}
@Test
public void integersWillPassWhenWithinBoundaries()
{
predicate.setMin(5);
predicate.setMax(10);
final boolean result = predicate.test("7");
assertThat("7 is within 5-10 range", result, equalTo(true));
}
}
|
package Rac;
import javax.swing.JFrame;
public class TestBoxLayout {
public static void main(String[] args) {
JFrame frame = new JFrame("toan");
Sim sim = new Sim();
Display t = new Display();
new Thread(sim).start();
frame.add(t);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
}
|
package com.SkyBlue.base.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import com.SkyBlue.base.serviceFacade.BaseServiceFacade;
import com.SkyBlue.base.to.AuthorityBean;
import com.SkyBlue.base.to.AuthorityInfoBean;
import com.SkyBlue.base.to.MenuAuthorityBean;
import com.SkyBlue.common.mapper.DatasetBeanMapper;
import com.tobesoft.xplatform.data.PlatformData;
@Controller
public class AuthorityController{
@Autowired
private BaseServiceFacade baseServiceFacade;
@Autowired
private DatasetBeanMapper datasetBeanMapper;
/* 권한에따른 menu목록을 가져오는 메서드 */
@RequestMapping("/base/findMenuAuthorityList.do")
public void findMenuAuthorityList(@RequestAttribute("inData") PlatformData inData,
@RequestAttribute("outData") PlatformData outData) throws Exception {
String authorityCode = inData.getVariable("authorityCode").getString();
//입력한 변수를 얻어와서 String으로 변경 하는 듯?
List<MenuAuthorityBean> menuAuthorityList = baseServiceFacade.findMenuAuthorityList(authorityCode);
datasetBeanMapper.beansToDataset(outData, menuAuthorityList, MenuAuthorityBean.class);
}
/* 권한목록을 가져오는 메서드 */
@RequestMapping("/base/findAuthorityList.do")
public void findAuthorityList(@RequestAttribute("inData") PlatformData inData,
@RequestAttribute("outData") PlatformData outData) throws Exception {
List<AuthorityBean> authorityList = baseServiceFacade.findAuthorityList();
datasetBeanMapper.beansToDataset(outData, authorityList, AuthorityBean.class);
}
/* 모든 메뉴를 다가져오는 메서드 */
@RequestMapping("/base/findMenuAuthorityListAll.do")
public void findMenuAuthorityListAll(@RequestAttribute("inData") PlatformData inData,
@RequestAttribute("outData") PlatformData outData) throws Exception {
List<MenuAuthorityBean> menuAuthorityList = baseServiceFacade.findMenuAuthorityListAll();
datasetBeanMapper.beansToDataset(outData, menuAuthorityList, MenuAuthorityBean.class);
}
/* 메뉴권한관련해서 일괄처리하는 메서드 */
@RequestMapping("/base/batchAuthority.do")
public void batchAuthority(@RequestAttribute("inData") PlatformData inData,
@RequestAttribute("outData") PlatformData outData) throws Exception {
//System.out.println(inData);
//권한은 변동을 하지 않아도 실행이 된다.
AuthorityInfoBean authorityInfoBean=new AuthorityInfoBean();
//authorityInfoBean.setAuthorityList(datasetBeanMapper.datasetToBeans(inData, AuthorityBean.class));
authorityInfoBean.setMenuAuthorityList(datasetBeanMapper.datasetToBeans(inData, MenuAuthorityBean.class));
baseServiceFacade.batchAuthority(authorityInfoBean);
//findAuthorityList(inData,outData);
findMenuAuthorityListAll(inData,outData);
}
}
|
package com.telyo.trainassistant.ui;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.anye.greendao.gen.WeatherTodayDao;
import com.telyo.trainassistant.Helper.WeatherDaoHelper;
import com.telyo.trainassistant.R;
import com.telyo.trainassistant.adapter.RecyclerDialogShearViewAdapter;
import com.telyo.trainassistant.entity.WeatherFuture;
import com.telyo.trainassistant.entity.WeatherToday;
import com.telyo.trainassistant.utils.StaticUtils;
import com.telyo.trainassistant.views.MyDialogView;
import com.telyo.trainassistant.views.MyLayoutWeatherView;
import com.telyo.trainassistant.views.WeatherView;
import java.util.List;
import static com.telyo.trainassistant.utils.StaticUtils.initWeatherImage;
/**
* Created by Administrator on 2017/7/3.
*/
public class WeatherActivity extends BaseNoTitileBarActivity implements View.OnClickListener {
public WeatherView weatherV_title;
private TextView tv_today;
private TextView tv_temperature;
private TextView tv_uit_light;
private TextView tv_weather;
private TextView tv_advise;
private MyLayoutWeatherView weather_1;
private MyLayoutWeatherView weather_2;
private MyLayoutWeatherView weather_3;
private MyLayoutWeatherView weather_4;
private MyLayoutWeatherView weather_5;
private WeatherToday mWeatherToday;
private List<WeatherFuture> mWeatherFutures;
private ImageView img_close;
private ImageView img_menu;
private LinearLayout ll_weather;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
initData();
initView();
setView();
}
private void initData() {
WeatherDaoHelper weatherDaoHelper = new WeatherDaoHelper();
mWeatherToday = weatherDaoHelper.getWeatherToday();
mWeatherFutures = weatherDaoHelper.getFutureWeathers();
}
private void initView() {
weatherV_title = (WeatherView) findViewById(R.id.weatherV_title);
tv_today = (TextView) findViewById(R.id.tv_today);
tv_temperature = (TextView) findViewById(R.id.tv_temperature);
tv_uit_light = (TextView) findViewById(R.id.tv_uit_light);
tv_weather = (TextView) findViewById(R.id.tv_weather);
tv_advise = (TextView) findViewById(R.id.tv_advise);
weather_1 = (MyLayoutWeatherView) findViewById(R.id.weather_1);
weather_2 = (MyLayoutWeatherView) findViewById(R.id.weather_2);
weather_3 = (MyLayoutWeatherView) findViewById(R.id.weather_3);
weather_4 = (MyLayoutWeatherView) findViewById(R.id.weather_4);
weather_5 = (MyLayoutWeatherView) findViewById(R.id.weather_5);
img_close = (ImageView) findViewById(R.id.img_close);
ll_weather = (LinearLayout) findViewById(R.id.ll_weather);
img_menu = (ImageView) findViewById(R.id.img_menu);
img_menu.setOnClickListener(this);
img_close.setOnClickListener(this);
}
private void setView() {
if (mWeatherToday != null && !mWeatherToday.getDate_y().isEmpty()) {
weatherV_title.setCityText(mWeatherToday.getCity());
weatherV_title.setTemperatureText(mWeatherToday.getTemperature());
weatherV_title.setWeatherText(mWeatherToday.getWeather());
String weatherIndex = StaticUtils.getWeatherIndex(mWeatherToday.getWeather(), "转");
weatherV_title.setWeatherImageView(initWeatherImage(weatherIndex));
tv_today.setText(mWeatherToday.getWeek() + " 今天");
tv_temperature.setText(mWeatherToday.getTemperature());
tv_uit_light.setText("紫外线: "+mWeatherToday.getUv_index());
tv_weather.setText(mWeatherToday.getDressing_index());
tv_advise.setText(mWeatherToday.getDressing_advice());
ll_weather.setBackgroundResource(initBackground(StaticUtils.getWeatherIndex(mWeatherToday.getWeather(), "转")));
}else {
ll_weather.setBackgroundResource(R.drawable.icon_bg_fine_night);
}
if (mWeatherFutures != null && mWeatherFutures.size() > 0){
weather_1.setTemperatureText(mWeatherFutures.get(1).getTemperature());
weather_1.setWeekText(mWeatherFutures.get(1).getWeek());
String weatherIndex_1 = StaticUtils.getWeatherIndex(mWeatherFutures.get(1).getWeather(), "转");
weather_1.setmImg_weatherRes(initWeatherImage(weatherIndex_1));
weather_2.setTemperatureText(mWeatherFutures.get(2).getTemperature());
weather_2.setWeekText(mWeatherFutures.get(2).getWeek());
String weatherIndex_2 = StaticUtils.getWeatherIndex(mWeatherFutures.get(2).getWeather(), "转");
weather_2.setmImg_weatherRes(initWeatherImage(weatherIndex_2));
weather_3.setTemperatureText(mWeatherFutures.get(3).getTemperature());
weather_3.setWeekText(mWeatherFutures.get(3).getWeek());
String weatherIndex_3 = StaticUtils.getWeatherIndex(mWeatherFutures.get(3).getWeather(), "转");
weather_3.setmImg_weatherRes(initWeatherImage(weatherIndex_3));
weather_4.setTemperatureText(mWeatherFutures.get(4).getTemperature());
weather_4.setWeekText(mWeatherFutures.get(4).getWeek());
String weatherIndex_4 = StaticUtils.getWeatherIndex(mWeatherFutures.get(4).getWeather(), "转");
weather_4.setmImg_weatherRes(initWeatherImage(weatherIndex_4));
weather_5.setTemperatureText(mWeatherFutures.get(5).getTemperature());
weather_5.setWeekText(mWeatherFutures.get(5).getWeek());
String weatherIndex_5 = StaticUtils.getWeatherIndex(mWeatherFutures.get(5).getWeather(), "转");
weather_5.setmImg_weatherRes(initWeatherImage(weatherIndex_5));
/*weather_6.setTemperatureText(mWeatherFutures.get(6).getTemperature());
weather_6.setWeekText(mWeatherFutures.get(6).getWeek());
String weatherIndex_6 = StaticUtils.getWeatherIndex(mWeatherFutures.get(6).getWeather(), "转");
weather_6.setmImg_weatherRes(initWeatherImage(weatherIndex_6));*/
}
}
private int initBackground(String weatherIndex) {
if (weatherIndex != null && weatherIndex.equals("00")){
return R.drawable.icon_bg_fine_day;
}else if (weatherIndex != null && (weatherIndex.equals("13")||
weatherIndex.equals("14")||
weatherIndex.equals("15")||
weatherIndex.equals("16")||
weatherIndex.equals("24")||
weatherIndex.equals("26")||
weatherIndex.equals("27")||
weatherIndex.equals("28")||
weatherIndex.equals("17")||
weatherIndex.equals("19"))){
return R.drawable.icon_bg_snow_day;
}else if (weatherIndex != null && (weatherIndex.equals("02")||
weatherIndex.equals("03")||
weatherIndex.equals("04")||
weatherIndex.equals("05")||
weatherIndex.equals("06")||
weatherIndex.equals("07")||
weatherIndex.equals("08")||
weatherIndex.equals("09")||
weatherIndex.equals("10")||
weatherIndex.equals("21")||
weatherIndex.equals("22")||
weatherIndex.equals("23")||
weatherIndex.equals("24")||
weatherIndex.equals("25")||
weatherIndex.equals("11")||
weatherIndex.equals("12"))){
return R.drawable.icon_bg_rain;
}else {
return R.drawable.icon_bg_over_cast;
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.img_menu:
showShearDialog();
break;
case R.id.img_close:
finish();
break;
}
}
private void showShearDialog() {
final MyDialogView myDialogView= new MyDialogView(this,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT,
R.layout.dialog_shear,R.style.Theme_dialog, Gravity.BOTTOM);
RecyclerView rv_dialog_shear = (RecyclerView) myDialogView.findViewById(R.id.rv_dialog_shear);
GridLayoutManager manager = new GridLayoutManager(this,5);
rv_dialog_shear.setLayoutManager(manager);
rv_dialog_shear.setAdapter(new RecyclerDialogShearViewAdapter(this));
Button btn_cancel = (Button) myDialogView.findViewById(R.id.btn_cancel);
myDialogView.show();
btn_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myDialogView.dismiss();
}
});
}
}
|
package exceptions;
// Referenced classes of package exceptions:
// SemanticException
public class ProcedureNameMismatchedException extends SemanticException
{
public ProcedureNameMismatchedException()
{
this("Procedure Name Mismatched Exception.");
}
public ProcedureNameMismatchedException(String s)
{
super(s);
}
} |
/*
* 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 selenium_test;
import org.openqa.selenium.chrome.ChromeDriver;
/**
*
* @author Kelly
*/
public class FriendsOfFriendsThread extends Thread{
private final ChromeDriver driver;
private final int min;
private final int max;
public FriendsOfFriendsThread(ChromeDriver driver, int min, int max){
this.driver = driver;
this.min = min;
this.max = max;
}
@Override
public void run() {
Selenium_Test.getFriendsOfFirends(Selenium_Test.friendsURL, min, max, driver);
}
}
|
package com.zhowin.miyou.mine.model;
import java.util.List;
/**
* 商城商品列表
*/
public class ShopMallPropsList {
/**
* id : 2
* name : 兔耳朵
* type : 1
* pictureKey : http://qfah2px93.hn-bkt.clouddn.com/image.backgroundPicture.default.default.jpg
* enable : 1
* sort : 1
* createTime : 1599362578000
* goodsTimes : [{"id":"dfasdf34t","goodsId":2,"timeType":0,"price":38,"bidPrice":35,"sort":1,"createTime":1599362949000,"goods":null}]
*/
private int id;
private String name;
private int type;
private String heightPicture;
private String greyPicture;
private int enable;
private int sort;
private long createTime;
private List<GoodsTimesBean> goodsTimes;
private boolean isSelect;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getHeightPicture() {
return heightPicture;
}
public void setHeightPicture(String heightPicture) {
this.heightPicture = heightPicture;
}
public String getGreyPicture() {
return greyPicture;
}
public void setGreyPicture(String greyPicture) {
this.greyPicture = greyPicture;
}
public int getEnable() {
return enable;
}
public void setEnable(int enable) {
this.enable = enable;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public List<GoodsTimesBean> getGoodsTimes() {
return goodsTimes;
}
public void setGoodsTimes(List<GoodsTimesBean> goodsTimes) {
this.goodsTimes = goodsTimes;
}
public boolean isSelect() {
return isSelect;
}
public void setSelect(boolean select) {
isSelect = select;
}
public static class GoodsTimesBean {
/**
* id : dfasdf34t
* goodsId : 2
* timeType : 0 物品期限 0:七天、1:一个月、2:三个月、3:一年、4:无限期
* price : 38
* bidPrice : 35
* sort : 1
* createTime : 1599362949000
* goods : null
*/
private String id;
private int goodsId;
private int timeType;
private int price;
private int bidPrice;
private int sort;
private long createTime;
private Object goods;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getGoodsId() {
return goodsId;
}
public void setGoodsId(int goodsId) {
this.goodsId = goodsId;
}
public int getTimeType() {
return timeType;
}
public void setTimeType(int timeType) {
this.timeType = timeType;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getBidPrice() {
return bidPrice;
}
public void setBidPrice(int bidPrice) {
this.bidPrice = bidPrice;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public Object getGoods() {
return goods;
}
public void setGoods(Object goods) {
this.goods = goods;
}
}
}
|
package kr.ko.nexmain.server.MissingU.common.mail;
import java.util.Locale;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import kr.ko.nexmain.server.MissingU.common.Constants;
import kr.ko.nexmain.server.MissingU.common.model.MailSendParam;
import kr.ko.nexmain.server.MissingU.common.utils.MsgUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MuMailNotifier implements MailNotifier {
protected static Logger log = LoggerFactory.getLogger(MuMailNotifier.class);
private JavaMailSender mailSender;
private MsgUtil msgUtil;
@Value("#{config['missingu.server.baseUrl']}")
private String MISSINGU_SERVER_BASEURL;
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void setMsgUtil(MsgUtil msgUtil) {
this.msgUtil = msgUtil;
}
@Override
public void sendEmail(MailSendParam param) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper messageHelper = new MimeMessageHelper(message,
true, "utf-8");
String emailtype = param.getEmailType();
Locale gLocale = new Locale(param.getLang());
//메일 제목설정
if(Constants.emailType.MEMBERSHIP_JOIN_CONFIRM.equals(emailtype)) {
messageHelper.setSubject(msgUtil.getPropMsg("mail.membership.title", gLocale));
} else if(Constants.emailType.TEMP_PASSWORD.equals(emailtype)) {
messageHelper.setSubject(msgUtil.getPropMsg("mail.pass.title", gLocale));
} else {
log.info("Unknown emailType");
return;
}
//메일 내용설정
String htmlContent = "";
if(emailtype == null || StringUtils.isEmpty(emailtype)) {
log.info("EmailType is null!");
return;
} else {
htmlContent = getMailContent(param);
}
messageHelper.setText(htmlContent, true);
messageHelper.setFrom("applus2013@gmail.com", "MissingU");
messageHelper.setTo(new InternetAddress(param.getLoginId(), param.getName(), "utf-8"));
//messageHelper.addInline("missinguTitleImg", new FileDataSource("/opt/lampp/tomcat60/files/img/missing_u.png"));
} catch (Throwable e) {
e.printStackTrace();
return;
}
try {
mailSender.send(message);
} catch (MailException e) {
e.printStackTrace();
}
}
/**
* 요청 emailType 에 따라 emailContent 리턴
* @param param
* @return
*/
public String getMailContent(MailSendParam param) {
StringBuilder sbHtmlContent = new StringBuilder();
String emailtype = param.getEmailType();
Locale gLocale = new Locale(param.getLang());
String OPENING_PART1 = msgUtil.getPropMsg("mail.membership.opening.01", gLocale);
String OPENING_PART2 = msgUtil.getPropMsg("mail.membership.opening.02", gLocale);
String CLOSING_PART1 = msgUtil.getPropMsg("mail.membership.closing.01", gLocale);
String CLOSING_PART2 = msgUtil.getPropMsg("mail.membership.closing.02", gLocale);
String REVIEW_BTN_TITLE = msgUtil.getPropMsg("mail.membership.review.btn.title", gLocale);
String REVIEW_BTN_TEXT = msgUtil.getPropMsg("mail.membership.review.btn.text", gLocale);
String FOOTER_TEXT_01 = msgUtil.getPropMsg("mail.footer.01", gLocale);
String FOOTER_TEXT_02 = msgUtil.getPropMsg("mail.footer.02", gLocale);
String REPLY_MAIL_ADDR = "appplus2013@gmail.com"; //회신 주소
if(Constants.emailType.MEMBERSHIP_JOIN_CONFIRM.equals(emailtype)) {
String MEMBERSHIP_GREETING = msgUtil.getPropMsg("mail.membership.greeting", gLocale);
String MEMBERSHIP_TEXT1_01 = msgUtil.getPropMsg("mail.membership.text1.01", gLocale);
String MEMBERSHIP_TEXT1_02 = msgUtil.getPropMsg("mail.membership.text1.02", gLocale);
String MEMBERSHIP_TEXT1_03 = msgUtil.getPropMsg("mail.membership.text1.03", gLocale);
String MEMBERSHIP_TEXT2_01 = null;
if("ko".equalsIgnoreCase(param.getLang())) {
MEMBERSHIP_TEXT2_01 = msgUtil.getPropMsg("mail.membership.text2.01", gLocale);
}
StringBuilder sbURI = new StringBuilder();
sbURI.append(MISSINGU_SERVER_BASEURL);
sbURI.append("/missingu/common/memberJoinCert.html");
sbURI.append("?gMemberId=").append(param.getMemberId());
sbURI.append("&gLang=").append(param.getLang());
String memberJoinCertReqURI = sbURI.toString();
/** 회원가입 완료 메일 */
sbHtmlContent.append("<img src='http://missingu.co.kr/img/mail/missing_u.png' alt='MissingU' style='background:#f0f0f0; width:112px; height:32px'/>");
sbHtmlContent.append("<hr /> \n");
sbHtmlContent.append("<table border='0' cellpadding='0' cellspacing='0' width='600' align='center'> \n");
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td style='width: 120px;'><img src='http://missingu.co.kr/img/mail/missing_u_logo.png' alt='MissingU' style='background:#f0f0f0; width:76px; height:76px'/></td> \n");
sbHtmlContent.append(" <td> \n");
sbHtmlContent.append(" <h3 style='font-size: 18px; margin: 0; padding: 0;'> \n");
sbHtmlContent.append(" ").append(OPENING_PART1).append(" <br />").append(OPENING_PART2).append(" \n");
sbHtmlContent.append(" </h3> \n");
sbHtmlContent.append(" </td> \n");
sbHtmlContent.append(" </tr> \n");
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td> </td> \n");
sbHtmlContent.append(" <td> </td> \n");
sbHtmlContent.append(" </tr> \n");
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td style='width: 120px;'> </td> \n");
sbHtmlContent.append(" <td> \n");
sbHtmlContent.append(" <h1 style='font-size: 50px; margin: 0; padding: 0;'>Thank You!</h1> \n");
sbHtmlContent.append(" <h3 style='font-size: 18px; margin: 0; padding: 0;'>").append(MEMBERSHIP_GREETING).append("</h3> \n");
sbHtmlContent.append(" </td> \n");
sbHtmlContent.append(" </tr> \n");
sbHtmlContent.append("</table> \n");
sbHtmlContent.append(" \n");
sbHtmlContent.append("<table border='0' cellpadding='0' cellspacing='0' width='600' align='center'> \n");
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td style='height: 50px;'> </td> \n");
sbHtmlContent.append(" <td> </td> \n");
sbHtmlContent.append(" <td style='width: 190px; height: 50px;'> </td> \n");
sbHtmlContent.append(" </tr> \n");
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td style='width: 30px;'> </td> \n");
sbHtmlContent.append(" <td colspan='2'>").append(MEMBERSHIP_TEXT1_01).append(" <span style='color: #5297d8;'><strong>").append(param.getLoginId()).append("</strong></span> \n");
sbHtmlContent.append(" ").append(MEMBERSHIP_TEXT1_02).append(" \n");
sbHtmlContent.append(" <a href='").append(memberJoinCertReqURI).append("' style='color:blue; text-decoration: underline;'><strong><Click Here!></strong></a> <span style='color:red'>").append(MEMBERSHIP_TEXT1_03).append("</span> \n");
sbHtmlContent.append(" </td> \n");
sbHtmlContent.append(" </tr> \n");
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td style='width: 30px; height: 10px;'> </td> \n");
sbHtmlContent.append(" <td> </td> \n");
sbHtmlContent.append(" <td style='width: 190px; '> </td> \n");
sbHtmlContent.append(" </tr> \n");
if("ko".equalsIgnoreCase(param.getLang())) {
//한국어인 경우만 출력하는 부분
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td style='width: 30px;'> </td> \n");
sbHtmlContent.append(" <td colspan='2'><h4>").append(MEMBERSHIP_TEXT2_01).append("</h4></td> \n");
sbHtmlContent.append(" </tr> \n");
}
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td style='width: 30px; height: 10px;'> </td> \n");
sbHtmlContent.append(" <td> </td> \n");
sbHtmlContent.append(" <td style='width: 190px; '> </td> \n");
sbHtmlContent.append(" </tr> \n");
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td style='width: 30px;'> </td> \n");
sbHtmlContent.append(" <td>").append(CLOSING_PART1).append("<br />").append(CLOSING_PART2).append("</td> \n");
sbHtmlContent.append(" <td style='width: 190px;'> \n");
sbHtmlContent.append(" <button style='border-radius:5px; text-align:left; padding:8px 12px; color:#293029; border:solid 1px #9c9694; background-image: linear-gradient(bottom, rgb(156,166,165) 0%, rgb(206,199,198) 100%); background-image: -o-linear-gradient(bottom, rgb(156,166,165) 0%, rgb(206,199,198) 100%); background-image: -moz-linear-gradient(bottom, rgb(156,166,165) 0%, rgb(206,199,198) 100%); background-image: -webkit-linear-gradient(bottom, rgb(156,166,165) 0%, rgb(206,199,198) 100%); background-image: -ms-linear-gradient(bottom, rgb(156,166,165) 0%, rgb(206,199,198) 100%); background-image: -webkit-gradient( linear, left bottom, left top, color-stop(0, rgb(156,166,165)), color-stop(1, rgb(206,199,198)));'> \n");
sbHtmlContent.append(" <p style='margin:0; padding:0;'><img src='http://missingu.co.kr/img/mail/phone_icon.png' align='left' style='padding:0 10px 0 0; width:18px; height:29px'/> ").append(REVIEW_BTN_TITLE).append(" <br /><span style='font-size:11px;color:#555;'>").append(REVIEW_BTN_TEXT).append("</span></p> \n");
sbHtmlContent.append(" </button></td> \n");
sbHtmlContent.append(" </tr> \n");
sbHtmlContent.append("</table> \n");
sbHtmlContent.append(" \n");
sbHtmlContent.append("<hr /> \n");
sbHtmlContent.append("<p>").append(FOOTER_TEXT_01).append(" <a href='mailto:").append(REPLY_MAIL_ADDR).append("'>").append(REPLY_MAIL_ADDR).append("</a> ").append(FOOTER_TEXT_02).append(" ⓒ2013 App+</p> \n");
} else if(Constants.emailType.TEMP_PASSWORD.equals(emailtype)) {
String PASS_GREETING = msgUtil.getPropMsg("mail.pass.greeting", gLocale);
String PASS_TEXT1_01 = msgUtil.getPropMsg("mail.pass.text1.01", gLocale);
String PASS_TEXT1_02 = msgUtil.getPropMsg("mail.pass.text1.02", gLocale);
String PASS_TEXT1_03 = msgUtil.getPropMsg("mail.pass.text1.03", gLocale);
String PASS_TEXT2_01 = msgUtil.getPropMsg("mail.pass.text2.01", gLocale);
String PASS_TEXT2_02 = msgUtil.getPropMsg("mail.pass.text2.02", gLocale);
/** 임시 패스워드 발급 메일 */
sbHtmlContent.append("<img src='http://missingu.co.kr/img/mail/missing_u.png' alt='MissingU' style='background:#f0f0f0; width:112px; height:32px'/>");
sbHtmlContent.append("<hr /> \n");
sbHtmlContent.append("<table border='0' cellpadding='0' cellspacing='0' width='600' align='center'> \n");
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td style='width: 120px;'><img src='http://missingu.co.kr/img/mail/missing_u_logo.png' alt='MissingU' style='background:#f0f0f0; width:76px; height:76px'/></td> \n");
sbHtmlContent.append(" <td> \n");
sbHtmlContent.append(" <h3 style='font-size: 18px; margin: 0; padding: 0;'> \n");
sbHtmlContent.append(" ").append(OPENING_PART1).append(" <br />").append(OPENING_PART2).append(" \n");
sbHtmlContent.append(" </h3> \n");
sbHtmlContent.append(" </td> \n");
sbHtmlContent.append(" </tr> \n");
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td> </td> \n");
sbHtmlContent.append(" <td> </td> \n");
sbHtmlContent.append(" </tr> \n");
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td style='width: 120px;'> </td> \n");
sbHtmlContent.append(" <td> \n");
sbHtmlContent.append(" <h3 style='font-size: 18px; margin: 0; padding: 0;'>").append(PASS_GREETING).append("</h3> \n");
sbHtmlContent.append(" </td> \n");
sbHtmlContent.append(" </tr> \n");
sbHtmlContent.append("</table> \n");
sbHtmlContent.append(" \n");
sbHtmlContent.append("<table border='0' cellpadding='0' cellspacing='0' width='600' align='center'> \n");
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td style='height: 20px;'> </td> \n");
sbHtmlContent.append(" <td> </td> \n");
sbHtmlContent.append(" <td style='width: 190px; height: 20px;'> </td> \n");
sbHtmlContent.append(" </tr> \n");
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td style='width: 30px;'> </td> \n");
sbHtmlContent.append(" <td colspan='2'> \n");
sbHtmlContent.append(" <p> <span style='color: #5297d8;'><strong>").append(param.getName()).append("</strong></span>").append(PASS_TEXT1_01).append("<br />").append(PASS_TEXT1_02).append(" <span style='color: #5297d8;'><strong>").append(param.getLoginPw()).append("</strong></span>").append(PASS_TEXT1_03).append("</p> \n");
sbHtmlContent.append(" \n");
sbHtmlContent.append(" <p> \n");
sbHtmlContent.append(" ").append(PASS_TEXT2_01).append("<br /> \n");
sbHtmlContent.append(" ").append(PASS_TEXT2_02).append(" \n");
sbHtmlContent.append(" </p> \n");
sbHtmlContent.append(" </td> \n");
sbHtmlContent.append(" </tr> \n");
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td style='width: 30px; height: 10px;'> </td> \n");
sbHtmlContent.append(" <td> </td> \n");
sbHtmlContent.append(" <td style='width: 190px; '> </td> \n");
sbHtmlContent.append(" </tr> \n");
sbHtmlContent.append(" <tr> \n");
sbHtmlContent.append(" <td style='width: 30px;'> </td> \n");
sbHtmlContent.append(" <td>").append(CLOSING_PART1).append("<br />").append(CLOSING_PART2).append("</td> \n");
sbHtmlContent.append(" <td style='width: 190px;'> \n");
sbHtmlContent.append(" <button style='border-radius:5px; text-align:left; padding:8px 12px; color:#293029; border:solid 1px #9c9694; background-image: linear-gradient(bottom, rgb(156,166,165) 0%, rgb(206,199,198) 100%); background-image: -o-linear-gradient(bottom, rgb(156,166,165) 0%, rgb(206,199,198) 100%); background-image: -moz-linear-gradient(bottom, rgb(156,166,165) 0%, rgb(206,199,198) 100%); background-image: -webkit-linear-gradient(bottom, rgb(156,166,165) 0%, rgb(206,199,198) 100%); background-image: -ms-linear-gradient(bottom, rgb(156,166,165) 0%, rgb(206,199,198) 100%); background-image: -webkit-gradient( linear, left bottom, left top, color-stop(0, rgb(156,166,165)), color-stop(1, rgb(206,199,198)));'> \n");
sbHtmlContent.append(" <p style='margin:0; padding:0;'><img src='http://missingu.co.kr/img/mail/phone_icon.png' align='left' style='padding:0 10px 0 0; width:18px; height:29px'/> ").append(REVIEW_BTN_TITLE).append(" <br /><span style='font-size:11px;color:#555;'>").append(REVIEW_BTN_TEXT).append("</span></p> \n");
sbHtmlContent.append(" </button></td> \n");
sbHtmlContent.append(" </tr> \n");
sbHtmlContent.append("</table> \n");
sbHtmlContent.append(" \n");
sbHtmlContent.append("<hr /> \n");
sbHtmlContent.append("<p>").append(FOOTER_TEXT_01).append(" <a href='mailto:").append(REPLY_MAIL_ADDR).append("'>").append(REPLY_MAIL_ADDR).append("</a> ").append(FOOTER_TEXT_02).append(" ⓒ2013 App+</p> \n");
} else {
log.info("Unknown emailType!");
}
return sbHtmlContent.toString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.