text stringlengths 10 2.72M |
|---|
package com.days.moment.qna.service;
import com.days.moment.qna.mapper.QnaTimeMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
@Log4j2
@Service
@RequiredArgsConstructor
public class QnaTimeServiceImpl implements QnaTimeService{
private final QnaTimeMapper qnaTimeMapper;
@Override
public String getNow() {
log.info("service...............getNow()");
return qnaTimeMapper.getTime3();
}
}
|
package production.dao;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import production.entity.Location;
import production.entity.LocationCollection;
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class LocationDao extends AbstractDao<Location>{
/**
*
*/
private static final long serialVersionUID = 1L;
@Inject
private EntityManager entityManager;
public LocationDao() {
super(Location.class);
}
@SuppressWarnings("unchecked")
public LocationCollection getAllLocationsForIdentifier(String userIdentifier) {
String queryString = "Select * from locations where user_identifier = '"
+ userIdentifier + "'";
Query query = this.entityManager.createNativeQuery(queryString, Location.class);
List<Location> locationList =(List<Location>) query.getResultList();
return this.loadLocationListToCollection(locationList);
}
private LocationCollection loadLocationListToCollection(List<Location> locationList)
{
LocationCollection locationCollection = new LocationCollection();
ArrayList<Location> locationsArray = new ArrayList<Location>(locationList);
locationCollection.setLocations(locationsArray);
return locationCollection;
}
}
|
/*
* 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.config;
import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.logging.Level;
import org.apache.webbeans.annotation.AnnotationManager;
import org.apache.webbeans.container.BeanManagerImpl;
import org.apache.webbeans.container.InjectableBeanManager;
import org.apache.webbeans.container.SerializableBeanVault;
import org.apache.webbeans.context.creational.CreationalContextFactory;
import org.apache.webbeans.conversation.ConversationManager;
import org.apache.webbeans.conversation.DefaultConversationService;
import org.apache.webbeans.corespi.se.DefaultApplicationBoundaryService;
import org.apache.webbeans.corespi.se.DefaultContextsService;
import org.apache.webbeans.corespi.se.DefaultJndiService;
import org.apache.webbeans.corespi.security.SimpleSecurityService;
import org.apache.webbeans.decorator.DecoratorsManager;
import org.apache.webbeans.deployment.StereoTypeManager;
import org.apache.webbeans.event.NotificationManager;
import org.apache.webbeans.exception.WebBeansException;
import org.apache.webbeans.inject.AlternativesManager;
import org.apache.webbeans.inject.impl.InjectionPointFactory;
import org.apache.webbeans.intercept.InterceptorResolutionService;
import org.apache.webbeans.intercept.InterceptorUtil;
import org.apache.webbeans.intercept.InterceptorsManager;
import org.apache.webbeans.logger.WebBeansLoggerFacade;
import org.apache.webbeans.plugins.PluginLoader;
import org.apache.webbeans.portable.AnnotatedElementFactory;
import org.apache.webbeans.portable.events.ExtensionLoader;
import org.apache.webbeans.proxy.SubclassProxyFactory;
import org.apache.webbeans.proxy.InterceptorDecoratorProxyFactory;
import org.apache.webbeans.proxy.NormalScopeProxyFactory;
import org.apache.webbeans.service.DefaultInjectionPointService;
import org.apache.webbeans.service.DefaultLoaderService;
import org.apache.webbeans.spi.BeanArchiveService;
import org.apache.webbeans.spi.ApplicationBoundaryService;
import org.apache.webbeans.spi.ContextsService;
import org.apache.webbeans.spi.ConversationService;
import org.apache.webbeans.spi.LoaderService;
import org.apache.webbeans.spi.ScannerService;
import org.apache.webbeans.spi.SecurityService;
import org.apache.webbeans.spi.TransactionService;
import org.apache.webbeans.spi.plugins.OpenWebBeansPlugin;
import org.apache.webbeans.util.ClassUtil;
import org.apache.webbeans.util.WebBeansUtil;
import org.apache.webbeans.xml.DefaultBeanArchiveService;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.BeanManager;
/**
* This is the central point to manage the whole CDI container
* for a single application There is one WebBeansContext per BeanManagerImpl.
*
* @version $Rev$ $Date$
*/
public class WebBeansContext
{
private final Map<Class<?>, Object> managerMap = new HashMap<>();
private final Map<Class<?>, Object> serviceMap = new HashMap<>();
private final WebBeansUtil webBeansUtil = new WebBeansUtil(this);
private final AlternativesManager alternativesManager = new AlternativesManager(this);
private final AnnotatedElementFactory annotatedElementFactory = new AnnotatedElementFactory(this);
private final BeanManagerImpl beanManagerImpl = new BeanManagerImpl(this);
private final CreationalContextFactory creationalContextFactory = new CreationalContextFactory(this);
private final DecoratorsManager decoratorsManager = new DecoratorsManager(this);
private final ExtensionLoader extensionLoader = new ExtensionLoader(this);
private final InterceptorsManager interceptorsManager = new InterceptorsManager(this);
private final InterceptorDecoratorProxyFactory interceptorDecoratorProxyFactory;
private final NormalScopeProxyFactory normalScopeProxyFactory;
private final SubclassProxyFactory subclassProxyFactory;
private final OpenWebBeansConfiguration openWebBeansConfiguration;
private final PluginLoader pluginLoader = new PluginLoader();
private final SerializableBeanVault serializableBeanVault = new SerializableBeanVault();
private final StereoTypeManager stereoTypeManager = new StereoTypeManager();
private final AnnotationManager annotationManager;
private final InjectionPointFactory injectionPointFactory;
private final InterceptorUtil interceptorUtil = new InterceptorUtil(this);
private final SecurityService securityService;
private final LoaderService loaderService;
private final InjectableBeanManager injectableBeanManager;
private final Bean<BeanManager> beanManagerBean;
private BeanArchiveService beanArchiveService;
private final InterceptorResolutionService interceptorResolutionService = new InterceptorResolutionService(this);
private final DeploymentValidationService deploymentValidationService = new DeploymentValidationService(this);
private ScannerService scannerService;
private ContextsService contextsService;
private final ConversationManager conversationManager;
private ConversationService conversationService;
private final ApplicationBoundaryService applicationBoundaryService;
private final NotificationManager notificationManager;
private TransactionService transactionService;
public WebBeansContext()
{
this(null, new OpenWebBeansConfiguration());
}
public WebBeansContext(Map<Class<?>, Object> initialServices, Properties properties)
{
this(initialServices, new OpenWebBeansConfiguration(properties));
}
private WebBeansContext(Map<Class<?>, Object> initialServices, OpenWebBeansConfiguration openWebBeansConfiguration)
{
this.openWebBeansConfiguration = openWebBeansConfiguration != null ? openWebBeansConfiguration : new OpenWebBeansConfiguration();
annotationManager = new AnnotationManager(this);
//pluggable service-loader
if (initialServices == null || !initialServices.containsKey(LoaderService.class))
{
String implementationLoaderServiceName =
this.openWebBeansConfiguration.getProperty(LoaderService.class.getName());
if (implementationLoaderServiceName == null)
{
serviceMap.put(LoaderService.class, new DefaultLoaderService());
}
else
{
serviceMap.put(LoaderService.class, LoaderService.class.cast(get(implementationLoaderServiceName)));
}
}
if (initialServices != null)
{
for (Map.Entry<Class<?>, Object> entry: initialServices.entrySet())
{
if (!entry.getKey().isAssignableFrom(entry.getValue().getClass()))
{
throw new IllegalArgumentException("Initial service claiming to be of type " + entry.getKey() + " is a " + entry.getValue().getClass());
}
serviceMap.put(entry.getKey(), entry.getValue());
}
}
injectionPointFactory = new InjectionPointFactory(this);
loaderService = getService(LoaderService.class);
securityService = getService(SecurityService.class);
applicationBoundaryService = getService(ApplicationBoundaryService.class);
interceptorDecoratorProxyFactory = new InterceptorDecoratorProxyFactory(this);
normalScopeProxyFactory = new NormalScopeProxyFactory(this);
subclassProxyFactory = new SubclassProxyFactory(this);
beanArchiveService = getService(BeanArchiveService.class);
conversationManager = new ConversationManager(this);
notificationManager = new NotificationManager(this);
beanManagerImpl.getInjectionResolver().setFastMatching(!"false".equalsIgnoreCase(getOpenWebBeansConfiguration()
.getProperty(OpenWebBeansConfiguration.FAST_MATCHING)));
injectableBeanManager = new InjectableBeanManager(beanManagerImpl);
beanManagerBean = getWebBeansUtil().getManagerBean();
}
public Bean<BeanManager> getBeanManagerBean()
{
return beanManagerBean;
}
public InjectableBeanManager getInjectableBeanManager()
{
return injectableBeanManager;
}
public static WebBeansContext getInstance()
{
WebBeansContext webBeansContext = WebBeansFinder.getSingletonInstance();
return webBeansContext;
}
/**
* Method to be used when static use is truely unavoidable, such as serialization
*
* Ideally this method would never lazily create a WebBeansContext and as we don't
* want to do any deployment of new apps during deserialization, we want to rehydrate
* objects from an existing WebBeansContext which should be the active context.
*
* This method could throw a runtime exception if no instance currently exists.
*
* @return
*/
public static WebBeansContext currentInstance()
{
return getInstance();
}
public <T> T getService(Class<T> clazz)
{
T t = clazz.cast(serviceMap.get(clazz));
if (t == null)
{
t = doServiceLoader(clazz);
registerService(clazz, t);
}
return t;
}
public <T> void registerService(Class<T> clazz, T t)
{
if (t != null)
{
serviceMap.put(clazz, t);
}
}
private <T> T doServiceLoader(Class<T> serviceInterface)
{
String implName = getOpenWebBeansConfiguration().getProperty(serviceInterface.getName());
if (implName == null)
{
//Look for plugins
List<OpenWebBeansPlugin> plugins = getPluginLoader().getPlugins();
if(plugins != null && plugins.size() > 0)
{
for(OpenWebBeansPlugin plugin : plugins)
{
if(plugin.supportService(serviceInterface))
{
return plugin.getSupportedService(serviceInterface);
}
}
}
return null;
}
return serviceInterface.cast(get(implName));
}
public InterceptorUtil getInterceptorUtil()
{
return interceptorUtil;
}
public InjectionPointFactory getInjectionPointFactory()
{
return injectionPointFactory;
}
public WebBeansUtil getWebBeansUtil()
{
return webBeansUtil;
}
public AnnotationManager getAnnotationManager()
{
return annotationManager;
}
public ConversationManager getConversationManager()
{
return conversationManager;
}
public OpenWebBeansConfiguration getOpenWebBeansConfiguration()
{
return openWebBeansConfiguration;
}
public AnnotatedElementFactory getAnnotatedElementFactory()
{
return annotatedElementFactory;
}
public BeanManagerImpl getBeanManagerImpl()
{
return beanManagerImpl;
}
public SerializableBeanVault getSerializableBeanVault()
{
return serializableBeanVault;
}
public CreationalContextFactory getCreationalContextFactory()
{
return creationalContextFactory;
}
public DecoratorsManager getDecoratorsManager()
{
return decoratorsManager;
}
public StereoTypeManager getStereoTypeManager()
{
return stereoTypeManager;
}
public AlternativesManager getAlternativesManager()
{
return alternativesManager;
}
public InterceptorsManager getInterceptorsManager()
{
return interceptorsManager;
}
public InterceptorResolutionService getInterceptorResolutionService()
{
return interceptorResolutionService;
}
public PluginLoader getPluginLoader()
{
return pluginLoader;
}
public ExtensionLoader getExtensionLoader()
{
return extensionLoader;
}
public InterceptorDecoratorProxyFactory getInterceptorDecoratorProxyFactory()
{
return interceptorDecoratorProxyFactory;
}
public NormalScopeProxyFactory getNormalScopeProxyFactory()
{
return normalScopeProxyFactory;
}
public SubclassProxyFactory getSubclassProxyFactory()
{
return subclassProxyFactory;
}
public TransactionService getTransactionService() // used in event bus so ensure it is a plain getter at runtime
{
if (transactionService == null)
{
// lazy init
transactionService = getService(TransactionService.class);
}
return transactionService;
}
public ScannerService getScannerService()
{
if (scannerService == null)
{
// lazy init
scannerService = getService(ScannerService.class);
}
return scannerService;
}
public ContextsService getContextsService()
{
if (contextsService == null)
{
contextsService = getService(ContextsService.class);
}
return contextsService;
}
public SecurityService getSecurityService()
{
return securityService;
}
public BeanArchiveService getBeanArchiveService()
{
return beanArchiveService;
}
public NotificationManager getNotificationManager()
{
return notificationManager;
}
public ConversationService getConversationService()
{
if (conversationService == null)
{
conversationService = getService(ConversationService.class);
}
return conversationService;
}
private Object get(String singletonName)
{
// skip reflection for these services
if (DefaultInjectionPointService.class.getName().equals(singletonName))
{
return new DefaultInjectionPointService(this);
}
if (SimpleSecurityService.class.getName().equals(singletonName))
{
return new SimpleSecurityService();
}
if (DefaultApplicationBoundaryService.class.getName().equals(singletonName))
{
return new DefaultApplicationBoundaryService();
}
if (DefaultBeanArchiveService.class.getName().equals(singletonName))
{
return new DefaultBeanArchiveService();
}
if (DefaultJndiService.class.getName().equals(singletonName))
{
return new DefaultJndiService();
}
if (DefaultContextsService.class.getName().equals(singletonName))
{
return new DefaultContextsService(this);
}
if (DefaultConversationService.class.getName().equals(singletonName))
{
return new DefaultConversationService();
}
// Load class by reflection
Class<?> clazz = ClassUtil.getClassFromName(singletonName);
if (clazz == null)
{
throw new WebBeansException("Class not found exception in creating instance with class : " + singletonName,
new ClassNotFoundException("Class with name: " + singletonName + " is not found in the system"));
}
return get(clazz);
}
public <T> T get(Class<T> clazz)
{
//util.Track.get(clazz);
T object = clazz.cast(managerMap.get(clazz));
/* No singleton for this application, create one */
if (object == null)
{
object = backwardCompatibilityLookup(clazz);
if (object == null)
{
object = createInstance(clazz);
}
// Save it for future usages
managerMap.put(clazz, object);
}
return object;
}
private <T> T backwardCompatibilityLookup(final Class<T> clazz)
{
if (clazz.isInstance(this)) // Allow the WebBeansContext itself to be looked up
{
return clazz.cast(this);
}
// Add them all into the map for backwards compatibility
if (clazz == AlternativesManager.class)
{
return clazz.cast(alternativesManager);
}
if (clazz == AnnotatedElementFactory.class)
{
return clazz.cast(annotatedElementFactory);
}
if (clazz == BeanManagerImpl.class)
{
return clazz.cast(beanManagerImpl);
}
if (clazz == ConversationManager.class)
{
return clazz.cast(conversationManager);
}
if (clazz == CreationalContextFactory.class)
{
return clazz.cast(creationalContextFactory);
}
if (clazz == DecoratorsManager.class)
{
return clazz.cast(decoratorsManager);
}
if (clazz == ExtensionLoader.class)
{
return clazz.cast(extensionLoader);
}
if (clazz == InterceptorsManager.class)
{
return clazz.cast(interceptorsManager);
}
if (clazz == InterceptorDecoratorProxyFactory.class)
{
return clazz.cast(interceptorDecoratorProxyFactory);
}
if (clazz == NormalScopeProxyFactory.class)
{
return clazz.cast(normalScopeProxyFactory);
}
if (clazz == SubclassProxyFactory.class)
{
return clazz.cast(subclassProxyFactory);
}
if (clazz == OpenWebBeansConfiguration.class)
{
return clazz.cast(openWebBeansConfiguration);
}
if (clazz == PluginLoader.class)
{
return clazz.cast(pluginLoader);
}
if (clazz == SerializableBeanVault.class)
{
return clazz.cast(serializableBeanVault);
}
if (clazz == StereoTypeManager.class)
{
return clazz.cast(stereoTypeManager);
}
if (clazz == InterceptorResolutionService.class)
{
return clazz.cast(interceptorResolutionService);
}
if (clazz == NotificationManager.class)
{
return clazz.cast(notificationManager);
}
return null;
}
private <T> T createInstance(Class<T> clazz)
{
// skip the reflection for know classes
if (DefaultLoaderService.class == clazz)
{
return clazz.cast(new DefaultLoaderService());
}
if (SimpleSecurityService.class == clazz)
{
return clazz.cast(new SimpleSecurityService());
}
if (DefaultApplicationBoundaryService.class == clazz)
{
return clazz.cast(new DefaultApplicationBoundaryService());
}
if (DefaultBeanArchiveService.class == clazz)
{
return clazz.cast(new DefaultBeanArchiveService());
}
if (DefaultJndiService.class == clazz)
{
return clazz.cast(new DefaultJndiService());
}
if (DefaultContextsService.class == clazz)
{
return clazz.cast(new DefaultContextsService(this));
}
if (DefaultConversationService.class == clazz)
{
return clazz.cast(new DefaultConversationService());
}
// try by reflection for extensions
try
{
// first try constructor that takes this object as an argument
try
{
Constructor<T> constructor = clazz.getConstructor(WebBeansContext.class);
return constructor.newInstance(this);
}
catch (NoSuchMethodException e)
{
}
// then try a no-arg constructor
try
{
Constructor<T> constructor = clazz.getConstructor();
return constructor.newInstance();
}
catch (NoSuchMethodException e)
{
throw new WebBeansException("No suitable constructor : " + clazz.getName(), e.getCause());
}
}
catch (InstantiationException | InvocationTargetException e)
{
throw new WebBeansException("Unable to instantiate class : " + clazz.getName(), e.getCause());
}
catch (IllegalAccessException e)
{
throw new WebBeansException("Illegal access exception in creating instance with class : " + clazz.getName(), e);
}
}
/**
* Clear and destroy the whole WebBeansContext.
* This will also properly destroy all SPI services
*/
public void clear()
{
destroyServices(managerMap.values());
destroyServices(serviceMap.values());
managerMap.clear();
serviceMap.clear();
}
private void destroyServices(Collection<Object> services)
{
for (Object spiService : services)
{
if (spiService instanceof Closeable)
{
try
{
((Closeable) spiService).close();
}
catch (IOException e)
{
WebBeansLoggerFacade.getLogger(WebBeansContext.class)
.log(Level.SEVERE, "Error while destroying SPI service " + spiService.getClass().getName(), e);
}
}
else if (ExecutorService.class.isInstance(spiService))
{
ExecutorService es = ExecutorService.class.cast(spiService);
es.shutdownNow().forEach(r -> {
try
{
r.run();
}
catch (RuntimeException re)
{
WebBeansLoggerFacade.getLogger(WebBeansContext.class).warning(re.getMessage());
}
});
}
}
}
public LoaderService getLoaderService()
{
return loaderService;
}
public DeploymentValidationService getDeploymentValidationService()
{
return deploymentValidationService;
}
public ApplicationBoundaryService getApplicationBoundaryService()
{
return applicationBoundaryService;
}
public boolean findMissingAnnotatedType(Class<?> missing)
{
return false; // used in hierarchical WBC
}
}
|
package Praktikum.src;
public class BukuNovel extends Buku {
private String kategori;
private int halaman;
public void setKategori(String newValue) {
kategori = newValue;
}
public void setHalaman(int newValue) {
halaman = newValue;
}
public int tambahHalaman(int newValue) {
halaman += newValue;
return halaman;
}
public int kurangiHalaman(int newValue) {
halaman -= newValue;
return halaman;
}
public String hapusKategori() {
kategori = "";
return kategori;
}
public void info() {
super.info();
System.out.println("Kategori\t\t: " + kategori);
System.out.println("Jumlah halaman\t\t: " + halaman + " halaman");
}
} |
package com.bookstore.users;
import com.bookstore.LoggedInUserData;
public class User {
private String name = "Undefined";
private String password;
private String username;
private boolean isAdmin = false;
public User(){}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public User(String username, String password, boolean isAdmin) {
this.username = username;
this.password = password;
this.isAdmin = isAdmin;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public boolean isPassword(String pass){
return this.password.equals(pass);
}
public boolean isAdmin(){
return this.isAdmin;
}
public void makeAdmin(){
if(LoggedInUserData.loggedInUser.isAdmin())
this.isAdmin = true;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package com.noname.setalarm.repository;
import com.noname.setalarm.model.ClockModel;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import java.util.List;
@Dao
public interface AlarmDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
void insertAlarm(AlarmRoom... alarmRoom);
@Query("UPDATE AlarmRoom SET timeList= :timeList WHERE alarmId = :id")
void updateAlarm(String id, List<ClockModel> timeList);
@Query("UPDATE AlarmRoom SET checked= :checked WHERE alarmId = :id")
void updateAlarmState(String id , boolean checked);
@Delete
void deleteAlarm(AlarmRoom alarmRoom);
@Query("SELECT * from AlarmRoom")
LiveData<List<AlarmRoom>> getAllAlarm();
}
|
package week2.day2homework;
import org.openqa.selenium.chrome.ChromeDriver;
public class Editlead {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","./Drivers/chromedriver.exe");
ChromeDriver driver=new ChromeDriver();
driver.get("http://leaftaps.com/opentaps");
driver.manage().window().maximize();
Thread.sleep(3000);
driver.findElementById("username").sendKeys("demosalesmanager");
driver.findElementById("password").sendKeys("crmsfa");
driver.findElementByClassName("decorativeSubmit").click();
Thread.sleep(3000);
driver.findElementByLinkText("CRM/SFA").click();
driver.findElementByLinkText("Create Lead").click();
driver.findElementByLinkText("Find Leads").click();
driver.findElementByXPath("(//span[@class='x-tab-strip-text '])[3]").click();
driver.findElementByXPath("//input[@name='emailAddress']").sendKeys("Pravin@gmail.com");
driver.findElementByXPath("//button[text()='Find Leads']").click();
Thread.sleep(5000);
driver.findElementByXPath("//div[@class='x-grid3-body']//a").click();
String title = driver.getTitle();
//System.out.println(title);
String Title1="View Lead | opentaps CRM";
if (title.equalsIgnoreCase(Title1))
{
System.out.println("Title is succcesfully Verified");
}
else {
System.out.println("Title is not Verified");
}
Thread.sleep(3000);
driver.findElementByXPath("(//a[@class='subMenuButton'])[3]").click();
Thread.sleep(3000);
driver.findElementById("updateLeadForm_companyName").clear();
driver.findElementById("updateLeadForm_companyName").sendKeys("TestDemo");
Thread.sleep(3000);
driver.findElementByXPath("//input[@value='Update']").click();
Thread.sleep(3000);
String textcompanyname = driver.findElementById("viewLead_companyName_sp").getText();
//System.out.println(textcompanyname);
String updatedindex="TestDemo";
if (textcompanyname.startsWith(updatedindex))
{
System.out.println(" Company name Verified");
}
else {
System.out.println("Company name Not verified");
}
driver.close();
}
}
|
package com.meridal.examples.recordcollection.domain;
public class SearchResult extends Entry {
private String title;
public SearchResult() {
super();
}
public SearchResult(final Integer id, final String title) {
super(id);
this.setTitle(title);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return new StringBuilder()
.append(this.getId())
.append(" ").append(this.title)
.toString();
}
}
|
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import model.Model;
import view.Application;
public class IncrementController implements ActionListener {
Model model;
Application application;
public IncrementController(Model model, Application application) {
this.model = model;
this.application = application;
}
@Override
public void actionPerformed(ActionEvent e) {
model.incrementCounter();
application.refresh();
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.test;
import edu.tsinghua.lumaqq.resource.Resources;
import edu.tsinghua.lumaqq.widgets.qstyle.IQTreeContentProvider;
import edu.tsinghua.lumaqq.widgets.qstyle.IQTreeLabelProvider;
import edu.tsinghua.lumaqq.widgets.qstyle.ItemLayout;
import edu.tsinghua.lumaqq.widgets.qstyle.QItem;
import edu.tsinghua.lumaqq.widgets.qstyle.QTree;
import edu.tsinghua.lumaqq.widgets.qstyle.QTreeViewer;
import edu.tsinghua.lumaqq.widgets.qstyle.Slat;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* @author luma
*/
public class QTreeViewerTest {
private class Model {
public int faceId;
public String text;
public Model(int f, String t) {
faceId = f;
text = t;
}
};
Model[] roots = new Model[] {
new Model(42, "Hello"),
new Model(45, "心软俱乐部"),
new Model(48, "哇哇")
};
private Shell shell;
private Display display;
public static void main(String[] args) {
QTreeViewerTest t = new QTreeViewerTest();
t.open();
}
/**
* 打开对话框
*/
public void open() {
// event loop
shell = new Shell(new Display());
display = shell.getDisplay();
shell.setLayout(new GridLayout());
shell.setSize(400, 300);
shell.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
final Slat slat = new Slat(shell, SWT.FLAT | SWT.CENTER, "Hello");
slat.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
final QTreeViewer<Model> viewer = new QTreeViewer<Model>(shell);
QTree tree = viewer.getQTree();
viewer.setContentProvider(new IQTreeContentProvider<Model>() {
public Model[] getElements(Object inputElement) {
return roots;
}
public Model[] getChildren(Model parent) {
if(parent == roots[0])
return new Model[] { roots[1], roots[roots.length - 1]};
return new Model[0];
}
public Model getParent(Model child) {
return null;
}
public boolean hasChildren(Model parent) {
return false;
}
});
viewer.setLabelProvider(new IQTreeLabelProvider<Model>() {
public String getText(Model element) {
return element.text;
}
public Image getImage(Model element) {
return Resources.getInstance().getHead(element.faceId);
}
public Image getDecoration(Model element) {
return Resources.getInstance().getImage(Resources.icoAwayDecoration);
}
public Image getAttachment(Model element, int index) {
// TODO Auto-generated method stub
return null;
}
public Color getForeground(Model element) {
// TODO Auto-generated method stub
return null;
}
public boolean isExpaned(Model element) {
// TODO Auto-generated method stub
return false;
}
public void setExpanded(Model element, boolean exp) {
// TODO Auto-generated method stub
}
public Image getPrefix(Model element) {
return Resources.getInstance().getImage(Resources.icoExpanded9);
}
});
viewer.setInput(this);
tree.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
tree.setLevelImageSize(1, 32);
tree.setLevelLayout(1, ItemLayout.VERTICAL);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.horizontalIndent = 100;
tree.setLayoutData(gd);
viewer.addDragSupport(DND.DROP_MOVE, new Transfer[] { TextTransfer.getInstance() }, new DragSourceListener() {
public void dragStart(DragSourceEvent event) {
QTree tree = (QTree)((DragSource)event.getSource()).getControl();
QItem item = tree.getItemUnderMouse();
if(item == null || item.getParentItem() == null)
event.doit = false;
else {
tree.saveExpandStatus();
tree.collapseAll();
}
}
public void dragSetData(DragSourceEvent event) {
QTree tree = (QTree)((DragSource)event.getSource()).getControl();
QItem item = tree.getItemUnderMouse();
event.data = item.getText();
}
public void dragFinished(DragSourceEvent event) {
QTree tree = (QTree)((DragSource)event.getSource()).getControl();
tree.restoreExpandStatus();
}
});
viewer.addDropSupport(DND.DROP_MOVE, new Transfer[] { TextTransfer.getInstance() }, new DropTargetListener() {
public void dragEnter(DropTargetEvent event) {
// TODO Auto-generated method stub
}
public void dragLeave(DropTargetEvent event) {
// TODO Auto-generated method stub
}
public void dragOperationChanged(DropTargetEvent event) {
// TODO Auto-generated method stub
}
public void dragOver(DropTargetEvent event) {
}
public void drop(DropTargetEvent event) {
QTree tree = (QTree)((DropTarget)event.getSource()).getControl();
Point loc = tree.toControl(event.x, event.y);
QItem item = tree.getItem(loc.x, loc.y);
System.out.println(event.data);
if(item != null)
System.out.println(item.getText());
}
public void dropAccept(DropTargetEvent event) {
// TODO Auto-generated method stub
}
});
shell.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
// roots = new Model[200];
// for(int i = 0; i < roots.length; i++) {
// roots[i] = new Model(i % 255, String.valueOf(i));
// }
// viewer.refresh();
// if(e.button == 3)
// slat.editText();
slat.setShowText(e.button == 1);
}
@Override
public void mouseUp(MouseEvent e) {
}
@Override
public void mouseDoubleClick(MouseEvent e) {
}
});
shell.layout();
shell.open();
while(!shell.isDisposed())
if(!display.readAndDispatch())
display.sleep();
}
}
|
package com.mybatis.interceptor.aspect;
import com.mybatis.interceptor.abstracts.BaseAspectAbstract;
import com.mybatis.interceptor.annotation.GroupBy;
import com.mybatis.interceptor.filterinterceptor.SQLLanguage;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import static com.mybatis.interceptor.enums.SQLEnums.GROUPBY;
/**
* @author yi
* @ClassName GroupByAspect
* @Description TODO
* @Date
**/
@Component
@Aspect
@Order(0)
public class GroupByAspect extends BaseAspectAbstract {
@Pointcut("@annotation(com.mybatis.interceptor.annotation.GroupBy)")
public void groupByCut() {}
@Before("groupByCut()")
public void groupBy(JoinPoint point) {
StringBuilder groupByBuilder = new StringBuilder(" GROUP BY ");
MethodSignature methodSignature = (MethodSignature)point.getSignature();
//获得对应注解
GroupBy groupBy =
methodSignature.getMethod().getAnnotation(GroupBy.class);
if (!StringUtils.isEmpty(groupBy)) {
if (!StringUtils.isEmpty(groupBy.tableAlias())) {
groupByBuilder.append(groupBy.tableAlias()+".");
}
groupByBuilder.append(groupBy.column());
putSQL(point,GROUPBY,new SQLLanguage(groupByBuilder.toString()));
}
}
}
|
package com.yy.lite.brpc.interceptor;
import com.baidu.brpc.interceptor.AbstractInterceptor;
import com.baidu.brpc.interceptor.InterceptorChain;
import com.baidu.brpc.protocol.Request;
import com.baidu.brpc.protocol.Response;
import com.yy.sv.base.util.MetricsClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BrpcMetricsInterceptor extends AbstractInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(BrpcMetricsInterceptor.class);
private static final int CODE_OK = 0;
private static final int CODE_ERROR = 1;
public static final String LOG_PROCESS_FINISH = "Brpc client method {} invoke finish, cost time:{},req:{},resp:{}";
public static final String LOG_PROCESS_ERROR= "Brpc client method {} invoke error, cost time:{},args:{}";
@Override
public void aroundProcess(Request request, Response response, InterceptorChain chain) throws Exception {
String method = request.getServiceName()+"_"+request.getMethodName();
long startTime = System.currentTimeMillis();
int metricsCode = CODE_OK;
super.aroundProcess(request, response, chain);
long costTime = System.currentTimeMillis() - startTime;
MetricsClient.reportDataInner(method, metricsCode, costTime);
if(response.getException()!=null){
metricsCode = CODE_ERROR;
}
if( metricsCode == CODE_OK){
LOGGER.info(LOG_PROCESS_FINISH, method, costTime,request.getArgs(),"");
}else{
LOGGER.error(LOG_PROCESS_ERROR, method, costTime,request.getArgs());
}
}
} |
package com.huawei.esdk.demo.autogen;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
/**
* This class was generated by Apache CXF 2.6.1
* 2014-04-29T10:32:46.546+08:00
* Generated source version: 2.6.1
*
*/
@WebService(targetNamespace = "http://smc.huawei.com/", name = "TPProfessional.ConfMgr")
@XmlSeeAlso({ObjectFactory.class})
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface TPProfessionalConfMgr {
@WebResult(name = "querySitesExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/querySitesEx")
public QuerySitesExResponse querySitesEx(
@WebParam(partName = "parameters", name = "querySitesEx", targetNamespace = "http://smc.huawei.com/")
QuerySitesEx parameters
);
@WebResult(name = "editRecurrenceConferenceExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/editRecurrenceConferenceEx")
public EditRecurrenceConferenceExResponse editRecurrenceConferenceEx(
@WebParam(partName = "parameters", name = "editRecurrenceConferenceEx", targetNamespace = "http://smc.huawei.com/")
EditRecurrenceConferenceEx parameters
);
@WebResult(name = "synchSiteStatusExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/synchSiteStatusEx")
public SynchSiteStatusExResponse synchSiteStatusEx(
@WebParam(partName = "parameters", name = "synchSiteStatusEx", targetNamespace = "http://smc.huawei.com/")
SynchSiteStatusEx parameters
);
@WebResult(name = "queryConferencesStatusExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/queryConferencesStatusEx")
public QueryConferencesStatusExResponse queryConferencesStatusEx(
@WebParam(partName = "parameters", name = "queryConferencesStatusEx", targetNamespace = "http://smc.huawei.com/")
QueryConferencesStatusEx parameters
);
@WebResult(name = "querySiteStatusExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/querySiteStatusEx")
public QuerySiteStatusExResponse querySiteStatusEx(
@WebParam(partName = "parameters", name = "querySiteStatusEx", targetNamespace = "http://smc.huawei.com/")
QuerySiteStatusEx parameters
);
@WebResult(name = "addSiteToConfExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/addSiteToConfEx")
public AddSiteToConfExResponse addSiteToConfEx(
@WebParam(partName = "parameters", name = "addSiteToConfEx", targetNamespace = "http://smc.huawei.com/")
AddSiteToConfEx parameters
);
@WebResult(name = "editScheduledConfExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/editScheduledConfEx")
public EditScheduledConfExResponse editScheduledConfEx(
@WebParam(partName = "parameters", name = "editScheduledConfEx", targetNamespace = "http://smc.huawei.com/")
EditScheduledConfEx parameters
);
@WebResult(name = "delScheduledConfExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/delScheduledConfEx")
public DelScheduledConfExResponse delScheduledConfEx(
@WebParam(partName = "parameters", name = "delScheduledConfEx", targetNamespace = "http://smc.huawei.com/")
DelScheduledConfEx parameters
);
@WebResult(name = "queryConfSitesStatusExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/queryConfSitesStatusEx")
public QueryConfSitesStatusExResponse queryConfSitesStatusEx(
@WebParam(partName = "parameters", name = "queryConfSitesStatusEx", targetNamespace = "http://smc.huawei.com/")
QueryConfSitesStatusEx parameters
);
@WebResult(name = "prolongScheduledConfExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/prolongScheduledConfEx")
public ProlongScheduledConfExResponse prolongScheduledConfEx(
@WebParam(partName = "parameters", name = "prolongScheduledConfEx", targetNamespace = "http://smc.huawei.com/")
ProlongScheduledConfEx parameters
);
@WebResult(name = "scheduleConfExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/scheduleConfEx")
public ScheduleConfExResponse scheduleConfEx(
@WebParam(partName = "parameters", name = "scheduleConfEx", targetNamespace = "http://smc.huawei.com/")
ScheduleConfEx parameters
);
@WebResult(name = "disconnectSitesExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/disconnectSitesEx")
public DisconnectSitesExResponse disconnectSitesEx(
@WebParam(partName = "parameters", name = "disconnectSitesEx", targetNamespace = "http://smc.huawei.com/")
DisconnectSitesEx parameters
);
@WebResult(name = "connectSitesExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/connectSitesEx")
public ConnectSitesExResponse connectSitesEx(
@WebParam(partName = "parameters", name = "connectSitesEx", targetNamespace = "http://smc.huawei.com/")
ConnectSitesEx parameters
);
@WebResult(name = "delSiteFromConfExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/delSiteFromConfEx")
public DelSiteFromConfExResponse delSiteFromConfEx(
@WebParam(partName = "parameters", name = "delSiteFromConfEx", targetNamespace = "http://smc.huawei.com/")
DelSiteFromConfEx parameters
);
@WebResult(name = "scheduleRecurrenceConferenceExResponse", targetNamespace = "http://smc.huawei.com/", partName = "parameters")
@WebMethod(action = "http://smc.huawei.com/scheduleRecurrenceConferenceEx")
public ScheduleRecurrenceConferenceExResponse scheduleRecurrenceConferenceEx(
@WebParam(partName = "parameters", name = "scheduleRecurrenceConferenceEx", targetNamespace = "http://smc.huawei.com/")
ScheduleRecurrenceConferenceEx parameters
);
}
|
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
public class Foo {
@Test
public void bar() {
assertThat(2 + 3).isEqualTo(5);
}
}
|
package category.dfs;
public class SudokuSolver2 {
public static void main(String[] args) {
SudokuSolver2 solver = new SudokuSolver2();
solver.solveSudoku(new char[][]{
{'1', '2', '3', '4', '5', '6', '7', '8', '9', },
{'9', '.', '5', '.', '2', '.', '.', '.', '.', },
{'6', '.', '4', '.', '1', '.', '.', '.', '.', },
{'4', '.', '7', '.', '9', '.', '.', '.', '.', },
{'2', '.', '9', '.', '6', '.', '.', '.', '.', },
{'3', '.', '8', '.', '7', '.', '.', '.', '.', },
{'7', '.', '2', '.', '8', '.', '.', '.', '.', },
{'8', '.', '6', '.', '3', '.', '.', '.', '.', },
{'5', '.', '1', '.', '4', '.', '.', '.', '.', }
});
/*for (int i = 0; i < 9; i++) {
System.out.print("{");
for (int j = 1; j < 10; j++) {
if(i == 0) System.out.print("'" + j + "', ");
else System.out.print("'.', ");
}
System.out.print("}, ");
System.out.println();
}*/
}
public void solveSudoku(char[][] board) {
if (board.length == 9) helper(board);
print(board);
}
public void print(char[][] board) {
for (int i = 0; i < board.length; i++) {
System.out.println(board[i]);
}
}
public boolean helper(char[][] board) {
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
if(board[i][j] != '.') continue;
for(char c = '1'; c <= '9'; c++) {
if(isValid(i, j, c, board)) {
board[i][j] = c;
if (helper(board)) return true;
board[i][j] = '.';
}
}
return false;
}
}
return true;
}
public boolean isValid(int i, int j, char c, char[][] board){
for (int row = 0; row < 9; row++)
if (board[row][j] == c) return false;
for (int col = 0; col < 9; col++)
if (board[i][col] == c) return false;
for (int row = i / 3 * 3; row < i / 3 * 3 + 3; row++)
for (int col = j / 3 * 3; col < j / 3 * 3 + 3; col++)
if (board[row][col] == c) return false;
return true;
}
}
|
package com.tencent.mm.plugin.game.gamewebview.a;
import com.tencent.mm.plugin.game.gamewebview.jsapi.biz.aq;
import com.tencent.mm.plugin.game.gamewebview.jsapi.biz.f;
import java.util.HashMap;
import java.util.Map;
public final class b {
private static final Map<String, Integer> jGa;
static {
Map hashMap = new HashMap();
jGa = hashMap;
hashMap.put("addDownloadTaskStraight", Integer.valueOf(1));
jGa.put(f.NAME, Integer.valueOf(2));
jGa.put("pauseDownloadTask", Integer.valueOf(3));
jGa.put(aq.NAME, Integer.valueOf(4));
jGa.put("openCustomWebview", Integer.valueOf(5));
jGa.put("openUrlWithExtraWebview", Integer.valueOf(6));
jGa.put("sendAppMessage", Integer.valueOf(7));
}
public static int CZ(String str) {
if (jGa.containsKey(str)) {
return ((Integer) jGa.get(str)).intValue();
}
return 0;
}
}
|
package yujia.xiangsheng;
import yujia.model.StreamingMediaPlayer;
import yujia.model.Works;
import yujia.util.Logger;
import yujia.util.MyStringUtil;
import yujia.util.MyUtil;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
public class PlayActivity extends Activity {
private StreamingMediaPlayer player;
private TextView nameView;
private TextView totalPlayTime;
private int clickCount_down;
private int clickCount_up;
private TextView msgView;
public TextView getNameView() {
return nameView;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play_layout);
ImageButton playBtn = (ImageButton) findViewById(R.id.btn_online_play);
ImageButton stopBtn = (ImageButton) findViewById(R.id.stopbutton);
ImageButton previousBtn = (ImageButton) findViewById(R.id.btn_previous);
ImageButton nextBtn = (ImageButton) findViewById(R.id.btn_next);
TextView currentPlayTime = (TextView) findViewById(R.id.currentPlayTimeView);
msgView = (TextView) findViewById(R.id.msgView);
totalPlayTime = (TextView) findViewById(R.id.totalPlayTimeView);
nameView = (TextView) findViewById(R.id.nameView);
SeekBar progressBar = (SeekBar) findViewById(R.id.music_progress);
String filename = getIntent().getStringExtra("name");
if (G.isFirstBoot) {
G.isFirstBoot = false;
MyUtil.makeToast(this, "双击音量键可切换曲目~~", true);
}
if (filename == null) {// 播放在在线文件
Works works = (Works) getIntent().getSerializableExtra("works");
Logger.i(" get serializable extra " + works);
player = new StreamingMediaPlayer(this, currentPlayTime,
progressBar, works, playBtn, previousBtn, nextBtn);
int sec = works.getLength();
String totalTime = MyStringUtil.getFormatTime(sec * 1000);
Logger.i(" total sec = " + sec + " format string = " + totalTime);
totalPlayTime.setText(totalTime);
nameView.setText(works.getName());
} else {// 播放本地文件
player = new StreamingMediaPlayer(this, currentPlayTime, playBtn,
progressBar, filename);
nameView.setText(filename);
}
previousBtn.setOnClickListener(player);
nextBtn.setOnClickListener(player);
stopBtn.setOnClickListener(player);
}
public TextView getMsgView() {
return msgView;
}
public TextView getTotalPlayTime() {
return totalPlayTime;
}
@Override
protected void onDestroy() {
super.onDestroy();
if (player != null)
player.onDestroy();
player = null;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
long down = event.getDownTime();
long eventtime = event.getEventTime();
if (down != eventtime)
return super.onKeyDown(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
Logger.i(" volume down called");
clickCount_down++;
clickCount_up = 0;
if (clickCount_down >= 2) {
player.playNext();
clickCount_down = 0;
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
Logger.i(" volume up called");
clickCount_down = 0;
clickCount_up++;
if (clickCount_up >= 2) {
player.playPrevious();
clickCount_up = 0;
}
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
}
|
import java.util.Scanner;
public class palindromePermutation266 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("input the String: ");
String inputStr = input.nextLine();
if(palindromePermutation( inputStr))
System.out.println("it is palandrome");
else
System.out.println("it is not a palandrome");
}
public static boolean palindromePermutation(String str) {
if (str==null)
return false;
BitSet bs = new BitSet(264);
for(char word:str.toCharArray()) {
bs.flip(word);
}
if (bs.cardinality()<=1)
return true;
return false;
}
}
|
package jdbcapplication;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class InserExample {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// Register The Driver
Class.forName("com.mysql.jdbc.Driver");
// Establish Connection
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/ripon", "root", "root");
/*
* DDL -->create ----execute(query)-boolean select , create ,upate , delete
*
* DML ---> Update -executeUpadte(query) -int- insert , upadte
*
* DRL----SElect -executeQuary()-- ResultSet --select
*/
// Create Statement
/*Scanner s=new Scanner(System.in);
System.out.println("Enter User Name");
String uname=s.next();
System.out.println("Enter Password");
String password=s.next();
System.out.println("Enter Email");
String email=s.next();
System.out.println("Enter Mobile");
String mobile=s.next();*/
/*Statement st=connection.createStatement();
PreparedStatement ps=connection.prepareStatement("insert into user values(?,?,?,?)");
ps.setString(1, uname);
ps.setString(2, password);
ps.setString(3, email);
ps.setString(4, mobile);
int res=ps.executeUpdate();
//int res=st.executeUpdate("insert into user values('"+uname+"','"+password+"','"+email+"','"+mobile+"')");
System.out.println(res+" Rows Inserted");
*/
/*PreparedStatement pst=connection.prepareStatement("create table employee122(uname varchar(2),password varchar(20))");
boolean status=pst.execute();
System.out.println(status);
if(!status)
{
System.out.println("Table is created");
}
*/
PreparedStatement pst=connection.prepareStatement("select * from user");
ResultSet rs=pst.executeQuery();
while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
connection.close();
}
}
|
package com.goldgov.gtiles.core.module;
import com.goldgov.gtiles.core.module.infofield.Version;
public class RemoteModuleImpl implements RemoteModule{
private static final long serialVersionUID = 4766204416065832161L;
private ModuleDescription description;
private String hostName;
public RemoteModuleImpl(String hostName,ModuleDescription description){
this.hostName = hostName;
this.description = description;
}
@Override
public String name() {
return description.name();
}
@Override
public String id() {
return description.id();
}
@Override
public Version version() {
return description.version();
}
@Override
public String description() {
return description.description();
}
@Override
public String moduleFrom() {
return hostName;
}
}
|
package com.zoho;
import java.io.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.actions.*;
import java.util.*;
import java.sql.*;
public class EnrollHandler{
String username,mailid,phone;
public String enrollmail(String username,String mailid){
try {
String connectionURL = "jdbc:mysql://localhost:3306/tomcat_realm";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "");
if(!connection.isClosed()){
//Statement stmt=connection.createStatement();
String sql="SELECT * from mailtable where user_name=? AND mailid=?";
PreparedStatement stmt=connection.prepareStatement(sql);
stmt.setString(1,username);
stmt.setString(2,mailid);
ResultSet rs=stmt.executeQuery();
if(rs.next()){
connection.close();
return "enrolled";
}
else{
sql="INSERT INTO mailtable (user_name,mailid) values (?,?)";
stmt=connection.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2,mailid);
stmt.executeUpdate();
connection.close();
return "enrolled";
}
// connection.close();
}
}
catch(Exception ex){
System.out.println("\n Exception in your file "+ex+"\n");
return "jdbc";
}
return "failed";
}
public String enrollphone(String username,String phone){
try {
String connectionURL = "jdbc:mysql://localhost:3306/tomcat_realm";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "");
if(!connection.isClosed()){
//Statement stmt=connection.createStatement();
String sql="SELECT * from phonetable where user_name=? AND phonenumber=?";
PreparedStatement stmt=connection.prepareStatement(sql);
stmt.setString(1,username);
stmt.setString(2,phone);
ResultSet rs=stmt.executeQuery();
if(rs.next()){
connection.close();
return "enrolled";
}
else{
sql="INSERT INTO phonetable (user_name,phonenumber) values (?,?)";
stmt=connection.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2,phone);
stmt.executeUpdate();
connection.close();
return "enrolled";
}
// connection.close();
}
}
catch(Exception ex){
System.out.println("\n Exception in your file "+ex+"\n");
return "jdbc";
}
return "failed";
}
/* REFERENCE
if(rs.next()){
sql="UPDATE answertable set answer=? where user_name=? AND qid=?";
stmt=connection.prepareStatement(sql);
stmt.setString(1,answer1);
stmt.setString(2,username);
stmt.setInt(3,1);
stmt.executeUpdate();
stmt=connection.prepareStatement(sql);
stmt.setString(1,answer2);
stmt.setString(2,username);
stmt.setInt(3,2);
stmt.executeUpdate();
connection.close();
return "enrolled";
}
else{
sql="INSERT INTO answertable (user_name,qid, answer) values (?,?,?)";
stmt=connection.prepareStatement(sql);
stmt.setString(1, username);
stmt.setInt(2,1);
stmt.setString(3,answer1);
stmt.executeUpdate();
stmt=connection.prepareStatement(sql);
stmt.setString(1,username);
stmt.setInt(2,2);
stmt.setString(3,answer2);
stmt.executeUpdate();
connection.close();
return "enrolled";
}
}
*/
} |
package com.jim.multipos.ui.inventory.fragments;
import com.jim.multipos.config.scope.PerFragment;
import com.jim.multipos.ui.inventory.presenter.InventoryPresenter;
import com.jim.multipos.ui.inventory.presenter.InventoryPresenterImpl;
import dagger.Binds;
import dagger.Module;
/**
* Created by developer on 09.11.2017.
*/
@Module
public abstract class InventoryPresenterModule {
@Binds
@PerFragment
abstract InventoryPresenter provideInventoryPresenter(InventoryPresenterImpl inventoryPresenter);
}
|
package Model.proc;
public class TestTreeCell{
// public static void main(String[]args){
//
// TreeCell left = new TreeCell(new FrameProcessMap("alt1"),new FrameProcess("alt"));
// TreeCell right = new TreeCell(new FrameProcessMap("alt1"));
// TreeCell cell = new TreeCell(new FrameProcessMap("loop"),left,right);
//
// printList(cell);
// System.out.println("-----------");
//// cell = delete(new Integer(105), cell);
// printList(cell);
//
// }
public static void printList(TreeCell T){
if(T==null) return ;
System.out.println(T.getDatum());
if(T.getLeft()!= null) printList(T.getLeft());
printList(T.getRight());
}
public static TreeCell remove(TreeCell T){
if(T.getLeft()==null) return null;
return new TreeCell(T.getDatum(),remove(T.getLeft()),T.getRight());
}
public static TreeCell findLeaf(TreeCell T){
if(T.getLeft()==null) return T;
return findLeaf(T.getLeft());
}
// public static TreeCell delete (Object x, TreeCell node) {
// if(node==null) return null;
// if(node.getDatum().compareTo(x)==0){
// if(node.getLeft()==null && node.getRight()==null) node = null;
// else if(node.getLeft()==null) {
// node = node.getRight();
// }
// else if(node.getRight()==null)node = node.getLeft();
// else{
// node.setDatum(findLeaf(node.getRight()).getDatum());
// node.setRight(remove(node.getRight()));
// }
// return node;
// }
// if(node.getDatum().compareTo(x)<0){
// node.setRight(delete(x, node.getRight()));
// }
// else node.setLeft(delete(x, node.getLeft()));
// return node;
//
// }
}
|
/*
* Copyright (c) 2016 Haulmont
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.company.sample.gui.user;
import com.company.sample.entity.UserExt;
import com.haulmont.cuba.core.entity.FileDescriptor;
import com.haulmont.cuba.core.global.FileStorageException;
import com.haulmont.cuba.gui.app.security.user.edit.UserEditor;
import com.haulmont.cuba.gui.components.*;
import com.haulmont.cuba.gui.upload.FileUploadingAPI;
import javax.inject.Inject;
import java.util.Map;
public class UserExtEditor extends UserEditor {
@Inject
private FileUploadField userImageUpload;
@Inject
private FileUploadingAPI fileUploadingAPI;
@Inject
private Image userImage;
@Override
public void init(Map<String, Object> params) {
userImageUpload.addFileUploadSucceedListener(event -> {
FileDescriptor fd = userImageUpload.getFileDescriptor();
try {
fileUploadingAPI.putFileIntoStorage(userImageUpload.getFileId(), fd);
} catch (FileStorageException e) {
throw new RuntimeException("Error saving file to FileStorage", e);
}
FileDescriptor committedImage = dataSupplier.commit(fd);
userImage.setSource(FileDescriptorResource.class).setFileDescriptor(committedImage);
((UserExt) getItem()).setImage(committedImage);
showNotification(formatMessage(getMessage("uploadSuccessMessage"), userImageUpload.getFileName()),
NotificationType.HUMANIZED);
});
super.init(params);
}
@Override
protected void postInit() {
super.postInit();
FileDescriptor userImageFile = ((UserExt) getItem()).getImage();
if (userImageFile == null) {
userImage.setSource(ClasspathResource.class).setPath(UserExtBrowser.DEFAULT_USER_IMAGE_PATH);
} else {
userImage.setSource(FileDescriptorResource.class).setFileDescriptor(userImageFile);
}
}
} |
package Tasks.LessonSix.Converters;
public class Call {
public static void main(String[] args) {
CelsiusKelvin celsiusKelvin = new CelsiusKelvin(0);
System.out.println(celsiusKelvin.convert());
CelsiusFahrenheit celsiusFahrenheit = new CelsiusFahrenheit(0);
System.out.println(celsiusFahrenheit.convert());
KelvinCelsius kelvinCelsius = new KelvinCelsius(0);
System.out.println(kelvinCelsius.convert());
KelvinFahrenheit kelvinFahrenheit = new KelvinFahrenheit(0);
System.out.println(kelvinFahrenheit.convert());
FahrenheitCelsius fahrenheitCelsius = new FahrenheitCelsius(0);
System.out.println(fahrenheitCelsius.convert());
FahrenheitKelvin fahrenheitKelvin = new FahrenheitKelvin(0);
System.out.println(fahrenheitKelvin.convert());
}
}
|
package com.itheima.ssm.controller;
import com.itheima.ssm.domain.Permission;
import com.itheima.ssm.domain.Role;
import com.itheima.ssm.domain.UserInfo;
import com.itheima.ssm.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@RequestMapping("/permission")
@Controller
public class PermissionController {
@Autowired
private IPermissionService permissionService;
@RequestMapping("/save.do")
public String save(Permission permission)throws Exception{
permissionService.save(permission);
return "redirect:findAll.do";
}
@RequestMapping("/findAll.do")
public ModelAndView findAll()throws Exception{
ModelAndView mv = new ModelAndView();
List<Permission> permissionList = permissionService.findAll();
mv.addObject("permissionList",permissionList);
mv.setViewName("permission-list");
return mv;
}
@RequestMapping("/findById.do")
public ModelAndView findById(@RequestParam(name="id",required = true)String permissionId) throws Exception{
ModelAndView mv = new ModelAndView();
Permission permission = permissionService.findById(permissionId);
mv.addObject("permissions",permission);
mv.setViewName("permission-show");
return mv;
}
@RequestMapping("/deletePermissionById.do")
public String deletePermissionById(@RequestParam(name="id",required = true)String permissionId) throws Exception{
permissionService.deleteRole(permissionId);
return "redirect:findAll.do";
}
}
|
/*
* 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 pe.gob.onpe.adan.controller.main;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
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 org.springframework.web.bind.annotation.RestController;
import pe.gob.onpe.adan.model.adan.Opcion;
import pe.gob.onpe.adan.model.admin.Proceso;
import pe.gob.onpe.adan.service.Adan.AsynchronousService;
import pe.gob.onpe.adan.service.Adan.OpcionService;
import pe.gob.onpe.adan.service.Admin.ProcesoService;
/**
*
* @author MArrisueno
*/
@Controller
@RequestMapping(value = "/header/*")
public class HeaderController {
@Autowired
OpcionService opcionService;
@Autowired
AsynchronousService asynchronousService;
@Autowired
ProcesoService procesoService;
@RequestMapping("retroceder")
public String openRetroceder() {
return "main/modalRetroceder";
}
@RequestMapping(value = "options", method = RequestMethod.GET)
public ResponseEntity<List> findOptions() {
List list = opcionService.findAllOpcionModule();
if (list.isEmpty()) {
return new ResponseEntity<List>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List>(list, HttpStatus.OK);
}
@RequestMapping(value = "/executeProcessOption", method = RequestMethod.POST, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> process(HttpServletRequest request, @RequestParam("option") int option) throws InterruptedException, Exception {
boolean success = false;
HttpSession session = request.getSession(false);
int idProceso = (Integer) session.getAttribute("CODIGO_PROCESO");
success = asynchronousService.executeReturnModule(getPrincipal(), option, idProceso);
if (success) {
Opcion currentOpcion = opcionService.findById(option);
return new ResponseEntity<Opcion>(currentOpcion, HttpStatus.OK);
}
return new ResponseEntity<List<Opcion>>(HttpStatus.NO_CONTENT);
}
private String getPrincipal() {
String userName = null;
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
userName = ((UserDetails) principal).getUsername();
} else {
userName = principal.toString();
}
return userName;
}
}
|
package org.seasar.silverlight.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.seasar.silverlight.connector.Connector;
public class SilverlightFilter implements Filter
{
private Connector connector;
public void init(FilterConfig config) throws ServletException
{
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException
{
if ("application/json".equals(request.getContentType()) == false)
{
chain.doFilter(request, response);
}
connector.doJSON((HttpServletRequest) request,
(HttpServletResponse) response, chain);
}
public void destroy()
{
// Do Nothings.
}
}
|
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
GridPane pane = new GridPane();
pane.setAlignment(Pos.CENTER);
pane.setHgap(5);
pane.setVgap(5);
ImageView imageView1 = new ImageView("file:///C:/Users/JAGma/Desktop/Java/pracMidQ1/src/sample/uk.gif");
ImageView imageView2 = new ImageView("file:///C:/Users/JAGma/Desktop/Java/pracMidQ1/src/sample/ca.gif");
ImageView imageView3 = new ImageView("file:///C:/Users/JAGma/Desktop/Java/pracMidQ1/src/sample/china.gif");
ImageView imageView4 = new ImageView("file:///C:/Users/JAGma/Desktop/Java/pracMidQ1/src/sample/us.gif");
pane.add(imageView1,0,0);
pane.add(imageView2,1,0);
pane.add(imageView3,0,1);
pane.add(imageView4,1,1);
//Create a scene and place it in the stage
Scene scene = new Scene(pane);
primaryStage.setTitle("Question 1");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
|
package com.example.Careplus.Statistics;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.example.Careplus.Main.MainActivity;
import com.example.Careplus.R;
import java.util.Calendar;
public class StatisticsMain_Activity extends AppCompatActivity {
int nowValue1,nowValue2,nowValue3,nowValue4;
ProgressBar bar1,bar2,bar3, bar4;
TextView click1,click2,click3,click4;
EditText name1,name2,name3,name4;
String nametext1,nametext2,nametext3,nametext4;
ImageView rank_iv1,rank_iv2, rank_iv3, rank_iv4;
private SharedPreferences sf;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.statistics_main);
Intent intent = new Intent(this.getIntent());
ImageButton Categorybtn2 = (ImageButton) findViewById(R.id.categorybtn2);
Categorybtn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(StatisticsMain_Activity.this, MainActivity.class);
startActivity(intent);
}
});
bar1 =(ProgressBar)findViewById(R.id.rank1_progressBar);
bar2 =(ProgressBar)findViewById(R.id.rank2_progressBar);
bar3 =(ProgressBar)findViewById(R.id.rank3_progressBar);
bar4 =(ProgressBar)findViewById(R.id.rank4_progressBar);
click1 =(TextView) findViewById(R.id.rank_click1);
click2 =(TextView)findViewById(R.id.rank_click2);
click3 =(TextView)findViewById(R.id.rank_click3);
click4 =(TextView)findViewById(R.id.rank_click4);
name1 =(EditText) findViewById(R.id.rank_name1);
name2 =(EditText) findViewById(R.id.rank_name2);
name3 =(EditText) findViewById(R.id.rank_name3);
name4 =(EditText) findViewById(R.id.rank_name4);
rank_iv1 =(ImageView) findViewById(R.id.rank_iv1);
rank_iv2 =(ImageView) findViewById(R.id.rank_iv2);
rank_iv3 =(ImageView) findViewById(R.id.rank_iv3);
rank_iv4 =(ImageView) findViewById(R.id.rank_iv4);
getData1();
getData2();
getData3();
getData4();
name1.setText(nametext1);
name2.setText(nametext2);
name3.setText(nametext3);
name4.setText(nametext4);
rank_iv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rank_iv1.setVisibility(View.INVISIBLE); //+버튼 사라지게
click1.setText("회");
}
});
click1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
OnceADay1();
bar1.setProgress(nowValue1);
click1.setText(nowValue1+"회");
saveData1(); //데이터 저장
}
});
rank_iv2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rank_iv2.setVisibility(View.INVISIBLE); //+버튼 사라지게
click2.setText("회");
}
});
click2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
OnceADay2();
bar2.setProgress(nowValue2);
click2.setText(nowValue2+"회");
saveData2(); //데이터 저장
}
});
rank_iv3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rank_iv3.setVisibility(View.INVISIBLE); //+버튼 사라지게
click3.setText("회");
}
});
click3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
OnceADay3();
bar3.setProgress(nowValue3);
click3.setText(nowValue3+"회");
saveData3(); //데이터 저장
}
});
rank_iv4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rank_iv4.setVisibility(View.INVISIBLE); //+버튼 사라지게
click4.setText("회");
}
});
click4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
OnceADay4();
bar4.setProgress(nowValue4);
click4.setText(nowValue4+"회");
saveData4(); //데이터 저장
}
});
}
/*첫번째 약, 하루에 한번만 버튼을 클릭이 가능하기 위해 구현(DAY OF MONTH), 테스트하기 위해 임시로 분마다 클릭이 가능하도록 설정함*/
public void OnceADay1(){
Calendar calendar1 = Calendar.getInstance(); //캘린더 초기화
int currentDay1 = calendar1.get(Calendar.MINUTE); //현재 분을 얻어옴
SharedPreferences settings = getSharedPreferences("EAT_1",0);
int lastDay1 = settings.getInt("day_1",0);
if(lastDay1!=currentDay1){
SharedPreferences.Editor editor = settings.edit();
editor.putInt("day_1",currentDay1);
editor.apply();
int maxValue = bar1.getMax(); //진행의 최대값
if (maxValue == nowValue1) { nowValue1 = 0; } //30회를 채우면 초기화
else {
bar1.setVisibility(View.VISIBLE);
rank_iv1.setVisibility(View.INVISIBLE);
nowValue1 += 1; //한번 클릭 시 1회 증가
}
if (nowValue1 == 0) { //초기화 되었을 때 축하메시지 팝업창 호출
bar1.setVisibility(View.VISIBLE);
showAlert();
}
else bar1.setProgress(nowValue1);
click1.setText(nowValue1+"회");
Toast.makeText(this,"1-오늘 달성 완료!",Toast.LENGTH_SHORT).show();
}
}
/*두번째 약, 하루에 한번만 버튼을 클릭이 가능하기 위해 구현*/
public void OnceADay2(){
Calendar calendar2 = Calendar.getInstance();
int currentDay2 = calendar2.get(Calendar.DAY_OF_MONTH);
SharedPreferences settings = getSharedPreferences("EAT_2",0);
int lastDay2 = settings.getInt("day_2",0);
if(lastDay2!=currentDay2){
SharedPreferences.Editor editor = settings.edit();
editor.putInt("day_2",currentDay2);
editor.apply();
int maxValue = bar2.getMax(); //진행의 최대값
if (maxValue == nowValue2) { nowValue2 = 0; }
else {
bar2.setVisibility(View.VISIBLE);
rank_iv2.setVisibility(View.INVISIBLE);
nowValue2 += 1;
}
if (nowValue2 == 0) {
bar2.setVisibility(View.VISIBLE);
showAlert();
}
else bar2.setProgress(nowValue2);
click2.setText(nowValue2+"회");
Toast.makeText(this,"2-오늘 달성 완료!",Toast.LENGTH_SHORT).show();
}
}
/*세번째 약, 하루에 한번만 버튼을 클릭이 가능하기 위해 구현*/
public void OnceADay3(){
Calendar calendar3 = Calendar.getInstance();
int currentDay3 = calendar3.get(Calendar.DAY_OF_MONTH);
SharedPreferences settings = getSharedPreferences("EAT_3",0);
int lastDay3 = settings.getInt("day_3",0);
if(lastDay3!=currentDay3){
SharedPreferences.Editor editor = settings.edit();
editor.putInt("day_3",currentDay3);
editor.apply();
int maxValue = bar3.getMax(); //진행의 최대값
if (maxValue == nowValue3) { nowValue3 = 0; }
else {
bar3.setVisibility(View.VISIBLE);
rank_iv3.setVisibility(View.INVISIBLE);
nowValue3 += 1;
}
if (nowValue3 == 0) {
bar3.setVisibility(View.VISIBLE);
showAlert();
}
else bar3.setProgress(nowValue3);
click3.setText(nowValue3+"회");
Toast.makeText(this,"3-오늘 달성 완료!",Toast.LENGTH_SHORT).show();
}
}
/*네번째 약, 하루에 한번만 버튼을 클릭이 가능하기 위해 구현*/
public void OnceADay4(){
Calendar calendar4 = Calendar.getInstance();
int currentDay4 = calendar4.get(Calendar.DAY_OF_MONTH);
SharedPreferences settings = getSharedPreferences("EAT_4",0);
int lastDay4 = settings.getInt("day_4",0);
if(lastDay4!=currentDay4){
SharedPreferences.Editor editor = settings.edit();
editor.putInt("day_4",currentDay4);
editor.apply();
int maxValue = bar4.getMax(); //진행의 최대값
if (maxValue == nowValue4) { nowValue4 = 0; }
else {
bar4.setVisibility(View.VISIBLE);
rank_iv4.setVisibility(View.INVISIBLE);
nowValue4 += 1;
}
if (nowValue4 == 0) {
bar4.setVisibility(View.GONE);
showAlert();
}
else bar4.setProgress(nowValue4);
click4.setText(nowValue4+"회");
Toast.makeText(this,"4-오늘 달성 완료!",Toast.LENGTH_SHORT).show();
}
}
/*데이터 저장*/
public void saveData1() {
SharedPreferences sharedPreferences = getSharedPreferences("sFile1",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("statistics1", nowValue1);
editor.putString("nameText1", String.valueOf(name1.getText()));
Log.e("set값", String.valueOf(nowValue1));
editor.commit();
}
/*데이터 불러오기*/
public void getData1() {
SharedPreferences sf = getSharedPreferences("sFile1", MODE_PRIVATE);
nowValue1 = sf.getInt("statistics1", 0);
nametext1 = sf.getString("nameText1","");
Log.e("get값", String.valueOf(nowValue1));
}
/*데이터 저장*/
public void saveData2() {
SharedPreferences sharedPreferences = getSharedPreferences("sFile2",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("statistics2", nowValue2);
Log.e("set값", String.valueOf(nowValue2));
editor.putString("nameText2", String.valueOf(name2.getText()));
editor.commit();
}
/*데이터 불러오기*/
public void getData2() {
SharedPreferences sf = getSharedPreferences("sFile2", MODE_PRIVATE);
nowValue2 = sf.getInt("statistics2", 0);
nametext2 = sf.getString("nameText2","");
Log.e("get값", String.valueOf(nowValue2));
}
/*데이터 저장*/
public void saveData3() {
SharedPreferences sharedPreferences = getSharedPreferences("sFile3",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("statistics3", nowValue3);
editor.putString("nameText3", String.valueOf(name3.getText()));
Log.e("set값", String.valueOf(nowValue3));
editor.commit();
}
/*데이터 불러오기*/
public void getData3() {
SharedPreferences sf = getSharedPreferences("sFile3", MODE_PRIVATE);
nowValue3 = sf.getInt("statistics3", 0);
nametext3 = sf.getString("nameText3","");
Log.e("get값", String.valueOf(nowValue3));
}
/*데이터 저장*/
public void saveData4() {
SharedPreferences sharedPreferences = getSharedPreferences("sFile4",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("statistics4", nowValue4);
editor.putString("nameText4", String.valueOf(name4.getText()));
Log.e("set값", String.valueOf(nowValue4));
editor.commit();
}
/*데이터 불러오기*/
public void getData4() {
SharedPreferences sf = getSharedPreferences("sFile4", MODE_PRIVATE);
nowValue4 = sf.getInt("statistics4", 0);
nametext4 = sf.getString("nameText4","");
Log.e("get값", String.valueOf(nowValue4));
}
public void showAlert() {
AlertDialog.Builder builder =
new AlertDialog.Builder(StatisticsMain_Activity.this);
// alert의 title과 Messege 세팅
builder.setTitle("축하합니다!");
builder.setMessage("30일 섭취 성공하셨습니다!");
// 버튼 추가 (Ok 버튼과 Cancle 버튼 )
builder.setPositiveButton("확인",null);
builder.create().show();
}
} |
package micro.auth.controllers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
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("/jwt")
public class JWTController {
Logger logger = LoggerFactory.getLogger(JWTController.class);
@Autowired
private BCryptPasswordEncoder bcrypt;
@GetMapping(produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<OAuth2Authentication> obtenerPorId(OAuth2Authentication auth) {
logger.info("JWTController");
logger.info(auth.getName());
return ResponseEntity.ok(auth);
}
@GetMapping(value = "/password/{password}")
public ResponseEntity<String> encodePassword(@PathVariable("password") String password) {
logger.info("/password/{password} : " + password);
String contra = bcrypt.encode(password);
return ResponseEntity.ok(contra);
}
}
|
package cn.wolfcode.crm.service.impl;
import cn.wolfcode.crm.domain.Customer;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.CustomerMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.ICustomerService;
import cn.wolfcode.crm.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
public class CustomerServiceImpl implements ICustomerService {
@Autowired
private CustomerMapper customerMapper;
@Override
public void save(Customer entry) {
//设置录入人,录入时间
Employee currentEmp = UserContext.getCurrentEmp();
entry.setInputUser(currentEmp);
entry.setInputTime(new Date());
customerMapper.insert(entry);
}
@Override
public void delete(Long id) {
customerMapper.deleteByPrimaryKey(id);
}
@Override
public void update(Customer entry) {
customerMapper.updateByPrimaryKey(entry);
}
@Override
public Customer get(Long id) {
return customerMapper.selectByPrimaryKey(id);
}
@Override
public List<Customer> listAll() {
return customerMapper.selectAll();
}
@Override
public PageInfo<Customer> query(QueryObject qo) {
//在这行代码下面的第一个SQL会拼接分页的片段
PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
List<Customer> list = customerMapper.selectForList(qo);
return new PageInfo<Customer>(list);
}
@Override
public void updateSellerAndStatusById(Customer customer, Employee seller) {
//对于更新必须新键更新语句,使用原来的语句会出现覆盖的情况
Customer entry = new Customer();
Employee emp = new Employee();
entry.setSeller(emp);
entry.getSeller().setId(seller.getId());
entry.setId(customer.getId());
entry.setStatus(Customer.STATUS_POTENTIAL);
customerMapper.updateSellerAndStatusById(entry);
}
@Override
public void updateStatus(Long cid, Long status) {
customerMapper.updateStatusById(cid, status);
}
}
|
package oop02.encapsule;
import java.security.InvalidParameterException;
public class NumberMatchService {
public void doService(int userInput) throws Exception{
if( !(userInput >= 1 && userInput <= 3))
throw new InvalidParameterException();
NumberMatchVO vo = new NumberMatchVO();
vo.setUserInput(userInput);
vo.setCpuInput();
System.out.println("컴퓨터가 선택한 숫자는 " + vo.getCpuInput() + "입니다.");
if(vo.getUserInput() == vo.getCpuInput())
System.out.println("이겼습니다. 축하합니다.");
else
System.out.println("지셨군요. 그러게 왜 도박을 합니까?");
}
}
|
package eu.rethink.globalregistry.util;
import io.jsonwebtoken.impl.Base64Codec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* DHT Manager class for accessing the DHT
*
* @date 29.03.2017
* @version 1
* @author Sebastian Göndör
*/
public class ECDSAKeyPairManager
{
public static final String ALGORITHM = "ECDSA";
public static final String CURVE = "secp256k1";
// public static final int KEYSIZE = 160;
public static final String PUBLICKEY_PREFIX = "-----BEGIN PUBLIC KEY-----";
public static final String PUBLICKEY_POSTFIX = "-----END PUBLIC KEY-----";
public static final String PRIVATEKEY_PREFIX = "-----BEGIN PRIVATE KEY-----";
public static final String PRIVATEKEY_POSTFIX = "-----END PRIVATE KEY-----";
public static KeyPair createKeyPair()
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException
{
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM, "BC");
ECGenParameterSpec ecSpec = new ECGenParameterSpec(CURVE);
keyGen.initialize(ecSpec, new SecureRandom());
return keyGen.generateKeyPair();
}
/**
* returns a PKCS#8 String beginning with -----BEGIN PUBLIC KEY-----
*
* @param key
* @return
*/
public static String encodePublicKey(PublicKey key)
{
Security.addProvider(new BouncyCastleProvider());
return PUBLICKEY_PREFIX + Base64Codec.BASE64.encode(key.getEncoded()) + PUBLICKEY_POSTFIX;
}
// TODO: maybe some error with this method
/**
* returns a PKCS#8 String beginning with -----BEGIN PRIVATE KEY-----
*
* @param key
* @return
*/
public static String encodePrivateKey(PrivateKey key)
{
Security.addProvider(new BouncyCastleProvider());
return PRIVATEKEY_PREFIX + Base64Codec.BASE64.encode(key.getEncoded()) + PRIVATEKEY_POSTFIX;
}
public static PublicKey decodePublicKey(String key) throws InvalidKeySpecException, NoSuchAlgorithmException
{
Security.addProvider(new BouncyCastleProvider());
key = key.replace(PUBLICKEY_PREFIX, "").replace(PUBLICKEY_POSTFIX, "").replace("\r", "").replace("\n", "")
.trim();
byte[] keyBytes = Base64Codec.BASE64.decode(key);
return KeyFactory.getInstance(ALGORITHM).generatePublic(new X509EncodedKeySpec(keyBytes));
}
// TODO: maybe some error with this method
public static PrivateKey decodePrivateKey(String key) throws InvalidKeySpecException, NoSuchAlgorithmException
{
Security.addProvider(new BouncyCastleProvider());
key = key.replace(PRIVATEKEY_PREFIX, "").replace(PRIVATEKEY_POSTFIX, "").replace("\r", "").replace("\n", "")
.trim();
byte[] keyBytes = Base64Codec.BASE64.decode(key);
return KeyFactory.getInstance(ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
}
public static String stripKey(String key)
{
return key.replace("\r", "").replace("\n", "").trim();
}
} |
package com.test.myapplication.viewmodels;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import com.test.myapplication.repositories.TrendingRepositoryRepo;
import com.test.myapplication.rest.responses.RepositoryResponse;
/**
* Created by Surendra Singh on 2/27/2020.
* Created for Pitney Bowes
*/
public class RepositoryViewModel extends ViewModel {
private TrendingRepositoryRepo mRepository;
private boolean mDidRetrieveRepository;
public RepositoryViewModel() {
mRepository = TrendingRepositoryRepo.getInstance();
mDidRetrieveRepository = false;
}
public LiveData<RepositoryResponse> getRepository() {
return mRepository.getRepository();
}
public LiveData<Boolean> isREpositoryeRequestTimedOut() {
return mRepository.isRepositoryRequestTimedOut();
}
public void setRetrievedRepository(boolean retrievedRepo) {
mDidRetrieveRepository = retrievedRepo;
}
public boolean didRetrieveRepository() {
return mDidRetrieveRepository;
}
}
|
/*
* Copyright (C) 2019-2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.mirror.grpc.controller;
import com.google.protobuf.InvalidProtocolBufferException;
import com.hedera.mirror.api.proto.ConsensusTopicQuery;
import com.hedera.mirror.api.proto.ConsensusTopicResponse;
import com.hedera.mirror.api.proto.ReactorConsensusServiceGrpc;
import com.hedera.mirror.common.domain.entity.EntityId;
import com.hedera.mirror.common.domain.topic.TopicMessage;
import com.hedera.mirror.common.util.DomainUtils;
import com.hedera.mirror.grpc.domain.TopicMessageFilter;
import com.hedera.mirror.grpc.service.TopicMessageService;
import com.hedera.mirror.grpc.util.ProtoUtil;
import com.hederahashgraph.api.proto.java.ConsensusMessageChunkInfo;
import com.hederahashgraph.api.proto.java.TransactionID;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import net.devh.boot.grpc.server.service.GrpcService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* GRPC calls their protocol adapter layer a service, but most of the industry calls this layer the controller layer.
* See the Front Controller pattern or Model-View-Controller (MVC) pattern. The service layer is generally reserved for
* non-protocol specific business logic so to avoid confusion with our TopicMessageService we'll name this GRPC layer as
* controller.
*/
@GrpcService
@Log4j2
@RequiredArgsConstructor
public class ConsensusController extends ReactorConsensusServiceGrpc.ConsensusServiceImplBase {
private final TopicMessageService topicMessageService;
@Override
public Flux<ConsensusTopicResponse> subscribeTopic(Mono<ConsensusTopicQuery> request) {
return request.map(this::toFilter)
.flatMapMany(topicMessageService::subscribeTopic)
.map(this::toResponse)
.onErrorMap(ProtoUtil::toStatusRuntimeException);
}
private TopicMessageFilter toFilter(ConsensusTopicQuery query) {
var filter = TopicMessageFilter.builder().limit(query.getLimit());
if (query.hasTopicID()) {
filter.topicId(EntityId.of(query.getTopicID()));
}
if (query.hasConsensusStartTime()) {
long startTime = DomainUtils.timestampInNanosMax(query.getConsensusStartTime());
filter.startTime(startTime);
}
if (query.hasConsensusEndTime()) {
long endTime = DomainUtils.timestampInNanosMax(query.getConsensusEndTime());
filter.endTime(endTime);
}
return filter.build();
}
// Consider caching this conversion for multiple subscribers to the same topic if the need arises.
private ConsensusTopicResponse toResponse(TopicMessage t) {
var consensusTopicResponseBuilder = ConsensusTopicResponse.newBuilder()
.setConsensusTimestamp(ProtoUtil.toTimestamp(t.getConsensusTimestamp()))
.setMessage(ProtoUtil.toByteString(t.getMessage()))
.setRunningHash(ProtoUtil.toByteString(t.getRunningHash()))
.setRunningHashVersion(t.getRunningHashVersion())
.setSequenceNumber(t.getSequenceNumber());
if (t.getChunkNum() != null) {
ConsensusMessageChunkInfo.Builder chunkBuilder = ConsensusMessageChunkInfo.newBuilder()
.setNumber(t.getChunkNum())
.setTotal(t.getChunkTotal());
TransactionID transactionID = parseTransactionID(
t.getInitialTransactionId(), t.getTopicId().getEntityNum(), t.getSequenceNumber());
EntityId payerAccountEntity = t.getPayerAccountId();
var validStartInstant = ProtoUtil.toTimestamp(t.getValidStartTimestamp());
if (transactionID != null) {
chunkBuilder.setInitialTransactionID(transactionID);
} else if (payerAccountEntity != null && validStartInstant != null) {
chunkBuilder.setInitialTransactionID(TransactionID.newBuilder()
.setAccountID(ProtoUtil.toAccountID(payerAccountEntity))
.setTransactionValidStart(validStartInstant)
.build());
}
consensusTopicResponseBuilder.setChunkInfo(chunkBuilder.build());
}
return consensusTopicResponseBuilder.build();
}
private TransactionID parseTransactionID(byte[] transactionIdBytes, long topicId, long sequenceNumber) {
if (transactionIdBytes == null) {
return null;
}
try {
return TransactionID.parseFrom(transactionIdBytes);
} catch (InvalidProtocolBufferException e) {
log.error("Failed to parse TransactionID for topic {} sequence number {}", topicId, sequenceNumber);
return null;
}
}
}
|
package com.example.edwin.traveling.System.System;
/**
* Created by Edwin on 2017-09-15.
*/
import android.util.Log;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by sleep on 2017-08-19.
*/
public class TourAPIData {
private final String OS = "AND";
private final String APPNAME = "TRIPLAY";
private Document doc;
private TourAPIData(){
}
private static class LazyIdiom {
public static TourAPIData INSTANCE = new TourAPIData();
}
public static TourAPIData getInstance() {
return LazyIdiom.INSTANCE;
}
public ArrayList<TravelPlace> getAdjacencyPlace(float pos_x, float pos_y){
final int MAX_NUM = 10;
final String RADIUS = "1000";
final String MAX_ROW = "100";
ArrayList<TravelPlace> result = new ArrayList<TravelPlace>();
Log.d("TRIPLAY", "mapX="+pos_x+" "+"mapY="+pos_y);
doc = getXMLData("locationBasedList", 1, "arrange=E", "mapX="+String.valueOf(pos_x), "mapY="+String.valueOf(pos_y), "radius="+RADIUS, "numOfRows="+MAX_ROW);
Elements eResult = doc.getElementsByTag("item");
int count = 0, cursor = 0;
int rowNum = eResult.size();
Log.d("TRIPLAY", "Row="+rowNum);
while(count < MAX_NUM && cursor < rowNum){
int type = Integer.parseInt(eResult.get(cursor).getElementsByTag("contenttypeid").get(0).text());
if(!checkOtherType(type)){
cursor++;
continue;
}
String id = eResult.get(cursor).getElementsByTag("contentid").get(0).text();
String name = eResult.get(cursor).getElementsByTag("title").get(0).text();
float x = Float.valueOf(eResult.get(cursor).getElementsByTag("mapx").get(0).text());
float y = Float.valueOf(eResult.get(cursor).getElementsByTag("mapy").get(0).text());
TravelPlace pl = new TravelPlace(id, type, name, x, y);
result.add(pl);
cursor++;
count++;
}
return result;
}
public ArrayList<TravelPlace> getAdjacencyFestival(float pos_x, float pos_y){
final int MAX_NUM = 5;
final String RADIUS = "1000";
final int MAX_ROW = 100;
ArrayList<TravelPlace> result = new ArrayList<TravelPlace>();
doc = getXMLData("locationBasedList", 1, "arrange=E", "mapX="+String.valueOf(pos_x), "mapY="+String.valueOf(pos_y), "radius="+RADIUS, "numOfRows="+String.valueOf(MAX_ROW));
Elements eResult = doc.getElementsByTag("item");
int count = 0, cursor = 0;
int rowNum = eResult.size();
Log.d("TRIPLAY", "ROWNUM="+rowNum);
while(count < MAX_NUM && cursor < rowNum){
int type = Integer.parseInt(eResult.get(cursor).getElementsByTag("contenttypeid").get(0).text());
if(!checkFestival(type)){
cursor++;
continue;
}
String id = eResult.get(cursor).getElementsByTag("contentid").get(0).text();
String name = eResult.get(cursor).getElementsByTag("title").get(0).text();
float x = Float.valueOf(eResult.get(cursor).getElementsByTag("mapx").get(0).text());
float y = Float.valueOf(eResult.get(cursor).getElementsByTag("mapy").get(0).text());
TravelPlace pl = new TravelPlace(id, type, name, x, y);
result.add(pl);
cursor++;
count++;
}
return result;
}
private boolean checkFestival(int type){
if(type == TravelPlace.FESTIVAL){
return true;
}
return false;
}
private boolean checkOtherType(int type){
switch(type) {
case TravelPlace.CULTURE:
case TravelPlace.FOOD:
case TravelPlace.REPORTS:
case TravelPlace.TOUR:
return true;
default:
return false;
}
}
public String getOverview(String ID){
String result="";
doc = getXMLData("detailCommon", 1, "contentId="+ID, "overviewYN=Y");
result += doc.getElementsByTag("overview").get(0).text();
return result;
}
private synchronized Document getXMLData(String serviceName, int page, String... parameters){
//Make real URL from parameters
String connectionURL = "http://api.visitkorea.or.kr/openapi/service/rest/KorService/" + serviceName + "?ServiceKey="+ getServiceKey() + "&pageNo=" + String.valueOf(page) +"&MobileOS=" + OS + "&MobileApp=" + APPNAME;
for(String s : parameters) {
connectionURL += "&" + s;
}
Document doc = new Document(""); //initialize
try {
//get XML file from URL
doc = Jsoup.connect(connectionURL).parser(Parser.xmlParser()).get();
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
private String getServiceKey(){
return "YiTsCc8u8%2Fe817wYreMVBf6ChuAPG%2F9o%2B7VYQVYAGActLV2%2B3%2FtuZ6N7Gy6nhEaETBAKE8ctYMESCOQoocy02g%3D%3D";
}
} |
package ui;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
// represents the menu screens that can be drawn in the game
public class Menu extends MouseAdapter {
private static DeadAhead game;
public static final int BUTTON_X = 5 * game.WIDTH / 14;
public static final int PLAY_BUTTON_Y = game.HEIGHT / 4;
public static final int SAVE_BUTTON_Y = 3 * game.HEIGHT / 8;
public static final int NEW_BUTTON_Y = 2 * game.HEIGHT / 4;
public static final int RETRY_BUTTON_Y = game.HEIGHT / 2;
public static final int BUTTON_WIDTH = 200;
public static final int BUTTON_HEIGHT = 64;
private GamePanel gp;
// EFFECTS: creates a Menu object
public Menu(DeadAhead game, GamePanel gp) {
this.game = game;
this.gp = gp;
}
// MODIFIES: gp
// EFFECTS: checks which button was clicked and performs the respective action
public void mousePressed(MouseEvent e) {
int mx = e.getX();
int my = e.getY();
if (gp.gameState == GamePanel.State.MENU) {
if (mouseOver(mx, my, BUTTON_X, PLAY_BUTTON_Y, BUTTON_WIDTH, BUTTON_HEIGHT)) {
gp.gameState = GamePanel.State.GAME;
return;
} else if (mouseOver(mx, my, BUTTON_X, SAVE_BUTTON_Y, BUTTON_WIDTH, BUTTON_HEIGHT)) {
game.saveGame();
return;
} else if (mouseOver(mx, my, BUTTON_X, NEW_BUTTON_Y, BUTTON_WIDTH, BUTTON_HEIGHT)) {
game.newGame();
return;
}
}
if (gp.gameState == GamePanel.State.END) {
if (mouseOver(mx, my, BUTTON_X, RETRY_BUTTON_Y, BUTTON_WIDTH, BUTTON_HEIGHT)) {
game.newGame();
// reset game
}
}
}
// EFFECTS: returns true if the click is inside a given space
private boolean mouseOver(int mx, int my, int x, int y, int width, int height) {
if (mx > x && mx < x + width) {
if (my > y && my < y + height) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}
|
package jour06;
import java.util.Scanner;
public class Odev1UcunKatiYazdirmak {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Lutfen bir tamsayi giriniz");
int num1 = scan.nextInt();
if(num1%3==0) {
System.out.println("3un kati");
}
if(num1%3!=0) {
System.out.println("3 un kati degildir");
}
}
}
|
package org.metaborg.sunshine.command.local;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.action.IActionService;
import org.metaborg.core.build.dependency.IDependencyService;
import org.metaborg.core.build.paths.ILanguagePathService;
import org.metaborg.core.language.ILanguageComponent;
import org.metaborg.core.language.ILanguageImpl;
import org.metaborg.core.language.LanguageUtils;
import org.metaborg.core.source.ISourceTextService;
import org.metaborg.spoofax.core.processing.ISpoofaxProcessorRunner;
import org.metaborg.spoofax.core.stratego.IStrategoCommon;
import org.metaborg.sunshine.arguments.InputDelegate;
import org.metaborg.sunshine.arguments.LanguagesDelegate;
import org.metaborg.sunshine.arguments.ProjectPathDelegate;
import org.metaborg.sunshine.command.base.TransformCommand;
import com.beust.jcommander.ParametersDelegate;
import javax.inject.Inject;
public class LocalTransformCommand extends TransformCommand {
@ParametersDelegate private LanguagesDelegate languagesDelegate;
@Inject public LocalTransformCommand(ISourceTextService sourceTextService, IDependencyService dependencyService,
ILanguagePathService languagePathService, IActionService actionService,
ISpoofaxProcessorRunner runner, IStrategoCommon strategoTransformerCommon,
ProjectPathDelegate languageSpecPathDelegate, InputDelegate inputDelegate,
LanguagesDelegate languagesDelegate) {
super(sourceTextService, dependencyService, languagePathService, actionService, runner, strategoTransformerCommon,
languageSpecPathDelegate, inputDelegate);
this.languagesDelegate = languagesDelegate;
}
@Override public int run() throws MetaborgException {
final Iterable<ILanguageComponent> components = languagesDelegate.discoverLanguages();
final Iterable<ILanguageImpl> impls = LanguageUtils.toImpls(components);
return run(impls);
}
}
|
package negocios;
import beans.MateriaPrima;
import dados.IRepositorioMateriaPrima;
import exceptions.MateriaPrimaJaExisteException;
import exceptions.MateriaPrimaNaoExisteException;
public class ControladorMateriaPrimas {
IRepositorioMateriaPrima repositorio;
public ControladorMateriaPrimas(IRepositorioMateriaPrima instanciaInterface){
this.repositorio = instanciaInterface;
}
public void cadastrar (MateriaPrima m) throws MateriaPrimaJaExisteException {
if(m==null) {
throw new IllegalArgumentException("");
} else{
if(this.repositorio.mpExiste(m.getCodigo()) == true){
this.repositorio.cadastrarMateriaPrima(m);
} else if (this.repositorio.mpExiste(m.getCodigo()) == false) {
MateriaPrimaJaExisteException c = new MateriaPrimaJaExisteException(m.getCodigo());
throw c;
}
}
}
public MateriaPrima buscar(int codigo) throws MateriaPrimaNaoExisteException {
if(this.repositorio.mpExiste(codigo) == true) {
return this.repositorio.buscarMateriaPrima(codigo);
} else {
throw new MateriaPrimaNaoExisteException(codigo);
}
}
public void remover(MateriaPrima m) throws MateriaPrimaNaoExisteException {
if(m == null) {
throw new IllegalArgumentException("");
} else {
if(this.repositorio.mpExiste(m.getCodigo()) == true) {
this.repositorio.removerMateriaPrima(m.getCodigo());
} else if(this.repositorio.mpExiste(m.getCodigo()) == false) {
MateriaPrimaNaoExisteException r = new MateriaPrimaNaoExisteException(m.getCodigo());
throw r;
}
}
}
public void alterar(MateriaPrima mpAlterada, MateriaPrima novaMateriaPrima) throws MateriaPrimaNaoExisteException {
if(mpAlterada != null && novaMateriaPrima != null) {
this.repositorio.alterarMateriaPrima(mpAlterada, novaMateriaPrima);
} else {
if(mpAlterada == null || novaMateriaPrima == null) {
IllegalArgumentException a = new IllegalArgumentException("");
throw a;
}
}
}
public int getQuantidade(int codigo) throws MateriaPrimaNaoExisteException {
if(this.repositorio.mpExiste(codigo) == true) {
MateriaPrima m = this.repositorio.buscarMateriaPrima(codigo);
return m.getQuantidade();
} else {
throw new MateriaPrimaNaoExisteException(codigo);
}
}
}
|
package com.anywaycloud.test.common.fastdfs;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.FileInfo;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
public class TestFastDFS2 {
// public String local_filename = "D:\\seafood_project\\fast_DFS\\src\\client.conf";
public String conf_filename = "D:\\ZY\\test\\fdfs_client.conf";
public String upload_filename = "D:\\ZY\\test\\testFastDFS.txt";
@org.junit.Test
public void testUpload() {
try {
/*// 连接超时的时限,单位为毫秒
ClientGlobal.setG_connect_timeout(2000);
// 网络超时的时限,单位为毫秒
ClientGlobal.setG_network_timeout(30000);
ClientGlobal.setG_anti_steal_token(false);
// 字符集
ClientGlobal.setG_charset("UTF-8");
ClientGlobal.setG_secret_key(null);
// HTTP访问服务的端口号
ClientGlobal.setG_tracker_http_port(8088);
// Tracker服务器列表
InetSocketAddress[] tracker_servers = new InetSocketAddress[1];
tracker_servers[0] = new InetSocketAddress("192.168.235.140", 22122);
ClientGlobal.setG_tracker_group(new TrackerGroup(tracker_servers));*/
ClientGlobal.init(conf_filename);
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer,
storageServer);
NameValuePair nvp[] = new NameValuePair[] {
new NameValuePair("age", "18"),
new NameValuePair("sex", "male") };
String fileIds[] = storageClient.upload_file(upload_filename, null, nvp);
System.out.println(fileIds.length);
System.out.println("组名:" + fileIds[0]);
System.out.println("路径: " + fileIds[1]);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
}
@org.junit.Test
public void testDownload() {
try {
ClientGlobal.init(conf_filename);
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer,
storageServer);
byte[] b = storageClient.download_file("group1",
"M00/00/00/rB8iMFU4I6mAZKY3AAAARhtsMZw959.txt");
System.out.println(b);
File ret = null;
BufferedOutputStream stream = null;
ret = new File("testtesttest.txt");
FileOutputStream fstream = new FileOutputStream(ret);
stream = new BufferedOutputStream(fstream);
stream.write(b);
stream.close();
// getFile(b, "d:\\", UUID.randomUUID().toString() + ".txt");
} catch (Exception e) {
e.printStackTrace();
}
}
private void getFile(byte[] b, String string, String string2) {
}
@org.junit.Test
public void testGetFileInfo() {
try {
ClientGlobal.init(conf_filename);
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer,
storageServer);
FileInfo fi = storageClient.get_file_info("group1",
"M00/00/00/rB8iMFU4GtiAa2JlAAAARhtsMZw293.txt");
System.out.println(fi.getSourceIpAddr());
System.out.println(fi.getFileSize());
System.out.println(fi.getCreateTimestamp());
System.out.println(fi.getCrc32());
} catch (Exception e) {
e.printStackTrace();
}
}
@org.junit.Test
public void testGetFileMate() {
try {
ClientGlobal.init(conf_filename);
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer,
storageServer);
NameValuePair nvps[] = storageClient.get_metadata("group1",
"M00/00/00/rB8iMFU4GtiAa2JlAAAARhtsMZw293.txt");
for (NameValuePair nvp : nvps) {
System.out.println(nvp.getName() + ":" + nvp.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
@org.junit.Test
public void testDelete() {
try {
ClientGlobal.init(conf_filename);
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer,
storageServer);
int i = storageClient.delete_file("group1",
"M00/00/00/rB8iMFU4GtiAa2JlAAAARhtsMZw293.txt");
System.out.println(i == 0 ? "删除成功" : "删除失败:" + i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package cn.hui.javapro.list.arraylist;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
public class BaseArrayList{
public static void add(){
Queue q = new LinkedList();
q = new PriorityQueue();
Map<String,String> mp = new HashMap<String,String>();
List<Object> arraylist = new ArrayList<Object>();
arraylist.add(1, 100);
}
public static void main(String[] args) {
add();
System.out.println("guojianhui121");
}
} |
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class MigrationModel extends Model {
//detectCollisions() will contain the logic that determines if the bird model has collided with objects such as the ground and other obstacles
@Override
public boolean detectCollisions() {
return false;
}
//updateLocationAndDirection() will contain the logic that allows the bird to move in the x or y direction based on user input
@Override
public void updateLocationAndDirection() {
}
//randomizeObstacles() will contain the logic that randomizes where obstacles such as blocks or enemies will appear in the game
public void randomizeObstacles() {
}
}
//-----------------------------------------------------------------------------------------------------
//JUnit Tests
class MigrationModelTest {
@Test
public void testDetectCollisions() {
MigrationModel test = new MigrationModel();
assertEquals(false, test.detectCollisions());
assertFalse(test.detectCollisions());
}
@Test
public void testUpdateLocationAndDirection() {
MigrationModel test = new MigrationModel();
test.setXloc(0);
test.setxVector(1);
test.updateLocationAndDirection();
assertNotEquals(0, test.getXloc());
assertNotEquals(1, test.getxVector());
}
@Test
public void testRandomizeObstacles() {
//can't test at this time
}
}
|
package org.wuqinghua.communicate;
import org.wuqinghua.thread.ObjectLock;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by wuqinghua on 18/2/11.
*/
public class MyQueue<T> {
//1.需要一个承装元素的集合
private final LinkedList<T> list = new LinkedList<>();
//2.需要一个计数器
private AtomicInteger count = new AtomicInteger(0);
//3.需要指定上限和下限
private final int minSize = 0;
private final int maxSize;
public MyQueue() {
this(5);
}
public MyQueue(int maxSize) {
this.maxSize = maxSize;
}
//4.需要一个对象来进行加锁
private final Object lock = new Object();
public void put(T t) {
synchronized (lock) {
while (this.count.get() == maxSize) { //容器已满
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//添加元素
this.list.add(t);
count.incrementAndGet();
System.out.println("添加了一个元素:" + t);
//唤醒其他线程
this.lock.notify();
}
}
public T take() {
T ret = null;
synchronized (lock) {
while (this.count.get() == this.minSize) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//获取数据
ret = list.removeFirst();
System.out.println("获取了一个元素:" + ret);
count.decrementAndGet();
this.lock.notify();
}
return ret;
}
public int size() {
return this.count.get();
}
public static void main(String[] args) {
MyQueue<String> queue = new MyQueue<>();
queue.put("a");
queue.put("b");
queue.put("c");
queue.put("d");
queue.put("e");
System.out.println(queue.size());
Thread t1 = new Thread(()->{
queue.put("f");
queue.put("g");
});
t1.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread t2 = new Thread(()->{
queue.take();
queue.take();
});
t2.start();
}
}
|
package com.mx.profuturo.bolsa.util.exception.custom;
/**
* Created by Luis Miguel Romero on 01/05/2017.
*/
public class AuthenticationException extends GenericStatusException {
public AuthenticationException() {
super();
}
public AuthenticationException(Exception e) {
super(e);
}
public AuthenticationException(String code, String message) {
super(code, message);
}
}
|
package com.example.administrator.hyxdmvp.ui.presenter.forgetpassword;
public class ForGetPassWordPresenter {
}
|
package ru.figures.model;
public class Polygon extends AbstractClosedFigure implements CorrectFigure{
private int numberOfSides;
private double length;
final int[] arr;
public Polygon(int numberOfSides, int length) {
arr = new int[10];
this.numberOfSides = numberOfSides;
this.length = length;
}
@Override
public double getRadiusOfInscribedCircle() {
int i = 0;
return length / 2 / Math.tan(Math.PI / numberOfSides);
}
@Override
public double getRadiusOfCircumscribedCircle() {
return length / 2 / Math.sin(Math.PI / numberOfSides);
}
@Override
public Double getArea() {
return numberOfSides * Math.pow(length, 2) / (4 * Math.tan(Math.PI / numberOfSides));
}
@Override
public Double getPerimeter() {
return numberOfSides * length;
}
@Override
public Double getPriority() {
return (double) getNumberOfSides();
}
@Override
public String toString() {
return "Polygon{" +
"numberOfSides=" + numberOfSides +
", length=" + length +
'}';
}
public int getNumberOfSides() {
return numberOfSides;
}
public void setNumberOfSides(int numberOfSides) {
this.numberOfSides = numberOfSides;
}
public Double getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
}
|
package hugo;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class MapPanel extends JPanel {
DataStore ds;
ControlUI cui;
public MapPanel(DataStore ds) {
this.ds = ds;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
final Color LIGHT_COLOR = new Color(150, 150, 150);
final Color DARK_COLOR = new Color(0, 0, 0);
final Color RED_COLOR = new Color(255, 0, 0);
final Color BLUE_COLOR = new Color(20, 0, 247);
final Color GREEN_COLOR = new Color(14, 163, 16);
final Color YELLOW_COLOR= new Color(255, 215, 0);
int x, y;
int x1, y1;
int x2, y2;
final int circlesize = 20;
final int ysize = 350;
final int xsize = 700;
if (ds.networkRead == true) { // Only try to plot is data has been properly read from file
// Compute scale factor in order to keep the map in proportion when the window is resized
int height = getHeight();
int width = getWidth();
double xscale = 1.0 * width / xsize;
double yscale = 1.0 * height / ysize;
//for (int i = 0; i < ds.nodes; i++) {
x = (int) ds.robotX;
y = (int) ds.robotY;
g.fillOval(x-((circlesize)/2), height - y- (circlesize) / 2, circlesize, circlesize);
g.setColor(DARK_COLOR);
// }
// Draw nodes as circles
for (int i = 0; i < ds.nodes; i++) {
x = (int) (ds.nodeX[i] * xscale);
y = (int) (ds.nodeY[i] * yscale);
if (ds.nodeColor[i] == 1) {
g.setColor(RED_COLOR);
}
else if(ds.nodeColor[i]==2){
g.setColor(GREEN_COLOR);
}
else if(ds.nodeColor[i]==3){
g.setColor(YELLOW_COLOR);
}
else {
g.setColor(BLUE_COLOR);
}
g.drawOval(x - (circlesize / 2), height - y - circlesize / 2, circlesize, circlesize);
}
// Draw arcs
for (int i = 0; i < ds.arcs; i++) {
x1 = (int) (ds.nodeX[ds.arcStart[i] - 1] * xscale);
y1 = (int) (ds.nodeY[ds.arcStart[i] - 1] * yscale);
x2 = (int) (ds.nodeX[ds.arcEnd[i] - 1] * xscale);
y2 = (int) (ds.nodeY[ds.arcEnd[i] - 1] * yscale);
if(ds.arcColor[i] == 1){
g.setColor(RED_COLOR);
}
else
g.setColor(BLUE_COLOR);
g.drawLine(x1, height - y1, x2, height - y2);
// System.out.println("Arc "+i+": "+ds.arcStart[i]+" "+ds.arcEnd[i]);
}
}
} // end paintComponent
}
|
package com.example.supplico_login;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class home extends AppCompatActivity {
TextView withcard,withoutcard,logt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
withcard=findViewById(R.id.buy_card_text);
withoutcard=findViewById(R.id.prdtwithout_card);
withcard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(home.this,pdt_card.class));
}
});
withoutcard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(home.this,pdt_without_crd.class));
}
});
logt=findViewById(R.id.log_out);
logt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(home.this,MainActivity.class));
}
});
}
}
|
package cn.izouxiang.rpc.service.api;
import cn.izouxiang.domain.Member;
import cn.izouxiang.rpc.service.api.base.BaseService;
public interface MemberService extends BaseService<Member> {
Member addMember(Member member);
Member findByUsernameOrPhoneOrMail(String str);
}
|
package com.gridnine.testing;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Flight> flightList = FlightBuilder.createFlights();
List<Flight> filteredList1 = new FlightFilter(flightList).afterDeparted(LocalDateTime.now());
int counter = 1;
for (Flight flight : filteredList1) {
System.out.print(counter++ +") ");
System.out.println(flight.toString());
}
counter=1;
System.out.println("____________________________________");
List<Flight> filteredList2 = new FlightFilter(flightList).afterArrival(LocalDateTime.now().plusDays(3).minusHours(6));
for (Flight flight : filteredList2) {
System.out.print(counter++ +") ");
System.out.println(flight.toString());
}
counter=1;
System.out.println("____________________________________");
List<Flight> flightList3 = new FlightFilter(flightList).timeOnGround(2l, false);
for (Flight flight: flightList3) {
System.out.print(counter++ +") ");
System.out.println(flight.toString());
}
ArrayList arrayList = new ArrayList();
LinkedList linkedList = new LinkedList();
}
}
|
package com.tencent.mm.pluginsdk.ui.tools;
import com.tencent.mm.plugin.appbrand.jsapi.appdownload.JsApiPauseDownloadTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final class q {
static Pattern qUr = Pattern.compile("(?:(http|https|file)\\:\\/\\/)?(?:([-A-Za-z0-9$_.+!*'(),;?&=]+(?:\\:[-A-Za-z0-9$_.+!*'(),;?&=]+)?)@)?([a-zA-Z0-9 -豈-﷏ﷰ-%_-][a-zA-Z0-9 -豈-﷏ﷰ-%_\\.-]*|\\[[0-9a-fA-F:\\.]+\\])?(?:\\:([0-9]*))?(\\/?[^#]*)?.*", 2);
String ben;
String fFQ;
String qUo;
String qUp;
int qUq;
public q(String str) {
if (str == null) {
throw new NullPointerException();
}
this.qUo = "";
this.qUp = "";
this.qUq = -1;
this.ben = "/";
this.fFQ = "";
Matcher matcher = qUr.matcher(str);
if (matcher.matches()) {
String group = matcher.group(1);
if (group != null) {
this.qUo = group.toLowerCase();
}
group = matcher.group(2);
if (group != null) {
this.fFQ = group;
}
group = matcher.group(3);
if (group != null) {
this.qUp = group;
}
group = matcher.group(4);
if (group != null && group.length() > 0) {
try {
this.qUq = Integer.parseInt(group);
} catch (NumberFormatException e) {
throw new Exception("Bad port");
}
}
String group2 = matcher.group(5);
if (group2 != null && group2.length() > 0) {
if (group2.charAt(0) == '/') {
this.ben = group2;
} else {
this.ben = "/" + group2;
}
}
if (this.qUq == JsApiPauseDownloadTask.CTRL_INDEX && this.qUo.equals("")) {
this.qUo = "https";
} else if (this.qUq == -1) {
if (this.qUo.equals("https")) {
this.qUq = JsApiPauseDownloadTask.CTRL_INDEX;
} else {
this.qUq = 80;
}
}
if (this.qUo.equals("")) {
this.qUo = "http";
return;
}
return;
}
throw new Exception("Bad address");
}
public final String toString() {
String str = "";
if ((this.qUq != JsApiPauseDownloadTask.CTRL_INDEX && this.qUo.equals("https")) || (this.qUq != 80 && this.qUo.equals("http"))) {
str = ":" + Integer.toString(this.qUq);
}
String str2 = "";
if (this.fFQ.length() > 0) {
str2 = this.fFQ + "@";
}
return this.qUo + "://" + str2 + this.qUp + str + this.ben;
}
}
|
package javax.swing;
import java.util.HashMap;
public class ActionMap {
private HashMap<String, Action> map = new HashMap<>();
public ActionMap() {}
public void put(String key, Action value) {
map.put(key, value);
}
public Action get(String key) {
return map.get(key);
}
}
|
package br.eti.ns.nssuite.requisicoes.nfe;
import br.eti.ns.nssuite.requisicoes._genericos.ListarNSNRecReq;
public class ListarNSNRecReqNFe extends ListarNSNRecReq {
public String chNFe;
}
|
/*
3. Создать класс Teacher (Преподаватель), имеющий поля “Имя”, “Предмет”.
Создать класс Student (Студент) с полем “Имя”.
Каждый класс имеет конструктор (с параметрами), set и get методы по необходимости,
а также у преподавателя есть метод evaluate (оценить студента), принимающий в качестве
аргумента студента, и работающий следующим образом: внутри метода случайным образом генерируется
число от 0 до 5, выводится строка: "Преподаватель ИМЯПРЕПОДАВАТЕЛЯ оценил студента с
именем ИМЯСТУДЕНТА по предмету ИМЯПРЕДМЕТА на оценку ОЦЕНКА."
Все слова, написанные большими буквами, должны быть заменены соответствующими значениями.
ОЦЕНКА должна принимать значения "отлично”, "хорошо”, "удовлетворительно" или "неудовлетворительно",
в зависимости от значения случайного числа.
Создайте по 1 экземпляру каждого класса, у преподавателя вызовите
метод оценки студента, передав студента в качестве аргумента метода.
*/
package day6;
public class Task3 {
public static void main(String[] args) {
Teacher teacher1 = new Teacher("Иван Иванович", "Алгебра");
Student student1 = new Student("Сергей Петров");
teacher1.evaluate(student1);
}
}
|
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.util.*;
import java.util.stream.Collectors;
public class IntermediateService extends java.rmi.server.UnicastRemoteObject implements IntermediateServiceInterface {
public static final int DELAY = 100;
private String name;
private Map<IntermediateServiceInterface, List<String>> intermediateServiceListMap = new HashMap<>();
private Map<SubscriberServiceInterface, List<String>> subscriberServiceListMap = new HashMap<>();
private Set<String> sentString = new HashSet<>();
private Set<String> receivedString = new HashSet<>();
protected IntermediateService() throws RemoteException {
super();
}
@Override
public void receiveSubscribeFromSubscriber(SubscriberServiceInterface subscriberServiceInterface, List<String> publishedList) throws RemoteException {
System.out.println("Recebendo assunatura de assinante " + subscriberServiceInterface.getName());
subscriberServiceListMap.replace(subscriberServiceInterface, publishedList);
sentInterestFromThisToNeighbor(publishedList);
}
@Override
public void sentInterestFromThisToNeighbor(List<String> publishedList) {
System.out.print("Enviando interesse do Intermediario " + getName() + " a seus Intermediarios vizinhos sobre " + publishedList);
intermediateServiceListMap.forEach((intermediate, listStrings) -> {
try {
System.out.print(" ,Vizinhos: " + intermediate.getName());
intermediate.receiveInterestFromNeightborIntermediate(this, publishedList);
} catch (RemoteException e) {
e.printStackTrace();
}
});
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" ");
}
@Override
public void receiveInterestFromNeightborIntermediate(IntermediateServiceInterface intermediateServiceInterface, List<String> listIntereset) throws RemoteException {
String strPrint = "";
List<String> interestList = intermediateServiceListMap.get(intermediateServiceInterface);
List<String> newListOfIntereset = listIntereset.stream().filter(newIntereset -> !interestList.contains(newIntereset)).collect(Collectors.toList());
if (newListOfIntereset.size() > 0) {
strPrint += ("O Intermediario " + this.name + " esta recebendo interesse do intermediario vizinho: " + intermediateServiceInterface.getName() + " sobre " + listIntereset.toString());
strPrint += ("Atualizando lista de interesses de " + interestList.toString());
interestList.addAll(newListOfIntereset);
strPrint += ("Atualizando lista de interesses para " + interestList.toString());
// intermediateServiceListMap.replace(intermediateServiceInterface, interestList);
intermediateServiceListMap.replace(intermediateServiceInterface, newListOfIntereset);
sentInterestFromThisToNeighbor(newListOfIntereset);
}
System.out.println(strPrint.join("\n"));
}
@Override
public void receivePublishFromPublisher(List<String> publishedList) throws RemoteException {
System.out.println("Recebendo Publicacao " + publishedList.toString());
this.receivedString.addAll(publishedList);
this.sentToEveryOneWithInterest(publishedList);
}
@Override
public void sentToEveryOneWithInterest(List<String> publishList) throws RemoteException {
System.out.print("Enviando, para vizinhos, informacao para interessados a " + publishList.toString());
publishList.forEach(string -> sendToSubscriber(string));
intermediateServiceListMap.forEach((intermediate, listStrings) -> {
List<String> matchedPublish = listStrings.stream().filter(string -> publishList.contains(string)).collect(Collectors.toList());
if (matchedPublish.size() > 0) {
matchedPublish.forEach(stringToSend -> {
try {
System.out.print(" para: " + intermediate.getName());
intermediate.receivePublishFromIntermediate(stringToSend);
} catch (RemoteException e) {
e.printStackTrace();
}
});
}
});
System.out.println(" ");
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void receivePublishFromIntermediate(String published) throws RemoteException {
System.out.println("Recebendo publicacao de intermediario " + published);
sendToSubscriber(published);
if (!sentString.contains(published)) {
sentString.add(published);
intermediateServiceListMap.forEach((intermediate, listStrings) -> {
if (listStrings.contains(published)) {
try {
System.out.println("E enviando para " + intermediate.getName());
intermediate.receivePublishFromIntermediate(published);
// intermediate.sentToEveryOneWithInterest(published);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void sendToSubscriber(String published) {
System.out.println("Enviando para assinante " + published);
subscriberServiceListMap.forEach((subscriber, listStrings) -> {
Boolean interest = listStrings.contains(published);
if (interest) {
try {
System.out.println("Assinante encontrado " + subscriber.getName());
subscriber.receivePublishedMessage(published);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public SubscriberServiceInterface connectToSubscriber(String name) {
System.out.println("Conectando ao assinante: " + name);
SubscriberServiceInterface subscriberServiceConnection = null;
try {
subscriberServiceConnection = (SubscriberServiceInterface) Naming.lookup("//127.0.0.1:1099/ " + name);
subscriberServiceListMap.put(subscriberServiceConnection, new ArrayList<>());
} catch (Exception e) {
e.printStackTrace();
}
return subscriberServiceConnection;
}
@Override
public IntermediateServiceInterface connectToIntermediate(String name) {
System.out.println("Conectando ao intermediario: " + name);
IntermediateServiceInterface intermediateServiceConnection = null;
try {
intermediateServiceConnection = (IntermediateServiceInterface) Naming.lookup("//127.0.0.1:1099/ " + name);
intermediateServiceListMap.put(intermediateServiceConnection, new ArrayList<>());
} catch (Exception e) {
e.printStackTrace();
}
return intermediateServiceConnection;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IntermediateService)) return false;
if (!super.equals(o)) return false;
IntermediateService that = (IntermediateService) o;
return Objects.equals(getName(), that.getName());
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), getName());
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
System.out.println("Name has been setted to " + name);
this.name = name;
}
public Map<IntermediateServiceInterface, List<String>> getIntermediateServiceListMap() {
return intermediateServiceListMap;
}
public void setIntermediateServiceListMap(Map<IntermediateServiceInterface, List<String>> intermediateServiceListMap) {
this.intermediateServiceListMap = intermediateServiceListMap;
}
public Map<SubscriberServiceInterface, List<String>> getSubscriberServiceListMap() {
return subscriberServiceListMap;
}
public void setSubscriberServiceListMap(Map<SubscriberServiceInterface, List<String>> subscriberServiceListMap) {
this.subscriberServiceListMap = subscriberServiceListMap;
}
}
|
package com.tencent.mm.plugin.game.gamewebview.jsapi.biz;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.tencent.mm.g.a.gl;
import com.tencent.mm.plugin.game.gamewebview.ipc.GWMainProcessTask;
import com.tencent.mm.plugin.game.gamewebview.ipc.GameWebViewMainProcessService;
import com.tencent.mm.plugin.game.gamewebview.jsapi.a;
import com.tencent.mm.plugin.game.gamewebview.ui.d;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.x;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
public final class GameJsApiGetGameCommInfo extends a {
public static final int CTRL_BYTE = 241;
public static final String NAME = "getGameCommInfo";
private static class GetGameCommInfoTask extends GWMainProcessTask {
public static final Creator<GetGameCommInfoTask> CREATOR = new 1();
public String bPE;
public int nc;
public String result;
/* synthetic */ GetGameCommInfoTask(Parcel parcel, byte b) {
this(parcel);
}
public final void aai() {
gl glVar = new gl();
glVar.bPC.nc = this.nc;
glVar.bPC.bPE = this.bPE;
glVar.bPC.context = ad.getContext();
com.tencent.mm.sdk.b.a.sFg.m(glVar);
this.result = glVar.bPD.result;
}
public final void g(Parcel parcel) {
this.nc = parcel.readInt();
this.bPE = parcel.readString();
this.result = parcel.readString();
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(this.nc);
parcel.writeString(this.bPE);
parcel.writeString(this.result);
}
private GetGameCommInfoTask(Parcel parcel) {
g(parcel);
}
}
public final void a(d dVar, JSONObject jSONObject, int i) {
x.i("MicroMsg.GameJsApiGetGameCommInfo", "invoke");
if (jSONObject == null) {
x.e("MicroMsg.GameJsApiGetGameCommInfo", "data is null");
dVar.E(i, a.f("getGameCommInfo:fail_invalid_data", null));
return;
}
GWMainProcessTask getGameCommInfoTask = new GetGameCommInfoTask();
getGameCommInfoTask.nc = jSONObject.optInt("cmd", 0);
getGameCommInfoTask.bPE = jSONObject.optString("param");
GameWebViewMainProcessService.b(getGameCommInfoTask);
Map hashMap = new HashMap();
hashMap.put("gameRegionName", getGameCommInfoTask.result);
dVar.E(i, a.f("getGameCommInfo:ok", hashMap));
}
}
|
package com.perfectorial.controller;
import com.perfectorial.entity.Category;
import com.perfectorial.logic.CategoryLogic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author Reza Safarpour (rsafarpour1991@gmail.com) on 9/11/2015
*/
@RestController
public class CategoryController {
@Autowired
private CategoryLogic categoryLogic;
@RequestMapping(value = URIConstants.Category.CATEGORY, method = RequestMethod.GET)
public Category getCategory(@PathVariable String id) {
return categoryLogic.get(id);
}
@RequestMapping(value = URIConstants.Category.CATEGORIES, method = RequestMethod.GET)
public List<Category> getCategories() {
return categoryLogic.getAll();
}
@RequestMapping(value = URIConstants.Category.CREATE_CATEGORY, method = RequestMethod.POST)
public Category createCategory(@RequestBody Category category) {
return categoryLogic.create(category);
}
}
|
import javax.swing.*;
public class Alient extends Fly implements Constans, Runnable {
Bomb bomb;
private int dis = -1;
public Alient(){
}
public Alient(int x, int y){
this.x = x;
this.y = y;
ImageIcon ic = new ImageIcon("DrawImage/alien.png");
this.setImage(ic.getImage());
bomb = new Bomb(x, y);
}
public void go(){
this.x += dis;
if (x <= 0){
dis = -1*dis;
this.setY(this.getY()+15);
}
if (x >= BOARD_WIDTH-12){
dis = -1*dis;
this.setY(this.getY()+15);
}
}
public int getDis() {
return dis;
}
public void setDis(int dis) {
this.dis = dis;
}
public Bomb getBomb(){
return bomb;
}
@Override
public void run() {
while (Board.ingame) {
go();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
package com.tencent.mm.plugin.appbrand;
import com.tencent.mm.plugin.appbrand.r.i.a;
import com.tencent.mm.sdk.platformtools.x;
class c$1 implements a {
final /* synthetic */ String fbS;
final /* synthetic */ c fbT;
c$1(c cVar, String str) {
this.fbT = cVar;
this.fbS = str;
}
public final void qe(String str) {
x.i("MicroMsg.AppBrandJSContextInterface[multicontext]", "create with appID(%s), scriptPath(%s), sdkScript inject succeed", new Object[]{this.fbT.fbP.mAppId, this.fbS});
this.fbT.cq(true);
}
public final void fM(String str) {
x.e("MicroMsg.AppBrandJSContextInterface[multicontext]", "create with appID(%s), scriptPath(%s), sdkScript inject failed", new Object[]{this.fbT.fbP.mAppId, this.fbS});
this.fbT.cq(false);
}
}
|
package mono.com.facebook.drawee.gestures;
public class GestureDetector_ClickListenerImplementor
extends java.lang.Object
implements
mono.android.IGCUserPeer,
com.facebook.drawee.gestures.GestureDetector.ClickListener
{
/** @hide */
public static final String __md_methods;
static {
__md_methods =
"n_onClick:()Z:GetOnClickHandler:Com.Facebook.Drawee.Gestures.GestureDetector/IClickListenerInvoker, Naxam.FrescoDrawee.Droid\n" +
"";
mono.android.Runtime.register ("Com.Facebook.Drawee.Gestures.GestureDetector+IClickListenerImplementor, Naxam.FrescoDrawee.Droid, Version=1.5.0.0, Culture=neutral, PublicKeyToken=null", GestureDetector_ClickListenerImplementor.class, __md_methods);
}
public GestureDetector_ClickListenerImplementor ()
{
super ();
if (getClass () == GestureDetector_ClickListenerImplementor.class)
mono.android.TypeManager.Activate ("Com.Facebook.Drawee.Gestures.GestureDetector+IClickListenerImplementor, Naxam.FrescoDrawee.Droid, Version=1.5.0.0, Culture=neutral, PublicKeyToken=null", "", this, new java.lang.Object[] { });
}
public boolean onClick ()
{
return n_onClick ();
}
private native boolean n_onClick ();
private java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
|
package problem_solve.dfs.maze_solve;
public class MazeSolver {
private int rowSize;
private int colSize;
private int[][] maze;
MazeSolver(int[][] maze){
this.maze = maze;
rowSize = maze.length;
colSize = maze[0].length;
}
public void dfs(int row, int col){
if(0 > row || row >= rowSize){
return;
}
if(0 > col || col >= colSize){
return;
}
if(maze[row][col] == 1){
return;
}
if(maze[row][col] == 3){
throw new RuntimeException();
}
maze[row][col] = 1;
System.out.println("Current Point : (" + row + ", " + col +")");
dfs(row, col + 1); // go right
dfs(row + 1, col); // go down
dfs(row, col - 1); // go left
dfs(row - 1, col); // go up
}
}
|
package br.com.senior.varejo.pedidos;
import org.springframework.beans.factory.annotation.Autowired;
import br.com.senior.messaging.model.HandlerImpl;
@HandlerImpl
public class ObterUrlUploadFotoImpl implements ObterUrlUploadFoto {
@Autowired
ClienteFotoService clienteFotoService;
@Override
public ObterUrlUploadFotoOutput obterUrlUploadFoto(ObterUrlUploadFotoInput request) {
return clienteFotoService.obterUrlUploadFoto(request.id);
}
}
|
/* */ package com.ketonix.ketonixpro;
/* */
/* */ import java.io.PrintStream;
/* */ import java.util.Map;
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class BootKetonix
/* */ {
/* */ public BootKetonix() {}
/* */
/* */ public static void startKSync()
/* */ throws Exception
/* */ {
/* 18 */ String separator = System.getProperty("file.separator");
/* 19 */ String classpath = System.getProperty("java.class.path");
/* 20 */ String path = System.getProperty("java.home") + separator + "bin" + separator + "java";
/* 21 */ String jlp = System.getProperty("java.library.path");
/* 22 */ System.out.println("java.library.path:" + jlp);
/* */
/* 24 */ ProcessBuilder processBuilder = new ProcessBuilder(new String[] { path, "-DLANG=sv_SE.UTF-8", "-jar", classpath, KSync.class.getName() });
/* 25 */ System.out.println(path + "-DLANG=sv_SE.UTF-8" + " -jar" + classpath + KSync.class.getName());
/* 26 */ Map<String, String> mp = processBuilder.environment();
/* 27 */ mp.put("LANG", "sv_SE.UTF-8");
/* 28 */ Process process = processBuilder.start();
/* 29 */ process.waitFor();
/* */ }
/* */ }
/* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/com/ketonix/ketonixpro/BootKetonix.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/ |
package ru.otus.homework.services;
import org.junit.jupiter.api.*;
import ru.otus.homework.models.Author;
import ru.otus.homework.repository.AuthorRepositoryJpa;
import ru.otus.outside.db.JpaDedicatedEntityManagerTest;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static ru.otus.outside.utils.LIstStringsHelper.assertListStringsEquals;
import static ru.otus.outside.utils.LIstStringsHelper.printListStrings;
import static ru.otus.outside.utils.TestData.*;
@DisplayName("Class AuthorsServiceImpl")
class AuthorsServiceImplTest
{
private AuthorRepositoryJpa repository;
private AuthorsServiceImpl service;
@Test
@DisplayName("is instantiated with new AuthorsServiceImpl()")
void isInstantiatedWithNew()
{
new AuthorsServiceImpl(null);
}
private AuthorsServiceImpl createMockService()
{
repository = mock(AuthorRepositoryJpa.class);
return new AuthorsServiceImpl(repository);
}
private List<String[]> createEmptyStringsAuthors()
{
List<String[]> result = new LinkedList<>();
result.add(AuthorRepositoryJpa.FIND_ALL_HEADER);
return result;
}
@Nested
@DisplayName("when new default")
class WhenNew
{
@BeforeEach
void createNewQuestions()
{
service = createMockService();
}
@Test
@DisplayName("injected values in AuthorsServiceImpl()")
void defaults()
{
assertThat(service).hasFieldOrPropertyWithValue("authorRepository", repository);
}
}
@Nested
@DisplayName("when mock AuthorRepositoryJpa")
class ServiceMethods
{
private final String[] TEST_AUTHOR6_RECORD = new String[]{
Long.toString(6L), TEST_AUTHOR6_FIRST_NAME, TEST_AUTHOR6_LAST_NAME
};
@BeforeEach
void createNewService() throws SQLException
{
service = createMockService();
}
@Test
void findAll_empty()
{
List<Author> authors = new LinkedList<>();
when(repository.findAll()).thenReturn(authors);
List<String[]> testList = service.findAll();
List<String[]> expected = createEmptyStringsAuthors();
assertEquals(expected.get(0).length, testList.get(0).length);
assertArrayEquals(expected.get(0), testList.get(0));
}
@Test
void findAll()
{
List<Author> authors = new LinkedList<>();
authors.add(createAuthor6());
when(repository.findAll()).thenReturn(authors);
List<String[]> testList = service.findAll();
List<String[]> expected = createEmptyStringsAuthors();
expected.add(TEST_AUTHOR6_RECORD);
// printListStrings(System.out, testList);
assertEquals(expected.get(0).length, testList.get(0).length);
assertListStringsEquals(expected, testList);
}
@Test
void findById()
{
when(repository.findById(6L)).thenReturn(createAuthor6());
List<String[]> testList = service.findById(6L);
List<String[]> expected = createEmptyStringsAuthors();
expected.add(TEST_AUTHOR6_RECORD);
// printListStrings(System.out, testList);
assertEquals(expected.get(0).length, testList.get(0).length);
assertListStringsEquals(expected, testList);
}
@Test
void findByFirstName()
{
List<Author> authors = new LinkedList<>();
authors.add(createAuthor6());
when(repository.findByFirstName(TEST_AUTHOR6_FIRST_NAME)).thenReturn(authors);
List<String[]> testList = service.findByFirstName(TEST_AUTHOR6_FIRST_NAME);
List<String[]> expected = createEmptyStringsAuthors();
expected.add(TEST_AUTHOR6_RECORD);
// printListStrings(System.out, testList);
assertEquals(expected.get(0).length, testList.get(0).length);
assertListStringsEquals(expected, testList);
}
@Test
void findByLastName()
{
List<Author> authors = new LinkedList<>();
authors.add(createAuthor6());
when(repository.findByLastName(TEST_AUTHOR6_LAST_NAME)).thenReturn(authors);
List<String[]> testList = service.findByLastName(TEST_AUTHOR6_LAST_NAME);
List<String[]> expected = createEmptyStringsAuthors();
expected.add(TEST_AUTHOR6_RECORD);
// printListStrings(System.out, testList);
assertEquals(expected.get(0).length, testList.get(0).length);
assertListStringsEquals(expected, testList);
}
}
@Nested
@DisplayName("JPA H2 insert/update tests for AuthorRepositoryJpa")
class JpaH2CreateUpdateTests extends JpaDedicatedEntityManagerTest
{
@BeforeEach
void createNew()
{
repository = new AuthorRepositoryJpa(entityManager);
service = new AuthorsServiceImpl(repository);
}
@DisplayName("insert")
@Test
void insert()
{
runInTransaction(() -> {
service.insert("test", "test");
List<Author> result = repository.findByFirstName("test");
assertEquals(1, result.size());
});
}
@DisplayName("update")
@Test
void update()
{
runInTransaction(() -> {
Author author6 = createAuthor6();
author6.setFirstName("test");
author6.setLastName("test");
service.update(author6.getId(), author6.getFirstName(), author6.getLastName());
Author test = repository.findById(author6.getId());
assertEquals(author6, test);
});
}
@DisplayName("delete")
@Test
void delete()
{
clearAuthorIsbn();
runInTransaction(() -> {
assertEquals(3, repository.findAll().size());
service.delete(6L);
assertEquals(2, repository.findAll().size());
});
}
}
} |
package com.mega.mvc14;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
//기능하나당 public 하나
// dao는 무조건 싱글톤으로 만들어주어야 한다
@Repository // 싱글톤으로 만들어준다 싱글톤을 만들어줄 객체가 아니면 어노테이샨 달면 않는다
public class MemberDAO {
// 스프링이 싱글톤으로 만들면 스프링이 가지고 있는 정보 3가지 // @Autowired
// 클래스명: SqlSessionTemplate, // @Inject
// 만들어진 객체명: myBatis
// 주소:100
// @Inject("mybatis")
@Autowired
SqlSessionTemplate myBatis; // 100
public List<MemberDTO> list() {
List<MemberDTO> list = myBatis.selectList("member.all");
return list;
}
public boolean login(MemberDTO dto) {
String dbId = "root";
String dbPw = "1234";
boolean result = false; // 컨트롤러의 결과를 알려주기 위한 변수
if (dto.getId().equals(dbId) && dto.getPw().equals(dbPw)) {
result = true;
}
return result;
}
// public boolean check(MemberDTO dto) {
// String dbNick = "superman";
// boolean result2 = false; // 컨트롤러의 결과를 알려주기 위한 변수
// if (dto.getNick().equals(dbNick)) {
// result2 = true;
// }
//
// return result2;
//
// }
public void create(MemberDTO memberDTO) {
myBatis.insert("member.create", memberDTO);
}
public MemberDTO read(MemberDTO memberDTO) {
MemberDTO dto = myBatis.selectOne("member.one", memberDTO);
return dto;
}
public void update() {
}
public int delete(MemberDTO memberDTO) {
int result = myBatis.delete("member.del", memberDTO);
return result;
}
}
|
package com.spizzyrichlife.ussrpg_v01;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.View;
import android.widget.ListView;
import com.spizzyrichlife.ussrpg_v01.Activities.CharacterCreationActivity;
import com.spizzyrichlife.ussrpg_v01.Activities.MainActivity;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onData;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.clearText;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.intent.Intents.intended;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.CoreMatchers.anything;
import static org.hamcrest.CoreMatchers.startsWith;
/**
* Created by SpizzyRich on 9/7/16.
*/
@RunWith(AndroidJUnit4.class)
public class EspressoTests {
@Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<MainActivity>(MainActivity.class);
//HOWTO Set up a test
// @Test
// public void testSomething() throws Exception {
// onView(withId(R.id.sign_in_button))
// .perform(click())
// .check(matches(isDisplayed()));
// }
@Test
public void testCharacterCreationProcess() throws Exception{
testMainCharCreateButton();
testCharNameSpace();
testXPSpace();
testCharCreateButton();
}
// Should switch to character creation activity
public void testMainCharCreateButton() throws Exception {
onView(withId(R.id.action_create))
.perform(click());
intended(hasComponent(CharacterCreationActivity.class.getName()));
}
// Should type test name into character creation name space
public void testCharNameSpace() throws Exception {
onView(withId(R.id.nameEditText))
.perform(clearText())
.perform(typeText("Test Char Name"))
.check(withText("Test Char Name"));
}
// Should type test XP value into character creation XP space
public void testXPSpace() throws Exception {
onView(withId(R.id.xpEditText))
.perform(clearText())
.perform(typeText("10"))
.check(withText("10"));
}
// Should click character creation button in character creation activity to send Player Character object to PC table in database
public void testCharCreateButton() throws Exception {
onView(withId(R.id.charCreateButton))
.perform(click());
}
//Leo's Tests
private void test1(String test) {
final int[] counts = new int[1];
onView(withId(R.id.pcList)).check(matches(new TypeSafeMatcher<View>() {
@Override
public boolean matchesSafely(View view) {
ListView listView = (ListView) view;
counts[0] = listView.getCount();
return true;
}
@Override
public void describeTo(Description description) {
}
}));
//TODO: figure out what this does...
// onView(ViewMatchers.withId(R.id.<Add Button>))
// .perform(click());
// onView(ViewMatchers.withId(R.id.game_name))
// .perform(typeText(test));
// onView(ViewMatchers.withId(R.id.game_numof_attributes))
// .perform(typeText("Health, Attack, Power"));
// onView(ViewMatchers.withId(android.R.id.button1))
// .perform(click());
onData(anything())
.inAdapterView(withId(R.id.pcList))
.atPosition(counts[0])
.onChildView(withId(R.id.pc_lv_character_name))
.check(matches(withText(startsWith(test))));
}
}
|
package Flags;
import javafx.scene.Node;
public abstract class Flag {
public String getName() { return "";
}
public abstract Node renderFlag();
} |
// store m in n, from bit i to j
// for i = 2, j = 4
//create mask 1100011
class Solution {
public int insert(int m, int n, int i, int j) {
}
}
|
package com.example.karol.wildboartraining;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class ShowPlanActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_plan);
}
}
|
/*
* 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 quotationsoftware;
import java.io.InputStream;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TabPane;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import quotationsoftware.util.DbHandler;
import quotationsoftware.util.Keys;
/**
*
* @author sakit
*/
public class QuatationSoftware extends Application{
@FXML private TabPane tabPane;
private final ResourceBundle RB = ResourceBundle.getBundle("resources.bundles.Bundle", Locale.getDefault());
public final static Properties PROP = new Properties();
@Override
public void start(Stage primaryStage) throws Exception {
//load the main fxml file
Parent root = (Parent)FXMLLoader.load(getClass().getResource(Keys.MAIN_SCREEN), RB);
//get tabpane and select the home window
tabPane = (TabPane)root.getChildrenUnmodifiable().get(0);
tabPane.getSelectionModel().clearAndSelect(6);
try ( //load properties file
InputStream in = getClass().getResourceAsStream("/resources/settings/preference")) {
PROP.load(in);
}
//load the gui
Scene scene = new Scene(root,1300,950);
primaryStage.setScene(scene);
primaryStage.setMaximized(true);
primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/resources/images/logo-small.png")));
primaryStage.setTitle(RB.getString(Keys.PROG_NAME));
primaryStage.setOnCloseRequest(e->{
DbHandler.shutdown();
System.out.println("database shutdowned");
});
primaryStage.show();
}
public static void main(String args[]){
launch(args);
}
}
|
package com.ssgl.controller;
/*
* 功能:
* User: jiajunkang
* email:jiajunkang@outlook.com
* Date: 2018/1/16 0016
* Time: 21:00
*/
import com.alibaba.fastjson.JSONObject;
import com.ssgl.bean.Page;
import com.ssgl.bean.Result;
import com.ssgl.bean.TUser;
import com.ssgl.service.UserService;
import com.ssgl.util.FileUtils;
import com.ssgl.util.MD5Utils;
import com.ssgl.util.StringUtils;
import com.ssgl.util.Util;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class UserController {
@Autowired
public UserService userService;
@RequestMapping(value = "toIndex")
public String toIndex() {
return "login";
}
@RequestMapping(value = "login")
public String login(TUser user, HttpServletRequest request, String j_captcha) {
return userService.login(user, request, j_captcha);
}
@RequiresPermissions("toFloorUI")
@RequestMapping(value = "toUserUI")
public String toFloorUI() {
return "administrator";
}
@RequiresPermissions("addUser")
@ResponseBody
@RequestMapping(value = "addUser")
public Result addUser(TUser user) {
try {
user.setId(String.valueOf(Util.makeId()));
user.setPassword(MD5Utils.md5(user.getPassword()));
return userService.addUser(user);
} catch (Exception e) {
e.printStackTrace();
return new Result("error", "添加失败");
}
}
@RequiresPermissions("selectUsersPage")
@ResponseBody
@RequestMapping(value = "selectUsersPage", produces = "text/html;charset=utf-8")
public String selectUsersPage(Integer page, Integer rows, HttpServletRequest request) {
try {
Page<TUser> result = userService.selectUsersPage(page, rows, request);
Map<String, Object> map = new HashMap<>();
if (null != result) {
map.put("total", result.getTotalRecord());
map.put("rows", result.getList());
return JSONObject.toJSONString(map);
}
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@RequiresPermissions("deleteUsers")
@ResponseBody
@RequestMapping(value="deleteUsers")
public Result deleteUsers(String ids){
try {
return userService.deleteUsers(StringUtils.stringConvertList(ids));
}catch (Exception e){
e.printStackTrace();
return new Result("error", "删除失败");
}
}
@RequiresPermissions("updateUser")
@ResponseBody
@RequestMapping(value="updateUser")
public Result updateUser(TUser user){
try {
return userService.updateUser(user);
}catch (Exception e){
e.printStackTrace();
return new Result("error", "修改失败");
}
}
@RequestMapping(value = "exportUser")
public void exportUser(HttpServletRequest request,HttpServletResponse response) {
try {
List<TUser> users = userService.exportUser();
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFCellStyle cellStyle = workbook.createCellStyle();
HSSFSheet sheet = workbook.createSheet("管理员信息表");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue("管理员信息");
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
cell.setCellStyle(cellStyle);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));
HSSFRow r = sheet.createRow(1);
r.createCell(0).setCellValue("姓名");
r.createCell(1).setCellValue("生日");
r.createCell(2).setCellValue("性别");
r.createCell(3).setCellValue("电话");
r.createCell(4).setCellValue("评价");
r.createCell(5).setCellValue("邮箱");
for (TUser user : users) {
HSSFRow h = sheet.createRow(sheet.getLastRowNum() + 1);
h.createCell(0).setCellValue(user.getUsername());
h.createCell(1).setCellValue(user.getBirthday());
h.createCell(2).setCellValue(user.getGender());
h.createCell(3).setCellValue(user.getTelephone());
h.createCell(4).setCellValue(user.getRemark());
h.createCell(5).setCellValue(user.getEmail());
}
ServletOutputStream out = response.getOutputStream();
response.setContentType("application/msexcel");
String agent = request.getHeader("User-Agent");
String filename = FileUtils.encodeDownloadFilename("管理员信息表.xls", agent);
response.setHeader("content-disposition", "attachment;filename=" + filename);
workbook.write(out);
out.flush();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
package wx.realware.grp.pt.pb.common.avlid.group;
/**
* 更新数据Gourp
* ahthod lfq
* date 20180808
*/
public interface UpdateGroup {
}
|
package zm.gov.moh.common.submodule.form.model;
import java.io.Serializable;
public class Condition implements Serializable {
private Object value;
//Add expression object
private Expression expression;
private String dataType;
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
//Setter for expression
public void setExpression(Expression expression) {
this.expression = expression;
}
//Getter for expression
public Expression getExpression() {
return expression;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getDataType() {
return dataType;
}
} |
package BottomUp;
public class BottomUp {
public static void sort(Comparable[] elements) {
Comparable[] aux = new Comparable[elements.length];
for (int size = 1; size < elements.length; size *= 2) {
for (int low = 0; low < elements.length - size; low += 2 * size) {
int mid = low + size - 1;
int high = Math.min(low + 2 * size - 1, elements.length - 1);
merge(elements, aux, low, mid, high);
}
}
}
private static void merge(Comparable[] elements, Comparable[] aux, int low, int mid, int high) {
for (int k = low; k <= high; k++) {
aux[k] = elements[k];
}
int i = low;
int j = mid + 1;
for (int k = low; k <= high; k++) {
if (i > mid) {
elements[k] = aux[j++];
} else if (j > high) {
elements[k] = aux[i++];
} else if (aux[j].compareTo(aux[i])<0) {
elements[k] = aux[j++];
} else {
elements[k] = aux[i++];
}
}
}
}
|
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import com.model.ImageData;
public class UplaodDAO {
public static int uploadImage(String recordId,String imagename){
//ImageData patient = new ImageData();
int status = 0;
try {
PreparedStatement ps = null;
Connection conn= uploadUtil.getConnection();
ps = conn.prepareStatement("INSERT INTO upload_record (image_path, image_name) VALUES (?,?)");
ps.setString(1,recordId);
ps.setString(2,imagename);
status = ps.executeUpdate();
conn.close();
ps.close();
}catch(Exception e)
{
e.printStackTrace();
}
return status;
//return true;
}
public static ArrayList<ImageData> getAllImage(){
ArrayList<ImageData> mImageData = new ArrayList<ImageData>();
try {
Connection conn=uploadUtil.getConnection();
Statement statement = conn.createStatement();
ResultSet rs=statement.executeQuery("SELECT * FROM `upload_record`");
while(rs.next()) {
ImageData list = new ImageData();
list.setId(rs.getString(rs.findColumn("image_id")));
list.setImagePath(rs.getString(rs.findColumn("image_path")));
list.setImageName(rs.getString(rs.findColumn("image_name")));
mImageData.add(list);
}
conn.close();
rs.close();
}catch(Exception e)
{
e.printStackTrace();
}
return mImageData;
}
}
|
package com.example.demo.dao;
import com.example.demo.entity.SysPermission;
import com.example.demo.mapper.IMapper;
public interface SysPermissionMapper extends IMapper<SysPermission> {
} |
package com.hladkevych.menu.service;
import com.hladkevych.menu.dto.DietDTO;
import com.hladkevych.menu.dto.JsonDietParser;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* Created by ggladko97 on 04.02.18.
*/
public class DietServiceImpl {
public List<DietDTO> listDiets() {
List<DietDTO> dietDTO = null;
try {
dietDTO = JsonDietParser.parseFromJson(new File(this.getClass().getClassLoader().getResource("diets_desc.json").getFile()));
} catch (IOException e) {
System.out.println("IOE while reading JSON\n" + e);
}
return dietDTO;
}
}
|
package com.example.sqllite_example;
public final class ContactContract {
private ContactContract(){ }
public static class ContactEntry
{
public static final String TABLE_NAME = "contact_info";
public static final String CONTACT_ID="contact_id";
public static final String NAME = "name";
public static final String EMAIL = "email";
}
}
|
package com.etech.testproject.ui.activity.Notification;
import android.os.Bundle;
import android.view.View;
import androidx.databinding.DataBindingUtil;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.etech.testproject.R;
import com.etech.testproject.data.model.Lecture;
import com.etech.testproject.databinding.ActivityNotificationBinding;
import com.etech.testproject.ui.adapter.NotificationAdapter;
import com.etech.testproject.ui.base.BaseActivity;
import com.etech.testproject.ui.callback.OnRecyclerViewItemClickListener;
import com.etech.testproject.utils.ViewUtils;
import java.util.ArrayList;
public class NotificationActivity extends BaseActivity implements NotificationContract.View {
private NotificationAdapter dashboardAdapter;
private ActivityNotificationBinding binding;
private NotificationContract.Presenter<NotificationContract.View> presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_notification);
presenter = new NotificationPresenter<>();
presenter.onAttach(this);
setUpView(binding.header.mainToolbar, binding.extraViews, "menu", true);
presenter.init();
binding.swRefDashboard.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
presenter.reset();
}
});
}
@Override
public void onRetryClicked() {
presenter.reset();
}
@Override
public void setUpView(boolean isReset) {
if (isReset) {
dashboardAdapter = null;
}
ViewUtils.setVisibility(binding.tvNotFound, View.GONE);
if (dashboardAdapter == null) {
dashboardAdapter = new NotificationAdapter(this, new OnRecyclerViewItemClickListener() {
@Override
public void onClicked(Object bean, View view, int position, ViewType viewType) {
if (viewType == ViewType.View) {
}
}
@Override
public void onLastItemReached() {
presenter.loadMoreRecords();
}
});
binding.rvDashboard.setAdapter(dashboardAdapter);
// skeletonScreen = AppUtils.bindRecyclerViewForSkeleton(binding.rvMyComplain, dashboardAdapter);
} else {
binding.rvDashboard.setAdapter(dashboardAdapter);
}
}
@Override
public void loadDataToView(ArrayList<Lecture> list) {
dashboardAdapter.addData(list);
hideSkeletonView();
}
private void hideSkeletonView() {
// if (skeletonScreen != null) {
// skeletonScreen.hide();
// skeletonScreen = null;
// }
}
@Override
public void setNotRecordsFoundView(boolean isActive) {
if (isActive) {
ViewUtils.setVisibility(binding.tvNotFound, View.VISIBLE);
} else {
ViewUtils.setVisibility(binding.tvNotFound, View.GONE);
}
}
@Override
public void showProgressBar() {
dashboardAdapter.updateBottomProgress(0);
}
@Override
public void hideProgressBar() {
dashboardAdapter.updateBottomProgress(1);
binding.swRefDashboard.setRefreshing(false);
hideSkeletonView();
}
@Override
public void onDestroy() {
presenter.onDetach();
super.onDestroy();
}
}
|
/*
* This class is auto generated by https://github.com/hauner/openapi-processor-spring.
* DO NOT EDIT.
*/
package generated.model;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Props {
@JsonProperty("prop1")
private String prop1;
@JsonProperty("prop2")
private String prop2;
public String getProp1() {
return prop1;
}
public void setProp1(String prop1) {
this.prop1 = prop1;
}
public String getProp2() {
return prop2;
}
public void setProp2(String prop2) {
this.prop2 = prop2;
}
}
|
package com.tencent.mm.protocal;
public class c$fg extends c$g {
public c$fg() {
super("openProductView", "open_product_view", 59, true);
}
}
|
package com.tencent.mm.g.a;
public final class mi$b {
public boolean bXc = false;
public String bXd;
public String bXe;
public String bXf;
public String bXg;
public String bXh;
public String bXi;
public String bXj;
public int errCode = 0;
public String userName;
}
|
package jdk8;
import java.util.Arrays;
import java.util.Comparator;
/**
* @author yinchao
* @date 2020/9/24 13:45
*/
class Solution {
public int scheduleCourse(int[][] courses) {
int time = 0;
int num = 0;
Arrays.sort(courses, Comparator.comparingInt(o->o[1]-o[0]));
Arrays.sort(courses,Comparator.comparingInt(o->o[1]-o[0]).thenComparingInt(o->o[0]));
for(int i=0;i<courses.length;i++){
System.out.println(courses[i][0]+" "+courses[i][1]);
if(time+courses[i][0]<courses[i][1]){
time += courses[i][0];
num++;
}
}
return num;
}
}
public class Test {
public static void main (String[] args) {
}
}
|
package org.milvus.util;
import java.util.List;
/**
* TODO: remove. No longer used.
*/
public interface SortedList<T extends Comparable<T>> extends List<T>{
int insert(T element);
}
|
package customer.gajamove.com.gajamove_customer.models;
import java.util.ArrayList;
/**
* Created by PC-GetRanked on 9/4/2018.
*/
public class Ride extends BaseModel {
public Ride() {
}
private String order_id="",pickup_loc,destination_loc;
private RideStatus rideStatus;
private Member memberLocationObject;
private boolean isMulti, hasMember= false;
private ArrayList<Prediction> predictionArrayList;
public RideStatus getRideStatus() {
return rideStatus;
}
public void setRideStatus(RideStatus rideStatus) {
this.rideStatus = rideStatus;
}
public String getPickup_loc() {
return pickup_loc;
}
public void setPickup_loc(String pickup_loc) {
this.pickup_loc = pickup_loc;
}
public String getDestination_loc() {
return destination_loc;
}
public void setDestination_loc(String destination_loc) {
this.destination_loc = destination_loc;
}
private LatLong meet_location,drop_location;
public LatLong getMeet_location() {
return meet_location;
}
public void setMeet_location(LatLong meet_location) {
this.meet_location = meet_location;
}
public LatLong getDrop_location() {
return drop_location;
}
public void setDrop_location(LatLong drop_location) {
this.drop_location = drop_location;
}
public boolean isMulti() {
return isMulti;
}
public void setMulti(boolean multi) {
isMulti = multi;
}
public ArrayList<Prediction> getPredictionArrayList() {
return predictionArrayList;
}
public void setPredictionArrayList(ArrayList<Prediction> predictionArrayList) {
this.predictionArrayList = predictionArrayList;
}
public Member getMemberLocationObject() {
return memberLocationObject;
}
public void setMemberLocationObject(Member memberLocationObject) {
this.memberLocationObject = memberLocationObject;
}
public boolean isHasMember() {
return hasMember;
}
public void setHasMember(boolean hasMember) {
this.hasMember = hasMember;
}
public String getOrder_id() {
return order_id;
}
public void setOrder_id(String order_id) {
this.order_id = order_id;
}
}
|
package com.drzewo97.ballotbox.panel.controller.election; |
class MyQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
// Time complexity: O(1)
public void enqueue(E item) {
list.addLast(item);
}
// Time complexity: O(1)
public E dequeue() {
return list.poll();
}
public E peek() {
return list.get(0);
}
public int size() {
return list.size();
}
}
public class MyStack<E> {
private MyQueue<E> inqueue = new MyQueue<E>();
private MyQueue<E> bkpqueue = new MyQueue<E>();
// Time complexity: O(n)
public void push(E item) {
if(inqueue.size()==0) {
inqueue.enqueue(item);
} else {
while(inqueue.size()>0) {
bkpqueue.enqueue(inqueue.dequeue());
}
inqueue.enqueue(item);
while(bkpqueue.size()>0) {
inqueue.inqueue(bkpqueque.dequeue());
}
}
}
// Time complexity: O(1)
public E pop() {
return inqueue.dequeque();
}
public E peek(){
return inqueue.peek();
}
public boolean empty(){
return inqueue.size()==0;
}
}
|
/**
*
* @author Derfel Terciano
* @version 1
*/
public abstract class ThreeDShape {
private double volume;
private double surfaceArea;
public ThreeDShape() {
//TODO ask why this constructor doesn't work
volume = calcVolume();
surfaceArea = calcSA();
}
// Can you write this code for this class or does it need to be overridden by
// every subclass?
public abstract double calcVolume();
// Can you write this code for this class or does it need to be overridden by
// every subclass?
public abstract double calcSA();
public double getVolume() {
volume = calcVolume();
return round2(volume);
}
public double getSA() {
surfaceArea = calcSA();
return round2(surfaceArea);
}
public double round2(double num) {
double x = (num - num % 0.001) * 1000;
if (x % 10 >= 5) {
x += 10;
return (x - x % 10) / 1000;
} else {
return (x - x % 10) / 1000;
}
}
}
|
package com.tencent.mm.plugin.wallet_core.ui;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.wallet_core.model.Bankcard;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.wallet_core.a;
class WalletVerifyCodeUI$9 implements OnClickListener {
final /* synthetic */ Bankcard oZt;
final /* synthetic */ WalletVerifyCodeUI pyT;
WalletVerifyCodeUI$9(WalletVerifyCodeUI walletVerifyCodeUI, Bankcard bankcard) {
this.pyT = walletVerifyCodeUI;
this.oZt = bankcard;
}
public final void onClick(View view) {
boolean z = false;
x.i("MicroMsg.WalletVertifyCodeUI", "hy: user clicked on the reset info tv and is balance. ");
x.i("MicroMsg.WalletVertifyCodeUI", "forwardProcess3 and finish!");
if (WalletVerifyCodeUI.d(this.pyT) != null && WalletVerifyCodeUI.d(this.pyT).bOB()) {
h.mEJ.h(13731, new Object[]{Integer.valueOf(9)});
}
Bundle bundle = this.pyT.sy;
bundle.putInt("key_err_code", 417);
bundle.putBoolean("key_need_show_switch_phone", true);
String str = "key_isbalance";
if (this.oZt == null || this.oZt.bOs()) {
z = true;
}
bundle.putBoolean(str, z);
a.j(this.pyT, bundle);
this.pyT.finish();
}
}
|
package com.shopify.admin.statis;
import java.sql.Date;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class AdminStatisMakeData {
private String crontab;
private String nowDate;
private String masterCode;
private String courierCompany;
private String courier;
private int payment;
private String volumeWeight; // 부피무게 (g) 단위
private String weight; // 부피무게(화면입력) (kg) 단위
private Date paymentDate;
private int addFeesPrice;
private int addSalePrice;
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.eutil;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.impl.XMLResourceFactoryImpl;
import edu.tsinghua.lumaqq.ecore.global.GlobalFactory;
import edu.tsinghua.lumaqq.ecore.global.GlobalPackage;
import edu.tsinghua.lumaqq.ecore.global.GlobalSetting;
import edu.tsinghua.lumaqq.ecore.global.LanguageType;
import edu.tsinghua.lumaqq.ecore.global.Robot;
import edu.tsinghua.lumaqq.ecore.global.Robots;
import edu.tsinghua.lumaqq.ecore.global.Servers;
/**
* Global配置文件工具类
*
* @author luma
*/
public class GlobalUtil {
/**
* 保存全局配置文件
*
* @param file
* 文件路径
* @param gs
* 文件根元素对象
* @throws IOException
* 如果保存出错
*/
@SuppressWarnings("unchecked")
public static final void save(File file, GlobalSetting gs) {
// Create a resource set.
ResourceSet resourceSet = new ResourceSetImpl();
// Register the default resource factory -- only needed for stand-alone!
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMLResourceFactoryImpl() {
@Override
public Resource createResource(URI uri) {
XMLResource xmlResource = (XMLResource) super.createResource(uri);
return xmlResource;
}
});
resourceSet.getPackageRegistry().put(GlobalPackage.eINSTANCE.getNsURI(), GlobalPackage.eINSTANCE);
// Get the URI of the model file.
URI fileURI = URI.createFileURI(file.getAbsolutePath());
// Create a resource for this file.
Resource resource = resourceSet.createResource(fileURI);
// add the globalsetting to the resoource
resource.getContents().add(gs);
// Save the contents of the resource to the file system.
Map options = new HashMap();
options.put(XMLResource.OPTION_ENCODING, "UTF-8");
try {
resource.save(options);
} catch (IOException e) {
}
}
/**
* 载入全局配置文件
*
* @param file
* 文件路径
* @return
* 根元素对象
*/
@SuppressWarnings("unchecked")
public static final GlobalSetting load(File file) {
// Create a resource set.
ResourceSet resourceSet = new ResourceSetImpl();
// Register the default resource factory -- only needed for stand-alone!
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMLResourceFactoryImpl() {
@Override
public Resource createResource(URI uri) {
XMLResource xmlResource = (XMLResource) super.createResource(uri);
return xmlResource;
}
});
resourceSet.getPackageRegistry().put(GlobalPackage.eINSTANCE.getNsURI(), GlobalPackage.eINSTANCE);
// Get the URI of the model file.
URI fileURI = URI.createFileURI(file.getAbsolutePath());
// Create a resource for this file.
Resource resource = resourceSet.createResource(fileURI);
// Save the contents of the resource to the file system.
Map options = new HashMap();
options.put(XMLResource.OPTION_ENCODING, "UTF-8");
try {
resource.load(options);
if(resource.getContents().isEmpty())
return null;
else
return (GlobalSetting) resource.getContents().get(0);
} catch (IOException e) {
return null;
}
}
/**
* @return
* 缺省的全局配置根元素对象
*/
@SuppressWarnings("unchecked")
public static final GlobalSetting createDefault() {
GlobalSetting gs = GlobalFactory.eINSTANCE.createGlobalSetting();
gs.setLanguage(LanguageType.ZH_LITERAL);
Servers servers = GlobalFactory.eINSTANCE.createServers();
String[] tcpServers = new String[] {
"tcpconn.tencent.com",
"tcpconn2.tencent.com",
"tcpconn3.tencent.com",
"tcpconn4.tencent.com",
"219.133.38.5",
"218.17.209.23"
};
String[] udpServers = new String[] {
"sz.tencent.com",
"sz2.tencent.com",
"sz3.tencent.com",
"sz4.tencent.com",
"sz5.tencent.com",
"sz6.tencent.com",
"sz7.tencent.com",
"61.144.238.155",
"61.144.238.156",
"202.96.170.163",
"202.96.170.164",
"219.133.38.129",
"219.133.38.130",
"219.133.38.43",
"219.133.38.44",
"219.133.40.215",
"219.133.40.216",
"219.133.48.100"
};
for(String s : tcpServers)
servers.getTCPServer().add(s);
for(String s : udpServers)
servers.getUDPServer().add(s);
gs.setServers(servers);
Robots robots = GlobalFactory.eINSTANCE.createRobots();
Robot robot = GlobalFactory.eINSTANCE.createRobot();
robot.setName("Dummy Robot");
robot.setClass("edu.tsinghua.lumaqq.qq.robot.DummyRobot");
robots.getRobot().add(robot);
gs.setRobots(robots);
return gs;
}
}
|
package paxos2;
import pro.eddiecache.CacheKit;
import pro.eddiecache.access.CacheKitAccess;
public class Paxos2Test
{
public static void main(String[] args) throws InterruptedException
{
CacheKit.setConfigFilename("/paxos2/cachekit.xml");
CacheKitAccess cacheKitAccess = CacheKit.getInstance("default");
//main线程休眠,等待服务发现和注册的完成
Thread.sleep(10000);
// 测试节点的数据读取
System.out.println("缓存对象" + cacheKitAccess.get("id0"));
Thread.sleep(30000);
}
}
|
/*
* 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 PackageJavaFX;
/**
*
* @author LABORATORIO_INFO
*/
public class TestaAutenticacao {
public static void main(String[] args) {
Usuario testee = new Usuario("dfsada", "dsafsadf");
//teste.setNome("Mia Khalifa");
//teste.setSenha("IAmVeryHappy");
System.out.println(testee.getNome() + "\n" + testee.getSenha());
}
}
|
import java.awt.Color;
import biuoop.DrawSurface;
/**
* Created by user on 12/05/2017.
*/
public class GameLevel implements Animation {
private SpriteCollection sprites = new SpriteCollection();
private GameEnvironment environment = new GameEnvironment();
private biuoop.KeyboardSensor keyboard;
private Counter remainingBlocks;
private Counter remainingBalls;
private Counter score;
private Counter lifes;
private AnimationRunner runner;
private LevelInformation li;
/**
* construct a GameLevel with runner, score, lifes, li and keyboard.
* @param runner the AnimationRunner to run the animation.
* @param score the score counter of the game.
* @param lifes the lives counter of the game.
* @param li LevelInformation, the relevant information of the current level.
* @param keyboard KeyboardSensor.
*/
public GameLevel(AnimationRunner runner, Counter score,
Counter lifes, LevelInformation li,
biuoop.KeyboardSensor keyboard) {
this.runner = runner;
this.li = li;
this.keyboard = keyboard;
this.remainingBlocks = new Counter(this.li.numberOfBlocksToRemove());
this.remainingBalls = new Counter(0);
this.score = runner.getScore();
this.lifes = lifes;
}
/**
* adding collidables to game environment's list.
* @param c a collidable to add to game environment.
*/
public void addCollidable(Collidable c) {
this.environment.addCollidable(c);
}
/**
*adding sprite to sprite collection's list.
* @param s a sprite to add to sprite collection.
*/
public void addSprite(Sprite s) {
this.sprites.addSprite(s);
}
/**
*initializing the game's set ups.
*/
public void initialize() {
Point p1 = new Point(0, 2);
Point p2 = new Point(798, 2);
Point p3 = new Point(-100, 620);
Point p4 = new Point(0, 2);
Rectangle rectangle1 = new Rectangle(p1, 800, 20);
Rectangle rectangle2 = new Rectangle(p2, 2, 600);
Rectangle rectangle3 = new Rectangle(p3, 1000, 10);
Rectangle rectangle4 = new Rectangle(p4, 2, 600);
Block block1 = new Block(rectangle1);
Block block2 = new Block(rectangle2);
Block deathRegion = new Block(rectangle3);
Block block4 = new Block(rectangle4);
this.li.getBackground().addToGame(this);
block1.addToGame(this);
block2.addToGame(this);
block4.addToGame(this);
deathRegion.addToGame(this);
HitListener hitListener = new BallRemover(this, this.remainingBalls);
HitListener hl = new BlockRemover(this, this.remainingBlocks);
HitListener hls = new ScoreTrackingListener(this.score);
deathRegion.addHitListener(hitListener);
for (Block i: this.li.blocks()) {
i.addToGame(this);
i.addHitListener(hls);
i.addHitListener(hl);
}
}
/**
* running one turn of the game.
*/
public void playOneTurn() {
for (int i = 0; i < this.li.numberOfBalls(); i++) {
addBallToGame(this.li.initialBallVelocities().get(i), this.remainingBalls);
}
this.runner.run(new CountdownAnimation(2, 3, this.sprites));
this.runner.run(this);
if (this.remainingBlocks.getValue() <= 0) {
this.score.increase(100);
}
if (this.remainingBlocks.getValue() > 0) {
this.lifes.decrease(1);
}
}
/**
*removes a Collidable from the game.
* @param c the Collidable.
*/
public void removeCollidable(Collidable c) {
for (int i = 0; i < this.environment.getList().size(); i++) {
if (c == this.environment.getList().get(i)) {
this.environment.getList().remove(i);
}
}
}
/**
*removes a Sprite from the game.
* @param s the Sprite.
*/
public void removeSprite(Sprite s) {
for (int i = 0; i < this.sprites.getList().size(); i++) {
if (s == this.sprites.getList().get(i)) {
this.sprites.getList().remove(i);
}
}
}
/**
*adding new balls to the game.
* @param v the ball's velocity.
* @param remainingBall the ball counter, in order update the counter when adding a new ball.
*/
public void addBallToGame(Velocity v, Counter remainingBall) {
Ball ball = new Ball(400, 560, 5, Color.white, this.environment);
ball.setVelocity(v);
ball.addToGame(this);
this.remainingBalls.increase(1);
}
/**
* the stopping condition of this animation.
* @return true or false.
*/
public boolean shouldStop() {
if (this.remainingBlocks.getValue() != 0
&& this.remainingBalls.getValue() != 0) {
return true;
}
return false;
}
/**
* drawing one frame of the GameLevel animation.
* @param d the surface that we draw on.
* @param dt dt.
*/
public void doOneFrame(DrawSurface d, double dt) {
d.setColor(Color.black);
d.fillRectangle(0, 0, d.getWidth(), d.getHeight());
this.sprites.drawAllOn(d);
this.sprites.notifyAllTimePassed(dt);
if (this.keyboard.isPressed("p")) {
this.runner.run(new KeyPressStoppableAnimation(keyboard,
"space", new PauseScreen(this.keyboard,
this.sprites)));
}
}
/**
* returns RemainingBlocks.
* @return RemainingBlocks.
*/
public Counter getRemainingBlocks() {
return this.remainingBlocks;
}
/**
* returns Li.
* @return Li.
*/
public LevelInformation getLi() {
return this.li;
}
/**
* returns sprites.
* @return sprites.
*/
public SpriteCollection getSprites() {
return this.sprites;
}
/**
*
*/
public void reset() {
}
}
|
package com.cloudera.CachingTest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
private final int StressAmount = 1000;
private final String password = "unittest";
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
public void testRedis() throws NoSuchAlgorithmException, UnsupportedEncodingException {
CacheService storage = new RedisCache();
CachedObject testobj = new Person("Ricky", "Saltzer", 24, "rickysaltzer@gmail.com");
testobj.setPassword(password);
storage.put(testobj);
CachedObject newobj = storage.get("rickysaltzer@gmail.com");
assertEquals(testobj.getKey(), newobj.getKey());
assertTrue(testobj.checkPassword(password));
}
public void testMemached() throws NoSuchAlgorithmException, IOException {
CacheService storage = new MemCache();
CachedObject testobj = new Person("Ricky", "Saltzer", 24, "rickysaltzer@gmail.com");
testobj.setPassword(password);
storage.put(testobj);
CachedObject newobj = storage.get("rickysaltzer@gmail.com");
assertEquals(testobj.getKey(), newobj.getKey());
assertTrue(testobj.checkPassword(password));
}
private void stressTest(CacheService storage, int amount) throws NoSuchAlgorithmException, UnsupportedEncodingException {
for (int i = 0; i <= amount; i++) {
Person tester = new Person("john", "doe", 24, "johnny" + Integer.toString(i) + "@gmail.com");
tester.setPassword(password);
assertTrue(storage.put(tester));
}
for (int i = 0; i <= amount; i++) {
CachedObject person = storage.get("johnny" + Integer.toString(i) + "@gmail.com");
assertEquals(person.getEmail(), "johnny" + Integer.toString(i) + "@gmail.com");
assertTrue(person.checkPassword(password));
}
}
public void testStressMemached() throws NoSuchAlgorithmException, IOException {
CacheService memcached = new MemCache();
stressTest(memcached, StressAmount);
}
public void testStressRedis() throws NoSuchAlgorithmException, UnsupportedEncodingException {
CacheService redis = new RedisCache();
stressTest(redis, StressAmount);
}
public void testStressHashMap() throws NoSuchAlgorithmException, UnsupportedEncodingException {
CacheService hashmap = new HashCache(10000);
stressTest(hashmap, StressAmount);
}
public void testStressHTable() throws NoSuchAlgorithmException, UnsupportedEncodingException {
CacheService hashmap = new HashTableCache(10000);
stressTest(hashmap, StressAmount);
}
}
|
package com.timmy.other;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.timmy.R;
import com.timmy.advance.animation.AnimationActivity;
import com.timmy.base.BaseActivity;
import com.timmy.highUI.dialog.DialogActivity;
import com.timmy.technologypoint.AutoPlayPicturesActivity;
import com.timmy.technologypoint.CameraPictureActivity;
import com.timmy.technologypoint.ClipToOutlineActivity;
import com.timmy.technologypoint.GlideImageActivity;
import com.timmy.technologypoint.Picture9Activity;
import com.timmy.technologypoint.RecycleHeaderViewActivity;
import com.timmy.technologypoint.TimmyHealthActivity;
import com.timmy.technologypoint.ToolBarActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by Administrator on 2016/3/23.
* 测试提交
*/
public class TechnologyPointActivity extends BaseActivity {
// @Bind(R.id.toolbar)
// Toolbar toolbar;
@BindView(R.id.btn_auto_images)
Button btn_autoImg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_technology_point);
ButterKnife.bind(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// initToolBar();
}
@OnClick({R.id.btn_auto_images, R.id.btn_camera_picture,
R.id.btn_animation, R.id.btn_glide, R.id.btn_clip,
R.id.btn_dialog, R.id.btn_view, R.id.btn_recycleview,
R.id.btn_toolbar,R.id.btn_coordi,R.id.btn_9pic})
public void technology(View v) {
switch (v.getId()) {
case R.id.btn_auto_images:
openActivity(AutoPlayPicturesActivity.class);
break;
case R.id.btn_camera_picture:
openActivity(CameraPictureActivity.class);
break;
case R.id.btn_animation:
openActivity(AnimationActivity.class);
break;
case R.id.btn_glide:
openActivity(GlideImageActivity.class);
break;
case R.id.btn_clip:
openActivity(ClipToOutlineActivity.class);
break;
case R.id.btn_dialog:
openActivity(DialogActivity.class);
break;
case R.id.btn_view:
openActivity(TimmyHealthActivity.class);
break;
case R.id.btn_recycleview:
openActivity(RecycleHeaderViewActivity.class);
break;
case R.id.btn_toolbar:
openActivity(ToolBarActivity.class);
break;
case R.id.btn_coordi:
break;
case R.id.btn_9pic:
openActivity(Picture9Activity.class);
break;
default:
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
|
package OOPS;
public class Blocks {
static {
System.out.println("Static block is executed");
}
{
System.out.println("non static block is executed ");
}
public Blocks() {
System.out.println("Constructor is executed");
}
{
System.out.println("non static block is validated ");
}
public void m1() {
System.out.println("m1 is started");
}
public static void main(String[] args) {
Blocks obj = new Blocks();
//obj.m1();
}
}
|
public class AdvancedParticleSystems extends BaseGameActivity {
//====================================================
// CONSTANTS
//====================================================
public static final int WIDTH = 800;
public static final int HEIGHT = 480;
public static final float HEIGHT_OFFSET = (HEIGHT - 50) / 9;
//====================================================
// VARIABLES
//====================================================
private Scene mScene;
private Camera mCamera;
// Particle texture region
private ITextureRegion mParticleTextureRegion;
// Modifier x coordinates
private final float pointsX[] = {
WIDTH / 2 - 90, // x1
WIDTH / 2 + 90, // x2
WIDTH / 2 - 180, // x3
WIDTH / 2 + 180, // x4
WIDTH / 2 - 40, // x5
WIDTH / 2 + 40, // x6
WIDTH / 2 - 100, // x7
WIDTH / 2 + 100 // x8
};
// Modifier y coordinates
private final float pointsY[] = {
HEIGHT - (HEIGHT_OFFSET * 2), // y1
HEIGHT - (HEIGHT_OFFSET * 3), // y2
HEIGHT - (HEIGHT_OFFSET * 4), // y3
HEIGHT - (HEIGHT_OFFSET * 5), // y4
HEIGHT - (HEIGHT_OFFSET * 6), // y5
HEIGHT - (HEIGHT_OFFSET * 7), // y6
HEIGHT - (HEIGHT_OFFSET * 8), // y7
HEIGHT - (HEIGHT_OFFSET * 9), // y8
};
// Create the cardinal spline modifier config
final CardinalSplineMoveModifierConfig mConfig = new CardinalSplineMoveModifierConfig(pointsX.length, 0);
//====================================================
// CREATE ENGINE OPTIONS
//====================================================
@Override
public EngineOptions onCreateEngineOptions() {
mCamera = new Camera(0, 0, WIDTH, HEIGHT);
EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR, new FillResolutionPolicy(), mCamera);
return engineOptions;
}
//====================================================
// CREATE RESOURCES
//====================================================
@Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback) {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
BuildableBitmapTextureAtlas texture = new BuildableBitmapTextureAtlas(
mEngine.getTextureManager(), 66, 66, TextureOptions.NEAREST);
// 64x64 particle image
mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(texture, getAssets(), "particle.png");
try {
texture.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 1));
} catch (TextureAtlasBuilderException e) {
e.printStackTrace();
}
texture.load();
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
//====================================================
// CREATE SCENE
//====================================================
@Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) {
mScene = new Scene();
pOnCreateSceneCallback.onCreateSceneFinished(mScene);
}
//====================================================
// POPULATE SCENE
//====================================================
@Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback) {
// Apply the float array coordinates to the modifier config
for (int i = 0; i < pointsX.length; i++) {
mConfig.setControlPoint(i, pointsX[i], pointsY[i]);
}
// Create the particle emitter (bottom/center of the screen)
PointParticleEmitter particleEmitter = new PointParticleEmitter(WIDTH / 2, HEIGHT);
// Create a batched particle system for efficiency
BatchedSpriteParticleSystem particleSystem = new BatchedSpriteParticleSystem(
particleEmitter, 1, 2, 20, mParticleTextureRegion,
mEngine.getVertexBufferObjectManager());
// Initialize the sprite's color (random)
particleSystem.addParticleInitializer(new ColorParticleInitializer<UncoloredSprite>(0, 1, 0, 1, 0, 1));
// Add the expire modifier (particles expire after 10 seconds)
particleSystem.addParticleInitializer(new ExpireParticleInitializer<UncoloredSprite>(10));
// Add 4 sequential scale modifiers
particleSystem.addParticleModifier(new ScaleParticleModifier<UncoloredSprite>(
1, 2, 1.3f, 0.4f));
particleSystem.addParticleModifier(new ScaleParticleModifier<UncoloredSprite>(
3, 4, 0.4f, 1.3f));
particleSystem.addParticleModifier(new ScaleParticleModifier<UncoloredSprite>(
5, 6, 1.3f, .4f));
particleSystem.addParticleModifier(new ScaleParticleModifier<UncoloredSprite>(
7, 9, 0.4f, 1.3f));
// Add alpha ('fade out') modifier
particleSystem.addParticleModifier(new AlphaParticleModifier<UncoloredSprite>(
9, 10, 1, 0));
// Create a custom particle modifier via the Particle Modifier interface
particleSystem.addParticleModifier(new IParticleModifier<UncoloredSprite>() {
// temporary particle color values
float red;
float green;
float blue;
// color check booleans
boolean incrementRed = true;
boolean incrementGreen = true;
boolean incrementBlue = true;
// Called when a particle is created
@Override
public void onInitializeParticle(Particle<UncoloredSprite> pParticle) {
// Create our movement modifier
CardinalSplineMoveModifier moveModifier = new CardinalSplineMoveModifier(10, mConfig);
// Register our modifier to each individual particle
pParticle.getEntity().registerEntityModifier(moveModifier);
}
// Called when a particle is updated (every frame)
@Override
public void onUpdateParticle(Particle<UncoloredSprite> pParticle) {
// Get the particle's sprite/entity
UncoloredSprite sprite = pParticle.getEntity();
// Get the particle's current color values
red = sprite.getRed();
green = sprite.getGreen();
blue = sprite.getBlue();
// Red reversion checks
if (red >= 0.75f)
incrementRed = false;
else if (red <= 0.3f)
incrementRed = true;
// Green reversion checks
if (green >= 0.75f)
incrementGreen = false;
else if (green <= 0.3f)
incrementGreen = true;
// Blue reversion checks
if (blue >= 0.75f)
incrementBlue = false;
else if (blue <= 0.3f)
incrementBlue = true;
// Inc/dec red value
if (incrementRed)
red += 0.075f;
else
red -= 0.075f;
// Inc/dec green value
if (incrementGreen)
green += 0.075f;
else
green -= 0.075f;
// Inc/dec blue value
if (incrementBlue)
blue += 0.075f;
else
blue -= 0.075f;
// Set the new color values for the particle's sprite
sprite.setColor(red, green, blue);
}
});
// Attach our particle system to the scene
mScene.attachChild(particleSystem);
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.