text stringlengths 10 2.72M |
|---|
package orm.integ.eao;
import java.util.ArrayList;
import java.util.List;
import orm.integ.dao.DataAccessObject;
import orm.integ.dao.annotation.KeyTypes;
import orm.integ.dao.annotation.Table;
import orm.integ.eao.model.Entity;
import orm.integ.eao.model.EntityModel;
import orm.integ.eao.transaction.DataChangeListener;
import orm.integ.eao.transaction.TransactionManager;
import orm.integ.utils.IdGenerator;
public abstract class EntityAccessService<T extends Entity> extends EaoAdapter<T> {
protected EntityAccessObject<T> eao;
protected DataAccessObject dao;
protected EntityModel em;
protected final List<DataChangeListener> dataChangeListeners = new ArrayList<>();
public EntityAccessService() {
eao = new EntityAccessObject<T>(this);
dao = this.getDao();
this.em = eao.getEntityModel();
if (this instanceof DataChangeListener) {
dataChangeListeners.add((DataChangeListener) this);
}
}
public EntityAccessObject<T> getEao() {
return eao;
}
public EntityModel getEntityModel() {
return em;
}
public Object createNewId() {
Table tab = em.getTable();
int idType = tab.keyType();
if (idType==KeyTypes.INT_INCREASE) {
return dao.getNextIntId(em.getFullTableName(), em.getKeyColumn());
}
else {
String id = IdGenerator.createRandomStr(tab.keyLength(), false);
if (!tab.keyPrefix().equals("")) {
id = tab.keyPrefix()+id;
}
return id;
}
}
public void executeTransaction(String methodName, Object...values) {
TransactionManager.executeTransaction(this, methodName, values);
}
}
|
package pop3;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.SerializationUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Mailbox {
private static final String RESOURCE_PATH = "D:\\6sem\\POP3SERVER\\src\\main\\resources";
private static final String INVALID_MESSAGE_INDEX_EXCEPTION = "Invalid message index %d was received. There is no messages with such index";
private List<Message> messages;
private Set<Integer> markedMessages;
private boolean isLocked;
public Mailbox() {
messages = new ArrayList<>();
markedMessages = new LinkedHashSet<>();
}
public void loadFromFile(String fileName) throws IOException {
messages = MailParser.parseMail(fileName);
}
public void saveToFile(String fileName) {
MailParser.saveToFile(messages, fileName);
}
public void markMessageToDelete(int msgIndex) {
if (isValidIndex(msgIndex)) {
markedMessages.add(msgIndex);
}
}
public void unmarkMessageToDelete(int msgIndex) {
if (isValidIndex(msgIndex)) {
markedMessages.remove(msgIndex);
}
}
public boolean deleteMarkedMessages() {
for (Integer msgIndex : markedMessages) {
messages.remove(msgIndex - 1);
}
markedMessages.clear();
return true;
}
public Set<Integer> getMarkedMessages() {
return markedMessages;
}
public Message getMessage(int msgIndex) {
if (isValidIndex(msgIndex)) {
return messages.get(msgIndex - 1);
} else {
throw new IllegalArgumentException(String.format(INVALID_MESSAGE_INDEX_EXCEPTION, msgIndex));
}
}
public int getMessageSize(int msgIndex) {
if (isValidIndex(msgIndex)) {
return SerializationUtils.serialize(messages.get(msgIndex - 1)).length;
} else {
return 0;
}
}
public int getMessageCount() {
return messages.size();
}
public int getMailSize() {
int size = 0;
for (int msgIndex = 1; msgIndex <= messages.size(); ++msgIndex) {
size += getMessageSize(msgIndex);
}
return size;
}
public boolean isValidIndex(int msgIndex) {
return msgIndex > 0 && msgIndex <= messages.size();
}
public boolean isMessageMarked(int msgIndex) {
return markedMessages.contains(msgIndex);
}
public boolean isLocked() {
return isLocked;
}
public void lock() {
isLocked = true;
}
public void unlock() {
isLocked = false;
}
public static class MailParser {
public static List<Message> parseMail(String fileName) throws IOException {
String lines =
new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + fileName)));
Gson gson = new Gson();
Type type = new TypeToken<List<Message>>() {
}.getType();
return gson.fromJson(lines, type);
}
public static void saveToFile(List<Message> messages, String fileName) {
Gson gson = new Gson();
String json = gson.toJson(messages);
try {
Files.write(Paths.get(RESOURCE_PATH + fileName), json.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* 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 und
*/
package org.wso2.carbon.identity.recovery.handler;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.identity.application.common.model.User;
import org.wso2.carbon.identity.base.IdentityRuntimeException;
import org.wso2.carbon.identity.core.bean.context.MessageContext;
import org.wso2.carbon.identity.core.handler.InitConfig;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.event.IdentityEventConstants;
import org.wso2.carbon.identity.event.IdentityEventException;
import org.wso2.carbon.identity.event.event.Event;
import org.wso2.carbon.identity.event.handler.AbstractEventHandler;
import org.wso2.carbon.identity.governance.IdentityGovernanceUtil;
import org.wso2.carbon.identity.governance.IdentityMgtConstants;
import org.wso2.carbon.identity.governance.exceptions.notiification.NotificationChannelManagerClientException;
import org.wso2.carbon.identity.governance.exceptions.notiification.NotificationChannelManagerException;
import org.wso2.carbon.identity.governance.service.notification.NotificationChannelManager;
import org.wso2.carbon.identity.governance.service.notification.NotificationChannels;
import org.wso2.carbon.identity.recovery.IdentityRecoveryClientException;
import org.wso2.carbon.identity.recovery.IdentityRecoveryConstants;
import org.wso2.carbon.identity.recovery.IdentityRecoveryException;
import org.wso2.carbon.identity.recovery.IdentityRecoveryServerException;
import org.wso2.carbon.identity.recovery.RecoveryScenarios;
import org.wso2.carbon.identity.recovery.RecoverySteps;
import org.wso2.carbon.identity.recovery.internal.IdentityRecoveryServiceDataHolder;
import org.wso2.carbon.identity.recovery.model.Property;
import org.wso2.carbon.identity.recovery.model.UserRecoveryData;
import org.wso2.carbon.identity.recovery.store.JDBCRecoveryDataStore;
import org.wso2.carbon.identity.recovery.store.UserRecoveryDataStore;
import org.wso2.carbon.identity.recovery.util.Utils;
import org.wso2.carbon.user.core.UserCoreConstants;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.user.core.UserStoreManager;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserSelfRegistrationHandler extends AbstractEventHandler {
private static final Log log = LogFactory.getLog(UserSelfRegistrationHandler.class);
public String getName() {
return "userSelfRegistration";
}
public String getFriendlyName() {
return "User Self Registration";
}
@Override
public void handleEvent(Event event) throws IdentityEventException {
Map<String, Object> eventProperties = event.getEventProperties();
String userName = (String) eventProperties.get(IdentityEventConstants.EventProperty.USER_NAME);
UserStoreManager userStoreManager = (UserStoreManager) eventProperties.get(IdentityEventConstants.EventProperty.USER_STORE_MANAGER);
String tenantDomain = (String) eventProperties.get(IdentityEventConstants.EventProperty.TENANT_DOMAIN);
String domainName = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
String[] roleList = (String[]) eventProperties.get(IdentityEventConstants.EventProperty.ROLE_LIST);
User user = new User();
user.setUserName(userName);
user.setTenantDomain(tenantDomain);
user.setUserStoreDomain(domainName);
boolean enable = Boolean.parseBoolean(Utils.getConnectorConfig(
IdentityRecoveryConstants.ConnectorConfig.ENABLE_SELF_SIGNUP, user.getTenantDomain()));
if (!enable) {
//Self signup feature is disabled
if (log.isDebugEnabled()) {
log.debug("Self signup feature is disabled in tenant: " + tenantDomain);
}
return;
}
//Check selfSignupRole is in the request. If it is not there, this handler will not do anything. just retrun
if (roleList == null) {
return;
} else {
List<String> roles = Arrays.asList(roleList);
if (!roles.contains(IdentityRecoveryConstants.SELF_SIGNUP_ROLE)) {
return;
}
}
boolean isAccountLockOnCreation = Boolean.parseBoolean(Utils.getConnectorConfig
(IdentityRecoveryConstants.ConnectorConfig.ACCOUNT_LOCK_ON_CREATION, user.getTenantDomain()));
boolean isEnableConfirmationOnCreation = Boolean.parseBoolean(Utils.getConnectorConfig
(IdentityRecoveryConstants.ConnectorConfig.SEND_CONFIRMATION_NOTIFICATION, user.getTenantDomain()));
boolean isNotificationInternallyManage = Boolean.parseBoolean(Utils.getConnectorConfig
(IdentityRecoveryConstants.ConnectorConfig.SIGN_UP_NOTIFICATION_INTERNALLY_MANAGE, user.getTenantDomain()));
if (IdentityEventConstants.Event.POST_ADD_USER.equals(event.getEventName())) {
UserRecoveryDataStore userRecoveryDataStore = JDBCRecoveryDataStore.getInstance();
try {
// Get the user preferred notification channel.
String preferredChannel = resolveNotificationChannel(eventProperties, userName, tenantDomain,
domainName);
// If the preferred channel is already verified, no need to send the notifications or lock
// the account.
boolean notificationChannelVerified = isNotificationChannelVerified(userName, tenantDomain,
preferredChannel, eventProperties);
if (notificationChannelVerified) {
return;
}
boolean isSelfRegistrationConfirmationNotify = Boolean.parseBoolean(Utils.getSignUpConfigs
(IdentityRecoveryConstants.ConnectorConfig.SELF_REGISTRATION_NOTIFY_ACCOUNT_CONFIRMATION, user.getTenantDomain()));
// If notify confirmation is enabled and both iAccountLockOnCreation &&
// EnableConfirmationOnCreation are disabled then send account creation notification.
if (!isAccountLockOnCreation && !isEnableConfirmationOnCreation && isNotificationInternallyManage
&& isSelfRegistrationConfirmationNotify) {
triggerAccountCreationNotification(user);
}
// If notifications are externally managed, no send notifications.
if ((isAccountLockOnCreation || isEnableConfirmationOnCreation) && isNotificationInternallyManage) {
userRecoveryDataStore.invalidate(user);
// Create a secret key based on the preferred notification channel.
String secretKey = Utils.generateSecretKey(preferredChannel, tenantDomain,
RecoveryScenarios.SELF_SIGN_UP.name());
// Resolve event name.
String eventName = resolveEventName(preferredChannel, userName, domainName, tenantDomain);
UserRecoveryData recoveryDataDO = new UserRecoveryData(user, secretKey,
RecoveryScenarios.SELF_SIGN_UP, RecoverySteps.CONFIRM_SIGN_UP);
// Notified channel is stored in remaining setIds for recovery purposes.
recoveryDataDO.setRemainingSetIds(preferredChannel);
userRecoveryDataStore.store(recoveryDataDO);
triggerNotification(user, preferredChannel, secretKey, Utils.getArbitraryProperties(), eventName);
}
} catch (IdentityRecoveryException e) {
throw new IdentityEventException("Error while sending self sign up notification ", e);
}
if (isAccountLockOnCreation || isEnableConfirmationOnCreation) {
HashMap<String, String> userClaims = new HashMap<>();
if (isAccountLockOnCreation) {
// Need to lock user account.
userClaims.put(IdentityRecoveryConstants.ACCOUNT_LOCKED_CLAIM, Boolean.TRUE.toString());
userClaims.put(IdentityRecoveryConstants.ACCOUNT_LOCKED_REASON_CLAIM,
IdentityMgtConstants.LockedReason.PENDING_SELF_REGISTRATION.toString());
}
if (Utils.isAccountStateClaimExisting(tenantDomain)) {
userClaims.put(IdentityRecoveryConstants.ACCOUNT_STATE_CLAIM_URI,
IdentityRecoveryConstants.PENDING_SELF_REGISTRATION);
}
try {
userStoreManager.setUserClaimValues(user.getUserName(), userClaims, null);
if (log.isDebugEnabled()) {
if (isAccountLockOnCreation) {
log.debug("Locked user account: " + user.getUserName());
}
if (isEnableConfirmationOnCreation) {
log.debug("Send verification notification for user account: " + user.getUserName());
}
}
} catch (UserStoreException e) {
throw new IdentityEventException("Error while lock user account :" + user.getUserName(), e);
}
}
}
}
/**
* Resolve the event name according to the notification channel.
*
* @param preferredChannel User preferred notification channel
* @param userName Username
* @param domainName Domain name
* @param tenantDomain Tenant domain name
* @return Resolved event name
*/
private String resolveEventName(String preferredChannel, String userName, String domainName, String tenantDomain) {
String eventName;
if (NotificationChannels.EMAIL_CHANNEL.getChannelType().equals(preferredChannel)) {
eventName = IdentityEventConstants.Event.TRIGGER_NOTIFICATION;
} else {
eventName = IdentityRecoveryConstants.NOTIFICATION_EVENTNAME_PREFIX + preferredChannel
+ IdentityRecoveryConstants.NOTIFICATION_EVENTNAME_SUFFIX;
}
if (log.isDebugEnabled()) {
String message = String
.format("For user : %1$s in domain : %2$s, notifications were sent from the event : %3$s",
domainName + CarbonConstants.DOMAIN_SEPARATOR + userName, tenantDomain, eventName);
log.debug(message);
}
return eventName;
}
/**
* Resolve the preferred notification channel for the user.
*
* @param eventProperties Event properties
* @param userName Username
* @param tenantDomain Tenant domain of the user
* @param domainName Userstore domain name of the user
* @return Resolved preferred notification channel
* @throws IdentityEventException Error while resolving the notification channel
*/
private String resolveNotificationChannel(Map<String, Object> eventProperties, String userName, String tenantDomain,
String domainName) throws IdentityEventException {
// If channel resolving logic is not enabled, return the server default notification channel. Do not need to
// resolve using user preferred channel.
if (!Boolean.parseBoolean(
IdentityUtil.getProperty(IdentityMgtConstants.PropertyConfig.RESOLVE_NOTIFICATION_CHANNELS))) {
return IdentityGovernanceUtil.getDefaultNotificationChannel();
}
// Get the user preferred notification channel.
String preferredChannel = (String) eventProperties.get(IdentityRecoveryConstants.PREFERRED_CHANNEL_CLAIM);
// Resolve preferred notification channel.
if (StringUtils.isEmpty(preferredChannel)) {
NotificationChannelManager notificationChannelManager = Utils.getNotificationChannelManager();
try {
preferredChannel = notificationChannelManager
.resolveCommunicationChannel(userName, tenantDomain, domainName);
} catch (NotificationChannelManagerException e) {
handledNotificationChannelManagerException(e, userName, domainName, tenantDomain);
}
}
if (log.isDebugEnabled()) {
String message = String
.format("Notification channel : %1$s for the user : %2$s in domain : %3$s.",
preferredChannel, domainName + CarbonConstants.DOMAIN_SEPARATOR + userName,
tenantDomain);
log.debug(message);
}
return preferredChannel;
}
/**
* Handles NotificationChannelManagerException thrown in resolving the channel.
*
* @param e NotificationChannelManagerException
* @param userName Username
* @param domainName Domain name
* @param tenantDomain Tenant domain name
* @throws IdentityEventException Error resolving the channel.
*/
private void handledNotificationChannelManagerException(NotificationChannelManagerException e, String userName,
String domainName, String tenantDomain) throws IdentityEventException {
if (StringUtils.isNotEmpty(e.getErrorCode()) && StringUtils.isNotEmpty(e.getMessage())) {
if (IdentityMgtConstants.ErrorMessages.ERROR_CODE_NO_NOTIFICATION_CHANNELS.getCode()
.equals(e.getErrorCode())) {
if (log.isDebugEnabled()) {
String error = String.format("No communication channel for user : %1$s in domain: %2$s",
domainName + CarbonConstants.DOMAIN_SEPARATOR + userName, tenantDomain);
log.debug(error, e);
}
} else {
if (log.isDebugEnabled()) {
String error = String.format("Error getting claim values for user : %1$s in domain: %2$s",
domainName + CarbonConstants.DOMAIN_SEPARATOR + userName, tenantDomain);
log.debug(error, e);
}
}
} else {
if (log.isDebugEnabled()) {
String error = String.format("Error getting claim values for user : %1$s in domain: %2$s",
domainName + CarbonConstants.DOMAIN_SEPARATOR + userName, tenantDomain);
log.debug(error, e);
}
}
throw new IdentityEventException(e.getErrorCode(), e.getMessage());
}
/**
* Checks whether the notification channel is already verified for the user.
*
* @param username Username
* @param tenantDomain Tenant domain
* @param notificationChannel Notification channel
* @param eventProperties Properties related to the event
* @return True if the channel is already verified.
*/
private boolean isNotificationChannelVerified(String username, String tenantDomain, String notificationChannel,
Map<String, Object> eventProperties) throws IdentityRecoveryClientException {
boolean isEnableAccountLockForVerifiedPreferredChannelEnabled = Boolean.parseBoolean(IdentityUtil.getProperty(
IdentityRecoveryConstants.ConnectorConfig.ENABLE_ACCOUNT_LOCK_FOR_VERIFIED_PREFERRED_CHANNEL));
if (!isEnableAccountLockForVerifiedPreferredChannelEnabled) {
if (log.isDebugEnabled()) {
String message = String
.format("SkipAccountLockOnVerifiedPreferredChannel is enabled for user : %s in domain : %s. "
+ "Checking whether the user is already verified", username, tenantDomain);
log.debug(message);
}
// Get the notification channel which matches the given channel type.
NotificationChannels channel = getNotificationChannel(username, notificationChannel);
// Get the matching claim uri for the channel.
String verifiedClaimUri = channel.getVerifiedClaimUrl();
// Get the verified status for given channel.
boolean notificationChannelVerified = Boolean.parseBoolean((String) eventProperties.get(verifiedClaimUri));
if (notificationChannelVerified) {
if (log.isDebugEnabled()) {
String message = String
.format("Preferred Notification channel : %1$s is verified for the user : %2$s "
+ "in domain : %3$s. Therefore, no notifications will be sent.",
notificationChannel, username, tenantDomain);
log.debug(message);
}
}
return notificationChannelVerified;
}
return false;
}
/**
* Get the NotificationChannels object which matches the given channel type.
*
* @param username Username
* @param notificationChannel Notification channel
* @return NotificationChannels object
* @throws IdentityRecoveryClientException Unsupported channel type
*/
private NotificationChannels getNotificationChannel(String username, String notificationChannel)
throws IdentityRecoveryClientException {
NotificationChannels channel;
try {
channel = NotificationChannels.getNotificationChannel(notificationChannel);
} catch (NotificationChannelManagerClientException e) {
if (log.isDebugEnabled()) {
log.debug("Unsupported channel type : " + notificationChannel);
}
throw Utils.handleClientException(
IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNSUPPORTED_PREFERRED_CHANNELS, username, e);
}
return channel;
}
@Override
public void init(InitConfig configuration) throws IdentityRuntimeException {
super.init(configuration);
}
@Override
public int getPriority(MessageContext messageContext) {
return 60;
}
protected void triggerNotification(User user, String type, String code, Property[] props) throws
IdentityRecoveryException {
if (log.isDebugEnabled()) {
log.debug("Sending self user registration notification user: " + user.getUserName());
}
String eventName = IdentityEventConstants.Event.TRIGGER_NOTIFICATION;
HashMap<String, Object> properties = new HashMap<>();
properties.put(IdentityEventConstants.EventProperty.USER_NAME, user.getUserName());
properties.put(IdentityEventConstants.EventProperty.TENANT_DOMAIN, user.getTenantDomain());
properties.put(IdentityEventConstants.EventProperty.USER_STORE_DOMAIN, user.getUserStoreDomain());
if (props != null && props.length > 0) {
for (int i = 0; i < props.length; i++) {
properties.put(props[i].getKey(), props[i].getValue());
}
}
if (StringUtils.isNotBlank(code)) {
properties.put(IdentityRecoveryConstants.CONFIRMATION_CODE, code);
}
properties.put(IdentityRecoveryConstants.TEMPLATE_TYPE, type);
Event identityMgtEvent = new Event(eventName, properties);
try {
IdentityRecoveryServiceDataHolder.getInstance().getIdentityEventService().handleEvent(identityMgtEvent);
} catch (IdentityEventException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_TRIGGER_NOTIFICATION, user
.getUserName(), e);
}
}
/**
* Triggers notifications according to the given event name.
*
* @param user User
* @param notificationChannel Notification channel
* @param code Recovery code
* @param props Event properties
* @param eventName Name of the event
* @throws IdentityRecoveryException Error triggering notifications
*/
private void triggerNotification(User user, String notificationChannel, String code, Property[] props,
String eventName) throws IdentityRecoveryException {
if (log.isDebugEnabled()) {
log.debug("Sending self user registration notification user: " + user.getUserName());
}
HashMap<String, Object> properties = new HashMap<>();
properties.put(IdentityEventConstants.EventProperty.USER_NAME, user.getUserName());
properties.put(IdentityEventConstants.EventProperty.TENANT_DOMAIN, user.getTenantDomain());
properties.put(IdentityEventConstants.EventProperty.USER_STORE_DOMAIN, user.getUserStoreDomain());
properties.put(IdentityEventConstants.EventProperty.NOTIFICATION_CHANNEL, notificationChannel);
if (props != null && props.length > 0) {
for (Property prop : props) {
properties.put(prop.getKey(), prop.getValue());
}
}
if (StringUtils.isNotBlank(code)) {
properties.put(IdentityRecoveryConstants.CONFIRMATION_CODE, code);
}
properties.put(IdentityRecoveryConstants.TEMPLATE_TYPE,
IdentityRecoveryConstants.NOTIFICATION_TYPE_ACCOUNT_CONFIRM);
Event identityMgtEvent = new Event(eventName, properties);
try {
IdentityRecoveryServiceDataHolder.getInstance().getIdentityEventService().handleEvent(identityMgtEvent);
} catch (IdentityEventException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_TRIGGER_NOTIFICATION,
user.getUserName(), e);
}
}
private void triggerAccountCreationNotification(User user) throws IdentityRecoveryServerException {
String eventName = IdentityEventConstants.Event.TRIGGER_NOTIFICATION;
HashMap<String, Object> properties = new HashMap<>();
properties.put(IdentityEventConstants.EventProperty.USER_NAME, user.getUserName());
properties.put(IdentityEventConstants.EventProperty.TENANT_DOMAIN, user.getTenantDomain());
properties.put(IdentityEventConstants.EventProperty.USER_STORE_DOMAIN, user.getUserStoreDomain());
properties.put(IdentityRecoveryConstants.TEMPLATE_TYPE,
IdentityRecoveryConstants.NOTIFICATION_TYPE_SELF_SIGNUP_NOTIFY);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy hh:mm:ss");
String selfSignUpConfirmationTime = simpleDateFormat.format(new Date(System.currentTimeMillis()));
properties.put(IdentityEventConstants.EventProperty.SELF_SIGNUP_CONFIRM_TIME, selfSignUpConfirmationTime);
Event identityMgtEvent = new Event(eventName, properties);
try {
IdentityRecoveryServiceDataHolder.getInstance().getIdentityEventService().handleEvent(identityMgtEvent);
} catch (IdentityEventException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_TRIGGER_NOTIFICATION,
user.getUserName(), e);
}
}
}
|
public class Planet{
public double xxPos;
public double yyPos;
public double xxVel;
public double yyVel;
public double mass;
public String imgFileName;
public Planet(double xP, double yP, double xV, double yV, double m, String img){
xxPos=xP;
yyPos=yP;
xxVel=xV;
yyVel=yV;
mass=m;
imgFileName=img;
}
public Planet(Planet p){
xxPos=p.xxPos;
yyPos=p.yyPos;
xxVel=p.xxVel;
yyVel=p.yyVel;
mass=p.mass;
imgFileName=p.imgFileName;
}
public double calcDistance(Planet plt){
double r = Math.sqrt((Math.pow((xxPos-plt.xxPos),2) + Math.pow((yyPos-plt.yyPos),2)));
return r;
}
private static final double G = 6.67*(Math.pow(10,-11));
public double calcForceExertedBy(Planet plt){
double r = this.calcDistance(plt);
double force = G*this.mass*plt.mass/(r*r);
return force;
}
public double calcForceExertedByX(Planet plt){
double netforce = this.calcForceExertedBy(plt)*((plt.xxPos - xxPos)/this.calcDistance(plt));
return netforce;
}
public double calcForceExertedByY(Planet plt){
double netforce = this.calcForceExertedBy(plt)*((plt.yyPos - yyPos)/this.calcDistance(plt));
return netforce;
}
public double calcNetForceExertedByX(Planet[] plts){
int i = 0;
double netforce = 0;
while (i<plts.length){
if(this.equals(plts[i])){
i++;
continue;
}
netforce += this.calcForceExertedBy(plts[i])*((plts[i].xxPos - xxPos)/this.calcDistance(plts[i]));
i++;
}
return netforce;
}
public double calcNetForceExertedByY(Planet[] plts){
int i = 0;
double netforce = 0;
while (i<plts.length){
if(this.equals(plts[i])){
i++;
continue;
}
netforce += this.calcForceExertedBy(plts[i])*((plts[i].yyPos - yyPos)/this.calcDistance(plts[i]));
i++;
}
return netforce;
}
public void update(double dt, double fx, double fy){
/** accelerate along x-axis*/
double ax = fx/this.mass;
double ay = fy/this.mass;
xxVel += ax*dt;
yyVel += ay*dt;
xxPos += xxVel*dt;
yyPos += yyVel*dt;
}
public void draw(){
StdDraw.picture(xxPos, yyPos, "images/"+imgFileName);
//StdDraw.show();
}
}
|
package ru.otus.sua.L14.webserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
public class LoginServlet extends HttpServlet {
@Autowired
private TemplateProcessor templateProcessor;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestLogin = Objects.toString(
request.getParameter(TemplateConstants.LOGIN_FORM_LOGIN_PARAMETER_NAME),
WebserverConstants.DEFAULT_USER_NAME);
ServletHelper.saveLoginToSession(request, requestLogin);
ServletHelper.setOK(response);
response.getWriter().println(
templateProcessor.getPage(TemplateConstants.LOGIN_PAGE_TEMPLATE, requestLogin, null));
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String previousLogin = ServletHelper.readLoginFromSession(request);
ServletHelper.setOK(response);
response.getWriter().println(
templateProcessor.getPage(TemplateConstants.LOGIN_PAGE_TEMPLATE, previousLogin, null));
}
}
|
package main;
import java.util.Iterator;
import java.util.List;
import classes.Book;
import classes.BookDAOImpl;
import interfaces.BookDAO;
/**
* @author dylan
*
*/
public class DAOPatternMain {
/**
* @param args
*/
public static void main(String[] args) {
BookDAO myLibrary = new BookDAOImpl();
List<Book> myBooks = myLibrary.getAllBooks();
Iterator bookIterator = myBooks.iterator();
while (bookIterator.hasNext()) {
Book currentBook = (Book) bookIterator.next();
System.out.println(currentBook.getTitle() + ", " + currentBook.getAuthor() + ", " + currentBook.getIsbn());
}
Book badBook = new Book("bookc", "authorc", 3);
myLibrary.deleteBook(badBook);
Book goodBook = new Book("bookce", "authore", 5);
myLibrary.saveBook(goodBook);
myBooks = myLibrary.getAllBooks();
bookIterator = myBooks.iterator();
while (bookIterator.hasNext()) {
Book currentBook = (Book) bookIterator.next();
System.out.println(currentBook.getTitle() + ", " + currentBook.getAuthor() + ", " + currentBook.getIsbn());
}
}
}
|
package com.github.muravyova.githubreporeader.models;
import com.github.muravyova.githubreporeader.App;
import com.github.muravyova.githubreporeader.R;
import com.github.muravyova.githubreporeader.network.Document;
import com.github.muravyova.githubreporeader.network.Repository;
import com.github.muravyova.githubreporeader.network.User;
import com.github.muravyova.githubreporeader.utils.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public abstract class CommonItem {
public final int type;
CommonItem(int type) {
this.type = type;
}
public static List<CommonItem> createLoadItem(){
List<CommonItem> items = new ArrayList<>();
items.add(new LoadItem());
return items;
}
public static List<CommonItem> createErrorItem(String message){
List<CommonItem> items = new ArrayList<>();
items.add(new ErrorItem(message));
return items;
}
public static List<CommonItem> createUserItems(List<User> users){
List<CommonItem> items = new ArrayList<>();
if (users.size() == 0){
StringUtil instance = App.INJECTOR.stringUtil;
items.add(new EmptyItem(instance.getString(R.string.not_found_users)));
return items;
}
for (User user : users){
items.add(new UserItem(user));
}
return items;
}
public static List<CommonItem> createRepositoryItems(List<Repository> repositories){
List<CommonItem> items = new ArrayList<>();
if (repositories.size() == 0){
StringUtil instance = App.INJECTOR.stringUtil;
items.add(new EmptyItem(instance.getString(R.string.empty_repositories)));
return items;
}
for (Repository repository : repositories){
items.add(new RepositoryItem(repository));
}
return items;
}
public static List<CommonItem> createFileItems(List<Document> documents){
List<CommonItem> items = new ArrayList<>();
if (documents.size() == 0){
StringUtil instance = App.INJECTOR.stringUtil;
items.add(new EmptyItem(instance.getString(R.string.empty_directory)));
return items;
}
Collections.sort(documents, (o1, o2) -> o1.getType().compareTo(o2.getType()));
for (Document document : documents){
document.createType();
items.add(new DocumentItem(document));
}
return items;
}
public interface ItemClick {
void onClick(CommonItem item);
}
}
|
package 线程安全;
/*
在java中,我们通过同步机制来解决线程安全问题。
1、同步代码块
Synchronized(同步监视器){//同步监视器俗称锁,任何一个类的对象都可以作为一把锁
//需要同步的代码(即操作共享数据的方法)
}
2、同步方法
与同步代码块一样,该方法将同步代码块抽象为一个方法,在方法中加上synchronize关键字即可。只不过
不需要显式声明监视器。
对于非静态的同步方法,监视器是this
对于静态的同步方法,监视器是类本身。
与实现runnable接口不同,监视器为this。对于继承方法,由于有多个对象,所以还需要在方法中加上
static关键字,保证监视器唯一。监视器为类.class。
*/
public class Synchronize_ThreadSafty {
public static void main(String[] args) {
Ticket1 T = new Ticket1();
Thread t1 = new Thread(T);
Thread t2 = new Thread(T);
Thread t3 = new Thread(T);
t3.start();
t1.start();
t2.start();
}
}
class Ticket1 implements Runnable {
private int ticket = 100;
Object obj = new Object();
@Override
public void run() {
while (true) {
synchronized (this) {
if (ticket > 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket + "张票!");
ticket--;
} else
break;
}
}
}
}
|
package com.evan.demo.yizhu.woshi_fragment;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import com.evan.demo.yizhu.R;
public class woshi_kongtiao extends Fragment {
private View rootView;
private TextView wendu;
private Typeface mFace;
private ImageButton woshi_zhileng;
private ImageButton woshi_chuchen;
private ImageButton woshi_zhire;
private ImageButton woshi_tongfeng;
private ImageButton woshi_button;
private Button woshi_fengxiang;
private Button woshi_fengsu;
private Button woshi_dingshi;
private Button woshi_jieneng;
private int flag = 0;
private int flag1 = 0;
private int flag2 = 0;
private int flag3 = 0;
private int flag4 = 0;
private int flag5 = 0;
private int flag6= 0;
private int flag7 = 0;
private int flag8 = 0;
@Override
public void onAttach(Context context){
super.onAttach(context);
}
@Override
public View onCreateView(@Nullable LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.fragment_woshi_kongtiao,container,false);
initUi();
return rootView;
}
private void initUi(){
//这里写加载布局的代码
wendu = (TextView)rootView.findViewById(R.id.woshi_wendu);
woshi_zhileng = (ImageButton)rootView.findViewById(R.id.woshi_zhileng);
woshi_chuchen = (ImageButton)rootView.findViewById(R.id.woshi_chuchen);
woshi_zhire = (ImageButton)rootView.findViewById(R.id.woshi_zhire);
woshi_tongfeng = (ImageButton)rootView.findViewById(R.id.woshi_tongfeng);
woshi_button = (ImageButton)rootView.findViewById(R.id.woshi_kaiguan);
woshi_fengxiang = (Button)rootView.findViewById(R.id.woshi_fengxiang);
woshi_fengsu = (Button)rootView.findViewById(R.id.woshi_fengsu);
woshi_dingshi = (Button)rootView.findViewById(R.id.woshi_dingshi);
woshi_jieneng = (Button)rootView.findViewById(R.id.woshi_jieneng);
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
//这里写逻辑代码
mFace = Typeface.createFromAsset(rootView.getContext().getAssets(), "fonts/sitka.ttc");
wendu.setTypeface(mFace);
if(flag == 0 ){
woshi_fengxiang.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
woshi_fengxiang.setTextColor(Color.rgb(64,147,74));
}
else {
woshi_fengxiang.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
woshi_fengxiang.setTextColor(Color.WHITE);
}
woshi_fengxiang.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag == 0 ){
woshi_fengxiang.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
woshi_fengxiang.setTextColor(Color.WHITE);
flag = 1;
}
else {
woshi_fengxiang.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
woshi_fengxiang.setTextColor(Color.rgb(64,147,74));
flag = 0;
}
}
});
if(flag1 == 0 ){
woshi_fengsu.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
woshi_fengsu.setTextColor(Color.rgb(64,147,74));
}
else {
woshi_fengsu.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
woshi_fengsu.setTextColor(Color.WHITE);
}
woshi_fengsu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag1 == 0 ){
woshi_fengsu.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
woshi_fengsu.setTextColor(Color.WHITE);
flag1 = 1;
}
else {
woshi_fengsu.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
woshi_fengsu.setTextColor(Color.rgb(64,147,74));
flag1 = 0;
}
}
});
if(flag2 == 0 ){
woshi_dingshi.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
woshi_dingshi.setTextColor(Color.rgb(64,147,74));
}
else {
woshi_dingshi.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
woshi_dingshi.setTextColor(Color.WHITE);
}
woshi_dingshi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag2 == 0 ){
woshi_dingshi.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
woshi_dingshi.setTextColor(Color.WHITE);
flag2 = 1;
}
else {
woshi_dingshi.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
woshi_dingshi.setTextColor(Color.rgb(64,147,74));
flag2 = 0;
}
}
});
if(flag3 == 0 ){
woshi_jieneng.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
woshi_jieneng.setTextColor(Color.rgb(64,147,74));
}
else {
woshi_jieneng.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
woshi_jieneng.setTextColor(Color.WHITE);
}
woshi_jieneng.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag3 == 0 ){
woshi_jieneng.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
woshi_jieneng.setTextColor(Color.WHITE);
flag3 = 1;
}
else {
woshi_jieneng.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
woshi_jieneng.setTextColor(Color.rgb(64,147,74));
flag3 = 0;
}
}
});
if(flag4 == 0 ){
woshi_zhileng.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
woshi_zhileng.setImageDrawable(getResources().getDrawable(R.drawable.xue));
}
else {
woshi_zhileng.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
woshi_zhileng.setImageDrawable(getResources().getDrawable(R.drawable.xue_white));
}
woshi_zhileng.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag4 == 0 ){
woshi_zhileng.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
woshi_zhileng.setImageDrawable(getResources().getDrawable(R.drawable.xue_white));
flag4 = 1;
}
else {
woshi_zhileng.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
woshi_zhileng.setImageDrawable(getResources().getDrawable(R.drawable.xue));
flag4 = 0;
}
}
});
if(flag5 == 0 ){
woshi_chuchen.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
}
else {
woshi_chuchen.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
}
woshi_chuchen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag5 == 0 ){
woshi_chuchen.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
flag5 = 1;
}
else {
woshi_chuchen.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
flag5 = 0;
}
}
});
if(flag6 == 0 ){
woshi_zhire.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
}
else {
woshi_zhire.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
}
woshi_zhire.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag6 == 0 ){
woshi_zhire.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
flag6 = 1;
}
else {
woshi_zhire.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
flag6 = 0;
}
}
});
if(flag7 == 0 ){
woshi_tongfeng.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
}
else {
woshi_tongfeng.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
}
woshi_tongfeng.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag7 == 0 ){
woshi_tongfeng.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
flag7 = 1;
}
else {
woshi_tongfeng.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
flag7 = 0;
}
}
});
if(flag8 == 0 ){
woshi_button.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
woshi_button.setImageDrawable(getResources().getDrawable(R.drawable.button_off));
}
else {
woshi_button.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
woshi_button.setImageDrawable(getResources().getDrawable(R.drawable.button_on));
}
woshi_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag8 == 0 ){
woshi_button.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
woshi_button.setImageDrawable(getResources().getDrawable(R.drawable.button_on));
flag8 = 1;
}
else {
woshi_button.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
woshi_button.setImageDrawable(getResources().getDrawable(R.drawable.button_off));
flag8 = 0;
}
}
});
}
}
|
package com.bnrc.adapter;
import java.util.List;
import java.util.Map;
import com.bnrc.ui.rjz.other.ItemDelListener;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Copyright (c) 2011 All rights reserved ���ƣ�MyListViewAdapter
* ������ListView�Զ���Adapter����
*
* @author zhaoqp
* @date 2011-11-8
* @version
*/
public class MyRoutListViewAdapter extends BaseAdapter {
private Context mContext;
// ���еIJ���
private int mResource;
// �б�չ�ֵ�����
private List<? extends Map<String, ?>> mData;
// Map�е�key
private String[] mFrom;
// view��id
private int[] mTo;
private ItemDelListener mDelListener;
/**
* ���췽��
*
* @param context
* @param data
* �б�չ�ֵ�����
* @param resource
* ���еIJ���
* @param from
* Map�е�key
* @param to
* view��id
*/
public MyRoutListViewAdapter(Context context,
List<? extends Map<String, ?>> data, int resource, String[] from,
int[] to) {
mContext = context;
mData = data;
mResource = resource;
mFrom = from;
mTo = to;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView,
final ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(mResource,
parent, false);
holder = new ViewHolder();
holder.itemsIcon = ((ImageView) convertView.findViewById(mTo[0]));
holder.itemsTitle = ((TextView) convertView.findViewById(mTo[1]));
holder.itemsText = ((TextView) convertView.findViewById(mTo[2]));
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Map<String, ?> dataSet = mData.get(position);
if (dataSet == null) {
return null;
}
// ��ȡ��������
final Object data0 = dataSet.get(mFrom[0]);
final Object data1 = dataSet.get(mFrom[1]);
final Object data2 = dataSet.get(mFrom[2]);
// �������ݵ�View
holder.itemsIcon.setImageResource((Integer) data0);
holder.itemsTitle.setText(data1.toString());
holder.itemsText.setText(data2.toString());
return convertView;
}
public void setDelListener(ItemDelListener delListener) {
this.mDelListener = delListener;
}
/**
* ViewHolder��
*/
static class ViewHolder {
ImageView itemsIcon;
TextView itemsTitle;
TextView itemsText;
ImageView itemsDel;
}
} |
/**
*
*/
package eu.fbk.dycapo.factories.bundles;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.os.Bundle;
import android.util.Log;
import eu.fbk.dycapo.models.Location;
/**
* @author riccardo
*
*/
public abstract class LocationBundle {
public static final String TAG = "LocationBundle";
public static final Bundle toBundle(Location location) {
Bundle result = new Bundle();
if (location.getHref() instanceof String)
result.putString(Location.HREF, location.getHref());
if (location.getCountry() instanceof String)
result.putString(Location.COUNTRY, location.getCountry());
if (location.getDays() instanceof String)
result.putString(Location.DAYS, location.getDays());
if (location.getGeorss_point() instanceof String)
result.putString(Location.GEORSS_POINT, location.getGeorss_point());
if (location.getLabel() instanceof String)
result.putString(Location.LABEL, location.getLabel());
if (location.getLeaves() instanceof Date) {
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
result.putString(Location.LEAVES,
formatter.format(location.getLeaves()));
}
if (location.getOffset() instanceof Integer)
result.putInt(Location.OFFSET, location.getOffset());
if (location.getPoint() instanceof Integer)
result.putString(Location.POINT,
Location.POINT_TYPE[location.getPoint()]);
if (location.getPostcode() instanceof Integer)
result.putInt(Location.POSTCODE, location.getPostcode());
if (location.getRecurs() instanceof String)
result.putString(Location.RECURS, location.getRecurs());
if (location.getRegion() instanceof String)
result.putString(Location.REGION, location.getRegion());
if (location.getStreet() instanceof String)
result.putString(Location.STREET, location.getStreet());
if (location.getSubregion() instanceof String)
result.putString(Location.SUBREGION, location.getSubregion());
if (location.getTown() instanceof String)
result.putString(Location.TOWN, location.getTown());
return result;
}
public static final Location fromBundle(Bundle data) {
Location location = new Location();
if (data.containsKey(Location.HREF))
location.setHref(data.getString(Location.HREF));
if (data.containsKey(Location.COUNTRY))
location.setCountry(data.getString(Location.COUNTRY));
if (data.containsKey(Location.DAYS))
location.setDays(data.getString(Location.DAYS));
if (data.containsKey(Location.GEORSS_POINT))
location.setGeorss_point(data.getString(Location.GEORSS_POINT));
if (data.containsKey(Location.LABEL))
location.setLabel(data.getString(Location.LABEL));
if (data.containsKey(Location.LEAVES)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
location.setLeaves(sdf.parse(data.getString(Location.LEAVES)));
} catch (ParseException e) {
Log.e(TAG, e.getMessage());
}
}
if (data.containsKey(Location.OFFSET))
location.setOffset(data.getInt(Location.OFFSET));
if (data.containsKey(Location.POINT)) {
String point_type = data.getString(Location.POINT);
if (point_type.equals(Location.POINT_TYPE[Location.ORIG]))
location.setPoint(Location.ORIG);
else if (point_type.equals(Location.POINT_TYPE[Location.DEST]))
location.setPoint(Location.DEST);
else if (point_type.equals(Location.POINT_TYPE[Location.WAYP]))
location.setPoint(Location.WAYP);
else if (point_type.equals(Location.POINT_TYPE[Location.POSI]))
location.setPoint(Location.POSI);
}
if (data.containsKey(Location.POSTCODE))
location.setPostcode(data.getInt(Location.POSTCODE));
if (data.containsKey(Location.RECURS))
location.setRecurs(data.getString(Location.RECURS));
if (data.containsKey(Location.REGION))
location.setRegion(data.getString(Location.REGION));
if (data.containsKey(Location.STREET))
location.setStreet(data.getString(Location.STREET));
if (data.containsKey(Location.SUBREGION))
location.setSubregion(data.getString(Location.SUBREGION));
if (data.containsKey(Location.TOWN))
location.setTown(data.getString(Location.TOWN));
return location;
}
}
|
package com.rabitmq.consumer.config.queue;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQQueueConfig {
@Bean
Queue queue() {
return QueueBuilder.durable("SpringBootQueue2").autoDelete().exclusive().build();
}
}
|
package com.trump.auction.back.push.service;
/**
* Author: zhanping
*/
public interface NotificationDeviceService {
}
|
package practices.written;
/**
* 京东测开笔试:修路,求最大利润
*/
import java.util.*;
public class FixRoad {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
if (n <= 0)
return;
int[] arr = new int[n - 1];
Map<String[], Integer> map = new HashMap<>();
for (int i = 0; i < n - 1; i++) {
String str = sc.nextLine();
if (str.length() != 3)
return;
String[] strs = str.split(" ");
arr[i] = Math.abs(Integer.parseInt(strs[0]) - Integer.parseInt(strs[1]));
map.put(strs, arr[i]);
}
Set<String[]> keys = new HashSet<>();
for (String[] key : keys) {
}
// Arrays.sort(arr);
// System.out.println(arr[0] * arr[arr.length - 1]);
}
} |
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.explorer.client.misc;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.examples.resources.client.Resources;
import com.sencha.gxt.examples.resources.client.TestData;
import com.sencha.gxt.explorer.client.model.Example.Detail;
import com.sencha.gxt.fx.client.Draggable;
import com.sencha.gxt.widget.core.client.ContentPanel;
@Detail(name = "Draggable (UiBinder)", icon = "draggable", category = "Misc", fit = true, files = "DraggableUiBinderExample.ui.xml")
public class DraggableUiBinderExample implements IsWidget, EntryPoint {
interface MyUiBinder extends UiBinder<Widget, DraggableUiBinderExample> {
}
private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
@UiField(provided = true)
String dummyTextShort = TestData.DUMMY_TEXT_SHORT;
@UiField
ContentPanel proxy;
@UiField
ContentPanel direct;
@UiField
ContentPanel vertical;
public Widget asWidget() {
Widget widget = uiBinder.createAndBindUi(this);
proxy.getHeader().setIcon(Resources.IMAGES.text());
direct.getHeader().setIcon(Resources.IMAGES.text());
vertical.getHeader().setIcon(Resources.IMAGES.text());
new Draggable(proxy);
new Draggable(direct, direct.getHeader()).setUseProxy(false);
new Draggable(vertical, vertical.getHeader()).setConstrainHorizontal(true);
return widget;
}
public void onModuleLoad() {
RootPanel.get().add(asWidget());
}
}
|
package cn.v5cn.v5cms.front.interceptor;
import cn.v5cn.v5cms.entity.Site;
import cn.v5cn.v5cms.service.SiteService;
import cn.v5cn.v5cms.util.SystemConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by zyw on 15/8/3.
*/
public class FrontInterceptor extends HandlerInterceptorAdapter {
@Autowired
private SiteService siteService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {
Object siteObj = request.getSession().getAttribute(SystemConstant.FRONT_SITE_SESSION_KEY);
if(siteObj != null) return true;
String serverName = request.getServerName();
int serverPort = request.getServerPort();
Site site = siteService.findByDomain(serverName + ":" + serverPort);
request.getSession().setAttribute(SystemConstant.FRONT_SITE_SESSION_KEY,site);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
}
}
|
package com.yxkj.facexradix.rtc;
import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.trtc.TRTCCloud;
import com.tencent.trtc.TRTCCloudDef;
import com.tencent.trtc.TRTCCloudListener;
import com.tencent.trtc.TRTCStatistics;
import java.util.ArrayList;
public class TRTCCloudListenerImpl extends TRTCCloudListener {
private final TRTCActivity trtcActivity;
private final TRTCCloud trtcCloud;
private final FrameLayout remoteVideoView;
public TRTCCloudListenerImpl(TRTCActivity trtcActivity, TRTCCloud trtcCloud, FrameLayout remoteVideoView) {
this.trtcActivity = trtcActivity;
this.trtcCloud = trtcCloud;
this.remoteVideoView = remoteVideoView;
}
@Override
public void onEnterRoom(long elapsed) {
}
@Override
public void onExitRoom(int reason) {
if (trtcActivity != null){
trtcActivity.finish();
}
}
@Override
public void onError(int errCode, String errMsg, Bundle extraInfo) {
}
@Override
public void onRemoteUserEnterRoom(String s) {
trtcActivity.enterRoom(s);
super.onRemoteUserEnterRoom(s);
}
@Override
public void onUserVideoAvailable(String userId, boolean available) {
if (trtcActivity != null) {
if (available) {
// 设置remoteView
TXCloudVideoView remoteView = new TXCloudVideoView(trtcActivity);
remoteVideoView.addView(remoteView);
trtcCloud.setRemoteViewFillMode(userId, TRTCCloudDef.TRTC_VIDEO_RENDER_MODE_FILL);
trtcCloud.startRemoteView(userId, remoteView);
trtcActivity.connectTypeChange();
} else {
//停止观看画面
trtcCloud.stopRemoteView(userId);
}
}
}
@Override
public void onUserSubStreamAvailable(String userId, boolean available) {
}
@Override
public void onUserAudioAvailable(String userId, boolean available) {
}
@Override
public void onFirstVideoFrame(String userId, int streamType, int width, int height) {
}
@Override
public void onUserVoiceVolume(ArrayList<TRTCCloudDef.TRTCVolumeInfo> userVolumes, int totalVolume) {
}
@Override
public void onStatistics(TRTCStatistics statics) {
}
@Override
public void onConnectOtherRoom(String userID, int err, String errMsg) {
}
@Override
public void onDisConnectOtherRoom(int err, String errMsg) {
}
@Override
public void onNetworkQuality(TRTCCloudDef.TRTCQuality localQuality, ArrayList<TRTCCloudDef.TRTCQuality> remoteQuality) {
}
@Override
public void onAudioEffectFinished(int effectId, int code) {
}
@Override
public void onRecvCustomCmdMsg(String userId, int cmdID, int seq, byte[] message) {
}
@Override
public void onRecvSEIMsg(String userId, byte[] data) {
}
@Override
public void onRemoteUserLeaveRoom(String s, int i) {
trtcActivity.LeaveRoom(s);
super.onRemoteUserLeaveRoom(s, i);
}
}
|
package com.example.web.springboot.domain.user;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User,Long> {
Optional<User> findByEmail(String email);
//Optional은 무엇을 판단할 때 사용 , User가 생성되어 있는지 여부를 판단
}
|
package com.lyj.test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;
/**
* @author yingjie.lu
* @version 1.0
* @date 2019/12/26 2:58 下午
*/
@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
/**
* 执行顺序:1
* 可以添加或修改BeanDefinition
* 在执行该方法时,所有常规的bean都已经加载并添加到BeanDefinitionMap中,但是此时的bean还未被实例化,
* 所以,在该方法中,允许修改已经添加到BeanDefinitionMap中的bean的定义,或者是添加我们自己的bean的定义,
* 然后在bean的实例化时,添加或修改的bean都会生效,并被spring所管理
* @param registry 上下文的beanDefinitionMap(bean定义的注册表)
* @throws BeansException
*/
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println("postProcessBeanDefinitionRegistry");
}
/**
* 执行顺序:2
* 只可以修改BeanDefinition,而不能添加BeanDefinition
* 在执行该方法时,所有bean定义都已加载,但还没有实例化bean;
* @param beanFactory 上下文的beanFactory
* @throws BeansException
*/
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("postProcessBeanFactory");
// DefaultListableBeanFactory factory = (DefaultListableBeanFactory) beanFactory;
// factory.registerBeanDefinition("mybean",null);
}
public MyBeanDefinitionRegistryPostProcessor() {
System.out.println("构造方法:MyBeanDefinitionRegistryPostProcessor");
}
}
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.DiskSyncListener;
import org.odk.collect.android.listeners.FormDownloaderListener;
import org.odk.collect.android.listeners.FormListDownloaderListener;
import org.odk.collect.android.logic.FormDetails;
import org.odk.collect.android.preferences.AdminPreferencesActivity;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.tasks.DiskSyncTask;
import org.odk.collect.android.tasks.DownloadFormListTask;
import org.odk.collect.android.tasks.DownloadFormsTask;
import org.odk.collect.android.utilities.CompatibilityUtils;
import org.taptwo.android.widget.ViewFlow;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
//import android.view.Menu;
//import android.view.MenuItem;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.mpower.database.feedbackdatabase;
import de.robert_heim.animation.ActivitySwitcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Responsible for displaying buttons to launch the major activities. Launches
* some activities based on returns of others.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class MainMenuActivity extends SherlockActivity implements DiskSyncListener,FormListDownloaderListener,FormDownloaderListener{
private static final String t = "MainMenuActivity";
private static final int PASSWORD_DIALOG = 1;
// menu options
private static final int MENU_PREFERENCES = Menu.FIRST;
private static final int MENU_ADMIN = Menu.FIRST + 1;
private ProgressDialog mProgressDialog;
// buttons
private Button mEnterDataButton;
private Button mManageFilesButton;
private Button mSendDataButton;
private Button mReviewDataButton;
private Button mGetFormsButton;
private View mReviewSpacer;
private View mGetFormsSpacer;
private AlertDialog mAlertDialog;
private SharedPreferences mAdminPreferences;
private int mCompletedCount;
private int mSavedCount;
private Cursor mFinalizedCursor;
private Cursor mSavedCursor;
private IncomingHandler mHandler = new IncomingHandler(this);
private MyContentObserver mContentObserver = new MyContentObserver();
private HashMap<String, FormDetails> mFormNamesAndURLs = new HashMap<String,FormDetails>();
private DownloadFormListTask mDownloadFormListTask;
private static boolean EXIT = true;
public static ViewFlow viewFlow;
private ArrayList<HashMap<String, String>> mFormList = new ArrayList<HashMap<String,String>>();
// private static boolean DO_NOT_EXIT = false;
private DownloadFormsTask mDownloadFormsTask;
private DiskSyncTask mDiskSyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an
// external intent
Log.i(t, "Starting up, creating directories");
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
setContentView(R.layout.activity_main);
ActionBar ab = getSupportActionBar();
ab.setBackgroundDrawable(getResources().getDrawable(R.drawable.topbar2));
ab.setTitle("");
viewFlow = (ViewFlow) findViewById(R.id.viewflow);
ImageAdapter flowadapter = new ImageAdapter(this);
viewFlow.setAdapter(flowadapter);
// ab.show();
//////////////////////////////commenting for action bar purposes///////////////////
// {
// // dynamically construct the "ODK Collect vA.B" string
// TextView mainMenuMessageLabel = (TextView) findViewById(R.id.main_menu_header);
// mainMenuMessageLabel.setText(Collect.getInstance()
// .getVersionedAppName());
// }
//
// setTitle(getString(R.string.app_name) + " > "
// + getString(R.string.main_menu));
//
File f = new File(Collect.ODK_ROOT + "/collect.settings");
if (f.exists()) {
boolean success = loadSharedPreferencesFromFile(f);
if (success) {
Toast.makeText(this,
"Settings successfully loaded from file",
Toast.LENGTH_LONG).show();
f.delete();
} else {
Toast.makeText(
this,
"Sorry, settings file is corrupt and should be deleted or replaced",
Toast.LENGTH_LONG).show();
}
}
// mReviewSpacer = findViewById(R.id.review_spacer);
// mGetFormsSpacer = findViewById(R.id.get_forms_spacer);
//
mAdminPreferences = this.getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
//
// // enter data button. expects a result.
// mEnterDataButton = (Button) findViewById(R.id.enter_data);
// mEnterDataButton.setText(getString(R.string.enter_data_button));
// mEnterDataButton.setOnClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// Collect.getInstance().getActivityLogger()
// .logAction(this, "fillBlankForm", "click");
// Intent i = new Intent(getApplicationContext(),
// FormChooserList.class);
// startActivity(i);
// }
// });
//
// // review data button. expects a result.
// mReviewDataButton = (Button) findViewById(R.id.review_data);
// mReviewDataButton.setText(getString(R.string.review_data_button));
// mReviewDataButton.setOnClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// Collect.getInstance().getActivityLogger()
// .logAction(this, "editSavedForm", "click");
// Intent i = new Intent(getApplicationContext(),
// InstanceChooserList.class);
// startActivity(i);
// }
// });
//
// // send data button. expects a result.
// mSendDataButton = (Button) findViewById(R.id.send_data);
// mSendDataButton.setText(getString(R.string.send_data_button));
// mSendDataButton.setOnClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// Collect.getInstance().getActivityLogger()
// .logAction(this, "uploadForms", "click");
// Intent i = new Intent(getApplicationContext(),
// InstanceUploaderList.class);
// startActivity(i);
// }
// });
//
// // manage forms button. no result expected.
// mGetFormsButton = (Button) findViewById(R.id.get_forms);
// mGetFormsButton.setText(getString(R.string.get_forms));
// mGetFormsButton.setOnClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// Collect.getInstance().getActivityLogger()
// .logAction(this, "downloadBlankForms", "click");
// Intent i = new Intent(getApplicationContext(),
// FormDownloadList.class);
// startActivity(i);
//
// }
// });
//
// // manage forms button. no result expected.
// mManageFilesButton = (Button) findViewById(R.id.manage_forms);
// mManageFilesButton.setText(getString(R.string.manage_files));
// mManageFilesButton.setOnClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// Collect.getInstance().getActivityLogger()
// .logAction(this, "deleteSavedForms", "click");
// Intent i = new Intent(getApplicationContext(),
// FileManagerTabs.class);
// startActivity(i);
// }
// });
//
// count for finalized instances
String selection = InstanceColumns.STATUS + "=? or "
+ InstanceColumns.STATUS + "=?";
String selectionArgs[] = { InstanceProviderAPI.STATUS_COMPLETE,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED };
mFinalizedCursor = managedQuery(InstanceColumns.CONTENT_URI, null,
selection, selectionArgs, null);
startManagingCursor(mFinalizedCursor);
mCompletedCount = mFinalizedCursor.getCount();
mFinalizedCursor.registerContentObserver(mContentObserver);
// count for finalized instances
String selectionSaved = InstanceColumns.STATUS + "=?";
String selectionArgsSaved[] = { InstanceProviderAPI.STATUS_INCOMPLETE };
mSavedCursor = managedQuery(InstanceColumns.CONTENT_URI, null,
selectionSaved, selectionArgsSaved, null);
startManagingCursor(mSavedCursor);
mSavedCount = mFinalizedCursor.getCount();
// // don't need to set a content observer because it can't change in the
// // background
//
// updateButtons();
/////////////////////////////////////////////////////////////
if(!checkformexists()){
downloadFormList();
}else{
mDiskSyncTask = (DiskSyncTask) getLastNonConfigurationInstance();
if (mDiskSyncTask == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle("processing disk for forms please wait");
mProgressDialog.show();
Log.i(t, "Starting new disk sync task");
mDiskSyncTask = new DiskSyncTask();
mDiskSyncTask.setDiskSyncListener(this);
mDiskSyncTask.execute((Void[]) null);
}
}
}
private boolean checkformexists() {
// TODO Auto-generated method stub
File file = new File("/sdcard/odk/forms/SAOO Reporting Form.xml");
File file2 = new File("/sdcard/odk/forms/Field Challenge Gathering.xml");
File file3 = new File("/sdcard/odk/forms/Farmer Query System.xml");
return file.exists()&&file2.exists()&&file3.exists();
// return false;
}
@Override
protected void onResume() {
ActivitySwitcher.animationIn(findViewById(R.id.container), getWindowManager());
System.gc();
super.onResume();
invalidateOptionsMenu();
// SharedPreferences sharedPreferences = this.getSharedPreferences(
// AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
//
// boolean edit = sharedPreferences.getBoolean(
// AdminPreferencesActivity.KEY_EDIT_SAVED, true);
// if (!edit) {
// mReviewDataButton.setVisibility(View.GONE);
// mReviewSpacer.setVisibility(View.GONE);
// } else {
// mReviewDataButton.setVisibility(View.VISIBLE);
// mReviewSpacer.setVisibility(View.VISIBLE);
// }
//
// boolean send = sharedPreferences.getBoolean(
// AdminPreferencesActivity.KEY_SEND_FINALIZED, true);
// if (!send) {
// mSendDataButton.setVisibility(View.GONE);
// } else {
// mSendDataButton.setVisibility(View.VISIBLE);
// }
//
// boolean get_blank = sharedPreferences.getBoolean(
// AdminPreferencesActivity.KEY_GET_BLANK, true);
// if (!get_blank) {
// mGetFormsButton.setVisibility(View.GONE);
// mGetFormsSpacer.setVisibility(View.GONE);
// } else {
// mGetFormsButton.setVisibility(View.VISIBLE);
// mGetFormsSpacer.setVisibility(View.VISIBLE);
// }
//
// boolean delete_saved = sharedPreferences.getBoolean(
// AdminPreferencesActivity.KEY_DELETE_SAVED, true);
// if (!delete_saved) {
// mManageFilesButton.setVisibility(View.GONE);
// } else {
// mManageFilesButton.setVisibility(View.VISIBLE);
// }
}
@Override
protected void onPause() {
super.onPause();
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean isLight = true;
// SampleList.THEME == R.style.Theme_Sherlock_Light;
LayoutInflater inflater = (LayoutInflater)this.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.iconbadge,null);
TextView txt = (TextView)(view.findViewById(R.id.textOne));
txt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
animatedStartActivity(new Intent(MainMenuActivity.this, farmerquery_feedback_list.class));
}
});
feedbackdatabase fdb = new feedbackdatabase(this);
txt.setText(""+fdb.returnunseenmessages());
menu.add(0, 0, 0, "notification").setActionView(view).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
// menu.add("Save")
// .setIcon(isLight ? R.drawable.notificationback : R.drawable.notificationback)
// .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
// menu.add("Search")
// .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
menu.add("settings")
.setIcon(isLight ? R.drawable.ic_menu_manage : R.drawable.ic_menu_manage)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
// SubMenu subMenu1 = menu.addSubMenu("Action Item");
// subMenu1.add("Sample");
// subMenu1.add("Menu");
// subMenu1.add("Items");
// MenuItem subMenu1Item = subMenu1.getItem();
// subMenu1Item.setIcon(R.drawable.ic_title_share_default);
// subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
// Collect.getInstance().getActivityLogger()
// .logAction(this, "onCreateOptionsMenu", "show");
// super.onCreateOptionsMenu(menu);
// CompatibilityUtils.setShowAsAction(
// menu.add(0, MENU_PREFERENCES, 0, R.string.general_preferences)
// .setIcon(R.drawable.ic_menu_preferences),
// MenuItem.SHOW_AS_ACTION_NEVER);
// CompatibilityUtils.setShowAsAction(
// menu.add(0, MENU_ADMIN, 0, R.string.admin_preferences)
// .setIcon(R.drawable.ic_menu_login),
// MenuItem.SHOW_AS_ACTION_NEVER);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
Collect.getInstance()
.getActivityLogger()
.logAction(this, "onOptionsItemSelected",
"MENU_PREFERENCES");
Intent ig = new Intent(this, PreferencesActivity.class);
startActivity(ig);
return true;
case 1:
Collect.getInstance().getActivityLogger()
.logAction(this, "onOptionsItemSelected", "MENU_ADMIN");
String pw = mAdminPreferences.getString(
AdminPreferencesActivity.KEY_ADMIN_PW, "");
if ("".equalsIgnoreCase(pw)) {
Intent i = new Intent(getApplicationContext(),
AdminPreferencesActivity.class);
startActivity(i);
} else {
showDialog(PASSWORD_DIALOG);
Collect.getInstance().getActivityLogger()
.logAction(this, "createAdminPasswordDialog", "show");
}
return true;
}
return super.onOptionsItemSelected(item);
}
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance().getActivityLogger()
.logAction(this, "createErrorDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
Collect.getInstance()
.getActivityLogger()
.logAction(this, "createErrorDialog",
shouldExit ? "exitApplication" : "OK");
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mAlertDialog.show();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PASSWORD_DIALOG:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog passwordDialog = builder.create();
passwordDialog.setTitle(getString(R.string.enter_admin_password));
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
input.setTransformationMethod(PasswordTransformationMethod
.getInstance());
passwordDialog.setView(input, 20, 10, 20, 10);
passwordDialog.setButton(AlertDialog.BUTTON_POSITIVE,
getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String value = input.getText().toString();
String pw = mAdminPreferences.getString(
AdminPreferencesActivity.KEY_ADMIN_PW, "");
if (pw.compareTo(value) == 0) {
Intent i = new Intent(getApplicationContext(),
AdminPreferencesActivity.class);
startActivity(i);
input.setText("");
passwordDialog.dismiss();
} else {
Toast.makeText(
MainMenuActivity.this,
getString(R.string.admin_password_incorrect),
Toast.LENGTH_SHORT).show();
Collect.getInstance()
.getActivityLogger()
.logAction(this, "adminPasswordDialog",
"PASSWORD_INCORRECT");
}
}
});
passwordDialog.setButton(AlertDialog.BUTTON_NEGATIVE,
getString(R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance()
.getActivityLogger()
.logAction(this, "adminPasswordDialog",
"cancel");
input.setText("");
return;
}
});
passwordDialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
return passwordDialog;
}
return null;
}
private void updateButtons() {
mFinalizedCursor.requery();
mCompletedCount = mFinalizedCursor.getCount();
if (mCompletedCount > 0) {
mSendDataButton.setText(getString(R.string.send_data_button,
mCompletedCount));
} else {
mSendDataButton.setText(getString(R.string.send_data));
}
mSavedCursor.requery();
mSavedCount = mSavedCursor.getCount();
if (mSavedCount > 0) {
mReviewDataButton.setText(getString(R.string.review_data_button,
mSavedCount));
} else {
mReviewDataButton.setText(getString(R.string.review_data));
}
}
/**
* notifies us that something changed
*
*/
private class MyContentObserver extends ContentObserver {
public MyContentObserver() {
super(null);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
mHandler.sendEmptyMessage(0);
}
}
/*
* Used to prevent memory leaks
*/
static class IncomingHandler extends Handler {
private final WeakReference<MainMenuActivity> mTarget;
IncomingHandler(MainMenuActivity target) {
mTarget = new WeakReference<MainMenuActivity>(target);
}
@Override
public void handleMessage(Message msg) {
MainMenuActivity target = mTarget.get();
if (target != null) {
target.updateButtons();
}
}
}
private boolean loadSharedPreferencesFromFile(File src) {
// this should probably be in a thread if it ever gets big
boolean res = false;
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream(src));
Editor prefEdit = PreferenceManager.getDefaultSharedPreferences(
this).edit();
prefEdit.clear();
// first object is preferences
Map<String, ?> entries = (Map<String, ?>) input.readObject();
for (Entry<String, ?> entry : entries.entrySet()) {
Object v = entry.getValue();
String key = entry.getKey();
if (v instanceof Boolean)
prefEdit.putBoolean(key, ((Boolean) v).booleanValue());
else if (v instanceof Float)
prefEdit.putFloat(key, ((Float) v).floatValue());
else if (v instanceof Integer)
prefEdit.putInt(key, ((Integer) v).intValue());
else if (v instanceof Long)
prefEdit.putLong(key, ((Long) v).longValue());
else if (v instanceof String)
prefEdit.putString(key, ((String) v));
}
prefEdit.commit();
// second object is admin options
Editor adminEdit = getSharedPreferences(AdminPreferencesActivity.ADMIN_PREFERENCES, 0).edit();
adminEdit.clear();
// first object is preferences
Map<String, ?> adminEntries = (Map<String, ?>) input.readObject();
for (Entry<String, ?> entry : adminEntries.entrySet()) {
Object v = entry.getValue();
String key = entry.getKey();
if (v instanceof Boolean)
adminEdit.putBoolean(key, ((Boolean) v).booleanValue());
else if (v instanceof Float)
adminEdit.putFloat(key, ((Float) v).floatValue());
else if (v instanceof Integer)
adminEdit.putInt(key, ((Integer) v).intValue());
else if (v instanceof Long)
adminEdit.putLong(key, ((Long) v).longValue());
else if (v instanceof String)
adminEdit.putString(key, ((String) v));
}
adminEdit.commit();
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
private void downloadFormList() {
ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni == null || !ni.isConnected()) {
Toast.makeText(this, R.string.no_connection, Toast.LENGTH_SHORT).show();
} else {
mProgressDialog = new ProgressDialog(this);
mFormNamesAndURLs = new HashMap<String, FormDetails>();
if (mProgressDialog != null) {
// This is needed because onPrepareDialog() is broken in 1.6.
mProgressDialog.setMessage(getString(R.string.please_wait));
}
mProgressDialog.show();
// showDialog(PROGRESS_DIALOG);
if (mDownloadFormListTask != null &&
mDownloadFormListTask.getStatus() != AsyncTask.Status.FINISHED) {
return; // we are already doing the download!!!
} else if (mDownloadFormListTask != null) {
mDownloadFormListTask.setDownloaderListener(null);
mDownloadFormListTask.cancel(true);
mDownloadFormListTask = null;
}
mDownloadFormListTask = new DownloadFormListTask();
mDownloadFormListTask.setDownloaderListener(this);
mDownloadFormListTask.execute();
}
}
@Override
public void formListDownloadingComplete(HashMap<String, FormDetails> result) {
// TODO Auto-generated method stub
// dismissDialog(PROGRESS_DIALOG);
mDownloadFormListTask.setDownloaderListener(null);
mDownloadFormListTask = null;
if (result == null) {
Log.e(t, "Formlist Downloading returned null. That shouldn't happen");
// Just displayes "error occured" to the user, but this should never happen.
// createAlertDialog(getString(R.string.load_remote_form_error),
// getString(R.string.error_occured), EXIT);
return;
}
if (result.containsKey(DownloadFormListTask.DL_AUTH_REQUIRED)) {
// need authorization
// showDialog(AUTH_DIALOG);
} else if (result.containsKey(DownloadFormListTask.DL_ERROR_MSG)) {
// Download failed
String dialogMessage =
getString(R.string.list_failed_with_error,
result.get(DownloadFormListTask.DL_ERROR_MSG).errorStr);
String dialogTitle = getString(R.string.load_remote_form_error);
// createAlertDialog(dialogTitle, dialogMessage, DO_NOT_EXIT);
} else {
// Everything worked. Clear the list and add the results.
// mProgressDialog.dismiss();
mFormNamesAndURLs = result;
mFormList.clear();
ArrayList<String> ids = new ArrayList<String>(mFormNamesAndURLs.keySet());
ArrayList<FormDetails> filesToDownload = new ArrayList<FormDetails>();
for (int i = 0; i < result.size(); i++) {
String formDetailsKey = ids.get(i);
FormDetails details = mFormNamesAndURLs.get(formDetailsKey);
HashMap<String, String> item = new HashMap<String, String>();
item.put("FORMNAME", details.formName);
item.put("FORMID_DISPLAY",
((details.formVersion == null) ? "" : (getString(R.string.version) + " " + details.formVersion + " ")) +
"ID: " + details.formID );
item.put("FORMDETAIL_KEY", formDetailsKey);
Log.v("formnames", ""+details.formName);
filesToDownload.add(details);
// Insert the new form in alphabetical order.
if (mFormList.size() == 0) {
mFormList.add(item);
} else {
int j;
for (j = 0; j < mFormList.size(); j++) {
HashMap<String, String> compareMe = mFormList.get(j);
String name = compareMe.get("FORMNAME");
if (name.compareTo(mFormNamesAndURLs.get(ids.get(i)).formName) > 0) {
break;
}
}
mFormList.add(j, item);
}
}
mDownloadFormsTask = new DownloadFormsTask();
mDownloadFormsTask.setDownloaderListener(this);
mDownloadFormsTask.execute(filesToDownload);
// mFormListAdapter.notifyDataSetChanged();
}
}
@Override
public void formsDownloadingComplete(HashMap<String, String> result) {
// TODO Auto-generated method stub
if (mDownloadFormsTask != null) {
mDownloadFormsTask.setDownloaderListener(null);
}
if (mProgressDialog.isShowing()) {
// should always be true here
mProgressDialog.dismiss();
}
mDiskSyncTask = (DiskSyncTask) getLastNonConfigurationInstance();
if (mDiskSyncTask == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle("processing disk for forms please wait");
mProgressDialog.show();
Log.i(t, "Starting new disk sync task");
mDiskSyncTask = new DiskSyncTask();
mDiskSyncTask.setDiskSyncListener(this);
mDiskSyncTask.execute((Void[]) null);
}
}
@Override
public void progressUpdate(String currentFile, int progress, int total) {
// TODO Auto-generated method stub
}
@Override
public void SyncComplete(String result) {
// TODO Auto-generated method stub
if(mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
}
@Override
public void overridePendingTransition(int enterAnim, int exitAnim) {
// TODO Auto-generated method stub
super.overridePendingTransition(0, 0);
}
private void animatedStartActivity(final Intent intent) {
// we only animateOut this activity here.
// The new activity will animateIn from its onResume() - be sure to implement it.
// final Intent intent = new Intent(con, Activity2.class);
// disable default animation for new intent
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
ActivitySwitcher.animationOut(((this) ).findViewById(R.id.container), (this).getWindowManager(), new ActivitySwitcher.AnimationFinishedListener() {
@Override
public void onAnimationFinished() {
System.gc();
startActivity(intent);
}
});
}
}
|
package com.finance.service;
import com.finance.dao.UserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.util.List;
public class UserService {
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
private UserDao userDao;
public Integer queryAge() {
return userDao.getAge();
}
public void query() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://192.168.33.12/finance");
dataSource.setUsername("root");
dataSource.setPassword("root");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "select * from user";
List list = jdbcTemplate.queryForList(sql);
for(Object o : list) {
System.out.println(o);
}
}
public void queryByBean() {
List list = userDao.queryByBean();
System.out.println(list);
}
public void updateMoney() {
userDao.decMoney();
userDao.incMoney();
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.support;
import java.util.Arrays;
import java.util.List;
import org.springframework.core.io.support.PropertySourceDescriptor;
import org.springframework.core.style.DefaultToStringStyler;
import org.springframework.core.style.SimpleValueStyler;
import org.springframework.core.style.ToStringCreator;
import org.springframework.lang.Nullable;
import org.springframework.test.context.TestPropertySource;
import org.springframework.util.Assert;
/**
* {@code MergedTestPropertySources} encapsulates the <em>merged</em> property
* sources declared on a test class and all of its superclasses and enclosing
* classes via {@link TestPropertySource @TestPropertySource}.
*
* @author Sam Brannen
* @since 4.1
* @see TestPropertySource
*/
class MergedTestPropertySources {
private static final MergedTestPropertySources empty = new MergedTestPropertySources(List.of(), new String[0]);
private final List<PropertySourceDescriptor> descriptors;
private final String[] properties;
/**
* Factory for an <em>empty</em> {@code MergedTestPropertySources} instance.
*/
static MergedTestPropertySources empty() {
return empty;
}
/**
* Create a {@code MergedTestPropertySources} instance with the supplied
* {@code descriptors} and {@code properties}.
* @param descriptors the descriptors for resource locations
* of properties files; may be empty but never {@code null}
* @param properties the properties in the form of {@code key=value} pairs;
* may be empty but never {@code null}
*/
MergedTestPropertySources(List<PropertySourceDescriptor> descriptors, String[] properties) {
Assert.notNull(descriptors, "The descriptors list must not be null");
Assert.notNull(properties, "The properties array must not be null");
this.descriptors = descriptors;
this.properties = properties;
}
/**
* Get the descriptors for resource locations of properties files.
* @see TestPropertySource#locations
* @see TestPropertySource#encoding
* @see TestPropertySource#factory
*/
List<PropertySourceDescriptor> getPropertySourceDescriptors() {
return this.descriptors;
}
/**
* Get the properties in the form of <em>key-value</em> pairs.
* @see TestPropertySource#properties()
*/
String[] getProperties() {
return this.properties;
}
/**
* Determine if the supplied object is equal to this {@code MergedTestPropertySources}
* instance by comparing both objects' {@linkplain #getPropertySourceDescriptors()
* descriptors} and {@linkplain #getProperties() properties}.
* @since 5.3
*/
@Override
public boolean equals(@Nullable Object other) {
if (this == other) {
return true;
}
if (other == null || other.getClass() != getClass()) {
return false;
}
MergedTestPropertySources that = (MergedTestPropertySources) other;
if (!this.descriptors.equals(that.descriptors)) {
return false;
}
if (!Arrays.equals(this.properties, that.properties)) {
return false;
}
return true;
}
/**
* Generate a unique hash code for all properties of this
* {@code MergedTestPropertySources} instance.
* @since 5.3
*/
@Override
public int hashCode() {
int result = this.descriptors.hashCode();
result = 31 * result + Arrays.hashCode(this.properties);
return result;
}
/**
* Provide a String representation of this {@code MergedTestPropertySources}
* instance.
* @since 5.3
*/
@Override
public String toString() {
return new ToStringCreator(this, new DefaultToStringStyler(new SimpleValueStyler()))
.append("descriptors", this.descriptors)
.append("properties", this.properties)
.toString();
}
}
|
package hadoop.inputformat.db;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class DbImprotApp {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err
.println("Usage: <input path> <output path>");
System.exit(-1);
}
Job job = Job.getInstance();
Configuration conf = job.getConfiguration();
job.setJarByClass(DbImprotApp.class);
job.setJobName("db import");
/*FileInputFormat.addInputPath(job, new Path(args[0]));*/
FileOutputFormat.setOutputPath(job, new Path(args[1]));
DBConfiguration.configureDB(conf,"com.mysql.jdbc.Driver","jdbc:mysql://192.168.6.14:3306/dwh","xiang","nEw-TESt@&2#");
DBInputFormat.setInput(job,UserWritable.class,"select id,name from base_user","select count(*) from base_user");
job.setInputFormatClass(DBInputFormat.class);
job.setMapperClass(DbImportMapper.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
|
/**
* @author Dylan Ragaishis (Dylanrr)
*/
package hw4;
/**
* Abstract scoring category class that checks if the current hand satisfies the FullHouse category
* @extends addScoreAbstract
* @see hw4.addScoreAbstract()
* @see hw4.mainAbstract()
*/
public class FullHouse extends addScoreAbstract{
/**
* Constructs a FullHouse category with the given display name and score.
* @param name name of this category
* @param score score awarded for a hand that satisfies this category
*/
public FullHouse(java.lang.String name, int score){
super(name, score);
}
/**
* {@inheritDoc}
*/
public boolean isSatisfiedBy(Hand hand){
int[] values = hand.getAllValues();
int set1 = -1, set1Count = 0;
int set2 = -1, set2Count = 0;
for(int i=0; i<values.length; i++){ //Iterates through array checking each element
if (set1 == -1) { //If cat 1 has not been set, set it and +1 to the cat 1 counter
set1 = values[i];
set1Count++;
}
else if(values[i] == set1) //Check is the next current element is equal to cat1 if so +1 to the cat1 counter
set1Count++;
else if (set2 == -1) { //If cat 2 has not been set, set it and +1 to the cat 2 counter
set2 = values[i];
set2Count++;
}
else if(values[i] == set2) //Check is the next current element is equal to cat2 if so +1 to the cat2 counter
set2Count++;
}
return (((set1Count == (values.length / 2)) && (set2Count == (values.length / 2))) ||
((set1Count == (values.length / 2)+1) && (set2Count == (values.length / 2))) ||
((set1Count == (values.length / 2)) && ((set2Count == (values.length / 2)+1)))) ? true : false;
} //Returns true if (Even: cat1 counter = cat2 counter Odd: cat1 counter is +1 than cat2 counter & vice versa) els returns false
} //Instead of comparing cat counter we compare the counters to the length of array /2 or length of array /2 +1
|
package com.ca.rs;
import java.time.format.DateTimeFormatter;
import static java.time.format.DateTimeFormatter.ofPattern;
import static java.util.TimeZone.getDefault;
public class Constants {
public static final DateTimeFormatter TIMESTAMP_FORMAT =
ofPattern("HH:mm - d MMM YYYY").withZone(getDefault().toZoneId());
public static final int RANDOM_CASEID_LENGTH_OF_STRING = 36;
} |
/*
* (C) Mississippi State University 2009
*
* The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is
* a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries
* and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in
* http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in
* all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html.
*/
//Animation.java
//Defines a class for doing thread-safe periodic animation.
//Davis Herring
//Created July 20 2002
//Updated April 7 2004
//Version 1.31
package org.webtop.util;
/**
* An instance of <code>Animation</code> controls an animation or other
* periodic process. The calculation is performed by an instance of
* <code>AnimationEngine</code>; the relationship is analogous to that of
* <code>Thread</code> and <code>Runnable</code>. <code>Animation</code> can
* be subclassed to provide functionality, or an instance of
* <code>AnimationEngine</code> can be given it upon construction, and it will
* be used for the calculations.
*
* <p>An object implementing the <code>Animation.Data</code> interface can be
* used to provide parameters to the engine without risk of interference in
* its calculations.
*
* <p>No <code>Animation</code> method is blocking; it will not wait for some
* action to be taken by the animation thread (like completing the current
* execution). It is thus impossible for a thread's accessing an
* <code>Animation</code> object to cause deadlock with the animation thread,
* even if the animation thread must (for other reasons) wait on some action
* of the client thread. This is true for any number of client threads:
* although behavior can become erratic if conflicting requests are made of
* the <code>Animation</code>, it will always be in a functional state
* consistent with (at least some of) the calls made to it.
*
* <p>The animation thread is created and started before the
* <code>Animation</code> constructor returns, or is never started if the
* <code>Animation</code> constructor completes abruptly. The default state
* for an <code>Animation</code> is not playing (and not paused), so the
* thread will not perform any calculations until calls to
* <code>setPlaying()</code> and/or <code>update()</code> are made.
*/
public class Animation extends Thread implements AnimationEngine
{
/**
* An interface for an arbitrary data object given to the animation engine.
* <code>Animation</code> objects must be able to replicate these objects to
* guarantee that supplying new data will not affect data in use.
*/
public interface Data {
/**
* Returns a replica of this object. Should generally return an object of
* the same type as the original. Should not return null.
*/
public Data copy();
}
/**
* The number of <code>Animation</code> threads thus far created.
*/
private static int animationCounter;
/**
* Returns the next thread ID number.
*/
private static synchronized int getNextCtr() {return animationCounter++;}
private final AnimationEngine engine;
private Data data,inData; //data is used; inData is assigned to
private volatile long period,minDelay; //all in milliseconds
private Object lock=new Object(); //for synchronization
//These flags have a hierarchy of importance reflected by their order here;
//if a variable is true the variables above it are ignored.
//pause==true is distinct from setting play=false in that play's prior value
//is masked instead of destroyed.
//The manner in which pause and update are handled suggests that a different
//implementation style (perhaps busy-updating so long as a widget is pausing
//us) may be better/faster. If so, mea culpa and good luck. [Davis]
//The thread must be notify()-ed when a 'not-playing' condition is to be
//exited!
private volatile boolean play, //If true, animate continually
pause, //If true, don't animate
update, //If true, execute exactly one update without time-stepping
seppuku; //If true, kill thread
private boolean interFrame=true;
/**
* Constructs an <code>Animation</code> running the given
* <code>AnimationEngine</code> object. The engine parameter may not be
* null. See next constructor for other parameter details.
*/
public Animation(AnimationEngine e,Data d,long p) {this(e,d,p,false);}
/**
* Constructs a self-running <code>Animation</code> with the given period
* and data object. This constructor is for the use of classes that
* subclass <code>Animation</code> to provide functionality.
*
* @param p the number of milliseconds between animation frames.
* @param d the <code>Data</code> object containing whatever parameters are
* needed by the calculations. May be null without error;
* however, if it is not null, then <code>getData()</code> will
* never return null (which is useful).
*/
protected Animation(long p,Data d) {this(null,d,p,true);}
private Animation(AnimationEngine e,Data d,long p,boolean subclass) {
super("WebTOP Animation Thread #"+getNextCtr());
//DEBUG:
//ThreadWatch.add(this);
if(!subclass && e==null)
throw new NullPointerException("No AnimationEngine to use.");
engine=(subclass?this:e);
setPeriod(p);
data=d;
engine.init(this);
start(); //Thread automatically runs, pausing immediately
}
/**
* Returns the period of this <code>Animation</code>.
*
* @return the period of this animation (in milliseconds).
*/
public long getPeriod() {return period;}
/**
* Sets the period of this <code>Animation</code>.
*
* @param p the new period for this animation (in milliseconds).
* @exception IllegalArgumentException if <code>p</code> is not positive.
*/
public void setPeriod(long p) {
if(p<=0) throw new IllegalArgumentException("Negative period: "+p);
period=p;
}
/**
* Returns the minimum amount of time this animation will wait between
* frames.
*
* @return the minimum delay time of this animation (in milliseconds).
*/
public long getMinDelay() {return minDelay;}
/**
* Specifies the minimum amount of time this animation must wait between
* frames.
*
* @param d the new minimum delay time for this animation (in milliseconds).
* @exception IllegalArgumentException if <code>d</code> is not positive.
*/
public void setMinDelay(long d) {
if(d<0 || d>=period)
throw new IllegalArgumentException("Delay value "+d+
" not on [0,period ("+period+")].");
minDelay=d;
}
/**
* Returns the data object associated with this <code>Animation</code>.
* There is no guarantee that objects returned by successive calls to
* getData() will be the same or that they will be different. However,
* getData() will only return null if no <code>Data</code> object was
* specified at construction and setData() has never been called for this
* <code>Animation</code>. Once getData() returns non-null for a given
* <code>Animation</code>, it will never again return null for that object.
*
* <p>The object returned by getData() may be modified and used with
* setData(); however, if multiple client threads invoke setData() and/or
* modify the return value of getData(), they must handle the
* synchronization to guarantee data is not lost or overwritten.
*
* @return a reference to a <code>Data</code> object, either the object most
* recently given to setData(), or a newly allocated object
* equivalent to the object currently in use.
*/
public Data getData() {
synchronized(lock) {return (inData==null&&data!=null)?data.copy():inData;}
}
/**
* Sets the data object to be used by this <code>Animation</code>. This may
* be invoked at any time without risk to the animation thread. Until the
* next animation frame, the provided data object will simply be held (and
* can thus be modified with the expected effects); at the next animation
* frame (whether the calculation is performed or not), the most recent
* value provided through setData() will be copied and no longer referenced
* by this <code>Animation</code>. Because it can be difficult to determine
* the status of the animation thread, calling setData() whenever a change
* is to be effected is the most reliable method.
*
* @param the <code>Data<code> object to use for subsequent iterations of
* the animation. Use null to discard any pending data and keep
* the object currently in use.
*/
public void setData(Data d) {
synchronized(lock) {inData=d;}
}
//There is little need for interrupt()-ion here; notify() if thread may be
//wait()-ing, but otherwise state change(s) will be properly effected at
//sleep()'s end.
/**
* Activates or deactivates this <code>Animation</code>. Note that if the
* animation is paused at the time of a <code>setPlaying(true)</code> call,
* the pause will remain in effect and no animation will occur until it is
* released.
*
* @param doPlay whether to proceed with the animation.
*/
public void setPlaying(boolean doPlay) {
synchronized(lock) {
play=doPlay;
if(isRunning())
lock.notify(); //Wake up the stoppy thread
}
}
/**
* Suspends or resumes the operation of this <code>Animation</code>,
* overriding its 'playing' state (as affected by
* <code>setPlaying()</code>). Use to temporarily stop the animation and
* then to resume its previous state.
*
* <p>Note that calling <code>setPaused(false)</code> does not guarantee
* animation; it simply allows it (this <code>Animation</code> must be set
* to play to animate). Also, there is no guarantee that the change in the
* animation's state will be effected before this method returns.
*
* @param noPlay true to halt animation; false to allow it to continue.
*/
public void setPaused(boolean noPlay) {
synchronized(lock) {
pause=noPlay;
if(isRunning())
lock.notify(); //Wake up the sleepy thread
}
}
/**
* Forces exactly one update as soon as possible, indicating to the engine
* for this iteration that no 'time' has passed.
*/
public void update() {
synchronized(lock) {
update=true;
//Might as well keep the lock, since isRunning() needs it
if(!isRunning())
interrupt(); //Wake up the lazy thread
}
//It makes sense to give the animation thread a chance to DO something now.
Thread.yield();
}
/**
* Attempts to perform an update in the calling thread. Returns true if
* successful; if the animation thread is already performing an update,
* immediately returns false. Using this method can be more efficient than
* using (just) <code>update()</code> when many updates are needed.
*/
public boolean updateHere() {
synchronized(lock) {
if(interFrame) {
grabData();
if(engine.timeElapsed(0)) engine.execute(data);
return true;
} else return false;
}
}
/**
* Stops the <code>Animation</code> permanently and destroys its thread.
* Once killed, the <code>Animation</code> cannot be restarted.
*
* <p>Note that the thread may not actually die before this method returns;
* <code>isAlive()</code> can be used to check if needed.
*/
public void kill() {
seppuku=true;
interrupt();
}
/**
* Checks whether this <code>Animation</code> is currently set to run.
*
* @return the most recent value passed to <code>setPlaying()</code>, or
* false if that function has never been called for this object.
*/
public boolean isPlaying() {return play;}
/**
* Checks whether this <code>Animation</code> is currently being prevented
* from running.
*
* @return the most recent value passed to <code>setPaused()</code>, or
* false if that function has never been called for this object.
*/
public boolean isPaused() {return pause;}
/**
* Checks whether this <code>Animation</code> is currently running.
*
* @return true if this object is set to play and is not paused.
*/
public boolean isRunning() {
//This uses two variables, and should thus be synchronized.
synchronized(lock) {return play&&!pause;}
}
//Must be synchronized on lock to call this method.
private void grabData() {
if(inData!=null) { //data for me!
data=inData.copy(); //only we can see the real data
inData=null;
}
}
/**
* Runs the animation.
*/
public final void run() {
long iterTime=-1,_period=period; // iterTime: start of [last] iteration
while(!seppuku) {
if(_period!=period) {
_period=period;
//Should there be more complicated behavior here? If so, there likely
//needs to be synchronization (or at least a local copy of period).
}
//DebugPrinter.println("\ni/"+System.currentTimeMillis()%1000);
boolean immediate; //will be true if update is
synchronized(lock) {
if(!update&&!isRunning()) {
//Whether we finish or are interrupted, start over to see changes.
try{lock.wait();} catch(InterruptedException e) {}
iterTime=-1;
continue;
}
//We're animating, or update is set, so calculate.
grabData();
immediate=update;
update=false;
interFrame=false;
}
//If it's an update(), it's been "0 time"; else, if we've just begun
//running, it's been the ideal "1 period" by definition. Otherwise see
//how far behind we may have gotten:
final float periods=immediate?0:iterTime==-1?1:
(System.currentTimeMillis()-iterTime)/(float)_period;
iterTime=System.currentTimeMillis();
if(engine.timeElapsed(periods)) engine.execute(data);
synchronized(lock) {interFrame=true;}
if(!update) { // skip attempt at sleep for efficiency
final long tPrime=System.currentTimeMillis();
do {
final long left=Math.max(iterTime+_period-tPrime,minDelay)-
(tPrime-System.currentTimeMillis()); // already slept this much
if(left<=0) break; // no more to sleep!
try {
sleep(left);
break; // sleep successful
} catch(InterruptedException e) {}
} while(!update && !seppuku); // stop trying to sleep if there's news
}
}
}
//These functions implement AnimationEngine minimally.
public void init(Animation a) {}
//Returns true because returning false would always have to be overridden.
public boolean timeElapsed(float periods) {return true;}
public void execute(Data d) {}
/*public static void main(String[] args) throws java.io.IOException {
Animation me=new Animation(500,null) {
long millis;
public boolean timeElapsed(float periods)
{System.out.println("te: "+periods); millis+=15*periods; return true;}
public void execute(Animation.Data d) {
System.out.print("exe");
try{sleep(millis);}catch(InterruptedException e){}
System.out.print('!');
try{sleep(millis);}catch(InterruptedException e){}
System.out.print('\n');
}
};
me.setPlaying(true);
System.in.read();
me.kill();
}*/
}
|
package com.kachunchan.javamediaplayer.controller;
import com.kachunchan.javamediaplayer.model.MediaLibrary;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaException;
import javafx.scene.media.MediaPlayer;
import javafx.stage.DirectoryChooser;
import javafx.util.Callback;
import java.io.File;
import java.nio.file.Path;
/*
* This class will respond to the user interactions.
*/
public class Controller {
// These instance variables are used to hold the loaded files and the list that is displayed on the GUI.
private final MediaLibrary mediaLibrary;
private final ObservableList<Path> viewableMediaLibrary;
// An array of strings is used to hold the supported file extensions.
private final String[] acceptedFileType;
// These instance variables are used to hold the media player, the selected file from the GUI, and the
// current file loaded to the media player.
private MediaPlayer mediaPlayer;
private Path selectedFile;
private Path loadedFile;
@FXML
private BorderPane borderPane;
@FXML
private Label selectedSongName;
@FXML
private ListView<Path> libraryListView;
public Controller() {
mediaLibrary = new MediaLibrary();
viewableMediaLibrary = FXCollections.observableArrayList();
acceptedFileType = new String[]{".mp3", ".wav"};
}
// Initialises the GUI screen.
public void initialize() {
initialiseLibraryListView();
initializeListener();
}
// Initialises GUI library list view
private void initialiseLibraryListView() {
libraryListView.setItems(viewableMediaLibrary);
// Cell factory added in to display only the filename rather than the whole path of the file.
libraryListView.setCellFactory(new Callback<>() {
@Override
public ListCell<Path> call(ListView<Path> param) {
ListCell<Path> cell = new ListCell<>() {
@Override
protected void updateItem(Path item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
} else {
setText(item.getFileName().toString());
}
}
};
return cell;
}
});
}
// Initialises the listeners for mouse clicks and key presses for the library list view.
private void initializeListener() {
libraryListView.setOnMouseClicked(click -> {
if (libraryListView.getSelectionModel().getSelectedItem() == null) {
return;
}
if (click.getButton().equals(MouseButton.PRIMARY)) {
processPrimaryMouseClicked(click);
}
});
libraryListView.setOnKeyPressed(event -> {
Path currentItemSelected = libraryListView.getSelectionModel().getSelectedItem();
if (currentItemSelected == null) {
return;
}
if (event.getCode().equals(KeyCode.ENTER)) {
selectedFile = currentItemSelected;
loadedFile = selectedFile;
forcePlayMedia();
}
});
}
// Add in what primary mouse click will perform in here.
private void processPrimaryMouseClicked(MouseEvent click) {
if (click.getClickCount() == 2) {
processDoublePrimaryMouseClick(click);
} else {
processSinglePrimaryMouseClick(click);
}
}
// An item on the library list view can be selected when it has be clicked on and
// can be deselected when it has been clicked on again with a brief pause in between each clicks.
private void processSinglePrimaryMouseClick(MouseEvent click) {
Path currentItemSelected = libraryListView.getSelectionModel().getSelectedItem();
if (currentItemSelected.equals(selectedFile)) {
selectedFile = null;
libraryListView.getSelectionModel().clearSelection();
} else {
selectedFile = currentItemSelected;
}
}
// Double clicking an item on the library list view will play the selected item.
// Double clicking on the same item that is currently playing will restart the media.
private void processDoublePrimaryMouseClick(MouseEvent click) {
selectedFile = libraryListView.getSelectionModel().getSelectedItem();
loadedFile = selectedFile;
forcePlayMedia();
}
public void handleOpenDirectory() {
File directory = getDirectoryEntry();
if (directory != null) {
mediaLibrary.loadItemsToMediaLibrary(directory.toPath(), acceptedFileType);
viewableMediaLibrary.clear();
viewableMediaLibrary.addAll(mediaLibrary.getMediaLibrary());
}
}
public void forcePlayMedia() {
if (mediaPlayer != null) {
mediaPlayer.stop();
}
try {
if (loadedFile != null) {
mediaPlayer = new MediaPlayer(new Media(loadedFile.toUri().toString()));
}
} catch (MediaException e) {
System.out.println("Media cannot be opened.");
e.printStackTrace();
}
playMedia();
}
public void playMedia() {
if (loadedFile == null) {
return;
}
mediaPlayer.play();
statusMessage("Playing " + loadedFile.toString());
}
public void pauseMedia() {
if (loadedFile == null) {
return;
}
mediaPlayer.pause();
statusMessage("Paused playing " + loadedFile.toString());
}
public void stopMedia() {
if (loadedFile == null) {
return;
}
mediaPlayer.stop();
statusMessage("Stopped playing " + loadedFile.toString());
}
// Updates the status message on the GUI.
private void statusMessage(String message) {
selectedSongName.setText(message);
}
// Returns the directory selected by the user
private File getDirectoryEntry() {
return (new DirectoryChooser()).showDialog(borderPane.getScene().getWindow());
}
} |
package com.ChrisIngram;
public class VehicleInfo {
private int VIN;
private double odometer;
private double consumption;
private double lastOilChange;
private double engineSizeInL;
public int getVIN() {
return VIN;
}
public void setVIN(int VIN) {
this.VIN = VIN;
}
public double getOdometer() {
return odometer;
}
public void setOdometer(double odometer) {
this.odometer = odometer;
}
public double getConsumption() {
return consumption;
}
public void setConsumption(double consumption) {
this.consumption = consumption;
}
public double getLastOilChange() {
return lastOilChange;
}
public void setLastOilChange(double lastOilChange) {
this.lastOilChange = lastOilChange;
}
public double getEngineSizeInL() {
return engineSizeInL;
}
public void setEngineSizeInL(double engineSizeInL) {
this.engineSizeInL = engineSizeInL;
}
}
|
package walke.base.tool;
import android.content.Context;
import android.content.SharedPreferences;
public class SharepreUtil {
public static SharedPreferences getSharedPreferences(Context context) {
return context.getSharedPreferences("isSave", Context.MODE_PRIVATE);
}
public static void putBoolean(Context context, String key, boolean value) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static void putString(Context context, String key, String value) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public static boolean getBoolean(Context context, String key, boolean defValue) {
return getSharedPreferences(context).getBoolean(key, defValue);
}
public static String getString(Context context, String key) {
return getSharedPreferences(context).getString(key, null);
}
public static void putIntTimes(Context context, String key, int times) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key,times);
editor.commit();
}
public static int getIntTimes(Context context, String key,int defaultTimes) {
return getSharedPreferences(context).getInt(key,defaultTimes);
}
}
|
package sr.hakrinbank.intranet.api.service;
import sr.hakrinbank.intranet.api.model.BlackListedPersonRetailBanking;
import java.util.List;
/**
* Created by clint on 5/29/17.
*/
public interface BlackListedPersonRetailBankingService {
List<BlackListedPersonRetailBanking> findAllBlackListedPersonRetailBanking();
BlackListedPersonRetailBanking findById(long id);
void updateBlackListedPersonRetailBanking(BlackListedPersonRetailBanking module);
List<BlackListedPersonRetailBanking> findAllActiveBlackListedPersonRetailBanking();
BlackListedPersonRetailBanking findByName(String name);
List<BlackListedPersonRetailBanking> findAllActiveBlackListedPersonRetailBankingBySearchQuery(String qry);
int countBlackListedPersonRetailBankingOfTheWeek();
List<BlackListedPersonRetailBanking> findAllActiveBlackListedPersonRetailBankingOrderedByDate();
List<BlackListedPersonRetailBanking> findAllActiveBlackListedPersonRetailBankingByDate(String date);
List<BlackListedPersonRetailBanking> findAllActiveBlackListedPersonRetailBankingBySearchQueryOrDate(String characters, String date);
}
|
package bean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Boolean isValid = false;
try {
ConnectToDb conn = new ConnectToDb();
Connection connection = conn.connect();
Statement statement = connection.createStatement();
ResultSet resultSet = null;
String role = request.getParameter("role");
if ("student".equals(role)) {
String sql = "select * from bkxk.student_info";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
if (request.getParameter("username").equals(resultSet.getString("s_id")) && request.getParameter("password").equals(resultSet.getString("s_key"))) {
isValid = true;
request.setAttribute("username", request.getParameter("username"));
request.getRequestDispatcher("stu_main.jsp").forward(request, response);
}
}
} else if ("teacher".equals(role)) {
String sql = "select * from bkxk.teacher_info";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
if (request.getParameter("username").equals(resultSet.getString("t_id")) && request.getParameter("password").equals(resultSet.getString("t_key"))) {
isValid = true;
request.setAttribute("username", request.getParameter("username"));
request.getRequestDispatcher("teacher_main.jsp").forward(request, response);
}
}
} else if ("admin".equals(role)) {
String sql = "select * from bkxk.admin_info";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
if (request.getParameter("username").equals(resultSet.getString("a_id")) && request.getParameter("password").equals(resultSet.getString("a_key"))) {
isValid = true;
request.setAttribute("username", request.getParameter("username"));
request.getRequestDispatcher("admin_main.jsp").forward(request, response);
}
}
}
if (resultSet != null) {
resultSet.close();
}
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (!isValid) {
request.setAttribute("msg", "�û����������������������..");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
|
package cn.itheima.methodPractice;
public class GetArrayPrint {
/*
9、定义一个方法,它可以接收一个int类型数组,并遍历输出数组中的元素。
在main方法中调用该方法。(有参数无返回值)
*/
public static void main(String[] args) {
int[] arr = {11, 22, 33, 44, 55};
printArray(arr);
}
private static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
|
package com.ipartek.formacion.nombreproyecto.ejercicios;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* Ejercicio para buscar en la tabla 'persona' todas las que contenga su email
* la cadena de texto "spambob"
*
* @author ur00
*
*/
public class BuscarPersonasByEmail {
// CONSTANTES PARA CONEXION DE BBDD
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String SERVER = "127.0.0.1";
private static final String DATABASE = "javabasic";
private static final String USER = "root";
private static final String PASS = "";
private static final String PORT = "3306";
static String consulta = "select id, nombre, email from persona where email like '%spambob%';";
public static void main(String[] args) throws Exception {
Class.forName(DRIVER);
Connection conexion = DriverManager.getConnection("jdbc:mysql://" + SERVER + ":" + PORT + "/" + DATABASE, USER, PASS);
PreparedStatement pst = conexion.prepareStatement(consulta);
ResultSet rs = pst.executeQuery();
while ( rs.next() ){
System.out.println("id: " + rs.getInt("id") );
System.out.println("nombre: " + rs.getString("nombre") );
System.out.println("email: " + rs.getString("email") );
System.out.println("--------------------------------" );
}
rs.close();
pst.close();
conexion.close();
}
}
|
package com.social.server.dao;
import com.social.server.entity.Dialog;
import com.social.server.entity.User;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashSet;
@RunWith(SpringRunner.class)
public class DialogRepositoryTest extends CommonTestRepository {
@Autowired
private DialogRepository dialogRepository;
private User user1;
private User user2;
private User user3;
private User user4;
private User user5;
@Before
public void setUp() {
user1 = createUser();
user2 = createUser();
user3 = createUser();
user4 = createUser();
user5 = createUser();
createExpectedDialog("EXPECTED", user1, user2);
createExpectedDialog("EXPECTED", user1, user4);
createExpectedDialog("FAKE", user3, user4);
createExpectedDialog("FAKE", user4, user5);
}
@Test
public void dialogListByUserIdTest() {
Page<Dialog> dialogs = dialogRepository.findByUsersIdInOrderByDateLastMessageDesc(user1.getId(), pagination);
Assert.assertEquals(dialogs.getContent().size(), 2);
dialogs.getContent().forEach((d) -> Assert.assertEquals(d.getLastMessage(), "EXPECTED"));
}
@Test
public void dialogByUsersIdTest() {
Dialog dialog = dialogRepository.findOneByUsersId(new HashSet<>(Arrays.asList(user1.getId(), user2.getId())));
Assert.assertNotNull(dialog);
dialog = dialogRepository.findOneByUsersId(new HashSet<>(Arrays.asList(user1.getId(), user4.getId())));
Assert.assertNotNull(dialog);
dialog = dialogRepository.findOneByUsersId(new HashSet<>(Arrays.asList(user3.getId(), user4.getId())));
Assert.assertNotNull(dialog);
dialog = dialogRepository.findOneByUsersId(new HashSet<>(Arrays.asList(user4.getId(), user5.getId())));
Assert.assertNotNull(dialog);
dialog = dialogRepository.findOneByUsersId(new HashSet<>(Arrays.asList(user2.getId(), user5.getId())));
Assert.assertNull(dialog);
dialog = dialogRepository.findOneByUsersId(new HashSet<>(Arrays.asList(user1.getId(), user3.getId())));
Assert.assertNull(dialog);
}
private void createExpectedDialog(String lastMessage, User... users) {
Dialog dialog = new Dialog();
dialog.setDateLastMessage(LocalDateTime.now());
dialog.setLastMessage(lastMessage);
dialog.setUsers(new HashSet<>(Arrays.asList(users)));
entityManager.persist(dialog);
}
}
|
import java.util.Scanner;
public class Java_Paradigmas_Progamacao {
public static void main(String[] args) {
float num1, num2;
char op;
Scanner s = new Scanner(System.in);
System.out.print("Informe o primeiro número: ");
num1 = s.nextInt();
System.out.print("Informe o segundo número: ");
num2 = s.nextInt();
System.out.print("Informe a operação a ser utilizada [ +, -, *, / ]: ");
op = s.next().charAt(0);
switch (op) {
case '+':
System.out.printf("%.2f + %.2f = %.2f", num1, num2, (num1 + num2));
break;
case '-':
System.out.printf("%.2f - %.2f = %.2f", num1, num2, (num1 - num2));
break;
case '*':
System.out.printf("%.2f * %.2f = %.2f", num1, num2, (num1 * num2));
break;
case '/':
System.out.printf("%.2f / %.2f = %.2f", num1, num2, (num1 / num2));
break;
}
}
}
|
/*
* 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.jclouds.openstack.glance.v1_0.features;
import static org.testng.Assert.assertEquals;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.openstack.glance.v1_0.GlanceApi;
import org.jclouds.openstack.glance.v1_0.internal.BaseGlanceExpectTest;
import org.jclouds.openstack.glance.v1_0.parse.ParseImagesTest;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "GlanceVersionNegotiationExpectTest")
public class GlanceVersionNegotiationExpectTest extends BaseGlanceExpectTest {
/*
* Test that if Glance returns a URL for a version with a different scheme
* than we used for the base endpoint we use the scheme associated w/ the
* base endpoint.
*
* This is useful for when Glance is behind a proxy.
*/
public void testSchemeMismatch() throws Exception {
// The referenced resource contains http endpoints for versions instead of the https endpoint returned by Keystone
versionNegotiationResponse = HttpResponse.builder().statusCode(300).message("HTTP/1.1 300 Multiple Choices").payload(
payloadFromResourceWithContentType("/glanceVersionResponseSchemeMismatch.json", "application/json")).build();
HttpRequest list = HttpRequest.builder().method("GET")
.endpoint("https://glance.jclouds.org:9292/v1.0/images")
.addHeader("Accept", "application/json")
.addHeader("X-Auth-Token", authToken).build();
HttpResponse listResponse = HttpResponse.builder().statusCode(200)
.payload(payloadFromResource("/images.json")).build();
GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword,
responseWithKeystoneAccess, versionNegotiationRequest, versionNegotiationResponse,
list, listResponse);
assertEquals(apiWhenExist.getImageApi("az-1.region-a.geo-1").list().concat().toString(),
new ParseImagesTest().expected().toString());
}
/*
* Test that Glance version negotiation fails with an exception if there is
* no endpoint returned for the requested version.
*/
@Test(expectedExceptions = UnsupportedOperationException.class)
public void testNonExistentVersion() throws Exception {
// The referenced resource only an endpoint for v999.999 of the GlanceApi
HttpResponse localVersionNegotiationResponse = HttpResponse.builder().statusCode(300).message("HTTP/1.1 300 Multiple Choices").payload(
payloadFromResourceWithContentType("/glanceVersionResponseVersionUnavailable.json", "application/json")).build();
GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword,
responseWithKeystoneAccess, versionNegotiationRequest, localVersionNegotiationResponse);
apiWhenExist.getImageApi("az-1.region-a.geo-1").list();
}
/*
* Test that Glance version negotiation happens with the base endpoint if
* the Keystone catalog returns an already versioned endpoint for Glance
*/
public void testKeystoneReturnsVersionedEndpoint() throws Exception {
// This sets the keystone response to return a Glance endpoint w/ version already present
HttpResponse localResponseWithKeystoneAccess = HttpResponse.builder().statusCode(200).message("HTTP/1.1 200").payload(
payloadFromResourceWithContentType("/keystoneAuthResponseVersionedGlanceEndpoint.json", "application/json")).build();
HttpRequest list = HttpRequest.builder().method("GET")
.endpoint("https://glance.jclouds.org:9292/v1.0/images")
.addHeader("Accept", "application/json")
.addHeader("X-Auth-Token", authToken).build();
HttpResponse listResponse = HttpResponse.builder().statusCode(200)
.payload(payloadFromResource("/images.json")).build();
GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword,
localResponseWithKeystoneAccess, versionNegotiationRequest, versionNegotiationResponse,
list, listResponse);
assertEquals(apiWhenExist.getImageApi("az-1.region-a.geo-1").list().concat().toString(),
new ParseImagesTest().expected().toString());
}
}
|
package com.lambda.test;
/**
*
*
* @author IBM
*/
public class RunnableTest {
public static void main(String... args){
//Normal expression
Runnable run1 = new Runnable(){
@Override
public void run(){
System.out.println("Hello World!!!");
}
};
//With lambda expression
Runnable run2 = ()->System.out.println("Hello lambda !!!");
run1.run();
run2.run();
}
}
|
/*
* @(#) EbmsContainerLogDAO.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ebms.ebmscontainerlog.dao.impl;
import java.util.List;
import com.esum.appframework.exception.ApplicationException;
import com.esum.appframework.dao.impl.SqlMapDAO;
import com.esum.wp.ebms.ebmscontainerlog.dao.IEbmsContainerLogDAO;
/**
*
* @author heowon@esumtech.com
* @version $Revision: 1.1 $ $Date: 2007/06/20 00:46:00 $
*/
public class EbmsContainerLogDAO extends SqlMapDAO implements IEbmsContainerLogDAO {
/**
* Default constructor. Can be used in place of getInstance()
*/
public EbmsContainerLogDAO () {}
public String selectPageListID = "";
public String getSelectPageListID() {
return selectPageListID;
}
public void setSelectPageListID(String selectPageListID) {
this.selectPageListID = selectPageListID;
}
public List selectPageList(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(selectPageListID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
} |
package com.ucl.request;
import com.ucl.common.Pagination;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
/**
* Created by jiang.zheng on 2017/9/18.
*/
public class OrderRequest extends Pagination {
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date startDate;
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date endDate;
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@Override
public String toString() {
return "OrderRequest{" +
"startDate=" + startDate +
", endDate=" + endDate +
'}';
}
}
|
package com.fehead.community.mapper;
import com.fehead.community.entities.ActivityUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ktoking
* @since 2020-04-03
*/
public interface ActivityUserMapper extends BaseMapper<ActivityUser> {
}
|
package hopper;
import hopper.GUI.MainGUI;
import hopper.GUI.MapDisplay;
import hopper.GUI.TestGUIController;
import hopper.interpreter.CollectCommand;
import hopper.interpreter.Command;
import hopper.interpreter.CommandQueue;
import hopper.interpreter.MapCommand;
import hopper.mapping.Garbage;
import hopper.mapping.MapRepresentation;
import hopper.mapping.PathCoordinate;
import hopper.mapping.Pivot;
import java.util.ArrayList;
import javaclient3.structures.fiducial.PlayerFiducialItem;
/**
* The Robot Controller is a singleton class that is responsible for controlling the individual robots
* and collecting data from them. It interprets a queue of commands passed on by the user via the terminal arguments,
* acts upon them, and thus contains helper methods to order the robot(s) to explore, collect garbage and export the
* aggregate map representation/data to an image file.
*
* @author Team Hopper
*
*/
public class RobotController implements SimplebotValueDelegate {
public static final boolean DEBUG_PRINT_MODE = true;
private static RobotController globalInstance = null;
private static final int kHopperNumberOfRobots = 3;
//State variables
public boolean multiMode;
public boolean exploring;
public boolean collecting;
/**
* Singleton method that returns the one Robot Controller of the app's runtime.
* @return the main <code>RobotController</code> object
*/
public static RobotController getController() {
if (globalInstance == null) {
globalInstance = new RobotController();
}
return globalInstance;
}
private CommandQueue commands;
private Destinationbot[] robots;
private MapRepresentation map;
private MapDisplay mapDisplay;
private boolean startedCollecting;
public ArrayList<Garbage> garbagesToCollect;
/**
* Creates a new robot controller.
*/
public RobotController() {
this.commands = new CommandQueue();
this.robots = new Destinationbot[kHopperNumberOfRobots];
this.map = new MapRepresentation();
this.mapDisplay = new MapDisplay();
this.exploring = false;
this.multiMode = true;
this.startedCollecting = false;
}
/**
* Creates a new robot controller given the string array of arguments passed on from the main method.
* @param args the main method arguments to parse
*/
public RobotController(String[] args) {
this();
this.commands = new CommandQueue(args);
}
/**
* @return the controller's map representation object
*/
public MapRepresentation getMap() {
return this.map;
}
public void start(String[] args) {
HLog("Starting up robots");
Destinationbot bot = new Destinationbot(0, this);
Destinationbot bot2 = new Destinationbot(1, this);
Destinationbot bot3 = new Destinationbot(2, this);
Destinationbot[] bots = {bot, bot2, bot3};
this.robots = bots;
HLog("Starting, initiating commands");
HLog("Arguments: " + args);
this.commands = new CommandQueue(args);
if (DEBUG_PRINT_MODE) this.startTestGUI();
this.evaluateNextCommand();
}
public void evaluateNextCommand() {
HLog("Evaluating commands");
if (!this.commands.isEmpty()) {
boolean checkedCollect = false;
boolean checkedMap = false;
for (Command command : this.commands.getCommandList()) {
HLog("Checking commands for map and collect");
if (!checkedCollect && command.getIdentifier().equals(Command.kCommandCollect)) {
CollectCommand collecter = (CollectCommand)command;
this.getMap().collectionCoordinates = collecter.getCoordinates();
this.getMap().buildGarbageArea();
HLog("Built garbage area");
checkedCollect = true;
} else if (!checkedMap && command.getIdentifier().equals(Command.kCommandMap)) {
MapCommand mapper = (MapCommand)command;
this.getMap().mapFilename = mapper.getMapFilename();
checkedMap = true;
}
}
Command command = this.commands.removeFirstCommand();
if (command.getIdentifier().equals(Command.kCommandModeSolo)) {
this.multiMode = false;
this.evaluateNextCommand();
} else if (command.getIdentifier().equals(Command.kCommandModeMulti)) {
this.multiMode = true;
this.evaluateNextCommand();
} else if (command.getIdentifier().equals(Command.kCommandExplore)) {
this.exploring = true;
} else if (command.getIdentifier().equals(Command.kCommandCollect)) {
this.collecting = true;
HLog("Collecting!");
} else if (command.getIdentifier().equals(Command.kCommandMap)) {
this.getMap().saveToImageInPath(this.getMap().mapFilename);
this.evaluateNextCommand();
} else if (command.getIdentifier().equals(Command.kCommandGUI)) {
MainGUI gui = new MainGUI(this.robots);
this.commands = new CommandQueue(); //Do nothing after -gui
}
} else {
HLog("Done with commands");
}
}
/**
* Starts up the testing environment for the project.
*/
public void startTestGUI() {
TestGUIController GUI = new TestGUIController(this.robots[0]);
//TestGUIController GUI2 = new TestGUIController(bot2);
HLog("Showing map display as well");
this.mapDisplay = new MapDisplay(this.map, this.robots[0], this.robots);
this.mapDisplay.setVisible(true);
}
/**
* See SimplebotValueDelegate
*/
public void simplebotDidUpdateValues(Simplebot bot) {
this.processRobot((Destinationbot)bot);
}
private static double kRobotControllerMinimumRobotDistance = 2.3;
private void processRobot(Destinationbot bot) {
try {
if (this.exploring) {
this.exploreWithBot(bot);
} else if (this.collecting) {
this.collectWithBot(bot);
}
//HLog("GCA adjacents: " + this.getMap().garbageAreaCoordinate.getAdjacents().size());
this.mapDisplay.updateMap();
} catch (NullPointerException e) {
}
}
private void collectWithBot(Destinationbot bot) {
if (this.multiMode) {
for (Destinationbot otherBot : this.robots) {
if (otherBot.getIndex() != bot.getIndex()) {
double distance = bot.distanceFromRobot(otherBot.getCoordinate());
if (distance < kRobotControllerMinimumRobotDistance) { //Robots are too close to each other
if (bot.getIndex() < otherBot.getIndex()) {
bot.halt();
return;
}
}
}
}
}
if (bot.getIndex() == 0) { //Ignoring 'multi' or solo
//TODO check for nearbies
//HLog("Collecting");
if (!this.startedCollecting) {
HLog("Making a copy of the garbages to collect:");
ArrayList<Garbage> garbages = new ArrayList<Garbage>(0);
for (Garbage g : this.getMap().garbages) {
garbages.add(g);
HLog("Adding " + g);
}
this.garbagesToCollect = garbages;
this.startedCollecting = true;
} else if (!bot.isAssignedGarbage) {
if (this.garbagesToCollect.size() > 0) {
Garbage nextOne = this.garbagesToCollect.remove(0);
HLog("Next one to collect is " + nextOne);
bot.isAssignedGarbage = true;
bot.assignedGarbage = nextOne;
ArrayList<PathCoordinate> path = this.getMap().pathFromPathCoordinateToPathCoordinate(bot.currentPathCoordinate, nextOne);
HLog("Got path");
//System.out.println("");
if (path.size() > 0) {
bot.travelThroughPath(path);
HLog("Made bot travel through path");
} else {
HLog("Path is inaccessible.");
bot.isAssignedGarbage = false;
bot.assignedGarbage = null;
}
} else {
HLog("Collected all!");
this.collecting = false;
for (Destinationbot aBot : this.robots) {
aBot.halt();
}
this.evaluateNextCommand();
}
}
} else if (this.multiMode) {
this.exploreWallsWithBot(bot);
}
}
public static final double kRobotControllerSensorWallFollowingMinimumWallDistance = 1.25;
private static final double kRobotControllerSensorMinimumYawAlignmentDifference = 0.15;
private static final double kRobotControllerSensorExploringMinimumWallDistance = 0.9;
private void exploreWithBot(Destinationbot bot) {
//Check for nearby robots
if (this.multiMode) {
for (Destinationbot otherBot : this.robots) {
if (otherBot.getIndex() != bot.getIndex()) {
double distance = bot.distanceFromRobot(otherBot.getCoordinate());
System.out.println("Distance: " + distance);
if (distance < kRobotControllerMinimumRobotDistance) { //Robots are too close to each other
if (bot.getIndex() < otherBot.getIndex()) {
bot.halt();
return;
}
}
}
}
}
//update map etc
double front = bot.getSonarValues()[Simplebot.kSimplebotSonarFrontMiddle];
double right = bot.getSonarValues()[Simplebot.kSimplebotSonarRightMiddle];
double rightFront = bot.getSonarValues()[Simplebot.kSimplebotSonarRightFront];
double rightBack = bot.getSonarValues()[Simplebot.kSimplebotSonarRightBack];
double left = bot.getSonarValues()[Simplebot.kSimplebotSonarLeftMiddle];
double leftFront = bot.getSonarValues()[Simplebot.kSimplebotSonarLeftFront];
double leftBack = bot.getSonarValues()[Simplebot.kSimplebotSonarLeftBack];
double back = bot.getSonarValues()[Simplebot.kSimplebotSonarBackMiddle];
//HLog("Front: " + front + " Left: " + left);
double frontDiagRight = bot.getSonarValues()[Simplebot.kSimplebotSonarDiagonalTopRight];
double frontDiagLeft = bot.getSonarValues()[Simplebot.kSimplebotSonarDiagonalTopLeft];
double backDiagRight = bot.getSonarValues()[Simplebot.kSimplebotSonarDiagonalBottomRight];
double backDiagLeft = bot.getSonarValues()[Simplebot.kSimplebotSonarDiagonalBottomLeft];
boolean check = !this.multiMode ? bot.getIndex() == 0 : this.multiMode;
//System.out.println("Multi: " + this.multiMode + " Index: " + bot.getIndex());
//EXPLORATION
if (check) { //Use only one robot for wall-following in future
if (bot.getIndex() == 0) { //Explorer
this.exploreMapWithBot(bot);
} else { //Wall-followers
this.exploreWallsWithBot(bot);
}
}
//MAPPING
ArrayList<Coordinate> coords = new ArrayList<Coordinate>();
double[] rawCoords = {front, right, left, back, frontDiagRight, frontDiagLeft, backDiagRight, backDiagLeft};
int[] indexes = {Simplebot.kSimplebotSonarFrontMiddle, Simplebot.kSimplebotSonarRightMiddle, Simplebot.kSimplebotSonarLeftMiddle, Simplebot.kSimplebotSonarBackMiddle, Simplebot.kSimplebotSonarDiagonalTopRight, Simplebot.kSimplebotSonarDiagonalTopLeft, Simplebot.kSimplebotSonarDiagonalBottomRight, Simplebot.kSimplebotSonarDiagonalBottomLeft};
for (int i = 0; i < rawCoords.length; i++) {
if (rawCoords[i] < Simplebot.kSimplebotSonarRangeLimit) {
Coordinate offset = bot.coordinateOffsetForSonarValueIndex(indexes[i]);
Coordinate c = new Coordinate(bot.getX() + offset.getX(), bot.getY() + offset.getY());
boolean close = false;
for (Destinationbot robotCheck : this.robots) {
if (bot != robotCheck) {
close = close || robotCheck.coordinateIsNearRobot(c);
}
}
if (!close) coords.add(c);
}
}
if (coords.size() > 0) this.map.addWalls(coords);
}
private void exploreMapWithBot(Destinationbot bot) {
PlayerFiducialItem[] items = bot.getFiducialValues();
for (PlayerFiducialItem item : items) {
double adjacent = Math.abs(item.getPose().getPx()) + 0.2;
double opposite = Math.abs(item.getPose().getPy());
double angle = Math.toDegrees(Math.atan(opposite/adjacent));
angle = item.getPose().getPy() < 0 ? Math.toDegrees(bot.getYaw()) + angle : Math.toDegrees(bot.getYaw()) - angle;
angle = angle % 360;
double hypotenuse = Math.sqrt(Math.pow(opposite, 2) + Math.pow(adjacent, 2));
if (hypotenuse < 2.2) {
Coordinate offset = bot.coordinateOffsetForAngleAndDistance(angle, hypotenuse);
Coordinate absolute = new Coordinate(bot.getX() + offset.getX(), bot.getY() + offset.getY());
this.getMap().reportGarbage(item.getId(), absolute, bot);
}
}
//Check for garbage area position
if (this.getMap().isBotInGarbageArea(bot)) {
this.getMap().reportBotInGarbageArea(bot);
}
double front = bot.getSonarValues()[Simplebot.kSimplebotSonarFrontMiddle];
double frontLeft = bot.getSonarValues()[Simplebot.kSimplebotSonarFrontLeft];
double frontRight = bot.getSonarValues()[Simplebot.kSimplebotSonarFrontRight];
double right = bot.getSonarValues()[Simplebot.kSimplebotSonarRightMiddle];
double rightFront = bot.getSonarValues()[Simplebot.kSimplebotSonarRightFront];
double rightBack = bot.getSonarValues()[Simplebot.kSimplebotSonarRightBack];
double left = bot.getSonarValues()[Simplebot.kSimplebotSonarLeftMiddle];
double leftFront = bot.getSonarValues()[Simplebot.kSimplebotSonarLeftFront];
double leftBack = bot.getSonarValues()[Simplebot.kSimplebotSonarLeftBack];
double back = bot.getSonarValues()[Simplebot.kSimplebotSonarBackMiddle];
double backLeft = bot.getSonarValues()[Simplebot.kSimplebotSonarBackLeft];
double backRight = bot.getSonarValues()[Simplebot.kSimplebotSonarBackRight];
//HLog("Front: " + front + " Left: " + left);
double frontDiagRight = bot.getSonarValues()[Simplebot.kSimplebotSonarDiagonalTopRight];
double frontDiagLeft = bot.getSonarValues()[Simplebot.kSimplebotSonarDiagonalTopLeft];
double backDiagRight = bot.getSonarValues()[Simplebot.kSimplebotSonarDiagonalBottomRight];
double backDiagLeft = bot.getSonarValues()[Simplebot.kSimplebotSonarDiagonalBottomLeft];
if (!bot.isMovingAutonomously()) {
if (!bot.startedExploring) {
HLog("1. Starting exploration");
Pivot initial = new Pivot(bot);
HLog("Setting initial: " + initial);
this.map.setRootPathCoordinate(initial);
bot.setInitialPivot(initial);
bot.setSpeedAndRotationRate(0.0, 0.0);
bot.setYaw(0.0);
bot.startedExploring = true;
bot.originPivot = initial;
bot.currentPathCoordinate = initial;
bot.originDirection = Pivot.NORTH;
bot.startedExploring = true;
} else if (!bot.startedFindingInitialExploringWall) {
HLog("2. Going north to look for initial wall");
if (front > kRobotControllerSensorExploringMinimumWallDistance) {
bot.setSpeedAndRotationRate(0.1, 0.0);
}
bot.startedFindingInitialExploringWall = true;
//HLog("2. Origin: " + bot.originPivot);
} else if (!bot.foundInitialExploringWall) {
if (front < kRobotControllerSensorExploringMinimumWallDistance) {
bot.setSpeedAndRotationRate(0.0, 0.0);
bot.setYaw(0.0);
bot.foundInitialExploringWall = true;
bot.foundPivotPlace = true;
HLog("3. Found initial wall!");
//HLog("3. Origin: " + bot.originPivot);
} else {
bot.setSpeedAndRotationRate(0.25, 0.0);
}
} else {
//HLog("4. Origin: " + bot.originPivot);
if (bot.foundPivotPlace) {
Pivot newPivot = new Pivot(bot);
HLog("Found pivot, adding it: " + newPivot);
bot.addPivot(newPivot);
bot.foundPivotPlace = false;
bot.originPivot = newPivot;
bot.currentPathCoordinate = newPivot;
//HLog("Going back to origin: " + bot.originPivot);
//bot.goToDestination(bot.originPivot.getCoordinate(), false);
} else {
if (!bot.movingForNewPivotExploration) {
//HLog("4. Finding new pivot to explore");
//Find new pivot to explore
Pivot unex = null;
for (Pivot p : bot.pivots) {
if (!p.isFullyExplored()) {
unex = p;
//break;
}
}
int count = 0;
for (Pivot p: bot.pivots) {
if (!p.isFullyExplored()) {
count++;
}
}
HLog("Still " + count + " unexplored pivots TO GO!");
if (unex != null) {
HLog("Planning path from " + bot.originPivot + " to first found unex: " + unex);
//bot.printPivots();
//Path-plan to unex
ArrayList<Pivot> path = this.map.pathFromPivotToPivot(bot.originPivot, unex, bot);
HLog("Got path");
ArrayList<PathCoordinate> pathC = new ArrayList<PathCoordinate>();
for (Pivot p : path) {
pathC.add(p);
}
HLog("Traveling through path");
bot.travelThroughPath(pathC);
bot.originPivot = unex;
bot.currentPathCoordinate = unex;
bot.settingDirectionForNewPivot = true;
bot.movingForNewPivotExploration = true;
} else {
//Fully explored pivots!
bot.halt();
HLog("Fully explored map!");
this.fullyExploredMap();
}
} else if (bot.settingDirectionForNewPivot) {
HLog("Setting direction for new pivot");
Pivot p = bot.originPivot;
if (!p.exploredNorth()) {
bot.setYaw(0.0);
bot.originDirection = Pivot.NORTH;
HLog("Going north");
} else if (!p.exploredEast()) {
bot.setYaw(Math.toRadians(90));
bot.originDirection = Pivot.EAST;
HLog("Going east");
} else if (!p.exploredWest()) {
bot.setYaw(Math.toRadians(270));
bot.originDirection = Pivot.WEST;
HLog("Going west");
} else if (!p.exploredSouth()) {
bot.setYaw(Math.toRadians(180));
bot.originDirection = Pivot.SOUTH;
HLog("Going south");
}
bot.settingDirectionForNewPivot = false;
bot.movingForNewPivotExploration = true;
} else if (bot.movingForNewPivotExploration) {
//Currently exploring for new pivot
double rotationRate = 0.0;
double speed = 0.3;
//Check wall sides
if (left < 0.8 && right < 0.8) {
if (left < right) {
rotationRate = -0.013;
} else if (left > right) {
rotationRate = 0.013;
} else {
rotationRate = 0.0;
}
speed = 0.1;
} else if (left < 0.7) {
rotationRate = -0.02;
} else if (right < 0.7) {
rotationRate = 0.02;
} else {
rotationRate = 0.0;
}
//HLog("Currently exploring for new pivot");
//1. Garbage
//2. Current pivots
Pivot foundP = null;
for (Pivot p : bot.pivots) {
if (!p.getCoordinate().equals(bot.originPivot.getCoordinate()) && p.getCoordinate().distanceFromCoordinate(bot.getCoordinate()) < 0.5 && !p.getNeighboringPivots().contains(bot.originPivot)) {
foundP = p;
}
}
if (foundP != null) {
HLog("Stepped on pivot!");
if (bot.originDirection == Pivot.NORTH) {
Pivot prevSouth = foundP.getSouth();
boolean exploredSouth = foundP.exploredSouth();
foundP.setSouth(bot.originPivot);
bot.originPivot.setNorth(foundP);
if ((exploredSouth && bot.originPivot.exploredSouth()) || prevSouth != null) bot.originPivot.setSouth(prevSouth);
} else if (bot.originDirection == Pivot.EAST) {
Pivot prevWest = foundP.getWest();
boolean exploredWest = foundP.exploredWest();
foundP.setWest(bot.originPivot);
bot.originPivot.setEast(foundP);
if ((exploredWest && bot.originPivot.exploredWest()) || prevWest != null) bot.originPivot.setWest(prevWest);
} else if (bot.originDirection == Pivot.WEST) {
Pivot prevEast = foundP.getEast();
boolean exploredEast = foundP.exploredEast();
foundP.setEast(bot.originPivot);
bot.originPivot.setWest(foundP);
if ((exploredEast && bot.originPivot.exploredEast()) || prevEast != null) bot.originPivot.setEast(prevEast);
} else if (bot.originDirection == Pivot.SOUTH) {
Pivot prevNorth = foundP.getNorth();
boolean exploredNorth = foundP.exploredNorth();
foundP.setNorth(bot.originPivot);
bot.originPivot.setSouth(foundP);
if ((exploredNorth && bot.originPivot.exploredNorth()) || prevNorth != null) bot.originPivot.setNorth(prevNorth);
}
bot.originPivot = foundP;
bot.currentPathCoordinate = foundP;
bot.movingForNewPivotExploration = false;
return;
}
//3. Side wall delta
if ((leftFront - bot.previousLeftFront > 1.5 && leftBack - bot.previousLeftBack > 1.5) || (bot.previousBackDiagLeft < 1.5 && backDiagLeft > 4.9)) {
if (bot.elapsedLeftWallExplorationTimeMillis < 0) bot.elapsedLeftWallExplorationTimeMillis = System.currentTimeMillis();
if ((bot.previousBackDiagLeft < 0.8 && backDiagLeft > 4.9) || System.currentTimeMillis() - bot.elapsedLeftWallExplorationTimeMillis > 1500) {
//bot.setSpeedAndRotationRate(0.5, 0.0);
bot.halt();
//bot.setYaw(0.0);
bot.foundPivotPlace = true;
bot.movingForNewPivotExploration = false;
bot.elapsedLeftWallExplorationTimeMillis = -1;
return;
}
} else {
if (leftFront < bot.previousLeftFront) bot.previousLeftFront = leftFront;
if (leftBack < bot.previousLeftBack) bot.previousLeftBack = leftBack;
bot.previousBackDiagLeft = backDiagLeft;
bot.elapsedLeftWallExplorationTimeMillis = -1;
}
if ((rightFront - bot.previousRightFront > 1.5 && rightBack - bot.previousRightBack > 1.5) || (bot.previousBackDiagRight < 1.5 && backDiagRight > 4.9)) {
HLog("SPOTTED RIGHT!");
if (bot.elapsedRightWallExplorationTimeMillis < 0) bot.elapsedRightWallExplorationTimeMillis = System.currentTimeMillis();
if ((bot.previousBackDiagRight < 0.8 && backDiagRight > 4.9) || System.currentTimeMillis() - bot.elapsedRightWallExplorationTimeMillis > 1500) {
//bot.setSpeedAndRotationRate(0.5, 0.0);
bot.halt();
//bot.setYaw(0.0);
bot.foundPivotPlace = true;
bot.movingForNewPivotExploration = false;
bot.elapsedRightWallExplorationTimeMillis = -1;
return;
}
} else {
if (rightFront < bot.previousRightFront) bot.previousRightFront = rightFront;
if (rightBack < bot.previousRightBack) bot.previousRightBack = rightBack;
bot.previousBackDiagRight = backDiagRight;
bot.elapsedRightWallExplorationTimeMillis = -1;
}
//4. Front wall
if (front < kRobotControllerSensorExploringMinimumWallDistance || frontLeft < kRobotControllerSensorExploringMinimumWallDistance|| frontRight < kRobotControllerSensorExploringMinimumWallDistance) {
HLog("Front wall whilst exploring!");
bot.halt();
//bot.setYaw(0.0);
bot.foundPivotPlace = true;
bot.movingForNewPivotExploration = false;
return;
}
//HLog("Speed " + speed);
bot.setSpeedAndRotationRate(speed, rotationRate);
}
}
}
}
}
private void fullyExploredMap() {
for (Destinationbot bot : this.robots) {
bot.halt();
}
this.exploring = false;
this.evaluateNextCommand();
}
private void exploreWallsWithBot(Destinationbot bot) {
double front = bot.getSonarValues()[Simplebot.kSimplebotSonarFrontMiddle];
double right = bot.getSonarValues()[Simplebot.kSimplebotSonarRightMiddle];
double rightFront = bot.getSonarValues()[Simplebot.kSimplebotSonarRightFront];
double rightBack = bot.getSonarValues()[Simplebot.kSimplebotSonarRightBack];
double left = bot.getSonarValues()[Simplebot.kSimplebotSonarLeftMiddle];
double leftFront = bot.getSonarValues()[Simplebot.kSimplebotSonarLeftFront];
double leftBack = bot.getSonarValues()[Simplebot.kSimplebotSonarLeftBack];
double back = bot.getSonarValues()[Simplebot.kSimplebotSonarBackMiddle];
//HLog("Front: " + front + " Left: " + left);
double frontDiagRight = bot.getSonarValues()[Simplebot.kSimplebotSonarDiagonalTopRight];
double frontDiagLeft = bot.getSonarValues()[Simplebot.kSimplebotSonarDiagonalTopLeft];
double backDiagRight = bot.getSonarValues()[Simplebot.kSimplebotSonarDiagonalBottomRight];
double backDiagLeft = bot.getSonarValues()[Simplebot.kSimplebotSonarDiagonalBottomLeft];
if (!bot.isMovingAutonomously()) {
if (!bot.startedWallExploring()) { //Start exploring, face north
//HLog(bot.getIndex() + ": Bot hasn't started exploring, starting now");
bot.setYaw(Math.toRadians(180 * (bot.getIndex() - 1)));
bot.startWallExploring();
} else if (!bot.startedFindingInitialWallFollowingWall()) { //Start looking for an upper wall
//HLog(bot.getIndex() + ": Setting speed, looking for initial wall");
if (front > kRobotControllerSensorWallFollowingMinimumWallDistance) {
bot.setSpeedAndRotationRate(0.1, 0.0);
}
bot.setStartedFindingInitialWallFollowingWall(true);
} else if (!bot.foundInitialWallFollowingWall()) { //Turn right to start wall-following
//HLog(bot.getIndex() + ": Looking for wall...");
if (front < kRobotControllerSensorWallFollowingMinimumWallDistance) {
//HLog(bot.getIndex() + ": Found wall, beginning turn");
bot.setYaw(bot.getYaw() + Math.toRadians(80));
//bot.setSpeedAndRotationRate(0.0, Destinationbot.RIGHT_MINIMUM);
bot.setFoundInitialWall(true);
} else {
bot.setSpeedAndRotationRate(0.1, 0.0);
}
} else if (!bot.alignedWithInitialWallFollowingWall()) {
//HLog(bot.getIndex() + ": Checking for alignment");
double diff = leftFront - leftBack;
if (Math.abs(diff) > kRobotControllerSensorMinimumYawAlignmentDifference) {
//HLog(bot.getIndex() + ": Not aligned yet...");
bot.setSpeedAndRotationRate(0.0, (left * 0.5) * diff);
} else {
//HLog(bot.getIndex() + ": I think I'm aligned!");
bot.setSpeedAndRotationRate(0.0, 0.0);
bot.setAlignedWithInitialWallFollowingWall(true);
bot.startWallFollowingCycle();
}
}
}
}
private static void HLog(String string) {
if (DEBUG_PRINT_MODE) {
System.out.println("RC: " + string);
}
}
public Destinationbot[] getRobots() {
return this.robots;
}
}
|
package com.tripper;
import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import static android.graphics.Color.CYAN;
public class HomePage extends AppCompatActivity {
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 12;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.AppTheme); // custom theme for the app!
setContentView(R.layout.activity_home_page);
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
getLocationPermission();
}
public void onNewTripClick(View view) {
Intent intent = new Intent(this, CreateNewTrip.class);
startActivity(intent);
}
//This method is used to test the TripOverview Page
public void onOverviewClick(View view){
Intent intent = new Intent(this,TripOverview.class);
startActivity(intent);
}
//This method is used to test the TagSuggestion Page
public void onTagClick(View view){
Intent intent = new Intent(this,TagSuggestion.class);
startActivity(intent);
}
// public void onSelectClick(View v){
// System.out.println("clicked");
// //v.setBackgroundColor(CYAN);
// ImageButton imgButton = findViewById(R.id.tagImage);
// TextView txtButton = findViewById(R.id.tagText);
// imgButton.setBackgroundColor(Color.CYAN);
// txtButton.setBackgroundColor(CYAN);
// //Button myBtn = findViewById(R.id.);
// //boolean selected = false;
// //selected = true;
// //ImageButton imgButton = findByID(R.id);
// //1. Put a bunch of buttons in the recycler view
// //2. Make an onClick method
// //3. In that onClick method, change the button's background color
// //myBtn.setBackgroundColor();
// }
private void getLocationPermission() {
int permission = ActivityCompat.checkSelfPermission(this.getApplicationContext(),
Manifest.permission.ACCESS_FINE_LOCATION);
if (permission == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this,
new String[] {Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
//This method is used to test the LocationSuggestion Page
public void onLocationClick(View view){
Intent intent = new Intent(this,LocationSuggestion.class);
startActivity(intent);
}
}
|
package server;
import UtilityClasses.MessageFX;
import UtilityClasses.Permissions;
import UtilityClasses.TokenizerInterfaceImpl;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/*
The NewUser reusable component controller.
Has text fields for name and password, button for
registering user in the database and button to quit.
*/
public class NewUserController extends VBox {
private TokenizerInterfaceImpl dataBase;
//Loads the FXML file and sets its root and controller.
public NewUserController() {
FXMLLoader fxmlLoader = new FXMLLoader(
getClass().getResource("/server/NewUser.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
//Initializes the database field.
public void setTokenizer(TokenizerInterfaceImpl dataBase) {
this.dataBase = dataBase;
}
@FXML
private Label txtHeader;
@FXML
private TextField txtUserName;
@FXML
private PasswordField txtPassword;
@FXML
private CheckBox chkRead;
@FXML
private CheckBox chkWrite;
@FXML
private Button btnRegister;
@FXML
private Button btnQuit;
//Closes the component if the button Quit is clicked.
@FXML
void btnQuitClicked(ActionEvent event) {
Stage stage = (Stage) btnQuit.getScene().getWindow();
stage.close();
}
//Shows error massage if the database is not initialized.
//Takes the input from the Username text field and password text field, and
//passes them to the registerUser method of the database.
//Shows error message if the method registerUser throws IOException.
//Shows confirmation message if the user was registered successfuly.
@FXML
void btnRegisterClicked(ActionEvent event) {
if (dataBase == null) {
MessageFX.errorMassage(MessageFX.NO_DATABASE_MESSAGE, "Error!", null);
return;
}
String name = txtUserName.getText();
String password = txtPassword.getText();
Permissions rights;
if (chkRead.isSelected() && chkWrite.isSelected())
rights = Permissions.REGISTER_TOKEN_AND_READ_CARD;
else if (chkWrite.isSelected())
rights = Permissions.REGISTER_TOKEN;
else
rights = Permissions.READ_CARD;
try {
dataBase.registerUser(name, password, rights);
MessageFX.messageDialog("User successfuly registered!", "Registration massage.", null);
} catch (IOException ex) {
Logger.getLogger(NewUserController.class.getName()).log(Level.SEVERE, null, ex);
MessageFX.errorMassage(ex.getMessage(), "Registration error!", null);
}
btnQuitClicked(event);
}
@FXML
void initialize() {
assert txtHeader != null : "fx:id=\"txtHeader\" was not injected: check your FXML file 'NewUser.fxml'.";
assert txtUserName != null : "fx:id=\"txtUserName\" was not injected: check your FXML file 'NewUser.fxml'.";
assert txtPassword != null : "fx:id=\"txtPassword\" was not injected: check your FXML file 'NewUser.fxml'.";
assert chkRead != null : "fx:id=\"chkRead\" was not injected: check your FXML file 'NewUser.fxml'.";
assert chkWrite != null : "fx:id=\"chkWrite\" was not injected: check your FXML file 'NewUser.fxml'.";
assert btnRegister != null : "fx:id=\"btnRegister\" was not injected: check your FXML file 'NewUser.fxml'.";
assert btnQuit != null : "fx:id=\"btnQuit\" was not injected: check your FXML file 'NewUser.fxml'.";
}
}
|
/*
* 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 ppro.contoller;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import ppro.modelo.PproUsuario;
import ppro.servicio.UsuarioServicio;
/**
*
* @author casa
*/
@ManagedBean
@SessionScoped
public class UsuarioController implements Serializable{
@EJB
private UsuarioServicio usuarioServicio;
@ManagedProperty(value = "#{pproUsuario}")
private PproUsuario pproUsuario;
private List<PproUsuario> listaUsuarios= new ArrayList<>();
public PproUsuario getPproUsuario() {
return pproUsuario;
}
public void setPproUsuario(PproUsuario pproUsuario) {
this.pproUsuario = pproUsuario;
}
public List<PproUsuario> getListaUsuarios() {
return listaUsuarios;
}
public void setListaUsuarios(List<PproUsuario> listaUsuarios) {
this.listaUsuarios = listaUsuarios;
}
public void login() throws IOException{
//String pagina="fallo";
pproUsuario=usuarioServicio.login(pproUsuario);
if(pproUsuario.getUsuId() != null){
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("pproUsuario",pproUsuario);
// pagina=pproUsuario.getPproRelUsuarioPerfilCollection().iterator()
// .next().getRupPerfId().getPerfNombre();
FacesContext.getCurrentInstance().getExternalContext().redirect("escritorio.xhtml");
} else{
FacesContext.getCurrentInstance().getExternalContext().redirect("fallo.xhtml");
}
}
public String logout(){
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
return "/login.xhtml?faces-redirect=true";
}
public void loginMd5()throws IOException{
pproUsuario=usuarioServicio.loginMd5(pproUsuario);
if(pproUsuario.getUsuId() != null){
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("pproUsuario",pproUsuario);
FacesContext.getCurrentInstance().getExternalContext().redirect("faces/escritorio.xhtml");
} else{
FacesContext.getCurrentInstance().getExternalContext().redirect("faces/fallo.xhtml");
}
}
}
|
/**
* Copyright (C) 2008 Atlassian
*
* 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.atlassian.connector.intellij.bamboo;
import com.gargoylesoftware.htmlunit.StringWebResponse;
import com.gargoylesoftware.htmlunit.TopLevelWindow;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HTMLParser;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTable;
import junit.framework.Assert;
import java.io.IOException;
import java.util.List;
class ResponseWrapper {
private final HtmlPage thePage;
private HtmlTable theTable;
ResponseWrapper(String htmlPage) throws IOException {
StringWebResponse swr = new StringWebResponse(htmlPage);
WebClient wc = new WebClient();
thePage = HTMLParser.parse(swr, new TopLevelWindow("", wc));
}
public HtmlPage getPage() {
return thePage;
}
public HtmlTable getTheTable() throws Exception {
if (theTable == null) {
List<?> tables = thePage.getByXPath("html/body/table");
Assert.assertEquals(1, tables.size());
theTable = (HtmlTable) tables.get(0);
}
return theTable;
}
}
|
package br.com.rafagonc.tjdata.models;
import javax.persistence.*;
@Entity
public class Cookie {
@Id
@GeneratedValue( strategy= GenerationType.AUTO )
private Long id;
@Column(nullable = false)
private String key;
@Column(nullable = false)
private String value;
@Column(nullable = true)
private String domain;
@Column(nullable = true)
private String path;
@ManyToOne(fetch = FetchType.EAGER)
private ESAJCaptcha captcha;
public Cookie() {
}
//
public Cookie(String key, String value, String domain) {
this.key = key;
this.value = value;
this.domain = domain;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
public String getDomain() {
return domain;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public ESAJCaptcha getCaptcha() {
return captcha;
}
public void setCaptcha(ESAJCaptcha captcha) {
this.captcha = captcha;
}
public void setKey(String key) {
this.key = key;
}
public void setValue(String value) {
this.value = value;
}
public void setDomain(String domain) {
this.domain = domain;
}
}
|
package com.xianzaishi.wms.tmscore.vo;
import com.xianzaishi.wms.tmscore.vo.WaveDetailVO;
public class WaveDetailDO extends WaveDetailVO {
} |
package com.Hierarchical_Inheritance;
class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest {
public static void main(String[] args) {
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispB() method of ClassB
b.dispB();
//call dispA() method of ClassA
b.dispA();
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispC() method of ClassC
c.dispC();
//call dispA() method of ClassA
c.dispA();
//Assigning ClassD object to ClassD reference
ClassD d = new ClassD();
//call dispD() method of ClassD
d.dispD();
//call dispA() method of ClassA
d.dispA();
}
}
|
package com.travel.lodge.userservice.domain;
import lombok.Data;
import javax.persistence.*;
@Entity
@Data
public class HotelUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String email;
private String firstName;
private String lastName;
private String location;
private String contactNo;
private int activityStatus;
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package assignment6;
import java.awt.image.BufferedImage;
import java.util.Scanner;
/**
*
* @author Kareem
*/
public class Location {
// Initializing the variables
private final Scene[] scenes;
private final String name;
public Location(Scanner input) {
// A scene for each direction
scenes = new Scene[4];
// Getting the name from txt file
name = input.nextLine();
// Making the scenes
for (int i = 0; i < 4; i++) {
Scene s = new Scene(input);
scenes[i] = s;
}
}
// Method that checks if the front is blocked
public boolean isFrontBlocked(String dir) {
// Checking each direction
for (int i = 0; i < 4; i++) {
// Checking if the scene is equal to a wall
if (scenes[i].getDirection().equals(dir)) {
return scenes[i].isBlocked();
}
}
return true;
}
// Method that gets the next location
public String getNextLocation(String dir) {
// Checking each direction
for (int i = 0; i < 4; i++) {
// Checking if the direction is equal to the previous one
if (scenes[i].getDirection().equals(dir)) {
return scenes[i].getNextLocation();
}
}
return null;
}
// Getting the image
public BufferedImage getImage(String dir) {
// Checking each direction
for (int i = 0; i < 4; i++) {
// Checking if the direction on the image and getting it
if (scenes[i].getDirection().equals(dir)) {
return scenes[i].getImage();
}
}
return null;
}
// Getting the name of the image
public String getName() {
return this.name;
}
}
|
/**
* 湖北安式软件有限公司
* Hubei Anssy Software Co., Ltd.
* FILENAME : VerifyCacheServer.java
* PACKAGE : com.anssy.venturebar.base.server
* CREATE DATE : 2016-8-27
* AUTHOR : make it
* MODIFIED BY :
* DESCRIPTION :
*/
package com.anssy.venturebar.base.server;
import com.anssy.webcore.common.BaseConstants;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* @author make it
* @version SVN #V1# #2016-8-27#
* 手机验证码redis时间缓存
*/
@Service("verifyCacheServer")
public class VerifyCacheServer {
@Resource
RedisTemplate<String, Long> redisTemplate;
/**
* 将号码和验证码加入缓存
*/
public void setCode(String phone, Long code) {
try {
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericToStringSerializer<Long>(Long.class));
redisTemplate.opsForValue().set(phone, code, BaseConstants.SECONDS, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 验证号码和验证码
*/
public Long findCode(String phone) {
Long code = null;
try {
code = redisTemplate.opsForValue().get(phone);
} catch (Exception e) {
e.printStackTrace();
}
return code;
}
} |
public class UniquePaths {
public int uniquePaths(int m, int n) {
int ans[][] = new int[m+1][n+1];
for(int i=1;i<=m;i++){
ans[i][1] = 1;
}
for(int i=1;i<=n;i++){
ans[1][i] = 1;
}
for(int i=2;i<=m;i++){
for(int j=2;j<=n;j++){
ans[i][j] = 2 * ans[i-1][j-1];
int a = i-2;
while( a >= 1){
ans[i][j] += ans[a][j-1];
a--;
}
int b= j-2;
while( b >= 1){
ans[i][j] += ans[i-1][b];
b--;
}
}
}
return ans[m][n];
}
}
|
package com.crm.acute.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.crm.acute.generics.WebDriverUtils;
public class CreatingNewOrganization
{
@FindBy(name = "accountname") private WebElement OrgNameTB;
@FindBy(name = "phone") private WebElement phoneTB;
@FindBy(id="email1")private WebElement emailTB;
@FindBy(xpath="//img[@alt='Select']") private WebElement memberOfTB;
@FindBy(xpath ="//input[@class='crmbutton small save']") private WebElement saveBtn;
WebDriver driver;
public CreatingNewOrganization(WebDriver driver)
{
this.driver=driver;
PageFactory.initElements(driver, this);
}
public OrganizationInformationPage createOrganizationWithPhone(String orgName, String fno)
{
OrgNameTB.sendKeys(orgName);
phoneTB.sendKeys(fno);
saveBtn.click();
return new OrganizationInformationPage(driver);
}
public OrganizationInformationPage createOrganizationwithEmailNphone(String orgName, String fno, String email)
{
OrgNameTB.sendKeys(orgName);
phoneTB.sendKeys(fno);
emailTB.sendKeys(email);
saveBtn.click();
return new OrganizationInformationPage(driver);
}
public OrganizationInformationPage createOrganizationwithMember(String orgName, String fno, String email)
{
OrgNameTB.sendKeys(orgName);
phoneTB.sendKeys(fno);
emailTB.sendKeys(email);
memberOfTB.click();
WebDriverUtils util= new WebDriverUtils();
util.switchtoChildWindow(driver);
OrganizationChildBrwsrPopUpWin child= new OrganizationChildBrwsrPopUpWin(driver);
child.setOrgNameinSearchTB("TY1");
child.clickSearchNowBtn();
child.clickFirstLink();
util.acceptAlert(driver);
util.switchtoParentWindow(driver);
saveBtn.click();
return new OrganizationInformationPage(driver);
}
}
|
package com.project.board.web.Comment.dto;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@RequiredArgsConstructor
public class DeleteCommentDto {
// 댓글 UID
private Long COMMENT_UID;
}
|
package webservice.stub;
import javax.xml.namespace.QName;
import javax.xml.ws.*;
import java.net.MalformedURLException;
import java.net.URL;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.9-b130926.1035
* Generated source version: 2.2
*
*/
@WebServiceClient(name = "ServiceReceiverImplService", targetNamespace = "http://server.webservice/", wsdlLocation = "file:///home/visiri/IdeaProjects/P2PFileSharer/Webservice/src/p2pFilesharer/webservice/p2pFilesharer/webservice/stub/p2pFilesharer.webservice.server.ServiceReceiver.wsdl")
public class ServiceReceiverImplService
extends Service
{
private final static URL SERVICERECEIVERIMPLSERVICE_WSDL_LOCATION;
private final static WebServiceException SERVICERECEIVERIMPLSERVICE_EXCEPTION;
private final static QName SERVICERECEIVERIMPLSERVICE_QNAME = new QName("http://server.webservice.p2pFilesharer/", "ServiceReceiverImplService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("file:///home/visiri/IdeaProjects/P2PFileSharer/Webservice/src/p2pFilesharer/webservice/p2pFilesharer/webservice/stub/p2pFilesharer.webservice.server.ServiceReceiver.wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
SERVICERECEIVERIMPLSERVICE_WSDL_LOCATION = url;
SERVICERECEIVERIMPLSERVICE_EXCEPTION = e;
}
public ServiceReceiverImplService() {
super(__getWsdlLocation(), SERVICERECEIVERIMPLSERVICE_QNAME);
}
public ServiceReceiverImplService(WebServiceFeature... features) {
super(__getWsdlLocation(), SERVICERECEIVERIMPLSERVICE_QNAME, features);
}
public ServiceReceiverImplService(URL wsdlLocation) {
super(wsdlLocation, SERVICERECEIVERIMPLSERVICE_QNAME);
}
public ServiceReceiverImplService(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, SERVICERECEIVERIMPLSERVICE_QNAME, features);
}
public ServiceReceiverImplService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public ServiceReceiverImplService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
/**
*
* @return
* returns ServiceReceiver
*/
@WebEndpoint(name = "ServiceReceiverImplPort")
public ServiceReceiver getServiceReceiverImplPort() {
return super.getPort(new QName("http://server.webservice.p2pFilesharer/", "ServiceReceiverImplPort"), ServiceReceiver.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns ServiceReceiver
*/
@WebEndpoint(name = "ServiceReceiverImplPort")
public ServiceReceiver getServiceReceiverImplPort(WebServiceFeature... features) {
return super.getPort(new QName("http://server.webservice.p2pFilesharer/", "ServiceReceiverImplPort"), ServiceReceiver.class, features);
}
private static URL __getWsdlLocation() {
if (SERVICERECEIVERIMPLSERVICE_EXCEPTION!= null) {
throw SERVICERECEIVERIMPLSERVICE_EXCEPTION;
}
return SERVICERECEIVERIMPLSERVICE_WSDL_LOCATION;
}
}
|
package com.ti.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ti.bean.UserBean;
import com.ti.service.ContentService;
/**
* Servlet implementation class ContentIssueServlet
*/
@WebServlet("/ContentIssueServlet")
public class ContentIssueServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ContentIssueServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String main_content = request.getParameter("submitcontent");
String main_title = request.getParameter("title");
PrintWriter out = response.getWriter();
UserBean user = (UserBean)request.getSession().getAttribute("USER");
ContentService contentadd = new ContentService();
String temp = "";
temp = contentadd.content_add(user.getUser_name(),main_title,main_content);
if(temp=="YES") {
response.sendRedirect("noteList.jsp");
}else {
out.print("<script type='text/javascript'>");
out.print("alert('ERROR');");
out.print("window.location='login.jsp';");
out.print("</script>");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
/*
* Copyright 2016 TeddySoft Technology. All rights reserved.
*
*/
package tw.teddysoft.gof.abstractFactory;
public class WindowsFactory extends AbstractFactory {
@Override
public Drive createDrive(String type, int index) {
SimpleDriveFactory driveFactory = new SimpleDriveFactory();
return driveFactory.createWindowsDrive(type, index);
}
@Override
public Process createProcess(int id) {
return new WinProcess(id);
}
@Override
public IOPort createIOPort(int address) {
return new WinIOPort(address);
}
@Override
public Monitor createMonitor(int id) {
return new WinMonitor(id);
}
}
|
package com.aftermoonest.tell_me_something_important.repository;
import com.vaadin.flow.component.textfield.EmailField;
import java.util.List;
public interface Controller {
Integer countOfElementsOnPage = 10;
void save(Object item, String key);
List<Item> get();
boolean find(String key);
boolean isTextCorrect(String value);
boolean isEmailCorrect(EmailField emailField);
Item buildItem(String email, String name, String date, String text);
Integer defineCountOfPages();
Integer getCountOfElementsOnPage();
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.type.classreading;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import org.springframework.asm.Opcodes;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.MethodMetadata;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
/**
* {@link AnnotationMetadata} created from a
* {@link SimpleAnnotationMetadataReadingVisitor}.
*
* @author Phillip Webb
* @author Sam Brannen
* @author Juergen Hoeller
* @since 5.2
*/
final class SimpleAnnotationMetadata implements AnnotationMetadata {
private final String className;
private final int access;
@Nullable
private final String enclosingClassName;
@Nullable
private final String superClassName;
private final boolean independentInnerClass;
private final Set<String> interfaceNames;
private final Set<String> memberClassNames;
private final Set<MethodMetadata> declaredMethods;
private final MergedAnnotations mergedAnnotations;
@Nullable
private Set<String> annotationTypes;
SimpleAnnotationMetadata(String className, int access, @Nullable String enclosingClassName,
@Nullable String superClassName, boolean independentInnerClass, Set<String> interfaceNames,
Set<String> memberClassNames, Set<MethodMetadata> declaredMethods, MergedAnnotations mergedAnnotations) {
this.className = className;
this.access = access;
this.enclosingClassName = enclosingClassName;
this.superClassName = superClassName;
this.independentInnerClass = independentInnerClass;
this.interfaceNames = interfaceNames;
this.memberClassNames = memberClassNames;
this.declaredMethods = declaredMethods;
this.mergedAnnotations = mergedAnnotations;
}
@Override
public String getClassName() {
return this.className;
}
@Override
public boolean isInterface() {
return (this.access & Opcodes.ACC_INTERFACE) != 0;
}
@Override
public boolean isAnnotation() {
return (this.access & Opcodes.ACC_ANNOTATION) != 0;
}
@Override
public boolean isAbstract() {
return (this.access & Opcodes.ACC_ABSTRACT) != 0;
}
@Override
public boolean isFinal() {
return (this.access & Opcodes.ACC_FINAL) != 0;
}
@Override
public boolean isIndependent() {
return (this.enclosingClassName == null || this.independentInnerClass);
}
@Override
@Nullable
public String getEnclosingClassName() {
return this.enclosingClassName;
}
@Override
@Nullable
public String getSuperClassName() {
return this.superClassName;
}
@Override
public String[] getInterfaceNames() {
return StringUtils.toStringArray(this.interfaceNames);
}
@Override
public String[] getMemberClassNames() {
return StringUtils.toStringArray(this.memberClassNames);
}
@Override
public MergedAnnotations getAnnotations() {
return this.mergedAnnotations;
}
@Override
public Set<String> getAnnotationTypes() {
Set<String> annotationTypes = this.annotationTypes;
if (annotationTypes == null) {
annotationTypes = Collections.unmodifiableSet(
AnnotationMetadata.super.getAnnotationTypes());
this.annotationTypes = annotationTypes;
}
return annotationTypes;
}
@Override
public Set<MethodMetadata> getAnnotatedMethods(String annotationName) {
Set<MethodMetadata> result = new LinkedHashSet<>(4);
for (MethodMetadata annotatedMethod : this.declaredMethods) {
if (annotatedMethod.isAnnotated(annotationName)) {
result.add(annotatedMethod);
}
}
return Collections.unmodifiableSet(result);
}
@Override
public Set<MethodMetadata> getDeclaredMethods() {
return Collections.unmodifiableSet(this.declaredMethods);
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof SimpleAnnotationMetadata that && this.className.equals(that.className)));
}
@Override
public int hashCode() {
return this.className.hashCode();
}
@Override
public String toString() {
return this.className;
}
}
|
/*
* traverse a map by achieving its EntrySet
*
*
*/
package Map;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
/**
*
* @author YNZ
*/
class TraverseMap {
Map<String, Number> map = new HashMap<>(10);
Random random = new Random(30);
public TraverseMap() {
for (int i = 0; i < 100; i++) {
map.put(String.valueOf(i), random.nextInt(100));
}
}
public Map<String, Number> sort() {
Map<String, Number> treeMap = new TreeMap<>(map);
return treeMap;
}
public void print() {
for (Map.Entry<String, Number> entry : map.entrySet()) {
String key = entry.getKey();
Number value = entry.getValue();
System.out.println(key + " " + value.toString());
}
}
public void print(Map<String, Number> map) {
for (Map.Entry<String, Number> entry : map.entrySet()) {
String key = entry.getKey();
Number value = entry.getValue();
System.out.println(key + " " + value.toString());
}
}
public static void main(String[] args) {
TraverseMap tm = new TraverseMap();
tm.print(tm.sort());
double[][] daa = new double[1][1];
System.out.println(daa.length);
}
}
|
package com.consultorio.model;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.consultorio.validation.Validation;
@Entity
public class Financeiro extends DefaultEntity<Financeiro> {
private static final long serialVersionUID = -2424463964056181252L;
private String paciente;
private String cpf;
private String descricao;
@Column(nullable = false)
@Temporal(TemporalType.DATE)
private Date data;
private Double valor;
private String medico;
public String getPaciente() {
return paciente;
}
public void setPaciente(String paciente) {
this.paciente = paciente;
}
public String getMedico() {
return medico;
}
public void setMedico(String medico) {
this.medico = medico;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public Double getValor() {
return valor;
}
public void setValor(Double valor) {
this.valor = valor;
}
@Override
public Validation<Financeiro> getValidation() {
// TODO Auto-generated method stub
return null;
}
}
|
package org.coresystems.services;
import org.coresystems.models.Company;
import org.coresystems.repositories.CompanyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class CompanyService {
@Autowired
private CompanyRepository companyRepository;
public List<Company> getCompanies() {
return new ArrayList<>(companyRepository.findAll());
}
public void addCompany(Company company) {
companyRepository.save(company);
}
}
|
/*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.oauth.as.token;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.apache.http.HttpHeaders;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.nimbusds.oauth2.sdk.token.BearerTokenError;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.server.api.internal.TokensManagement;
/**
* RESTful implementation of the user information token resource
*
* @author K. Benedyczak
*/
@Produces("application/json")
@Path(OAuthTokenEndpoint.USER_INFO_PATH)
public class UserInfoResource extends BaseTokenResource
{
public UserInfoResource(TokensManagement tokensManagement)
{
super(tokensManagement);
}
@Path("/")
@GET
public Response getToken(@HeaderParam("Authorization") String bearerToken)
throws EngineException, JsonProcessingException
{
TokensPair internalAccessToken;
try
{
internalAccessToken = super.resolveBearerToken(bearerToken);
extendValidityIfNeeded(internalAccessToken.tokenSrc, internalAccessToken.parsedToken);
} catch (OAuthTokenException e)
{
return e.getErrorResponse();
}
String contents = internalAccessToken.parsedToken.getUserInfo();
if (contents == null)
return makeBearerError(BearerTokenError.INSUFFICIENT_SCOPE);
return toResponse(Response.ok(contents).header(HttpHeaders.CONTENT_TYPE, "application/json"));
}
}
|
package de.cuuky.varo.threads.dailycheck;
import de.cuuky.varo.Main;
import de.cuuky.varo.config.config.ConfigEntry;
import de.cuuky.varo.config.messages.ConfigMessages;
import de.cuuky.varo.logger.logger.EventLogger.LogType;
import de.cuuky.varo.player.VaroPlayer;
public class SessionCheck extends Checker {
@Override
public void check() {
int sessionsPerDay = ConfigEntry.SESSION_PER_DAY.getValueAsInt();
int preProduceable = ConfigEntry.PRE_PRODUCE_AMOUNT.getValueAsInt();
for(VaroPlayer vp : VaroPlayer.getVaroPlayer()) {
if(sessionsPerDay > 0) {
if(ConfigEntry.SESSION_PER_DAY_ADDSESSIONS.getValueAsBoolean())
vp.getStats().setSessions(vp.getStats().getSessions() + sessionsPerDay);
else
vp.getStats().setSessions(sessionsPerDay);
}
if(preProduceable > 0) {
if(vp.getStats().getPreProduced() > 0)
vp.getStats().setPreProduced(vp.getStats().getPreProduced() - 1);
if(vp.getStats().getPreProduced() <= 0)
vp.getStats().setMaxProduced(false);
else
vp.getStats().setMaxProduced(true);
}
}
if(sessionsPerDay > 0)
Main.getLoggerMaster().getEventLogger().println(LogType.ALERT, ConfigMessages.ALERT_SESSION_RESET.getValue().replace("%amount%", String.valueOf(sessionsPerDay)));
if(preProduceable > 0)
Main.getLoggerMaster().getEventLogger().println(LogType.ALERT, ConfigMessages.ALERT_REMOVED_PRE_PRODUCED.getValue());
}
}
|
package com.example.hp.cold_chain_logistic.fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.example.hp.cold_chain_logistic.R;
import com.example.hp.cold_chain_logistic.base.ConstData;
import com.example.hp.cold_chain_logistic.db.IMSI;
import com.example.hp.cold_chain_logistic.db.Para;
import com.example.hp.cold_chain_logistic.ui.ComWidget;
import com.example.hp.cold_chain_logistic.utils.HttpUrlCallback;
import com.example.hp.cold_chain_logistic.utils.HttpUtils;
import com.example.hp.cold_chain_logistic.utils.Utility;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import okhttp3.Call;
import okhttp3.Response;
import static android.content.ContentValues.TAG;
/**
* @author liz
* @version V1.0
* @date 2018/4/8
*/
public class OneShowFragment extends Fragment {
private ListView lv_fg_one_show;
private ArrayList<HashMap<String, String>> mArrayList = new ArrayList<>();
private SimpleAdapter simpleAdapter;
private ImageView iv_fg_one_show_back;
private ImageView iv_fg_one_show_del;
private ImageView iv_fg_one_show_save;
private ImageView iv_fg_one_show_left;
private ImageView iv_fg_one_show_right;
private ImageView iv_fg_one_show_first;
private int curFraNum; //当前帧号
private String firstFraNum; //最初帧号
private String IMSICODE; //当前输入的IMSI号
private String url="";
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one_show, container, false);
lv_fg_one_show = view.findViewById(R.id.lv_fg_one_show);
iv_fg_one_show_back = view.findViewById(R.id.iv_fg_one_show_back);
iv_fg_one_show_del = view.findViewById(R.id.iv_fg_one_show_del);
iv_fg_one_show_save = view.findViewById(R.id.iv_fg_one_show_save);
iv_fg_one_show_left = view.findViewById(R.id.iv_fg_one_show_left);
iv_fg_one_show_right = view.findViewById(R.id.iv_fg_one_show_right);
iv_fg_one_show_first = view.findViewById(R.id.iv_fg_one_show_first);
showList();
return view;
}
/**
* 展示列表
*/
private void showList() {
simpleAdapter = new SimpleAdapter(getContext(),
mArrayList,
R.layout.item_listview_fg_one,
new String[]{"one_show_item_title", "one_show_item_text"}, //动态数组里与ListItem对应的子项
new int[]{R.id.one_show_item_title, R.id.one_show_item_text} //
);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
lv_fg_one_show.setAdapter(simpleAdapter);
}
});
}
@Override
public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//上一帧数据
iv_fg_one_show_left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
curFraNum--;
url = ConstData.getAhlInterfaceServer()+"get:" +
"curlen(" + curFraNum + "&" + IMSICODE;
HttpUtils.sendOkHttpRequest(url, new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ComWidget.ToastShow("请检查网络状态!",getActivity());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//jsonarray
String data=response.body().string();
//whether exists data
String result=Utility.isValueTure(data);
if(result.equals("false")){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ComWidget.ToastShow("该IMSI无实时数据!",getActivity());
}
});
}else{
//update listview
mArrayList = Utility.parseJsonArrayToHashArray(data);
simpleAdapter.notifyDataSetChanged();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
lv_fg_one_show.setAdapter(simpleAdapter);
}
});
}
}
});
}
});
//下一帧数据
iv_fg_one_show_right.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
curFraNum++;
url = ConstData.getAhlInterfaceServer()+"get:" +
"curlen(" + curFraNum + "&" + IMSICODE;
HttpUtils.sendOkHttpRequest(url, new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ComWidget.ToastShow("请检查网络状态!",getActivity());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//jsonarray
String data=response.body().string();
//whether exists data
String result=Utility.isValueTure(data);
if(result.equals("false")){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ComWidget.ToastShow("该IMSI无实时数据!",getActivity());
}
});
}else{
//update listview
mArrayList = Utility.parseJsonArrayToHashArray(data);
simpleAdapter.notifyDataSetChanged();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
lv_fg_one_show.setAdapter(simpleAdapter);
}
});
}
}
});
}
});
//第一帧
iv_fg_one_show_first.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
url = ConstData.getAhlInterfaceServer()+"get:old&" +
IMSICODE;
HttpUtils.sendOkHttpRequest(url, new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ComWidget.ToastShow("请检查网络状态!",getActivity());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//jsonarray
String data=response.body().string();
//whether exists data
String result=Utility.isValueTure(data);
if(result.equals("false")){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ComWidget.ToastShow("该IMSI无实时数据!",getActivity());
}
});
}else{
//update listview
mArrayList = Utility.parseJsonArrayToHashArray(data);
simpleAdapter.notifyDataSetChanged();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
lv_fg_one_show.setAdapter(simpleAdapter);
}
});
}
}
});
}
});
//保存IMSI号
iv_fg_one_show_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("确定保存该IMSI号吗?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
url=ConstData.getUSER_ITERFACE_SERVER()+
"save_imsi.php?imsi="+IMSICODE+"&account="+ConstData.getAccount();
HttpUtils.sendOkHttpRequest(url, new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ComWidget.ToastShow("请检查网络连接!",getActivity());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String data = response.body().string();
switch ((int) Utility.getJsonObjectAttr(data, "code")) {
case 200:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ComWidget.ToastShow("存储成功!",getActivity());
}
});
break;
case 401:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
ComWidget.ToastShow("已经存储过该IMSI号!",getActivity());
}
});
break;
default:
break;
}
}
});
}
}).setNegativeButton("取消", null);
builder.show();
}
});
}
});
//回退到上一个界面
iv_fg_one_show_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().popBackStack();
}
});
//清空数据
iv_fg_one_show_del.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("确定清空数据吗?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < mArrayList.size(); i++) {
mArrayList.get(i).put("one_show_item_text", "");
}
simpleAdapter.notifyDataSetChanged();
lv_fg_one_show.setAdapter(simpleAdapter);
}
}).setNegativeButton("取消", null);
builder.show();
}
});
}
});
}
public void setData(String data) {
mArrayList = Utility.parseJsonArrayToHashArray(data);
firstFraNum = mArrayList.get(0).get("one_show_item_text");
curFraNum = Integer.parseInt(firstFraNum);
IMSICODE = mArrayList.get(1).get("one_show_item_text");
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package rearrangeword.rearrange;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import rearrangeword.reader.Lexicon;
/**
*
* @author Riju
*/
public class Main {
/**
* @param args the command line arguments
*/
String[] letters;
int max;
int min;
int c;
String buffer;
Lexicon lex;
HashSet arrangedWords;
public HashSet getWords(){
return arrangedWords;
}
public int getMin(){
return min;
}
public int getMax(){
return max;
}
public int getCurrent(){
return c;
}
private void assignNumber(String s) {
//first we assign each letter to each number 1 through 9;
letters = new String[s.length() + 1];
for (int i = 0; i < s.length(); i++) {
letters[i + 1] = "" + s.charAt(i);
}
//!
System.out.print("Rearranging: ");
for (int k = 1; k < letters.length; k++) {
System.out.print(letters[k]);
}
System.out.println();
//!
}
private void setRange(String s) {
//setting min
for (int i = 0; i < s.length(); i++) {
min = (min * 10) + (i + 1);
}
//System.err.println("Min:" + min);
for (int i = s.length(); i > 0; i--) {
max = (max * 10) + i;
}
max++; //code optimized to not go further than the practical max limit
//System.err.println("Max:" + max);
}
private boolean digitsRecurr(int x) {
String dig = Integer.toString(x);
int z = 0;
for (int i = 0; i < dig.length() - 1; i++) {
String u = Character.toString(dig.charAt(i));
//now we break the string into two parts such that
//we can search each part for recurrence. Otherwise indexOf
//will return the same value and a bug will be created
String up = dig.substring(0, i);
// z=i;
// if(i==dig.length())
// z--;
String down = dig.substring(i + 1); //includes sample
//treat up first
z = up.indexOf(u);
if (z >= 0)//recurrs
{
return true;
}
//treat down
z = down.indexOf(u);
if (z >= 0) {
return true;
}
}
return false;
}
private boolean allOccur(int x) {
String z = Integer.toString(x);
for (int i = 0; i < letters.length - 1; i++) {
String d = "" + (i + 1);
if (!(z.indexOf(d) >= 0)) {
return false;
}
}
return true;
}
private String getRearrangedString(int x) {
String s = "";
String num = Integer.toString(x);
for (int i = 0; i < num.length(); i++) {
int p = Integer.parseInt(Character.toString(num.charAt(i)));
s += letters[p];
}
return s;
}
public void rearrange(String s) {
arrangedWords=new HashSet(); c=0;
//load the lexicon
lex=new Lexicon();
//Now we get to the nitty gritty of rearranging
//first assign numbers
assignNumber(s);
//then decide which are the minimum and the maximum numbers
setRange(s);
//now increament one number and check for digit recurrunce
String rString="";
for (int i = min; i < max; i++) {
c++;
if (allOccur(i)) {
// System.out.println(getRearrangedString(i));
rString=getRearrangedString(i);
if(lex.hasWord(rString)){
arrangedWords.add(rString);
System.out.println(rString);
}
}
}
}
public static void main(String[] args) throws IOException {
// TODO code application logic here
System.out.print("What to rearrange? ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s = in.readLine();
if (s.length() > 9) {
System.err.println("To long to rearrange!");
return;
}
new Main().rearrange(s);
}
}
|
package com.prenevin.application.service.impl;
import com.prenevin.application.domain.Tool;
import com.prenevin.application.repository.api.ToolRepository;
import com.prenevin.application.service.api.ToolService;
import com.prenevin.library.crud.service.impl.BaseCrudServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class ToolServiceImpl extends BaseCrudServiceImpl<Tool> implements ToolService {
private final ToolRepository toolRepository;
public ToolServiceImpl(ToolRepository toolRepository) {
super(toolRepository);
this.toolRepository = toolRepository;
}
}
|
package com.example.push.controller;
import com.example.push.export.ResultMapUtil;
import com.example.push.export.error.BusinessException;
import com.example.push.model.CmdbServerInfo;
import com.example.push.model.PushGroup;
import com.example.push.model.PushSubscriber;
import com.example.push.service.CmdbService;
import com.example.push.service.PushGroupService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import java.io.File;
import java.util.Map;
/**
* @author: Farben
* @description: CmdbController cmdb服务控制类
* @create: 2020/4/23-15:48
**/
@Controller
public class CmdbController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(CmdbController.class);
@Autowired
CmdbService cmdbService;
/**
* 读取外部数据源,落地到本地数据库
* @return
*/
@RequestMapping(value = "/cmdbDataLanding", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> saveServerInfo(@RequestParam("file") MultipartFile file, String token ) {
Map<String, Object> result;
try{
result=cmdbService.saveServerInfo(file,token);
}catch (Exception e ){
logger.error("saveServerInfo错误:{}",e);
result=ResultMapUtil.fail("跑批失败");
}
return result;
}
@RequestMapping(value = "/cmdbQuery")
@RequiresPermissions("CMDB_SER_Q")
public ModelAndView query() {
ModelAndView view=new ModelAndView("cmdb/serverInfo");
linkSysInfo(view);
return view;
}
@RequestMapping(value = "/cmdbQueryServerInfo")
@RequiresPermissions("CMDB_SER_Q")
@ResponseBody
public Map<String, Object> queryServerInfo(CmdbServerInfo cmdbServerInfo) {
return cmdbService.queryServerInfo(cmdbServerInfo);
}
@RequestMapping(value = "/queryAllEnv")
@ResponseBody
public Map<String, Object> queryAllEnv() {
return cmdbService.queryAllEnv();
}
}
|
package org.lastresponders.uberassignment.service;
import org.lastresponders.uberassignment.data.model.ImageSearchResult;
import java.util.List;
/**
* Created by sjan on 1/15/2015.
*/
public interface ISearchService {
public List<ImageSearchResult> imageSearch(String searchTerm);
public List<ImageSearchResult> imageSearch(String searchTerm, Integer count);
public List<ImageSearchResult> imageSearch(String searchTerm, Integer count, Integer startIndex );
public List<ImageSearchResult> searchResults(String searchString);
public void clear();
}
|
package com.example.tennisscorekeeper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.util.*;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
final private Player player1 = new Player("Player", "One");
final private Player player2 = new Player("Player", "Two");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("mainActivityCheck", "Before create players...");
TextView playerOne = findViewById(R.id.name_of_player_one);
playerOne.setText(player1.getFullName());
TextView playerTwo = findViewById(R.id.name_of_player_two);
playerTwo.setText(player2.getFullName());
Button button_player_one = findViewById(R.id.button_of_add_point_one);
button_player_one.setOnClickListener(this);
Button button_player_two = findViewById(R.id.button_of_add_point_two);
button_player_two.setOnClickListener(this);
Log.i("mainActivityCheck", "After created players.");
}
@Override
public void onClick(View view) {
Log.i("onClickCheck", "Get into Bug selection!");
switch (view.getId()) {
case R.id.button_of_add_point_one:
player1.addOnePoint(player2);
break;
case R.id.button_of_add_point_two:
player2.addOnePoint(player1);
break;
default:
break;
}
updateBoard(Arrays.asList(new TextView[]{
findViewById(R.id.point_of_player_one),
findViewById(R.id.game_of_player_one),
findViewById(R.id.set_of_player_one)}
), player1);
updateBoard(Arrays.asList(new TextView[]{
findViewById(R.id.point_of_player_two),
findViewById(R.id.game_of_player_two),
findViewById(R.id.set_of_player_two)}
), player2);
}
private void updateBoard(List<TextView> viewList, Player player) {
int[] values = new int[]{player.getPoint(), player.getGame(), player.getSet()};
for(int i = 0; i < viewList.size(); i++) {
viewList.get(i).setText(Integer.toString(values[i]));
}
}
} |
package com.wirelesscar.dynafleet.api.types;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Api_FormMessageWithDestinationPointTO complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Api_FormMessageWithDestinationPointTO">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="formId" type="{http://wirelesscar.com/dynafleet/api/types}Api_FormId"/>
* <element name="isRead" type="{http://wirelesscar.com/dynafleet/api/types}Api_Boolean"/>
* <element name="messageData" type="{http://wirelesscar.com/dynafleet/api/types}Api_FormMessageFieldTO" maxOccurs="unbounded" minOccurs="0"/>
* <element name="messageId" type="{http://wirelesscar.com/dynafleet/api/types}Api_FormMessageId"/>
* <element name="point" type="{http://wirelesscar.com/dynafleet/api/types}Api_PointTO"/>
* <element name="sendstatus" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="sendstatusLastChangeTime" type="{http://wirelesscar.com/dynafleet/api/types}Api_Date"/>
* <element name="timestamp" type="{http://wirelesscar.com/dynafleet/api/types}Api_Date"/>
* <element name="userId" type="{http://wirelesscar.com/dynafleet/api/types}Api_UserId"/>
* <element name="vehicleId" type="{http://wirelesscar.com/dynafleet/api/types}Api_VehicleId"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Api_FormMessageWithDestinationPointTO", propOrder = {
"formId",
"isRead",
"messageData",
"messageId",
"point",
"sendstatus",
"sendstatusLastChangeTime",
"timestamp",
"userId",
"vehicleId"
})
public class ApiFormMessageWithDestinationPointTO {
@XmlElement(required = true)
protected ApiFormId formId;
@XmlElement(required = true, nillable = true)
protected ApiBoolean isRead;
protected List<ApiFormMessageFieldTO> messageData;
@XmlElement(required = true, nillable = true)
protected ApiFormMessageId messageId;
@XmlElement(required = true)
protected ApiPointTO point;
@XmlElement(required = true, nillable = true)
protected String sendstatus;
@XmlElement(required = true, nillable = true)
protected ApiDate sendstatusLastChangeTime;
@XmlElement(required = true, nillable = true)
protected ApiDate timestamp;
@XmlElement(required = true, nillable = true)
protected ApiUserId userId;
@XmlElement(required = true)
protected ApiVehicleId vehicleId;
/**
* Gets the value of the formId property.
*
* @return
* possible object is
* {@link ApiFormId }
*
*/
public ApiFormId getFormId() {
return formId;
}
/**
* Sets the value of the formId property.
*
* @param value
* allowed object is
* {@link ApiFormId }
*
*/
public void setFormId(ApiFormId value) {
this.formId = value;
}
/**
* Gets the value of the isRead property.
*
* @return
* possible object is
* {@link ApiBoolean }
*
*/
public ApiBoolean getIsRead() {
return isRead;
}
/**
* Sets the value of the isRead property.
*
* @param value
* allowed object is
* {@link ApiBoolean }
*
*/
public void setIsRead(ApiBoolean value) {
this.isRead = value;
}
/**
* Gets the value of the messageData property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the messageData property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMessageData().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ApiFormMessageFieldTO }
*
*
*/
public List<ApiFormMessageFieldTO> getMessageData() {
if (messageData == null) {
messageData = new ArrayList<ApiFormMessageFieldTO>();
}
return this.messageData;
}
/**
* Gets the value of the messageId property.
*
* @return
* possible object is
* {@link ApiFormMessageId }
*
*/
public ApiFormMessageId getMessageId() {
return messageId;
}
/**
* Sets the value of the messageId property.
*
* @param value
* allowed object is
* {@link ApiFormMessageId }
*
*/
public void setMessageId(ApiFormMessageId value) {
this.messageId = value;
}
/**
* Gets the value of the point property.
*
* @return
* possible object is
* {@link ApiPointTO }
*
*/
public ApiPointTO getPoint() {
return point;
}
/**
* Sets the value of the point property.
*
* @param value
* allowed object is
* {@link ApiPointTO }
*
*/
public void setPoint(ApiPointTO value) {
this.point = value;
}
/**
* Gets the value of the sendstatus property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSendstatus() {
return sendstatus;
}
/**
* Sets the value of the sendstatus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSendstatus(String value) {
this.sendstatus = value;
}
/**
* Gets the value of the sendstatusLastChangeTime property.
*
* @return
* possible object is
* {@link ApiDate }
*
*/
public ApiDate getSendstatusLastChangeTime() {
return sendstatusLastChangeTime;
}
/**
* Sets the value of the sendstatusLastChangeTime property.
*
* @param value
* allowed object is
* {@link ApiDate }
*
*/
public void setSendstatusLastChangeTime(ApiDate value) {
this.sendstatusLastChangeTime = value;
}
/**
* Gets the value of the timestamp property.
*
* @return
* possible object is
* {@link ApiDate }
*
*/
public ApiDate getTimestamp() {
return timestamp;
}
/**
* Sets the value of the timestamp property.
*
* @param value
* allowed object is
* {@link ApiDate }
*
*/
public void setTimestamp(ApiDate value) {
this.timestamp = value;
}
/**
* Gets the value of the userId property.
*
* @return
* possible object is
* {@link ApiUserId }
*
*/
public ApiUserId getUserId() {
return userId;
}
/**
* Sets the value of the userId property.
*
* @param value
* allowed object is
* {@link ApiUserId }
*
*/
public void setUserId(ApiUserId value) {
this.userId = value;
}
/**
* Gets the value of the vehicleId property.
*
* @return
* possible object is
* {@link ApiVehicleId }
*
*/
public ApiVehicleId getVehicleId() {
return vehicleId;
}
/**
* Sets the value of the vehicleId property.
*
* @param value
* allowed object is
* {@link ApiVehicleId }
*
*/
public void setVehicleId(ApiVehicleId value) {
this.vehicleId = value;
}
}
|
package edu.betygreg.domain;
public class GradeTek implements Grade {
private String grade = "U"; //TODO kan den vara u?
public GradeTek (String grade){
this.grade = grade;
}
@Override
public String getGrade() {
return grade;
}
@Override
public Grade setGrade(String grade) {
this.grade = grade;
/*
if (grade.compareTo(grades[0]) == 0 || grade.compareTo(grades[1]) == 0 || grade.compareTo(grades[2]) == 0 ||
grade.compareTo(grades[3]) == 0 || grade.compareTo(grades[4]) == 0) {
this.grade = grade;
} else {
System.out.println("Wrong input");
}
*/
return this;
}
}
|
/**
* 异步事件的定义.
*/
package xyz.noark.core.event; |
package fr.unice.polytech.isa.polyevent.entities.exceptions;
public class ClientDejaCreeException extends Exception {
private String mail;
public ClientDejaCreeException(String mail) {
this.mail = mail;
}
public ClientDejaCreeException() {
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
} |
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import java.awt.Font;
public class Calc_1 extends JFrame {
static int count = 0;
static int current;
static int result;
static int temp=0;
static boolean minus = false;
static int check_temp = 0;
static String screen = new String();
static boolean initial = true;
int arr[] = {1,1,1,1,1,1,1,1,1,1};
private JPanel contentPane;
private JTextField textField1;
private JTextField textField2;
private JButton buttonOperator1;
private JButton buttonOperator2;
private JButton buttonOperator3;
private JButton buttonOperator4;
private JButton button0;
private JButton buttonSpecial2;
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
private JButton button5;
private JButton button6;
private JButton button7;
private JButton button8;
private JButton button9;
void visibleAll(){
buttonOperator1.setVisible(true);
buttonOperator2.setVisible(true);
buttonOperator3.setVisible(true);
buttonOperator4.setVisible(true);
button0.setVisible(true);
buttonSpecial2.setVisible(true);
}
void disableAll(){
buttonOperator1.setVisible(false);
buttonOperator2.setVisible(false);
buttonOperator3.setVisible(false);
buttonOperator4.setVisible(false);
buttonSpecial2.setVisible(false);
}
void checkMinus(boolean test){
if (test){
arr[count]*=-1;
}
}
void disableNumber(){
button0.setVisible(false);
button1.setVisible(false);
button2.setVisible(false);
button3.setVisible(false);
button4.setVisible(false);
button5.setVisible(false);
button6.setVisible(false);
button7.setVisible(false);
button8.setVisible(false);
button9.setVisible(false);
}
void enableNumber(){
button0.setVisible(true);
button1.setVisible(true);
button2.setVisible(true);
button3.setVisible(true);
button4.setVisible(true);
button5.setVisible(true);
button6.setVisible(true);
button7.setVisible(true);
button8.setVisible(true);
button9.setVisible(true);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Calc_1 frame = new Calc_1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Calc_1() {
setTitle("Calculator 1.0");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField1 = new JTextField();
textField1.setFont(new Font("Tahoma", Font.PLAIN, 15));
textField1.setEditable(false);
textField1.setHorizontalAlignment(SwingConstants.RIGHT);
textField1.setBounds(20, 30, 209, 41);
contentPane.add(textField1);
textField1.setColumns(10);
textField2 = new JTextField();
textField2.setFont(new Font("Tahoma", Font.BOLD, 18));
textField2.setHorizontalAlignment(SwingConstants.RIGHT);
textField2.setEditable(false);
textField2.setColumns(10);
textField2.setBounds(20, 70, 209, 68);
contentPane.add(textField2);
JPanel panel = new JPanel();
panel.setBounds(253, 30, 171, 207);
contentPane.add(panel);
panel.setLayout(null);
button1 = new JButton("1");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
initial = false;
temp = temp*10 + 1;
visibleAll();
if (screen == null)
screen = "1";
else
screen += "1";
textField1.setText(screen);
}
});
button1.setBounds(0, 0, 55, 45);
panel.add(button1);
button4 = new JButton("4");
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
initial = false;
temp = temp*10 + 4;
visibleAll();
if (screen == null)
screen = "4";
else
screen += "4";
textField1.setText(screen);
}
});
button4.setBounds(0, 56, 55, 45);
panel.add(button4);
button7 = new JButton("7");
button7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
initial = false;
temp = temp*10 + 7;
visibleAll();
if (screen == null)
screen = "7";
else
screen += "7";
textField1.setText(screen);
}
});
button7.setBounds(0, 106, 55, 45);
panel.add(button7);
JButton buttonSpecial1 = new JButton(".");
buttonSpecial1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Coming soon in next version! This calculator only supports integer number!");
}
});
buttonSpecial1.setBounds(0, 162, 55, 45);
panel.add(buttonSpecial1);
button2 = new JButton("2");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
initial = false;
temp = temp*10 + 2;
visibleAll();
if (screen == null)
screen = "2";
else
screen += "2";
textField1.setText(screen);
}
});
button2.setBounds(53, 0, 55, 45);
panel.add(button2);
button3 = new JButton("3");
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
initial = false;
temp = temp*10 + 3;
visibleAll();
if (screen == null)
screen = "3";
else
screen += "3";
textField1.setText(screen);
}
});
button3.setBounds(107, 0, 55, 45);
panel.add(button3);
button5 = new JButton("5");
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
initial = false;
temp = temp*10 + 5;
visibleAll();
if (screen == null)
screen = "5";
else
screen += "5";
textField1.setText(screen);
}
});
button5.setBounds(53, 56, 55, 45);
panel.add(button5);
button6 = new JButton("6");
button6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
initial = false;
temp = temp*10 + 6;
visibleAll();
if (screen == null)
screen = "6";
else
screen += "6";
textField1.setText(screen);
}
});
button6.setBounds(107, 56, 55, 45);
panel.add(button6);
button8 = new JButton("8");
button8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
initial = false;
temp = temp*10 + 8;
visibleAll();
if (screen == null)
screen = "8";
else
screen += "8";
textField1.setText(screen);
}
});
button8.setBounds(53, 106, 55, 45);
panel.add(button8);
button9 = new JButton("9");
button9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
initial = false;
temp = temp*10 + 9;
visibleAll();
if (screen == null)
screen = "9";
else
screen += "9";
textField1.setText(screen);
}
});
button9.setBounds(107, 106, 55, 45);
panel.add(button9);
button0 = new JButton("0");
button0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
initial = false;
temp = temp*10 + 0;
visibleAll();
if (screen == null)
screen = "0";
else
screen += "0";
textField1.setText(screen);
}
});
button0.setBounds(53, 162, 55, 45);
panel.add(button0);
buttonSpecial2 = new JButton("=");
buttonSpecial2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
arr[count] *= temp;
temp = 0;
checkMinus(minus);
minus = false;
for(int i=0; i<=count; i++){
result+=arr[i];
}
String equal = String.valueOf(result);
textField2.setText(equal);
buttonSpecial2.setVisible(false);
disableNumber();
disableAll();
}
});
buttonSpecial2.setBounds(107, 162, 55, 45);
panel.add(buttonSpecial2);
buttonOperator1 = new JButton("+");
buttonOperator1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (initial)
JOptionPane.showMessageDialog(null, "Press the number first!!!");
else{
arr[count] *= temp;
temp=0;
checkMinus(minus);
minus = false;
count++;
disableAll();
screen += " + ";
textField1.setText(screen);
}
}
});
buttonOperator1.setBounds(20, 155, 66, 33);
contentPane.add(buttonOperator1);
buttonOperator2 = new JButton("-");
buttonOperator2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (initial)
JOptionPane.showMessageDialog(null, "Press the number first!!!");
else{
arr[count] *= temp;
temp=0;
checkMinus(minus);
count++;
disableAll();
minus = true;
screen += " - ";
textField1.setText(screen);
}
}
});
buttonOperator2.setBounds(96, 155, 66, 33);
contentPane.add(buttonOperator2);
buttonOperator3 = new JButton("*");
buttonOperator3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (initial)
JOptionPane.showMessageDialog(null, "Press the number first!!!");
else{
arr[count] *= temp;
temp = 0;
disableAll();
screen += "*";
textField1.setText(screen);
}
}
});
buttonOperator3.setBounds(20, 207, 66, 30);
contentPane.add(buttonOperator3);
buttonOperator4 = new JButton("/");
buttonOperator4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//disableAll();
//button0.setVisible(false);
JOptionPane.showMessageDialog(null, "Coming soon in next version! This calculator only supports integer number!");
}
});
buttonOperator4.setBounds(96, 207, 66, 30);
contentPane.add(buttonOperator4);
JButton buttonOperator5 = new JButton("Del");
buttonOperator5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField2.setText(null);
textField1.setText(null);
visibleAll();
for(int i=0; i<10; i++){
arr[i] = 1;
}
count = 0;
current = 0;
result = 0;
temp = 0;
minus = false;
screen = null;
textField1.setText(null);
enableNumber();
initial = true;
}
});
buttonOperator5.setBounds(172, 155, 57, 82);
contentPane.add(buttonOperator5);
}
}
|
package redempt.crunch.functional;
import redempt.crunch.token.TokenType;
import redempt.crunch.token.Value;
/**
* Represents a lazy function call with other lazy values as function arguments
* @author Redempt
*/
public class FunctionCall implements Value {
private Value[] values;
private Function function;
private double[] numbers;
public FunctionCall(Function function, Value[] values) {
this.function = function;
this.values = values;
numbers = new double[function.getArgCount()];
}
@Override
public TokenType getType() {
return TokenType.FUNCTION_CALL;
}
@Override
public double getValue() {
for (int i = 0; i < values.length; i++) {
numbers[i] = values[i].getValue();
}
return function.call(numbers);
}
@Override
public Value getClone() {
Value[] clone = new Value[values.length];
System.arraycopy(values, 0, clone, 0, values.length);
return new FunctionCall(function, values);
}
public String toString() {
StringBuilder builder = new StringBuilder(function.getName()).append('(');
for (int i = 0; i < values.length; i++) {
Value arg = values[i];
builder.append(arg.toString());
if (i != values.length - 1) {
builder.append(", ");
}
}
return builder.append(')').toString();
}
}
|
package poker;
import java.util.ArrayList;
import java.util.Random;
/**
*
* @author Danil
*/
public class Baraja {
private static ArrayList<Carta> baraja= new ArrayList<>(); //Tanto baraja como mano son ArrayList de tipo Carta
private static ArrayList<Carta> mano= new ArrayList<>();
private static String[] palos={"Oros","Copas","Espadas","Bastos"}; //palos y figuras son dos Arrays de String que contienen los palos y las figuras posibles
private static String[] figuras={"As","Dos","Sota","Caballo","Rey"};
/**
*
* @return
*/
public static ArrayList<Carta> creaBaraja(){
for (int palo=0; palo<4; palo++) {
for (int fig = 0; fig < 5; fig++) {
baraja.add(new Carta(palos[palo],figuras[fig])); //Creamos nuestra baraja añadiendo combinaciones de palos y figuras en Objetos de tipo Carta
}
}
return baraja;
}
/**
*
* @param baraja
* @return
*/
public static ArrayList<Carta> creaMano(ArrayList<Carta> baraja){
Random aleatorio = new Random();
for (int i = 0; i < 5; i++) {
int rand= aleatorio.nextInt(baraja.size());
mano.add(baraja.get(rand)); //Llenamos nuestra mano con cinco Objetos Carta aleatorios de nuestra baraja
baraja.remove(rand); //Luego, quitamos esa misma carta de baraja, para evitar repeticiones de carta en nuestra mano
}
return mano;
}
} |
package org.garret.perst.reflect;
/**
* Replacement of java.lang.reflect.Method class
*/
public class Member {
Type owner;
int modifiers;
protected Member(int modifiers) {
this.modifiers = modifiers;
}
/**
* Get member modifiers. There are not predefined modifiers, such as PUBLIC -
* iterpretation of modifiers bits is application dependent
* @return bitmask of member modifiers
*/
public int getModifiers() {
return modifiers;
}
/**
* Get declaring clsss descriptor
* @return descriptor of the class containing this member
*/
public Type getDeclaringClass() {
return owner;
}
}
|
package com.arthur.leetcode;
/**
* @program: leetcode
* @description: 重复叠加字符串匹配
* @title: No686
* @Author hengmingji
* @Date: 2021/12/22 10:26
* @Version 1.0
*/
public class No686 {
public int repeatedStringMatch(String a, String b) {
int m = a.length();
int n = b.length();
String temp = a;
int count = 1;
while (count <= (n / m + 2)) {
if(a.contains(b)) {
return count;
}
a += temp;
count++;
}
return -1;
}
}
|
package com.san.fieldXForm;
import org.springframework.data.repository.CrudRepository;
public interface FieldXFormRepository extends CrudRepository<FieldXForm, Integer> {
}
|
import java.util.Scanner;
public class micro06
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int numero=0;
System.out.print("Digite um numero de 1 a 5: ");
numero = s.nextInt();
switch(numero)
{
case 1:
System.out.println("Um");
break;
case 2:
System.out.println("Dois");
break;
case 3:
System.out.println("Tres");
break;
case 4:
System.out.println("Quatro");
break;
case 5:
System.out.println("Cinco");
break;
default:
System.out.println("Numero Invalido");
}
}
} |
package com.zc.pivas.printlabel.controller;
import com.google.gson.Gson;
import com.zc.base.common.controller.SdDownloadController;
import com.zc.base.orm.mybatis.paging.JqueryStylePaging;
import com.zc.base.orm.mybatis.paging.JqueryStylePagingResults;
import com.zc.pivas.printlabel.entity.PrintLogBean;
import com.zc.pivas.printlabel.service.PrintLogService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
/**
* 瓶签打印日志控制类
*
* @author Jack.M
* @version 1.0
*/
@Controller()
@RequestMapping(value = "/printLog")
public class PrintLogController extends SdDownloadController
{
/**
* 打印日志
*/
@Resource
private PrintLogService printLogService;
/**
*
* @param model
* @return
*/
@RequestMapping("/toPrintLog")
public String init(Model model)
{
return "pivas/bottleLabel/printLogList";
}
/**
* 查询所有数据
*
* @param bean
* @param jquryStylePaging
* @return
* @throws Exception
*/
@RequestMapping(value = "/printBottleLabelList", produces = "application/json")
@ResponseBody
public String printLabelConList(PrintLogBean bean, JqueryStylePaging jquryStylePaging)
throws Exception
{
JqueryStylePagingResults<PrintLogBean> pagingResults = printLogService.getPrintLogList(bean, jquryStylePaging);
return new Gson().toJson(pagingResults);
}
}
|
package matthbo.mods.darkworld.block.fluid;
import matthbo.mods.darkworld.init.ModFluids;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.BlockPos;
import net.minecraft.util.DamageSource;
import net.minecraft.world.World;
import net.minecraftforge.fluids.Fluid;
public class FluidDarkLava extends FluidDarkWorld {
public FluidDarkLava(Fluid fluidName) {
super(fluidName, Material.lava);
this.setUnlocalizedName("darklava");
}
@Override
public void onEntityCollidedWithBlock(World world, BlockPos pos, Entity entity) {
if(entity instanceof EntityLivingBase){
EntityLivingBase living = (EntityLivingBase)entity;
living.addPotionEffect(new PotionEffect(Potion.weakness.id, 200));
living.addPotionEffect(new PotionEffect(Potion.blindness.id, 80));
living.addPotionEffect(new PotionEffect(Potion.moveSlowdown.id, 40, 3));
living.addPotionEffect(new PotionEffect(Potion.poison.id, 600));
living.addPotionEffect(new PotionEffect(Potion.wither.id, 20, 3));
}
entity.setFire(10);
entity.attackEntityFrom(DamageSource.lava, 4.0F);
}
}
|
/* ------------------------------------------------------------------------------
* 软件名称:美播移动
* 公司名称:美播娱乐
* 开发作者:sg.z
* 开发时间:2014年7月29日/2014
* All Rights Reserved 2012-2015
* ------------------------------------------------------------------------------
* 注意:本内容均来自美播娱乐研发部,仅限内部交流使用,未经过公司许可 禁止转发
* ------------------------------------------------------------------------------
* prj-name:meibo-admin
* fileName:UserHandler.java
* -------------------------------------------------------------------------------
*/
package com.rednovo.ace.handler.show;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.tree.ConfigurationNode;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.ace.database.service.ShowService;
import com.ace.database.service.UserService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rednovo.ace.constant.Constant;
import com.rednovo.ace.constant.Constant.ChatMode;
import com.rednovo.ace.constant.Constant.InteractMode;
import com.rednovo.ace.constant.Constant.MsgType;
import com.rednovo.ace.constant.Constant.OperaterStatus;
import com.rednovo.ace.constant.Constant.userStatus;
import com.rednovo.ace.entity.LiveShow;
import com.rednovo.ace.entity.Message;
import com.rednovo.ace.entity.Summary;
import com.rednovo.ace.entity.User;
import com.rednovo.ace.globalData.GlobalUserSessionMapping;
import com.rednovo.ace.globalData.LiveShowManager;
import com.rednovo.ace.globalData.OutMessageManager;
import com.rednovo.ace.globalData.StaticDataManager;
import com.rednovo.ace.globalData.UserManager;
import com.rednovo.ace.globalData.UserRelationManager;
import com.rednovo.ace.handler.BasicServiceAdapter;
import com.rednovo.tools.KeyGenerator;
import com.rednovo.tools.PPConfiguration;
import com.rednovo.tools.UserAssistant;
import com.rednovo.tools.Validator;
import com.rednovo.tools.web.HttpSender;
/**
* @author yongchao.Yang/2014年7月15日
*/
public class ShowHandler extends BasicServiceAdapter {
private Logger logger = Logger.getLogger(ShowHandler.class);
private static Random rdm = new Random();
public static ArrayList<User> freedomUser = new ArrayList<User>();
private static Random r = new Random();
static {
XMLConfiguration cf = (XMLConfiguration) PPConfiguration.getXML("robot.xml");
List<ConfigurationNode> list = cf.getRoot().getChildren();
for (ConfigurationNode node2 : list) {
User u = new User();
u.setUserId(String.valueOf(node2.getChild(1).getValue()));
u.setNickName(String.valueOf(node2.getChild(4).getValue()));
u.setProfile(String.valueOf(node2.getChild(9).getValue()));
freedomUser.add(u);
}
}
/*
* (non-Javadoc)
*
* @see com.power.handler.BasicServiceAdapter\t\t #service()
*/
@Override
protected void service() {
String key = this.getKey();
if (StringUtils.equals("002-002", key)) {// 读取用户资料
this.newShow();
} else if ("002-004".equals(key)) {// 获取直播列表
this.getLiveShowList();
} else if ("002-005".equals(key)) {// 获取观众列表
this.getShowInitData();
} else if ("002-011".equals(key)) {// 分享直播
this.share();
} else if ("002-014".equals(key)) {// 结束直播(删除数据库)
this.updateShowData();
} else if ("002-015".equals(key)) {// 结束直
this.clearShowData();
} else if ("002-016".equals(key)) {// 直播清算
this.getShowSettleData();
} else if ("001-029".equals(key)) {// 获取我的订阅直列表
this.getSubscribeShow();
} else if ("002-017".equals(key)) {// 获取应用宝直播列表
this.getTencentList();
} else if ("002-018".equals(key)) {// 禁言
this.forbidUser();
} else if ("002-019".equals(key)) {// 拉去分享模板
this.getShareData();
}
}
/**
* 开播
*
* @author Yongchao.Yang
* @since 2016年3月8日下午2:49:04
*/
private void newShow() {
String userId = this.getWebHelper().getString("userId");
String title = this.getWebHelper().getString("title");
String position = this.getWebHelper().getString("position");
String name = this.getWebHelper().getString("showImg");
byte[] data = this.getWebHelper().getBytes("showImg");
User u = UserService.getUser(userId);
// 判断用户状态
if (u.getIsActive().equals(userStatus.FREEZE.getValue())) {
// 用户已经被冻结
this.setError("208");
return;
}
// 主播开播
if (userStatus.FORBIDSHOW.getValue().equals(u.getIsForbidShow())) {
this.setError("222", "用户被禁播");
return;
}
if (Validator.isEmpty(title)) {
title = UserManager.getUser(userId).getNickName() + "的直播";
} else {
List<String> words = StaticDataManager.getKeyWord(Constant.KeyWordType.NAME.getValue());
if (Validator.checkKeyWord(title, words)) {
this.setError("218");
return;
}
}
if (Validator.isEmpty(position)) {
position = "地球的背面";
}
String exeCode = "";
if (!Validator.isEmpty(name)) {
String imgName = KeyGenerator.createUniqueId() + "-show.png";
// 保存封面
String path = UserAssistant.getUserAbsoluteDir(userId);
File img = new File(path + File.separator + imgName);
FileOutputStream fis;
try {
if (!img.exists()) {
img.createNewFile();
}
fis = new FileOutputStream(img);
fis.write(data);
fis.flush();
fis.close();
} catch (Exception e) {
logger.error("保存封面失败", e);
e.printStackTrace();
}
String visitUrl = PPConfiguration.getProperties("cfg.properties").getString("img.server.root.url") + UserAssistant.getUserRelativeDir(userId) + "/" + imgName;
exeCode = UserService.updateShowImg(userId, visitUrl);
if (!Constant.OperaterStatus.SUCESSED.getValue().equals(exeCode)) {
this.setError(exeCode);
return;
}
}
exeCode = ShowService.addShow(userId, u.getShowImg(), title, position);
if (Constant.OperaterStatus.SUCESSED.getValue().equals(exeCode)) {
// 更新用户的位置信息
UserManager.setExtData(userId, "position", position);
this.setValue("upStream", PPConfiguration.getProperties("cfg.properties").getString("cdn.upstream.url") + userId);
this.setValue("showId", userId);
this.setSuccess();
// 添加推送队列
UserManager.addPushStarId(userId);
} else {
this.setError(exeCode);
}
}
/**
* 直播结算
*
* @author Yongchao.Yang
* @since 2016年3月15日下午7:20:39
*/
private void getShowSettleData() {
String showId = this.getWebHelper().getString("showId");
LiveShow ls = ShowService.getLiveShow(showId);
if (ls != null) {
this.setValue("support", ls.getSupportCnt());
this.setValue("coins", ls.getCoinCnt());
this.setValue("fans", ls.getFansCnt());
this.setValue("length", ls.getLength());
this.setValue("memberCnt", ls.getMemberCnt());
this.setSuccess();
} else {
this.setError("300");
}
}
/**
* 观众列表
*
* @author Yongchao.Yang
* @since 2016年3月8日下午8:52:11
*/
private void getShowInitData() {
String showId = this.getWebHelper().getString("showId");
int page = this.getWebHelper().getInt("page");
int pageSize = this.getWebHelper().getInt("pageSize");
ArrayList<User> memberList = new ArrayList<User>();
List<String> sessionIds = LiveShowManager.getMemberList(showId, 1, 1000);
for (String sid : sessionIds) {
String uid = GlobalUserSessionMapping.getSessionUser(sid);
if (Validator.isEmpty(uid)) {
User u = new User();
u.setUserId("-1");
u.setNickName("游客");
memberList.add(u);
} else {
User u = UserManager.getUser(uid);
u.setChannel(null);
u.setCreateTime(null);
u.setPassWord(null);
u.setUpdateTime(null);
u.setShowImg(null);
u.setTokenId(null);
u.setSchemaId(null);
u.setUuid(null);
u.setSubscribeCnt(0);
memberList.add(u);
}
Collections.shuffle(freedomUser);
for (int i = 0; i < 30; i++) {
memberList.add(freedomUser.get(i));
}
}
String supportCnt = LiveShowManager.getTotalSupportCnt(showId);
String memberSize = String.valueOf((LiveShowManager.getMemberCnt(showId) - 1) * 14 + LiveShowManager.getRobotCnt(showId));
this.setSuccess();
this.setValue("memberList", memberList);
this.setValue("supportCnt", Validator.isEmpty(supportCnt) ? "0" : supportCnt);
this.setValue("memberSize", memberSize);
}
/**
* 获取直播列表
*
* @author Yongchao.Yang
* @since 2016年3月3日下午9:54:45
*/
private void getLiveShowList() {
int page = this.getWebHelper().getInt("page");
int pageSize = this.getWebHelper().getInt("pageSize");
List<String> list = LiveShowManager.getSortList(page, pageSize);
ArrayList<User> users = new ArrayList<User>();
ArrayList<LiveShow> shows = new ArrayList<LiveShow>();
HashMap<String, User> userMap = new HashMap<String, User>();
for (String id : list) {
LiveShow s = LiveShowManager.getShow(id);
User u = UserManager.getUser(s.getUserId());
userMap.put(id, u);
if (s != null) {
// 考虑机器人数
long memberCnt = (LiveShowManager.getMemberCnt(id) - 1) * 14 + LiveShowManager.getRobotCnt(id);
s.setMemberCnt(String.valueOf(memberCnt));
long scroe = getSort(memberCnt, 0l, Long.valueOf(s.getStartTime()), Long.valueOf(u.getBasicScore()));
s.setSortCnt(scroe);
shows.add(s);
}
}
Collections.sort(shows);
for (LiveShow liveShow : shows) {
users.add(userMap.get(liveShow.getShowId()));
}
this.setSuccess();
this.setValue("showList", shows);
this.setValue("userList", users);
}
/**
* 分享成功
*
* @author Yongchao.Yang
* @since 2016年5月25日下午3:34:48
*/
private void share() {
String userId = this.getWebHelper().getString("userId");
String showId = this.getWebHelper().getString("showId");
String channel = this.getWebHelper().getString("channel");
HashMap<String, String> params = new HashMap<String, String>();
params.put("userId", userId);
params.put("showId", showId);
params.put("type", "2");
String res = HttpSender.httpClientRequest(PPConfiguration.getProperties("cfg.properties").getString("redis.server.url") + "/001-001", params);
/*Message msg = new Message();
Summary sumy = new Summary();
sumy.setRequestKey("002-018");
sumy.setChatMode(ChatMode.GROUP.getValue());
sumy.setInteractMode(InteractMode.REQUEST.getValue());
sumy.setMsgId("9999-share");
sumy.setMsgType(MsgType.TXT_MSG.getValue());
sumy.setSenderId(userId);
sumy.setShowId(showId);
sumy.setReceiverId(showId);
msg.setSumy(sumy);
JSONObject obj = new JSONObject();
User u = UserManager.getUser(userId);
obj.put("type", "2");
obj.put("channel", channel);
obj.put("userId", userId);
obj.put("nickName", u.getNickName());
obj.put("profile", u.getProfile());
msg.setBody(obj);
// 将消息压入缓存中
OutMessageManager.addMessage(msg);
*/
this.setSuccess();
}
private void getSubscribeShow() {
String userId = this.getWebHelper().getString("userId");
ArrayList<User> users = new ArrayList<User>();
ArrayList<LiveShow> subscribeList = new ArrayList<LiveShow>();
// 获取我订阅的主播
List<String> stars = UserRelationManager.getSubscribe(userId, 1, 10000);
if (!Validator.isEmpty(stars)) {
List<String> showIds = LiveShowManager.getSortList(1, 10000);
for (String uid : stars) {
for (String showId : showIds) {
if (showId.equals(uid)) {
users.add(UserManager.getUser(uid));
LiveShow s = LiveShowManager.getShow(showId);
s.setMemberCnt(String.valueOf((LiveShowManager.getMemberCnt(showId) - 1) * 14 + LiveShowManager.getRobotCnt(showId)));
subscribeList.add(s);
break;
}
}
}
} else {
this.setValue("ifSubscribe", "0");
}
if (!subscribeList.isEmpty()) {
this.setValue("showList", subscribeList);
} else {
// 获取最新的10条直播
List<String> newShowIds = LiveShowManager.getSortList(1, 10);
for (String sid : newShowIds) {
users.add(UserManager.getUser(sid));
LiveShow s = LiveShowManager.getShow(sid);
s.setMemberCnt(String.valueOf((LiveShowManager.getMemberCnt(sid) - 1) * 14 + LiveShowManager.getRobotCnt(sid)));
subscribeList.add(s);
}
this.setValue("recommandList", subscribeList);
}
this.setValue("userList", users);
this.setSuccess();
}
/**
* 结束直播
*
* @author Yongchao.Yang
* @since 2016年3月8日下午8:58:42
*/
private void updateShowData() {
String showId = this.getWebHelper().getString("showId");
if (OperaterStatus.SUCESSED.getValue().equals(ShowService.finishShow(showId))) {
this.setSuccess();
} else {
this.setError("300");
}
}
/**
* 结束直播所有数据
*
* @author Yongchao.Yang
* @since 2016年3月14日下午8:58:10
*/
private void clearShowData() {
String showId = this.getWebHelper().getString("showId");
ShowService.finishShow(showId);
LiveShowManager.removeSortShow(showId);
this.setSuccess();
}
private void getTencentList() {
int page = this.getWebHelper().getInt("page");
int pageSize = this.getWebHelper().getInt("pageSize");
List<String> list = LiveShowManager.getSortList(page, 1000);
HashMap<String, User> userMap = new HashMap<String, User>();
ArrayList<User> users = new ArrayList<User>();
ArrayList<LiveShow> shows = new ArrayList<LiveShow>();
for (String id : list) {
LiveShow s = LiveShowManager.getShow(id);
if (s != null) {
shows.add(s);
long memCnt = LiveShowManager.getMemberCnt(id);
s.setMemberCnt(String.valueOf(memCnt));
// 获取各项统计值
HashMap<String, String> data = LiveShowManager.getShowExtData(id);
// 获取用户
User u = UserManager.getUser(s.getUserId());
userMap.put(u.getUserId(), u);
// 计算用户当前拍排序值
long score = this.getSort(memCnt, Long.valueOf(data.get("SUPPORT")), Long.valueOf(s.getStartTime()), (long) u.getBasicScore());
s.setSortCnt(score);
}
}
// 排序
Collections.sort(shows);
JSONArray ja = new JSONArray();
for (LiveShow liveShow : shows) {
User u = userMap.get(liveShow.getUserId());
int radio_id = Integer.parseInt(liveShow.getUserId());
String radio_name = u.getNickName();
String radio_subname = "";
String radio_city = liveShow.getPosition();
long radio_fan_number = UserRelationManager.getFansCnt(liveShow.getUserId()) + rdm.nextInt(1000);
int radio_show_number = Integer.parseInt(liveShow.getMemberCnt()) + rdm.nextInt(1000);
String radio_label = "";
String radio_pic_url = u.getShowImg();
String radio_action_url = "http://api.17ace.cn/share/index2.html?showId=" + liveShow.getShowId();
int is_showing_now = 1;
JSONObject jo = new JSONObject();
jo.put("radio_id", radio_id);
jo.put("radio_name", radio_name);
jo.put("radio_subname", radio_subname);
jo.put("radio_city", radio_city);
jo.put("radio_fan_number", radio_fan_number);
jo.put("radio_show_number", radio_show_number);
jo.put("radio_label", radio_label);
jo.put("radio_pic_url", radio_pic_url);
jo.put("radio_action_url", radio_action_url);
jo.put("is_showing_now", is_showing_now);
ja.add(jo);
}
this.setValue("radio_list", ja);
this.setValue("ret", 0);
this.setValue("msg", "OK");
this.setSuccess();
}
private void forbidUser() {
String showId = this.getWebHelper().getString("showId");
String userId = this.getWebHelper().getString("userId");
String type = this.getWebHelper().getString("type");
if ("1".equals(type)) {
LiveShowManager.delForbidUser(userId, showId);
} else {
LiveShowManager.addForbidUser(userId, showId);
}
this.setSuccess();
}
/**
* 拉取分享模板数据
*
* @author Yongchao.Yang
* @since 2016年5月24日下午8:39:12
*/
private void getShareData() {
String showId = this.getWebHelper().getString("showId");
String userId = this.getWebHelper().getString("userId");
String type = this.getWebHelper().getString("type");
if (Validator.isEmpty(userId) || Validator.isEmpty(type) || Validator.isEmpty(showId)) {
this.setError("218");
return;
}
// type:1 主播自己分享 0普通用户
String title = StaticDataManager.getSysConfig("shareTitle"), imgSrc = "", sumy = StaticDataManager.getSysConfig("shareSummary"), url = StaticDataManager.getSysConfig("shareURL") + "?showId=" + showId;
User u = UserManager.getUser(showId);
if ("1".equals(type)) {
title = title.replaceAll("\\$", u.getNickName());
} else {
LiveShow show = LiveShowManager.getShow(showId);
title = show.getTitle();
}
imgSrc = u.getShowImg();
this.setValue("title", title);
this.setValue("imgSrc", Validator.isEmpty(imgSrc) ? "http://cache.17ace.cn/share/default.png" : imgSrc);
this.setValue("sumy", sumy.replaceAll("\\$", u.getNickName()));
this.setValue("url", url);
this.setSuccess();
}
/**
* 计算直播的排序
*
* @param memberCnt int 每个用户2个权重
* @param supportCnt int 每个100个赞1个权重
* @param remainTime int 每剩余10秒2个权重
* @param basicCnt int 基本权重
* @return
* @author Yongchao.Yang
* @since 2016年4月23日下午6:33:25
*/
private long getSort(long memberCnt, long supportCnt, long beginTime, long basicCnt) {
long score = memberCnt * 2;
// score = score + (supportCnt / 500);
// long remainTime = (System.currentTimeMillis() - beginTime) / 1000;// 播放时长
// // 开播前5分钟给于加权
// if (remainTime < 600) {
// score = score + (600 - remainTime) / 60;
// }
score = score + basicCnt;
return score;
}
}
|
package Scrabble;
import java.io.InputStream;
final public class TileImgLoader {
public static InputStream load(String pathName){
InputStream inputPicture = TileImgLoader.class.getResourceAsStream(pathName);
if(inputPicture == null){
inputPicture = TileImgLoader.class.getResourceAsStream("/"+pathName);
}
return inputPicture;
}
}
|
import java.io.*;
import java.util.*;
public class Main {
static Scanner in = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int[] names = new int[26];
static int combination (int n) {
return n * (n - 1) / 2;
}
public static void main(String[] args) {
int n = in.nextInt();
in.nextLine();
for (int i = 0; i < n; i++) {
String name = in.nextLine();
names[name.charAt(0) - 'a']++;
}
int ans = 0;
for (int i = 0; i < 26; i++) {
int a = names[i] / 2;
int b = names[i] - a;
ans += combination(a) + combination(b);
}
out.println(ans);
in.close();
out.close();
}
} |
package org.jasypt.util.filehandler;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Properties;
import org.apache.commons.io.FilenameUtils;
import org.jasypt.intf.cli.JasyptEncryptorUtil;
/**
* This class will handle encryption/decryption of simple files.</br>
* Encryption/Decryption is done on a line-by-line basis and the whole line is encrypted.
* <b>This class is for internal use only</b>.
*
* @author prakash.tiwari
*
*/
public class SimpleHandler implements FileHandler {
String location = System.getProperty("user.dir") + "/";
public String encryptFile(String fileName, Properties argumentValues) throws Exception{
JasyptEncryptorUtil encryptor = new JasyptEncryptorUtil(argumentValues);
String path = location + fileName;
BufferedReader reader = new BufferedReader(new FileReader(path));
String fileType = FilenameUtils.getExtension(fileName);
String dot = (fileType.length()> 0)?("."):("");
String output = "output"+ dot + fileType;
path = location + output;
FileWriter outputFile = new FileWriter(path);
String line = reader.readLine();
while (line != null) {
line.trim();
if(line.length()>0) {
String encryptedValue = encryptor.encrypt(line);
outputFile.write(encryptedValue + "\n");
}
else {
outputFile.write("\n");
}
line = reader.readLine(); // read next line
}
reader.close();
outputFile.close();
return path;
}
public String decryptFile(String fileName, Properties argumentValues) throws Exception{
JasyptEncryptorUtil encryptor = new JasyptEncryptorUtil(argumentValues);
String path = location + fileName;
BufferedReader reader = new BufferedReader(new FileReader(path));
String fileType = FilenameUtils.getExtension(fileName);
String dot = (fileType.length()> 0)?("."):("");
String output = "decryptedOutput"+ dot + fileType;
path = location + output;
FileWriter outputFile = new FileWriter(path);
String line = reader.readLine();
while (line != null) {
line.trim();
if(line.length()>0) {
String decryptedValue = encryptor.decrypt(line);
outputFile.write(decryptedValue + "\n");
}
else {
outputFile.write("\n");
}
line = reader.readLine(); // read next line
}
reader.close();
outputFile.close();
return path;
}
}
|
package com.pdd.pop.sdk.http.api.request;
import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty;
import com.pdd.pop.sdk.http.api.response.PddSmsRemainSettingDetailQueryResponse;
import com.pdd.pop.sdk.http.HttpMethod;
import com.pdd.pop.sdk.http.PopBaseHttpRequest;
import com.pdd.pop.sdk.common.util.JsonUtil;
import java.util.Map;
import java.util.TreeMap;
public class PddSmsRemainSettingDetailQueryRequest extends PopBaseHttpRequest<PddSmsRemainSettingDetailQueryResponse>{
/**
* //1:提醒付款 ; 3:召唤买家成团
*/
@JsonProperty("scene")
private Integer scene;
@Override
public String getVersion() {
return "V1";
}
@Override
public String getDataType() {
return "JSON";
}
@Override
public String getType() {
return "pdd.sms.remain.setting.detail.query";
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.POST;
}
@Override
public Class<PddSmsRemainSettingDetailQueryResponse> getResponseClass() {
return PddSmsRemainSettingDetailQueryResponse.class;
}
@Override
public Map<String, String> getParamsMap() {
Map<String, String> paramsMap = new TreeMap<String, String>();
paramsMap.put("version", getVersion());
paramsMap.put("data_type", getDataType());
paramsMap.put("type", getType());
paramsMap.put("timestamp", getTimestamp().toString());
if(scene != null) {
paramsMap.put("scene", scene.toString());
}
return paramsMap;
}
public void setScene(Integer scene) {
this.scene = scene;
}
} |
package com.staniul.teamspeak.commands.core;
public class Command {
private String command;
private String description;
private int scope;
public Command() {
}
public Command(String command, String description, int scope) {
this.command = command;
this.description = description;
this.scope = scope;
}
public String getCommand() {
return command;
}
public String getDescription() {
return description;
}
public int getScope() {
return scope;
}
}
|
package com.stratio.pf.sparkAT.coverage.hdfs;
import com.stratio.qa.cucumber.testng.CucumberRunner;
import com.stratio.spark.tests.utils.BaseTest;
import cucumber.api.CucumberOptions;
import org.testng.annotations.Test;
@CucumberOptions(features = {
"src/test/resources/features/pf/coverage/hdfs-coverage.feature"
})
public class HDFSCoverage_IT extends BaseTest {
public HDFSCoverage_IT() {
}
@Test(enabled = true, groups = {"HDFSCoverage"})
public void hdfsCoverage() throws Exception {
new CucumberRunner(this.getClass()).runCukes();
}
}
|
public interface ClasseDirigida {
void plaClasseMaquina ();
void plaClassePiscina ();
void plaClasseDirigida ();
}
|
package kiemtra;
import java.util.ArrayList;
import java.util.Scanner;
public class Quanlynhanvien extends Nhanvien {
public static ArrayList<Quanlynhanvien> qlnv = new ArrayList<Quanlynhanvien>();
private Scanner s = new Scanner(System.in);
public Quanlynhanvien(String ma, String hoTen, double luong) {
super(ma, hoTen, luong);
}
public void menu() {
while(true) {
System.out.println("------------------$-MENU-$-------------------");
System.out.println("-1.Nhập danh sách nhân viên từ bàn phím.");
System.out.println("-2.Xuất danh sách nhân viên ra màn hình.");
System.out.println("-3.Tìm và hiển thị nhân viên theo mã nhập từ bàn phím.");
System.out.println("-4.Xóa nhân viên theo mã nhập từ bàn phím.");
System.out.println("-5.Cập nhật thông tin nhân viên theo mã nhập từ bàn phím");
System.out.println("-6.Tìm các nhân viên theo khoảng lương nhập từ bàn phím.");
System.out.println("-7.Sắp xếp nhân viên theo họ và tên.");
System.out.println("-8.Sắp xếp nhân viên theo thu nhập.");
System.out.println("-9.Xuất 5 nhân viên có thu nhập cao nhất.");
System.out.println("-10.Kết thúc");
System.out.println("---------------------------------------------");
System.out.println("Lua chon menu :");
String chon = s.nextLine();
switch (chon) {
case "1":
nhap();
break;
case "2":
xuat();
break;
case "3":
search();
break;
case "4":
xoa();
break;
case "5":
capnhat();
break;
case "6":
timtheoluong();
break;
case "7":
sapxeptheoten();
break;
case "8":
sapxeptheothunhap();
break;
case "9":
thunhapcaonhat();
break;
case "10":
System.out.println("Tam biet");
s.close();
System.exit(0);
break;
default:
System.out.println("Menu khong ton tai");
break;
}
}
}
public void nhap() {
System.out.println("Moi ban chon nhan vien de nhap: ");
System.out.println("1.Nhan vien hanh chanh");
System.out.println("2.Nhan vien tiep thi");
System.out.println("3.Truong phong");
String loaiNhanvien = s.nextLine();
if("1".equals(loaiNhanvien)) {
System.out.println("Nhap ma nhan vien: ");
String ma = s.nextLine();
System.out.println("Nhap ten nhan vien: ");
String hoTen = s.nextLine();
System.out.println("Nhap luong nhan vien: ");
double luong = Double.parseDouble(s.nextLine());
Quanlynhanvien nv = new Quanlynhanvien(ma, hoTen, luong);
qlnv.add(nv);
}else if ("2".equals(loaiNhanvien)) {
System.out.println("Nhap ma nhan vien: ");
String ma = s.nextLine();
System.out.println("Nhap ten nhan vien: ");
String hoTen = s.nextLine();
System.out.println("Nhap luong nhan vien: ");
double luong = Double.parseDouble(s.nextLine());
System.out.println("Doanh so ban hang: ");
double doanhso = Double.parseDouble(s.nextLine());
System.out.println("Ti le hoa hong: ");
double hoahong = Double.parseDouble(s.nextLine());
Quanlynhanvien nv = new Quanlynhanvien(ma, hoTen, luong);
qlnv.add(nv);
}else if ("3".equals(loaiNhanvien)) {
System.out.println("Nhap ma nhan vien: ");
String ma = s.nextLine();
System.out.println("Nhap ten nhan vien: ");
String hoTen = s.nextLine();
System.out.println("Nhap luong nhan vien: ");
double luong = Double.parseDouble(s.nextLine());
System.out.println("Nhap luong trach nhiem: ");
double trachnhiem = Double.parseDouble(s.nextLine());
Quanlynhanvien nv = new Quanlynhanvien(ma, hoTen, luong);
qlnv.add(nv);
}else {
System.out.println("Ban da chon sai!");
}
}
public void xuat() {
if (qlnv.size() != 0) {
for (int i=0;i<qlnv.size();i++) {
System.out.println("===============");
String ma = qlnv.get(i).ma;
System.out.println("Ma nhan vien: " + ma);
String hoTen = qlnv.get(i).hoTen;
System.out.println("Ten nhan vien: " + hoTen);
double luong = qlnv.get(i).luong;
System.out.println("Luong nhan vien: " + luong);
}
} else {
System.out.println("Danh sach nhan vien rong");
}
}
public void search() {
System.out.println("Nhap ma tim kiem: ");
String nhapma = s.nextLine();
for(int i=0;i<qlnv.size();i++) {
if(nhapma.equalsIgnoreCase(qlnv.get(i).ma)) {
System.out.println("===============");
String ma = qlnv.get(i).ma;
System.out.println("Ma nhan vien: " + ma);
String hoTen = qlnv.get(i).hoTen;
System.out.println("Ten nhan vien: " + hoTen);
}
}
}
public void xoa() {
String nhapten;
System.out.println("Nhap ma muon xoa: ");
nhapten = s.nextLine();
int check = 0;
int giaTri = 0;
for (int i=0;i<qlnv.size();i++) {
String maso=qlnv.get(i).ma;
if(nhapten.equals(maso)) {
check = 1;
giaTri = i;
} else {
}
}
if (check==1) {
qlnv.remove(giaTri);
xuat();
} else {
System.out.println("Không có mã trong danh sách");
}
}
public void capnhat() {
System.out.println("Nhap ma cap nhat: ");
String nhapma = s.nextLine();
for(int i=0;i<qlnv.size();i++) {
if(nhapma.equalsIgnoreCase(qlnv.get(i).ma)) {
System.out.println("Ma thay doi: ");
String nhaplaima = s.nextLine();
qlnv.get(i).ma = nhaplaima;
System.out.println("Ten thay doi: ");
String nhaplaiten = s.nextLine();
qlnv.get(i).hoTen = nhaplaiten;
System.out.println("Ma thay doi: "+nhaplaima);
System.out.println("Ten thay doi: "+nhaplaiten);
}
}
}
public void timtheoluong() {
}
public void sapxeptheoten() {
}
public void sapxeptheothunhap() {
}
public void thunhapcaonhat() {
}
@Override
public double getLuong() {
// TODO Auto-generated method stub
return 0;
}
}
|
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;
class Pi {
private static final BigDecimal ONE = new BigDecimal(1);//constant with Value 1
private static final BigDecimal TWO = new BigDecimal(2);//constant with Value 2
private static final BigDecimal FOUR = new BigDecimal(4);//constant with Value 4 (used in multiplying at end)
public static void main(String[] args) {
/* initialize and obtain user input */
Scanner scanner = new Scanner(System.in);
int num;
System.out.println("Please enter the digits of Pi you wish to calculate:");
num = scanner.nextInt();
/* run method calculate with user input and print out our answer */
System.out.println(calculate(num));
System.out.println("Please note that PI may not be accurate in the last few digits, this is due to rounding.");
}
/* Gauss-Legendre Algorithm for calculating PI */
public static BigDecimal calculate(final int NUM) {
BigDecimal b1 = ONE;
BigDecimal b2 = ONE.divide(sqrt(TWO, NUM), NUM, RoundingMode.HALF_UP);
BigDecimal b3 = new BigDecimal("0.25");
BigDecimal b4 = ONE;
BigDecimal b5;
while (!b1.equals(b2)) {
b5 = b1;
b1 = b1.add(b2).divide(TWO, NUM, RoundingMode.HALF_UP);
b2 = sqrt(b2.multiply(b5), NUM);
b3 = b3.subtract(b4.multiply(b5.subtract(b1).multiply(b5.subtract(b1))));
b4 = b4.multiply(TWO);
}
return b1.add(b2).multiply(b1.add(b2)).divide(b3.multiply(FOUR), NUM, RoundingMode.HALF_UP);
}
/* Newton's method */
public static BigDecimal sqrt(BigDecimal NUM1, final int NUM2) {
BigDecimal b1 = new BigDecimal("0");
BigDecimal b2 = BigDecimal.valueOf(Math.sqrt(NUM1.doubleValue()));
while (!b1.equals(b2)) {
b1 = b2;
b2 = NUM1.divide(b1, NUM2, RoundingMode.HALF_UP);
b2 = b2.add(b1);
b2 = b2.divide(TWO, NUM2, RoundingMode.HALF_UP);
}
return b2;
}
} |
package org.wuxinshui.boosters.designPatterns.simpleFacthory.moreMethods;
/**
* Created by FujiRen on 2016/10/30.
* 简单工厂模式不属于23中涉及模式,简单工厂一般分为:普通简单工厂、多方法简单工厂、静态方法简单工厂。
*/
public class SendFactory {
public Sender produceEmail() {
return new Email();
}
public Sender produceSms() {
return new Sms();
}
}
|
package it.bibliotecaweb.service.utente;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import it.bibliotecaweb.dao.utente.UtenteDAO;
import it.bibliotecaweb.model.Utente;
import it.bibliotecaweb.service.IBaseService;
public interface UtenteService extends IBaseService<Utente> {
public void setUtenteDAO(UtenteDAO utenteDAO);
public void passaAdAttivo(Utente utenteInput);
public void passaAInattivo(Utente utenteInput);
public Utente findUtenteByUsernamePassword(String username, String password);
public List<String> validate(HttpServletRequest req);
}
|
package com.ddup.mapper;
import com.ddup.dto.QuestionQueryDTO;
import com.ddup.model.Question;
import java.util.List;
public interface QuestionExtMapper {
int incView(Question question);
int incCommentCount(Question question);
List<Question> selectRelated(Question question);
Integer countBySearch(QuestionQueryDTO questionQueryDTO);
List<Question> selectBySearch(QuestionQueryDTO questionQueryDTO);
} |
package DAO.Dbtable;
import Helpers.DbTable;
/**
* Classe Prog_allen_manu che estende l'helpers DbTable
*/
public class Prog_allen_manu extends DbTable {
public Prog_allen_manu(){
name="prog_allen_man";
sql="";
}
} |
package arrival.storm;
import arrival.util.TimeUtil;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.BasicOutputCollector;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseBasicBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import arrival.util.Accout;
import arrival.util.UserGroup;
import java.io.IOException;
import java.util.Map;
/**
* 接收所有的信令
*/
public class UserGroupStatusDetectorBolt extends BaseBasicBolt implements UserGroup.Listener {
private static Logger logger = LoggerFactory.getLogger(UserGroupStatusDetectorBolt.class);
private UserGroup userGroup = new UserGroup(this);
private BasicOutputCollector outputcollector;
public static final String DETECTORSTREAM = "detectorStream";
private long lastSignalTime = 0L;
@Override
public void execute(Tuple input, BasicOutputCollector collector) {
if (logger.isDebugEnabled()){
logger.debug(input.toString());
}
this.outputcollector = collector;
String sourceStreamId = input.getSourceStreamId();
if (PreconditionBolt.PRECONDITION.equals(sourceStreamId)) {
String imsi = input.getString(0);
String eventType = input.getString(1);
long time = input.getLong(2);
String lac = input.getString(3);
String cell = input.getString(4);
try {
userGroup.onSignal(time, eventType, imsi, lac, cell);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
else if (PreconditionBolt.UPDATETIME.equals(sourceStreamId)) {
long time = input.getLong(0);
if (time > lastSignalTime){
userGroup.updateGlobleTime(time, input.getString(1));
lastSignalTime = time;
if (logger.isDebugEnabled()){
logger.debug(input.toString());
}
} else {
logger.info("drop time:" + time + "/" + TimeUtil.getTime(time) + " < " + lastSignalTime);
}
}
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declareStream(DETECTORSTREAM, new Fields("time", "imsi", "status")); //用户有三种状态:1:到港客户(arrival),2:工作人员(worker),3:什么都不是(normal)
}
@Override
public void onAddArrival(long userTime, String imsi, Accout.Status preStatus) {
if (preStatus == Accout.Status.Arrival) return;
// this.outputcollector.emit(DETECTORSTREAM, new Values(userTime, imsi, "arrival"));
System.out.println(String.format("+a:%s %s/%s", imsi, userTime, TimeUtil.getTime(userTime)));
}
@Override
public void onAddWorker(long userTime, String imsi, Accout.Status preStatus) {
if (preStatus == Accout.Status.Worker) return;
// this.outputcollector.emit(DETECTORSTREAM, new Values(userTime, imsi, "worker"));
System.out.println(String.format("-w:%s %s/%s", imsi, userTime, TimeUtil.getTime(userTime)));
}
@Override
public void onAddNormal(long userTime, String imsi, Accout.Status preStatus) {
if (preStatus == Accout.Status.Normal) return;
// this.outputcollector.emit(DETECTORSTREAM, new Values(userTime, imsi, "normal"));
System.out.println(String.format("-n:%s %s/%s", imsi, userTime, TimeUtil.getTime(userTime)));
}
@Override
public void sendSms(long userTime, String imsi) {
this.outputcollector.emit(DETECTORSTREAM, new Values(userTime, imsi, "sms"));
System.out.println(String.format("+sms:%s %s/%s", imsi, userTime, TimeUtil.getTime(userTime)));
}
@Override
public void cleanup() {
userGroup.close();
}
@Override
public void prepare(Map stormConf, TopologyContext context) {
this.userGroup.init();
}
}
|
package org.shujito.cartonbox.model;
public class Response
{
private String reason;
private boolean success;
/* constructor */
public Response()
{
this.reason = null;
this.success = false;
}
/* getters */
public String getReason()
{ return reason; }
public boolean isSuccess()
{ return success; }
/* setters */
public Response setReason(String s)
{
this.reason = s;
return this;
}
public Response setSuccess(boolean b)
{
this.success = b;
return this;
}
}
|
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertFalse;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class BloomFilterTest {
private List<String> dictionary;
@Before
public void init() {
dictionary = Arrays.asList("a", "aa", "ab", "abc", "b", "c", "d", "e", "f", "gh");
System.out.println(Math.log(1130491)/Math.log(2));
System.out.println(Math.pow(2,21));
}
@Test
public void emptyBloomFilterAlwaysReturnNotFound() throws NoSuchAlgorithmException {
BloomFilter bloomFilter = new BloomFilter(16);
assertFalse(bloomFilter.test("a"));
}
@Test
public void whenElementAddedThenPossiblyExist() throws NoSuchAlgorithmException {
BloomFilter bloomFilter = new BloomFilter(16);
bloomFilter.add("a");
assertTrue(bloomFilter.test("a"));
}
@Test
public void addAllDictionaryWordsAndTestAllOfThemShouldBeTrue() throws NoSuchAlgorithmException {
BloomFilter bloomFilter = new BloomFilter(16);
for (String word: dictionary) {
bloomFilter.add(word);
}
for (String word: dictionary) {
assertTrue(bloomFilter.test(word));
}
assertFalse(bloomFilter.test("aaa"));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.