text
stringlengths 10
2.72M
|
|---|
package com.javatechie.jenkin.api;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SpringJenkinsApplication {
public static Logger l=LoggerFactory.getLogger(SpringJenkinsApplication.class);
@GetMapping("/ping")
public String message() {
return "Wao!! Application Deployed successfully in SAP Cloud..";
}
@PostConstruct
public void init() {
l.info("Application started");
l.info("Inside Init method, checking auto build process");
}
public static void main(String[] args) {
l.info("Inside Main method");
SpringApplication.run(SpringJenkinsApplication.class, args);
}
}
|
package com.test;
public class event02 implements Event {
public event02() { }
@Override
public void action() {
System.out.println("엔터입력 !");
}
}
|
package com.example.homework2;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.app.Activity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
public class ListFragment extends Fragment implements View.OnClickListener{
RecyclerView listV;
Button controlB;
private OnFragmentInteractionListener lListener;
public ListFragment(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
listV = (RecyclerView) view.findViewById(R.id.lapList);
controlB = (Button) view.findViewById(R.id.ctrlBtn);
controlB.setOnClickListener(this);
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof OnFragmentInteractionListener){
this.lListener = (OnFragmentInteractionListener) context;
}
else{
throw new RuntimeException("Implement OnFragmentInteractionListener");
}
}
public void onDetach(){
super.onDetach();
}
public void onClick(View view){
if(view.getId() == R.id.ctrlBtn){
lListener.onButtonClicked(0);
}
}
public interface OnFragmentInteractionListener{
void onButtonClicked(int id);
}
}
|
package solve;
import structure.ComparablePair;
import evaluators.Differentiator;
import evaluators.Evaluator;
import evaluators.ExpressionEvaluator;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import static solve.DoubleUtil.fuzzyEqual;
import static solve.DoubleUtil.isEqual;
/**
* Created by Matthew on 11/6/2017.
*/
public class CrossValue {
public static final double EPSILON = 2.22e-16d;
private ExpressionEvaluator expression;
private double value;
/**
* finds all values such f(x)=value
* @param fx
* @param lowerBound
* @param upperBound
* @param value
* @return
*/
public static Set<Double> equalXes(Evaluator fx, double lowerBound, double upperBound, double value) {
HashSet<Double> equalLocation = new HashSet<>();
equalLocation.addAll(crossXes(fx, lowerBound, upperBound, value));
Differentiator dfxdx = new Differentiator(fx);
Set<Double> potenialTangents = crossXes(dfxdx, lowerBound, upperBound, 0);
for(double potenialTangent : potenialTangents) {
if(fuzzyEqual(fx.eval(potenialTangent), value)) equalLocation.add(potenialTangent);
}
return equalLocation;
}
/**
* looks for when f(x) crosses value
* potentially finds tangents, but it is not guaranteed
* @param fx
* @param lowerBound
* @param upperBound
* @param value
* @return
*/
private static Set<Double> crossXes(Evaluator fx, double lowerBound, double upperBound, double value) {
/* fxDiscrete must exist such that for:
x1 is any x
x2 is the smallest x greater than x1
c in (x1, x2)
dx = x2-x1
f(c) for c in (x1, x2) is monotonically increasing or monotonically decreasing
this is made likely but not guaranteed by sufficiently small dx
functions with an infinite number of f(x) = value are not supported (ex sin(1/x) = 1 on [-1,1])
functions that otherwise require dx < epsilon are also not supported
*/
TreeMap<Double, Double> fxDiscrete = fx.eval(lowerBound, upperBound, 0.01);
Map.Entry<Double, Double> lastEntry = null;
HashSet<ComparablePair<Double, Double>> crossInterval = new HashSet<>(); //for ComparablePair p in minMaxXCrossValue: f(p.a) < value < f(p.b)
HashSet<Double> crossLocation = new HashSet<>(); //for x in crossX: f(x) approximates value well
boolean added = false;
for(Map.Entry<Double, Double> entry : fxDiscrete.entrySet()) {
if(lastEntry != null) {
double low = Math.min(entry.getValue(), lastEntry.getValue());
double high = Math.max(entry.getValue(), lastEntry.getValue());
double lowx = entry.getValue() == low ? entry.getKey() : lastEntry.getKey();
double highx = entry.getValue() == high ? entry.getKey() : lastEntry.getKey();
if(!added && (low<value && high>value) ) {
crossInterval.add(new ComparablePair<>(lowx, highx));
added = true;
}else if(!added && isEqual(low, value)) {
crossLocation.add(lowx);
added = true;
}else if(!added && isEqual(high, value)) {
crossLocation.add(highx);
added = true;
}else{
added = false;
}
}
lastEntry = entry;
}
for(ComparablePair<Double, Double> interval : crossInterval) {
crossLocation.add(crossX(fx, interval.a, interval.b, value));
}
return crossLocation;
}
/***
* f(x) must be monotonically increasing or monotonically decreasing for [xlow, xhigh] or [xhigh, xlow] respectively
* f(x_fxlow) < value < f(x_fxhigh)
*
* @param x_fxLow
* @param x_fxHigh
* @param value
* @param fx
* @return x such |f(x) - value| is minimized
*/
private static double crossX (Evaluator fx, double x_fxLow, double x_fxHigh, double value) {
double low = x_fxLow;
double high = x_fxHigh;
double mid = (low+high)/2;
double fLow = fx.eval(low);
double fHigh = fx.eval(high);
final int INCREASING = 1, DECREASING = -1;
boolean increasing = x_fxLow < x_fxHigh;
double sign = increasing ? INCREASING : DECREASING;
double direction = increasing ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
while(fLow < fHigh) {
mid = (low+high)/2;
double fMid = fx.eval(mid);
if(fMid > value) {
high = Math.nextAfter(mid, -direction);
}
if(fMid < value) {
Math.nextAfter(mid, direction);
low = Math.nextAfter(mid, direction);
}
if(isEqual(fMid, value)) {
break;
}
fLow = fx.eval(low);
fHigh = fx.eval(high);
}
return mid;
}
}
|
package Frame;
import Model.CreamCart;
import Model.Ocasion;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
/*
Класс - хранилище действий, привязываемых к кнопкам.
*/
public class Actions {
/*
Абстрактный класс - родительский для всех действий
Содержит 2 конструктора:
С конвеером мороженого, для всех основных действий
С конвеером мороженого и объектом событий, для действия,
запускающего потоки (и завершающего).
Все остальные классы отнаследованы от данного.
*/
public static abstract class BaseAction extends AbstractAction {
//Переменные так же наследуются (доступны в классах - наследниках)
protected CreamCart cart;
protected Ocasion ocasion;
//Конструктор с ковеером и событиями
public BaseAction(CreamCart cart, Ocasion ocasion) {
this.cart = cart;
this.ocasion = ocasion;
}
//Конструктор с ковеером
public BaseAction(CreamCart cart) {
this.cart = cart;
}
//Абстрактный метод, реализованный в классах - наследниках
public abstract void actionPerformed(ActionEvent e);
}
//Класс действия запускающий потоки
public static class StartAction extends BaseAction {
//Конструктор класса
public StartAction(CreamCart cart, Ocasion ocasion) {
//Вызов конструктора родителя
super(cart, ocasion);
}
//Обработчик события
@Override
public void actionPerformed(ActionEvent e) {
//Если потоки ещё не были запущены, то стартует их
if (!cart.isAlive()) {
cart.start();
ocasion.start();
JButton button = (JButton) e.getSource();
button.setText("Завершить работу");
//Иначе завершает работу приложения
} else {
cart.setWorking(false);
JButton button = (JButton) e.getSource();
button.getTopLevelAncestor().dispatchEvent(new WindowEvent((Window) button.getTopLevelAncestor(),
WindowEvent.WINDOW_CLOSING));
}
}
}
//Класс действия, повышающего значение температуры
public static class TemperatureUp extends BaseAction {
//Конструктор класса
public TemperatureUp(CreamCart cart) {
//Вызов конструктора родителя
super(cart);
}
//Обработчик события
@Override
public void actionPerformed(ActionEvent e) {
if (cart.isAlive() & cart.getTemperature() < 100) {
cart.setTemperature(cart.getTemperature() + 5);
}
}
}
//Класс действия, понижающего значение температуры
public static class TemperatureDown extends BaseAction {
//Конструктор класса
public TemperatureDown(CreamCart cart) {
//Вызов конструктора родителя
super(cart);
}
//Обработчик события
@Override
public void actionPerformed(ActionEvent e) {
if (cart.isAlive() & cart.getTemperature() > -25) {
cart.setTemperature(cart.getTemperature() - 5);
}
}
}
//Класс действия, повышающего значение давления
public static class PressureUp extends BaseAction {
//Конструктор класса
public PressureUp(CreamCart cart) {
//Вызов конструктора родителя
super(cart);
}
//Обработчик события
@Override
public void actionPerformed(ActionEvent e) {
if (cart.isAlive() & cart.getPressure() < 10) {
cart.setPressure(cart.getPressure() + 0.5);
}
}
}
//Класс действия, понижающего значение давления
public static class PressureDown extends BaseAction {
//Конструктор класса
public PressureDown(CreamCart cart) {
//Вызов конструктора родителя
super(cart);
}
//Обработчик события
@Override
public void actionPerformed(ActionEvent e) {
if (cart.isAlive() & cart.getPressure() > 0) {
cart.setPressure(cart.getPressure() - 0.5);
}
}
}
//Класс действия, запускаюжего генератор
public static class RebootGenerator extends BaseAction {
//Конструктор класса
public RebootGenerator(CreamCart cart) {
//Вызов конструктора родителя
super(cart);
}
//Обработчик события
@Override
public void actionPerformed(ActionEvent e) {
if (cart.isAlive()) {
cart.setGeneratorActive(true);
}
}
}
//Класс действия, добавляющего ингридиенты
public static class AddIngridients extends BaseAction {
//Конструктор класса
public AddIngridients(CreamCart cart) {
//Вызов конструктора родителя
super(cart);
}
//Обработчик события
@Override
public void actionPerformed(ActionEvent e) {
if (cart.isAlive()) {
cart.setEnoughComponents(true);
}
}
}
}
|
package com.bowlong.third.netty4;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import com.bowlong.third.netty4.codec.LengthByteArrayDecoder;
import com.bowlong.third.netty4.codec.LengthByteArrayEncoder;
public class TcpPipelineFactory extends ChannelInitializer<SocketChannel> {
public static Timer timer = new HashedWheelTimer();
int nThreads = 8;
int maxFrameLength = 32 * 1024;
int lengthFieldOffset = 0;
int lengthFieldLength = 4;
int lengthAdjustment = 0;
int initialBytesToStrip = 4;
final ReadTimeoutHandler idleHandle;
final ChannelInboundHandlerAdapter adapter;
public TcpPipelineFactory(ReadTimeoutHandler idleHandle,
ChannelInboundHandlerAdapter adapter) {
this.idleHandle = idleHandle;
this.adapter = adapter;
}
public TcpPipelineFactory(ReadTimeoutHandler idleHandle,
ChannelInboundHandlerAdapter adapter, int nThreads,
int maxFrameLength, int lengthFieldOffset, int lengthFieldLength,
int lengthAdjustment, int initialBytesToStrip) {
this.idleHandle = idleHandle;
this.adapter = adapter;
this.nThreads = nThreads;
this.maxFrameLength = maxFrameLength;
this.lengthFieldOffset = lengthFieldOffset;
this.lengthFieldLength = lengthFieldLength;
this.lengthAdjustment = lengthAdjustment;
this.lengthAdjustment = lengthAdjustment;
}
// static IpFilterRuleList rules=new IpFilterRuleList("-n:192.168.2.222");
// static OrderedMemoryAwareThreadPoolExecutor e = new
// OrderedMemoryAwareThreadPoolExecutor(
// 16, 0, 0);
// static ExecutionHandler executionHandler = new ExecutionHandler(e);
// public ChannelPipeline getPipeline() throws Exception {
// // Create a default pipeline implementation.
// ChannelPipeline pipeline = pipeline();
//
// // Uncomment the following line if you want HTTPS
// // SSLEngine engine =
// // SecureChatSslContextFactory.getServerContext().createSSLEngine();
// // engine.setUseClientMode(false);
// // pipeline.addLast("ssl", new SslHandler(engine));
// // pipeline.addLast("decoder", new HttpRequestDecoder());
// // Uncomment the following line if you don't want to handle HttpChunks.
// // pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
// // pipeline.addLast("encoder", new HttpResponseEncoder());
// // Remove the following line if you don't want automatic content
// // compression.
// // pipeline.addLast("deflater", new HttpContentCompressor());
// // pipeline.addLast("handler", new WebHandler());
// pipeline.addLast("timeout", new IdleHandler(timer, 600));
// // IpFilterRuleHandler firewall = new IpFilterRuleHandler();
// // firewall.addAll(rules);
// // pipeline.addLast("firewall", firewall);
// // pipeline.addLast("executor", executionHandler);
// pipeline.addLast("decoder", new B2Decoder());
// pipeline.addLast("tcp", new LogicTcpHandler());
// return pipeline;
// }
EventExecutorGroup eventExecutorGroup = new DefaultEventExecutorGroup(
nThreads);
@Override
protected void initChannel(SocketChannel sc) throws Exception {
ChannelPipeline pipeline = sc.pipeline();
pipeline.addLast("timeout", idleHandle);
pipeline.addLast("decoder", new LengthByteArrayDecoder(maxFrameLength,
lengthFieldOffset, lengthFieldLength, lengthAdjustment,
initialBytesToStrip));
pipeline.addLast("encoder", new LengthByteArrayEncoder());
pipeline.addLast(eventExecutorGroup, "tcp_adapter", adapter);
}
}
|
package com.cloudogu.smeagol.wiki.infrastructure;
import com.cloudogu.smeagol.Account;
import com.cloudogu.smeagol.wiki.domain.Wiki;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ResetCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.treewalk.CanonicalTreeParser;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.treewalk.filter.PathFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import java.io.*;
import java.net.URI;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import static com.cloudogu.smeagol.ScmHttpClient.BEARER_TOKEN_IDENTIFIER;
import static com.cloudogu.smeagol.wiki.infrastructure.GitConfig.DEFAULT_REMOTE;
import static java.util.Collections.singleton;
@SuppressWarnings("squid:S1160") // ignore multiple exception rule
public class GitClient implements AutoCloseable {
@VisibleForTesting
static final String FIRST_INDEX_VERSION = "1";
@VisibleForTesting
static final String INDEX_VERSION = "2";
@VisibleForTesting
static final String INDEX_VERSION_FILE = "index.version";
private static final Logger LOG = LoggerFactory.getLogger(GitClient.class);
private final ApplicationEventPublisher publisher;
private final Account account;
private final DirectoryResolver directoryResolver;
private final Wiki wiki;
private final File repository;
private Git gitRepository;
private PullChangesStrategy strategy;
GitClient(ApplicationEventPublisher publisher, DirectoryResolver directoryResolver, PullChangesStrategy strategy, Account account, Wiki wiki) {
this.publisher = publisher;
this.directoryResolver = directoryResolver;
this.strategy = strategy;
this.account = account;
this.wiki = wiki;
this.repository = directoryResolver.resolve(wiki.getId());
}
public void refresh() throws GitAPIException, IOException {
if (repository.exists()) {
checkSearchIndex();
pullChangesIfNeeded();
} else {
createClone();
}
}
private void pullChangesIfNeeded() throws GitAPIException, IOException {
if (strategy.shouldPull(wiki.getId())) {
pullChangesAndLogTime();
} else {
LOG.debug("skip pulling changes, because pull strategy {}", strategy.getClass());
}
}
private void pullChangesAndLogTime() throws GitAPIException, IOException {
Stopwatch sw = Stopwatch.createStarted();
try {
pullChanges();
} finally {
LOG.debug("pull changes of {} finished in {}", wiki.getId(), sw);
}
}
private void checkSearchIndex() throws IOException {
File searchIndex = directoryResolver.resolveSearchIndex(wiki.getId());
if (!searchIndex.exists()) {
createSearchIndexDirectory();
createRepositoryChangedEvent();
} else {
String indexVersion = readIndexVersion(searchIndex);
if (!INDEX_VERSION.equals(indexVersion)) {
recreateSearchIndexDirectory(indexVersion);
}
}
}
private void recreateSearchIndexDirectory(String oldVersion) throws IOException {
LOG.warn("recreate search index, because the index uses format {} and we need version {}", oldVersion, INDEX_VERSION);
removeOldSearchIndex();
createSearchIndexDirectory();
createRepositoryChangedEvent();
}
private void removeOldSearchIndex() {
publisher.publishEvent(new ClearIndexEvent(wiki.getId()));
}
private String readIndexVersion(File directory) throws IOException {
Path versionFilePath = Paths.get(directory.getPath(), INDEX_VERSION_FILE);
if (Files.exists(versionFilePath)) {
byte[] data = Files.readAllBytes(versionFilePath);
return new String(data, Charsets.UTF_8);
}
return FIRST_INDEX_VERSION;
}
@VisibleForTesting
Git open() throws IOException {
if (gitRepository == null) {
gitRepository = Git.open(repository);
}
return gitRepository;
}
public File file(String path) {
return new File(repository, path);
}
public Optional<RevCommit> lastCommit(String path) throws IOException, GitAPIException {
Git git = open();
Iterator<RevCommit> iterator = git.log()
.addPath(path)
.setMaxCount(1)
.call()
.iterator();
if (iterator.hasNext()) {
return Optional.of(iterator.next());
}
return Optional.empty();
}
public List<RevCommit> findCommits(String path) throws IOException, GitAPIException {
Git git = open();
return ImmutableList.copyOf(
git
.log()
.addPath(path)
.call()
.iterator());
}
private void pullChanges() throws GitAPIException, IOException {
LOG.debug("open repository {}", repository);
Git git = open();
LOG.debug("pull changes from remote for repository {}", repository);
ObjectId oldHead = git.getRepository().resolve("HEAD^{tree}");
// We have to be sure that the origin url points to the actual wiki repository url.
// This can be differ if the fqdn of the ecosystem has changed or after a migration
// from scm-manager v1 to v2.
GitConfig.from(git).ensureOriginMatchesUrl(getRemoteRepositoryUrl());
git.pull()
.setRemote(DEFAULT_REMOTE)
.setRemoteBranchName(wiki.getId().getBranch())
.setCredentialsProvider(credentialsProvider(account))
.call();
ObjectId head = git.getRepository().resolve("HEAD^{tree}");
if (hasRepositoryChanged(oldHead, head)) {
RepositoryChangedEvent repositoryChangedEvent = createRepositoryChangedEvent(git, oldHead, head);
if (!repositoryChangedEvent.isEmpty()) {
publisher.publishEvent(repositoryChangedEvent);
}
}
}
private String getRemoteRepositoryUrl() {
return wiki.getRepositoryUrl().toExternalForm();
}
private RepositoryChangedEvent createRepositoryChangedEvent(Git git, ObjectId oldHead, ObjectId head) throws IOException, GitAPIException {
ObjectReader reader = git.getRepository().newObjectReader();
CanonicalTreeParser newTree = new CanonicalTreeParser();
newTree.reset(reader, head);
CanonicalTreeParser oldTree = new CanonicalTreeParser();
oldTree.reset(reader, oldHead);
List<DiffEntry> diffs = git.diff()
.setNewTree(newTree)
.setOldTree(oldTree)
.call();
RepositoryChangedEvent event = new RepositoryChangedEvent(wiki.getId());
for (DiffEntry entry : diffs) {
if (isPageDiff(entry)) {
addChangeToEvent(entry, event);
}
}
return event;
}
private boolean isPageDiff(DiffEntry entry) {
return Pages.isPageFilename(entry.getNewPath()) || Pages.isPageFilename(entry.getOldPath());
}
private void addChangeToEvent(DiffEntry entry, RepositoryChangedEvent event) {
switch (entry.getChangeType()) {
case ADD:
case COPY:
event.added(entry.getNewPath());
break;
case DELETE:
event.deleted(entry.getOldPath());
break;
case MODIFY:
event.modified(entry.getNewPath());
break;
case RENAME:
event.deleted(entry.getOldPath());
event.added(entry.getNewPath());
}
}
private boolean hasRepositoryChanged(ObjectId oldHead, ObjectId head) {
return !head.equals(oldHead);
}
public void createClone() throws GitAPIException, IOException {
String branch = wiki.getId().getBranch();
LOG.info("clone repository {} to {}", wiki.getRepositoryUrl(), repository);
gitRepository = Git.cloneRepository()
.setURI(getRemoteRepositoryUrl())
.setDirectory(repository)
.setBranchesToClone(singleton("refs/head" + branch))
.setBranch(branch)
.setCredentialsProvider(credentialsProvider(account))
.call();
if (!"master".equals(branch)) {
File newRef = new File(repository, ".git/refs/heads/master");
File refDirectory = newRef.getParentFile();
if (!refDirectory.exists() && !refDirectory.mkdirs()) {
throw new IOException("failed to create parent directory " + refDirectory);
}
if (!newRef.exists() && !newRef.createNewFile()) {
throw new IOException("failed to create parent directory");
}
try (BufferedWriter output = new BufferedWriter(new FileWriter(newRef))) {
output.write("ref: refs/heads/" + branch);
}
}
createSearchIndexDirectory();
createRepositoryChangedEvent();
}
public void deleteClone() throws IOException {
LOG.info("remove local repository {} ", repository.getPath());
FileUtils.deleteDirectory(repository);
}
private void createSearchIndexDirectory() throws IOException {
File directory = directoryResolver.resolveSearchIndex(wiki.getId());
if (!directory.exists() && !directory.mkdirs()) {
throw new IllegalStateException("failed to create search index directory at " + directory);
}
writeIndexVersion(directory);
}
private void writeIndexVersion(File directory) throws IOException {
Path versionFilePath = Paths.get(directory.getPath(), INDEX_VERSION_FILE);
Files.write(versionFilePath, INDEX_VERSION.getBytes(Charsets.UTF_8));
}
private void createRepositoryChangedEvent() throws IOException {
URI repositoryUri = repository.toURI();
RepositoryChangedEvent repositoryChangedEvent = new RepositoryChangedEvent(wiki.getId());
Files.walkFileTree(repository.toPath(), new SimpleFileVisitor<java.nio.file.Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (".git".equals(dir.getFileName().toString())) {
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(java.nio.file.Path file, BasicFileAttributes attrs) {
String path = repositoryUri.relativize(file.toUri()).getPath();
if (Pages.isPageFilename(path)) {
repositoryChangedEvent.added(path);
}
return FileVisitResult.CONTINUE;
}
});
if (!repositoryChangedEvent.isEmpty()) {
publisher.publishEvent(repositoryChangedEvent);
}
}
private CredentialsProvider credentialsProvider(Account account) {
return new UsernamePasswordCredentialsProvider(BEARER_TOKEN_IDENTIFIER, account.getAccessToken());
}
public RevCommit commit(String path, String displayName, String email, String message) throws GitAPIException, IOException {
String[] paths = {path};
return commit(paths, displayName, email, message);
}
public RevCommit commit(String[] paths, String displayName, String email, String message) throws GitAPIException, IOException {
Git git = open();
for (String path : paths) {
// git.add() does not work for removed files
// so we have to use git.rm(), if commit is used for delete operation
if (Files.exists(Paths.get(repository.getPath(), path))) {
LOG.debug("add file {} to git index", path);
git.add().addFilepattern(path)
.call();
} else {
LOG.debug("remove file {} from git index", path);
git.rm().addFilepattern(path)
.call();
}
}
RevCommit commit = git.commit()
.setAuthor(displayName, email)
.setMessage(message)
.call();
pushChanges(commit);
return commit;
}
public RevCommit getCommitFromId(String commitId) throws IOException {
Git git = open();
try (RevWalk revWalk = new RevWalk(git.getRepository())) {
RevCommit commit = revWalk.parseCommit(ObjectId.fromString(commitId));
revWalk.dispose();
return commit;
}
}
public Optional<String> pathContentAtCommit(String path, RevCommit commit) throws IOException {
Git git = open();
RevTree tree = commit.getTree();
try (TreeWalk treeWalk = new TreeWalk(git.getRepository())) {
treeWalk.addTree(tree);
treeWalk.setRecursive(true);
treeWalk.setFilter(PathFilter.create(path));
if (!treeWalk.next()) {
return Optional.empty();
}
ObjectId objectId = treeWalk.getObjectId(0);
return Optional.of(readContent(objectId));
}
}
private String readContent(ObjectId objectId) throws IOException {
ObjectLoader loader = open().getRepository().open(objectId);
ByteArrayOutputStream resultBytes = new ByteArrayOutputStream();
loader.copyTo(resultBytes);
return new String(resultBytes.toByteArray());
}
private void pushChanges(RevCommit commit) throws GitAPIException, IOException {
String branch = wiki.getId().getBranch();
CredentialsProvider credentials = credentialsProvider(account);
Git git = open();
LOG.info("push changes to remote {} on branch {}", wiki.getRepositoryUrl(), branch);
try {
git.push()
.setRemote(getRemoteRepositoryUrl())
.setRefSpecs(new RefSpec(branch + ":" + branch))
.setCredentialsProvider(credentials)
.call();
} catch (TransportException e) {
LOG.info("TransportException revert {}", commit);
git.reset()
.setMode(ResetCommand.ResetType.HARD)
.setRef(commit.getParent(0).toObjectId().getName())
.call();
throw e;
}
}
@Override
public void close() {
if (gitRepository != null) {
gitRepository.close();
}
}
}
|
package com.example.graphqldemo.record;
import java.util.List;
public record BookInput(String title, Integer pageCount, Long authorId, List<Long> genreIds) {
}
|
package present;
import java.util.List;
import bean.TuijianBean;
import m.Getdatamodle;
import mInterface.SpHotv;
import mybase.Basepresent;
/**
* Created by 地地 on 2017/12/7.
* 邮箱:461211527@qq.com.
*/
public class SpHotp extends Basepresent {
private Getdatamodle getdatamodle;
private SpHotv spHotv;
public SpHotp(Object viewmodel) {
super(viewmodel);
this.spHotv= (SpHotv) viewmodel;
if(getdatamodle==null){
getdatamodle=new Getdatamodle();
}
}
public void getSpHotdata(int page){
getdatamodle.getspremen(page, new Getdatamodle.requesttuijianBack() {
@Override
public void success(List<TuijianBean> list) {
spHotv.getdatasuess(list);
}
@Override
public void fail(Throwable e) {
spHotv.getdatafail(e.toString());
}
});
}
}
|
package elaundry.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
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 org.springframework.web.bind.annotation.ResponseBody;
import elaundry.domain.LaundryItem;
import elaundry.domain.LaundryService;
import elaundry.service.LaundryItemService;
import elaundry.service.LaundryServiceService;
@Controller
@RequestMapping("services")
public class LaundryServiceController {
@Autowired
private LaundryServiceService laundryServiceService;
@Autowired
private LaundryItemService laundryItemService;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String LoadService(Model model, HttpServletRequest request) {
request.setAttribute("selectedService", new LaundryService());
model.addAttribute("services", laundryServiceService.getLaundryServcies());
return "serviceAndItem";
}
@RequestMapping(value = "/items/{serviceId}", method = RequestMethod.GET)
public @ResponseBody List<LaundryItem> getLaundryItemsByServiceId(@PathVariable(value = "serviceId") int serviceId) {
return laundryItemService.getLaundryItemsByServiceId(serviceId);
}
@RequestMapping(value = "/item/{itemId}", method = RequestMethod.GET)
public @ResponseBody LaundryItem getLaundryItemById(@PathVariable(value = "itemId") int itemId) {
return laundryItemService.getLaundryItemById(itemId);
}
}
|
package com.tks.ds;
/**
* @see Graph#dijkstra(int)
*/
public class ExceptionContainsNegativeWeight extends Exception {
private static final long serialVersionUID = 2L;
ExceptionContainsNegativeWeight() {
super("Graph contains a negative weighted edge cycle");
}
}
|
package com.tencent.mm.ui.chatting.viewitems;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import com.tencent.mm.R;
import com.tencent.mm.ak.o;
import com.tencent.mm.g.a.dj;
import com.tencent.mm.g.a.hz;
import com.tencent.mm.g.a.mw;
import com.tencent.mm.g.a.qu;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.q;
import com.tencent.mm.model.u.b;
import com.tencent.mm.modelappbrand.e;
import com.tencent.mm.modelappbrand.f;
import com.tencent.mm.modelappbrand.u;
import com.tencent.mm.modelappbrand.v;
import com.tencent.mm.plugin.appbrand.config.WxaAttributes;
import com.tencent.mm.plugin.appbrand.n.c;
import com.tencent.mm.plugin.appbrand.q.k;
import com.tencent.mm.pluginsdk.model.app.l;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.bd;
import com.tencent.mm.ui.chatting.b.b.i;
import com.tencent.mm.ui.chatting.c.a;
import com.tencent.mm.ui.chatting.j;
import com.tencent.mm.ui.chatting.t.m;
import com.tencent.rtmp.TXLiveConstants;
public class n$b extends b implements f, m {
private u fye = new v(this);
private a tKy;
public final boolean bba() {
return true;
}
public final boolean aq(int i, boolean z) {
if (z && i == 553648177) {
return true;
}
return false;
}
public final View a(LayoutInflater layoutInflater, View view) {
if (view != null && view.getTag() != null) {
return view;
}
r rVar = new r(layoutInflater, R.i.chatting_item_to_appmsg_wxa_dynamic);
n$d s = new n$d().s(rVar, false);
View bH = ((e) g.l(e.class)).bH(rVar.getContext());
s.ubE = bH;
s.ubD.addView(bH, new LayoutParams(-1, -1));
rVar.setTag(s);
return rVar;
}
public final void a(b.a aVar, int i, a aVar2, bd bdVar, String str) {
com.tencent.mm.y.g.a J;
n$d n_d = (n$d) aVar;
this.tKy = aVar2;
i iVar = (i) aVar2.O(i.class);
iVar.aX(bdVar);
String str2 = bdVar.field_content;
iVar.aV(bdVar);
if (str2 != null) {
J = com.tencent.mm.y.g.a.J(str2, bdVar.field_reserved);
} else {
J = null;
}
au auVar = new au(bdVar, aVar2.cwr(), i, null, 0);
if (J != null) {
CharSequence charSequence;
n_d.tZS.setVisibility(8);
n_d.tZR.setVisibility(8);
n_d.tZO.setVisibility(8);
n_d.uaq.setVisibility(8);
WxaAttributes rR = ((c) g.l(c.class)).rR(J.dyS);
if (rR != null) {
charSequence = rR.field_nickname;
} else {
Object charSequence2 = J.bZH;
}
str2 = rR != null ? rR.field_brandIconURL : J.dzb;
n_d.uaq.setVisibility(0);
n_d.uam.setVisibility(8);
n_d.uat.setText(J.title);
n_d.uam.setText(J.description);
n_d.uao.setText(charSequence2);
switch (J.dyZ) {
case 1:
n_d.uap.setText(R.l.app_brand_share_wxa_testing_tag);
break;
case 2:
n_d.uap.setText(R.l.app_brand_share_wxa_preview_tag);
break;
default:
n_d.uap.setText(R.l.app_brand_entrance);
break;
}
o.Pj().a(str2, n_d.uan, n$d.ubC);
if (cxN()) {
com.tencent.mm.ui.chatting.b.b.g gVar = (com.tencent.mm.ui.chatting.b.b.g) aVar2.O(com.tencent.mm.ui.chatting.b.b.g.class);
if (bdVar.field_status == 2 && a(gVar, bdVar.field_msgId)) {
if (n_d.uai != null) {
n_d.uai.setVisibility(0);
}
} else if (n_d.uai != null) {
n_d.uai.setVisibility(8);
}
if (n_d.mgA != null) {
n_d.mgA.setVisibility(8);
}
} else if (n_d.mgA != null) {
n_d.mgA.setVisibility(0);
if (bdVar.field_status >= 2) {
n_d.mgA.setVisibility(8);
}
}
com.tencent.mm.y.a aVar3 = (com.tencent.mm.y.a) J.u(com.tencent.mm.y.a.class);
Bundle bundle = new Bundle();
bundle.putString("app_id", J.dyT);
bundle.putString("msg_id", bdVar.field_msgId);
String str3 = "cache_key";
if (aVar3 != null) {
str2 = aVar3.dvD;
} else {
str2 = null;
}
bundle.putString(str3, str2);
bundle.putString("msg_title", J.title);
bundle.putString("msg_path", J.dyR);
bundle.putInt("msg_pkg_type", J.dyZ);
bundle.putInt("pkg_version", J.cbu);
bundle.putInt("widget_type", 0);
bundle.putInt("scene", aVar2.cwr() ? TXLiveConstants.PUSH_EVT_START_VIDEO_ENCODER : TXLiveConstants.PUSH_EVT_FIRST_FRAME_AVAILABLE);
bundle.putInt("view_init_width", n$d.ubA);
bundle.putInt("view_init_height", n$d.ubB);
n_d.ubE.setTag(n_d);
((e) g.l(e.class)).a(k.bq(aVar2), n_d.ubE, bundle, this.fye);
}
n_d.hrH.setTag(auVar);
n_d.hrH.setOnClickListener(d(aVar2));
b v = com.tencent.mm.model.u.Hx().v(k.bq(aVar2), true);
n.c cVar = (n.c) v.get("listener", null);
if (cVar == null) {
cVar = new n.c();
v.p("listener", cVar);
}
cVar.j(aVar2);
if (this.qUB) {
n_d.hrH.setOnLongClickListener(c(aVar2));
}
a(i, n_d, bdVar, aVar2.cwp(), aVar2.cwr(), aVar2, this);
}
public final boolean a(ContextMenu contextMenu, View view, bd bdVar) {
int i = ((au) view.getTag()).position;
if (bdVar.field_content != null) {
com.tencent.mm.y.g.a gp = com.tencent.mm.y.g.a.gp(com.tencent.mm.model.bd.b(this.tKy.cwr(), bdVar.field_content, bdVar.field_isSend));
if (gp != null) {
if (com.tencent.mm.pluginsdk.model.app.g.h(com.tencent.mm.pluginsdk.model.app.g.bl(gp.appId, false)) && !j.au(bdVar)) {
contextMenu.add(i, 111, 0, this.tKy.tTq.getMMResources().getString(R.l.retransmit));
}
if ((bdVar.field_status == 2 || bdVar.cGF == 1) && a(bdVar, this.tKy) && aaA(bdVar.field_talker)) {
contextMenu.add(i, 123, 0, view.getContext().getString(R.l.chatting_long_click_menu_revoke_msg));
}
dj djVar = new dj();
djVar.bLf.bJC = bdVar.field_msgId;
com.tencent.mm.sdk.b.a.sFg.m(djVar);
if (djVar.bLg.bKE || c$b.a(this.tKy.tTq.getContext(), gp)) {
contextMenu.add(i, 129, 0, view.getContext().getString(R.l.chatting_long_click_menu_open));
}
if (!this.tKy.cws()) {
contextMenu.add(i, 100, 0, this.tKy.tTq.getMMResources().getString(R.l.chatting_long_click_menu_delete_msg));
}
com.tencent.mm.modelappbrand.j JN = ((e) g.l(e.class)).JN();
if (JN.JP() || JN.ho(gp.dyZ)) {
contextMenu.add(i, 133, 0, this.tKy.tTq.getMMResources().getString(R.l.chatting_long_click_menu_open_wxa_widget_debugger_settings));
contextMenu.add(i, 132, 0, this.tKy.tTq.getMMResources().getString(R.l.chatting_long_click_menu_open_wxa_widget_debugger));
}
}
}
return true;
}
public final boolean a(MenuItem menuItem, a aVar, bd bdVar) {
com.tencent.mm.y.g.a aVar2 = null;
String str;
switch (menuItem.getItemId()) {
case 100:
str = bdVar.field_content;
if (str != null) {
aVar2 = com.tencent.mm.y.g.a.gp(str);
}
if (aVar2 != null) {
if (19 == aVar2.type) {
mw mwVar = new mw();
mwVar.bXL.type = 3;
mwVar.bXL.bJC = bdVar.field_msgId;
com.tencent.mm.sdk.b.a.sFg.m(mwVar);
}
com.tencent.mm.pluginsdk.model.app.f bl = com.tencent.mm.pluginsdk.model.app.g.bl(aVar2.appId, false);
if (bl != null && bl.aaq()) {
a(aVar, aVar2, bdVar, bl);
}
}
com.tencent.mm.model.bd.aU(bdVar.field_msgId);
break;
case 103:
String str2 = bdVar.field_content;
if (str2 != null) {
aVar2 = com.tencent.mm.y.g.a.gp(str2);
if (aVar2 != null) {
switch (aVar2.type) {
case 16:
hz hzVar = new hz();
hzVar.bRv.bRw = aVar2.bRw;
hzVar.bRv.bIZ = bdVar.field_msgId;
hzVar.bRv.bRx = bdVar.field_talker;
com.tencent.mm.sdk.b.a.sFg.m(hzVar);
break;
}
}
}
break;
case 111:
c$b.a(aVar, bdVar, b(aVar, bdVar));
break;
case 132:
((e) g.l(e.class)).JN().bI(aVar.tTq.getContext());
break;
case 133:
str = bdVar.field_content;
if (str != null) {
aVar2 = com.tencent.mm.y.g.a.gp(str);
}
if (aVar2 != null) {
Bundle bundle = new Bundle();
bundle.putString("app_id", aVar2.dyT);
bundle.putString("msg_id", bdVar.field_msgId);
bundle.putInt("pkg_type", aVar2.dyZ);
bundle.putInt("pkg_version", aVar2.dyW);
((e) g.l(e.class)).JN().d(aVar.tTq.getContext(), bundle);
break;
}
break;
}
return false;
}
public final boolean b(View view, a aVar, bd bdVar) {
view.getTag();
String str = bdVar.field_content;
if (str == null) {
return false;
}
com.tencent.mm.y.g.a gp = com.tencent.mm.y.g.a.gp(str);
if (gp == null) {
return false;
}
com.tencent.mm.pluginsdk.model.app.f bl = com.tencent.mm.pluginsdk.model.app.g.bl(gp.appId, true);
if (!(bl == null || bi.oW(bl.field_appId) || !bl.aaq())) {
a(aVar, gp, q.GF(), bl, bdVar.field_msgSvrId);
}
qu quVar = new qu();
quVar.cbq.appId = gp.dyT;
quVar.cbq.userName = gp.dyS;
quVar.cbq.cbs = gp.dyR;
quVar.cbq.cbt = gp.dyZ;
quVar.cbq.cbw = gp.dyV;
quVar.cbq.cbu = gp.dza;
quVar.cbq.cbx = gp.dyZ != 0;
str = gp.dyX;
StringBuilder stringBuilder;
if (aVar.cwr()) {
quVar.cbq.scene = TXLiveConstants.PUSH_EVT_START_VIDEO_ENCODER;
stringBuilder = new StringBuilder(aVar.getTalkerUserName());
stringBuilder.append(":");
stringBuilder.append(b(aVar, bdVar));
stringBuilder.append(":");
stringBuilder.append(str);
quVar.cbq.bGG = stringBuilder.toString();
} else {
quVar.cbq.scene = TXLiveConstants.PUSH_EVT_FIRST_FRAME_AVAILABLE;
stringBuilder = new StringBuilder(b(aVar, bdVar));
stringBuilder.append(":");
stringBuilder.append(str);
quVar.cbq.bGG = stringBuilder.toString();
}
quVar.cbq.cbz.dFy = aVar.getTalkerUserName();
quVar.cbq.cbz.dzR = gp.dyY;
com.tencent.mm.sdk.b.a.sFg.m(quVar);
return true;
}
public final void q(View view, int i) {
Object tag = view.getTag();
if (tag instanceof n$d) {
x.i("MicroMsg.ChattingItemAppMsgWxaDynamicTo", "onWidgetStateChanged(%s, state : %d)", new Object[]{Integer.valueOf(view.hashCode()), Integer.valueOf(i)});
n$d n_d = (n$d) tag;
switch (i) {
case 0:
n_d.gzp.setVisibility(0);
n_d.gzp.cAG();
n_d.ubE.setVisibility(4);
n_d.oBp.setVisibility(4);
return;
case 1:
n_d.gzp.cAH();
n_d.gzp.setVisibility(4);
n_d.ubE.setVisibility(4);
n_d.oBp.setVisibility(0);
n_d.oBp.setImageResource(R.k.dynamic_page_res_not_found);
return;
case 4:
n_d.gzp.cAH();
n_d.gzp.setVisibility(4);
n_d.ubE.setVisibility(0);
n_d.oBp.setVisibility(4);
return;
default:
n_d.gzp.cAH();
n_d.gzp.setVisibility(4);
n_d.ubE.setVisibility(4);
n_d.oBp.setVisibility(0);
n_d.oBp.setImageResource(R.k.app_brand_share_page_cover_default);
return;
}
}
}
public final void a(a aVar, bd bdVar) {
if (bdVar.aQm()) {
l.ae(bdVar);
com.tencent.mm.model.bd.aU(bdVar.field_msgId);
aVar.lT(true);
}
}
}
|
package com.tencent.mm.plugin.offline.a;
import android.text.TextUtils;
import com.tencent.mm.plugin.wallet_core.model.Bankcard;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
public final class i extends com.tencent.mm.wallet_core.tenpay.model.i {
public String bTi = "";
public String lJT = "0";
private String lJU = "0";
private boolean lJV = false;
public i(Bankcard bankcard, String str, String str2, int i, String str3) {
Map hashMap = new HashMap();
hashMap.put("passwd", str);
hashMap.put("oper", str2);
if (str2.equals("changeto")) {
if (TextUtils.isEmpty(str3)) {
hashMap.put("verify_code", "");
} else {
hashMap.put("verify_code", str3);
}
hashMap.put("chg_fee", String.valueOf(i));
hashMap.put("bind_serialno", bankcard.field_bindSerial);
hashMap.put("bank_type", bankcard.field_bankcardType);
hashMap.put("card_tail", bankcard.field_bankcardTail);
}
this.bTi = bankcard.field_mobile;
F(hashMap);
}
public final int aBO() {
return 50;
}
public final void a(int i, String str, JSONObject jSONObject) {
if (jSONObject != null) {
this.lJT = jSONObject.optString("verify_flag");
this.lJU = jSONObject.optString("limit_fee");
}
}
}
|
package com.sushichet.sushichet.mvvvm.paging;
import android.arch.paging.PagedList;
import android.arch.paging.PagedListAdapter;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.sushichet.sushichet.R;
import com.sushichet.sushichet.activity.ProductDetails;
import com.sushichet.sushichet.room.entity.Product;
public class PagingProductAdapter extends PagedListAdapter<Product, PagingProductAdapter.ProductViewHolder> {
Context context;
public PagingProductAdapter(Context context) {
super(Product.DIFF_CALLBACK);
this.context = context;
}
@NonNull
@Override
public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_product, parent, false);
return new ProductViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull final ProductViewHolder holder, int position) {
final Product model = getItem(position);
if (model != null) {
holder.productName.setText(model.getName());
String euro = "\u20ac";
holder.productPrice.setText(model.getPrice() + " " + euro);
Picasso.with(context).load(model.getCropImage()).networkPolicy(NetworkPolicy.OFFLINE).into(holder.productImage, new com.squareup.picasso.Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Picasso.with(context).load(model.getCropImage()).into(holder.productImage);
}
});
holder.holder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, ProductDetails.class);
intent.putExtra("productImage",model.getFullImage());
intent.putExtra("productTitle",model.getName());
intent.putExtra("productPrice",model.getPrice());
intent.putExtra("productId",model.getId()+"");
context.startActivity(intent);
}
});
}
}
public static class ProductViewHolder extends RecyclerView.ViewHolder {
View holder;
ImageView productImage;
TextView productName, productPrice;
ProductViewHolder(View itemView) {
super(itemView);
holder = itemView;
productImage = holder.findViewById(R.id.product_img);
productName = holder.findViewById(R.id.product_txt);
productPrice = holder.findViewById(R.id.product_price);
}
}
@Override
public void submitList(PagedList<Product> pagedList) {
super.submitList(pagedList);
}
}
|
package com.edu.miusched.controller;
import com.edu.miusched.domain.Entry;
import com.edu.miusched.service.EntryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.ArrayList;
import java.util.List;
@Controller
public class EntryController {
@Autowired
EntryService entryService;
@RequestMapping(value = {"/admin/entry"}, method = RequestMethod.GET)
public String getEntryForm(@ModelAttribute("newEntry") Entry entry, Model model) {
Entry entry1 = new Entry();
List<Entry> entries = new ArrayList<Entry>();
entries.addAll(entryService.getAllEntries());
System.out.println(entries);
model.addAttribute("entries", entries);
model.addAttribute("newEntry", entry);
model.addAttribute("entry1",entry1);
return "Admin/ManageEntry";
}
@RequestMapping(value = {"/admin/entry/addnewentry"}, method = RequestMethod.POST)
public String addEntry(@ModelAttribute("newEntry") @Validated Entry entryObj, BindingResult result, Model model) {
if (result.hasErrors()) {
return "Admin/ManageEntry";
} else {
entryObj.setEntryName(entryObj.getEntryType().name()+entryObj.getStartDate().getYear());
entryService.save(entryObj);
return "redirect:/admin/entry";
}
}
@RequestMapping("/admin/entries")
public String listEntries(Model model) {
model.addAttribute("entries", entryService.getAllEntries());
return "Admin/ManageEntry";
}
@RequestMapping("/admin/entry/delete/{id}")
public String deleteEntry(@PathVariable Long id) {
entryService.deleteEntry(id);
return "redirect:/admin/entry";
}
@RequestMapping(value = "/admin/entry/edit/{id}", method = RequestMethod.GET)
public String editEntry(@PathVariable Long id, ModelMap model) {
Entry entry = new Entry();
model.addAttribute("entry", entryService.findByEntryId(id));
return "Admin/ManageEntry";
}
@RequestMapping(value = "/admin/entry/updateentry", method = RequestMethod.POST)
public String updateEntry(@ModelAttribute("entry") Entry entryupdate, BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "Admin/ManageEntry";
}
entryService.save(entryupdate);
return "redirect:/admin/entry";
}
}
|
package prj.betfair.api.betting.operations;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import prj.betfair.api.betting.datatypes.EventTypeResult;
import prj.betfair.api.betting.datatypes.MarketFilter;
import prj.betfair.api.betting.exceptions.APINGException;
import prj.betfair.api.common.Executor;
/***
* Returns a list of Event Types (i.e. Sports) associated with the markets selected by the
* MarketFilter.
*/
public class ListEventTypesOperation {
private final MarketFilter filter;
private final String locale;
private final Executor executor;
public ListEventTypesOperation(Builder builder) {
this.filter = builder.filter;
this.locale = builder.locale;
this.executor = builder.executor;
}
/**
* @return filter The filter to select desired markets. All markets that match the criteria in the
* filter are selected.
*/
public MarketFilter getFilter() {
return this.filter;
}
/**
* @return locale The language used for the response. If not specified, the default is returned.
*/
public String getLocale() {
return this.locale;
}
public List<EventTypeResult> execute() throws APINGException {
return executor.execute(this);
}
public static class Builder {
private MarketFilter filter;
private String locale;
private Executor executor;
/**
* @param filter : The filter to select desired markets. All markets that match the criteria in
* the filter are selected.
*/
public Builder(@JsonProperty("filter") MarketFilter filter) {
this.filter = filter;
}
/**
* Use this function to set locale
*
* @param locale The language used for the response. If not specified, the default is returned.
* @return Builder
*/
public Builder withLocale(String locale) {
this.locale = locale;
return this;
}
/**
* @param executor Executor for this operation
* @return Builder
*/
public Builder withExecutor(Executor executor) {
this.executor = executor;
return this;
}
public ListEventTypesOperation build() {
return new ListEventTypesOperation(this);
}
}
}
|
package net.sourceforge.vrapper.vim.commands;
import net.sourceforge.vrapper.keymap.KeyStroke;
import net.sourceforge.vrapper.keymap.vim.ConstructorWrappers;
import net.sourceforge.vrapper.utils.Function;
import net.sourceforge.vrapper.vim.EditorAdaptor;
import net.sourceforge.vrapper.vim.MacroPlayer;
import net.sourceforge.vrapper.vim.register.Register;
import net.sourceforge.vrapper.vim.register.RegisterContent;
import net.sourceforge.vrapper.vim.register.RegisterManager;
/**
* Enqueues a macro in the playlist of the {@link MacroPlayer}.
*
* @author Matthias Radig
*/
public class PlaybackMacroCommand extends SimpleRepeatableCommand {
public static final Function<Command, KeyStroke> KEYSTROKE_CONVERTER = new Function<Command, KeyStroke>() {
public Command call(KeyStroke arg) {
return new PlaybackMacroCommand(arg.getCharacter());
}
};
private final String macroName;
public PlaybackMacroCommand(char macroName) {
this(String.valueOf(macroName));
}
public PlaybackMacroCommand(String macroName) {
this.macroName = macroName;
}
public void execute(EditorAdaptor editorAdaptor)
throws CommandExecutionException {
RegisterManager registerManager = editorAdaptor.getRegisterManager();
Register namedRegister = registerManager.getRegister(macroName);
RegisterContent content = namedRegister.getContent();
if (content == null) {
throw new CommandExecutionException("Macro "+macroName+" does not exist");
}
//store this register for the '@@' command
registerManager.setLastNamedRegister(namedRegister);
Iterable<KeyStroke> parsed = ConstructorWrappers.parseKeyStrokes(content.getText());
editorAdaptor.getMacroPlayer().add(parsed);
}
public Command repetition() {
return this;
}
}
|
package hacker.rank.reformattingdates;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.IntStream;
class Result {
/*
* Complete the 'reformatDate' function below.
*
* The function is expected to return a STRING_ARRAY.
* The function accepts STRING_ARRAY dates as parameter.
*/
static{
final Map<String, String> DAYS = new HashMap<>();
}
public static List<String> reformatDate(List<String> dates)
{
List<String> result = new ArrayList<>();
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM", Locale.ENGLISH);
for(String date : dates){
String[] tokens = date.split(" ");
int day=0;
try
{
day = Integer.parseInt(tokens[0].substring(0, 2));
}catch (NumberFormatException e){
day = Integer.parseInt(tokens[0].substring(0, 1));
}
int year = Integer.parseInt(tokens[2]);
Date monthDate = null;
try
{
monthDate = dateFormat.parse(tokens[1]);
}
catch (ParseException e)
{
e.printStackTrace();
}
cal.setTime(monthDate);
int month = cal.get(Calendar.MONTH);
result.add(LocalDate.of(year,month+1, day).toString());
}
return result;
}
}
public class Solution {
public static void main(String[] args) throws IOException
{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));
int datesCount = Integer.parseInt(bufferedReader.readLine().trim());
List<String> dates = IntStream.range(0, datesCount).mapToObj(i -> {
try {
return bufferedReader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
})
.collect(toList());
List<String> result = Result.reformatDate(dates);
bufferedWriter.write(
result.stream()
.collect(joining("\n"))
+ "\n"
);
bufferedReader.close();
bufferedWriter.close();
}
}
|
// Shape.java
public abstract class Shape {
protected Location location;
public Shape() {
location = new Location();
}
public void setLocation( Location location ) {
this.location = location;
}
public Location getLocation() {
return location;
}
public abstract double area();
public abstract double perimeter();
}
|
package com.tencent.mm.plugin.sns.ui;
public interface af$a {
void SN();
void aX(String str, boolean z);
boolean bCr();
int getPlayErrorCode();
int getPlayVideoDuration();
int getUiStayTime();
void sG(int i);
}
|
/*
* 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 trial;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
/**
*
* @author ASUS
*/
public class MongoConnector {
private final String C_CONN_ATLAS = "mongodb://admin:admin@cluster0-shard-00-00-cfus9.mongodb.net:27017,cluster0-shard-00-01-cfus9.mongodb.net:27017,cluster0-shard-00-02-cfus9.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin";
private final String C_CONN_SIAKAD = "mongodb://admin:admin@101.50.1.164:27017/admin";
private MongoDatabase database = null;
public MongoConnector(){
MongoClientURI uri = new MongoClientURI(C_CONN_SIAKAD);
MongoClient mongoClient = new MongoClient(uri);
this.database = mongoClient.getDatabase("ahp");
}
public MongoDatabase getDatabase(){
return this.database;
}
}
|
package com.lhlp.pages.entity;
import java.util.Date;
public class Student {
private int stuId;
private int courId;
private String stuName;
private String stuPass;
private String stuSex;
private String major;
private String dept;
private String className;
private String stuTel;
private Date birDate;
private Date stuDate;
private String test1;
public int getStuId() {
return stuId;
}
public void setStuId(int stuId) {
this.stuId = stuId;
}
public int getCourId() {
return courId;
}
public void setCourId(int courId) {
this.courId = courId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuPass() {
return stuPass;
}
public void setStuPass(String stuPass) {
this.stuPass = stuPass;
}
public String getStuSex() {
return stuSex;
}
public void setStuSex(String stuSex) {
this.stuSex = stuSex;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getStuTel() {
return stuTel;
}
public void setStuTel(String stuTel) {
this.stuTel = stuTel;
}
public Date getBirDate() {
return birDate;
}
public void setBirDate(Date birDate) {
this.birDate = birDate;
}
public Date getStuDate() {
return stuDate;
}
public void setStuDate(Date stuDate) {
this.stuDate = stuDate;
}
public String getTest1() {
return test1;
}
public void setTest1(String test1) {
this.test1 = test1;
}
public Student() {
super();
}
public Student(int stuId, int courId, String stuName, String stuPass, String stuSex, String major, String dept, String className, String stuTel, Date birDate, Date stuDate, String test1) {
super();
this.stuId = stuId;
this.courId = courId;
this.stuName = stuName;
this.stuPass = stuPass;
this.stuSex = stuSex;
this.major = major;
this.dept = dept;
this.className = className;
this.stuTel = stuTel;
this.birDate = birDate;
this.stuDate = stuDate;
this.test1 = test1;
}
@Override
public String toString() {
return "Student [stuId=" + stuId + ", courId=" + courId + ", stuName=" + stuName + ", stuPass=" + stuPass + ", stuSex=" + stuSex + ", major=" + major + ", dept=" + dept + ", className=" + className + ", stuTel=" + stuTel + ", birDate="
+ birDate + ", stuDate=" + stuDate + ", test1=" + test1 + "]";
}
}
|
package org.alienideology.jcord.internal.object.client.app;
import org.alienideology.jcord.handle.client.app.IAuthApplication;
import org.alienideology.jcord.handle.oauth.Scope;
import org.alienideology.jcord.internal.object.client.Client;
import org.alienideology.jcord.internal.object.client.ClientObject;
import java.util.List;
/**
* @author AlienIdeology
*/
public final class AuthApplication extends ClientObject implements IAuthApplication {
private final String id;
private final String authId;
private final String name;
private final String icon;
private final String description;
private final List<Scope> scopes;
private final boolean isPublicBot;
private final boolean requireCodeGrant;
public AuthApplication(Client client, String id, String authId, String name, String icon, String description, List<Scope> scopes,
boolean isPublicBot, boolean requireCodeGrant) {
super(client);
this.id = id;
this.authId = authId;
this.name = name;
this.icon = icon;
this.description = description;
this.scopes = scopes;
this.isPublicBot = isPublicBot;
this.requireCodeGrant = requireCodeGrant;
}
@Override
public String getId() {
return id;
}
@Override
public String getAuthorizeId() {
return authId;
}
@Override
public String getName() {
return name;
}
@Override
public String getIconHash() {
return icon;
}
@Override
public String getDescription() {
return description;
}
@Override
public List<Scope> getScopes() {
return scopes;
}
@Override
public boolean isPublicBot() {
return isPublicBot;
}
@Override
public boolean requireCodeGrant() {
return requireCodeGrant;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof AuthApplication)) return false;
if (!super.equals(o)) return false;
AuthApplication that = (AuthApplication) o;
if (!id.equals(that.id)) return false;
return authId.equals(that.authId);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + id.hashCode();
result = 31 * result + authId.hashCode();
return result;
}
@Override
public String toString() {
return "AuthApplication{" +
"id='" + id + '\'' +
", authId='" + authId + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
", scopes=" + scopes +
'}';
}
}
|
package com.bytedance.platform.godzilla.d.a;
import android.os.Handler;
import android.os.HandlerThread;
import com.bytedance.platform.godzilla.d.d;
public final class b {
private static HandlerThread a;
private static Handler b = new Handler(a.getLooper());
private static boolean c;
private static int d = 10000;
private static int e = 10000;
public static String a(StackTraceElement[] paramArrayOfStackTraceElement) {
String str = "";
if (paramArrayOfStackTraceElement == null)
return "";
int j = paramArrayOfStackTraceElement.length;
for (int i = 0; i < j; i++) {
StackTraceElement stackTraceElement = paramArrayOfStackTraceElement[i];
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
stringBuilder.append(stackTraceElement.toString());
stringBuilder.append("\n");
str = stringBuilder.toString();
}
return str;
}
public static void a(a parama) {
b.postDelayed(parama, d);
}
public static void a(c paramc) {
b.postDelayed(paramc, e);
}
public static boolean a() {
return c;
}
public static void b(a parama) {
b.removeCallbacks(parama);
}
public static void b(c paramc) {
b.removeCallbacks(paramc);
}
static {
d.a a = new d.a("pool-monitor", 0, 0);
a.start();
a = (HandlerThread)a;
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\bytedance\platform\godzilla\d\a\b.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.scottehboeh.glc.managers;
import com.scottehboeh.glc.referrals.ReferralDirectories;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;
/**
* Created by 1503257 on 29/11/2017.
* <p>
* Log Manager
* <p>
* This class is used to log various different means of activity, such as
* logging in, logging out, editing personal details, etc.
*/
public class LogManager {
/**
* Audit - Create new Log Entry to Audit Log
*
* @param givenLog - Given Log
* @throws IOException - Handled Exception (IOException)
*/
public static void audit(String givenLog, UUID givenUserID, String logExtension) throws IOException {
/** Get new Date Instance */
Date date = new Date();
/** Get Local Date Instance from Date Instance */
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
/** Get Year, Month and Day for Audit Log File Name */
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
/** Get Time and Date Formatted */
String formattedTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
String formattedDate = day + "-" + month + "-" + year;
/** If Log Directory doesn't exis, create it */
if (!ReferralDirectories.logsDirectory.exists()) {
ReferralDirectories.logsDirectory.mkdir();
}
/** Cast Audit File to new File Instance */
File auditFile = new File(ReferralDirectories.logsDirectory + "/" + givenUserID.toString() + "-LOG-" + formattedDate + "." + logExtension);
/** If Audit File doesn't exist, create it */
if (!auditFile.exists()) {
auditFile.createNewFile();
}
/** Get Network and Hardware Instances/Information */
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] hwAddress = network.getHardwareAddress();
/** Concat new Log Entry as String with given Address/Details/Description */
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hwAddress.length; i++) {
sb.append(String.format("%02X%s", hwAddress[i], (i < hwAddress.length - 1) ? "-" : ""));
}
/** Open File Writer Instance */
FileWriter fw = new FileWriter(auditFile.getAbsolutePath(), true);
/** Write Audit Entry to Audit Log */
fw.write("PC ID: " + sb + " | " + formattedDate + " " + formattedTime + " | " + givenLog + "\n");
/** Close File Writer Instance */
fw.close();
}
}
|
package com.supconit.kqfx.web.fxzf.notify.daos.Impl;
import hc.base.domains.Pageable;
import hc.orm.AbstractBasicDaoImpl;
import org.springframework.stereotype.Repository;
import com.supconit.kqfx.web.fxzf.notify.daos.NotifyDao;
import com.supconit.kqfx.web.fxzf.notify.entities.Notify;
@Repository("taizhou_offsite_enforcement_notify_dao")
public class NotifyDaoImpl extends AbstractBasicDaoImpl<Notify, String> implements NotifyDao {
private static final String NAMESPACE=Notify.class.getName();
@Override
public Pageable<Notify> findByPager(Pageable<Notify> pager, Notify condition) {
// TODO Auto-generated method stub
return findByPager(pager, "selectPager", "countPager", condition);
}
@Override
protected String getNamespace() {
// TODO Auto-generated method stub
return NAMESPACE;
}
@Override
public int insert(Notify entity) {
// TODO Auto-generated method stub
return super.insert(entity);
}
@Override
public Notify getById(String id) {
// TODO Auto-generated method stub
return super.getById(id);
}
}
|
package kyle.game.besiege.party;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import kyle.game.besiege.Assets;
public class AmmoType {
public enum Type {
ARROW,
ARROW_FIRE,
ARROW_POISON,
DART,
THROWN_AXE,
THROWN_FIRE,
SPEAR,
SPEAR_FIRE,
ROCK,
CROSSBOW_BOLT,
BULLET
}
public String name;
public int dmg;
public Type type;
public boolean isValidForWeapon(RangedWeaponType.Type rangedWeapon) {
switch (rangedWeapon) {
case BOW:
if (type == Type.ARROW || type == Type.ARROW_FIRE || type == Type.ARROW_POISON) return true;
return false;
}
// TODO, for now allow everything.
return true;
}
public void setType(String typeString) {
if (typeString.equals("arrow"))
type = Type.ARROW;
if (typeString.equals("arrow_poison"))
type = Type.ARROW_POISON;
if (typeString.equals("arrow_fire")) {
type = Type.ARROW_FIRE;
}
if (typeString.equals("rock"))
type = Type.ROCK;
if (typeString.equals("dart"))
type = Type.DART;
if (typeString.equals("crossbow"))
type = Type.CROSSBOW_BOLT;
if (typeString.equals("spear"))
type = Type.SPEAR;
if (typeString.equals("spear_fire"))
type = Type.SPEAR_FIRE;
if (typeString.equals("thrown_axe"))
type = Type.THROWN_AXE;
if (typeString.equals("thrown_fire"))
type = Type.THROWN_FIRE;
if (typeString.equals("firearm"))
type = Type.BULLET;
if (type == null) throw new AssertionError("type not found " + typeString);
}
public boolean isOnFire() {
switch(type) {
case ARROW_FIRE:
case THROWN_FIRE:
case SPEAR_FIRE:
return true;
}
return false;
}
public TextureRegion getRegion() {
switch (type) {
case ARROW:
case ARROW_FIRE:
case ARROW_POISON:
return Assets.map.findRegion("arrow");
case DART:
return Assets.map.findRegion("dart");
case SPEAR:
case SPEAR_FIRE:
return Assets.map.findRegion("dart");
case THROWN_AXE:
return Assets.map.findRegion("axe");
case THROWN_FIRE:
case ROCK:
return Assets.map.findRegion("slingstone");
}
return Assets.map.findRegion("catapult");
}
public TextureRegion getBrokenRegion() {
switch (type) {
case ARROW:
case ARROW_FIRE:
case ARROW_POISON:
return Assets.map.findRegion("half arrow");
case DART:
case SPEAR:
case SPEAR_FIRE:
return Assets.map.findRegion("half dart");
case THROWN_AXE:
double rand = Math.random();
if (rand < 0.4)
return Assets.map.findRegion("half axe");
if (rand < 0.66)
return Assets.map.findRegion("half axe2");
return Assets.map.findRegion("half axe3");
case THROWN_FIRE:
case ROCK:
return Assets.map.findRegion("slingstone");
}
return Assets.map.findRegion("catapult");
}
public boolean shouldSpin() {
switch (type) {
case ARROW:
case ARROW_FIRE:
case ARROW_POISON:
case DART:
case SPEAR:
case SPEAR_FIRE:
case CROSSBOW_BOLT:
return false;
case THROWN_AXE:
case THROWN_FIRE:
case ROCK:
case BULLET:
return true;
}
return false;
}
}
|
package com.tencent.mm.plugin.luckymoney.ui;
import android.content.Intent;
class LuckyMoneyPrepareUI$14 implements Runnable {
final /* synthetic */ LuckyMoneyPrepareUI kWX;
LuckyMoneyPrepareUI$14(LuckyMoneyPrepareUI luckyMoneyPrepareUI) {
this.kWX = luckyMoneyPrepareUI;
}
public final void run() {
Intent intent = new Intent();
intent.setClass(this.kWX.mController.tml, LuckyMoneyIndexUI.class);
intent.addFlags(67108864);
this.kWX.mController.tml.startActivity(intent);
this.kWX.finish();
}
}
|
import java.net.*;
import java.io.*;
import java.util.concurrent.*;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class ServeurThread extends ServeurFonctions implements Runnable{
public Socket socket;
int port;
ArrayList <Games> listePartie;
Games jeu;
Joueur joueur;
public ServeurThread(Socket s, int p, ArrayList <Games> l){
this.socket = s;
this.port = p;
this.listePartie = l;
}
public void run(){
try{
PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int nombreJoueur;
nouveauJoueurConnecte(this, pw, br);
while(true){
String mess = br.readLine();
System.out.println(mess);
String mess1 = mess.substring(0, mess.length()-3);
String [] messTab = mess1.split(" ");
System.out.println("le mess= "+messTab[0]);
/******************************Creation partie***************************/
if(messTab[0].equals("NEW")){
String portString = messTab[2];
int portClient = Integer.parseInt(portString);
String idJoueur = messTab[1];
creationPartie(this, pw, br, messTab[1], portClient);
System.out.println("Voici l'id du joueur qui créé une partie: "+this.joueur.getId());
}
/******************************Rejoindre partie**************************/
if(messTab[0].equals("REG")){
String portString = messTab[2];
int portClient = Integer.parseInt(portString);
String idJoueur = messTab[1];
int partieChoisie = Integer.parseInt(messTab[3]);
rejoindrePartie(this, pw, br, idJoueur, portClient, partieChoisie);
}
/*****************************desinscription********************/
if(messTab[0].equals("UNREG")){
desincrireJoueur(this, pw, br, this.jeu, this.joueur);
}
/*************************taille du labyrinthe*****************/
if(messTab[0].equals("SIZE?")){
String partieNumS = messTab[1];
int partieNum = Integer.parseInt(partieNumS);
tailleLabyrintheDemande(this, pw, br, partieNum);
}
/*******************liste joueurs inscris****************/
if(messTab[0].equals("LIST?")){
String partieNumS = messTab[1];
int partieNum = Integer.parseInt(partieNumS);
joueursInscritsPartie(this, pw, br, this.jeu, partieNum);
}
/******************liste des games non commencees************/
if(messTab[0].equals("GAMES?")){
partiesNonCommencees(this, pw, br);
}
if(messTab[0].equals("START")){
System.out.println("voici:"+this.joueur+"la");
if(this.joueur == null){
pw.println("bye");
pw.flush();
pw.close();
br.close();
this.socket.close();
}
else if(this.joueur.getGame()==0){
System.out.println("salut");
pw.println("bye");
pw.flush();
pw.close();
br.close();
this.socket.close();
}
else {
System.out.println("problemeZ");
joueurPret(this.joueur);
while(!partiePrete(this.jeu)){
System.out.println("iciiii");
if(partiePrete(this.jeu)){
System.out.println("la partie va commencer");
break;
}
}
break;
}
}
System.out.println("le joueur est pret");
}
/*******************debut du jeu********************/
this.jeu.partieCommence();
System.out.println("probleme");
String numS = ""+this.jeu.getNumero();
String hS = ""+this.jeu.laby.length;
String wS = ""+this.jeu.laby[0].length;
String fS = ""+this.jeu.getNbFantome();
pw.println("WELCOME "+littleEndian(numS)+" "+littleEndian(hS)+" "+littleEndian(wS)+" "+littleEndian(fS)+" "+completerIp(this.jeu.getAddresseIp())+" "+this.jeu.getNumPort()+"***");
pw.flush();
mettreJoueursLaby(this, pw, br, this.jeu.getNumero());
pw.println("POS "+this.joueur.getId()+" "+completer30(this.joueur.getX())+" "+completer30(this.joueur.getY())+"***");
pw.flush();
while(this.jeu.getPartie()){
if(this.jeu.listeJoueur.size()==0 || this.jeu.getNbFantome() ==0){
if(this.jeu.getPartie()==true){
Joueur gagnant = this.jeu.gagnant();
String messagePourEnvoie = "END "+gagnant.getId()+" "+completer40(gagnant.getScore())+"+++";
byte[]data=messagePourEnvoie.getBytes();
DatagramPacket paquet=new DatagramPacket(data,data.length,this.jeu.getIa());
this.jeu.getDso().send(paquet);
this.jeu.setPartie(false);
}
break;
}
afficheLaby(this, pw, br);
String mess = br.readLine();
System.out.println(mess);
String mess1 = mess.substring(0, mess.length()-3);
String [] messTab = mess1.split(" ");
System.out.println("le mess= "+mess);
if(messTab[0].equals("SEND?")){
if(this.jeu.getPartie()==false){
// finDeJeu(this, pw);
break;
}
String idM = messTab[1];
String messageEnvoie = messTab[2];
envoieMessagePerso(this, idM, messageEnvoie, pw);
}
if(messTab[0].equals("ALL?")){
if(this.jeu.getPartie()==false){
//finDeJeu(this, pw);
break;
}
String messageEnvoie = mess.substring(5, mess.length()-3);
envoieMessageGeneral(this, messageEnvoie, pw);
}
if(messTab[0].equals("UP")){
if(this.jeu.getPartie()==false){
// finDeJeu(this, pw);
break;
}
String nbaS = messTab[1];
int nba = Integer.parseInt(nbaS);
monter(this, pw, br, nba, this.joueur.getX(), this.joueur.getY());
this.jeu.incrementeDeplacement();
this.jeu.mouvementFantome();
}
if(messTab[0].equals("DOWN")){
if(this.jeu.getPartie()==false){
// finDeJeu(this, pw);
break;
}
String nbaS = messTab[1];
int nba = Integer.parseInt(nbaS);
descendre(this, pw, br, nba, this.joueur.getX(), this.joueur.getY());
this.jeu.incrementeDeplacement();
this.jeu.mouvementFantome();
}
if(messTab[0].equals("LEFT")){
if(this.jeu.getPartie()==false){
// finDeJeu(this, pw);
break;
}
String nbaS = messTab[1];
int nba = Integer.parseInt(nbaS);
gauche(this, pw, br, nba, this.joueur.getX(), this.joueur.getY());
this.jeu.incrementeDeplacement();
this.jeu.mouvementFantome();
}
if(messTab[0].equals("RIGHT")){
if(this.jeu.getPartie()==false){
// finDeJeu(this, pw);
break;
}
String nbaS = messTab[1];
int nba = Integer.parseInt(nbaS);
droite(this, pw, br, nba, this.joueur.getX(), this.joueur.getY());
this.jeu.incrementeDeplacement();
this.jeu.mouvementFantome();
}
if(messTab[0].equals("QUIT")){
supprimerJoueur(this, pw, br, this.joueur.getId());
break;
}
if(messTab[0].equals("GLIST?")){
if(this.jeu.getPartie()==false){
// finDeJeu(this, pw);
break;
}
listeJoueursPosition(this, pw, br);
}
}
pw.println("BYE***");
pw.flush();
pw.close();
br.close();
this.socket.close();
}catch(Exception e){
}
}
}
|
package tech.hobbs.mallparkingmanagementsystem.repository;
import tech.hobbs.mallparkingmanagementsystem.entities.ParkingBay;
import java.util.Optional;
public interface ParkingBayRepository extends BaseRepository<ParkingBay> {
Optional<ParkingBay> findFirst1ByBayOccupiedIsFalse();
}
|
package com.hxsb.model.BUY_ERP_ORDER_CREATE;
import java.util.Date;
public class SCM_S00_NOTICE {
private Long reckey;
private String taskname;
private String dataname;
private String datacode;
private Long bizunitid;
private Long bizareaid;
private Long bizshopid;
private Integer deptid;
private String title;
private Long operator;
private String optexp;
private Integer optdata;
private String noticename;
private Date createtime;
private Long creator;
private Long billid;
private String billkey;
public Long getReckey() {
return reckey;
}
public void setReckey(Long reckey) {
this.reckey = reckey;
}
public String getTaskname() {
return taskname;
}
public void setTaskname(String taskname) {
this.taskname = taskname;
}
public String getDataname() {
return dataname;
}
public void setDataname(String dataname) {
this.dataname = dataname;
}
public String getDatacode() {
return datacode;
}
public void setDatacode(String datacode) {
this.datacode = datacode;
}
public Long getBizunitid() {
return bizunitid;
}
public void setBizunitid(Long bizunitid) {
this.bizunitid = bizunitid;
}
public Long getBizareaid() {
return bizareaid;
}
public void setBizareaid(Long bizareaid) {
this.bizareaid = bizareaid;
}
public Long getBizshopid() {
return bizshopid;
}
public void setBizshopid(Long bizshopid) {
this.bizshopid = bizshopid;
}
public Integer getDeptid() {
return deptid;
}
public void setDeptid(Integer deptid) {
this.deptid = deptid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Long getOperator() {
return operator;
}
public void setOperator(Long operator) {
this.operator = operator;
}
public String getOptexp() {
return optexp;
}
public void setOptexp(String optexp) {
this.optexp = optexp;
}
public Integer getOptdata() {
return optdata;
}
public void setOptdata(Integer optdata) {
this.optdata = optdata;
}
public String getNoticename() {
return noticename;
}
public void setNoticename(String noticename) {
this.noticename = noticename;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public Long getCreator() {
return creator;
}
public void setCreator(Long creator) {
this.creator = creator;
}
public Long getBillid() {
return billid;
}
public void setBillid(Long billid) {
this.billid = billid;
}
public String getBillkey() {
return billkey;
}
public void setBillkey(String billkey) {
this.billkey = billkey;
}
@Override
public String toString() {
return "SCM_S00_NOTICE [reckey=" + reckey + ", taskname=" + taskname + ", dataname=" + dataname + ", datacode="
+ datacode + ", bizunitid=" + bizunitid + ", bizareaid=" + bizareaid + ", bizshopid=" + bizshopid
+ ", deptid=" + deptid + ", title=" + title + ", operator=" + operator + ", optexp=" + optexp
+ ", optdata=" + optdata + ", noticename=" + noticename + ", createtime=" + createtime + ", creator="
+ creator + ", billid=" + billid + ", billkey=" + billkey + "]";
}
}
|
package com.perhab.napalm.statement;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks the method to be executed for performance test.
* @author bigbear3001
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Execute {
int HUNDRED = 100;
int TEN_THOUSAND = 10000;
int MILLION = 1000000;
Parameter[] parameters();
int[] iterations() default {1, HUNDRED, TEN_THOUSAND, MILLION};
}
|
package com.project.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.project.model.Education;
import com.project.services.EducationService;
@RestController
@RequestMapping("/education")
public class EducationController {
@Autowired
private EducationService educationService;
@GetMapping
public List<Education> getAll() {
return educationService.getAll();
}
@PostMapping
@ResponseStatus(HttpStatus.OK)
public Education add(@RequestBody Education education) {
System.err.println(education.getCv());
return educationService.save(education);
}
@PostMapping("/delete")
@ResponseStatus(HttpStatus.OK)
public void delete(@RequestBody Education education) {
educationService.delete(education);
}
}
|
package CollectionsTest;
import java.util.Iterator;
import java.util.TreeSet;
public class SetDemo {
public static void main(String[] args) {
TreeSet<String> set = new TreeSet<>();
set.add("b");
set.add("a");
set.add("r");
set.add("e");
//移除一个元素
set.remove("r");
//普通遍历,由于树集是对插入任意进行排序输出,所以,不可以根据索引获得
System.out.println("根据索引遍历不行");
System.out.println("增强for循环");
for (String s:set) {
System.out.println(s);
}
//迭代器遍历
System.out.println("迭代器迭代:");
Iterator<String> iter = set.iterator();
while(iter.hasNext())
System.out.println(iter.next());
//lambda表达式迭代
System.out.println("lambda表达式迭代:");
Iterator<String> it = set.iterator();
it.forEachRemaining(element->System.out.println(element));
}
}
|
package com.tencent.mm.plugin.appbrand.menu;
import android.content.Context;
import android.widget.Toast;
import com.tencent.mm.plugin.appbrand.config.AppBrandSysConfig;
import com.tencent.mm.plugin.appbrand.menu.a.a;
import com.tencent.mm.plugin.appbrand.page.p;
import com.tencent.mm.plugin.appbrand.performance.AppBrandPerformanceManager;
import com.tencent.mm.plugin.appbrand.s$j;
import com.tencent.mm.ui.base.l;
public final class e extends a {
public e() {
super(l.gjA - 1);
}
public final void a(Context context, p pVar, l lVar, String str) {
AppBrandSysConfig appBrandSysConfig = pVar.fdO.fcu;
if (appBrandSysConfig.frm.fih == 1) {
CharSequence string;
if (appBrandSysConfig.fqM) {
string = context.getString(s$j.app_brand_performance_disable);
} else {
string = context.getString(s$j.app_brand_performance_enable);
}
lVar.e(l.gjA - 1, string);
}
}
public final void a(Context context, p pVar, String str, k kVar) {
if ((!pVar.fdO.fcu.fqM ? 1 : 0) != 0) {
AppBrandPerformanceManager.vg(str);
Toast.makeText(context, s$j.app_brand_performance_enable_toast, 0).show();
return;
}
AppBrandPerformanceManager.vh(str);
Toast.makeText(context, s$j.app_brand_performance_disable_toast, 0).show();
}
}
|
package model;
/**
* Created by 11437 on 2017/12/11.
*/
public class Code {
private String status;
private String code;
private String message;
public void setStatus(String status){
this.status=status;
}
public void setCode(String code){
this.code=code;
}
public void setMessage(String message){
this.message=message;
}
public String getStatus(){
return this.status;
}
public String getCode(){return this.code;}
public String getMessage(){return this.message;}
}
|
package br.com.inter.banco.modelo.core;
import java.util.Random;
public abstract class Conta {
private Integer numero;
private Double saldo;
private Cliente cliente;
public Conta() {
this.saldo = 0.0;
}
public abstract void depositar(Double valor);
public Double consultarSaldo() {
return this.saldo;
}
public void sacar(Double valor) throws SaldoInsuficienteException, HoraFuncionamenoException {
if (new Random().nextBoolean()) {//Define se estah na hora permitida para sacar
if (getSaldo() >= valor) {
setSaldo(getSaldo() - valor);
} else {
SaldoInsuficienteException ex = new SaldoInsuficienteException();
ex.setSaldoAtual(getSaldo());
throw ex;
}
} else {
throw new HoraFuncionamenoException();
}
}
public Integer getNumero() {
return numero;
}
public void setNumero(Integer numero) {
this.numero = numero;
}
protected Double getSaldo() {
return saldo;
}
protected void setSaldo(Double saldo) {
this.saldo = saldo;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((numero == null) ? 0 : numero.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass().getSuperclass() != obj.getClass().getSuperclass())
return false;
Conta other = (Conta) obj;
if (numero == null) {
if (other.numero != null)
return false;
} else if (!numero.equals(other.numero))
return false;
return true;
}
}
|
package com.afs.invoiceapi.service;
import com.afs.invoiceapi.exceptions.DomainNotFoundException;
import com.afs.invoiceapi.model.Invoice;
import com.afs.invoiceapi.repository.CustomerRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlGroup;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class CustomerServiceIT {
@Autowired
private CustomerRepository customerRepository;
@SpyBean
private InvoiceService invoiceService;
@Autowired
private CustomerService customerService;
@Test
@SqlGroup({
@Sql(value = "/test-data.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD),
@Sql(value = "/delete-data.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
})
public void it_should_delete_customer() {
//given
String customerId = "customerId3";
//when
customerService.deleteCustomer(customerId);
//then
List<Invoice> invoices = invoiceService.retrieveInvoices(customerId);
assertTrue(invoices.isEmpty());
DomainNotFoundException exception = assertThrows(DomainNotFoundException.class,
() -> customerRepository.retrieveCustomer(customerId));
assertEquals("customer.not.found", exception.getKey());
assertEquals(customerId, exception.getArgs()[0]);
}
@Test
@SqlGroup({
@Sql(value = "/test-data.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD),
@Sql(value = "/delete-data.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
})
public void it_should_not_delete_invoice_items_when_exception_occured_during_delete_customer() {
//given
String customerId = "customerId2";
Mockito.doThrow(RuntimeException.class).when(invoiceService).deleteInvoices(customerId);
//when
RuntimeException exception = assertThrows(RuntimeException.class,
() -> customerService.deleteCustomer(customerId));
//then
assertNotNull(exception);
assertNotNull(customerRepository.retrieveCustomer(customerId));
List<Invoice> invoices = invoiceService.retrieveInvoices(customerId);
assertEquals(1, invoices.size());
}
}
|
package com.yirmio.lockawayadmin.BL;
import android.widget.ImageView;
import com.parse.ParseFile;
/**
* Created by yirmio on 1/9/2015.
*/
public class RestaurantMenuObject implements Comparable<RestaurantMenuObject> {
//region Properties
private float price;
private String title;
private float timeToMake;
private ParseFile pic;
private String type;
private boolean isReady;
private String description;
private boolean isVeg;
private boolean isGlootenFree;
private String id;
private ImageView image;
private boolean isAvaliable;
private boolean isOnSale;
//endregion
//region Ctor
public RestaurantMenuObject() {
}
// //Convert MenuListRowLayoutItem to RestaurantMenuObject
// public RestaurantMenuObject(OrdersListRawItem item){
// this.price = item.getPrice();
// this.title = item.getLable();
// this.timeToMake = item.getTimeToMake();
// //this.pic = item.getPhotoParseFile();
// //TODO handle type
// //this.type = item.get;
// this.isReady = false;
// this.description = item.getInfo();
// this.isVeg = item.isVeg();
// this.isGlootenFree = item.isGlotenFree();
// this.id = item.getId();
// }
public RestaurantMenuObject(String itemID, String desc, float price, String title, int timeToMake, String type, boolean isVeg, boolean isGlootenFree, boolean isAvalabe,boolean onSale) {
this.price = price;
this.title = title;
this.timeToMake = timeToMake;
//this.pic = pic;
this.type = type;
this.isReady = false;
this.description = desc;
this.isVeg = isVeg;
this.isGlootenFree = isGlootenFree;
this.id = itemID;
this.isAvaliable = isAvalabe;
this.isOnSale = onSale;
}
//endregion
//region Getters & Setters
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean isVeg() {
return isVeg;
}
public void setIsVeg(boolean isVeg) {
this.isVeg = isVeg;
}
public boolean isGlootenFree() {
return isGlootenFree;
}
public void setIsGlootenFree(boolean isGlootenFree) {
this.isGlootenFree = isGlootenFree;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setIsReady(boolean isReady) {
this.isReady = isReady;
}
public String getType() {
return type;
}
public float getPrice() {
return price;
}
public String getTitle() {
return title;
}
public float getTimeToMake() {
return timeToMake;
}
// public ParseFile getPic() {
// return pic;
// }
public void setPrice(float price) {
this.price = price;
}
public boolean isReady() {
return isReady;
}
public void setReady(boolean isReady) {
this.isReady = isReady;
}
public void setTitle(String title) {
this.title = title;
}
public void setTimeToMake(int timeToMake) {
this.timeToMake = timeToMake;
}
// public void setPic(ParseFile pic) {
// this.pic = pic;
// }
public void setType(String type) {
this.type = type;
}
//endregion
//region Overrides
@Override
//Will Compare MenuItems by TimeToMake
public int compareTo(RestaurantMenuObject another) {
if (this.timeToMake < another.timeToMake) {
return -1;
} else return 1;
}
public ImageView getImage() {
return image;
}
public void setImage(ImageView image) {
this.image = image;
}
public boolean isAvaliable() {
return isAvaliable;
}
public void setAvaliable(boolean avaliable) {
this.isAvaliable = avaliable;
}
public boolean isOnSale() {
return isOnSale;
}
public void setOnSale(boolean onSale) {
this.isOnSale = onSale;
}
//endregion
}
|
package com.learn.learn.bassis.datasave;
import android.content.Context;
import android.content.SharedPreferences;
import com.wyt.common.base.BaseActivity;
public class SharedPreferencesActivity extends BaseActivity {
@Override
protected int getLayout() {
return 0;
}
@Override
public void initView() {
}
@Override
public void start() {
//存数据
SharedPreferences sp = getSharedPreferences("sp_demo", Context.MODE_PRIVATE);
sp.edit().putString("name", "小张").putInt("age", 11).commit();
//取数据
SharedPreferences sp1 = getSharedPreferences("sp_demo", Context.MODE_PRIVATE);
String name = sp1.getString("name", null);
int age = sp1.getInt("age", 0);
}
@Override
public void initData() {
}
}
|
package jbyco.optimization.jump;
import jbyco.optimization.Statistics;
import jbyco.optimization.common.ClassTransformer;
import jbyco.optimization.common.MethodTransformer;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodNode;
import java.util.List;
/**
* A transformer that applies a chain of method transformers.
*/
public class JumpTransformer extends ClassTransformer {
Statistics stats;
JumpCollector collector;
MethodTransformer mt;
public JumpTransformer(MethodTransformer mt, JumpCollector collector, Statistics stats) {
this.mt = mt;
this.collector = collector;
this.stats = stats;
}
public JumpTransformer(ClassTransformer ct, MethodTransformer mt, JumpCollector collector, Statistics stats) {
super(ct);
this.mt = mt;
this.collector = collector;
this.stats = stats;
}
@Override
public boolean transform(ClassNode cn) {
// no change in the class
boolean classChange = false;
// process methods
for (MethodNode mn : (List<MethodNode>)cn.methods) {
// get instruction list
InsnList list = mn.instructions;
// do while there are changes in the method
boolean change = true;
while(change) {
// no change in the method
change = false;
// collect data
collector.collect(mn);
// transform method with chain of transformers
if (mt.transform(mn)) {
classChange = true;
change = true;
continue;
}
}
}
// call next class transformer
return classChange | super.transform(cn);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.webbeans.container;
import org.apache.webbeans.annotation.DefaultLiteral;
import org.apache.webbeans.component.AbstractOwbBean;
import org.apache.webbeans.component.AbstractProducerBean;
import org.apache.webbeans.component.ManagedBean;
import org.apache.webbeans.component.OwbBean;
import org.apache.webbeans.config.WebBeansContext;
import org.apache.webbeans.exception.WebBeansConfigurationException;
import org.apache.webbeans.exception.WebBeansDeploymentException;
import org.apache.webbeans.inject.AlternativesManager;
import org.apache.webbeans.logger.WebBeansLoggerFacade;
import org.apache.webbeans.spi.BDABeansXmlScanner;
import org.apache.webbeans.spi.ScannerService;
import org.apache.webbeans.util.AnnotationUtil;
import org.apache.webbeans.util.Asserts;
import org.apache.webbeans.util.ClassUtil;
import org.apache.webbeans.util.GenericsUtil;
import org.apache.webbeans.util.InjectionExceptionUtil;
import org.apache.webbeans.util.SingleItemSet;
import org.apache.webbeans.util.WebBeansUtil;
import jakarta.enterprise.event.Event;
import jakarta.enterprise.inject.Instance;
import jakarta.enterprise.inject.UnproxyableResolutionException;
import jakarta.enterprise.inject.spi.AnnotatedType;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.InjectionPoint;
import java.lang.annotation.Annotation;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.apache.webbeans.util.InjectionExceptionUtil.throwAmbiguousResolutionException;
/**
* Injection point resolver class.
* <p>
* It is a singleton class per BeanManager. It is
* responsible for resolving the bean instances at the injection points for
* its bean manager.
* </p>
*
* @version $Rev$ $Date$
*/
public class InjectionResolver
{
private static final Logger logger = WebBeansLoggerFacade.getLogger(InjectionResolver.class);
/**
* Bean Manager
*/
private WebBeansContext webBeansContext;
private AlternativesManager alternativesManager;
/**
* This Map contains all resolved beans via it's type and qualifiers.
* If a bean have resolved as not existing, the entry will contain <code>null</code> as value.
* The Long key is a hashCode, see
* {@link BeanCacheKey#BeanCacheKey(boolean, Type, String, java.util.function.Function, Annotation...)}
*/
private Map<BeanCacheKey, Set<Bean<?>>> resolvedBeansByType = new ConcurrentHashMap<>();
/**
* This Map contains all resolved beans via it's ExpressionLanguage name.
*/
private Map<String, Set<Bean<?>>> resolvedBeansByName = new ConcurrentHashMap<>();
/**
* Whether the container is in startup mode.
* Set to {@code false} immediately before the BeforeDeploymentValidation event gets fired.
*/
private boolean startup;
private boolean fastMatching;
private Bean<Instance<Object>> instanceBean;
private Bean<Event<Object>> eventBean;
/**
* Creates a new injection resolve for given bean manager.
*
* @param webBeansContext WebBeansContext
*/
public InjectionResolver(WebBeansContext webBeansContext)
{
this.webBeansContext = webBeansContext;
alternativesManager = webBeansContext.getAlternativesManager();
startup = true;
fastMatching = false;
instanceBean = webBeansContext.getWebBeansUtil().getInstanceBean();
eventBean = webBeansContext.getWebBeansUtil().getEventBean();
}
public void setFastMatching(boolean fastMatching)
{
this.fastMatching = fastMatching;
}
public void setStartup(boolean startup)
{
this.startup = startup;
}
/**
* Clear caches.
*/
public void clearCaches()
{
resolvedBeansByName.clear();
resolvedBeansByType.clear();
}
/**
* Check the type of the injection point.
* <p>
* Injection point type can not be {@link java.lang.reflect.TypeVariable}.
* </p>
*
* @param injectionPoint injection point
* @throws WebBeansConfigurationException if not obey the rule
*/
public void checkInjectionPointType(InjectionPoint injectionPoint)
{
Type type = injectionPoint.getType();
//Check for injection point type variable
if (ClassUtil.isTypeVariable(type))
{
throw new WebBeansConfigurationException("Injection point type : " + injectionPoint + " can not define Type Variable generic type");
}
//Check for raw event type (10.3.2)
if (type == Event.class)
{
throw new WebBeansConfigurationException("Injection point type : " + injectionPoint + " needs to define type argument for " + Event.class.getName());
}
if (type == Instance.class)
{
throw new WebBeansConfigurationException("Injection point type : " + injectionPoint + " needs to define type argument for " + Instance.class.getName());
}
// not that happy about this check here and at runtime but few TCKs test Weld behavior only...
Bean<?> bean = resolve(implResolveByType(false, type, injectionPoint.getQualifiers().toArray(new Annotation[injectionPoint.getQualifiers().size()])),
injectionPoint);
if (bean != null && ManagedBean.class.isInstance(bean))
{
try
{
ManagedBean.class.cast(bean).valid();
}
catch (UnproxyableResolutionException ure)
{
throw new WebBeansDeploymentException(ure);
}
}
}
/**
* Check that a valid enabled bean exists in the deployment for the given
* injection point definition.
*
* @param injectionPoint injection point
* @throws WebBeansConfigurationException If bean is not available in the current deployment for given injection
*/
public void checkInjectionPoint(InjectionPoint injectionPoint)
{
WebBeansUtil.checkInjectionPointNamedQualifier(injectionPoint);
Type type = injectionPoint.getType();
if (ClassUtil.isTypeVariable(type))
{
throw new WebBeansConfigurationException("Injection point type : " + injectionPoint + " type can not be defined as Typevariable or Wildcard type!");
}
if (webBeansContext.getBeanManagerImpl().isAfterBeanDiscoveryDone())
{
Annotation[] qualifiers = new Annotation[injectionPoint.getQualifiers().size()];
qualifiers = injectionPoint.getQualifiers().toArray(qualifiers);
// OWB-890 some 3rd party InjectionPoints return null in getBean();
Class<?> injectionPointClass = Object.class; // the fallback
Bean injectionPointBean = injectionPoint.getBean();
if (injectionPointBean != null)
{
injectionPointClass = injectionPointBean.getBeanClass();
}
if (injectionPointClass == null && type instanceof Class)
{
injectionPointClass = (Class) type;
}
Set<Bean<?>> beanSet = implResolveByType(injectionPoint.isDelegate(), type, injectionPointClass, qualifiers);
Bean<?> bean = resolve(beanSet, injectionPoint);
if (bean == null)
{
Class<?> clazz;
if (type instanceof ParameterizedType)
{
ParameterizedType pt = (ParameterizedType) type;
clazz = (Class<?>) pt.getRawType();
}
else
{
clazz = (Class<?>) type;
}
InjectionExceptionUtil.throwUnsatisfiedResolutionException(clazz, injectionPoint, qualifiers);
}
}
}
/**
* Returns bean for injection point.
*
* @param injectionPoint injection point declaration
* @return bean for injection point
*/
public Bean<?> getInjectionPointBean(InjectionPoint injectionPoint)
{
Type type = injectionPoint.getType();
Class<?> clazz;
if (type instanceof ParameterizedType)
{
ParameterizedType pt = (ParameterizedType) type;
clazz = (Class<?>) pt.getRawType();
}
else
{
clazz = (Class<?>) type;
}
Set<Annotation> qualSet = injectionPoint.getQualifiers();
Annotation[] qualifiers = qualSet.toArray(new Annotation[qualSet.size()]);
Set<Bean<?>> beanSet = implResolveByType(injectionPoint.isDelegate(), type, clazz, qualifiers);
if (beanSet.isEmpty())
{
InjectionExceptionUtil.throwUnsatisfiedResolutionException(clazz, injectionPoint, qualifiers);
}
return resolve(beanSet, injectionPoint);
}
private Bean<?> getInstanceOrEventInjectionBean(Type type)
{
Class<?> clazz;
if (type instanceof ParameterizedType)
{
ParameterizedType pt = (ParameterizedType) type;
clazz = (Class<?>) pt.getRawType();
if (clazz.isAssignableFrom(Instance.class))
{
return instanceBean;
}
if (clazz.isAssignableFrom(Event.class))
{
return eventBean;
}
}
return null;
}
/**
* Returns set of beans for given bean name.
*
* @param name bean name
* @return set of beans for given bean name
*/
@SuppressWarnings("unchecked")
public Set<Bean<?>> implResolveByName(String name)
{
Asserts.assertNotNull(name, "name parameter");
String cacheKey = name;
Set<Bean<?>> resolvedComponents = resolvedBeansByName.get(cacheKey);
if (resolvedComponents != null)
{
return resolvedComponents;
}
resolvedComponents = new HashSet<>();
Set<Bean<?>> deployedComponents = webBeansContext.getBeanManagerImpl().getBeans();
//Finding all beans with given name
for (Bean<?> component : deployedComponents)
{
if (component.getName() != null)
{
if (component.getName().equals(name))
{
resolvedComponents.add(component);
}
}
}
if (resolvedComponents.isEmpty())
{
// maintain negative cache but use standard empty set so we can garbage collect
resolvedBeansByName.put(cacheKey, Collections.EMPTY_SET);
}
else
{
resolvedBeansByName.put(cacheKey, resolvedComponents);
}
if (logger.isLoggable(Level.FINE))
{
logger.log(Level.FINE, "DEBUG_ADD_BYNAME_CACHE_BEANS", cacheKey);
}
return resolvedComponents;
}
/**
* Resolution by type.
*
* @param isDelegate whether the InjectionPoint is for a {@link jakarta.decorator.Delegate}
* @param injectionPointType injection point api type
* @param qualifiers qualifiers of the injection point
* @return set of resolved beans
*/
public Set<Bean<?>> implResolveByType(boolean isDelegate, Type injectionPointType, Annotation... qualifiers)
{
return implResolveByType(isDelegate, injectionPointType, null, qualifiers);
}
private String getBDABeansXMLPath(Class<?> injectionPointBeanClass)
{
if (injectionPointBeanClass == null)
{
return null;
}
ScannerService scannerService = webBeansContext.getScannerService();
BDABeansXmlScanner beansXMLScanner = scannerService.getBDABeansXmlScanner();
return beansXMLScanner.getBeansXml(injectionPointBeanClass);
}
/**
* Resolution by type.
*
* @param isDelegate whether the InjectionPoint is for a {@link jakarta.decorator.Delegate}
* @param injectionPointType injection point api type
* @param qualifiers qualifiers of the injection point
* @return set of resolved beans
*/
public Set<Bean<?>> implResolveByType(boolean isDelegate, Type injectionPointType,
Class<?> injectionPointClass, Annotation... qualifiers)
{
ScannerService scannerService = webBeansContext.getScannerService();
String bdaBeansXMLFilePath = null;
if (scannerService.isBDABeansXmlScanningEnabled())
{
bdaBeansXMLFilePath = getBDABeansXMLPath(injectionPointClass);
}
boolean currentQualifier = false;
if (qualifiers.length == 0)
{
qualifiers = DefaultLiteral.ARRAY;
currentQualifier = true;
}
Set<Bean<?>> resolvedComponents;
BeanCacheKey cacheKey = null;
if (!startup)
{
// we only cache and validate once the set of Beans is final, otherwise we would cache crap
validateInjectionPointType(injectionPointType);
cacheKey = new BeanCacheKey(isDelegate, injectionPointType, bdaBeansXMLFilePath, this::findQualifierModel, qualifiers);
resolvedComponents = resolvedBeansByType.get(cacheKey);
if (resolvedComponents != null)
{
return resolvedComponents;
}
}
resolvedComponents = new HashSet<>();
boolean returnAll = injectionPointType.equals(Object.class) && currentQualifier;
for (Bean<?> component : webBeansContext.getBeanManagerImpl().getBeans())
{
// no need to check instanceof OwbBean as we always wrap in a
// ThirdpartyBeanImpl at least
if (!((OwbBean) component).isEnabled())
{
continue;
}
if (returnAll)
{
resolvedComponents.add(component);
}
else
{
if (fastMatching)
{
for (Type componentApiType : component.getTypes())
{
if (ClassUtil.isRawClassEquals(injectionPointType, componentApiType))
{
resolvedComponents.add(component);
break;
}
}
}
else
{
for (Type componentApiType : component.getTypes())
{
if (GenericsUtil.satisfiesDependency(
isDelegate, AbstractProducerBean.class.isInstance(component),
injectionPointType, componentApiType, new HashMap<>()))
{
resolvedComponents.add(component);
break;
}
}
}
}
}
if (!returnAll)
{
// Look for qualifiers
resolvedComponents = findByQualifier(resolvedComponents, injectionPointType, qualifiers);
// have an additional round of checks for assignability of parameterized types.
Set<Bean<?>> byParameterizedType = findByParameterizedType(resolvedComponents, injectionPointType, isDelegate);
if (byParameterizedType.isEmpty())
{
resolvedComponents = findByBeanType(resolvedComponents, injectionPointType, isDelegate);
}
else
{
resolvedComponents = byParameterizedType;
}
}
if (resolvedComponents.isEmpty())
{
// for Instance or Event creation we provided special Beans
// because they actually needs to fit every Qualifier
Bean<?> specialBean = getInstanceOrEventInjectionBean(injectionPointType);
if (specialBean != null)
{
resolvedComponents.add(specialBean);
}
}
if (!startup && !resolvedComponents.isEmpty())
{
resolvedBeansByType.put(cacheKey, resolvedComponents);
if (logger.isLoggable(Level.FINE))
{
logger.log(Level.FINE, "DEBUG_ADD_BYTYPE_CACHE_BEANS", cacheKey);
}
}
return resolvedComponents;
}
private Set<Bean<?>> findByBeanType(Set<Bean<?>> allComponents, Type injectionPointType, boolean isDelegate)
{
if (allComponents == null || allComponents.isEmpty())
{
// fast path
return allComponents;
}
Set<Bean<?>> resolved = new HashSet<>();
for (Bean<?> bean : allComponents)
{
boolean isProducer = AbstractProducerBean.class.isInstance(bean);
for (Type type : bean.getTypes())
{
if (GenericsUtil.satisfiesDependency(isDelegate, isProducer, injectionPointType, type, new HashMap<>()))
{
resolved.add(bean);
}
if (!ClassUtil.isParametrizedType(injectionPointType)
&& ClassUtil.isRawClassEquals(injectionPointType, type))
{
resolved.add(bean);
}
}
}
return resolved;
}
private Set<Bean<?>> findByParameterizedType(Set<Bean<?>> allComponents, Type injectionPointType, boolean isDelegate)
{
Bean<?> rawProducerBean = null;
Set<Bean<?>> resolvedComponents = new HashSet<>();
for (Bean<?> component : allComponents)
{
boolean isProducer = AbstractProducerBean.class.isInstance(component);
for (Type componentApiType : component.getTypes())
{
if (GenericsUtil.satisfiesDependency(isDelegate, isProducer, injectionPointType, componentApiType, new HashMap<>()))
{
resolvedComponents.add(component);
break;
}
else if (isProducer && componentApiType instanceof Class && ClassUtil.isRawClassEquals(injectionPointType, componentApiType))
{
rawProducerBean = component;
}
}
}
if (resolvedComponents.isEmpty() && rawProducerBean != null)
{
resolvedComponents.add(rawProducerBean);
}
return resolvedComponents;
}
/**
* Verify that we have a legal Type at the injection point.
* CDI can basically only handle Class and ParameterizedType injection points atm.
* @throws WebBeansConfigurationException on TypeVariable, WildcardType and GenericArrayType
* @throws IllegalArgumentException if the type is not yet supported by the spec.
*/
private void validateInjectionPointType(Type injectionPointType)
{
if (injectionPointType instanceof TypeVariable || injectionPointType instanceof WildcardType || injectionPointType instanceof GenericArrayType)
{
throw new WebBeansConfigurationException("Injection point cannot define Type Variable " + injectionPointType);
}
if (!(injectionPointType instanceof Class) &&
!(injectionPointType instanceof ParameterizedType))
{
throw new IllegalArgumentException("Unsupported type " + injectionPointType.getClass());
}
}
/**
* Gets alternatives from set.
*
* @param beans resolved set
* @return contains alternatives
*/
public <X> Set<Bean<? extends X>> findByAlternatives(Set<Bean<? extends X>> beans)
{
// first check whether we have Alternatives with a Priority annotation
List<Class<?>> prioritizedAlternatives = alternativesManager.getPrioritizedAlternatives();
for (Class<?> alternativeClazz : prioritizedAlternatives)
{
for (Bean<? extends X> bean: beans)
{
if (alternativeClazz.equals(bean.getBeanClass()))
{
return new SingleItemSet<>(bean);
}
}
}
// if none such Alternative got found let's check the 'old' alternatives from beans.xml
Set<Bean<? extends X>> alternativeSet = new HashSet<>();
Set<Bean<? extends X>> enableSet = new HashSet<>();
for (Bean<? extends X> bean : beans)
{
if (bean.isAlternative() ||
(bean instanceof AbstractProducerBean &&
((AbstractProducerBean) bean).getOwnerComponent().isAlternative()))
{
alternativeSet.add(bean);
}
else
{
if (alternativeSet.isEmpty())
{
AbstractOwbBean<?> temp = (AbstractOwbBean<?>) bean;
if (temp.isEnabled())
{
enableSet.add(bean);
}
}
}
}
if (!alternativeSet.isEmpty())
{
return alternativeSet;
}
//
return enableSet;
}
/**
* resolve any ambiguity by checking for Alternatives.
* If any @Alternative exists, then we pick the one with the
* highest priority.
*
* @param beans
* @param injectionPoint only used for logging. Can be null.
* @param <X>
* @return the single resolved bean, null if none is activated
* @throws jakarta.enterprise.inject.AmbiguousResolutionException if more than 1 bean is active
*/
public <X> Bean<? extends X> resolve(Set<Bean<? extends X>> beans, InjectionPoint injectionPoint)
{
if (beans == null || beans.isEmpty())
{
return null;
}
if (beans.size() == 1)
{
// if there is only one Bean left, then there is for sure no ambiguity.
return beans.iterator().next();
}
Set set = resolveAll(beans);
if (set.isEmpty())
{
return null;
}
if(set.size() > 1)
{
throwAmbiguousResolutionException(set, null, injectionPoint);
}
return (Bean<? extends X>)set.iterator().next();
}
public <X> Set<Bean<? extends X>> resolveAll(Set<Bean<? extends X>> beans)
{
if (beans == null || beans.isEmpty())
{
return Collections.emptySet();
}
Set set = findByAlternatives(beans);
if (set == null || set.isEmpty())
{
return Collections.emptySet();
}
return set;
}
/**
* Returns filtered bean set according to the qualifiers.
*
* @param remainingSet bean set for filtering by qualifier
* @param annotations qualifiers on injection point
* @return filtered bean set according to the qualifiers
*/
private Set<Bean<?>> findByQualifier(Set<Bean<?>> remainingSet, Type type, Annotation... annotations)
{
if (remainingSet == null || remainingSet.isEmpty())
{
// fast path
return remainingSet;
}
Iterator<Bean<?>> it = remainingSet.iterator();
Set<Bean<?>> result = new HashSet<>();
while (it.hasNext())
{
Bean<?> component = it.next();
Set<Annotation> qTypes = component.getQualifiers();
int i = 0;
for (Annotation annot : annotations)
{
for (Annotation qualifier : qTypes)
{
if (annot.annotationType().equals(qualifier.annotationType()))
{
AnnotatedType<?> at = findQualifierModel(qualifier.annotationType());
if (at == null)
{
if (AnnotationUtil.isCdiAnnotationEqual(qualifier, annot))
{
i++;
}
}
else
{
if (AnnotationUtil.isCdiAnnotationEqual(at, qualifier, annot))
{
i++;
}
}
}
}
}
if (i == annotations.length)
{
result.add(component);
}
}
return result;
}
private AnnotatedType<? extends Annotation> findQualifierModel(final Class<?> qualifier)
{
return webBeansContext.getBeanManagerImpl().getAdditionalAnnotatedTypeQualifiers().get(qualifier);
}
}
|
package com.haozileung.rpc.common.compression.strategy;
public interface CompressionStrategy {
CompressionResult compress(byte[] buffer);
byte[] decompress(byte[] buffer);
}
|
class Request {
private int distance;
private int numOfPassengers;
private int time;
public Request (int distance, int numOfPassengers, int time) {
this.distance = distance;
this.numOfPassengers = numOfPassengers;
this.time = time;
}
public int getDistance() {
return this.distance;
}
public int getNumOfPassengers() {
return this.numOfPassengers;
}
public int getTime() {
return this.time;
}
}
|
/*
* [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.types.service;
import de.hybris.platform.cmsfacades.data.StructureTypeMode;
import java.util.List;
/**
* Structure Type Mode Provider Interface
*/
public interface StructureTypeModeAttributeFilterProvider
{
/**
* Returns the structure type mode list given its type code and structure mode.
* @param typeCode the type code
* @param mode the structure type mode
* @return a list of {@link StructureTypeModeAttributeFilter}; never null.
*/
List<StructureTypeModeAttributeFilter> getStructureTypeModeAttributeFilters(final String typeCode, final StructureTypeMode mode);
/**
* Adds a new Structure Type Mode to the existing list of mode definitions.
*/
void addStructureTypeModeAttributeFilter(StructureTypeModeAttributeFilter mode);
}
|
package com.city.beijing.dao.shardingMapper;
import com.city.beijing.model.UtilMessageBundle;
import com.city.beijing.model.UtilMessageBundleExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UtilMessageBundleMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table util_message_bundle
*
* @mbggenerated
*/
int countByExample(UtilMessageBundleExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table util_message_bundle
*
* @mbggenerated
*/
int deleteByExample(UtilMessageBundleExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table util_message_bundle
*
* @mbggenerated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table util_message_bundle
*
* @mbggenerated
*/
int insert(UtilMessageBundle record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table util_message_bundle
*
* @mbggenerated
*/
int insertSelective(UtilMessageBundle record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table util_message_bundle
*
* @mbggenerated
*/
List<UtilMessageBundle> selectByExample(UtilMessageBundleExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table util_message_bundle
*
* @mbggenerated
*/
UtilMessageBundle selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table util_message_bundle
*
* @mbggenerated
*/
int updateByExampleSelective(@Param("record") UtilMessageBundle record, @Param("example") UtilMessageBundleExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table util_message_bundle
*
* @mbggenerated
*/
int updateByExample(@Param("record") UtilMessageBundle record, @Param("example") UtilMessageBundleExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table util_message_bundle
*
* @mbggenerated
*/
int updateByPrimaryKeySelective(UtilMessageBundle record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table util_message_bundle
*
* @mbggenerated
*/
int updateByPrimaryKey(UtilMessageBundle record);
}
|
public class RooperK
{
public static void main(String[]arg)
{
int a = 1;
short b = 2;
byte c = 127;
double d = 1000000000;
float f = 3.14f;
String str = "Попов_ИВТ/б-11о";
System.out.printf("Привет,%s:a=%7d,b=%o,c=%x,d=%+8.2f,f=%06.3f!",str,a,b,c,d,f);
}
}
|
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class Reducesize {
public static void main(String[] args) {
InternetExplorerDriver driver=new InternetExplorerDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Dimension dim=driver.manage().window().getSize();
System.out.println(" the width of the browser is"+dim.width);
System.out.println("the height of the browser is"+dim.height);
Dimension ndim=new Dimension(dim.width/3,dim.height/3);
driver.manage().window().setSize(ndim);
}
}
|
package com.tencent.mm.plugin.appbrand.permission;
import com.tencent.mm.sdk.platformtools.x;
class b$5 implements Runnable {
final /* synthetic */ String bAj;
final /* synthetic */ String fEQ;
final /* synthetic */ Runnable gqb;
b$5(Runnable runnable, String str, String str2) {
this.gqb = runnable;
this.bAj = str;
this.fEQ = str2;
}
public final void run() {
if (b.uB()) {
b.amk().add(this.gqb);
x.i("MicroMsg.AppBrandJsApiUserAuth", "requireUserAuth, another request already running, put this in queue, appId %s, api %s", new Object[]{this.bAj, this.fEQ});
return;
}
b.cZ(true);
this.gqb.run();
}
}
|
package fr.lteconsulting;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class LireFichier
{
public static void main( String[] args )
{
File fichier = new File( "C:\\Tmp\\QCM1.png" );
if( !fichier.exists() )
{
System.out.println( "Le fichier à lire n'existe pas !!!" );
}
else
{
lire( fichier );
}
}
private static void lire( File fichier )
{
FileInputStream fis = null;
System.out.printf( "Lecture du fichier '%s' de %d octets\n", fichier.getAbsolutePath(), fichier.length() );
try
{
// On prépare un stream nous permettant de lire les octets dans la source
fis = new FileInputStream( fichier );
// on crée une zone mémoire qui va nous permettre de faire transiter les données
// de la source vers notre programme
byte[] buffer = new byte[16];
int nbBytesRead = 0;
int adresseLecture = 0;
// on boucle tant qu'il y a des octets à lire
while( (nbBytesRead = fis.read( buffer )) > 0 )
{
System.out.printf( "%08X ", adresseLecture );
// après lecture, le buffer contient les nbBytesRead lus
for( int i = 0; i < nbBytesRead; i++ )
System.out.printf( "%02X ", buffer[i] );
System.out.println();
adresseLecture += nbBytesRead;
}
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
try
{
if( fis != null )
fis.close();
}
catch( IOException e )
{
e.printStackTrace();
}
System.out.println( "Lecture terminée" );
}
}
}
|
package com.aacademy.bike_station.controller;
import com.aacademy.bike_station.dto.ColorDto;
import com.aacademy.bike_station.service.ColorService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/colors")
public class ColorController {
private final ColorService colorService;
public ColorController(ColorService colorService) {
this.colorService = colorService;
}
@GetMapping(value = "/{colors}")
public ResponseEntity<ColorDto> findByColor(@PathVariable String color) {
return ResponseEntity.ok(colorService.findByColor(color));
}
}
|
package com.forpleuvoir.forpleuvoir.controller;
import com.forpleuvoir.forpleuvoir.utils.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("upload")
public class UploadController {
@PostMapping("/imgUpload")
@ResponseBody
public Map upload(@RequestParam("file") MultipartFile file, @RequestParam("directory") Integer directory, HttpSession session) throws IOException {
Map map = new HashMap();
String fileName = file.getOriginalFilename();
if(!StringUtil.isImg(fileName.substring(fileName.lastIndexOf(".")))){
map.put("status",0);
return map;
}
String newFileName = new Date().getTime() + fileName.substring(fileName.lastIndexOf("."));
String path;
switch (directory) {
case 0:
path = ClassUtils.getDefaultClassLoader().getResource("static/images/upload/article").getPath();
break;
default:
path = ClassUtils.getDefaultClassLoader().getResource("static/images/upload/").getPath();
}
File baseFile = new File(path);
if (!baseFile.exists()) {
baseFile.mkdirs();
}
System.out.println(path + "/" + newFileName);
file.transferTo(new File(path + "/" + newFileName));
map.put("status", 1);
map.put("fileName", newFileName);
return map;
}
}
|
package net.minecraft.world.gen.feature;
import java.util.Random;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public abstract class WorldGenerator {
private final boolean doBlockNotify;
public WorldGenerator() {
this(false);
}
public WorldGenerator(boolean notify) {
this.doBlockNotify = notify;
}
public abstract boolean generate(World paramWorld, Random paramRandom, BlockPos paramBlockPos);
public void setDecorationDefaults() {}
protected void setBlockAndNotifyAdequately(World worldIn, BlockPos pos, IBlockState state) {
if (this.doBlockNotify) {
worldIn.setBlockState(pos, state, 3);
} else {
worldIn.setBlockState(pos, state, 2);
}
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\world\gen\feature\WorldGenerator.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package br.com.univag.dao;
import br.com.univag.exception.DaoException;
import br.com.univag.fabricaConexao.Conexao;
import br.com.univag.model.UsuarioVo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author CRISTIANO
*/
public class UsuarioDao {
Connection con;
private PreparedStatement ps;
private ResultSet rs;
public UsuarioDao(Connection con) {
this.con = con;
}
public void salvarUsuarioVo(UsuarioVo vo) throws DaoException {
String sql = "insert into usuario (nome_usuario,perfil_usuario,senha_usuario,email_usuario,cpf_usuario)values"
+ "(?,?,?,?,?)";
int i = 1;
try {
ps = con.prepareStatement(sql);
ps.setString(i++, vo.getNome());
ps.setInt(i++, vo.getPerfil());
ps.setString(i++, vo.getSenha());
ps.setString(i++, vo.getEmail());
ps.setString(i++, vo.getCpf());
ps.executeUpdate();
} catch (SQLException ex) {
throw new DaoException("Erro ao gravar usuario", ex.getCause());
} finally {
Conexao.close(ps);
}
}
@SuppressWarnings("null")
public UsuarioVo autenticarUsuarioVo(String usuario, String senha) throws DaoException {
String sql = "select * from usuario where email_usuario = ? and senha_usuario = ?";
UsuarioVo vo = null;
try {
ps = con.prepareStatement(sql);
ps.setString(1, usuario);
ps.setString(2, senha);
rs = ps.executeQuery();
if (rs.next()) {
vo = new UsuarioVo();
vo.setCodigo(rs.getInt(1));
vo.setNome(rs.getString(2));
vo.setPerfil(rs.getInt(3));
vo.setSenha(rs.getString(4));
vo.setEmail(rs.getString(5));
vo.setCpf(rs.getString(6));
}
if (rs.next()) {
throw new DaoException("Usuario duplicado");
}
} catch (SQLException ex) {
throw new DaoException("Erro ao retornar usuario", ex.getCause());
} finally {
Conexao.close(ps, rs);
}
return vo;
}
public UsuarioVo selectUsuarioById(int codigo) throws DaoException {
String sql = "select * from usuario where id_usuario = ?";
UsuarioVo vo = null;
try {
ps = con.prepareStatement(sql);
ps.setInt(1, codigo);
rs = ps.executeQuery();
if (rs.next()) {
vo = new UsuarioVo();
vo.setCodigo(rs.getInt(1));
vo.setNome(rs.getString(2));
vo.setPerfil(rs.getInt(3));
vo.setSenha(rs.getString(4));
vo.setEmail(rs.getString(5));
vo.setCpf(rs.getString(6));
}
if (rs.next()) {
throw new DaoException("Retornou 2 usuarios");
}
} catch (SQLException ex) {
throw new DaoException("Erro ao selecionar usuario pelo codigo", ex.getCause());
} finally {
Conexao.close(ps, rs);
}
return vo;
}
public List<UsuarioVo> listaUsuarioVo(int registro) throws DaoException {
String sql = "SELECT * FROM univag_estacionamento_db.usuario LIMIT 10 OFFSET ?";
List<UsuarioVo> list = new ArrayList<>();
try {
ps = con.prepareStatement(sql);
ps.setInt(1, registro);
rs = ps.executeQuery();
while (rs.next()) {
UsuarioVo vo = new UsuarioVo();
vo.setCodigo(rs.getInt(1));
vo.setNome(rs.getString(2));
vo.setPerfil(rs.getInt(3));
vo.setSenha(rs.getString(4));
vo.setEmail(rs.getString(5));
vo.setCpf(rs.getString(6));
list.add(vo);
}
} catch (SQLException ex) {
throw new DaoException("Erro ao listar usuarios", ex.getCause());
} finally {
Conexao.close(ps, rs);
}
return list;
}
public void updateUsuarioVoPerfil(UsuarioVo vo) throws DaoException {
String sql = "update usuario set nome_usuario = ?,perfil_usuario = ? where id_usuario = ? ";
int i = 1;
try {
ps = con.prepareStatement(sql);
ps.setString(i++, vo.getNome());
ps.setInt(i++, vo.getPerfil());
ps.setInt(i++, vo.getCodigo());
ps.executeUpdate();
} catch (SQLException ex) {
throw new DaoException("Erro ao alterar usuario", ex.getCause());
} finally {
Conexao.close(ps);
}
}
public UsuarioVo consutarUsuarioPorCpf(String cpf) throws DaoException {
String sql = "select * from usuario where cpf_usuario = ?";
UsuarioVo vo = null;
try {
ps = con.prepareStatement(sql);
ps.setString(1, cpf);
rs = ps.executeQuery();
if (rs.next()) {
vo = new UsuarioVo();
vo.setCodigo(rs.getInt(1));
vo.setNome(rs.getString(2));
vo.setPerfil(rs.getInt(3));
vo.setSenha(rs.getString(4));
vo.setEmail(rs.getString(5));
vo.setCpf(rs.getString(6));
}
if (rs.next()) {
throw new DaoException("Erro ao buscar usuario pelo cpf");
}
} catch (SQLException ex) {
throw new DaoException("Erro ao selecionar usuario pelo cpf", ex.getCause());
} finally {
Conexao.close(ps, rs);
}
return vo;
}
public UsuarioVo consultarUsuarioEmail(String email) throws DaoException {
String sql = "select * from usuario where email_usuario = ?";
UsuarioVo vo = null;
try {
ps = con.prepareStatement(sql);
ps.setString(1, email);
rs = ps.executeQuery();
if (rs.next()) {
vo = new UsuarioVo();
vo.setCodigo(rs.getInt(1));
vo.setNome(rs.getString(2));
vo.setPerfil(rs.getInt(3));
vo.setSenha(rs.getString(4));
vo.setEmail(rs.getString(5));
vo.setCpf(rs.getString(6));
}
if (rs.next()) {
throw new DaoException("Existem usuarios com emails identicos");
}
} catch (SQLException ex) {
throw new DaoException("Erro ao selecionar usuario pelo email", ex.getCause());
} finally {
Conexao.close(ps, rs);
}
return vo;
}
public int totalUsuarioVo() throws DaoException {
String sql = "SELECT Count(*) AS quantidade FROM usuario";
int total = 0;
try {
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
if (rs.next()) {
total = rs.getInt("quantidade");
}
} catch (SQLException ex) {
throw new DaoException("Erro ao contar tabela", ex.getCause());
}
return total;
}
public void deleteUser(int codigo) throws DaoException {
String sql = "delete from usuario where id_usuario=?";
try {
ps = con.prepareStatement(sql);
ps.setInt(1, codigo);
ps.executeUpdate();
} catch (SQLException ex) {
throw new DaoException("Erro ao excluir usuario", ex.getCause());
}
}
public void updateUsuarioVoSenha(UsuarioVo vo) throws DaoException {
String sql = "update usuario set senha_usuario = ? where id_usuario = ? ";
int i = 1;
try {
ps = con.prepareStatement(sql);
ps.setString(i++, vo.getSenha());
ps.setInt(i++, vo.getCodigo());
ps.executeUpdate();
} catch (SQLException ex) {
throw new DaoException("Erro ao senha usuario", ex.getCause());
} finally {
Conexao.close(ps);
}
}
}
|
package rugal.westion.jiefanglu.controller;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import rugal.common.page.Pagination;
import rugal.westion.jiefanglu.common.CommonMessageContent;
import rugal.westion.jiefanglu.common.Message;
import rugal.westion.jiefanglu.common.ShowDataStruct;
import rugal.westion.jiefanglu.core.entity.Account;
import rugal.westion.jiefanglu.core.entity.QQThirdPart;
import rugal.westion.jiefanglu.core.entity.RelationShip;
import rugal.westion.jiefanglu.core.entity.WBThirdPart;
import rugal.westion.jiefanglu.core.entity.WXThirdPart;
import rugal.westion.jiefanglu.core.service.AccountService;
@Controller
public class AccountController {
private static final Logger LOG = LoggerFactory
.getLogger(AccountController.class.getName());
@Autowired
private AccountService accountService;
public AccountController() {
}
/**
* QQ登录
* */
@ResponseBody
@RequestMapping(value = "/v1/users/login/qq", method = RequestMethod.POST)
public Message getRoutes(@RequestBody QQThirdPart qqThirdPart,
HttpServletRequest request) {
Account account = accountService.loginByQQ(qqThirdPart, request);
Map<String, Object> data = new LinkedHashMap<String, Object>();
data.put("id", account.getId());
data.put("nickname", account.getNickname());
data.put("uid", account.getUid());
ShowDataStruct returnData = ShowDataStruct.getDataStruct(null, data);
return Message.successMessage(CommonMessageContent.LOGIN_SUCCEED,
returnData);
}
/**
* 微博登录
* */
@ResponseBody
@RequestMapping(value = "/v1/users/login/wb", method = RequestMethod.POST)
public Message getRoutes(@RequestBody WBThirdPart WBThirdPart,
HttpServletRequest request) {
Account account = accountService.loginByWB(WBThirdPart, request);
Map<String, Object> data = new LinkedHashMap<String, Object>();
data.put("id", account.getId());
data.put("nickname", account.getNickname());
data.put("uid", account.getUid());
ShowDataStruct returnData = ShowDataStruct.getDataStruct(null, data);
return Message.successMessage(CommonMessageContent.LOGIN_SUCCEED,
returnData);
}
/**
* 微信登录
* */
@ResponseBody
@RequestMapping(value = "/v1/users/login/wx", method = RequestMethod.POST)
public Message getRoutes(@RequestBody WXThirdPart wxThirdPart,
HttpServletRequest request) {
Account account = accountService.loginByWX(wxThirdPart, request);
Map<String, Object> data = new LinkedHashMap<String, Object>();
data.put("id", account.getId());
data.put("nickname", account.getNickname());
data.put("uid", account.getUid());
ShowDataStruct returnData = ShowDataStruct.getDataStruct(null, data);
return Message.successMessage(CommonMessageContent.LOGIN_SUCCEED,
returnData);
}
/**
* 建立好友关系
* */
@ResponseBody
@RequestMapping(value = "/v1/users/{user_id}/friends/{friend_id}", method = RequestMethod.POST)
public Message getFriend(@PathVariable(value = "user_id") Integer userId,
@PathVariable(value = "friend_id") Integer friendId) {
RelationShip relationShip = accountService.getFriendShip(userId,
friendId);
Map<String, Object> data = new LinkedHashMap<String, Object>();
data.put("id", relationShip.getAccount().getId());
data.put("friend_id", relationShip.getFriend().getId());
ShowDataStruct returnData = ShowDataStruct.getDataStruct(null, data);
return Message.successMessage(CommonMessageContent.SAVE_SUCCEED,
returnData);
}
/**
* 取消好友关系
* */
@ResponseBody
@RequestMapping(value = "/v1/users/{user_id}/friends/{friend_id}", method = RequestMethod.DELETE)
public Message deleteFriend(
@PathVariable(value = "user_id") Integer userId,
@PathVariable(value = "friend_id") Integer friendId) {
accountService.deleteFriendShip(userId, friendId);
return Message
.successMessage(CommonMessageContent.DELETE_SUCCEED, null);
}
/**
* 用户验证
* */
@ResponseBody
@RequestMapping(value = "/v1/users/identify/{guid}", method = RequestMethod.GET)
public Message isFriend(@PathVariable(value = "guid") String guid) {
if (accountService.findByGuid(guid) == null)
return Message.failMessage("无此人");
return Message.successMessage(CommonMessageContent.GET_SUCCEED, null);
}
/* 获取好友及动态 */
@ResponseBody
@RequestMapping(value = "/v1/users/actions", method = RequestMethod.GET)
public Message getActions(
@RequestParam(required = false, defaultValue = "10") Integer pagesize,
@RequestParam(required = false, defaultValue = "1") Integer pageno,
HttpServletRequest request) {
Account account = (Account) request.getSession().getAttribute("user");
Pagination page = accountService.listFriendsAction(account.getId(),
pageno, pagesize);
ShowDataStruct returnData = ShowDataStruct.getDataStruct(page,
page.getList());
return Message.successMessage(CommonMessageContent.GET_SUCCEED,
returnData);
}
}
|
package org.yipuran.gsonhelper.array;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
/**
* JsonArrayReader生成ビルダ.
* <PRE>
* (使用例)
*
* GsonBuilder gsonbuilder = new GsonBuilder().serializeNulls()
* .registerTypeAdapter(LocalDateTime.class, LocalDateTimeAdapter.of("yyyy/MM/dd HH:mm:ss"));
*
* JsonArrayParseBuilder.<Item>of(gsonbuilder, TypeToken.get(Item.class).getType())
* .path("group", "itemlist").create()
* .execute(reader, t->{
* // t=配列要素
* });
* </PRE>
* @since 4.12
*/
public final class JsonArrayParseBuilder<T>{
private GsonBuilder gsonbuilder;
private Stream<String> pathstream;
private Type type;
private JsonArrayParseBuilder(GsonBuilder gsonbuilder, Type type) {
this.gsonbuilder = gsonbuilder;
this.type = type;
}
/**
* Type指定インスタンス生成.
* @param gsonbuilder Tクラス解析のGson生成する為のGsonBuilder
* @param type 配列要素 T クラスの java.lang.reflect.Type
* @return
*/
public static <T> JsonArrayParseBuilder<T> of(GsonBuilder gsonbuilder, Type type) {
return new JsonArrayParseBuilder<T>(gsonbuilder, type);
}
/**
* クラス指定インスタンス生成
* @param gsonbuilder Tクラス解析のGson生成する為のGsonBuilder
* @param cls 配列要素 T クラス
* @return
*/
public static <T> JsonArrayParseBuilder<T> of(GsonBuilder gsonbuilder, Class<T> cls) {
return new JsonArrayParseBuilder<T>(gsonbuilder, TypeToken.get(cls).getType());
}
/**
* 解析対象配列までの JSONキーをPATH としてリストで指定
* @param pathlist List
* @return
*/
public JsonArrayParseBuilder<T> path(List<String> pathlist) {
if (pathlist.size() < 1) throw new IllegalArgumentException("path is required!");
pathstream = pathlist.stream();
return this;
}
/**
* 解析対象配列までの JSONキーをPATH として並べる。
* @param path String[]
* @return
*/
public JsonArrayParseBuilder<T> path(String...path) {
if (path.length < 1) throw new IllegalArgumentException("path is required!");
pathstream = Arrays.asList(path).stream();
return this;
}
/**
* JsonArrayReader生成
* @return JsonArrayParser
*/
public JsonArrayParser<T> create() {
String ptn = "^\\$\\." + pathstream
.map(e->e.replaceAll("\\.", "\\."))
.map(e->e.replaceAll("\\[", "\\\\["))
.map(e->e.replaceAll("\\]", "\\\\]"))
.map(e->e.replaceAll("\\-", "\\\\-"))
.map(e->e.replaceAll("\\+", "\\\\+"))
.map(e->e.replaceAll("\\*", "\\\\*"))
.map(e->e.replaceAll("\\$", "\\$"))
.map(e->e.replaceAll("\\^", "\\^"))
.map(e->e.replaceAll("\\?", "\\?"))
.map(e->e.replaceAll("\\{", "\\\\{"))
.map(e->e.replaceAll("\\}", "\\\\}"))
.collect(Collectors.joining("\\."))
+ "\\[\\d+\\]$";
return new JsonArrayParser<>(gsonbuilder, type, ptn);
}
}
|
package com.intraway.error;
import com.intraway.exception.MessageNotFoundException;
import com.intraway.exception.TransactionRefuseException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@ControllerAdvice
public class IntrawayExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(MessageNotFoundException.class)
public void handleMessageNotFound(HttpServletResponse response) throws IOException{
response.sendError(HttpStatus.NOT_FOUND.value());
}
@ExceptionHandler(TransactionRefuseException.class)
public void handleBadInput(HttpServletResponse response) throws IOException{
response.sendError(HttpStatus.BAD_REQUEST.value());
}
}
|
package com.msir.web;
import com.msir.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/FilmNews")
public class NewsController {
@Autowired
public NewsService newsService;
@ResponseBody
@RequestMapping(value = "/MovieListWithOne", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
public Object getMoveList4One() {
return newsService.getMoveList4One();
}
@ResponseBody
@RequestMapping(value = "/MovieDetail/{MovieId}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
public Object getMoveDetail4One(@PathVariable("MovieId") String MovieId) {
return newsService.getMoveDetail4One(MovieId);
}
@ResponseBody
@RequestMapping(value = "/MovieListHistory/{historyId}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
public Object getMoveListHistory4One(@PathVariable("historyId") String historyId) {
return newsService.getMoveListHistory4One(historyId);
}
@ResponseBody
@RequestMapping(value = "/Trailers", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
public Object getTrailerList4EyePetizer() {
return newsService.getTrailerList4EyePetizer();
}
}
|
package listFragmentExample;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.project.project1.R;
/**
* Created by user on 19/04/16.
*/
public class MyCustomListFragment extends ListFragment implements AdapterView.OnItemClickListener {
public String TAG = MyCustomListFragment.this.getClass().getSimpleName();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] arr = getActivity().getResources().getStringArray(R.array.Planets);
MyListAdapter myListAdapter = new MyListAdapter(getActivity(), arr);
setListAdapter(myListAdapter);
getListView().setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick() got called");
}
}
|
package br.com.smarthouse.controledeluzes.persistence;
import org.springframework.data.jpa.repository.JpaRepository;
import br.com.smarthouse.controledeluzes.model.ambiente.Objeto;
public interface ObjetoDAO extends JpaRepository<Objeto, Long> {
}
|
/*
* 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.platform.action;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ListSelectionModel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.qtplaf.library.app.Session;
import com.qtplaf.library.database.Persistor;
import com.qtplaf.library.database.Record;
import com.qtplaf.library.swing.ActionUtils;
import com.qtplaf.library.swing.action.ActionSelectColumns;
import com.qtplaf.library.swing.core.JOptionFrame;
import com.qtplaf.library.swing.core.JPanelTableRecord;
import com.qtplaf.library.swing.core.JTableRecord;
import com.qtplaf.library.swing.core.TableModelRecord;
import com.qtplaf.library.trading.server.Server;
import com.qtplaf.platform.LaunchArgs;
import com.qtplaf.platform.database.Fields;
import com.qtplaf.platform.util.PersistorUtils;
import com.qtplaf.platform.util.RecordSetUtils;
/**
* Shows the list of available instruments for the server set as launch argument.
*
* @author Miquel Sas
*/
public class ActionAvailableInstruments extends AbstractAction {
/** Logger instance. */
private static final Logger LOGGER = LogManager.getLogger();
/**
* Action to close the frame.
*/
class ActionClose extends AbstractAction {
/**
* Constructor.
*
* @param session The working session.
*/
public ActionClose(Session session) {
super();
ActionUtils.configureClose(session, this);
ActionUtils.setDefaultCloseAction(this, true);
}
/**
* Perform the action.
*/
@Override
public void actionPerformed(ActionEvent e) {
JOptionFrame frame = (JOptionFrame) ActionUtils.getUserObject(this);
frame.setVisible(false);
frame.dispose();
}
}
/**
* Runnable to launch it in a thread.
*/
class RunAction implements Runnable {
@Override
public void run() {
try {
Session session = ActionUtils.getSession(ActionAvailableInstruments.this);
Server server = LaunchArgs.getServer(ActionAvailableInstruments.this);
Persistor persistor = PersistorUtils.getPersistorInstruments(session);
Record masterRecord = persistor.getDefaultRecord();
JTableRecord tableRecord = new JTableRecord(session, ListSelectionModel.SINGLE_SELECTION);
JPanelTableRecord panelTableRecord = new JPanelTableRecord(tableRecord);
TableModelRecord tableModelRecord = new TableModelRecord(session, masterRecord);
tableModelRecord.addColumn(Fields.INSTRUMENT_ID);
tableModelRecord.addColumn(Fields.INSTRUMENT_DESC);
tableModelRecord.addColumn(Fields.INSTRUMENT_PIP_VALUE);
tableModelRecord.addColumn(Fields.INSTRUMENT_PIP_SCALE);
tableModelRecord.addColumn(Fields.INSTRUMENT_TICK_VALUE);
tableModelRecord.addColumn(Fields.INSTRUMENT_TICK_SCALE);
tableModelRecord.addColumn(Fields.INSTRUMENT_VOLUME_SCALE);
tableModelRecord.addColumn(Fields.INSTRUMENT_PRIMARY_CURRENCY);
tableModelRecord.addColumn(Fields.INSTRUMENT_SECONDARY_CURRENCY);
tableModelRecord.setRecordSet(RecordSetUtils.getRecordSetAvailableInstruments(session, server));
tableRecord.setModel(tableModelRecord);
JOptionFrame frame = new JOptionFrame(session);
frame.setTitle(server.getName() + " " + session.getString("qtMenuServersAvInst").toLowerCase());
frame.setComponent(panelTableRecord);
frame.addAction(new ActionClose(session));
frame.addAction(new ActionSelectColumns(tableRecord));
frame.setSize(0.6, 0.8);
frame.showFrame();
} catch (Exception exc) {
LOGGER.catching(exc);
}
}
}
/**
* Constructor.
*/
public ActionAvailableInstruments() {
super();
}
/**
* Perform the action.
*/
@Override
public void actionPerformed(ActionEvent e) {
new Thread(new RunAction()).start();
}
}
|
package com.example.ticktick;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.ticktick.ViewHolders.LendingViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class LendingListActivity extends AppCompatActivity {
private RecyclerView recylerView;
private RecyclerView.LayoutManager layoutManager;
private Button addLendingRedirectBtn, checkBalanceBtn;
private TextView txtTotalAmount;
private int totalPrice = 0;
public String key="", loanTotal = "", lendingTotal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lending_list);
lendingTotal = getIntent().getStringExtra("lendingTotal");
loanTotal = getIntent().getStringExtra("loanTotal");
recylerView = (RecyclerView) findViewById(R.id.lendingList);
recylerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recylerView.setLayoutManager(layoutManager);
addLendingRedirectBtn = (Button) findViewById(R.id.addLendingRedirectBtn);
checkBalanceBtn = (Button) findViewById(R.id.checkBalanceBtn);
txtTotalAmount = (TextView) findViewById(R.id.lendingTotalTxt);
addLendingRedirectBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(LendingListActivity.this, AddLendingActivity.class);
startActivity(intent);
}
});
final DatabaseReference lendingListRef = FirebaseDatabase.getInstance().getReference();
FirebaseRecyclerOptions<com.example.ticktick.model.LendingInfo> options =
new FirebaseRecyclerOptions.Builder<com.example.ticktick.model.LendingInfo>()
.setQuery(lendingListRef
.child("Lendings"), com.example.ticktick.model.LendingInfo.class)
.build();
FirebaseRecyclerAdapter<com.example.ticktick.model.LendingInfo, LendingViewHolder> adapter
= new FirebaseRecyclerAdapter<com.example.ticktick.model.LendingInfo, LendingViewHolder>(options)
{
@Override
protected void onBindViewHolder(@NonNull LendingViewHolder holder, int position, @NonNull final com.example.ticktick.model.LendingInfo model)
{
// Retrieving data from Firebase to the recyclerview
holder.txtLendingDate.setText("Date: " + model.getDate());
holder.txtLendingName.setText("Name: " + model.getName());
holder.txtLendingAmount.setText("Amount: Rs. " + model.getAmount());
// Calculating and Displaying the total amount
int oneTypeProductTotalPrice = (((Integer.valueOf(model.getAmount()))));
totalPrice = totalPrice + oneTypeProductTotalPrice;
txtTotalAmount.setText("Total Amount : Rs. " + String.valueOf(totalPrice));
// OnClick Options Function
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
CharSequence options[] = new CharSequence[]
{
"Edit"
};
AlertDialog.Builder builder = new AlertDialog.Builder(LendingListActivity.this);
builder.setTitle("Options: ");
builder.setItems(options, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
if(i==0)
{
Intent intent = new Intent(LendingListActivity.this, UpdateLendingActivity.class);
key = lendingListRef.push().getKey();
intent.putExtra("lendingID", model.getLendingID());
intent.putExtra("loanTotal", loanTotal);
intent.putExtra("lendingTotal", String.valueOf(totalPrice));
startActivity(intent);
}
}
});
builder.show();
}
});
}
@NonNull
@Override
public LendingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.lending_items_layout, parent, false);
LendingViewHolder holder = new LendingViewHolder(view);
return holder;
}
};
checkBalanceBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(LendingListActivity.this, FinalActivity.class);
intent.putExtra("lendingTotal", String.valueOf(totalPrice));
intent.putExtra("loanTotal", loanTotal);
startActivity(intent);
}
});
recylerView.setAdapter(adapter);
adapter.startListening();
}
}
|
package com.onplan.persistence;
import com.onplan.domain.persistent.SystemEventHistory;
public interface SystemEventHistoryDao extends GenericDao<SystemEventHistory> {
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.math.BigDecimal;
import java.util.Date;
/**
* TvTaskPartId generated by hbm2java
*/
public class TvTaskPartId implements java.io.Serializable {
private String taskuid;
private String partNumber;
private BigDecimal qtyreq;
private Long reqtype;
private BigDecimal allocatedqty;
private Byte isineffect;
private Date createtime;
private String creator;
private BigDecimal singlein;
private BigDecimal singleout;
private String uniqueId;
private Date satisfydate;
private String notes;
private BigDecimal preassQty;
private String preassEmp;
private Date preassDate;
private String warehouseid;
private BigDecimal applyQty;
private String prepareEmployeeid;
private String prepareWarehouseid;
private Byte prepareState;
private long preassLevel;
private String partName;
private String partDescription;
private String drawingid;
private String productDept;
private Byte toolchecklevel;
private String partNumberType;
private Long prepareLeadTime;
private String prepareEmployeename;
private String prepareWarehousename;
private String taskid;
private String taskname;
private String model;
private String batchnum;
private String taskPartNumber;
private String tasktype;
private String mastershop;
private BigDecimal taskstate;
private Date planstart;
private Integer materialstate;
private Byte suspended;
private String preassEmpname;
private String warehousename;
private BigDecimal pretreatqty;
private String productDeptName;
private String toolcheckleveldesc1;
private String toolcheckleveldesc;
private String taskDrawingid;
private String taskPartName;
public TvTaskPartId() {
}
public TvTaskPartId(String taskuid, String partNumber, String uniqueId, long preassLevel, String taskPartNumber) {
this.taskuid = taskuid;
this.partNumber = partNumber;
this.uniqueId = uniqueId;
this.preassLevel = preassLevel;
this.taskPartNumber = taskPartNumber;
}
public TvTaskPartId(String taskuid, String partNumber, BigDecimal qtyreq, Long reqtype, BigDecimal allocatedqty,
Byte isineffect, Date createtime, String creator, BigDecimal singlein, BigDecimal singleout,
String uniqueId, Date satisfydate, String notes, BigDecimal preassQty, String preassEmp, Date preassDate,
String warehouseid, BigDecimal applyQty, String prepareEmployeeid, String prepareWarehouseid,
Byte prepareState, long preassLevel, String partName, String partDescription, String drawingid,
String productDept, Byte toolchecklevel, String partNumberType, Long prepareLeadTime,
String prepareEmployeename, String prepareWarehousename, String taskid, String taskname, String model,
String batchnum, String taskPartNumber, String tasktype, String mastershop, BigDecimal taskstate,
Date planstart, Integer materialstate, Byte suspended, String preassEmpname, String warehousename,
BigDecimal pretreatqty, String productDeptName, String toolcheckleveldesc1, String toolcheckleveldesc,
String taskDrawingid, String taskPartName) {
this.taskuid = taskuid;
this.partNumber = partNumber;
this.qtyreq = qtyreq;
this.reqtype = reqtype;
this.allocatedqty = allocatedqty;
this.isineffect = isineffect;
this.createtime = createtime;
this.creator = creator;
this.singlein = singlein;
this.singleout = singleout;
this.uniqueId = uniqueId;
this.satisfydate = satisfydate;
this.notes = notes;
this.preassQty = preassQty;
this.preassEmp = preassEmp;
this.preassDate = preassDate;
this.warehouseid = warehouseid;
this.applyQty = applyQty;
this.prepareEmployeeid = prepareEmployeeid;
this.prepareWarehouseid = prepareWarehouseid;
this.prepareState = prepareState;
this.preassLevel = preassLevel;
this.partName = partName;
this.partDescription = partDescription;
this.drawingid = drawingid;
this.productDept = productDept;
this.toolchecklevel = toolchecklevel;
this.partNumberType = partNumberType;
this.prepareLeadTime = prepareLeadTime;
this.prepareEmployeename = prepareEmployeename;
this.prepareWarehousename = prepareWarehousename;
this.taskid = taskid;
this.taskname = taskname;
this.model = model;
this.batchnum = batchnum;
this.taskPartNumber = taskPartNumber;
this.tasktype = tasktype;
this.mastershop = mastershop;
this.taskstate = taskstate;
this.planstart = planstart;
this.materialstate = materialstate;
this.suspended = suspended;
this.preassEmpname = preassEmpname;
this.warehousename = warehousename;
this.pretreatqty = pretreatqty;
this.productDeptName = productDeptName;
this.toolcheckleveldesc1 = toolcheckleveldesc1;
this.toolcheckleveldesc = toolcheckleveldesc;
this.taskDrawingid = taskDrawingid;
this.taskPartName = taskPartName;
}
public String getTaskuid() {
return this.taskuid;
}
public void setTaskuid(String taskuid) {
this.taskuid = taskuid;
}
public String getPartNumber() {
return this.partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public BigDecimal getQtyreq() {
return this.qtyreq;
}
public void setQtyreq(BigDecimal qtyreq) {
this.qtyreq = qtyreq;
}
public Long getReqtype() {
return this.reqtype;
}
public void setReqtype(Long reqtype) {
this.reqtype = reqtype;
}
public BigDecimal getAllocatedqty() {
return this.allocatedqty;
}
public void setAllocatedqty(BigDecimal allocatedqty) {
this.allocatedqty = allocatedqty;
}
public Byte getIsineffect() {
return this.isineffect;
}
public void setIsineffect(Byte isineffect) {
this.isineffect = isineffect;
}
public Date getCreatetime() {
return this.createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getCreator() {
return this.creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public BigDecimal getSinglein() {
return this.singlein;
}
public void setSinglein(BigDecimal singlein) {
this.singlein = singlein;
}
public BigDecimal getSingleout() {
return this.singleout;
}
public void setSingleout(BigDecimal singleout) {
this.singleout = singleout;
}
public String getUniqueId() {
return this.uniqueId;
}
public void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId;
}
public Date getSatisfydate() {
return this.satisfydate;
}
public void setSatisfydate(Date satisfydate) {
this.satisfydate = satisfydate;
}
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public BigDecimal getPreassQty() {
return this.preassQty;
}
public void setPreassQty(BigDecimal preassQty) {
this.preassQty = preassQty;
}
public String getPreassEmp() {
return this.preassEmp;
}
public void setPreassEmp(String preassEmp) {
this.preassEmp = preassEmp;
}
public Date getPreassDate() {
return this.preassDate;
}
public void setPreassDate(Date preassDate) {
this.preassDate = preassDate;
}
public String getWarehouseid() {
return this.warehouseid;
}
public void setWarehouseid(String warehouseid) {
this.warehouseid = warehouseid;
}
public BigDecimal getApplyQty() {
return this.applyQty;
}
public void setApplyQty(BigDecimal applyQty) {
this.applyQty = applyQty;
}
public String getPrepareEmployeeid() {
return this.prepareEmployeeid;
}
public void setPrepareEmployeeid(String prepareEmployeeid) {
this.prepareEmployeeid = prepareEmployeeid;
}
public String getPrepareWarehouseid() {
return this.prepareWarehouseid;
}
public void setPrepareWarehouseid(String prepareWarehouseid) {
this.prepareWarehouseid = prepareWarehouseid;
}
public Byte getPrepareState() {
return this.prepareState;
}
public void setPrepareState(Byte prepareState) {
this.prepareState = prepareState;
}
public long getPreassLevel() {
return this.preassLevel;
}
public void setPreassLevel(long preassLevel) {
this.preassLevel = preassLevel;
}
public String getPartName() {
return this.partName;
}
public void setPartName(String partName) {
this.partName = partName;
}
public String getPartDescription() {
return this.partDescription;
}
public void setPartDescription(String partDescription) {
this.partDescription = partDescription;
}
public String getDrawingid() {
return this.drawingid;
}
public void setDrawingid(String drawingid) {
this.drawingid = drawingid;
}
public String getProductDept() {
return this.productDept;
}
public void setProductDept(String productDept) {
this.productDept = productDept;
}
public Byte getToolchecklevel() {
return this.toolchecklevel;
}
public void setToolchecklevel(Byte toolchecklevel) {
this.toolchecklevel = toolchecklevel;
}
public String getPartNumberType() {
return this.partNumberType;
}
public void setPartNumberType(String partNumberType) {
this.partNumberType = partNumberType;
}
public Long getPrepareLeadTime() {
return this.prepareLeadTime;
}
public void setPrepareLeadTime(Long prepareLeadTime) {
this.prepareLeadTime = prepareLeadTime;
}
public String getPrepareEmployeename() {
return this.prepareEmployeename;
}
public void setPrepareEmployeename(String prepareEmployeename) {
this.prepareEmployeename = prepareEmployeename;
}
public String getPrepareWarehousename() {
return this.prepareWarehousename;
}
public void setPrepareWarehousename(String prepareWarehousename) {
this.prepareWarehousename = prepareWarehousename;
}
public String getTaskid() {
return this.taskid;
}
public void setTaskid(String taskid) {
this.taskid = taskid;
}
public String getTaskname() {
return this.taskname;
}
public void setTaskname(String taskname) {
this.taskname = taskname;
}
public String getModel() {
return this.model;
}
public void setModel(String model) {
this.model = model;
}
public String getBatchnum() {
return this.batchnum;
}
public void setBatchnum(String batchnum) {
this.batchnum = batchnum;
}
public String getTaskPartNumber() {
return this.taskPartNumber;
}
public void setTaskPartNumber(String taskPartNumber) {
this.taskPartNumber = taskPartNumber;
}
public String getTasktype() {
return this.tasktype;
}
public void setTasktype(String tasktype) {
this.tasktype = tasktype;
}
public String getMastershop() {
return this.mastershop;
}
public void setMastershop(String mastershop) {
this.mastershop = mastershop;
}
public BigDecimal getTaskstate() {
return this.taskstate;
}
public void setTaskstate(BigDecimal taskstate) {
this.taskstate = taskstate;
}
public Date getPlanstart() {
return this.planstart;
}
public void setPlanstart(Date planstart) {
this.planstart = planstart;
}
public Integer getMaterialstate() {
return this.materialstate;
}
public void setMaterialstate(Integer materialstate) {
this.materialstate = materialstate;
}
public Byte getSuspended() {
return this.suspended;
}
public void setSuspended(Byte suspended) {
this.suspended = suspended;
}
public String getPreassEmpname() {
return this.preassEmpname;
}
public void setPreassEmpname(String preassEmpname) {
this.preassEmpname = preassEmpname;
}
public String getWarehousename() {
return this.warehousename;
}
public void setWarehousename(String warehousename) {
this.warehousename = warehousename;
}
public BigDecimal getPretreatqty() {
return this.pretreatqty;
}
public void setPretreatqty(BigDecimal pretreatqty) {
this.pretreatqty = pretreatqty;
}
public String getProductDeptName() {
return this.productDeptName;
}
public void setProductDeptName(String productDeptName) {
this.productDeptName = productDeptName;
}
public String getToolcheckleveldesc1() {
return this.toolcheckleveldesc1;
}
public void setToolcheckleveldesc1(String toolcheckleveldesc1) {
this.toolcheckleveldesc1 = toolcheckleveldesc1;
}
public String getToolcheckleveldesc() {
return this.toolcheckleveldesc;
}
public void setToolcheckleveldesc(String toolcheckleveldesc) {
this.toolcheckleveldesc = toolcheckleveldesc;
}
public String getTaskDrawingid() {
return this.taskDrawingid;
}
public void setTaskDrawingid(String taskDrawingid) {
this.taskDrawingid = taskDrawingid;
}
public String getTaskPartName() {
return this.taskPartName;
}
public void setTaskPartName(String taskPartName) {
this.taskPartName = taskPartName;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof TvTaskPartId))
return false;
TvTaskPartId castOther = (TvTaskPartId) other;
return ((this.getTaskuid() == castOther.getTaskuid()) || (this.getTaskuid() != null
&& castOther.getTaskuid() != null && this.getTaskuid().equals(castOther.getTaskuid())))
&& ((this.getPartNumber() == castOther.getPartNumber()) || (this.getPartNumber() != null
&& castOther.getPartNumber() != null && this.getPartNumber().equals(castOther.getPartNumber())))
&& ((this.getQtyreq() == castOther.getQtyreq()) || (this.getQtyreq() != null
&& castOther.getQtyreq() != null && this.getQtyreq().equals(castOther.getQtyreq())))
&& ((this.getReqtype() == castOther.getReqtype()) || (this.getReqtype() != null
&& castOther.getReqtype() != null && this.getReqtype().equals(castOther.getReqtype())))
&& ((this.getAllocatedqty() == castOther.getAllocatedqty())
|| (this.getAllocatedqty() != null && castOther.getAllocatedqty() != null
&& this.getAllocatedqty().equals(castOther.getAllocatedqty())))
&& ((this.getIsineffect() == castOther.getIsineffect()) || (this.getIsineffect() != null
&& castOther.getIsineffect() != null && this.getIsineffect().equals(castOther.getIsineffect())))
&& ((this.getCreatetime() == castOther.getCreatetime()) || (this.getCreatetime() != null
&& castOther.getCreatetime() != null && this.getCreatetime().equals(castOther.getCreatetime())))
&& ((this.getCreator() == castOther.getCreator()) || (this.getCreator() != null
&& castOther.getCreator() != null && this.getCreator().equals(castOther.getCreator())))
&& ((this.getSinglein() == castOther.getSinglein()) || (this.getSinglein() != null
&& castOther.getSinglein() != null && this.getSinglein().equals(castOther.getSinglein())))
&& ((this.getSingleout() == castOther.getSingleout()) || (this.getSingleout() != null
&& castOther.getSingleout() != null && this.getSingleout().equals(castOther.getSingleout())))
&& ((this.getUniqueId() == castOther.getUniqueId()) || (this.getUniqueId() != null
&& castOther.getUniqueId() != null && this.getUniqueId().equals(castOther.getUniqueId())))
&& ((this.getSatisfydate() == castOther.getSatisfydate())
|| (this.getSatisfydate() != null && castOther.getSatisfydate() != null
&& this.getSatisfydate().equals(castOther.getSatisfydate())))
&& ((this.getNotes() == castOther.getNotes()) || (this.getNotes() != null
&& castOther.getNotes() != null && this.getNotes().equals(castOther.getNotes())))
&& ((this.getPreassQty() == castOther.getPreassQty()) || (this.getPreassQty() != null
&& castOther.getPreassQty() != null && this.getPreassQty().equals(castOther.getPreassQty())))
&& ((this.getPreassEmp() == castOther.getPreassEmp()) || (this.getPreassEmp() != null
&& castOther.getPreassEmp() != null && this.getPreassEmp().equals(castOther.getPreassEmp())))
&& ((this.getPreassDate() == castOther.getPreassDate()) || (this.getPreassDate() != null
&& castOther.getPreassDate() != null && this.getPreassDate().equals(castOther.getPreassDate())))
&& ((this.getWarehouseid() == castOther.getWarehouseid())
|| (this.getWarehouseid() != null && castOther.getWarehouseid() != null
&& this.getWarehouseid().equals(castOther.getWarehouseid())))
&& ((this.getApplyQty() == castOther.getApplyQty()) || (this.getApplyQty() != null
&& castOther.getApplyQty() != null && this.getApplyQty().equals(castOther.getApplyQty())))
&& ((this.getPrepareEmployeeid() == castOther.getPrepareEmployeeid())
|| (this.getPrepareEmployeeid() != null && castOther.getPrepareEmployeeid() != null
&& this.getPrepareEmployeeid().equals(castOther.getPrepareEmployeeid())))
&& ((this.getPrepareWarehouseid() == castOther.getPrepareWarehouseid())
|| (this.getPrepareWarehouseid() != null && castOther.getPrepareWarehouseid() != null
&& this.getPrepareWarehouseid().equals(castOther.getPrepareWarehouseid())))
&& ((this.getPrepareState() == castOther.getPrepareState())
|| (this.getPrepareState() != null && castOther.getPrepareState() != null
&& this.getPrepareState().equals(castOther.getPrepareState())))
&& (this.getPreassLevel() == castOther.getPreassLevel())
&& ((this.getPartName() == castOther.getPartName()) || (this.getPartName() != null
&& castOther.getPartName() != null && this.getPartName().equals(castOther.getPartName())))
&& ((this.getPartDescription() == castOther.getPartDescription())
|| (this.getPartDescription() != null && castOther.getPartDescription() != null
&& this.getPartDescription().equals(castOther.getPartDescription())))
&& ((this.getDrawingid() == castOther.getDrawingid()) || (this.getDrawingid() != null
&& castOther.getDrawingid() != null && this.getDrawingid().equals(castOther.getDrawingid())))
&& ((this.getProductDept() == castOther.getProductDept())
|| (this.getProductDept() != null && castOther.getProductDept() != null
&& this.getProductDept().equals(castOther.getProductDept())))
&& ((this.getToolchecklevel() == castOther.getToolchecklevel())
|| (this.getToolchecklevel() != null && castOther.getToolchecklevel() != null
&& this.getToolchecklevel().equals(castOther.getToolchecklevel())))
&& ((this.getPartNumberType() == castOther.getPartNumberType())
|| (this.getPartNumberType() != null && castOther.getPartNumberType() != null
&& this.getPartNumberType().equals(castOther.getPartNumberType())))
&& ((this.getPrepareLeadTime() == castOther.getPrepareLeadTime())
|| (this.getPrepareLeadTime() != null && castOther.getPrepareLeadTime() != null
&& this.getPrepareLeadTime().equals(castOther.getPrepareLeadTime())))
&& ((this.getPrepareEmployeename() == castOther.getPrepareEmployeename())
|| (this.getPrepareEmployeename() != null && castOther.getPrepareEmployeename() != null
&& this.getPrepareEmployeename().equals(castOther.getPrepareEmployeename())))
&& ((this.getPrepareWarehousename() == castOther.getPrepareWarehousename())
|| (this.getPrepareWarehousename() != null && castOther.getPrepareWarehousename() != null
&& this.getPrepareWarehousename().equals(castOther.getPrepareWarehousename())))
&& ((this.getTaskid() == castOther.getTaskid()) || (this.getTaskid() != null
&& castOther.getTaskid() != null && this.getTaskid().equals(castOther.getTaskid())))
&& ((this.getTaskname() == castOther.getTaskname()) || (this.getTaskname() != null
&& castOther.getTaskname() != null && this.getTaskname().equals(castOther.getTaskname())))
&& ((this.getModel() == castOther.getModel()) || (this.getModel() != null
&& castOther.getModel() != null && this.getModel().equals(castOther.getModel())))
&& ((this.getBatchnum() == castOther.getBatchnum()) || (this.getBatchnum() != null
&& castOther.getBatchnum() != null && this.getBatchnum().equals(castOther.getBatchnum())))
&& ((this.getTaskPartNumber() == castOther.getTaskPartNumber())
|| (this.getTaskPartNumber() != null && castOther.getTaskPartNumber() != null
&& this.getTaskPartNumber().equals(castOther.getTaskPartNumber())))
&& ((this.getTasktype() == castOther.getTasktype()) || (this.getTasktype() != null
&& castOther.getTasktype() != null && this.getTasktype().equals(castOther.getTasktype())))
&& ((this.getMastershop() == castOther.getMastershop()) || (this.getMastershop() != null
&& castOther.getMastershop() != null && this.getMastershop().equals(castOther.getMastershop())))
&& ((this.getTaskstate() == castOther.getTaskstate()) || (this.getTaskstate() != null
&& castOther.getTaskstate() != null && this.getTaskstate().equals(castOther.getTaskstate())))
&& ((this.getPlanstart() == castOther.getPlanstart()) || (this.getPlanstart() != null
&& castOther.getPlanstart() != null && this.getPlanstart().equals(castOther.getPlanstart())))
&& ((this.getMaterialstate() == castOther.getMaterialstate())
|| (this.getMaterialstate() != null && castOther.getMaterialstate() != null
&& this.getMaterialstate().equals(castOther.getMaterialstate())))
&& ((this.getSuspended() == castOther.getSuspended()) || (this.getSuspended() != null
&& castOther.getSuspended() != null && this.getSuspended().equals(castOther.getSuspended())))
&& ((this.getPreassEmpname() == castOther.getPreassEmpname())
|| (this.getPreassEmpname() != null && castOther.getPreassEmpname() != null
&& this.getPreassEmpname().equals(castOther.getPreassEmpname())))
&& ((this.getWarehousename() == castOther.getWarehousename())
|| (this.getWarehousename() != null && castOther.getWarehousename() != null
&& this.getWarehousename().equals(castOther.getWarehousename())))
&& ((this.getPretreatqty() == castOther.getPretreatqty())
|| (this.getPretreatqty() != null && castOther.getPretreatqty() != null
&& this.getPretreatqty().equals(castOther.getPretreatqty())))
&& ((this.getProductDeptName() == castOther.getProductDeptName())
|| (this.getProductDeptName() != null && castOther.getProductDeptName() != null
&& this.getProductDeptName().equals(castOther.getProductDeptName())))
&& ((this.getToolcheckleveldesc1() == castOther.getToolcheckleveldesc1())
|| (this.getToolcheckleveldesc1() != null && castOther.getToolcheckleveldesc1() != null
&& this.getToolcheckleveldesc1().equals(castOther.getToolcheckleveldesc1())))
&& ((this.getToolcheckleveldesc() == castOther.getToolcheckleveldesc())
|| (this.getToolcheckleveldesc() != null && castOther.getToolcheckleveldesc() != null
&& this.getToolcheckleveldesc().equals(castOther.getToolcheckleveldesc())))
&& ((this.getTaskDrawingid() == castOther.getTaskDrawingid())
|| (this.getTaskDrawingid() != null && castOther.getTaskDrawingid() != null
&& this.getTaskDrawingid().equals(castOther.getTaskDrawingid())))
&& ((this.getTaskPartName() == castOther.getTaskPartName())
|| (this.getTaskPartName() != null && castOther.getTaskPartName() != null
&& this.getTaskPartName().equals(castOther.getTaskPartName())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getTaskuid() == null ? 0 : this.getTaskuid().hashCode());
result = 37 * result + (getPartNumber() == null ? 0 : this.getPartNumber().hashCode());
result = 37 * result + (getQtyreq() == null ? 0 : this.getQtyreq().hashCode());
result = 37 * result + (getReqtype() == null ? 0 : this.getReqtype().hashCode());
result = 37 * result + (getAllocatedqty() == null ? 0 : this.getAllocatedqty().hashCode());
result = 37 * result + (getIsineffect() == null ? 0 : this.getIsineffect().hashCode());
result = 37 * result + (getCreatetime() == null ? 0 : this.getCreatetime().hashCode());
result = 37 * result + (getCreator() == null ? 0 : this.getCreator().hashCode());
result = 37 * result + (getSinglein() == null ? 0 : this.getSinglein().hashCode());
result = 37 * result + (getSingleout() == null ? 0 : this.getSingleout().hashCode());
result = 37 * result + (getUniqueId() == null ? 0 : this.getUniqueId().hashCode());
result = 37 * result + (getSatisfydate() == null ? 0 : this.getSatisfydate().hashCode());
result = 37 * result + (getNotes() == null ? 0 : this.getNotes().hashCode());
result = 37 * result + (getPreassQty() == null ? 0 : this.getPreassQty().hashCode());
result = 37 * result + (getPreassEmp() == null ? 0 : this.getPreassEmp().hashCode());
result = 37 * result + (getPreassDate() == null ? 0 : this.getPreassDate().hashCode());
result = 37 * result + (getWarehouseid() == null ? 0 : this.getWarehouseid().hashCode());
result = 37 * result + (getApplyQty() == null ? 0 : this.getApplyQty().hashCode());
result = 37 * result + (getPrepareEmployeeid() == null ? 0 : this.getPrepareEmployeeid().hashCode());
result = 37 * result + (getPrepareWarehouseid() == null ? 0 : this.getPrepareWarehouseid().hashCode());
result = 37 * result + (getPrepareState() == null ? 0 : this.getPrepareState().hashCode());
result = 37 * result + (int) this.getPreassLevel();
result = 37 * result + (getPartName() == null ? 0 : this.getPartName().hashCode());
result = 37 * result + (getPartDescription() == null ? 0 : this.getPartDescription().hashCode());
result = 37 * result + (getDrawingid() == null ? 0 : this.getDrawingid().hashCode());
result = 37 * result + (getProductDept() == null ? 0 : this.getProductDept().hashCode());
result = 37 * result + (getToolchecklevel() == null ? 0 : this.getToolchecklevel().hashCode());
result = 37 * result + (getPartNumberType() == null ? 0 : this.getPartNumberType().hashCode());
result = 37 * result + (getPrepareLeadTime() == null ? 0 : this.getPrepareLeadTime().hashCode());
result = 37 * result + (getPrepareEmployeename() == null ? 0 : this.getPrepareEmployeename().hashCode());
result = 37 * result + (getPrepareWarehousename() == null ? 0 : this.getPrepareWarehousename().hashCode());
result = 37 * result + (getTaskid() == null ? 0 : this.getTaskid().hashCode());
result = 37 * result + (getTaskname() == null ? 0 : this.getTaskname().hashCode());
result = 37 * result + (getModel() == null ? 0 : this.getModel().hashCode());
result = 37 * result + (getBatchnum() == null ? 0 : this.getBatchnum().hashCode());
result = 37 * result + (getTaskPartNumber() == null ? 0 : this.getTaskPartNumber().hashCode());
result = 37 * result + (getTasktype() == null ? 0 : this.getTasktype().hashCode());
result = 37 * result + (getMastershop() == null ? 0 : this.getMastershop().hashCode());
result = 37 * result + (getTaskstate() == null ? 0 : this.getTaskstate().hashCode());
result = 37 * result + (getPlanstart() == null ? 0 : this.getPlanstart().hashCode());
result = 37 * result + (getMaterialstate() == null ? 0 : this.getMaterialstate().hashCode());
result = 37 * result + (getSuspended() == null ? 0 : this.getSuspended().hashCode());
result = 37 * result + (getPreassEmpname() == null ? 0 : this.getPreassEmpname().hashCode());
result = 37 * result + (getWarehousename() == null ? 0 : this.getWarehousename().hashCode());
result = 37 * result + (getPretreatqty() == null ? 0 : this.getPretreatqty().hashCode());
result = 37 * result + (getProductDeptName() == null ? 0 : this.getProductDeptName().hashCode());
result = 37 * result + (getToolcheckleveldesc1() == null ? 0 : this.getToolcheckleveldesc1().hashCode());
result = 37 * result + (getToolcheckleveldesc() == null ? 0 : this.getToolcheckleveldesc().hashCode());
result = 37 * result + (getTaskDrawingid() == null ? 0 : this.getTaskDrawingid().hashCode());
result = 37 * result + (getTaskPartName() == null ? 0 : this.getTaskPartName().hashCode());
return result;
}
}
|
package com.conglomerate.dev.models.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
import lombok.Value;
@Value
@Builder
@AllArgsConstructor
public class AddUserDomain {
String email;
String passwordHash;
String userName;
public AddUserDomain() {
this.email = "";
this.passwordHash = "";
this.userName = "";
}
}
|
package com.objectrecogniser.listeners;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.util.Log;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import com.objectrecogniser.callbacks.SimpleCallback;
import com.objectrecogniser.helpers.SingletonHashMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
/**
* Created by aishwaryagm on 6/30/18.
*/
public class ImageEventListener implements ValueEventListener {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Object databaseSnapshot = dataSnapshot.getValue();
if (databaseSnapshot == null) {
return;
}
Log.i("INFO", String.format("Database snapshot : %s", databaseSnapshot));
HashMap<Object, Object> databaseHM = (HashMap<Object, Object>) databaseSnapshot;
Log.i("INFO", String.format("Database hash Map %s", databaseHM));
Set<Object> keys = databaseHM.keySet();
Object key = keys.iterator().next();
Log.i("INFO", String.format("First key element %s", key));
HashMap<String, SimpleCallback> singletonHashMap = SingletonHashMap.getHashMap();
Log.i("INFO", String.format("singletonHashMap %s ", singletonHashMap));
SimpleCallback callBackInterfaceObject = singletonHashMap.get(key.toString());
HashMap<Object, Object> visionDataHM = (HashMap<Object, Object>) databaseHM.get(key);
Log.i("INFO", String.format("visionDataHM %s", visionDataHM));
Set<Object> visiondataHMkeys = visionDataHM.keySet();
Object visiondataKey = visiondataHMkeys.iterator().next();
HashMap<Object, Object> visionData = (HashMap<Object, Object>) visionDataHM.get(visiondataKey);
List<Object> labelAnnotations = (ArrayList<Object>) visionData.get("labelAnnotations");
Log.i("INFO", String.format("labelAnnotations : %s", labelAnnotations));
List<String> descriptions = new ArrayList<>();
for (Object labelAnnotation : labelAnnotations) {
HashMap<Object, Object> labelAnnotationHM = (HashMap<Object, Object>) labelAnnotation;
String description = labelAnnotationHM.get("description").toString();
descriptions.add(description);
}
Log.i("INFO", String.format("Descrptions : %s", descriptions));
String[] imageDescriptionArray = new String[descriptions.size()];
int count = 0;
for (Object description : descriptions) {
imageDescriptionArray[count++] = description.toString();
}
Log.i("INFO", String.format("ImageDescription %s", Arrays.toString(imageDescriptionArray)));
Log.i("INFO", String.format("Label annotations data %s", labelAnnotations));
if (callBackInterfaceObject != null) {
Log.i("INFO", "About to call update on the call back object");
callBackInterfaceObject.updateUserInterface(imageDescriptionArray);
} else {
Log.i("INFO", String.format("Callback Interface object is null %s", callBackInterfaceObject));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e("ERROR", String.format("Image Ref database error : %s", databaseError.getMessage()));
databaseError.toException().printStackTrace();
}
}
|
package com.darichey.blockgame.world;
import com.badlogic.gdx.math.Vector2;
import com.darichey.blockgame.entity.block.Block;
import com.darichey.blockgame.entity.dynamic.DynamicEntity;
import com.darichey.blockgame.entity.dynamic.EntityPlayer;
import com.darichey.blockgame.world.chunk.Chunk;
import com.darichey.blockgame.util.PerlinNoise;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
/**
* Contains all of the entities and other game objects that the player can interact with.
*/
public class World {
/**
* The gravity of this world.
*/
public static final int GRAVITY_VELOCITY = 25;
public static final int LOAD_RADIUS = 2;
/**
* A hashmap of the {@link Chunk}s that make up the world. The Integer key is the x-position of the chunk in the world.
*/
private HashMap<Integer, Chunk> chunks = new HashMap<Integer, Chunk>();
/**
* A list of {@link DynamicEntity}s in the world.
*/
private ArrayList<DynamicEntity> dynamicEntities = new ArrayList<DynamicEntity>();
/**
* The {@link EntityPlayer} in the world.
*/
public EntityPlayer player = (EntityPlayer) spawnEntityAt(new EntityPlayer(), new Vector2(0, 5));
public PerlinNoise noise = new PerlinNoise(new Random().nextLong());
public World() {
for (int i = -2; i < 2; i++) {
addChunk(new Chunk(noise, i));
}
/*
for (int x = -32; x < 32; x++) {
int columnHeight = noise.getNoise(x, 256);
for (int y = 0; y < columnHeight; y++) {
Block block;
if (y < columnHeight - 5) {
block = Blocks.stone;
} else if (y == columnHeight - 1) {
block = Blocks.grass;
} else {
block = Blocks.dirt;
}
if (y == 0) block = Blocks.bedrock;
setBlockAt(block, new Vector2(x, y));
}
}
*/
}
/**
* Gets the list of dynamic entities in the world.
* @return The dynamic entities.
*/
public ArrayList<DynamicEntity> getDynamicEntities() {
return this.dynamicEntities;
}
/**
* Gets the {@link Block} at the given position.
* @param pos The position in the world.
* @return The Block at that position.
*/
public Block getBlockAt(Vector2 pos) {
return getChunkForWorldPos(pos).getBlockAt(getChunkForWorldPos(pos).convertWorldToChunkPos(pos));
}
/**
* Sets the block at the given position to the given block.
* @param block The block.
* @param pos The position in the world.
*/
public void setBlockAt(Block block, Vector2 pos) {
Chunk chunk = getChunkForWorldPos(pos);
chunk.setBlockAt(block, chunk.convertWorldToChunkPos(pos));
}
/**
* Spawns an entity at the given position.
* @param entity The entity.
* @param pos The position.
* @return The entity at the given position.
*/
public DynamicEntity spawnEntityAt(DynamicEntity entity, Vector2 pos) {
entity.setPosition(pos);
entity.setWorld(this);
getDynamicEntities().add(entity);
return entity;
}
public Chunk getChunkForWorldPos(Vector2 pos) {
int x;
if (pos.x < 0) {
x = (int) (-1 * Math.ceil(Math.abs(pos.x) / Chunk.WIDTH));
} else {
x = (int) Math.floor(pos.x / Chunk.WIDTH);
}
return chunks.get(x);
}
public Chunk getChunkAt(int xPos) {
return chunks.get(xPos);
}
public ArrayList<Chunk> getChunks() {
return new ArrayList<Chunk>(chunks.values());
}
public ArrayList<Chunk> getLoadedChunks() {
ArrayList<Chunk> loadedChunks = new ArrayList<Chunk>(5);
int playerChunkPos = getChunkForWorldPos(player.getPosition()).getPosition();
for (Chunk chunk : getChunks()) {
if (chunk.getPosition() >= playerChunkPos - LOAD_RADIUS && chunk.getPosition() <= playerChunkPos + LOAD_RADIUS)
loadedChunks.add(chunk);
}
return loadedChunks;
}
public void addChunk(Chunk chunk) {
chunks.put(chunk.getPosition(), chunk);
}
}
|
package com.example.markus.todoregister.gui;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import com.example.markus.todoregister.R;
/**
* Created by Markus on 13.4.2017.
* Activity for creating a new task
*/
public class CreationActivity extends AppCompatActivity {
public static final String EXTRA_TITLE = "com.example.markus.todoregister.EXTRA_T";
public static final String EXTRA_CONTENT = "com.example.markus.todoregister.EXTRA_C";
public static final String EXTRA_PRIORITY = "com.example.markus.todoregister.EXTRA_P";
public static boolean create = false; //BAD?
private EditText title, content;
private int priority = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task_creation);
registerComponents();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.creation_menu, menu);
setActionBar(menu);
return true;
}
/**
* Set actionbar with spinner for the creation activity
* @param menu menu
*/
public void setActionBar(Menu menu) {
MenuItem item = menu.findItem(R.id.spinner);
Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.spinner_list_item_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// spinner.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.dropdown_icon, null));
spinner.setPopupBackgroundResource(R.color.actionBarColor);
spinner.setAdapter(adapter);
getSupportActionBar().setTitle("");
setSpinnerListener(spinner);
}
/**
* Set listener for the priority spinner
* @param spinner spinner on the actionbar
*/
public void setSpinnerListener(Spinner spinner) {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
setPriority(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
setPriority(0);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.finishCreation) {
createTask();
return true;
}
return super.onOptionsItemSelected(item);
}
//Find all the views used in this activity
private void registerComponents() {
title = (EditText) findViewById(R.id.title);
content = (EditText) findViewById(R.id.content);
content.requestFocus();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(content, InputMethodManager.SHOW_IMPLICIT);
}
public int getPriority() {
return priority;
}
//Get the user title input
public String getTaskTitle() {
return title.getText().toString();
}
//Get the user content input
public String getContent() {
return content.getText().toString();
}
//Creates a new Task and returns to Main Activity
public void createTask() {
create = true;
changeActivity(getPriority(), getTaskTitle(), getContent());
}
//Set a priority for the task being created
private void setPriority(int priority) {
this.priority = priority;
}
//Change Activity while sending some data
public void changeActivity(int priority, String title, String content) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
Bundle extras = new Bundle();
extras.putInt(EXTRA_PRIORITY, priority);
extras.putString(EXTRA_TITLE, title);
extras.putString(EXTRA_CONTENT, content);
intent.putExtras(extras);
startActivity(intent);
}
}
|
import java.util.*;
class Permutations {
public List<List<Integer>> getPermutations(List<List<Integer>> nums) {
List<List<Integer>> result = new LinkedList<>();
List<Integer> path = new LinkedList();
dfs(result, nums, path, 0);
return result;
}
private void dfs(List<List<Integer>> result, List<List<Integer>> nums, List<Integer> path, int index) {
if (index == nums.size()) {
result.add(new ArrayList<Integer>(path));
return;
}
List<Integer> current = nums.get(index);
for (int num : current) {
path.add(num);
dfs(result, nums, path, index + 1);
path.remove(path.size() - 1);
}
}
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
List<Integer> list2 = new ArrayList<Integer>();
list2.add(4);
List<Integer> list3 = new ArrayList<Integer>();
list3.add(5);
list3.add(6);
List<List<Integer>> nums = new ArrayList<>();
nums.add(list1);
nums.add(list2);
nums.add(list3);
Permutations test = new Permutations();
List<List<Integer>> result = test.getPermutations(nums);
for (int i = 0; i < result.size(); i++) {
System.out.println(Arrays.toString(result.get(i).toArray()));
}
}
}
|
package info.blockchain.wallet.payload.data;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.kotlin.KotlinModule;
import com.google.common.annotations.VisibleForTesting;
import info.blockchain.wallet.exceptions.DecryptionException;
import info.blockchain.wallet.exceptions.EncryptionException;
import info.blockchain.wallet.exceptions.HDWalletException;
import info.blockchain.wallet.exceptions.NoSuchAddressException;
import info.blockchain.wallet.keys.SigningKey;
import info.blockchain.wallet.util.DoubleEncryptionFactory;
import info.blockchain.wallet.util.FormatsUtil;
import org.apache.commons.lang3.StringUtils;
import org.bitcoinj.core.AddressFormatException;
import org.bitcoinj.core.Base58;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.LegacyAddress;
import org.bitcoinj.params.MainNetParams;
import org.spongycastle.crypto.InvalidCipherTextException;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(fieldVisibility = Visibility.NONE,
getterVisibility = Visibility.NONE,
setterVisibility = Visibility.NONE,
creatorVisibility = Visibility.NONE,
isGetterVisibility = Visibility.NONE)
public class Wallet {
@JsonProperty("guid")
private String guid;
@JsonProperty("sharedKey")
private String sharedKey;
@JsonProperty("double_encryption")
private boolean doubleEncryption;
@JsonProperty("dpasswordhash")
private String dpasswordhash;
@JsonProperty("metadataHDNode")
private String metadataHDNode;
@JsonProperty("tx_notes")
private Map<String, String> txNotes;
@JsonProperty("tx_tags")
private Map<String, List<Integer>> txTags;
@JsonProperty("tag_names")
private List<Map<Integer, String>> tagNames;
@JsonProperty("options")
private Options options;
@JsonProperty("wallet_options")
private Options walletOptions;
@JsonProperty("hd_wallets")
private List<WalletBody> walletBodies;
@JsonProperty("keys")
private List<ImportedAddress> imported;
@JsonProperty("address_book")
private List<AddressBook> addressBook;
@JsonIgnore
private int wrapperVersion;
public Wallet() {
guid = UUID.randomUUID().toString();
sharedKey = UUID.randomUUID().toString();
txNotes = new HashMap<>();
imported = new ArrayList<>();
options = Options.getDefaultOptions();
wrapperVersion = WalletWrapper.V4;
walletBodies = new ArrayList<>();
}
public Wallet(String defaultAccountName) throws Exception {
this(defaultAccountName, false);
}
public Wallet(String defaultAccountName, boolean createV4) throws Exception {
guid = UUID.randomUUID().toString();
sharedKey = UUID.randomUUID().toString();
txNotes = new HashMap<>();
imported = new ArrayList<>();
options = Options.getDefaultOptions();
WalletBody walletBodyBody = new WalletBody(defaultAccountName, createV4);
wrapperVersion = createV4 ? WalletWrapper.V4 : WalletWrapper.V3;
walletBodies = new ArrayList<>();
walletBodies.add(walletBodyBody);
}
public String getGuid() {
return guid;
}
public String getSharedKey() {
return sharedKey;
}
public boolean isDoubleEncryption() {
return doubleEncryption;
}
public String getDpasswordhash() {
return dpasswordhash;
}
public String getMetadataHDNode() {
return metadataHDNode;
}
public Map<String, String> getTxNotes() {
return txNotes;
}
public Map<String, List<Integer>> getTxTags() {
return txTags;
}
public List<Map<Integer, String>> getTagNames() {
return tagNames;
}
public Options getOptions() {
fixPbkdf2Iterations();
return options;
}
public Options getWalletOptions() {
return walletOptions;
}
@Deprecated
@Nullable
public List<WalletBody> getWalletBodies() {
return walletBodies;
}
@Nullable
public WalletBody getWalletBody() {
if (walletBodies == null || walletBodies.isEmpty()) {
return null;
}
else {
return walletBodies.get(HD_WALLET_INDEX);
}
}
public List<ImportedAddress> getImportedAddressList() {
return imported;
}
public List<AddressBook> getAddressBook() {
return addressBook;
}
public int getWrapperVersion() {
return wrapperVersion;
}
public void setGuid(String guid) {
this.guid = guid;
}
public void setSharedKey(String sharedKey) {
this.sharedKey = sharedKey;
}
@Deprecated
public void setWalletBodies(List<WalletBody> walletBodies) {
this.walletBodies = walletBodies;
}
public void setWalletBody(WalletBody walletBody) {
this.walletBodies = Collections.singletonList(walletBody);
}
public void setImportedAddressList(List<ImportedAddress> keys) {
this.imported = keys;
}
public void setWrapperVersion(int wrapperVersion) {
this.wrapperVersion = wrapperVersion;
}
public boolean isUpgradedToV3() {
return (walletBodies != null && walletBodies.size() > 0);
}
public static Wallet fromJson(String json)
throws IOException, HDWalletException {
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
KotlinModule module = new KotlinModule();
module.addAbstractTypeMapping(Account.class, AccountV3.class);
mapper.registerModule(module);
return fromJson(json, mapper);
}
public static Wallet fromJson(
String json,
ObjectMapper mapper
) throws IOException, HDWalletException {
Wallet wallet = mapper.readValue(json, Wallet.class);
if (wallet.getWalletBodies() != null) {
ArrayList<WalletBody> walletBodyList = new ArrayList<>();
for (WalletBody walletBody : wallet.getWalletBodies()) {
walletBodyList.add(
WalletBody.fromJson(
walletBody.toJson(mapper),
mapper
)
);
}
wallet.setWalletBodies(walletBodyList);
}
return wallet;
}
public String toJson(ObjectMapper mapper) throws JsonProcessingException {
return mapper.writeValueAsString(this);
}
void addHDWallet(WalletBody walletBody) {
if (walletBodies == null) {
walletBodies = new ArrayList<>();
}
walletBodies.add(walletBody);
}
/**
* Checks imported address and hd keys for possible double encryption corruption
*/
public boolean isEncryptionConsistent() {
ArrayList<String> keyList = new ArrayList<>();
if (getImportedAddressList() != null) {
List<ImportedAddress> importedAddresses = getImportedAddressList();
for (ImportedAddress importedAddress : importedAddresses) {
String privateKey = importedAddress.getPrivateKey();
// Filter watch-only addresses, which still exist in some wallets
if (privateKey != null) {
keyList.add(privateKey);
}
}
}
if (getWalletBodies() != null && getWalletBodies().size() > 0) {
for (WalletBody walletBody : getWalletBodies()) {
List<Account> accounts = walletBody.getAccounts();
for (Account account : accounts) {
keyList.add(account.getXpriv());
}
}
}
return isEncryptionConsistent(isDoubleEncryption(), keyList);
}
boolean isEncryptionConsistent(boolean isDoubleEncrypted, List<String> keyList) {
boolean consistent = true;
for (String key : keyList) {
if (isDoubleEncrypted) {
consistent = FormatsUtil.isKeyEncrypted(key);
} else {
consistent = FormatsUtil.isKeyUnencrypted(key);
}
if (!consistent) {
break;
}
}
return consistent;
}
public void validateSecondPassword(@Nullable String secondPassword) throws DecryptionException {
if (isDoubleEncryption()) {
DoubleEncryptionFactory.validateSecondPassword(
getDpasswordhash(),
getSharedKey(),
secondPassword,
getOptions().getPbkdf2Iterations()
);
}
else if (!isDoubleEncryption() && secondPassword != null) {
throw new DecryptionException("Double encryption password specified on non double encrypted wallet.");
}
}
public void upgradeV2PayloadToV3(@Nullable String secondPassword, String defaultAccountName) throws Exception {
//Check if payload has 2nd password
validateSecondPassword(secondPassword);
if (!isUpgradedToV3()) {
//Create new hd wallet
WalletBody walletBodyBody = new WalletBody(defaultAccountName);
walletBodyBody.setWrapperVersion(wrapperVersion);
addHDWallet(walletBodyBody);
//Double encrypt if need
if (!StringUtils.isEmpty(secondPassword)) {
//Double encrypt seedHex
String doubleEncryptedSeedHex = DoubleEncryptionFactory.encrypt(
walletBodyBody.getSeedHex(),
getSharedKey(),
secondPassword,
getOptions().getPbkdf2Iterations()
);
walletBodyBody.setSeedHex(doubleEncryptedSeedHex);
//Double encrypt private keys
for (Account account : walletBodyBody.getAccounts()) {
String encryptedXPriv = DoubleEncryptionFactory.encrypt(
account.getXpriv(),
getSharedKey(),
secondPassword,
getOptions().getPbkdf2Iterations()
);
account.setXpriv(encryptedXPriv);
}
}
setWrapperVersion(WalletWrapper.V3);
}
}
@VisibleForTesting
public ImportedAddress addImportedAddress(ImportedAddress address, @Nullable String secondPassword)
throws Exception {
validateSecondPassword(secondPassword);
if (secondPassword != null) {
//Double encryption
String unencryptedKey = address.getPrivateKey();
String encryptedKey = DoubleEncryptionFactory.encrypt(
unencryptedKey,
getSharedKey(),
secondPassword,
getOptions().getPbkdf2Iterations()
);
address.setPrivateKey(encryptedKey);
}
imported.add(address);
return address;
}
public ImportedAddress addImportedAddressFromKey(SigningKey key, @Nullable String secondPassword)
throws Exception {
return addImportedAddress(ImportedAddress.fromECKey(key.toECKey()), secondPassword);
}
public void decryptHDWallet(String secondPassword)
throws DecryptionException,
IOException,
InvalidCipherTextException,
HDWalletException {
validateSecondPassword(secondPassword);
WalletBody walletBody = walletBodies.get(HD_WALLET_INDEX);
walletBody.decryptHDWallet(secondPassword, sharedKey, getOptions().getPbkdf2Iterations());
}
public void encryptAccount(Account account, String secondPassword)
throws UnsupportedEncodingException, EncryptionException {
//Double encryption
if (secondPassword != null) {
String encryptedPrivateKey = DoubleEncryptionFactory.encrypt(
account.getXpriv(),
sharedKey,
secondPassword,
getOptions().getPbkdf2Iterations()
);
account.setXpriv(encryptedPrivateKey);
}
}
public Account addAccount(
String label,
@Nullable String secondPassword,
int version
) throws Exception {
validateSecondPassword(secondPassword);
//Double decryption if need
decryptHDWallet(secondPassword);
WalletBody walletBody = walletBodies.get(HD_WALLET_INDEX);
walletBody.setWrapperVersion(version);
Account account = walletBody.addAccount(label);
//Double encryption if need
encryptAccount(account, secondPassword);
return account;
}
public ImportedAddress setKeyForImportedAddress(
SigningKey key,
@Nullable String secondPassword
) throws DecryptionException,
UnsupportedEncodingException,
EncryptionException,
NoSuchAddressException {
ECKey ecKey = key.toECKey();
validateSecondPassword(secondPassword);
List<ImportedAddress> addressList = getImportedAddressList();
String address = LegacyAddress.fromKey(
MainNetParams.get(),
ecKey
).toString();
ImportedAddress matchingAddressBody = null;
for (ImportedAddress addressBody : addressList) {
if (addressBody.getAddress().equals(address)) {
matchingAddressBody = addressBody;
}
}
if (matchingAddressBody == null) {
throw new NoSuchAddressException("No matching address found for key");
}
if (secondPassword != null) {
//Double encryption
String encryptedKey = Base58.encode(ecKey.getPrivKeyBytes());
String encrypted2 = DoubleEncryptionFactory.encrypt(
encryptedKey,
getSharedKey(),
secondPassword,
getOptions().getPbkdf2Iterations()
);
matchingAddressBody.setPrivateKey(encrypted2);
}
else {
matchingAddressBody.setPrivateKeyFromBytes(ecKey.getPrivKeyBytes());
}
return matchingAddressBody;
}
/**
* @deprecated Use the kotlin extension: {@link WalletExtensionsKt#nonArchivedImportedAddressStrings}
*/
@Deprecated
public List<String> getImportedAddressStringList() {
List<String> addrs = new ArrayList<>(imported.size());
for (ImportedAddress importedAddress : imported) {
if (!ImportedAddressExtensionsKt.isArchived(importedAddress)) {
addrs.add(importedAddress.getAddress());
}
}
return addrs;
}
public List<String> getImportedAddressStringList(long tag) {
List<String> addrs = new ArrayList<>(imported.size());
for (ImportedAddress importedAddress : imported) {
if (importedAddress.getTag() == tag) {
addrs.add(importedAddress.getAddress());
}
}
return addrs;
}
public boolean containsImportedAddress(String addr) {
for (ImportedAddress importedAddress : imported) {
if (importedAddress.getAddress().equals(addr)) {
return true;
}
}
return false;
}
/**
* In case wallet was encrypted with iterations other than what is specified in options, we
* will ensure next encryption and options get updated accordingly.
*
* @return
*/
private int fixPbkdf2Iterations() {
//Use default initially
int iterations = WalletWrapper.DEFAULT_PBKDF2_ITERATIONS_V2;
//Old wallets may contain 'wallet_options' key - we'll use this now
if (walletOptions != null && walletOptions.getPbkdf2Iterations() > 0) {
iterations = walletOptions.getPbkdf2Iterations();
options.setPbkdf2Iterations(iterations);
}
//'options' key override wallet_options key - we'll use this now
if (options != null && options.getPbkdf2Iterations() > 0) {
iterations = options.getPbkdf2Iterations();
}
//If wallet doesn't contain 'option' - use default
if (options == null) {
options = Options.getDefaultOptions();
}
//Set iterations
options.setPbkdf2Iterations(iterations);
return iterations;
}
/**
* Returns label if match found, otherwise just returns address.
*
* @param address
*/
public String getLabelFromImportedAddress(String address) {
List<ImportedAddress> addresses = getImportedAddressList();
for (ImportedAddress importedAddress : addresses) {
if (importedAddress.getAddress().equals(address)) {
String label = importedAddress.getLabel();
if (label == null || label.isEmpty()) {
return address;
}
else {
return label;
}
}
}
return address;
}
//Assume we only support 1 hdWallet
private static final int HD_WALLET_INDEX = 0;
private boolean isKeyUnencrypted(String data) {
if (data == null)
return false;
try {
Base58.decode(data);
return true;
} catch (AddressFormatException e) {
return false;
}
}
}
|
package com.tencent.mm.plugin.webview.b;
import android.database.Cursor;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.au;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
public final class b {
private static long pNr = 2592000;
private static b pNs;
private c pNt;
private Map<String, Long> pNu = new HashMap();
private long pNv = 0;
static /* synthetic */ long Qd(String str) {
long j = bi.getLong(str, 604800);
return j > pNr ? pNr : j;
}
static /* synthetic */ void b(b bVar) {
c bTC = bVar.bTC();
String format = String.format("delete from %s where %s<%s", new Object[]{"WebViewData", "expireTime", Long.valueOf(System.currentTimeMillis() / 1000)});
x.d("MicroMsg.WebViewDataStorage", "clearExpireTimeData: " + format);
x.d("MicroMsg.WebViewDataStorage", "clearExpireTimeData: " + bTC.fV("WebViewData", format));
}
public static b bTB() {
if (pNs == null) {
pNs = new b();
}
return pNs;
}
public final c bTC() {
if (this.pNt == null) {
g.Ek();
this.pNt = new c(g.Ei().dqq);
}
return this.pNt;
}
public final boolean a(String str, String str2, String str3, String str4, String str5, boolean z) {
long j;
long j2;
Cursor rawQuery = bTC().rawQuery(String.format("select %s from %s where %s=\"%s\"", new Object[]{"size", "WebViewData", "appIdKey", c.fl(str, str2)}), new String[0]);
if (rawQuery == null) {
j = 0;
} else {
j2 = 0;
if (rawQuery.moveToFirst()) {
j2 = rawQuery.getLong(0);
}
rawQuery.close();
j = j2;
}
long length = ((long) (str2.getBytes().length + str3.getBytes().length)) - j;
if (this.pNu.containsKey(str)) {
j2 = ((Long) this.pNu.get(str)).longValue();
} else {
c bTC = bTC();
String format = String.format("select %s from %s where %s=\"%s\"", new Object[]{"size", "WebViewData", "appIdKey", c.aj(str, "###@@@@TOTAL@@@###SIZE####", "_")});
x.d("MicroMsg.WebViewDataStorage", "getAppIdSize: " + format);
j2 = 0;
rawQuery = bTC.rawQuery(format, new String[0]);
if (rawQuery != null) {
if (rawQuery.moveToFirst()) {
j2 = rawQuery.getLong(0);
}
rawQuery.close();
}
x.d("MicroMsg.WebViewDataStorage", "getAppIdSize: " + j2);
}
final long j3 = j2 + length;
final long j4 = str.equals("wx62d9035fd4fd2059") ? j3 - 52428800 : j3 - 10485760;
x.i("MicroMsg.WebViewDataCenter", "prevSize = %d, valueSize = %d, diffSize = %d, newAppSize = %d, expireSize = %d", new Object[]{Long.valueOf(j), Long.valueOf(r10), Long.valueOf(length), Long.valueOf(j3), Long.valueOf(j4)});
if (j4 > 0 && !z) {
return false;
}
final String str6 = str;
final String str7 = str2;
final String str8 = str3;
final String str9 = str4;
final String str10 = str5;
au.Em().H(new Runnable() {
public final void run() {
long j;
if (j4 > 0) {
c bTC = b.this.bTC();
String str = str6;
long j2 = j4;
str = String.format("select * from %s where appId='%s' order by weight,timeStamp", new Object[]{"WebViewData", str});
x.d("MicroMsg.WebViewDataStorage", "deleteSize querySql: " + str);
Cursor rawQuery = bTC.rawQuery(str, new String[0]);
if (rawQuery == null) {
j = 0;
} else {
List<String> linkedList = new LinkedList();
long j3 = j2;
while (rawQuery.moveToFirst() && j3 > 0) {
str = rawQuery.getString(1);
long j4 = rawQuery.getLong(6);
linkedList.add(str);
j3 -= j4;
}
rawQuery.close();
if (linkedList.size() > 0) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("(");
for (String str2 : linkedList) {
stringBuilder.append("\"" + str2 + "\",");
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
stringBuilder.append(")");
str2 = String.format("delete from %s where %s in %s", new Object[]{"WebViewData", "appIdKey", stringBuilder.toString()});
x.d("MicroMsg.WebViewDataStorage", "deleteSize deleteSql: " + str2);
x.d("MicroMsg.WebViewDataStorage", "deleteSize: " + bTC.fV("WebViewData", str2));
}
j = j2 - j3;
}
b.this.pNu.put(str6, Long.valueOf(j3 - j));
} else {
b.this.pNu.put(str6, Long.valueOf(j3));
}
c bTC2 = b.this.bTC();
String str3 = str6;
String str4 = str7;
String str5 = str8;
String aG = bi.aG(str9, "1");
long Qd = b.Qd(str10);
a aVar = new a();
aVar.field_appId = str3;
aVar.field_appIdKey = c.fl(str3, str4);
aVar.field_value = str5;
aVar.field_weight = aG;
aVar.field_expireTime = Qd + (System.currentTimeMillis() / 1000);
aVar.field_size = (long) (str4.getBytes().length + str5.getBytes().length);
aVar.field_timeStamp = System.currentTimeMillis() / 1000;
x.d("MicroMsg.WebViewDataStorage", "setData: " + bTC2.a(aVar));
c bTC3 = b.this.bTC();
str5 = str6;
j = b.this.pNu.get(str6) == null ? 0 : ((Long) b.this.pNu.get(str6)).longValue();
a aVar2 = new a();
aVar2.field_appId = str5;
aVar2.field_appIdKey = c.aj(str5, "###@@@@TOTAL@@@###SIZE####", "_");
aVar2.field_expireTime = Long.MAX_VALUE;
aVar2.field_size = j;
boolean a = bTC3.a(aVar2);
x.d("MicroMsg.WebViewDataStorage", "setAppIdSize: %b, size: %d", new Object[]{Boolean.valueOf(a), Long.valueOf(j)});
b.b(b.this);
}
});
return true;
}
public final a fk(String str, String str2) {
c bTC = bTC();
String format = String.format("select * from %s where %s=\"%s\"", new Object[]{"WebViewData", "appIdKey", c.fl(str, str2)});
x.d("MicroMsg.WebViewDataStorage", "getData: " + format);
Cursor rawQuery = bTC.rawQuery(format, new String[0]);
a aVar = new a();
if (rawQuery != null) {
if (rawQuery.moveToFirst()) {
aVar.d(rawQuery);
}
rawQuery.close();
}
return aVar;
}
public final void b(String str, JSONArray jSONArray) {
c bTC = bTC();
if (jSONArray != null && jSONArray.length() != 0) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("(");
for (int i = 0; i < jSONArray.length(); i++) {
try {
stringBuilder.append("\"" + c.fl(str, jSONArray.getString(i)) + "\",");
} catch (Exception e) {
x.e("MicroMsg.WebViewDataStorage", "clearData: " + e.getMessage());
}
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
stringBuilder.append(")");
String format = String.format("delete from %s where %s in %s", new Object[]{"WebViewData", "appIdKey", stringBuilder.toString()});
x.d("MicroMsg.WebViewDataStorage", "deleteData: " + format);
x.d("MicroMsg.WebViewDataStorage", "clearData: " + bTC.fV("WebViewData", format));
}
}
public final void Qc(String str) {
c bTC = bTC();
String format = String.format("delete from %s where %s=\"%s\"", new Object[]{"WebViewData", "appId", str});
x.d("MicroMsg.WebViewDataStorage", "cleanAllData: " + format);
x.d("MicroMsg.WebViewDataStorage", "cleanAllData: " + bTC.fV("WebViewData", format));
}
}
|
package com.todoapp.repository;
import com.todoapp.entity.Group;
import java.util.List;
public interface GroupRepository {
List<Group> findByName(String name);
Group save(Group var1);
Group findById(String var1);
void delete(int var1);
List<Group> findAll();
boolean checkEnroll(String username,String password);
}
|
package com.maweiming.wechat.bot.service.message.core;
/**
* maweiming.com
* Copyright (C) 1994-2018 All Rights Reserved.
*
* @author CoderMa
* @version MessageType.java, v 0.1 2018-11-06 00:18
*/
public enum MessageType {
TEXT("文本"),
IMAGES("图片"),
VOICE("语音"),
VIDEO("视频"),
EMOJI("表情包"),
RECALL("撤回一条消息"),
LINK("分享链接"),
MINIAPP("小程序"),
OPEN("打开"),
CLOSE("关闭")
;
MessageType(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package com.yida.utils;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
*********************
* 流通用方法
*
* @author yangke
* @version 1.0
* @created 2018年5月10日 下午12:13:12
***********************
*/
public final class StreamUtils {
/**
* 字符转文件
*
* @param buf
* @param file
*/
public static void bytesToFile(byte[] buf, File file) {
BufferedOutputStream bos = null;
try {
FileUtils.ensureParentPath(file);
bos = new BufferedOutputStream(new FileOutputStream(file));
bos.write(buf);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (bos != null) {
try {
bos.flush();
bos.close();
} catch (IOException e) {
}
}
}
}
/**
* 流转文件
*
* @param is
* @param file
*/
public static void inputstreamToFile(InputStream in, File file) {
BufferedOutputStream bos = null;
try {
FileUtils.ensureParentPath(file);
bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] b = new byte[8196];
int len;
while ((len = in.read(b)) != -1) {
bos.write(b, 0, len);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (bos != null) {
try {
bos.flush();
bos.close();
} catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
}
|
package com.fatosajvazi;
import java.util.ArrayList;
public class Customer {
private String customerName;
ArrayList<Double> transactions;
public Customer(String customerName) {
this.customerName = customerName;
this.transactions = new ArrayList<>();
}
public Customer(String customerName, double transactionAmount){
this.customerName = customerName;
this.transactions = new ArrayList<>();
this.addTransaction(transactionAmount);
}
public String getCustomerName() {
return customerName;
}
public void addTransaction(double amount){
this.transactions.add(Double.valueOf(amount));
}
}
|
package com.greenfoxacademy.webshop.controllers;
import com.greenfoxacademy.webshop.ShopItem;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MainController {
private List<ShopItem> emptyList = new ArrayList<>();
private List<ShopItem> shopItemsList = addItemsToList();
public List<ShopItem> addItemsToList() {
emptyList.add(new ShopItem("Running shoes",
"Nike running shoes for everyday sport", 1000, 5, "clothesandshoes"));
emptyList.add(new ShopItem("Wokin", "Chicken with fried rice and WOKIN sauce",
119, 100, "beveragesandsnacks"));
emptyList.add(new ShopItem("Printer", "Some HP printer that will print pages",
3000, 2, "electronics"));
emptyList.add(new ShopItem("Coca cola", "0.5l standard coke",
25, 0, "beveragesandsnacks"));
emptyList.add(new ShopItem("T-shirt", "Blue with a corgi on a bike",
300, 1, "clothesandshoes"));
return emptyList;
}
@ResponseBody
@RequestMapping(value = "", method = RequestMethod.GET)
public String helloWorld() {
return "Hello World";
}
@RequestMapping(value = "/webshop", method = RequestMethod.GET) //
public String displayMyShop(Model model) {
model.addAttribute("items", shopItemsList);
model.addAttribute("currency", "czk");
return "myshop";
}
@RequestMapping(value = "webshop/onlyavaible", method = RequestMethod.GET)
public String onlyAvaible(Model model) {
model.addAttribute("items", shopItemsList.stream()
.filter(item -> item.getQuantityOfStock() > 0)
.collect(Collectors.toList()));
model.addAttribute("currency", "czk");
return "myshop";
}
@RequestMapping(value = "webshop/cheapest", method = RequestMethod.GET)
public String cheapestFirst(Model model) {
model.addAttribute("items", shopItemsList.stream()
.sorted(Comparator.comparing(ShopItem::getPrice))
.collect(Collectors.toList()));
model.addAttribute("currency", "czk");
return "myshop";
}
@RequestMapping(value = "webshop/containsnike", method = RequestMethod.GET)
public String containsNike(Model model) {
model.addAttribute("items", shopItemsList.stream()
.filter(item -> item.getName().toLowerCase().contains("nike")
|| item.getDescription().toLowerCase().contains("nike"))
.collect(Collectors.toList()));
model.addAttribute("currency", "czk");
return "myshop";
}
@RequestMapping(value = "webshop/mostexpensive", method = RequestMethod.GET)
public String mostExpensiveItem(Model model) {
model.addAttribute("items", shopItemsList.stream()
.sorted(Comparator.comparingDouble(ShopItem::getPrice).reversed())
.limit(1)
.collect(Collectors.toList()));
model.addAttribute("currency", "czk");
return "myshop";
}
@RequestMapping(value = "webshop/avarage", method = RequestMethod.GET)
public String getAverageStock(Model model) {
model.addAttribute("averageOfStock", shopItemsList.stream()
.mapToDouble(item -> item.getQuantityOfStock())
.average()
.orElseGet(() -> 0));
return "stockavarage";
}
@RequestMapping(path = "webshop/search", method = RequestMethod.POST)
public String searchByNames(String searchInput,
Model model) {
model.addAttribute("items", shopItemsList.stream()
.filter(item -> item.getName().toLowerCase().contains(searchInput.toLowerCase())
|| item.getDescription().toLowerCase().contains(searchInput.toLowerCase()))
.collect(Collectors.toList()));
model.addAttribute("currency", "czk");
return "myshop";
}
@RequestMapping(value = "/webshop/more", method = RequestMethod.GET) //
public String moreOption(Model model) {
model.addAttribute("items", shopItemsList);
model.addAttribute("currency", "czk");
return "morefilteroption";
}
@RequestMapping(value = "webshop/clothesandshoes", method = RequestMethod.GET)
public String clothesAndShoes(Model model) {
model.addAttribute("items", shopItemsList.stream()
.filter(item -> item.getType().equals("clothesandshoes"))
.collect(Collectors.toList()));
model.addAttribute("currency", "czk");
return "morefilteroption";
}
@RequestMapping(value = "webshop/electronics", method = RequestMethod.GET)
public String electronics(Model model) {
model.addAttribute("items", shopItemsList.stream()
.filter(item -> item.getType().equals("electronics"))
.collect(Collectors.toList()));
model.addAttribute("currency", "czk");
return "morefilteroption";
}
@RequestMapping(value = "webshop/beveragesandsnacks", method = RequestMethod.GET)
public String beveragesAndSnacks(Model model) {
model.addAttribute("items", shopItemsList.stream()
.filter(item -> item.getType().equals("beveragesandsnacks"))
.collect(Collectors.toList()));
model.addAttribute("currency", "czk");
return "morefilteroption";
}
@RequestMapping(value = "webshop/originalprice", method = RequestMethod.GET)
public String originalCurrency(Model model) {
model.addAttribute("items", shopItemsList);
model.addAttribute("currency", "czk");
return "morefilteroption";
}
@RequestMapping(value = "webshop/priceineuro", method = RequestMethod.GET)
public String priceInEuro(Model model) {
model.addAttribute("items", shopItemsList.stream()
.map(item -> new ShopItem(item.getName(), item.getDescription(),
item.getPrice() * 0.035f,
item.getQuantityOfStock(), item.getType()))
.collect(Collectors.toList()));
model.addAttribute("currency", "eur");
return "morefilteroption";
}
@RequestMapping(path = "/webshop/filterbyprice", method = RequestMethod.POST)
public String filterByPrice(@RequestParam String searchValue,
@RequestParam(value = "filterbyprice") Integer number,
Model model) {
switch (searchValue) {
case "Above":
model.addAttribute("items", shopItemsList.stream()
.filter(item -> item.getPrice() > Float.valueOf(number))
.collect(Collectors.toList()));
break;
case "Below":
model.addAttribute("items", shopItemsList.stream()
.filter(item -> item.getPrice() < Float.valueOf(number))
.collect(Collectors.toList()));
break;
case "Exactly":
model.addAttribute("items", shopItemsList.stream()
.filter(item -> item.getPrice() == Float.valueOf(number))
.collect(Collectors.toList()));
break;
}
model.addAttribute("currency", new String("CZK"));
return "morefilteroption";
}
}
|
package com.app.basics;
import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
public class Product {
private static Logger log = Logger.getLogger(Product.class);
public static void main(String[] args) {
Layout out = new SimpleLayout();
Appender ap = new ConsoleAppender(out);
log.addAppender(ap);
log.debug("hi");
log.info("Ashok");
}
}
|
package com.example.SBNZ.mappers;
import com.example.SBNZ.dto.CEPInputDTO;
import com.example.SBNZ.model.training.cep.CEPInput;
import com.example.SBNZ.service.ExerciseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class CEPInputMapper implements MapperInterface<CEPInput, CEPInputDTO>{
@Autowired
ExerciseMapper exerciseMapper;
@Autowired
ExerciseService exerciseService;
@Override
public CEPInput toEntity(CEPInputDTO dto) {
return new CEPInput(exerciseService.findById(dto.getExerciseDTO()), dto.getHeartRate());
}
@Override
public CEPInputDTO toDTO(CEPInput entity) {
return new CEPInputDTO(entity.getExercise().getId(), entity.getHeartRate());
}
@Override
public List<CEPInput> toEntityList(List<CEPInputDTO> dtos) {
List<CEPInput> inputs = new ArrayList<>();
for (CEPInputDTO dto: dtos) {
inputs.add(this.toEntity(dto));
}
return inputs;
}
@Override
public List<CEPInputDTO> toDTOList(List<CEPInput> entities) {
List<CEPInputDTO> dtos = new ArrayList<>();
for (CEPInput cepInput: entities) {
dtos.add(this.toDTO(cepInput));
}
return dtos;
}
}
|
/*
* 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 Vistas;
/**
*
* @author USUARIO
*/
public class AcercaDe extends javax.swing.JInternalFrame {
/**
* Creates new form AcercaDe
*/
public AcercaDe() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
setClosable(true);
setIconifiable(true);
setTitle("Acerca De");
setPreferredSize(new java.awt.Dimension(610, 440));
jPanel1.setBackground(new java.awt.Color(0, 0, 0));
jLabel1.setForeground(new java.awt.Color(0, 204, 51));
jLabel1.setText("Esta aplicacion ha sido desarrollada por el alumno Josue Cruz Santiago con matricula 142Z0469 ");
jLabel2.setForeground(new java.awt.Color(0, 204, 51));
jLabel2.setText(" biblioteca del Instituto Tecnologico Superior de Alamo Temapache. campus Xoyotitla .");
jLabel3.setForeground(new java.awt.Color(0, 204, 51));
jLabel3.setText("con el fin de llevar a cabo el control de inventario, prestamos de libros, refrendos y multas de la");
jLabel4.setForeground(new java.awt.Color(204, 0, 0));
jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel4.setText(" CREDITOS:");
jLabel5.setForeground(new java.awt.Color(0, 153, 153));
jLabel5.setText("Diseño general del Sistema:");
jLabel6.setForeground(new java.awt.Color(0, 153, 153));
jLabel6.setText("Diseño de interfaz grafica:");
jLabel7.setForeground(new java.awt.Color(255, 204, 0));
jLabel7.setText("Asesorado por Enrique Cruz Limon.");
jLabel8.setForeground(new java.awt.Color(255, 204, 0));
jLabel8.setText("Ing. Cinthya Pacheco Bernabe.");
jLabel9.setForeground(new java.awt.Color(255, 102, 0));
jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel9.setText("***** SISTEMA PARA EL CONTROL DE PRESTAMOS BIBLIOTECARIOS ITSAT *****");
jLabel10.setForeground(new java.awt.Color(255, 102, 0));
jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel10.setText("*****¡ MUCHAS GRACIAS! *****");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(31, 31, 31)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 471, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(0, 17, Short.MAX_VALUE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel6)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(jLabel8))
.addGap(116, 116, 116)))))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
}
|
package org.usfirst.frc.team3223.robot;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Talon;
public class RobotConfiguration {
private SpeedController left_motor, right_motor;
public RobotConfiguration(){
left_motor = new Talon(0);
right_motor = new Talon(1);
}
public void turn(double voltage){
left_motor.set(voltage);
right_motor.set(voltage);
}
public void forward(double voltage){
left_motor.set(voltage);
right_motor.set(-voltage);
}
public void autonomous(long startTime){
long currentTime = System.currentTimeMillis();
if(currentTime<=startTime+5000){
left_motor.set(0.5);
right_motor.set(-0.5);
}else{
left_motor.set(0);
right_motor.set(0);
}
}
}
|
package com.example.railway.service.Passenger;
import com.example.railway.model.Passenger;
import java.util.List;
public interface IPassengerService {
Passenger update(Passenger passenger);
Passenger delete(String id);
Passenger getById(String id);
Passenger create(Passenger passenger);
List<Passenger> getAll();
}
|
package org.rart.petclinic.services;
import org.rart.petclinic.models.Vet;
public interface VetService extends CrudService<Vet,Long> {
}
|
package uw.cse.dineon.user.restaurantselection;
import java.util.Collection;
import java.util.List;
import uw.cse.dineon.library.RestaurantInfo;
import uw.cse.dineon.library.animation.ExpandAnimation;
import uw.cse.dineon.library.image.DineOnImage;
import uw.cse.dineon.library.image.ImageGetCallback;
import uw.cse.dineon.library.image.ImageObtainable;
import uw.cse.dineon.user.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* List of Restaurants the user can choose from. This just presents a view that the user
* @author mhotan
*/
public class RestaurantListFragment extends ListFragment {
private final String TAG = this.getClass().getSimpleName();
private RestaurantListListener mListener;
private RestaurantListAdapter mAdapter;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
List<RestaurantInfo> mRestaurants = mListener.getRestaurants();
mAdapter = new RestaurantListAdapter(this.getActivity(), mRestaurants);
setListAdapter(mAdapter);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof RestaurantListListener) {
mListener = (RestaurantListListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet RestaurantListFragment.RestaurantListListener");
}
}
/**
* Add a restaurantInfo to the list.
*
* @param infos info to add.
*/
public void addRestaurantInfos(List<RestaurantInfo> infos) {
this.mAdapter.clear();
for (RestaurantInfo r : infos) {
this.mAdapter.add(r);
}
}
/**
* Clears the current list of restaurants.
*/
public void clearRestaurants() {
mAdapter.clear();
}
/**
* Notifies this fragment that the state has just changed.
*/
public void notifyStateChange() {
mAdapter.notifyDataSetChanged();
}
/**
* Inavlidate the restaurant selection list.
* @param restaurants
*/
public void notifyInvalidated(List<RestaurantInfo> restaurants) {
mAdapter.notifyDataSetInvalidated();
mAdapter = new RestaurantListAdapter(this.getActivity(), restaurants);
setListAdapter(mAdapter);
}
/**
* For any activity that wishes to contain this fragment then that
* activity must implement this interface.
* @author mhotan
*/
public interface RestaurantListListener extends ImageObtainable {
/**
*
* @param restaurant Restaurant that was chosen
*/
public void onRestaurantSelected(RestaurantInfo restaurant);
/**
* Returns a non null list of restaurant info to present.
* @return return the list of restaurant infos.
*/
public List<RestaurantInfo> getRestaurants();
}
/**
* Class that will help display custom list view items of Restaurants.
*
* Given a list of restaurant information instances produce a list displaying all the
* restaraunts. Each item allows the user to select
*
* @author mhotan
*/
private class RestaurantListAdapter extends ArrayAdapter<RestaurantInfo> {
private final Context mContext;
/**
*
*
* @param context Context
* @param values List of Strings
*/
public RestaurantListAdapter(Context context, List<RestaurantInfo> values) {
super(context, R.layout.listitem_restaurant_top, values); // Use our custom row layout
this.mContext = context;
}
@Override
public void add(RestaurantInfo r) {
super.add(r);
// this.mValues.add(r);
this.notifyDataSetChanged();
}
@Override
public void addAll(Collection<? extends RestaurantInfo> collection) {
super.addAll(collection);
notifyDataSetChanged();
}
@Override
public void clear() {
super.clear();
// this.mValues.clear();
this.notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Establish a reference to the top and bottom of ex
View vwTop;
View vwBot;
LinearLayout layoutView = null;
if (convertView == null) { // Created for the first time.
layoutView = new LinearLayout(mContext);
layoutView.setOrientation(LinearLayout.VERTICAL);
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vwTop = inflater.inflate(R.layout.listitem_restaurant_top, null, true);
vwBot = inflater.inflate(R.layout.listitem_restaurant_bottom, null, true);
layoutView.addView(vwTop);
layoutView.addView(vwBot);
convertView = layoutView;
} else { // We already have a view for this layout
vwTop = convertView.findViewById(R.id.restaurant_top);
vwBot = convertView.findViewById(R.id.restaurant_bottom);
}
// We have a rsetaurant info to show.
RestaurantInfo restToShow = getItem(position);
// For every restaurant to present create a handler for the restaurant;
// We are creating this view for the very first time
if (layoutView != null) {
// Create a handler just for the restaurant.
new RestaurantHandler(restToShow, vwTop, vwBot);
}
return convertView;
}
/**
* Restaurant handler that manages the user input for the views that
* correspond to a particular restaurant.
* @author mhotan
*/
private class RestaurantHandler implements OnClickListener {
private final RestaurantInfo mInfo;
private final ImageView mExpandDown;
private final ImageButton mPickRestaurant;
private final View mTop, mBottom;
/**
* Build this handler from Restaurant info and its corresponging views.
*
* @param info Restaurant to associate to.
* @param top Top view for the restaurant.
* @param bottom bottom view for the restaurant.
*/
public RestaurantHandler(RestaurantInfo info, View top, View bottom) {
mInfo = info;
mTop = top;
mBottom = bottom;
// Get a reference to all the top pieces
final ImageView RESTIMAGE = (ImageView)
mTop.findViewById(R.id.image_restaurant_thumbnail);
TextView restaurantNameView = (TextView)
mTop.findViewById(R.id.label_restaurant_title);
mExpandDown = (ImageView)
mTop.findViewById(R.id.button_expand_down);
// Get a reference to all the bottom pieces
TextView restaurantAddressView = (TextView)
mBottom.findViewById(R.id.label_restaurant_address);
TextView restaurantPhoneView = (TextView)
mBottom.findViewById(R.id.label_restaurant_phone);
TextView restaurantHoursView = (TextView)
mBottom.findViewById(R.id.label_restaurant_hours);
mPickRestaurant = (ImageButton) mBottom.findViewById(R.id.button_proceed);
// Set the values that will never change.
restaurantNameView.setText(mInfo.getName());
String hours = getResources().getString(R.string.string_format_hours);
String phone = getResources().getString(R.string.string_format_phone);
String address = getResources().getString(R.string.string_format_address);
restaurantAddressView.setText(String.format(address, mInfo.getReadableAddress()));
restaurantHoursView.setText(String.format(hours, mInfo.getHours()));
restaurantPhoneView.setText(String.format(phone, mInfo.getPhone()));
// Set the image of this restaurant
DineOnImage image = info.getMainImage();
if (image != null) {
mListener.onGetImage(image, new ImageGetCallback() {
@Override
public void onImageReceived(Exception e, Bitmap b) {
if (e == null) {
// We got the image so set the bitmap
RESTIMAGE.setImageBitmap(b);
}
}
});
}
// Set the bottom view to initial to be invisible
mBottom.setVisibility(View.GONE);
mTop.setOnClickListener(this);
mPickRestaurant.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == mTop) {
int bottomVisibility = mBottom.getVisibility();
// Expand the bottom view if it is not shown
// Hide the expand down button.
if (bottomVisibility == View.GONE) {
mExpandDown.setVisibility(View.GONE);
} else if (bottomVisibility == View.VISIBLE) {
mExpandDown.setVisibility(View.VISIBLE);
}
// Expand the animation
ExpandAnimation expandAni = new ExpandAnimation(mBottom, 500);
mBottom.startAnimation(expandAni);
} else if (v == mPickRestaurant) {
mListener.onRestaurantSelected(mInfo);
}
}
}
}
}
|
package com.company;
import java.util.Scanner;
public class CheckForPalindrome {
private static final String ENTER_NUMBER_FOR_CHECK = "Введите число для проверки на палиндром : ";
private static final String IS_PALINDROME = "Палиндром";
private static final String IS_NOT_PALINDROME = "Не палиндром";
private static final Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println(ENTER_NUMBER_FOR_CHECK);
Integer numberForCheck = input.nextInt();
int i = 0;
while (i < numberForCheck.toString().length()) {
if (numberForCheck.toString().charAt(i) != numberForCheck.toString().charAt(numberForCheck.toString().length() - 1 - i)) {
System.out.println(IS_NOT_PALINDROME);
break;
}
i++;
if (i == numberForCheck.toString().length())
System.out.println(IS_PALINDROME);
}
}
}
|
package com.tencent.mm.plugin.setting.ui.setting;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.setting.model.e;
class SettingsTrustFriendUI$5 implements OnCancelListener {
final /* synthetic */ SettingsTrustFriendUI mUl;
final /* synthetic */ e mUn;
SettingsTrustFriendUI$5(SettingsTrustFriendUI settingsTrustFriendUI, e eVar) {
this.mUl = settingsTrustFriendUI;
this.mUn = eVar;
}
public final void onCancel(DialogInterface dialogInterface) {
g.DF().c(this.mUn);
}
}
|
package pages;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
import org.testng.annotations.*;
import factory.BrowserFactory;
import factory.DataProviderFactory;
public class VerifyHomePage extends BrowserFactory{
@BeforeMethod
public void setUp() throws Exception
{
driver= BrowserFactory.getBrowser("chrome");
driver.get(DataProviderFactory.getconfig().getApplicationUrl());
}
@Test
public void testHomePage() throws Exception
{
Homepage home= PageFactory.initElements(driver, Homepage.class);
String title= home.getApplicationTitle();
System.out.println(title);
Assert.assertTrue(title.contains("Log In"));
}
@AfterMethod
public void tearDown()
{
BrowserFactory.closeBrowser(driver);
}
}
|
package com.tencent.pb.common.b.a;
import com.google.a.a.b;
import com.google.a.a.e;
public final class a$as extends e {
public int dQN;
public int dQO;
public int veK;
public int veL;
public int veM;
public int veN;
public int veO;
public int veP;
public int veQ;
public int veR;
public int veS;
public int veT;
public a$as() {
this.veK = 0;
this.dQN = 0;
this.dQO = 0;
this.veL = 0;
this.veM = 0;
this.veN = 0;
this.veO = 0;
this.veP = 0;
this.veQ = 0;
this.veR = 0;
this.veS = 0;
this.veT = 0;
this.bfP = -1;
}
public final void a(b bVar) {
if (this.veK != 0) {
bVar.aE(1, this.veK);
}
if (this.dQN != 0) {
bVar.aE(2, this.dQN);
}
if (this.dQO != 0) {
bVar.aE(3, this.dQO);
}
if (this.veL != 0) {
bVar.aE(4, this.veL);
}
if (this.veM != 0) {
bVar.aE(5, this.veM);
}
if (this.veN != 0) {
bVar.aE(6, this.veN);
}
if (this.veO != 0) {
bVar.aE(7, this.veO);
}
if (this.veP != 0) {
bVar.aE(8, this.veP);
}
if (this.veQ != 0) {
bVar.aE(9, this.veQ);
}
if (this.veR != 0) {
bVar.aE(10, this.veR);
}
if (this.veS != 0) {
bVar.aE(11, this.veS);
}
if (this.veT != 0) {
bVar.aE(12, this.veT);
}
super.a(bVar);
}
protected final int sl() {
int sl = super.sl();
if (this.veK != 0) {
sl += b.aG(1, this.veK);
}
if (this.dQN != 0) {
sl += b.aG(2, this.dQN);
}
if (this.dQO != 0) {
sl += b.aG(3, this.dQO);
}
if (this.veL != 0) {
sl += b.aG(4, this.veL);
}
if (this.veM != 0) {
sl += b.aG(5, this.veM);
}
if (this.veN != 0) {
sl += b.aG(6, this.veN);
}
if (this.veO != 0) {
sl += b.aG(7, this.veO);
}
if (this.veP != 0) {
sl += b.aG(8, this.veP);
}
if (this.veQ != 0) {
sl += b.aG(9, this.veQ);
}
if (this.veR != 0) {
sl += b.aG(10, this.veR);
}
if (this.veS != 0) {
sl += b.aG(11, this.veS);
}
if (this.veT != 0) {
return sl + b.aG(12, this.veT);
}
return sl;
}
}
|
package com.tencent.mm.plugin.facedetect.model;
import com.tencent.mm.plugin.facedetect.FaceProNative;
import com.tencent.mm.plugin.facedetect.FaceProNative.FaceResult;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
public final class g {
public FaceProNative iNy = null;
public final FaceResult aJR() {
if (this.iNy == null) {
x.e("MicroMsg.FaceDetectNativeManager", "hy: release out not init");
return null;
}
try {
long VG = bi.VG();
x.i("MicroMsg.FaceDetectNativeManager", "hy: uninitialize result : %d, using: %d ms", new Object[]{Integer.valueOf(this.iNy.engineReleaseOut().result), Long.valueOf(bi.VG() - VG)});
this.iNy = null;
return this.iNy.engineReleaseOut();
} catch (Throwable th) {
x.printErrStackTrace("MicroMsg.FaceDetectNativeManager", th, "hy: face lib release crash!!!", new Object[0]);
this.iNy.engineRelease();
this.iNy = null;
return null;
}
}
public final int aJS() {
String str = "MicroMsg.FaceDetectNativeManager";
String str2 = "alvinluo cutDown sFaceProNative == null: %b";
Object[] objArr = new Object[1];
objArr[0] = Boolean.valueOf(this.iNy == null);
x.v(str, str2, objArr);
if (this.iNy == null) {
x.e("MicroMsg.FaceDetectNativeManager", "hy: reelase not init");
return -101;
}
x.i("MicroMsg.FaceDetectNativeManager", "hy: cut down result: %d", new Object[]{Integer.valueOf(this.iNy.engineRelease())});
this.iNy = null;
return this.iNy.engineRelease();
}
}
|
package resources;
import dto.InventoryDetailsDto;
import dto.MessageDto;
import entity.Inventory;
import io.dropwizard.hibernate.UnitOfWork;
import service.InventoryService;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;
@Path("/inventory")
@Produces(MediaType.APPLICATION_JSON)
public class InventoryResource {
private InventoryService inventoryService;
public InventoryResource(InventoryService inventoryService) {
this.inventoryService = inventoryService;
}
@GET
@UnitOfWork
public InventoryDetailsDto getInventoryDetailsById(@QueryParam("id") long id) {
return inventoryService.getInventoryDetailById(id);
}
@POST
@UnitOfWork
public InventoryDetailsDto createNewInventory(InventoryDetailsDto inventoryDetailsDto) {
return inventoryService.createInventoryDetail(inventoryDetailsDto.getBookId(), inventoryDetailsDto.getQuantity());
}
@PUT
@UnitOfWork
public InventoryDetailsDto updateInventoryById(@QueryParam("id") long id, InventoryDetailsDto inventoryDetailsDto) {
return inventoryService.updateInventoryDetail(id, inventoryDetailsDto.getQuantity());
}
@DELETE
@UnitOfWork
public MessageDto deleteInventoryDetailsById(@QueryParam("id") long id) {
inventoryService.deleteInventoryDetailById(id);
return new MessageDto("Successfully deleted");
}
}
|
package com.example.mynews;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface NewsAPI {
@GET("top-headlines")
Call<NewsResponse> getNewsList(@Query("country") String newCountry, @Query("apiKey") String apiKey);
@GET("everything")
Call<NewsResponse> getNewsEverythingFilter(@Query("q") String katakunci, @Query("apiKey") String apiKey);
@GET("everything")
Call<NewsResponse> getNewsEverything(@Query("apiKey") String apiKey);
@GET("everything")
Call<NewsResponse> getNewsListFilter(@Query("q") String katakunci, @Query("apiKey") String apiKey);
@GET("sources")
Call<NewsResponse> getNewsSource(@Query("country") String country);
// @GET("everything")
// Call<NewsResponse>
}
|
package me.ljseokd.basicboard.modules.notice.reply;
import lombok.RequiredArgsConstructor;
import me.ljseokd.basicboard.modules.account.Account;
import me.ljseokd.basicboard.modules.account.AccountRepository;
import me.ljseokd.basicboard.modules.notice.Notice;
import me.ljseokd.basicboard.modules.notice.NoticeRepository;
import me.ljseokd.basicboard.modules.notice.event.ReplyCreatedEvent;
import me.ljseokd.basicboard.modules.notice.reply.form.ReplyForm;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
@RequiredArgsConstructor
public class ReplyService {
private final NoticeRepository noticeRepository;
private final AccountRepository accountRepository;
private final ReplyRepository replyRepository;
private final ApplicationEventPublisher eventPublisher;
public void addReply(Account account, Long noticeId, ReplyForm replyForm) {
String nickname = account.getNickname();
Notice notice = noticeRepository.findById(noticeId)
.orElseThrow(() -> new IllegalArgumentException(String.valueOf(noticeId)));
Account findAccount = accountRepository.findByNickname(nickname)
.orElseThrow(() -> new IllegalArgumentException(nickname));
Reply newReply = new Reply(findAccount, notice, replyForm.getContents());
eventPublisher.publishEvent(new ReplyCreatedEvent(newReply));
}
public void modifyContents(Long replyId, String contents) {
Reply reply = replyRepository.findById(replyId)
.orElseThrow(() -> new IllegalArgumentException(String.valueOf(replyId)));
reply.modifyContents(contents);
}
}
|
package com.sameer.springdemo;
public class MyApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
Coach theCoach = new TrackCoach();
System.out.println(theCoach.getDetailWorkout());
}
}
|
package elements;
public class HtmlTableCol extends HtmlElement {
private HtmlTag TABLECOL_OPEN_TAG = HtmlTag.TD_OPEN;
private HtmlTag CLOSE_TAG = HtmlTag.CLOSE_TAG;
private HtmlTag TABLECOL_CLOSE_TAG = HtmlTag.TD_CLOSE;
@Override
protected HtmlTag getStartTag() {
return TABLECOL_OPEN_TAG;
}
@Override
protected HtmlTag getCloseTag() {
return CLOSE_TAG;
}
@Override
public void addOption(HtmlOption option) {
}
@Override
public String print() {
return super.print() +
TABLECOL_CLOSE_TAG.text;
}
}
|
package com.tencent.mm.plugin.qqmail.ui;
import android.view.View;
import android.view.View.OnClickListener;
class ComposeUI$3 implements OnClickListener {
final /* synthetic */ ComposeUI mfs;
ComposeUI$3(ComposeUI composeUI) {
this.mfs = composeUI;
}
public final void onClick(View view) {
ComposeUI.j(this.mfs).getText().clear();
ComposeUI.j(this.mfs).requestFocus();
}
}
|
package com.cnk.travelogix.service;
import com.cnk.travelogix.fb.userdata.FBUserInfo;
/**
* Facebook Auth Template
*/
public interface FacebookAuthTemplate
{
/**
* @param paramString
* @return FBUserInfo
*/
public FBUserInfo getUserInfo(String paramString);
}
|
package com.tencent.mm.g.a;
public final class lz$b {
public boolean bJm = false;
public String bOX;
public String bWx;
}
|
package L17_March3;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;
public class GenericTree {
// private class Node {
int data;
ArrayList<Node> children = new ArrayList<>();
}
private Node root;
private int size;
public GenericTree() {
this.root = takeInput(new Scanner(System.in), null, -1);
}
public Node takeInput(Scanner scn, Node parent, int ith) {
// give prompt to user
if (parent == null) {
System.out.println("Enter the value for root node ?");
} else {
System.out.println("Enter the value for " + ith + " child of " + parent.data);
}
// take value of node from user
int val = scn.nextInt();
// create a new node
Node nn = new Node();
nn.data = val;
this.size++;
// prompt for no. of children
System.out.println("No. of children for " + nn.data + " ?");
int nc = scn.nextInt();
// loop on children
for (int i = 0; i < nc; i++) {
// take input of each child
Node child = takeInput(scn, nn, i);
// attach child with present node
nn.children.add(child);
}
return nn;
}
public int size() {
return this.size;
}
public boolean isEmpty() {
return this.size == 0;
}
public void display() {
System.out.println("----------------------");
display(this.root);
System.out.println("----------------------");
}
private void display(Node node) {
String str = node.data + " => ";
for (int i = 0; i < node.children.size(); i++) {
str += node.children.get(i).data + ", ";
}
str += ".";
System.out.println(str);
for (Node child : node.children) {
display(child);
}
}
public int size2() {
return size2(this.root);
}
private int size2(Node node) {
int cs = 0;
for (Node child : node.children) {
cs += size2(child);
}
return cs + 1;
}
public int max() {
return max(this.root);
}
private int max(Node node) {
int sm = node.data;
for (Node child : node.children) {
int cm = max(child);
if (cm > sm) {
sm = cm;
}
}
return sm;
}
// public int second_max_byme(){
// int[] a=new int[this.size2];
//
// return second_max_byme(this.root,a);
// }
// private int second_max_byme(Node node,int[] a){
//
//
//
// }
public boolean find(int item) {
return find(this.root, item);
}
private boolean find(Node node, int item) {
if (node.data == item) {
return true;
}
for (Node child : node.children) {
boolean res = find(child, item);
if (res) {
return true;
}
}
return false;
}
public int height() {
return height(this.root);
}
private int height(Node node) {
int sh = -1;
for (Node child : node.children) {
int ch = height(child);
if (ch > sh) {
sh = ch;
}
}
return sh + 1;
}
public void mirror() {
mirror(this.root);
}
private void mirror(Node node) {
for (Node child : node.children) {
mirror(child);
}
int left = 0;
int right = node.children.size() - 1;
while (left < right) {
Node ln = node.children.get(left);
Node rn = node.children.get(right);
node.children.set(left, rn);
node.children.set(right, ln);
left++;
right--;
}
}
public void preorder() {
System.out.println("----------------");
preorder(this.root);
System.out.println(".");
System.out.println("----------------");
}
private void preorder(Node node) {
System.out.print(node.data + " ");
for (Node child : node.children) {
preorder(child);
}
}
public void postorder() {
System.out.println("----------------");
postorder(this.root);
System.out.println(".");
System.out.println("----------------");
}
private void postorder(Node node) {
for (Node child : node.children) {
postorder(child);
}
System.out.print(node.data + " ");
}
public void traversal() {
System.out.println("----------------");
traversal(this.root);
System.out.println(".");
System.out.println("----------------");
}
private void traversal(Node node) {
System.out.println("hii " + node.data);
for (Node child : node.children) {
System.out.println("going towards " + child.data);
traversal(child);
System.out.println("coming back from " + child.data);
}
System.out.println("bye " + node.data);
}
public void levelorder() {
LinkedList<Node> queue = new LinkedList<>();
queue.addLast(this.root);
while (!queue.isEmpty()) {
Node rn = queue.removeFirst();
System.out.println(rn.data);
for (Node child : rn.children) {
queue.addLast(child);
}
}
}
public void levelorderLW() {
LinkedList<Node> primaryq = new LinkedList<>();
LinkedList<Node> helperq = new LinkedList<>();
primaryq.addLast(this.root);
while (!primaryq.isEmpty()) {
Node rn = primaryq.removeFirst();
System.out.print(rn.data + " ");
for (Node child : rn.children) {
helperq.addLast(child);
}
if (primaryq.isEmpty()) {
System.out.println();
primaryq = helperq;
helperq = new LinkedList<>();
}
}
}
public void levelorderZZ() {
int c = 0;
LinkedList<Node> queue = new LinkedList<>();
LinkedList<Node> stack = new LinkedList<>();
queue.addLast(this.root);
while (!queue.isEmpty()) {
Node rn = queue.removeFirst();
System.out.print(rn.data + " ");
if (c % 2 == 0) {
for (int i = 0; i < rn.children.size(); i++) {
stack.addFirst(rn.children.get(i));
}
} else {
for (int i = rn.children.size() - 1; i >= 0; i--) {
stack.addFirst(rn.children.get(i));
}
}
if (queue.isEmpty()) {
c++;
System.out.println();
queue = stack;
stack = new LinkedList<>();
}
}
}
public void multiSolver(int item) {
HeapMover mover = new HeapMover();
multiSolver(this.root, mover, item, 0);
System.out.println("Size : " + mover.size);
System.out.println("Height : " + mover.height);
System.out.println("Max : " + mover.max);
System.out.println("Found : " + mover.found);
System.out.println("Pred : " + (mover.predecessor == null ? null : mover.predecessor.data));
System.out.println("Succ : " + (mover.successor == null ? null : mover.successor.data));
System.out.println("JL : " + (mover.jl == null ? null : mover.jl.data));
}
private void multiSolver(Node node, HeapMover mover, int item, int level) {
mover.size++;
if (level > mover.height) {
mover.height = level;
}
if (node.data > mover.max) {
mover.max = node.data;
}
if (mover.found == true && mover.successor == null) {
mover.successor = node;
}
if (node.data == item) {
mover.found = true;
}
if (mover.found == false) {
mover.predecessor = node;
}
if (node.data > item) {
if (mover.jl == null) {
mover.jl = node;
} else {
if (node.data < mover.jl.data) {
mover.jl = node;
}
}
}
for (Node child : node.children) {
multiSolver(child, mover, item, level + 1);
}
}
private class HeapMover {
int size = 0;
int height = 0;
int max = Integer.MIN_VALUE;
boolean found = false;
Node predecessor;
Node successor;
Node jl;
}
private class OrderPair {
Node node;
boolean selfDone;
int childrenDone;
}
public void preorderI() {
System.out.println("----------------");
LinkedList<OrderPair> stack = new LinkedList<>();
OrderPair fp = new OrderPair();
fp.node = this.root;
stack.addFirst(fp);
while (!stack.isEmpty()) {
OrderPair tp = stack.getFirst();
if (tp.selfDone == false) {
System.out.print(tp.node.data + " ");
tp.selfDone = true;
} else if (tp.childrenDone < tp.node.children.size()) {
OrderPair np = new OrderPair();
np.node = tp.node.children.get(tp.childrenDone);
stack.addFirst(np);
tp.childrenDone++;
} else {
stack.removeFirst();
}
}
System.out.println(".");
System.out.println("----------------");
}
}
|
package com.jingb.application.ninegag;
/**
* Created by jingb on 16/3/19.
*/
public class NineGagDatagram {
String status;
String message;
NineGagPaging paging;
NineGagImageDatagram[] data;
public NineGagImageDatagram[] getData() {
return data;
}
public void setData(NineGagImageDatagram[] data) {
this.data = data;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public NineGagPaging getPaging() {
return paging;
}
public void setPaging(NineGagPaging paging) {
this.paging = paging;
}
}
|
package com.rockwellcollins.atc.limp.converter;
import org.eclipse.xtext.conversion.IValueConverter;
import org.eclipse.xtext.conversion.ValueConverter;
import org.eclipse.xtext.conversion.impl.AbstractDeclarativeValueConverterService;
import org.eclipse.xtext.conversion.impl.STRINGValueConverter;
import com.google.inject.Inject;
public class LimpValueConverterService extends AbstractDeclarativeValueConverterService {
@Inject
private STRINGValueConverter stringValueConverter;
@ValueConverter(rule = "STRING")
public IValueConverter<String> STRING() {
return stringValueConverter;
}
}
|
package com.vilio.bps.inquiry.pojo;
import java.io.Serializable;
import java.util.Date;
/**
* Created by zhuxu on 2017/5/4.
*/
public class InquiryBaseValueBean implements Serializable{
//关联估价公司
private String companyCode;
//
private String code;
//状态值 1 有估价值;2 等待人工估价; 3 无法估价
private String status;
//估值
private String price;
private Date priceTime;
public String getCompanyCode() {
return companyCode;
}
public void setCompanyCode(String companyCode) {
this.companyCode = companyCode;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public Date getPriceTime() {
return priceTime;
}
public void setPriceTime(Date priceTime) {
this.priceTime = priceTime;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.