text stringlengths 10 2.72M |
|---|
package com.mtl.hulk.bench;
import com.mtl.hulk.tools.SystemPropertyUtil;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.runner.options.ChainedOptionsBuilder;
/**
* Default implementation of the JMH microbenchmark adapter.
*/
@Fork(AbstractBenchmark.DEFAULT_FORKS)
public class AbstractBenchmark extends AbstractBenchmarkBase {
protected static final int DEFAULT_FORKS = 2;
private final String[] jvmArgs;
public AbstractBenchmark() {
this(false);
}
public AbstractBenchmark(boolean disableAssertions) {
final String[] customArgs;
customArgs = new String[]{"-Xms768m", "-Xmx768m", "-XX:MaxDirectMemorySize=768m"};
String[] jvmArgs = new String[BASE_JVM_ARGS.length + customArgs.length];
System.arraycopy(BASE_JVM_ARGS, 0, jvmArgs, 0, BASE_JVM_ARGS.length);
System.arraycopy(customArgs, 0, jvmArgs, BASE_JVM_ARGS.length, customArgs.length);
if (disableAssertions) {
jvmArgs = removeAssertions(jvmArgs);
}
this.jvmArgs = jvmArgs;
}
@Override
protected String[] jvmArgs() {
return jvmArgs;
}
@Override
protected ChainedOptionsBuilder newOptionsBuilder() throws Exception {
ChainedOptionsBuilder runnerOptions = super.newOptionsBuilder();
if (getForks() > 0) {
runnerOptions.forks(getForks());
}
return runnerOptions;
}
protected int getForks() {
return SystemPropertyUtil.getInt("forks", -1);
}
}
|
package com.rankytank.client.pages;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.*;
import com.rankytank.client.gui.AddResultPopUp;
import com.rankytank.client.gui.RankingUI;
import com.jg.core.client.ui.TextBoxUi;
import com.rankytank.client.model.TestData;
/**
*
*/
public class RankingPage extends FlowPanel {
private RankingUI left;
private FlowPanel top;
private FlowPanel right;
private Label header;
private Button addResultButton;
public RankingPage() {
getElement().getStyle().setBackgroundColor("rgb(231,231,231)");
Image image = new Image("logo.png");
image.getElement().getStyle().setPosition(Style.Position.FIXED);
image.getElement().getStyle().setBottom(0, Style.Unit.PX);
image.getElement().getStyle().setRight(120, Style.Unit.PX);
add(image);
add(getTop());
add(getLeft());
add(getRight());
setHeight("100%");
}
public FlowPanel getLeft() {
if (left == null) {
left = new RankingUI(TestData.getPlayers());
left.setHeight("100%");
left.setStyleName("lineShadow");
left.getElement().getStyle().setFloat(Style.Float.LEFT);
left.getElement().getStyle().setMargin(30, Style.Unit.PX);
left.getElement().getStyle().setBackgroundColor("rgb(251,251,251)");
}
return left;
}
public FlowPanel getTop() {
if (top == null) {
top = new FlowPanel();
top.setHeight("50px");
top.add(getHeader());
}
return top;
}
public Label getHeader() {
if (header == null) {
header = new Label("Schantz' Bordfodboldrangliste");
header.setStyleName("ranking_title");
}
return header;
}
public FlowPanel getRight() {
if (right == null) {
right = new FlowPanel();
right.setWidth("300px");
right.getElement().getStyle().setFloat(Style.Float.LEFT);
right.getElement().getStyle().setMargin(0, Style.Unit.PX);
right.getElement().getStyle().setMarginTop(50, Style.Unit.PX);
right.add(getAddResultButton());
right.add(new TextBoxUi());
}
return right;
}
public Button getAddResultButton() {
if (addResultButton == null) {
addResultButton = new Button("Add match");
addResultButton.setStyleName("colorbutton3");
addResultButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
final MultiWordSuggestOracle or = new MultiWordSuggestOracle();
or.add("Jonas Green");
or.add("Anders Matthesen");
or.add("Jonas Andersen");
or.add("Jonas Frank");
or.add("Jonas John");
or.add("Jon Green");
AddResultPopUp popUp = new AddResultPopUp(or);
popUp.show();
}
});
}
return addResultButton;
}
}
|
/*
* 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 senha.model;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
/**
*
* @author gustavosmc
*/
public class PrinterSenha {
private FrameModelo frame;
private final PrinterJob printerJob;
private final String senha;
private final String data;
private final String hora;
private final String tipoAtendimento;
public PrinterSenha(String tipoAtendimento, String senha, String data, String hora, String prefixo, String setor){
this.hora = hora;
this.senha = prefixo + senha;
this.data = data;
this.tipoAtendimento = setor +" "+ tipoAtendimento;
printerJob = PrinterJob.getPrinterJob();
}
public void printSenha(){
frame = new FrameModelo(tipoAtendimento, senha, data, hora);
printerJob.setPrintable(frame);
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(MediaSizeName.NA_8X10);
try {
printerJob.print(pras);
System.out.println("Impresso com sucesso");
} catch (PrinterException ex) {
System.out.println("Não foi possivel imprimir");
Logger.getLogger(PrinterSenha.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
/*
* Copyright (C) 2009 INBio ( Instituto Nacional de Biodiversidad )
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.inbio.ara.dto.security;
import org.inbio.ara.dto.BaseEntityOrDTOFactory;
import org.inbio.ara.persistence.person.Person;
import org.inbio.ara.persistence.taxonomy.NomenclaturalGroup;
/**
*
* @author esmata
*/
public class NomenclaturalGroupDTOFactory extends
BaseEntityOrDTOFactory<NomenclaturalGroup, NomenclaturalGroupDTO> {
public NomenclaturalGroupDTO createDTO(NomenclaturalGroup entity) {
if(entity == null) return null;
NomenclaturalGroupDTO result = new NomenclaturalGroupDTO();
result.setCollectionId(entity.getCollectionId());
result.setDescription(entity.getDescription());
result.setName(entity.getName());
result.setNomenclaturalGroupId(entity.getNomenclaturalGroupId());
result.setTemporality(entity.getTemporality());
result.setCommonName(entity.getCommonName());
result.setCertificatorPersonId(entity.getCertificatorPersonId());
if(entity.getCertificatorPerson() != null){
result.setCertificatorPerson(entity.getCertificatorPerson().getNaturalLongName());
}
result.setNotes(entity.getNotes());
return result;
}
@Override
public NomenclaturalGroup getEntityWithPlainValues(
NomenclaturalGroupDTO dto) {
if(dto == null) return null;
NomenclaturalGroup entity = new NomenclaturalGroup();
entity.setNomenclaturalGroupId(dto.getNomenclaturalGroupId());
entity.setName(dto.getName());
entity.setDescription(dto.getDescription());
entity.setTemporality(dto.getTemporality());
entity.setCommonName(dto.getCommonName());
entity.setCertificatorPersonId(dto.getCertificatorPersonId());
entity.setCollectionId(dto.getCollectionId());
entity.setNotes(dto.getNotes());
return entity;
}
@Override
public NomenclaturalGroup updateEntityWithPlainValues(
NomenclaturalGroupDTO dto, NomenclaturalGroup entity) {
if(dto == null || entity == null) return null;
entity.setNomenclaturalGroupId(dto.getNomenclaturalGroupId());
entity.setName(dto.getName());
entity.setDescription(dto.getDescription());
entity.setTemporality(dto.getTemporality());
entity.setCommonName(dto.getCommonName());
entity.setCertificatorPersonId(dto.getCertificatorPersonId());
entity.setCollectionId(dto.getCollectionId());
entity.setNotes(dto.getNotes());
return entity;
}
}
|
public class RandomNumber2{
public static void main(String[] args){
int randomnumber = (int ) (Math.random() * 6 + 1);
int randomnumber2 = (int ) (Math.random() * 6 + 1);
System.out.println("Dice 1: " + randomnumber);
System.out.println("Dice 2: " + randomnumber2);
System.out.println("Sum: " + (randomnumber + randomnumber2));
}
} |
/*
* 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;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;
import kotlin.Unit;
import kotlin.coroutines.CoroutineContext;
import kotlin.jvm.JvmClassMappingKt;
import kotlin.reflect.KClass;
import kotlin.reflect.KClassifier;
import kotlin.reflect.KFunction;
import kotlin.reflect.KParameter;
import kotlin.reflect.full.KCallables;
import kotlin.reflect.jvm.KCallablesJvm;
import kotlin.reflect.jvm.ReflectJvmMapping;
import kotlinx.coroutines.BuildersKt;
import kotlinx.coroutines.CoroutineStart;
import kotlinx.coroutines.Deferred;
import kotlinx.coroutines.Dispatchers;
import kotlinx.coroutines.GlobalScope;
import kotlinx.coroutines.flow.Flow;
import kotlinx.coroutines.reactor.MonoKt;
import kotlinx.coroutines.reactor.ReactorFlowKt;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* Utilities for working with Kotlin Coroutines.
*
* @author Sebastien Deleuze
* @author Phillip Webb
* @since 5.2
*/
public abstract class CoroutinesUtils {
/**
* Convert a {@link Deferred} instance to a {@link Mono}.
*/
public static <T> Mono<T> deferredToMono(Deferred<T> source) {
return MonoKt.mono(Dispatchers.getUnconfined(),
(scope, continuation) -> source.await(continuation));
}
/**
* Convert a {@link Mono} instance to a {@link Deferred}.
*/
public static <T> Deferred<T> monoToDeferred(Mono<T> source) {
return BuildersKt.async(GlobalScope.INSTANCE, Dispatchers.getUnconfined(),
CoroutineStart.DEFAULT,
(scope, continuation) -> MonoKt.awaitSingleOrNull(source, continuation));
}
/**
* Invoke a suspending function and convert it to {@link Mono} or {@link Flux}.
* Uses an {@linkplain Dispatchers#getUnconfined() unconfined} dispatcher.
* @param method the suspending function to invoke
* @param target the target to invoke {@code method} on
* @param args the function arguments. If the {@code Continuation} argument is specified as the last argument
* (typically {@code null}), it is ignored.
* @return the method invocation result as reactive stream
* @throws IllegalArgumentException if {@code method} is not a suspending function
*/
public static Publisher<?> invokeSuspendingFunction(Method method, Object target,
Object... args) {
return invokeSuspendingFunction(Dispatchers.getUnconfined(), method, target, args);
}
/**
* Invoke a suspending function and convert it to {@link Mono} or
* {@link Flux}.
* @param context the coroutine context to use
* @param method the suspending function to invoke
* @param target the target to invoke {@code method} on
* @param args the function arguments. If the {@code Continuation} argument is specified as the last argument
* (typically {@code null}), it is ignored.
* @return the method invocation result as reactive stream
* @throws IllegalArgumentException if {@code method} is not a suspending function
* @since 6.0
*/
@SuppressWarnings("deprecation")
public static Publisher<?> invokeSuspendingFunction(CoroutineContext context, Method method, Object target,
Object... args) {
Assert.isTrue(KotlinDetector.isSuspendingFunction(method), "'method' must be a suspending function");
KFunction<?> function = Objects.requireNonNull(ReflectJvmMapping.getKotlinFunction(method));
if (method.isAccessible() && !KCallablesJvm.isAccessible(function)) {
KCallablesJvm.setAccessible(function, true);
}
Mono<Object> mono = MonoKt.mono(context, (scope, continuation) -> {
Map<KParameter, Object> argMap = CollectionUtils.newHashMap(args.length + 1);
int index = 0;
for (KParameter parameter : function.getParameters()) {
switch (parameter.getKind()) {
case INSTANCE -> argMap.put(parameter, target);
case VALUE -> {
if (!parameter.isOptional() || args[index] != null) {
argMap.put(parameter, args[index]);
}
index++;
}
}
}
return KCallables.callSuspendBy(function, argMap, continuation);
})
.filter(result -> !Objects.equals(result, Unit.INSTANCE))
.onErrorMap(InvocationTargetException.class, InvocationTargetException::getTargetException);
KClassifier returnType = function.getReturnType().getClassifier();
if (returnType != null) {
if (returnType.equals(JvmClassMappingKt.getKotlinClass(Flow.class))) {
return mono.flatMapMany(CoroutinesUtils::asFlux);
}
else if (returnType.equals(JvmClassMappingKt.getKotlinClass(Mono.class))) {
return mono.flatMap(o -> ((Mono<?>)o));
}
else if (returnType instanceof KClass<?> kClass &&
Publisher.class.isAssignableFrom(JvmClassMappingKt.getJavaClass(kClass))) {
return mono.flatMapMany(o -> ((Publisher<?>)o));
}
}
return mono;
}
private static Flux<?> asFlux(Object flow) {
return ReactorFlowKt.asFlux(((Flow<?>) flow));
}
}
|
package com.lenovohit.ssm.treat.web.rest;
import java.util.ArrayList;
import java.util.List;
import org.apache.cxf.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.lenovohit.core.dao.Page;
import com.lenovohit.core.utils.DateUtils;
import com.lenovohit.core.utils.JSONUtils;
import com.lenovohit.core.web.MediaTypes;
import com.lenovohit.core.web.rest.BaseRestController;
import com.lenovohit.core.web.utils.Result;
import com.lenovohit.core.web.utils.ResultUtils;
import com.lenovohit.ssm.treat.hisModel.EEGOrderReport;
import com.lenovohit.ssm.treat.manager.EEGManager;
@RestController
@RequestMapping("/ssm/treat/eeg")
public class EEGRestController extends BaseRestController {
// @Autowired
// private HisPatientManager hisPatientManager;
@Autowired
private EEGManager<EEGOrderReport, String> eEGOrderReportManager;
/**
* 心电图分页查询
* @param start
* @param limit
* @return
*/
@RequestMapping(value = "/page/{start}/{limit}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forPage(@PathVariable("start") String start, @PathVariable("limit") String limit,
@RequestParam(value = "data", defaultValue = "") String data) {
EEGOrderReport query = JSONUtils.deserialize(data, EEGOrderReport.class);
StringBuilder jql = new StringBuilder( " from EEGOrderReport where 1=1 ");
List<Object> values = new ArrayList<Object>();
//非自费患者设置关联卡病人编号
// if (!"0000".equals(query.getPatientNo())) {//查找关联的医保患者自费卡
// Patient args = new Patient();
// args.setMiCardNo(query.getPatientNo());// 只有查询条件
// HisListResponse<Patient> miRelaPatientResponse = hisPatientManager.getRelaCardByMiCardNo(args);// PATIENT0026
// List<Patient> miRelaPatient = miRelaPatientResponse.getList();
// if (null != miRelaPatient && miRelaPatient.size() == 1) {
// Patient patient = miRelaPatient.get(0);
// System.out.println("关联卡病人编号 "+patient.getNo());
// if(!StringUtils.isEmpty(patient.getNo())){
// jql.append(" and patinetNo like ? ");
// values.add("%"+patient.getNo()+"%");
// }
//
// } else if (null == miRelaPatient || miRelaPatient.size() <= 0) {
// return ResultUtils.renderFailureResult("不存在关联的医保档案");
// } else {
// return ResultUtils.renderFailureResult("存在额外的医保档案信息");
// }
// }else{
// if(!StringUtils.isEmpty(query.getPatientNo())){
// jql.append(" and patinetNo like ? ");
// values.add("%"+query.getPatientNo()+"%");
// }
// }
if(!StringUtils.isEmpty(query.getPatientNo())){
jql.append(" and patinetNo = ? ");
values.add(query.getPatientNo());
}
if(!StringUtils.isEmpty(query.getInpatientNo())){
jql.append(" and inpatientNo = ? ");
values.add(query.getInpatientNo());
}
if(!StringUtils.isEmpty(query.getStartDate())){
jql.append(" and reportTime > ? ");
values.add(DateUtils.string2Date(query.getStartDate(), DateUtils.DATE_PATTERN_DASH_YYYYMMDD_HHMMSS));
}
if(!StringUtils.isEmpty(query.getEndDate())){
jql.append(" and reportTime < ? ");
values.add(DateUtils.string2Date(query.getEndDate(), DateUtils.DATE_PATTERN_DASH_YYYYMMDD_HHMMSS));
}
// jql.append(" and reportFileName = ? ");
// values.add("JZNK1FS2017091700010_4.jpg");
jql.append(" order by reportTime desc ");
Page page = new Page();
page.setStart(start);
page.setPageSize(limit);
page.setQuery(jql.toString());
page.setValues(values.toArray());
eEGOrderReportManager.findPage(page);
return ResultUtils.renderSuccessResult(page);
}
/**
* 心电图列表查询
* @param start
* @param limit
* @return
*/
@RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forList(@RequestParam(value = "data", defaultValue = "") String data) {
EEGOrderReport query = JSONUtils.deserialize(data, EEGOrderReport.class);
StringBuilder jql = new StringBuilder( " from EEGOrderReport where 1=1 ");
List<Object> values = new ArrayList<Object>();
//
// //非自费患者设置关联卡病人编号
// if (!"0000".equals(query.getPatientNo())) {//查找关联的医保患者自费卡
// Patient args = new Patient();
// args.setMiCardNo(query.getPatientNo());// 只有查询条件
//// args.setMiCardNo("530121A31489278");//手动设置医保患者卡内数据
// HisListResponse<Patient> miRelaPatientResponse = hisPatientManager.getRelaCardByMiCardNo(args);// PATIENT0026
// List<Patient> miRelaPatient = miRelaPatientResponse.getList();
// if (null != miRelaPatient && miRelaPatient.size() == 1) {
// Patient patient = miRelaPatient.get(0);
// if(!StringUtils.isEmpty(patient.getNo())){
// jql.append(" and patientNo = ? ");
// values.add(patient.getNo());
// }
// } else if (null == miRelaPatient || miRelaPatient.size() <= 0) {
// return ResultUtils.renderFailureResult("不存在关联的医保档案");
// } else {
// return ResultUtils.renderFailureResult("存在额外的医保档案信息");
// }
// }else{
// if(!StringUtils.isEmpty(query.getPatientNo())){
// jql.append(" and patientNo = ? ");
// values.add(query.getPatientNo());
// }
// }
if(!StringUtils.isEmpty(query.getPatientNo())){
jql.append(" and patinetNo = ? ");
values.add(query.getPatientNo());
}
if(!StringUtils.isEmpty(query.getInpatientNo())){
jql.append(" and inpatientNo = ? ");
values.add(query.getInpatientNo());
}
if(!StringUtils.isEmpty(query.getStartDate())){
jql.append(" and reportTime > ? ");
values.add(DateUtils.string2Date(query.getStartDate(), DateUtils.DATE_PATTERN_DASH_YYYYMMDD_HHMMSS));
}
if(!StringUtils.isEmpty(query.getEndDate())){
jql.append(" and reportTime < ? ");
values.add(DateUtils.string2Date(query.getEndDate(), DateUtils.DATE_PATTERN_DASH_YYYYMMDD_HHMMSS));
}
// jql.append(" and reportFileName = ? ");
// values.add("JZNK1FS2017091700010_4.jpg");
jql.append(" order by reportTime desc ");
List<EEGOrderReport> records = eEGOrderReportManager.find(jql.toString(), values.toArray());
return ResultUtils.renderSuccessResult(records);
}
/**
* 心电图详情打印结果回传
* @param id
* @return
*/
@RequestMapping(value="/{patientId}",method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8)
public Result forPrint(@PathVariable("patientId") String patientId){
return ResultUtils.renderSuccessResult();
}
}
|
package com.esum.comp.xvr.process;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.comp.xvr.XVRCode;
import com.esum.comp.xvr.XVRException;
import com.esum.framework.core.component.ComponentException;
import com.esum.framework.core.component.ComponentInfo;
import com.esum.framework.core.component.ComponentManagerFactory;
import com.esum.framework.core.component.listener.channel.ChannelMessageListener;
import com.esum.framework.core.event.log.ErrorInfo;
import com.esum.framework.core.event.message.MessageEvent;
import com.esum.framework.core.event.message.RoutingInfo;
import com.esum.framework.core.exception.SystemException;
import com.esum.framework.core.queue.mq.JmsQueueMessageHandler;
/**
* com.esum.comp.xvr.XVRListener.java.
*/
public class XVRMessageListener extends ChannelMessageListener<MessageEvent> {
private Logger log = LoggerFactory.getLogger(XVRMessageListener.class);
public XVRMessageListener(String componentId, String channelName) throws SystemException {
super(componentId, channelName);
}
public MessageEvent onEvent(MessageEvent messageEvent) {
traceId = "[" + messageEvent.getMessageControlId() + "] ";
log.info(traceId + "Received MessageEvent");
XVRMessageProcessor processor = null;
try {
processor = new XVRMessageProcessor(messageEvent, this);
processor.process();
} catch (XVRException e) {
ErrorInfo errorInfo = new ErrorInfo(e.getErrorCode(), e.getErrorLocation(), e.getMessage());
try {
processor.sendExceptionLogging(errorInfo);
log.info(traceId + "Sent LoggingEvent to Logger in case of Exception.");
sendResponse(messageEvent, errorInfo);
} catch (Exception ex) {
log.error(traceId + "Fail to send LoggingEvent to log channel in case of Exception. ", ex);
}
} catch (Exception e) {
String errorMsg = "Fail to transform the received messages by Runtime Exception. ";
log.error(traceId + errorMsg, e);
ErrorInfo errorInfo = new ErrorInfo(XVRCode.ERROR_UNDEFINED, "onMessageEvent()", errorMsg + e.toString());
try {
if(processor!=null){
processor.sendExceptionLogging(errorInfo);
log.info(traceId + "Sent LoggingEvent to Logger in case of Exception.");
sendResponse(messageEvent, errorInfo);
}
} catch (Exception ex) {
log.error(traceId + "Fail to send LoggingEvent to log channel in case of Exception. ", ex);
}
}
return null;
}
public void sendResponse(MessageEvent event, ErrorInfo errorInfo){
event.getMessage().getHeader().setErrorInfo(errorInfo);
if(event.getRoutingInfo().getRouteType().equals(RoutingInfo.SYNC_ROUTING)){
if(!event.getRoutingInfo().isEndPath())
return;
String startComponentId = event.getRoutingInfo().getStartComponent();
ComponentInfo componentInfo = null;
try {
componentInfo = ComponentManagerFactory.currentComponentManager().getComponentInfo(startComponentId);
} catch (ComponentException e) {
log.error(traceId+"Start Componenet("+startComponentId+") is not found. Can not send to response message.");
return;
}
JmsQueueMessageHandler replyHandler = null;
try {
replyHandler = getMessageChannel().getQueueHandler(componentInfo.getSyncChannelName());
replyHandler.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
replyHandler.reply(event,
event.getEventHeader().getMessagePriority(),
event.getMessageControlId(), event.getRoutingInfo().getTimeToLive());
log.debug(traceId+"response message(sync) sent.");
} catch (JMSException e) {
log.error(traceId+"Can not send response message to "+componentInfo.getSyncChannelName());
} finally {
if(replyHandler!=null)
replyHandler.close();
}
return;
}
}
}
|
package net.nowtryz.mcutils.command.graph;
import net.nowtryz.mcutils.command.contexts.NodeSearchContext;
import net.nowtryz.mcutils.command.exceptions.CompleterDuplicationException;
import net.nowtryz.mcutils.command.execution.Completer;
import java.util.List;
import java.util.Optional;
class GenericCommandNode extends CommandNode {
private Completer completer;
public GenericCommandNode() {
super("<argument>");
}
protected GenericCommandNode(String key) {
super(key);
}
List<String> completeArgument(NodeSearchContext context) {
return Optional.ofNullable(this.completer)
.map(c -> c.complete(context.completion().build()))
.orElse(null);
}
void setCompleter(Completer completer) {
if (this.completer != null) throw new CompleterDuplicationException(this.completer, completer);
this.completer = completer;
}
@Override
protected void appendToStringGraph(String tabs, StringBuilder builder) {
if (this.completer != null) builder.append(tabs).append(" completer: ").append(completer).append("\n");
}
}
|
package ru.job4j.services;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
//import org.junit.Ignore;
import org.junit.Test;
import ru.job4j.checking.DBDriver;
import ru.job4j.models.Body;
import ru.job4j.models.Brand;
import ru.job4j.models.Car;
import ru.job4j.models.Founder;
import ru.job4j.models.IModel;
/**
* Класс DAOTest тестирует класс DAO.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 2018-12-08
* @since 2018-05-15
*/
public class DAOTest {
/**
* Драйвер бд.
*/
private DBDriver driver;
/**
* Логгер.
*/
private Logger logger = LogManager.getLogger(this.getClass().getSimpleName());
/**
* DAO моделей.
*/
private DAO dao;
/**
* Действия перед тестом.
*/
@Before
public void beforeTest() {
try {
this.dao = new DAO();
this.driver = new DBDriver("jdbc:postgresql://localhost:5432/jpack3p1ch2task1", "postgres", "postgresrootpass");
String path = new File(DBDriver.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath() + "/";
path = path.replaceFirst("^/(.:/)", "$1");
this.driver.executeSqlScript(path + "../../src/main/resources/junior.pack3.p1.ch2.task1v2.sql");
} catch (Exception ex) {
this.logger.error("ERROR", ex);
ex.printStackTrace();
}
}
/**
* Тестирует public int create(T obj) throws PersistenceException.
* Тип: Body.
*/
@Test
public void testCreateWithTypeBody() {
try {
Body expected = new Body(0, "Targa");
int id = this.dao.create(expected);
expected.setId(id);
String query = String.format("select * from bodies where id = %d", expected.getId());
List<HashMap<String, String>> result = this.driver.select(query);
Body actual = new Body(Integer.parseInt(result.get(0).get("id")), result.get(0).get("name"));
assertEquals(expected, actual);
} catch (Exception ex) {
this.logger.error("ERROR", ex);
ex.printStackTrace();
}
}
/**
* Тестирует public int create(T obj) throws PersistenceException.
* Тип: Brand.
*/
@Test
public void testCreateWithTypeBrand() {
try {
Founder f = new Founder(0, "ЦК КПСС", "Совет министров СССР");
int id = this.dao.create(f);
f.setId(id);
Brand expected = new Brand(0, "ВАЗ", f);
id = this.dao.create(expected);
expected.setId(id);
String query = String.format("select brands.id as brand_id, brands.name as brand_name, founders.id as founder_id, founders.name_last as founder_name_last, founders.name as founder_name from brands, founders where brands.founder_id = founders.id and brands.id = %d", expected.getId());
List<HashMap<String, String>> result = this.driver.select(query);
Founder founder = new Founder();
founder.setId(Integer.parseInt(result.get(0).get("founder_id")));
founder.setNameLast(result.get(0).get("founder_name_last"));
founder.setName(result.get(0).get("founder_name"));
Brand actual = new Brand();
actual.setId(Integer.parseInt(result.get(0).get("brand_id")));
actual.setName(result.get(0).get("brand_name"));
actual.setFounder(founder);
assertEquals(expected, actual);
} catch (Exception ex) {
this.logger.error("ERROR", ex);
ex.printStackTrace();
}
}
/**
* Тестирует public int create(T obj) throws PersistenceException.
* Тип: Car.
*/
@Test
public void testCreateWithTypeCar() {
try {
Car expected = new Car();
expected.setId(0);
expected.setName("Niva");
List<Body> ebodies = new ArrayList<>();
ebodies.add(new Body(3, "universal"));
expected.setBodies(ebodies);
Founder founder = new Founder(0, "ЦК КПСС", "Совет министров СССР");
int id = this.dao.create(founder);
founder.setId(id);
Brand brand = new Brand(0, "ВАЗ", founder);
id = this.dao.create(brand);
brand.setId(id);
expected.setBrand(brand);
id = this.dao.create(expected);
expected.setId(id);
String query = String.format("select cars.id as car_id, cars.name as car_name, brands.id as brand_id, brands.name as brand_name, founders.id as founder_id, founders.name_last as founder_name_last, founders.name as founder_name from cars, brands, founders where cars.brand_id = brands.id and brands.founder_id = founders.id and cars.id = %d", expected.getId());
List<HashMap<String, String>> result = this.driver.select(query);
Car actual = new Car();
actual.setId(Integer.parseInt(result.get(0).get("car_id")));
actual.setName(result.get(0).get("car_name"));
Founder f = new Founder(Integer.parseInt(result.get(0).get("founder_id")), result.get(0).get("founder_name_last"), result.get(0).get("founder_name"));
Brand b = new Brand(Integer.parseInt(result.get(0).get("brand_id")), result.get(0).get("brand_name"), f);
actual.setBrand(b);
query = String.format("select bodies.id, bodies.name from bodies, cars_bodies where bodies.id = cars_bodies.body_id and car_id = %d order by bodies.id", expected.getId());
result = this.driver.select(query);
List<Body> abodies = new ArrayList<>();
abodies.add(new Body(Integer.parseInt(result.get(0).get("id")), result.get(0).get("name")));
actual.setBodies(abodies);
assertEquals(expected, actual);
} catch (Exception ex) {
this.logger.error("ERROR", ex);
ex.printStackTrace();
}
}
/**
* Тестирует public void delete(T obj) throws PersistenceException.
* Тип: Founder.
*/
@Test
public void testDeleteWithTypeFounder() {
try {
Founder founder = new Founder(0, "ЦК КПСС", "Совет министров СССР");
int id = this.dao.create(founder);
founder.setId(id);
// Удаляет запросом: delete from items where id=?
this.dao.delete(founder);
String query = String.format("select id from founders where id = %d", id);
List<HashMap<String, String>> result = this.driver.select(query);
assertTrue(result.isEmpty());
} catch (Exception ex) {
this.logger.error("ERROR", ex);
ex.printStackTrace();
}
}
/**
* Тестирует public void delete(T obj) throws PersistenceException.
* Тип: Brand.
*/
@Test
public void testDeleteWithTypeBrand() {
try {
Founder founder = new Founder(0, "ЦК КПСС", "Совет министров СССР");
int id = this.dao.create(founder);
founder.setId(id);
String name = "ВАЗ";
Brand brand = new Brand(0, name, founder);
id = this.dao.create(brand);
brand.setId(id);
this.dao.delete(brand);
String query = String.format("select name from brands where id = %d", id);
List<HashMap<String, String>> resultBrand = this.driver.select(query);
query = String.format("select name_last from founders where id = %d", founder.getId());
List<HashMap<String, String>> resultFounder = this.driver.select(query);
assertTrue(resultBrand.isEmpty() && resultFounder.isEmpty());
} catch (Exception ex) {
this.logger.error("ERROR", ex);
ex.printStackTrace();
}
}
/**
* Тестирует public void delete(T obj) throws PersistenceException.
* Тип: Car.
*/
@Test
public void testDeleteWithTypeCar() {
try {
Founder founder = new Founder(0, "ЦК КПСС", "Совет министров СССР");
int id = this.dao.create(founder);
founder.setId(id);
String name = "ВАЗ";
Brand brand = new Brand(0, name, founder);
id = this.dao.create(brand);
brand.setId(id);
Car car = new Car();
car.setId(0);
car.setName("Vesta");
car.setBrand(brand);
List<Body> bodies = new ArrayList<>();
bodies.add(new Body(1, "sedan"));
bodies.add(new Body(4, "crossover"));
car.setBodies(bodies);
id = this.dao.create(car);
car.setId(id);
this.dao.delete(car);
String query = String.format("select name from cars where id = %d", car.getId());
List<HashMap<String, String>> resultCar = this.driver.select(query);
query = String.format("select name from brands where id = %d", brand.getId());
List<HashMap<String, String>> resultBrand = this.driver.select(query);
query = String.format("select name_last from founders where id = %d", founder.getId());
List<HashMap<String, String>> resultFounder = this.driver.select(query);
assertTrue(resultCar.isEmpty() && resultBrand.isEmpty() && resultFounder.isEmpty());
} catch (Exception ex) {
this.logger.error("ERROR", ex);
ex.printStackTrace();
}
}
/**
* Тестирует private U U process(final Function<Session, U> command).
* @throws java.lang.Exception исключение.
*/
@Test(expected = Exception.class)
public void testProcess() throws Exception {
this.dao.create(null);
}
/**
* Тестирует public List<T> read(T obj) throws PersistenceException.
* Тип: Founder.
*/
@Test
public void testReadWithTypeFounder() {
try {
List<Founder> expected = new ArrayList<>();
String query = "select * from founders order by name";
List<HashMap<String, String>> result = this.driver.select(query);
for (HashMap<String, String> item : result) {
Founder founder = new Founder();
founder.setId(Integer.parseInt(item.get("id")));
founder.setNameLast(item.get("name_last"));
founder.setName(item.get("name"));
expected.add(founder);
}
List<IModel> actual = this.dao.read(new Founder());
assertEquals(expected, actual);
} catch (Exception ex) {
this.logger.error("ERROR", ex);
ex.printStackTrace();
}
}
/**
* Тестирует public List<T> read(T obj) throws PersistenceException.
* Тип: Brand.
*/
@Test
public void testReadWithTypeBrand() {
try {
List<Brand> expected = new ArrayList<>();
String query = "select brands.id as brand_id, brands.name as brand_name, founders.id as founder_id, founders.name_last as founder_name_last, founders.name as founder_name from brands, founders where founder_id = founders.id order by brands.name";
List<HashMap<String, String>> result = this.driver.select(query);
for (HashMap<String, String> item : result) {
Founder f = new Founder();
f.setId(Integer.parseInt(item.get("founder_id")));
f.setNameLast(item.get("founder_name_last"));
f.setName(item.get("founder_name"));
expected.add(new Brand(Integer.parseInt(item.get("brand_id")), item.get("brand_name"), f));
}
List<IModel> actual = this.dao.read(new Brand());
assertEquals(expected, actual);
} catch (Exception ex) {
this.logger.error("ERROR", ex);
ex.printStackTrace();
}
}
/**
* Тестирует public List<T> read(T obj) throws PersistenceException.
* Тип: Car.
*/
@Test
public void testReadWithTypeCar() {
try {
List<Car> expected = new ArrayList<>();
String query = "select cars.id as car_id, cars.name as car_name, brands.id as brand_id, brands.name as brand_name, founders.id as founder_id, founders.name_last as founder_name_last, founders.name as founder_name from cars, brands, founders where cars.brand_id = brands.id and brands.founder_id = founders.id order by cars.name";
List<HashMap<String, String>> result = this.driver.select(query);
for (HashMap<String, String> item : result) {
Founder founder = new Founder();
founder.setId(Integer.parseInt(item.get("founder_id")));
founder.setNameLast(item.get("founder_name_last"));
founder.setName(item.get("founder_name"));
Brand brand = new Brand();
brand.setId(Integer.parseInt(item.get("brand_id")));
brand.setName(item.get("brand_name"));
brand.setFounder(founder);
Car car = new Car();
car.setId(Integer.parseInt(item.get("car_id")));
car.setName(item.get("car_name"));
car.setBrand(brand);
query = String.format("select bodies.id, bodies.name from bodies, cars_bodies where bodies.id = cars_bodies.body_id and car_id = %d order by bodies.id", car.getId());
List<HashMap<String, String>> resultBodies = this.driver.select(query);
List<Body> bodies = new ArrayList<>();
for (HashMap<String, String> resultBody : resultBodies) {
Body body = new Body();
body.setId(Integer.parseInt(resultBody.get("id")));
body.setName(resultBody.get("name"));
bodies.add(body);
}
car.setBodies(bodies);
expected.add(car);
}
List<IModel> cars = this.dao.read(new Car());
List<Car> actual = new ArrayList<>();
for (IModel item : cars) {
actual.add((Car) item);
}
assertEquals(expected, actual);
} catch (Exception ex) {
this.logger.error("ERROR", ex);
ex.printStackTrace();
}
}
/**
* Тестирует public void update(E obj).
* Тип: Founder.
*/
@Test
public void testUpdateWithTypeFounder() {
try {
Founder expected = new Founder(0, "ЦК КПСС", "Совет министров СССР");
int id = this.dao.create(expected);
expected.setId(id);
expected.setName("new name");
this.dao.update(expected);
String query = String.format("select * from founders where id = %d", id);
List<HashMap<String, String>> result = this.driver.select(query);
Founder actual = new Founder();
actual.setId(Integer.parseInt(result.get(0).get("id")));
actual.setNameLast(result.get(0).get("name_last"));
actual.setName(result.get(0).get("name"));
assertEquals(expected, actual);
} catch (Exception ex) {
this.logger.error("ERROR", ex);
ex.printStackTrace();
}
}
/**
* Тестирует public void update(E obj).
* Тип: Brand.
*/
@Test
public void testUpdateWithTypeBrand() {
try {
Founder f = new Founder(0, "ЦК КПСС", "Совет министров СССР");
int id = this.dao.create(f);
f.setId(id);
Brand expected = new Brand(0, "ВАЗ", f);
id = this.dao.create(expected);
expected.setId(id);
expected.setName("Tatra");
expected.getFounder().setName("Ignats");
expected.getFounder().setNameLast("Shustala");
this.dao.update(expected);
String query = String.format("select brands.id as brand_id, brands.name as brand_name, founders.id as founder_id, founders.name_last as founder_name_last, founders.name as founder_name from brands, founders where brands.founder_id = founders.id and brands.id = %d", expected.getId());
List<HashMap<String, String>> result = this.driver.select(query);
Founder founder = new Founder();
founder.setId(Integer.parseInt(result.get(0).get("founder_id")));
founder.setNameLast(result.get(0).get("founder_name_last"));
founder.setName(result.get(0).get("founder_name"));
Brand actual = new Brand();
actual.setId(Integer.parseInt(result.get(0).get("brand_id")));
actual.setName(result.get(0).get("brand_name"));
actual.setFounder(founder);
assertEquals(expected, actual);
} catch (Exception ex) {
this.logger.error("ERROR", ex);
ex.printStackTrace();
}
}
/**
* Тестирует public void update(E obj).
* Тип: Gearbox.
*/
@Test
public void testUpdateWithTypeCar() {
try {
Car expected = new Car();
expected.setId(0);
expected.setName("Niva");
List<Body> ebodies = new ArrayList<>();
ebodies.add(new Body(3, "universal"));
expected.setBodies(ebodies);
Founder founder = new Founder(0, "ЦК КПСС", "Совет министров СССР");
int id = this.dao.create(founder);
founder.setId(id);
Brand brand = new Brand(0, "ВАЗ", founder);
id = this.dao.create(brand);
brand.setId(id);
expected.setBrand(brand);
id = this.dao.create(expected);
expected.setId(id);
expected.setName("613");
List<Body> bodies = expected.getBodies();
bodies.set(0, new Body(1, "sedan"));
bodies.add(new Body(2, "hatchback"));
expected.setBodies(bodies);
expected.getBrand().setName("Tatra");
expected.getBrand().getFounder().setName("Ignats");
expected.getBrand().getFounder().setNameLast("Shustala");
this.dao.update(expected);
String query = String.format("select cars.id as car_id, cars.name as car_name, brands.id as brand_id, brands.name as brand_name, founders.id as founder_id, founders.name_last as founder_name_last, founders.name as founder_name from cars, brands, founders where cars.brand_id = brands.id and brands.founder_id = founders.id and cars.id = %d", expected.getId());
List<HashMap<String, String>> result = this.driver.select(query);
Car actual = new Car();
actual.setId(Integer.parseInt(result.get(0).get("car_id")));
actual.setName(result.get(0).get("car_name"));
Founder f = new Founder(Integer.parseInt(result.get(0).get("founder_id")), result.get(0).get("founder_name_last"), result.get(0).get("founder_name"));
Brand b = new Brand(Integer.parseInt(result.get(0).get("brand_id")), result.get(0).get("brand_name"), f);
actual.setBrand(b);
query = String.format("select bodies.id, bodies.name from bodies, cars_bodies where bodies.id = cars_bodies.body_id and car_id = %d order by bodies.id", expected.getId());
result = this.driver.select(query);
List<Body> abodies = new ArrayList<>();
for (HashMap<String, String> item : result) {
Body body = new Body();
body.setId(Integer.parseInt(item.get("id")));
body.setName(item.get("name"));
abodies.add(body);
}
actual.setBodies(abodies);
assertEquals(expected, actual);
} catch (Exception ex) {
this.logger.error("ERROR", ex);
ex.printStackTrace();
}
}
/**
* Действия после теста.
*/
@After
public void afterTest() {
try {
this.dao.close();
} catch (Exception ex) {
this.logger.error("ERROR", ex);
ex.printStackTrace();
}
}
} |
package net.itcast.course.regex.basic.lesson2;
public class DotMatch {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] strings = new String[] { "a", "A", "0", "$", "(", "."};
String normalDot = ".";
String escapedDot = "\\.";
String characterClassDot = "[.]";
for (String s : strings) {
if (regexMatch(s, normalDot)) {
System.out.println("\"" + s + "\" can be matched with regex \""
+ normalDot + "\"");
} else {
System.out.println("\"" + s
+ "\" can not be matched with regex \"" + normalDot + "\"");
}
}
System.out.println("");
for (String s : strings) {
if (regexMatch(s, escapedDot)) {
System.out.println("\"" + s + "\" can be matched with regex \""
+ escapedDot + "\"");
} else {
System.out.println("\"" + s
+ "\" can not be matched with regex \"" + escapedDot + "\"");
}
}
System.out.println("");
for (String s : strings) {
if (regexMatch(s, characterClassDot)) {
System.out.println("\"" + s + "\" can be matched with regex \""
+ characterClassDot + "\"");
} else {
System.out.println("\"" + s
+ "\" can not be matched with regex \"" + characterClassDot + "\"");
}
}
System.out.println("");
}
public static boolean regexMatch(String s, String regex) {
return s.matches(regex);
}
}
|
/*
* Copyright (c) 2008-2019 Haulmont.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.haulmont.reports.gui.parameter.edit;
import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.global.Metadata;
import com.haulmont.cuba.core.global.Security;
import com.haulmont.cuba.gui.components.*;
import com.haulmont.cuba.gui.components.autocomplete.JpqlSuggestionFactory;
import com.haulmont.cuba.gui.components.autocomplete.Suggestion;
import com.haulmont.cuba.gui.data.Datasource;
import com.haulmont.cuba.gui.data.impl.DatasourceImplementation;
import com.haulmont.cuba.gui.sys.ScreensHelper;
import com.haulmont.cuba.gui.theme.ThemeConstants;
import com.haulmont.cuba.security.entity.EntityOp;
import com.haulmont.reports.app.service.ReportService;
import com.haulmont.reports.entity.ParameterType;
import com.haulmont.reports.entity.PredefinedTransformation;
import com.haulmont.reports.entity.ReportInputParameter;
import com.haulmont.reports.gui.report.run.ParameterClassResolver;
import com.haulmont.reports.gui.report.run.ParameterFieldCreator;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.*;
import static java.lang.String.format;
public class ParameterEditor extends AbstractEditor<ReportInputParameter> {
protected final static String LOOKUP_SETTINGS_TAB_ID = "lookupSettingsTab";
protected final static String WHERE = " where ";
@Inject
protected Label<String> defaultValueLabel;
@Inject
protected BoxLayout defaultValueBox;
@Inject
protected LookupField<String> screen;
@Inject
protected LookupField<String> enumeration;
@Inject
protected LookupField<ParameterType> type;
@Inject
protected LookupField<String> metaClass;
@Inject
protected CheckBox lookup;
@Inject
protected Label<String> lookupLabel;
@Inject
protected SourceCodeEditor lookupWhere;
@Inject
protected SourceCodeEditor lookupJoin;
@Named("tabsheet.lookupSettingsTab")
protected VBoxLayout lookupSettingsTab;
@Inject
protected TabSheet tabsheet;
@Inject
protected Label<String> enumerationLabel;
@Inject
protected Label<String> screenLabel;
@Inject
protected Label<String> metaClassLabel;
@Inject
protected GridLayout predefinedTransformationBox;
@Inject
protected CheckBox predefinedTransformation;
@Inject
protected SourceCodeEditor transformationScript;
@Inject
protected SourceCodeEditor validationScript;
@Inject
protected Label<String> transformationScriptLabel;
@Inject
protected LookupField<PredefinedTransformation> wildcards;
@Inject
protected Label<String> wildcardsLabel;
@Inject
protected CheckBox defaultDateIsCurrentCheckBox;
@Inject
protected Label<String> defaultDateIsCurrentLabel;
@Inject
protected Label<String> requiredLabel;
@Inject
protected CheckBox required;
@Inject
protected Metadata metadata;
@Inject
protected Security security;
@Inject
protected ThemeConstants themeConstants;
@Inject
protected ReportService reportService;
@Inject
protected Datasource<ReportInputParameter> parameterDs;
@Inject
protected ScreensHelper screensHelper;
@Inject
protected ParameterClassResolver parameterClassResolver;
@Inject
protected TextArea localeTextField;
protected ReportInputParameter parameter;
protected ParameterFieldCreator parameterFieldCreator = new ParameterFieldCreator(this);
@Override
public void setItem(Entity item) {
ReportInputParameter newParameter = (ReportInputParameter) metadata.create(parameterDs.getMetaClass());
metadata.getTools().copy(item, newParameter);
newParameter.setId((UUID) item.getId());
if (newParameter.getParameterClass() == null) {
newParameter.setParameterClass(parameterClassResolver.resolveClass(newParameter));
}
super.setItem(newParameter);
enableControlsByParamType(newParameter.getType());
initScreensLookup();
initTransformations();
}
@Override
public void init(Map<String, Object> params) {
super.init(params);
type.setOptionsList(Arrays.asList(ParameterType.TEXT, ParameterType.NUMERIC, ParameterType.BOOLEAN, ParameterType.ENUMERATION,
ParameterType.DATE, ParameterType.TIME, ParameterType.DATETIME, ParameterType.ENTITY, ParameterType.ENTITY_LIST));
initMetaClassLookup();
initEnumsLookup();
initListeners();
initHelpButtons();
initCodeEditors();
}
protected void initHelpButtons() {
localeTextField.setContextHelpIconClickHandler(e ->
showMessageDialog(getMessage("localeText"), getMessage("parameter.localeTextHelp"),
MessageType.CONFIRMATION_HTML
.modal(false)
.width(700f)));
transformationScript.setContextHelpIconClickHandler(e ->
showMessageDialog(getMessage("transformationScript"), getMessage("parameter.transformationScriptHelp"),
MessageType.CONFIRMATION_HTML
.modal(false)
.width(700f)));
validationScript.setContextHelpIconClickHandler(e ->
showMessageDialog(getMessage("validationScript"), getMessage("validationScriptHelp"),
MessageType.CONFIRMATION_HTML
.modal(false)
.width(700f)));
}
@Override
public boolean commit() {
if (super.commit()) {
metadata.getTools().copy(getItem(), parameter);
return true;
}
return false;
}
protected void initListeners() {
type.addValueChangeListener(e ->
enableControlsByParamType(e.getValue())
);
parameterDs.addItemPropertyChangeListener(e -> {
boolean typeChanged = e.getProperty().equalsIgnoreCase("type");
boolean classChanged = e.getProperty().equalsIgnoreCase("entityMetaClass")
|| e.getProperty().equalsIgnoreCase("enumerationClass");
boolean defaultDateIsCurrentChanged = e.getProperty().equalsIgnoreCase("defaultDateIsCurrent");
ReportInputParameter parameter = getItem();
if (typeChanged || classChanged) {
parameter.setParameterClass(parameterClassResolver.resolveClass(parameter));
if (typeChanged) {
parameter.setEntityMetaClass(null);
parameter.setEnumerationClass(null);
}
parameter.setDefaultValue(null);
parameter.setScreen(null);
initScreensLookup();
initDefaultValueField();
}
if (defaultDateIsCurrentChanged) {
initDefaultValueField();
initCurrentDateTimeField();
}
((DatasourceImplementation<ReportInputParameter>) parameterDs).modified(e.getItem());
});
lookup.addValueChangeListener(e -> {
if (Boolean.TRUE.equals(e.getValue())) {
if (tabsheet.getTab(LOOKUP_SETTINGS_TAB_ID) == null) {
tabsheet.addTab(LOOKUP_SETTINGS_TAB_ID, lookupSettingsTab);
}
} else {
if (tabsheet.getTab(LOOKUP_SETTINGS_TAB_ID) != null) {
tabsheet.removeTab(LOOKUP_SETTINGS_TAB_ID);
}
}
});
}
protected void initCodeEditors() {
lookupWhere.setSuggester((source, text, cursorPosition) -> requestHint(lookupWhere, cursorPosition));
lookupWhere.setHeight(themeConstants.get("cuba.gui.customConditionFrame.whereField.height"));
lookupJoin.setSuggester((source, text, cursorPosition) -> requestHint(lookupJoin, cursorPosition));
lookupJoin.setHeight(themeConstants.get("cuba.gui.customConditionFrame.joinField.height"));
}
protected void initScreensLookup() {
ReportInputParameter parameter = getItem();
if (parameter.getType() == ParameterType.ENTITY || parameter.getType() == ParameterType.ENTITY_LIST) {
Class clazz = parameterClassResolver.resolveClass(parameter);
if (clazz != null) {
Map<String, String> screensMap = screensHelper.getAvailableBrowserScreens(clazz);
screen.setOptionsMap(screensMap);
}
}
}
protected void initEnumsLookup() {
Map<String, String> enumsOptionsMap = new TreeMap<>();
for (Class enumClass : metadata.getTools().getAllEnums()) {
String enumLocalizedName = messages.getMessage(enumClass, enumClass.getSimpleName());
enumsOptionsMap.put(enumLocalizedName + " (" + enumClass.getSimpleName() + ")", enumClass.getCanonicalName());
}
enumeration.setOptionsMap(enumsOptionsMap);
}
protected void initMetaClassLookup() {
Map<String, String> metaClassesOptionsMap = new TreeMap<>();
Collection<MetaClass> classes = metadata.getSession().getClasses();
for (MetaClass clazz : classes) {
if (!metadata.getTools().isSystemLevel(clazz)) {
String caption = messages.getTools().getDetailedEntityCaption(clazz);
metaClassesOptionsMap.put(caption, clazz.getName());
}
}
metaClass.setOptionsMap(metaClassesOptionsMap);
}
@Override
protected boolean preCommit() {
if (!(getEditedEntity().getType() == ParameterType.ENTITY && Boolean.TRUE.equals(lookup.getValue()))) {
lookupWhere.setValue(null);
lookupJoin.setValue(null);
}
return super.preCommit();
}
protected void initDefaultValueField() {
defaultValueLabel.setVisible(false);
defaultValueBox.removeAll();
ReportInputParameter parameter = getItem();
if (canHaveDefaultValue()) {
Field<Object> field;
if (ParameterType.ENTITY.equals(parameter.getType()) && Boolean.TRUE.equals(parameter.getLookup())) {
ReportInputParameter entityParam = metadata.create(ReportInputParameter.class);
entityParam.setReport(parameter.getReport());
entityParam.setType(parameter.getType());
entityParam.setEntityMetaClass(parameter.getEntityMetaClass());
entityParam.setScreen(parameter.getScreen());
entityParam.setAlias(parameter.getAlias());
entityParam.setRequired(parameter.getRequired());
field = parameterFieldCreator.createField(entityParam);
} else {
field = parameterFieldCreator.createField(parameter);
}
field.addValueChangeListener(e -> {
if (e.getValue() != null) {
parameter.setDefaultValue(reportService.convertToString(e.getValue().getClass(), e.getValue()));
} else {
parameter.setDefaultValue(null);
}
});
if (parameter.getParameterClass() != null) {
field.setValue(reportService.convertFromString(parameter.getParameterClass(), parameter.getDefaultValue()));
}
field.setRequired(false);
defaultValueBox.add(field);
defaultValueLabel.setVisible(true);
}
defaultValueBox.setEnabled(security.isEntityOpPermitted(metadata.getClassNN(ReportInputParameter.class), EntityOp.UPDATE));
}
protected void initCurrentDateTimeField() {
boolean parameterDateOrTime = isParameterDateOrTime();
defaultDateIsCurrentLabel.setVisible(parameterDateOrTime);
defaultDateIsCurrentCheckBox.setVisible(parameterDateOrTime);
}
protected boolean canHaveDefaultValue() {
ReportInputParameter parameter = getItem();
if (parameter == null) {
return false;
}
if (isParameterDateOrTime() && BooleanUtils.isTrue(parameter.getDefaultDateIsCurrent())) {
return false;
}
ParameterType type = parameter.getType();
return type != null
&& type != ParameterType.ENTITY_LIST
&& (type != ParameterType.ENTITY || StringUtils.isNotBlank(parameter.getEntityMetaClass()))
&& (type != ParameterType.ENUMERATION || StringUtils.isNotBlank(parameter.getEnumerationClass()));
}
protected void enableControlsByParamType(ParameterType type) {
boolean isSingleEntity = type == ParameterType.ENTITY;
boolean isEntity = isSingleEntity || type == ParameterType.ENTITY_LIST;
boolean isEnum = type == ParameterType.ENUMERATION;
boolean isText = type == ParameterType.TEXT;
metaClass.setVisible(isEntity);
metaClassLabel.setVisible(isEntity);
lookup.setVisible(isSingleEntity);
lookupLabel.setVisible(isSingleEntity);
if (isSingleEntity && Boolean.TRUE.equals(lookup.getValue())) {
if (tabsheet.getTab(LOOKUP_SETTINGS_TAB_ID) == null) {
tabsheet.addTab(LOOKUP_SETTINGS_TAB_ID, lookupSettingsTab);
}
} else {
if (tabsheet.getTab(LOOKUP_SETTINGS_TAB_ID) != null) {
tabsheet.removeTab(LOOKUP_SETTINGS_TAB_ID);
}
}
screen.setVisible(isEntity);
screenLabel.setVisible(isEntity);
enumeration.setVisible(isEnum);
enumerationLabel.setVisible(isEnum);
predefinedTransformationBox.setVisible(isText);
initDefaultValueField();
initCurrentDateTimeField();
}
protected void initTransformations() {
ReportInputParameter parameter = getItem();
predefinedTransformation.setValue(parameter.getPredefinedTransformation() != null);
enableControlsByTransformationType(parameter.getPredefinedTransformation() != null);
predefinedTransformation.addValueChangeListener(e -> {
boolean hasPredefinedTransformation = e.getValue() != null && e.getValue();
enableControlsByTransformationType(hasPredefinedTransformation);
if (hasPredefinedTransformation) {
parameter.setTransformationScript(null);
} else {
parameter.setPredefinedTransformation(null);
}
});
predefinedTransformation.setEditable(security.isEntityOpPermitted(ReportInputParameter.class, EntityOp.UPDATE));
}
protected void enableControlsByTransformationType(boolean hasPredefinedTransformation) {
transformationScript.setVisible(!hasPredefinedTransformation);
transformationScriptLabel.setVisible(!hasPredefinedTransformation);
wildcards.setVisible(hasPredefinedTransformation);
wildcardsLabel.setVisible(hasPredefinedTransformation);
}
protected boolean isParameterDateOrTime() {
ReportInputParameter parameter = getItem();
return Optional.ofNullable(parameter)
.map(reportInputParameter ->
ParameterType.DATE.equals(parameter.getType()) ||
ParameterType.DATETIME.equals(parameter.getType()) ||
ParameterType.TIME.equals(parameter.getType()))
.orElse(false);
}
protected List<Suggestion> requestHint(SourceCodeEditor sender, int senderCursorPosition) {
String joinStr = lookupJoin.getValue();
String whereStr = lookupWhere.getValue();
// CAUTION: the magic entity name! The length is three character to match "{E}" length in query
String entityAlias = "a39";
int queryPosition = -1;
Class javaClassForEntity = getItem().getParameterClass();
if (javaClassForEntity == null) {
return new ArrayList<>();
}
String queryStart = format("select %s from %s %s ", entityAlias, metadata.getClassNN(javaClassForEntity), entityAlias);
StringBuilder queryBuilder = new StringBuilder(queryStart);
if (StringUtils.isNotEmpty(joinStr)) {
if (sender == lookupJoin) {
queryPosition = queryBuilder.length() + senderCursorPosition - 1;
}
if (!StringUtils.containsIgnoreCase(joinStr, "join") && !StringUtils.contains(joinStr, ",")) {
queryBuilder.append("join ").append(joinStr);
queryPosition += "join ".length();
} else {
queryBuilder.append(joinStr);
}
}
if (StringUtils.isNotEmpty(whereStr)) {
if (sender == lookupWhere) {
queryPosition = queryBuilder.length() + WHERE.length() + senderCursorPosition - 1;
}
queryBuilder.append(WHERE).append(whereStr);
}
String query = queryBuilder.toString();
query = query.replace("{E}", entityAlias);
return JpqlSuggestionFactory.requestHint(query, queryPosition, sender.getAutoCompleteSupport(), senderCursorPosition);
}
}
|
package com.grandsea.ticketvendingapplication.model.common;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
/**
* 对Gson的方法做了一层包装
*
* @author luowenjie
*
*/
public class GsonObject{
JsonObject jsonData = null;
public GsonObject(JsonObject jsonData) {
if (jsonData == null) {
throw new RuntimeException("jsonData is null");
}
this.jsonData = jsonData;
}
public JsonObject getAsJsonObject() {
return jsonData;
}
public boolean isnull(String key) {
if (jsonData.has(key)) {
if (!jsonData.get(key).isJsonNull()) {
return false;
}
}
return true;
}
public int getInt(String key, int defaultvalue) {
if (jsonData.has(key)) {
defaultvalue = jsonData.get(key).getAsInt();
}
return defaultvalue;
}
public long getLong(String key, long defaultvalue) {
if (jsonData.has(key)) {
defaultvalue = jsonData.get(key).getAsLong();
}
return defaultvalue;
}
public float getFloat(String key, float defaultvalue) {
if (jsonData.has(key)) {
defaultvalue = jsonData.get(key).getAsFloat();
}
return defaultvalue;
}
public double getDouble(String key, double defaultvalue) {
if (jsonData.has(key)) {
defaultvalue = jsonData.get(key).getAsDouble();
}
return defaultvalue;
}
public String getString(String key) {
if (jsonData.has(key)) {
String value = jsonData.get(key).getAsString();
return value;
}
return null;
}
public String getString(String key, String defaultvalue) {
if (jsonData.has(key)) {
defaultvalue = jsonData.get(key).getAsString();
}
return defaultvalue;
}
public boolean getBoolean(String key, boolean defaultvalue) {
if (jsonData.has(key)) {
defaultvalue = jsonData.get(key).getAsBoolean();
}
return defaultvalue;
}
public GsonObject getGsonObject(String key) {
if (jsonData.has(key)) {
JsonObject value = jsonData.get(key).getAsJsonObject();
if (value != null) {
return new GsonObject(value);
}
}
return null;
}
public JsonObject getJsonObject(String key) {
if (jsonData.has(key)) {
JsonObject value = jsonData.get(key).getAsJsonObject();
return value;
}
return null;
}
public JsonArray getJsonArray(String key) {
if (jsonData.has(key)) {
JsonArray value = jsonData.get(key).getAsJsonArray();
return value;
}
return null;
}
public <T> List<T> getAsList(Gson gson, String key, Class<T> elementClass){
List<T> list = new ArrayList<T>();
JsonArray jsonArray = this.getJsonArray(key);
if(jsonArray != null){
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement jsonElement = jsonArray.get(i);
list.add(gson.fromJson(jsonElement, elementClass));
}
}
return list;
}
// public final static GsonObject getJsonStrAsGsonObject(String data){
// GsonObject dataGson = new GsonObject(gsonWithoutNull.fromJson(data, JsonObject.class));
// return dataGson;
// }
@Override
public String toString() {
if (jsonData != null) {
return jsonData.toString();
} else {
return "";
}
}
public static void main(String[] args) {
String qids = "1,2,3,";
System.out.println(qids.substring(0, qids.length()-1));
}
}
|
package practise;
public class Wrapperpractise1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a=5;
Integer i=new Integer(a);//autoboxing
int r=i;//unboxing
System.out.println(i);
String s="1234";
int f=(int)(Float.parseFloat(s));
System.out.println(f);
char c='e';
int c1=c;
System.out.println(c1);
int w=89;
char w1=(char)w;
System.out.println(w1);
}
}
|
package com.alibaba.druid.bvt.sql.mysql.select;
import com.alibaba.druid.sql.MysqlTest;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.util.JdbcConstants;
import java.util.List;
public class MySqlSelectTest_169_values extends MysqlTest {
public void test_0() throws Exception {
String sql = "SELECT * FROM (VALUES (89), (35), (77)) EXCEPT SELECT * FROM (VALUES (33), (35), (60))";
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0);
assertEquals(1, statementList.size());
assertEquals("SELECT *\n" + "FROM (\n" + "\tVALUES (89), \n" + "\t(35), \n" + "\t(77)\n" + ")\n"
+ "EXCEPT\n" + "SELECT *\n" + "FROM (\n" + "\tVALUES (33), \n" + "\t(35), \n" + "\t(60)\n"
+ ")", stmt.toString());
}
public void test_2() throws Exception {
String sql = "SELECT * FROM (VALUES 89, 35, 77) EXCEPT SELECT * FROM (VALUES 33, 35, 60)";
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0);
assertEquals(1, statementList.size());
assertEquals("SELECT *\n" + "FROM (\n" + "\tVALUES (89), \n" + "\t(35), \n" + "\t(77)\n" + ")\n" + "EXCEPT\n"
+ "SELECT *\n" + "FROM (\n" + "\tVALUES (33), \n" + "\t(35), \n" + "\t(60)\n" + ")", stmt.toString());
}
} |
package com.stefanini.controller;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.stefanini.model.Agente;
import com.stefanini.model.Infracoes;
import com.stefanini.service.AgenteService;
import com.stefanini.service.InfracoesService;
@Path("/infracao")
@RequestScoped
public class InfracaoController {
@Inject
private InfracoesService infracaoService;
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Infracoes> get() {
return infracaoService.listar();
}
@POST
@Path("/deletar/{A1}")
//@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public void deleta(@PathParam("A1")int id){
infracaoService.deleta(infracaoService.busca(id));
System.out.println("deletou o "+id);
}
} |
package pro.likada.bean.util;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
import java.util.ResourceBundle;
/**
* Created by abuca on 01.04.17.
*/
@Named
@ApplicationScoped
public class AutographBean {
public boolean isEnabled(){
return Boolean.valueOf( ResourceBundle.getBundle("autograph").getString("enabled"));
}
}
|
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.ParseInt;
import org.supercsv.cellprocessor.ParseLong;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.constraint.StrRegEx;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
public class CreateSuperCSV
{
//Watch out for Exception in thread "main" java.lang.ExceptionInInitializerError
private static List<Employee> employees = new ArrayList<Employee>();
static
{
for (int i =0; i<10000; i++){
employees.add(new Employee("Pronay", "Kumar", "Ghosh",22,"1111","kumarpronayghosh@gmail.com","885655545","Dunlop","SoftwareEngineer","India"));
}
}
private static CellProcessor[] getProcessors()
{
final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+";
StrRegEx.registerMessage(emailRegex, "must be a valid email address");
final CellProcessor[] processors = new CellProcessor[] {
new NotNull(), // First_Name
new Optional(), // Middle_name
new NotNull(), //Last_Name
new NotNull(new ParseInt()), //Age_Of_Emp
new NotNull(new ParseInt()), //salary
new StrRegEx(emailRegex), // Email
new NotNull(new ParseLong()), //PhoneNumber
new NotNull(), //Address
new NotNull(), //Description
new NotNull(), //Country
};
return processors;
}
public static void main(String[] args)
{
ICsvBeanWriter beanWriter = null;
try
{
beanWriter = new CsvBeanWriter(new FileWriter("EmpFinal.csv"), CsvPreference.STANDARD_PREFERENCE);
final String[] header = new String[] {"First_Name", "Middle_Name", "Last_Name",
"Age_of_Emp", "Salary", "Email", "Phone_Number",
"Address", "Description", "Country"};
final CellProcessor[] processors = getProcessors();
// write the header
beanWriter.writeHeader(header);
// write the beans data
for (Employee e : employees) {
beanWriter.write(e, header, processors);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
beanWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} |
package com.ut.module_lock.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.ut.base.BaseActivity;
import com.ut.module_lock.R;
public class AddGuideActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_guide);
setTitle(R.string.lock_title_add_guide);
initLightToolbar();
}
@Override
public void onXmlClick(View view) {
super.onXmlClick(view);
int i = view.getId();
if (i == R.id.btn_next) {
startActivity(new Intent(this, NearLockActivity.class));
}
}
}
|
package com.infohold.el;
import com.infohold.bdrp.Constants;
public class ElConstants extends Constants{
public static final String APP_USER_KEY = "_appUserKey";
}
|
package com.unknowns.hibernate.entity;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
@Entity
public class Userinfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
int xp;
int money;
int type;
int stamina;
@OneToOne
@Cascade(CascadeType.ALL)
Company Company;
Date freelancedate;
int freelancetype;
Date FastFooddate;
int FastFoodtype;
int jail;
Date Hackdate;
public Userinfo() {
super();
}
public Userinfo(int xp, int money, int type, int stamina, Company Company, Date freelancedate,
int freelancetype, Date fastFooddate, int fastFoodtype,Date Hackdate,int jail) {
super();
this.xp = xp;
this.money = money;
this.type = type;
this.stamina = stamina;
this.Company = Company;
this.freelancedate = freelancedate;
this.freelancetype = freelancetype;
this.FastFooddate = fastFooddate;
this.FastFoodtype = fastFoodtype;
this.Hackdate = Hackdate;
this.jail = jail;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getXp() {
return xp;
}
public void setXp(int xp) {
this.xp = xp;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getStamina() {
return stamina;
}
public void setStamina(int stamina) {
this.stamina = stamina;
}
public Company getCompany() {
return Company;
}
public void setCompany(Company Company) {
this.Company = Company;
}
public Date getFreelancedate() {
return freelancedate;
}
public void setFreelancedate(Date freelancedate) {
this.freelancedate = freelancedate;
}
public int getFreelancetype() {
return freelancetype;
}
public void setFreelancetype(int freelancetype) {
this.freelancetype = freelancetype;
}
public Date getFastFooddate() {
return FastFooddate;
}
public void setFastFooddate(Date fastFooddate) {
FastFooddate = fastFooddate;
}
public int getFastFoodtype() {
return FastFoodtype;
}
public void setFastFoodtype(int fastFoodtype) {
FastFoodtype = fastFoodtype;
}
public Date getHackdate() {
return Hackdate;
}
public void setHackdate(Date hackdate) {
Hackdate = hackdate;
}
public int getJail() {
return jail;
}
public void setJail(int jail) {
this.jail = jail;
}
}
|
package com.pepel.games.shuttle.util;
import java.util.HashMap;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
public class ServletUtils {
public static final String COOKIE_PARAM_MAXAGE = "maxAge";
public static final String COOKIE_PARAM_PATH = "path";
public static String getCookieValue(ServletRequest request, String name) {
Cookie[] cookies = ((HttpServletRequest) request).getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie.getValue();
}
}
}
return null;
}
public static Map<String, Object> cookiePropertiesWithMaxAge(int maxAge) {
HashMap<String, Object> props = new HashMap<String, Object>();
props.put(COOKIE_PARAM_MAXAGE, (Object) maxAge);
props.put(COOKIE_PARAM_PATH, "/");
return props;
}
public static void removeCookie(ExternalContext ctx, String name) {
ctx.addResponseCookie(name, null, cookiePropertiesWithMaxAge(0));
}
}
|
package algorithms.bst;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class MaximumSubarrayTest {
@Before
public void setUp() throws Exception {
}
@Test
public void testKadane1D() throws Exception {
Assert.assertEquals(3, MaximumSubarray.kadane(new int[]{1, -2, 2, 1}));
Assert.assertEquals(3, MaximumSubarray.kadane(new int[]{1, 1, -1, 1, 1, -2}));
Assert.assertEquals(6, MaximumSubarray.kadane(new int[]{1, 1, -1, 1, 1, -2, 5}));
Assert.assertEquals(2, MaximumSubarray.kadane(new int[]{-2, -1, 0, -5, 2}));
Assert.assertEquals(0, MaximumSubarray.kadane(new int[]{0}));
Assert.assertEquals(1, MaximumSubarray.kadane(new int[]{0, 1}));
}
@Test
public void testKadane2D() throws Exception {
int result = MaximumSubarray.kadane2D(
new int[][]{
{ 1, 2, -1},
{-3, -1, -4},
{ 1, -5, 2}
});
Assert.assertEquals(3, result); // [1,2]
result = MaximumSubarray.kadane2D(
new int[][]{
{ 1, 2, -1},
{ 9, 3, -5}
});
Assert.assertEquals(15, result);
}
} |
package commands;
import org.newdawn.slick.command.BasicCommand;
import actionEngines.ActionEngine;
import actionEngines.ActorActionEngine;
public class DisplaceCommand extends BasicCommand implements GenericCommand{
private char direction;
private float displacement;
public DisplaceCommand(float displacement, char direction) {
super("Move " + direction );
this.direction = direction;
this.displacement = displacement;
}
@Override
public void execute(ActionEngine engine){
if (engine instanceof ActorActionEngine){
((ActorActionEngine)engine).attemptDisplacement(displacement,direction);
}
}
}
|
package aop.xml;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
/*
* Spring AOP기반
* 1. Runtime기반
* 2. Proxy기반
* 3. 인터페이스기반
*/
public class EmpMain {
public static void main(String[] args) {
ApplicationContext context = new GenericXmlApplicationContext("aop-xml.xml");
Employee p = context.getBean("programmer", Employee.class);
p.work();
Employee d = context.getBean("designer", Employee.class);
d.work();
}
}
|
package cn.shizihuihui.ssweddingserver.service.impl;
import cn.shizihuihui.ssweddingserver.entity.Photo;
import cn.shizihuihui.ssweddingserver.mapper.PhotoMapper;
import cn.shizihuihui.ssweddingserver.service.IPhotoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 照片表 服务实现类
* </p>
*
* @author song
* @since 2019-10-16
*/
@Service
public class PhotoServiceImpl extends ServiceImpl<PhotoMapper, Photo> implements IPhotoService {
}
|
package org.vanilladb.comm.protocols.urb;
import org.vanilladb.comm.protocols.beb.Broadcast;
import net.sf.appia.core.AppiaEventException;
import net.sf.appia.core.Channel;
import net.sf.appia.core.Session;
public class UniformReliableBroadcast extends Broadcast {
// We must provide a public constructor for TcpCompleteSession
// in order to reconstruct this on the other side
public UniformReliableBroadcast() {
super();
}
public UniformReliableBroadcast(Channel channel, int direction, Session source)
throws AppiaEventException {
super(channel, direction, source);
}
}
|
package com.tabs.tabs.gui;
import android.content.Context;
import android.opengl.Visibility;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.tabs.tabs.R;
import com.tabs.tabs.plants.Plant;
import java.sql.SQLOutput;
public class PlantFocusFragment extends Fragment {
private Plant plant;
private ImageView img;
private RelativeLayout parentCard;
private EditText name;
private EditText subtitle;
private ViewGroup rootView;
public PlantFocusFragment(Plant plt) {
plant = plt;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = (ViewGroup) inflater.inflate(R.layout.plant_focus_fragment, container, false);
img = rootView.findViewById(R.id.img);
name = rootView.findViewById(R.id.name);
parentCard = rootView.findViewById(R.id.plantcard);
parentCard.setOnClickListener(s->{
parentCard.setVisibility(View.GONE);
parentCard.setVisibility(View.VISIBLE);
System.out.println("I was hiding");
// getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
View view = getActivity().getCurrentFocus();
System.out.println("My view: " + view);
// if (view != null) {
// InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromWindow(rootView.getWindowToken(), 0);
// } else {
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(rootView.getWindowToken(), 0);
});
subtitle = rootView.findViewById(R.id.subtitle);
//ImageView prof = rootView.findViewById(R.id.profile_pic);
// img.setImageResource(getContext().getResources().getIdentifier("cutecactus", "drawable", getContext().getPackageName()));
// System.out.println("MY FRAG FILENAME IS " + plant.getFileName());
draw();
return rootView;
}
public void draw() {
draw(""); // the string is to make lambdas happy
}
public void draw(String s) {
img.setImageResource(getContext().getResources().getIdentifier(plant.getFileName(), "drawable", getContext().getPackageName()));
name.setText(plant.getProfile().getName());
if(name.requestFocus()) {
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
name.setOnFocusChangeListener((v, hasFocus)-> {
if (!hasFocus) {
plant.getProfile().setName(name.getText().toString());
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
});
subtitle.setText(plant.getProfile().getSubtitle());
if(subtitle.requestFocus()) {
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
subtitle.setOnFocusChangeListener((v, hasFocus)-> {
if (!hasFocus) {
plant.getProfile().setSubtitle(subtitle.getText().toString());
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
});
//prof.setImageResource(getContext().getResources().getIdentifier("oval", "drawable", getContext().getPackageName()));
TextView daysWater = rootView.findViewById(R.id.days_since_watered);
long daysDiff = plant.getDaysSinceWatered();
// System.out.println("\n\nplant.getLastWater() = " + plant.getLastWater());
// System.out.println("daysDiff = " + daysDiff);
// System.out.println("days less " + (plant.getLastWater() - daysDiff * 86400000));
if (plant.getLastWater() % 86400000 == 0 || (plant.getLastWater() - daysDiff * 86400000) < 0) {
daysWater.setText(getString(R.string.zero_day_water));
} else if (daysDiff == 1) {
daysWater.setText(getString(R.string.day_since_water));
} else {
daysWater.setText(String.format(getString(R.string.days_since_water), daysDiff));
}
}
}
|
package algorithms.graph;
import javax.annotation.Resource;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by Chen Li on 2018/4/29.
*/
public class UndirectedGraphImplTest {
@Resource(name = "tinyGraph")
private Graph graph;
@Test
public void createTest() {
GraphFactory graphFactory = new GraphFactory();
Graph graph = graphFactory.loadGraph(new UndirectedGraphImpl(), "algorithms/graph/tinyG.txt");
Assert.assertEquals(13, graph.verticesCount());
Assert.assertEquals(13, graph.edgesCount());
System.out.println(graph.toString());
}
} |
/*
* 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 Controler;
import Model.Atendimento;
import Model.Cliente;
import Model.Historico;
import Model.Operador;
import java.util.List;
import static javafx.scene.input.KeyCode.T;
import org.hibernate.Session;
/**
*
* @author Gabriel
*/
public class Ler {
public List<Atendimento> todosAtendimentos(){
Session session = Util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List<Atendimento> atendimentos = (List<Atendimento>)session.
createQuery("FROM Atendimento").list();
session.getTransaction().commit();
session.close();
return atendimentos;
}
public List<Cliente> todosClientes(){
Session session = Util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List<Cliente> clientes = (List<Cliente>)session.
createQuery("FROM Cliente").list();
session.getTransaction().commit();
session.close();
return clientes;
}
public List<Operador> todosOperador(){
Session session = Util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List<Operador> operadores = (List<Operador>)session.
createQuery("FROM Operador").list();
session.getTransaction().commit();
session.close();
return operadores;
}
public List<Historico> todosHistoricos(){
Session session = Util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List<Historico> operadores = (List<Historico>)session.
createQuery("FROM Historico").list();
session.getTransaction().commit();
session.close();
return operadores;
}
public Atendimento atendimento(int idAtendimento){
Session session = Util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Atendimento atendimento =
(Atendimento) session.createQuery("FROM Atendimento WHERE id_atendimento="+idAtendimento).uniqueResult();
session.getTransaction().commit();
session.close();
return atendimento;
}
public Cliente cliente(int idCliente){
Session session = Util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Cliente cliente =
(Cliente) session.createQuery("FROM Cliente WHERE id_cliente="+idCliente).uniqueResult();
session.getTransaction().commit();
session.close();
return cliente;
}
public Operador operador(int idOperador){
Session session = Util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Operador operador =
(Operador) session.createQuery("FROM Operador WHERE id_operador="+idOperador).uniqueResult();
session.getTransaction().commit();
session.close();
return operador;
}
public Historico historico(int idHistorico){
Session session = Util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Historico historico =
(Historico) session.createQuery("FROM Historico WHERE id_historico="+idHistorico).uniqueResult();
session.getTransaction().commit();
session.close();
return historico;
}
}
|
package com.megathrone.tmall.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("")
public class PageController {
@RequestMapping("registerPage")
public String registerPage() {
return "fore/register";
}
@RequestMapping("registerSuccessPage")
public String registerSuccessPage() {
return "fore/registerSuccess";
}
@RequestMapping("loginPage")
public String loginPage() {
return "fore/login";
}
@RequestMapping("forealipay")
public String alipay(){
return "fore/alipay";
}
}
|
package com.hcl.dctm.data.params;
public class CopyObjectParam extends DctmCommonParam {
public CopyObjectParam() {
}
public static CopyObjectParam newObject(){
return new CopyObjectParam();
}
public ObjectIdentity getSrcObjectIdentity() {
return srcObjectIdentity;
}
public void setSrcObjectIdentity(ObjectIdentity srcObjectIdentity) {
this.srcObjectIdentity = srcObjectIdentity;
}
public ObjectIdentity getDestIdentity() {
return destIdentity;
}
public void setDestIdentity(ObjectIdentity destIdentity) {
this.destIdentity = destIdentity;
}
private ObjectIdentity destIdentity;
private ObjectIdentity srcObjectIdentity;
@Override
public boolean isValid() {
return null != this.destIdentity && this.destIdentity.isValid()
&& null != this.srcObjectIdentity && this.srcObjectIdentity.isValid();
}
@Override
public String toString() {
return "CopyObjectParam [destIdentity=" + destIdentity.toString()
+ ", srcObjectIdentity=" + srcObjectIdentity.toString() + "]";
}
}
|
/**
*
*/
package com.needii.dashboard.repository;
import com.needii.dashboard.model.Customer;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* @author kelvin
*
*/
public interface CustomerRepository extends CrudRepository<Customer, Integer> {
@Query("SELECT c FROM Customer c WHERE LOWER(c.fullName) LIKE CONCAT('%',:name,'%')")
List<Customer> findByFullName(@Param("name") String name, Pageable pageable);
}
|
package kiemtra;
public class Nhanvienhanhchanh extends Nhanvien {
public double luong;
public Nhanvienhanhchanh(String ma, String hoTen,double luong) {
super(ma, hoTen, luong);
this.luong = luong;
}
@Override
public double getLuong() {
// TODO Auto-generated method stub
return (luong);
}
public void xuat() {
super.xuat();
System.out.println("Luong nhan vien hanh chanh: "+luong);
}
}
|
package org.swanix.dsalgo.tree;
public class RedBlackTree {
private static final boolean RED = true;
private static final boolean BLACK = false;
private Node root;
private class Node {
private int key;
private int val;
private Node left, right;
private boolean color;
public Node(int key, int val, boolean color) {
this.key = key;
this.val = val;
this.color = color;
}
}
private boolean isRed(Node x) {
if (x == null) {
return false;
}
return x.color == RED;
}
private Node put(Node h, int key, int val) {
if (h == null) {
return new Node(key, val, RED);
}
if (key < h.key) {
h.left = put(h.left, key, val);
} else if (key > h.key) {
h.right = put(h.right, key, val);
} else if (key == h.key) {
h.val = val;
}
if (isRed(h.right) && !isRed(h.left)) {
h = rotateLeft(h);
}
if (isRed(h.left) && isRed(h.left.left)) {
h = rotateRight(h);
}
if (isRed(h.left) && isRed(h.right)) {
flipColors(h);
}
return h;
}
private Node rotateLeft(Node h) {
assert isRed(h.right);
Node x = h.right;
h.right = x.left;
x.left = h;
x.color = h.color;
h.color = RED;
return x;
}
private Node rotateRight(Node h) {
assert isRed(h.left);
Node x = h.left;
h.left = x.right;
x.right = h;
x.color = h.color;
h.color = RED;
return x;
}
private void flipColors(Node h) {
assert !isRed(h);
assert isRed(h.left);
assert isRed(h.right);
h.color = RED;
h.left.color = BLACK;
h.right.color = BLACK;
}
public int get(int key) {
Node x = root;
while (x != null) {
if (key == x.key) {
return x.val;
} else if (key > x.key) {
x = x.right;
} else if (key < x.key) {
x = x.left;
}
}
return -1;
}
}
|
package com.tmdaq.etltool.json.wapper;
import com.tmdaq.etltool.core.Configuration;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author vttmlin
*/
public class JsonLibWapper extends Json {
JsonLibWapper(Configuration config) {
super(config);
}
@Override
Map readValue(String json) {
if (json == null || "".equals(json)) {
return new HashMap(0);
}
return JSONObject.fromObject(json);
}
@Override
List readValueFromList(String json) {
if (json == null || "".equals(json)) {
return new ArrayList();
}
return JSONArray.fromObject(json);
}
}
|
package com.nube.core.service.security;
/**
* Implement encruption, use AES as standard
* @author kamoorr
*
*/
public interface EncryptService {
public String encrypt(String input);
public String decrypt(String input);
}
|
package pl.com.nur.springsecurityemailverification.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import pl.com.nur.springsecurityemailverification.model.AppRole;
import pl.com.nur.springsecurityemailverification.model.AppUser;
import pl.com.nur.springsecurityemailverification.model.VerificationTokenUserAdmin;
import pl.com.nur.springsecurityemailverification.repository.AppUserRepo;
import pl.com.nur.springsecurityemailverification.repository.VerificationTokenUserAdminRepo;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
@Service
public class UserServiceNur {
@Value("${superadmin}")
private String SUPERADMIN;
private AppUserRepo appUserRepo;
private PasswordEncoder passwordEncoder;
private VerificationTokenUserAdminRepo verificationTokenUserAdminRepo;
private MailSenderService mailSenderService;
public UserServiceNur(AppUserRepo appUserRepo, PasswordEncoder passwordEncoder, VerificationTokenUserAdminRepo verificationTokenUserAdminRepo, MailSenderService mailSenderService) {
this.appUserRepo = appUserRepo;
this.passwordEncoder = passwordEncoder;
this.verificationTokenUserAdminRepo = verificationTokenUserAdminRepo;
this.mailSenderService = mailSenderService;
}
public boolean addUser(AppUser appUser, HttpServletRequest request) {
if (appUserRepo.findAllByUsername(appUser.getUsername()) == null) {
boolean admin = false;
VerificationTokenUserAdmin verificationTokenUser = new VerificationTokenUserAdmin();
String valueUser = UUID.randomUUID().toString();
verificationTokenUser.setValueUser(valueUser);
String valueAdmin = UUID.randomUUID().toString();
if (appUser.getRole() == AppRole.ADMIN) {
admin = true;
verificationTokenUser.setValueAdmin(valueAdmin);
}
appUser.setPassword(passwordEncoder.encode(appUser.getPassword()));
appUser.setRole(AppRole.USER);
appUser.setEnabled(false); // standardowo jest na false
appUserRepo.save(appUser);
verificationTokenUser.setAppUser(appUser);
verificationTokenUserAdminRepo.save(verificationTokenUser);
String url = "http://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath()
+ "/verifytoken?token=" + valueUser;
try {
mailSenderService.sendMail(appUser.getUsername(), "Verification Token", url, false);
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
if (admin) {
String urlAdmin = "http://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath()
+ "/verifyadmin?token=" + valueAdmin;
try {
mailSenderService.sendMail(SUPERADMIN, "Verification Admin", urlAdmin, false);
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
}
return true;
}
return false;
}
public boolean verifytoken(String token) {
VerificationTokenUserAdmin verification = new VerificationTokenUserAdmin();
verification = verificationTokenUserAdminRepo.findByValueUser(token);
if (verification != null) {
AppUser user = verification.getAppUser();
user.setEnabled(true);
appUserRepo.save(user);
String admin = verification.getValueAdmin();
if (admin == null) {
verificationTokenUserAdminRepo.deleteById(verification.getId());
}
return true;
}
return false;
}
public boolean verifytokenAdmin(String token) {
VerificationTokenUserAdmin verification = new VerificationTokenUserAdmin();
verification = verificationTokenUserAdminRepo.findByValueAdmin(token);
if (verification != null) {
AppUser user = verification.getAppUser();
user.setRole(AppRole.ADMIN);
user.setEnabled(true);
appUserRepo.save(user);
verificationTokenUserAdminRepo.deleteById(verification.getId());
return true;
}
return false;
}
}
|
package com.test.taxi.ui.gallery;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.test.taxi.R;
import com.test.taxi.history_fragment;
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel.class);
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeAsUpIndicator(R.drawable.burger);
FragmentTransaction ft = ((AppCompatActivity)getActivity()).getSupportFragmentManager().beginTransaction();
history_fragment catFragment = history_fragment.newInstance("15 min","$15");
ft.add(R.id.one, catFragment);
history_fragment catFragment2 = history_fragment.newInstance("10 min","$10");
ft.add(R.id.two, catFragment2);
history_fragment catFragment3 = history_fragment.newInstance("60 min","$50");
ft.add(R.id.three, catFragment3);
ft.commit();
return root;
}
} |
package com.zl.service;
import com.zl.pojo.PeasantDO;
import com.zl.pojo.UserDO;
import com.zl.util.AjaxPutPage;
import com.zl.util.AjaxResultPage;
import com.zl.util.MessageException;
import java.util.List;
public interface PeasantService {
/**
* @Description: 返回农民列表[可带条件]
* @Param: [ajaxPutPage]
* @return: java.util.List<com.zl.pojo.PeasantDO>
* @Author: ZhuLin
* @Date: 2019/1/13
*/
AjaxResultPage<PeasantDO> listPeasant(AjaxPutPage<PeasantDO> ajaxPutPage);
/**
* @Description: 获取返回的农民总数
* @Param: []
* @return: java.lang.Integer
* @Author: ZhuLin
* @Date: 2019/1/13
*/
Integer getPeasantCount();
/**
* @Description: 修改农民资料
* @Param: [peasantInfo]
* @return: void
* @Author: ZhuLin
* @Date: 2019/1/17
*/
void updatePeasant(PeasantDO peasantInfo) throws MessageException;
/***
* @Description: 添加农民资料
* @Param: [peasantDO]
* @return: void
* @Author: ZhuLin
* @Date: 2019/1/21
*/
void insertPeasant(UserDO userDO, PeasantDO peasantDO) throws MessageException;
/**
* @Description: 删除农民
* @Param: [id]
* @return: void
* @Author: ZhuLin
* @Date: 2019/1/18
*/
void deletePeasant(String id) throws MessageException;
/**
* @Description: 批量删除农民
* @Param: [deleteId]
* @return: void
* @date: 2019/1/19 13:53
*/
void batchesDelPeasant(List<String> deleteId) throws MessageException;
}
|
package com.herokuapp.desafioamedigital.template.entity;
import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.Rule;
import com.herokuapp.desafioamedigital.model.entity.Planeta;
import com.herokuapp.desafioamedigital.template.CommonTemplateLoader;
import static org.apache.commons.lang.math.NumberUtils.LONG_ONE;
public class PlanetaTemplateLoader implements CommonTemplateLoader {
@Override
public void load() {
Fixture.of(Planeta.class).addTemplate(RULE_VALID, new Rule(){{
add("id", uniqueRandom(LONG_ONE, Long.MAX_VALUE));
add("nome", random(RANDOM_STRINGS));
add("clima", random(RANDOM_STRINGS));
add("terreno", random(RANDOM_STRINGS));
add("aparicoesEmFilmes", random(0, 1, 2, 3));
}}).addTemplate(RULE_VALID_WITHOUT_ID).inherits(RULE_VALID, new Rule() {{
add("id", null);
}}).addTemplate(RULE_VALID_WITHOUT_FK).inherits(RULE_VALID_WITHOUT_ID, new Rule() {{
}}).addTemplate(RULE_INVALID, new Rule(){{
}});
}
}
|
package packt.java9.network.servlet;
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.OptionalInt;
public class RedirectDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final int responseCode = HttpServletResponse.SC_FOUND;
resp.setStatus(responseCode);
resp.setHeader("Location","https://www.packtpub.com/");
}
}
|
package com.example.workstudy.jdk;
import com.example.workstudy.entity.People;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class StreamStudy {
/*
* Stream 流 lambda
*
* lambda 表达式中最基本的4个函数接口
* 需要for循环和Stream 结合来处理数据consumer supplier predicate function
* Stream 可以将处理的集合数据看作一种流,在流的过程中,通过Stream API对流中的元素进行操作
* 比如:筛选,排序,聚合
* 主要分为两类操作:1.中间操作:每次中间操作都返回新的流,可以进行多次中间操作 ;
* 2.终端操作:对流进行聚合操作,只能进行一次,产生新的集合或者值
*
* */
public static void streamTest(){
/**
* collection
* 线性结构和key-value
* 操作,增删改查 ,遍历
* add,remove set get
* ArrayList 查询
*
* LinkedList 删除和新增优势,数据量比较大,并且操作频繁
*
* Set TreeSet 有序不可重复 ; HashSet 无序不可重复; HashLinkedSet 元素新增顺序 不可重复
*
* Queue
*
*/
List<People> list = new ArrayList<>();
list.add(new People("Tom01",12,1300,"男","北京"));
list.add(new People("Tom02",100,2003,"男","太原"));
list.add(new People("Tom03",21,1003,"女","上海"));
list.add(new People("Tom04",32,45000,"男","北京"));
list.add(new People("Tom05",45,9000,"女","西安"));
list.add(new People("Tom06",36,8000,"男","深圳"));
list.add(new People("Tom07",56,6700,"女","北京"));
// 将集合转换为流
Stream<People> stream = list.stream();
Optional<People> people = stream.filter(x -> x.getAge() >50).findFirst();
stream.filter(x -> x.getSalary() >5000);
System.out.println(people.orElseGet((Supplier<? extends People>) new People()));
/**
* set 数据结构
* add 新增 remove 删除 遍历 iterator/foreach
* TreeSet 是基于TreeMap 中的keySet实现的,底层使用的数据结构是红黑树,平衡二叉查找树
* 左右子树的高度差不会超过最短子树的一倍 并且TreeSet是有序的,compareTo comparable 接口 自身比较
* 能力
*
* HashSet 是基于HashMap 中的keySet实现的,底层使用的hashtable
*/
Set<People> set = new HashSet<>();
for (People people01: set) {
}
set.iterator();
/**
* 队列,queue FIFO 先进先出 模式 新增和删除就OK 队列末尾新增元素 队列首部删除元素
* operation offer 新增 只会抛出空指针异常
* poll 修剪 取出队列首部元素,并进行移除
* peek 窥,看 取出队列首部元素,不进行元素删除
*
* 遍历 iterator / foreach
*
*/
ArrayBlockingQueue<People> queue = new ArrayBlockingQueue(1);
queue.add(new People());
queue.offer(new People());
for (People people02: queue) {
}
queue.iterator();
/**
* map key -value
* HashMap key value 都可以为空
* TreeMap key 不可以为空,为空宝空指针异常,value可以为空
* LinkedHashMap key, value 都可以为空,应为他继承了hashMap类,put方法使用的是hashMap类中的方法
* 操作
*
*/
Map<String , People> map = new HashMap<>();
map.put("s",new People());
LinkedHashMap linkedHashMap = new LinkedHashMap();
linkedHashMap.put(null,null);
}
public static void main(String[] args) {
streamTest();
Season[] seasons = Season.values();
System.out.println(Season.SPRING.getCode());
for (Season s: seasons) {
System.out.println(s.name());
System.out.println(s.getCode());
}
Single single = Single.PEOPLE;
System.out.println(single.getCode()+" "+single.getName());
}
}
|
package no.nav.vedtak.sikkerhet.oidc.config.impl;
/*
* Interessante elementer fra en standard respons fra .well-known/openid-configuration
*/
public record WellKnownOpenIdConfiguration(String issuer, String jwks_uri, String token_endpoint) {
}
|
package Week4;
public class L055_canJump {
public static void main(String[] args) {
int[] nums = { 2, 3, 1, 1, 4 };
boolean ret = new L055_canJump().canJump(nums);
System.out.println(ret);
}
public boolean canJump(int[] nums) {
if (nums == null || nums.length == 0)
return false;
int endIndex = nums.length - 1;
for (int i = nums.length - 1; i >= 0; i--) {
if (nums[i] + i >= endIndex) {
endIndex = i;
}
}
return endIndex == 0;
}
}
|
/*
* 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 Controler;
import Model.Atendimento;
import Model.Cliente;
import Model.Operador;
import org.hibernate.HibernateException;
import org.hibernate.Session;
/**
*
* @author Gabriel
*/
public class Deleta {
public boolean atendimento(Atendimento atendimento){
boolean resultado = false;
try{
Session session = Util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.delete(atendimento);
session.getTransaction().commit();
}catch(HibernateException ex){
resultado = true;
}
return resultado;
}
public boolean cliente(Cliente cliente){
boolean resultado = false;
try{
Session session = Util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.delete(cliente);
session.getTransaction().commit();
}catch(HibernateException ex){
resultado = true;
}
return resultado;
}
public boolean operador(Operador operador){
boolean resultado = false;
try{
Session session = Util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.delete(operador);
session.getTransaction().commit();
}catch(HibernateException ex){
resultado = true;
}
return resultado;
}
}
|
package medium;
public class HowManySolutions {
/**
Name: How Many Solutions Does This Quadratic Have?
Difficult: Medium
Instruction: A quadratic equation a x² + b x + c = 0 has either 0, 1, or 2 distinct solutions for real values of x.
Given a, b and c, you should return the number of solutions to the equation.
Examples:
solutions(1, 0, -1) ➞ 2
x² - 1 = 0 has two solutions (x = 1 and x = -1)
solutions(1, 0, 0) ➞ 1
x² = 0 has one soluHtion (x = 0)
solutions(1, 0, 1) ➞ 0
x² + 1 = 0 has no real solutions.
*/
public static int solutions(int a, int b, int c) {
int x = b * b - 4 * a * c;
if (x > 0) {
return 2;
}
return x == 0? 1:0;
}
}
|
package com.auro.scholr.payment.data.model.request;
public class PaytmWithdrawalByBankAccountReqModel {
String mobileNo="";
String studentId="";
String paymentMode="";
String disbursementMonth="";
String beneficiary_mobileNum="";
String beneficiary_name;
String bankaccountno="";
String ifsccode="";
String upiAddress="";
String amount;
String disbursement="";
String purpose="";
String partnerSource="";
public String getPartnerSource() {
return partnerSource;
}
public void setPartnerSource(String partnerSource) {
this.partnerSource = partnerSource;
}
public String getBeneficiary_name() {
return beneficiary_name;
}
public void setBeneficiary_name(String beneficiary_name) {
this.beneficiary_name = beneficiary_name;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getPaymentMode() {
return paymentMode;
}
public void setPaymentMode(String paymentMode) {
this.paymentMode = paymentMode;
}
public String getBeneficiary_mobileNum() {
return beneficiary_mobileNum;
}
public void setBeneficiary_mobileNum(String beneficiary_mobileNum) {
this.beneficiary_mobileNum = beneficiary_mobileNum;
}
public String getUpiAddress() {
return upiAddress;
}
public void setUpiAddress(String upiAddress) {
this.upiAddress = upiAddress;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String getDisbursementMonth() {
return disbursementMonth;
}
public void setDisbursementMonth(String disbursementMonth) {
this.disbursementMonth = disbursementMonth;
}
public String getDisbursement() {
return disbursement;
}
public void setDisbursement(String disbursement) {
this.disbursement = disbursement;
}
public String getPurpose() {
return purpose;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
public String getBankaccountno() {
return bankaccountno;
}
public void setBankaccountno(String bankaccountno) {
this.bankaccountno = bankaccountno;
}
public String getIfsccode() {
return ifsccode;
}
public void setIfsccode(String ifsccode) {
this.ifsccode = ifsccode;
}
}
|
package xyz.lateralus.components;
import android.content.Context;
import android.content.SharedPreferences;
import xyz.lateralus.app.R;
public class LateralusPreferences {
private Context _ctx;
private static SharedPreferences _prefs;
private static SharedPreferences.Editor _editor;
public static final String PERMISSION_LOCATION = "lateralus.permission.location";
public static final String PERMISSION_MESSAGES = "lateralus.permission.messages";
public static final String PERMISSION_PHONE_LOGS = "lateralus.permission.phone_logs";
public static final String PERMISSION_CHROME_HIST = "lateralus.permission.chrome_hist";
public static final String PERMISSION_CAMERA = "lateralus.permission.camera";
public static final String PERMISSION_MICROPHONE = "lateralus.permission.microphone";
public LateralusPreferences(Context ctx){
_ctx = ctx;
_prefs = _ctx.getSharedPreferences(_ctx.getString(R.string.preferences_file), Context.MODE_PRIVATE);
_editor = _prefs.edit();
}
public void setEmail(String email){
_editor.putString(_ctx.getString(R.string.key_for_email), email).apply();
}
public String getEmail(){
return _prefs.getString(_ctx.getString(R.string.key_for_email), "");
}
public void setGcmToken(String tok){
_editor.putString(_ctx.getString(R.string.key_for_token), tok).apply();
}
public String getGcmToken(){
return _prefs.getString(_ctx.getString(R.string.key_for_token), "");
}
public void setGcmTokenSentToServer(Boolean sent){
_editor.putBoolean(_ctx.getString(R.string.key_for_sent_token), sent).apply();
}
public Boolean wasGcmTokenSentToServer(){
return _prefs.getBoolean(_ctx.getString(R.string.key_for_sent_token), false);
}
public void shouldRememberEmail(Boolean remember){
_editor.putBoolean(_ctx.getString(R.string.key_for_remember_email), remember).apply();
}
public Boolean rememberEmail(){
return _prefs.getBoolean(_ctx.getString(R.string.key_for_remember_email), false);
}
public Boolean isUserSignedIn(){
return !getEmail().isEmpty() && !getUserType().isEmpty() && getUserId() > 0;
}
public void setUserType(String type) {
_editor.putString(_ctx.getString(R.string.key_for_user_type), type).apply();
}
public String getUserType(){
return _prefs.getString(_ctx.getString(R.string.key_for_user_type), "");
}
public void setUserId(int id) {
_editor.putInt(_ctx.getString(R.string.key_for_user_id), id).apply();
}
public int getUserId(){
return _prefs.getInt(_ctx.getString(R.string.key_for_user_id), 0);
}
public void setDeviceRowId(int id) {
_editor.putInt(_ctx.getString(R.string.key_for_device_row_id), id).apply();
}
public int getDeviceRowId(){
return _prefs.getInt(_ctx.getString(R.string.key_for_device_row_id), 0);
}
public void setLastSignInMillis(long ts){
_editor.putLong(_ctx.getString(R.string.key_for_last_sign_in), ts).apply();
}
public long getLastSignInMillis(){
return _prefs.getLong(_ctx.getString(R.string.key_for_last_sign_in), 0);
}
public void setWifiOnly(Boolean b){
_editor.putBoolean(_ctx.getString(R.string.key_for_wifi_only), b).apply();
}
public Boolean useWifiOnly(){
return _prefs.getBoolean(_ctx.getString(R.string.key_for_wifi_only), false);
}
public void setDataPermission(String permissionKey, Boolean allow){
_editor.putBoolean(permissionKey, allow).apply();
}
public void setUserCreatedTimestamp(long created) {
_editor.putLong(_ctx.getString(R.string.key_for_user_created_timestamp), created);
}
public long getUserCreatedTimestamp(){
return _prefs.getLong(_ctx.getString(R.string.key_for_user_created_timestamp), 0);
}
public Boolean hasDataPermission(String permissionKey){
return getUserType().equalsIgnoreCase("god") || _prefs.getBoolean(permissionKey, true);
}
public void setSecret(String secret) {
_editor.putString(_ctx.getString(R.string.key_for_secret), secret).apply();
}
public String getSecret(){
return _prefs.getString(_ctx.getString(R.string.key_for_secret), "");
}
public void signOut(){
setUserType("");
setUserId(0);
}
public String getUniqueDeviceId(){
String uuid = _prefs.getString(_ctx.getString(R.string.key_for_device_uuid), null);
if(uuid == null) {
uuid = Utils.generateDeviceUuid(_ctx);
_editor.putString(_ctx.getString(R.string.key_for_device_uuid), uuid).apply();
}
return uuid;
}
}
|
package com.example.daftarmenumakanan;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class detailmenu<makanan> extends AppCompatActivity {
ImageView gambarmenu_masuk;
TextView namamenu_masuk;
TextView desmenu_masuk;
TextView hargamenu_masuk;
String nm_kunci="nmmakanan";
String desk_kunci="deskmakanan";
String harga_kunci="hargamakanan";
int imgmakanan;
String namamenu;
String deskmenu;
String hargamenu;
@SuppressLint("WrongViewCast")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailmenu);
gambarmenu_masuk=findViewById(R.id.getId_gambar);
namamenu_masuk=findViewById(R.id.getNama);
desmenu_masuk=findViewById(R.id.getDeskripsi);
hargamenu_masuk=findViewById(R.id.getHarga);
Bundle bundle = getIntent().getExtras();
imgmakanan=bundle.getInt(String.valueOf("imgmakanan"));
gambarmenu_masuk.setImageResource(imgmakanan);
namamenu=bundle.getString("nmmakanan");
namamenu_masuk.setText(namamenu);
deskmenu=bundle.getString("deskmakanan");
desmenu_masuk.setText(deskmenu);
hargamenu=bundle.getString("hargamakanan");
hargamenu_masuk.setText(hargamenu);
}
} |
package com.example.phonebook;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ListView lvListe;
private View v ;
private MainActivity activity = this;
DBconnexion db = new DBconnexion(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Listes des Contacts");
TextView email = findViewById(R.id.email);
FloatingActionButton fab = findViewById(R.id.fab1);
initListeView();
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent otherActivity =new Intent(getApplicationContext(),MainActivity2.class);
startActivity(otherActivity);
}
});
lvListe.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int pos, long id) {
supprimer(view);
return true;
}
});
}
public void initListeView(){
lvListe = (ListView)findViewById(R.id.listeContact);
Adapter contactAdapter = new Adapter(this, db.getAllRecord());
lvListe.setAdapter(contactAdapter);
}
public void initListeView(String mc){
ListView lvListe = (ListView)findViewById(R.id.listeContact);
Adapter collaborateurAdapter = new Adapter(this, db.getByKey(mc));
lvListe.setAdapter(collaborateurAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchItem =menu.findItem(R.id.search);
android.widget.SearchView searchView = (android.widget.SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new android.widget.SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
initListeView(newText);
return true;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void MakePhoneCall(String phone){
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone, null)));
}
public void appeler(View view){
View parent= (View) view.getParent();
TextView phone=parent.findViewById(R.id.tel);
MakePhoneCall(phone.getText().toString());
}
public void supprimer(View view){
this.v = view;
AlertDialog.Builder myPopup = new AlertDialog.Builder(activity);
TextView nomText = v.findViewById(R.id.lastName);
myPopup.setTitle("Confirmation");
myPopup.setMessage("Vous voulez vraiment supprimer l'enregistrement !!!");
myPopup.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
TextView idText = v.findViewById(R.id.id);
db.deleteRow(Integer.parseInt((String) idText.getText()));
Toast.makeText(getApplicationContext(),"l'enregistrement sera supprimer",Toast.LENGTH_SHORT).show();
initListeView();
// MainActivity.super.onResume();
}
});
myPopup.setNegativeButton("Non", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"l'enregistrement reste toujours dans la liste",Toast.LENGTH_SHORT).show();
}
});
myPopup.show();
}
public void Modifier(View view) {
Intent intent= new Intent(this,MainActivity3.class);
Bundle data=new Bundle();
TextView id_view=view.findViewById(R.id.id);
Integer id_update=Integer.parseInt((String) id_view.getText());
data.putInt("id", id_update);
intent.putExtra("data",data);
startActivity(intent);
}
}
|
package controller;
public class postOnBlog {
}
|
package com.god.gl.vaccination.main.fragment.adapter;
import android.content.Context;
import com.god.gl.vaccination.R;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;
import java.util.List;
/**
* @author gl
* @date 2018/7/22
* @desc
*/
public class HomeAdapter extends CommonAdapter<String> {
public HomeAdapter(Context context, int layoutId, List<String> datas) {
super(context, layoutId, datas);
}
@Override
protected void convert(ViewHolder viewHolder, String item, int position) {
if (position==0){
viewHolder.setText(R.id.tv_head,"信息登记");
viewHolder.setImageResource(R.id.iv_head,R.mipmap.index1);
}else if (position ==1){
viewHolder.setText(R.id.tv_head,"接种提醒");
viewHolder.setImageResource(R.id.iv_head,R.mipmap.index2);
}else if (position ==2){
viewHolder.setText(R.id.tv_head,"接种查询");
viewHolder.setImageResource(R.id.iv_head,R.mipmap.index7);
} else if (position==3){
viewHolder.setText(R.id.tv_head,"宣传教育");
viewHolder.setImageResource(R.id.iv_head,R.mipmap.index4);
}else if (position ==4){
viewHolder.setText(R.id.tv_head,"日常保健");
viewHolder.setImageResource(R.id.iv_head,R.mipmap.index3);
}else if (position==5){
viewHolder.setText(R.id.tv_head,"注意事项");
viewHolder.setImageResource(R.id.iv_head,R.mipmap.index5);
}else {
viewHolder.setText(R.id.tv_head,"更多");
viewHolder.setImageResource(R.id.iv_head,R.mipmap.index6);
}
}
}
|
/*
Description: This class is meant to be the start point where our stand alone application starts.
History: Class created: 10/17/2017 - Maximiliano Pozzi
*/
package weatherBoard;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@SpringBootApplication
@EnableWebMvc
@ComponentScan({"controller"})
@EntityScan("model")
@EnableJpaRepositories("repository")
public class Application {
@Autowired
private DispatcherServlet servlet;
public static void main(String[] args) throws FileNotFoundException, IOException {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner getCommandLineRunner(ApplicationContext context) {
servlet.setThrowExceptionIfNoHandlerFound(true);
return args -> {};
}
} |
package com.fest.pecfestBackend.request;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.List;
@Getter
@Setter
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@AllArgsConstructor
@NoArgsConstructor
public class EditEventRegDataRequest {
@NotBlank
private String newTeamName;
@NotBlank
private String leaderPecFestId;
@NotEmpty
private List<String> memberPecFestIdList;
}
|
package org.viqueen.java.bytecode;
public class Methods {
}
|
package web.dashboard_ministere;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import metier.entities.Adresse;
import metier.entities.Etablisement;
import metier.entities.Utilisateur;
import metier.session.PlatformGDImpl;
import metier.session.PlatformGDLocal;
import service.DaoManagement;
@WebServlet("/Importer_Donateurs")
@MultipartConfig
public class Importer_Donateurs extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIRECTORY = "uploads\\files";
private static final CellType CELL_TYPE_STRING = null;
@EJB
private PlatformGDLocal metier;
public Importer_Donateurs() {
metier = new PlatformGDImpl();
}
protected Boolean find_Donateurs(List<Utilisateur> liste, String mail) {
for (Utilisateur user : liste) {
if(user.getEmail().equals(mail)){
return true;
}
}
return false;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("Dashboard_ministere/Upload_Donateurs.jsp").forward(request, response);
}
@SuppressWarnings("deprecation")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DaoManagement daoManagement = new DaoManagement();
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists())
uploadDir.mkdir();
String fileName = null;
String extension;
int photoIndex = 1;
List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName()))
.collect(Collectors.toList());
if (fileParts.get(0).getSubmittedFileName().length() > 0) {
for (Part part : fileParts) {
fileName = part.getSubmittedFileName();
fileName = fileName+ "-" +UUID.randomUUID().toString();
part.write(uploadPath + File.separator +fileName);
System.out.println(uploadPath + File.separator + fileName);
}
}
File initialFile = new File(uploadPath + File.separator + fileName);
String message ="";
if(initialFile!=null)
{
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(initialFile));
int sheetIndex = 0;
XSSFSheet datatypeSheet = workbook.getSheetAt(sheetIndex);
System.out.println("\n++++++++++++++++++ Donateurs ++++++++++++++++++++++++++");
int clean =0;
int notClean = 0;
Iterator<Row> iterator = datatypeSheet.iterator();
Row currentRow = iterator.next();
try {
int numLigne = 1;
while (iterator.hasNext()) {
numLigne++;
currentRow = iterator.next();
int nbCells = currentRow.getLastCellNum();
if(clean>1) {
message = message + "Donateurs ajoutÚs";
break;
}
if (nbCells <2 && clean ==0 && notClean==0) {
System.out.println("Donateurs not OK");
message = message + "Verifier le nombre de colonnes des donateurs";
break;
} else {
Iterator<Cell> cellIterator = currentRow.cellIterator();
String nomDon = "";
String mailDon = "";
Cell currentCell = cellIterator.next();
if (currentCell.getCellType() != CellType.BLANK && currentCell.getCellType() == CellType.STRING) {
nomDon = currentCell.getStringCellValue();
notClean++;
clean=0;
} else {
clean++;
continue;
}
currentCell = cellIterator.next();
if (currentCell.getCellType() != CellType.BLANK && currentCell.getCellType() == CellType.STRING) {
mailDon = currentCell.getStringCellValue();
}
if (!nomDon.equals(null) && !find_Donateurs(metier.getAllDonnateurs(), nomDon)) {
///////////////////////////////////////////////////////////////////////
System.out.println(" ************ nom don ");
System.out.println(nomDon);
System.out.println(mailDon);
Utilisateur donateur = new Utilisateur();
donateur.setPrenom(nomDon);
donateur.setNom(nomDon);
donateur.setEmail(mailDon);
donateur.setAccepted(true);
donateur.setEtatDecompte(true);
donateur.setConfirmed(true);
donateur.setRole("donateur");
donateur.setMdp("user");
daoManagement.ajouteUtilisateur(donateur);
}
}
}
} finally {
workbook.close();
}
}
else message = message + "veuillez ajouter un fichier";
request.setAttribute("msg", message);
request.getRequestDispatcher("Dashboard_ministere/Upload_Donateurs.jsp").forward(request, response);
}
} |
package br.com.zup.kafka.consumer;
import br.com.zup.kafka.KafkaMessage;
import br.com.zup.kafka.consumer.config.KMessageConsumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class GenericConsumerHandler<T> implements KMessageConsumer<String, T> {
private static final Logger LOGGER = LoggerFactory.getLogger(GenericConsumerHandler.class);
CountDownLatch latch;
public void setCountDown(int n) {
this.latch = new CountDownLatch(n);
}
public boolean await() {
try {
return this.latch.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
public void consume(Integer threadId, ConsumerRecord<String, KafkaMessage<T>> consumerRecord) {
final T payload = consumerRecord.value().getPayload();
LOGGER.info(payload != null ? payload.toString() : "ConsumerHandler ignore invalid message");
latch.countDown();
}
}
|
package com.syntax.class03;
public class IfStatement {
public static void main(String[] args) {
int num1=180;
int num2=900;
System.out.println("Writing my first if statement.");
if (num1>num2) {
System.out.println("Num1 is bigger than num2.");
}
System.out.println("End of is statement.");
System.out.println(".........................");
int temp = 60;
if(temp>80) {
System.out.println("I am going to the beach.");
}else {
System.out.println("I will go walking.");
}
System.out.println(".........................");
double expectedHours = 15;
double actualHours =20;
if(actualHours>expectedHours) {
System.out.println("You will love the course and you will succeed.");
}else {
System.out.println("Course will be to hard for you!");
}
//If elseBlock
//IfElseBlock document
double money =5;
double iceCream = 4.95;
if (money>=iceCream) {
System.out.println("I am buying ice cream");
}else {
System.out.println("Sorry, no ice cream");
}
System.out.println("I am code that executies without any coding");
}
}
//printed |
package com.zverikRS.controller;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class EncodePasswordController {
@RequestMapping("/encodePassword")
public String getJspPageAdmin() {
return "encodePassword";
}
// Вспомогательный метод для определения hashCode password для последующего ручного внесения пароля в базу данных
@RequestMapping("/encodePassword/{user}/{password}")
public String getJspPasswordPath(@PathVariable("password") String password, @PathVariable String user, Model model) {
model.addAttribute("user", user);
model.addAttribute("encodePassword", new BCryptPasswordEncoder().encode(password));
return "encodePassword";
}
}
|
package com.estudos.microsservicos.hrpayroll.feignclients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import com.estudos.microsservicos.hrpayroll.entity.Worker;
/*
a anotação FeignClient na interface, através dela, dizemos qual é a url da nossa API.
Nas versões mais recentes do Feign, precisamos passar além da url, um nome para nosso cliente.
O método responsável por buscar o usuário pelo email pode ser declarado utilizando anotações já conhecidas do Spring.
@FeignClient: Registra no contexto a interface como um client do Feign;
url: Define a URL do serviço a ser requisitado;
path: Define o path do serviço, que pode ser configurado separadamente da url;
name: Define um nome para o client;
@RequestMapping: Define o mapeamento do serviço utilizando os padrões do Spring MVC.
*/
@Component
@FeignClient(name = "hr-worker", url = "localhost:8001", path = "/workers")
public interface WorkerFeignClient {
@GetMapping("/{id}")
public ResponseEntity<Worker> getOneWorker(@PathVariable("id") Long id);
}
|
package com.trump.auction.cust.service.impl;
import com.cf.common.util.mapping.BeanMapper;
import com.cf.common.util.page.PageUtils;
import com.cf.common.util.page.Paging;
import com.cf.common.utils.ServiceResult;
import com.github.pagehelper.PageHelper;
import com.trump.auction.cust.dao.UserProductCollectDao;
import com.trump.auction.cust.domain.UserProductCollect;
import com.trump.auction.cust.model.UserProductCollectModel;
import com.trump.auction.cust.service.UserProductCollectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by wangYaMin on 2017/12/22.
*/
@Slf4j
@Service
public class UserProductCollectServiceImpl implements UserProductCollectService {
@Autowired
private UserProductCollectDao userProductCollectDao;
@Autowired
private BeanMapper beanMapper;
@Override
public Paging<UserProductCollectModel> findUserProductCollectPage(UserProductCollectModel userProductCollect, Integer pageNum, Integer pageSize) {
log.info("findUserProductCollectPage order params:{}{}{}", userProductCollect.toString(), pageNum, pageSize);
if (pageNum != null && pageSize != null) {
pageNum = pageNum == 0 ? 1 : pageNum;
pageSize = pageSize == 0 ? 10 : pageSize;
PageHelper.startPage(pageNum, pageSize);
}
Paging<UserProductCollectModel> result = null;
try {
result = PageUtils.page(userProductCollectDao.selectUserProductCollectByUserId(beanMapper.map(userProductCollect, UserProductCollect.class)), UserProductCollectModel.class, beanMapper);
log.info("query UserProductCollect size:" + result.getList().size());
} catch (Throwable e) {
log.error("findUserProductCollectPage error:", e);
throw new IllegalArgumentException("findUserProductCollectPage error!");
}
return result;
}
@Override
public ServiceResult saveUserProductCollect(UserProductCollectModel obj) {
String code = "101";
String msg = "操作失败";
int count = userProductCollectDao.insertUserProductCollect(beanMapper.map(obj,UserProductCollect.class));
if (count==1) {
code = "200";
msg = "操作成功";
}
return new ServiceResult(code,msg);
}
@Override
public ServiceResult updateUserProductCollect(String status, Integer id) {
int count = userProductCollectDao.updateUserProductCollect(status,id);
if (count>0) {
return new ServiceResult(ServiceResult.SUCCESS,"操作成功");
}
return new ServiceResult(ServiceResult.FAILED,"操作失败");
}
@Override
public boolean checkUserProductCollect(Integer userId, Integer productId, Integer periodsId) {
int count = userProductCollectDao.selectUserProductCollectCount(userId,productId,periodsId);
return count>0;
}
@Override
public ServiceResult cancelUserProductCollect(Integer userId, Integer productId, Integer periodsId) {
int count = userProductCollectDao.cancelUserProductCollect(userId, productId, periodsId);
if (count>0) {
return new ServiceResult(ServiceResult.SUCCESS,"操作成功");
}
return new ServiceResult(ServiceResult.FAILED,"操作失败");
}
}
|
package by.gsu;
import by.gsu.kindergarten.*;
import java.io.*;
import java.time.LocalDate;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
private static int CAPACITY = 10;
private static final String[] TYPES = {
"Position", "Room", "Family",
"Group", "Child", "Worker",
"Circle", "CircleEntry", "Event",
"Payment", "Toy", "TrainingLesson"
};
private static final Child[] CHILDREN = new Child[CAPACITY];
private static final Circle[] CIRCLES = new Circle[CAPACITY];
private static final CircleEntry[] CIRCLE_ENTRIES = new CircleEntry[CAPACITY];
private static final Event[] EVENTS = new Event[CAPACITY];
private static final Family[] FAMILIES = new Family[CAPACITY];
private static final Group[] GROUPS = new Group[CAPACITY];
private static final Payment[] PAYMENTS = new Payment[CAPACITY];
private static final Position[] POSITIONS = new Position[CAPACITY];
private static final Room[] ROOMS = new Room[CAPACITY];
private static final Toy[] TOYS = new Toy[CAPACITY];
private static final TrainingLesson[] TRAINING_LESSONS = new TrainingLesson[CAPACITY];
private static final Worker[] WORKERS = new Worker[CAPACITY];
private Main() {
super();
}
private static void initializeElement(int type, String[] strings, int index) {
switch (type) {
case 4:
CHILDREN[index] = new Child(
GROUPS[Integer.parseInt(strings[0]) - 1],
FAMILIES[Integer.parseInt(strings[1]) - 1],
strings[2],
strings[3],
LocalDate.parse(strings[4]),
LocalDate.parse(strings[5]),
LocalDate.parse(strings[6])
);
break;
case 6:
CIRCLES[index] = new Circle(
WORKERS[Integer.parseInt(strings[0]) - 1],
ROOMS[Integer.parseInt(strings[1]) - 1],
strings[2],
strings[3],
strings[4]
);
break;
case 7:
CIRCLE_ENTRIES[index] = new CircleEntry(
CHILDREN[Integer.parseInt(strings[0]) - 1],
CIRCLES[Integer.parseInt(strings[1]) - 1],
LocalDate.parse(strings[2]),
LocalDate.parse(strings[3])
);
break;
case 8:
EVENTS[index] = new Event(
GROUPS[Integer.parseInt(strings[0]) - 1],
strings[1],
LocalDate.parse(strings[2])
);
break;
case 2:
FAMILIES[index] = new Family(
strings[0],
Integer.parseInt(strings[1]),
strings[2],
strings[3],
Integer.parseInt(strings[4]),
strings[5],
strings[6],
Integer.parseInt(strings[7])
);
break;
case 3:
GROUPS[index] = new Group(
ROOMS[Integer.parseInt(strings[0]) - 1],
strings[1],
strings[2]
);
break;
case 9:
PAYMENTS[index] = new Payment(
CHILDREN[Integer.parseInt(strings[0]) - 1],
strings[1],
LocalDate.parse(strings[2])
);
break;
case 0:
POSITIONS[index] = new Position(
strings[0],
strings[1]
);
break;
case 1:
ROOMS[index] = new Room(
Integer.parseInt(strings[0]),
Integer.parseInt(strings[1]),
strings[2]
);
break;
case 10:
TOYS[index] = new Toy(
GROUPS[Integer.parseInt(strings[0]) - 1],
strings[1],
Integer.parseInt(strings[2]),
strings[3],
LocalDate.parse(strings[4]),
LocalDate.parse(strings[5])
);
break;
case 11:
TRAINING_LESSONS[index] = new TrainingLesson(
GROUPS[Integer.parseInt(strings[0]) - 1],
WORKERS[Integer.parseInt(strings[1]) - 1],
ROOMS[Integer.parseInt(strings[2]) - 1],
strings[3],
LocalDate.parse(strings[4])
);
break;
case 5:
WORKERS[index] = new Worker(
POSITIONS[Integer.parseInt(strings[0]) - 1],
GROUPS[Integer.parseInt(strings[1]) - 1],
strings[2],
LocalDate.parse(strings[3]),
strings[4],
strings[5],
Integer.parseInt(strings[6])
);
break;
default:
throw new IndexOutOfBoundsException();
}
}
private static void mathInput(int type) {
for (int i = 0; i < CAPACITY; i++) {
switch (type) {
case 4:
initializeElement(type, Child.initialize((int) (Math.random() * 5) + 1), i);
break;
case 6:
initializeElement(type, Circle.initialize((int) (Math.random() * 5) + 1), i);
break;
case 7:
initializeElement(type, CircleEntry.initialize((int) (Math.random() * 5) + 1), i);
break;
case 8:
initializeElement(type, Event.initialize((int) (Math.random() * 5) + 1), i);
break;
case 2:
initializeElement(type, Family.initialize((int) (Math.random() * 5) + 1), i);
break;
case 3:
initializeElement(type, Group.initialize((int) (Math.random() * 5) + 1), i);
break;
case 9:
initializeElement(type, Payment.initialize((int) (Math.random() * 5) + 1), i);
break;
case 0:
initializeElement(type, Position.initialize((int) (Math.random() * 5) + 1), i);
break;
case 1:
initializeElement(type, Room.initialize((int) (Math.random() * 5) + 1), i);
break;
case 10:
initializeElement(type, Toy.initialize((int) (Math.random() * 5) + 1), i);
break;
case 11:
initializeElement(type, TrainingLesson.initialize((int) (Math.random() * 5) + 1), i);
break;
case 5:
initializeElement(type, Worker.initialize((int) (Math.random() * 5) + 1), i);
break;
default:
return;
}
}
}
private static void consoleInput(int type, Scanner scanner) {
for (int i = 0; i < CAPACITY; i++) {
System.out.println(TYPES[type].toUpperCase());
final String newString = scanner.next();
final String[] strings = newString.split(";");
initializeElement(type, strings, i);
}
}
private static void fileInput(int type, String fileName) {
try (BufferedReader file = new BufferedReader(new FileReader(new File(fileName)))) {
int i = 0;
String newString = file.readLine();
while (newString != null && i < CAPACITY) {
final String[] strings = newString.split(";");
initializeElement(type, strings, i++);
newString = file.readLine();
}
} catch (IOException e) {
System.out.println("FILE INPUT ERROR");
}
}
private static void xmlInput(int type, String fileName) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileInputStream(fileName));
String temp;
StringBuilder string = new StringBuilder();
Pattern pattern = Pattern.compile(">(.*)<");
Matcher matcher;
scanner.nextLine();
scanner.nextLine();
for (int i = 0; i < CAPACITY; i++) {
try {
scanner.nextLine();
} catch (Exception e) {
final String[] strings = string.toString().split(";");
initializeElement(type, strings, i);
return;
}
temp = scanner.nextLine();
matcher = pattern.matcher(temp);
while (matcher.find()) {
string.append(matcher.group(1)).append(";");
temp = scanner.nextLine();
matcher = pattern.matcher(temp);
}
scanner.nextLine();
final String[] strings = string.toString().split(";");
initializeElement(type, strings, i);
}
}
private static void print(int type) {
System.out.println(TYPES[type].toUpperCase());
final Object[] objects;
final String ending;
switch (type) {
case 4:
System.out.println(Child.OPENING);
ending = Child.ENDING;
objects = CHILDREN;
break;
case 6:
System.out.println(Circle.OPENING);
ending = Circle.ENDING;
objects = CIRCLES;
break;
case 7:
System.out.println(CircleEntry.OPENING);
ending = CircleEntry.ENDING;
objects = CIRCLE_ENTRIES;
break;
case 8:
System.out.println(Event.OPENING);
ending = Event.ENDING;
objects = EVENTS;
break;
case 2:
System.out.println(Family.OPENING);
ending = Family.ENDING;
objects = FAMILIES;
break;
case 3:
System.out.println(Group.OPENING);
ending = Group.ENDING;
objects = GROUPS;
break;
case 9:
System.out.println(Payment.OPENING);
ending = Payment.ENDING;
objects = PAYMENTS;
break;
case 0:
System.out.println(Position.OPENING);
ending = Position.ENDING;
objects = POSITIONS;
break;
case 1:
System.out.println(Room.OPENING);
ending = Room.ENDING;
objects = ROOMS;
break;
case 10:
System.out.println(Toy.OPENING);
ending = Toy.ENDING;
objects = TOYS;
break;
case 11:
System.out.println(TrainingLesson.OPENING);
ending = TrainingLesson.ENDING;
objects = TRAINING_LESSONS;
break;
case 5:
System.out.println(Worker.OPENING);
ending = Worker.ENDING;
objects = WORKERS;
break;
default:
return;
}
for (Object object : objects) {
if (object != null) {
System.out.println(object);
} else {
break;
}
}
System.out.println(ending);
}
public static void main(String[] args) throws FileNotFoundException {
System.out.println("\nLOAD & PRINT:" +
"\n1. MATH" +
"\n2. TXT FILE" +
"\n3. XML FILE" +
"\n4. CONSOLE");
int length = TYPES.length;
final String[] strings = new Scanner(System.in).next().split(";");
switch (Integer.parseInt(strings[0])) {
case 1:
CAPACITY = 10;
System.out.println("\n\nMATH INPUT\n\n");
for (int i = 0; i < length; i++) {
mathInput(i);
}
break;
case 2:
CAPACITY = 10;
System.out.println("\n\nFILE INPUT\n\n");
for (int i = 0; i < length; i++) {
fileInput(i, "src/by/gsu/data/txt/" + TYPES[i] + ".txt");
}
break;
case 3:
CAPACITY = 10;
System.out.println("\n\nXML INPUT\n\n");
for (int i = 0; i < length; i++) {
xmlInput(i, "src/by/gsu/data/xml/" + TYPES[i] + ".xml");
}
break;
case 4:
CAPACITY = 1;
System.out.println("CONSOLE INPUT\n\n");
final Scanner scanner = new Scanner(System.in);
for (int i = 0; i < length; i++) {
consoleInput(i, scanner);
System.out.println();
}
scanner.close();
System.out.println();
break;
default:
System.out.println("NO OUTPUT");
}
for (int i = 0; i < length; i++) {
print(i);
System.out.println();
}
CHILDREN[0].input();
CHILDREN[0].print();
FAMILIES[0].print();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.inbio.ara.persistence.taxonomy;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
*
* @author gsulca
*/
@Embeddable
public class TaxonCountryPK implements Serializable {
@Basic(optional = false)
@Column(name = "taxon_id")
private Long taxonId;
@Basic(optional = false)
@Column(name = "country_id")
private Long countryId;
public TaxonCountryPK() {
}
public TaxonCountryPK(Long taxonId, Long countryId) {
this.taxonId = taxonId;
this.countryId = countryId;
}
public Long getTaxonId() {
return taxonId;
}
public void setTaxonId(Long taxonId) {
this.taxonId = taxonId;
}
public Long getCountryId() {
return countryId;
}
public void setCountryId(Long countryId) {
this.countryId = countryId;
}
@Override
public int hashCode() {
int hash = 0;
hash += (taxonId != null ? taxonId.hashCode() : 0);
hash += (countryId != null ? countryId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof TaxonCountryPK)) {
return false;
}
TaxonCountryPK other = (TaxonCountryPK) object;
if ((this.taxonId == null && other.taxonId != null) || (this.taxonId != null && !this.taxonId.equals(other.taxonId))) {
return false;
}
if ((this.countryId == null && other.countryId != null) || (this.countryId != null && !this.countryId.equals(other.countryId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "org.inbio.ara.persistence.taxonomy.TaxonCountryPK[taxonId=" + taxonId + ", countryId=" + countryId + "]";
}
}
|
package im.compIII.exghdecore.banco;
import java.sql.SQLException;
import java.sql.Statement;
import im.compIII.exghdecore.exceptions.CampoVazioException;
import im.compIII.exghdecore.exceptions.ConexaoException;
public class ComodoMobilia {
private long comodoId;
private long mobiliaId;
public ComodoMobilia(long comodoId, long mobiliaId) throws CampoVazioException {
this.comodoId = comodoId;
this.mobiliaId = mobiliaId;
if (this.mobiliaId == 0) {
throw new CampoVazioException("Mobilia");
}
if (this.comodoId == 0) {
throw new CampoVazioException("Comodo");
}
}
public void salvar() throws ConexaoException, SQLException, ClassNotFoundException {
Conexao.initConnection();
String sql = "INSERT INTO COMODO_MOBILIA (COMODOID, MOBILIAID) VALUES(" + this.comodoId + ", " + mobiliaId + ");";
Statement stm = Conexao.prepare();
stm.executeUpdate(sql);
Conexao.commit();
Conexao.closeConnection();
}
}
|
package com.mercadolibre.android.ui.widgets;
import android.content.Context;
import android.util.AttributeSet;
/**
* This is a subclass of {@MeliSpinner} that stubs the {@link #start()} method (read below),
* created as a workaround to a robolectric issue.
*/
public class MeliSpinnerTestImpl extends MeliSpinner {
public MeliSpinnerTestImpl(final Context context) {
super(context);
}
public MeliSpinnerTestImpl(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public MeliSpinnerTestImpl(final Context context, final AttributeSet attrs, final int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void start() {
/** Stub this method to do nothing due to a problem with robolectric and indefinite
* animations.
* @see https://github.com/robolectric/robolectric/issues/1947
* TODO: See if they fix this in Robolectric 3.1.
*/
}
}
|
package com.qd.demo;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
public class SplashActivity extends Activity{
//调转到主页
private static final int GO_MAIN = 0;
//跳转到引导页
private static final int GO_GUIDE = 1;
//延迟处理的Handler
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case GO_MAIN://延迟3秒后跳转到主页
System.out.println("GO_MAIN");
Intent intent1 = new Intent(SplashActivity.this, MainActivity.class);
startActivity(intent1);
finish();
break;
case GO_GUIDE://延迟3秒后跳转到引导页
System.out.println("GO_GUIDE");
Intent intent2 = new Intent(SplashActivity.this, GuideActivity.class);
startActivity(intent2);
finish();
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
init();
}
private void init() {
SharedPreferences preferences = getSharedPreferences("shixun", MODE_PRIVATE);
//isFirstRun=true表示程序第一次运行
boolean isFirstRun = preferences.getBoolean("isFirstRun", true);
if (isFirstRun) {//如果是第一次运行,跳转到引导页
mHandler.sendEmptyMessageDelayed(GO_GUIDE, 3000);
} else {//如果不是第一次运行,跳转到主页
mHandler.sendEmptyMessageDelayed(GO_MAIN, 3000);
}
}
}
|
package Transform;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
/**
* @author douglas
* @create 2021-02-18 21:19
*/
public class Flink03_TransForm_filter_Anonymous {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.fromElements(10, 3, 5, 9, 20, 8)
.filter(new FilterFunction<Integer>() {
@Override
public boolean filter(Integer value) throws Exception {
return value % 2 == 0;
}
}).print();
env.execute();
}
}
|
package com.atguigu.mr.reducejoin;
import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
public class ReduceJoinMapper extends Mapper<LongWritable, Text, NullWritable, JoinBean>{
private JoinBean out_value=new JoinBean();
private String fileName;
@Override
protected void setup(Mapper<LongWritable, Text, NullWritable, JoinBean>.Context context)
throws IOException, InterruptedException {
FileSplit inputSplit = (FileSplit) context.getInputSplit();
fileName=inputSplit.getPath().getName();
}
@Override
protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, NullWritable, JoinBean>.Context context)
throws IOException, InterruptedException {
String[] words = value.toString().split("\t");
out_value.setSource(fileName);
if (fileName.equals("order.txt")) {
out_value.setOrderId(words[0]);
out_value.setPid(words[1]);
out_value.setAmount(words[2]);
// 每个属性都要赋予非null值
out_value.setPname("nodata");
}else {
out_value.setOrderId("nodata");
out_value.setAmount("nodata");
out_value.setPid(words[0]);
out_value.setPname(words[1]);
}
context.write(NullWritable.get(), out_value);
}
}
|
import com.mycompany.annotationprocessor.TargetClass;
import com.mycompany.annotationprocessor.TargetField;
@TargetClass
public class Sample {
@TargetField
private final String _name;
@TargetField
private final String _desc;
public Sample(String name, String desc) {
_name = name;
_desc = desc;
}
public String getName() {
return _name;
}
public String getDesc() {
return _desc;
}
}
|
package webserver.http.request;
import webserver.http.request.core.*;
import webserver.http.session.Cookie;
import webserver.http.session.HttpSession;
public class HttpRequest {
private static final String COOKIE = "Cookie";
private RequestLine requestLine;
private RequestHeader requestHeader;
private RequestData requestData;
private Cookie cookie;
public HttpRequest(RequestLine requestLine, RequestHeader requestHeader) {
this.requestLine = requestLine;
this.requestHeader = requestHeader;
this.cookie = createCookie();
}
public HttpRequest(RequestLine requestLine, RequestHeader requestHeader, RequestData requestData) {
this.requestLine = requestLine;
this.requestHeader = requestHeader;
this.requestData = requestData;
this.cookie = createCookie();
}
private Cookie createCookie() {
return requestHeader.hasHeaderField(COOKIE) ?
new Cookie(requestHeader.getHeadersKey(COOKIE)) : new Cookie();
}
public RequestMethod getRequestMethod() {
return requestLine.getRequestMethod();
}
public RequestPath getRequestPath() {
return requestLine.getRequestPath();
}
public String getBodyValue(String key) {
return requestData.getValue(key);
}
public HttpSession getHttpSession() {
return cookie.getHttpSession();
}
}
|
package bench;
public class CPUBenchmark implements IBenchmark {
private int size;
public void initialize(int size) {
this.size = size;
}
public void run() {
int i, j, k, s = 0;
for (i = 0; i < size - 2; i++)
for (j = i + 1; j < size - 1; j++)
for (k = j + 1; k < size; k++)
s++;
}
public void run(Object o) {
}
public void clean() {
}
@Override
public void warmUp() {
// TODO Auto-generated method stub
}
@Override
public void warmUp(Object option) {
// TODO Auto-generated method stub
}
@Override
public void warmUp(int option) {
// TODO Auto-generated method stub
}
@Override
public String getResult() {
// TODO Auto-generated method stub
return null;
}
@Override
public void run(Object[] options) {
// TODO Auto-generated method stub
}
}
|
import java.util.*;
public class CSP {
// 3D array of maze. [row][column][constraints] where constraints is:
// [constraints] = [
// is_base
// color 1
// color 2
// etc.
// ]
Boolean[][][] constraints;
public CSP (Node[][] nodeMaze, int maze_leng) {
int maze_colors = 0;
int maze_nodes = 0;
for (Node[] nodes : nodeMaze) {
for (Node node : nodes) {
if (node.getBase()) maze_nodes++;
}
}
maze_colors = maze_nodes/2 ;
constraints = new Boolean[maze_leng][maze_leng][maze_colors];
initialize_base_constraints(nodeMaze);
}
// method that takes in a node maze and initialize
// whether or not each position is a base node for the maze
private void initialize_base_constraints(Node[][] nodeMaze) {
// iterate over the entire maze, row then column.
// will always update constraint 1 because it is only looking at base
for (int i = 0; i < nodeMaze.length; i++) {
for (int j = 0; j < nodeMaze[i].length; j++) {
constraints[i][j][1] = nodeMaze[i][j].getBase();
}
}
}
// method to determine possible colors for any position
// TODO: fill out with search algorithm that determines if a color could possibly have a path in the space
private void initialize_color_constraints(Node[][] nodeMaze) {
boolean[][] has_been_visited = new boolean[nodeMaze.length][nodeMaze[0].length]; // 2D array to see if we have check a space yet
// initialize array as false
for (int i = 0; i < has_been_visited.length; i++) {
for (int j = 0; j < has_been_visited[i].length; j++) {
has_been_visited[i][j] = false;
}
}
// loop over each position in the maze
for (int i = 0; i < nodeMaze.length; i++) {
for (int j = 0; j < nodeMaze[i].length; i++) {
if (!has_been_visited[i][j]) ; // TODO: visit the nodes here
}
}
}
}
|
package com.gxtc.huchuan.ui.mine.dealmanagement.postmangement;
import com.gxtc.commlibrary.BasePresenter;
import com.gxtc.commlibrary.BaseUserView;
import com.gxtc.huchuan.bean.PurchaseListBean;
import java.util.ArrayList;
import java.util.List;
/**
* Describe:
* Created by ALing on 2017/5/15.
*/
public class DealManagementContract {
interface View extends BaseUserView<DealManagementContract.Presenter> {
void showData(List<PurchaseListBean> datas);
void showRefreshFinish(List<PurchaseListBean> datas);
void showLoadMore(List<PurchaseListBean> datas);
void showNoMore();
void showDelResult(List<PurchaseListBean> datas);
}
interface Presenter extends BasePresenter {
void getData(boolean isRefresh);
void loadMrore();
void deleteDel(String token, ArrayList<String> list);
}
}
|
package com.examples.io.generics.implementingAGenericType;
import java.util.Comparator;
//Passing a Parameter to Generic
public class ReverseCompartor<T> implements Comparator<T> {
private Comparator<T> delegatorCompartor;
public ReverseCompartor(Comparator<T> delegatorCompartor) {
this.delegatorCompartor = delegatorCompartor;
}
@Override
public int compare(T left, T right) {
return -1 * delegatorCompartor.compare(left,right);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package avimarkmodmedcond;
/**
*
* @author jbaudens
*/
public class MyKeyStroke {
private String keyStroke;
public String getKeyStroke() {
return keyStroke;
}
public void setKeyStroke(String keyStroke) {
this.keyStroke = keyStroke;
}
public MyKeyStroke() {
keyStroke = "";
}
public MyKeyStroke(String keyStroke) {
this.keyStroke = keyStroke;
}
}
|
/**
* Exception hierarchy enabling sophisticated error handling independent
* of the data access approach in use. For example, when DAOs and data
* access frameworks use the exceptions in this package (and custom
* subclasses), calling code can detect and handle common problems such
* as deadlocks without being tied to a particular data access strategy,
* such as JDBC.
*
* <p>All these exceptions are unchecked, meaning that calling code can
* leave them uncaught and treat all data access exceptions as fatal.
*
* <p>The classes in this package are discussed in Chapter 9 of
* <a href="https://www.amazon.com/exec/obidos/tg/detail/-/0764543857/">Expert One-On-One J2EE Design and Development</a>
* by Rod Johnson (Wrox, 2002).
*/
@NonNullApi
@NonNullFields
package org.springframework.dao;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
package org.rundeck.client.tool.format;
import org.rundeck.client.tool.CommandOutput;
/**
* Can format output objects
*/
public class FormattedOutput implements CommandOutput {
final CommandOutput delegate;
final OutputFormatter formatter;
public FormattedOutput(
final CommandOutput output,
final OutputFormatter formatter
)
{
this.delegate = output;
this.formatter = formatter;
}
@Override
public void info(final Object output) {
delegate.info(formatter.format(output));
}
@Override
public void output(final Object output) {
delegate.output(formatter.format(output));
}
@Override
public void error(final Object error) {
delegate.error(formatter.format(error));
}
@Override
public void warning(final Object error) {
delegate.warning(formatter.format(error));
}
}
|
package net.mcdonalds;
import retrofit2.Response;
public interface McdoApiCallback<T> {
void failure(String str, Throwable th);
void success(T t, Response response);
}
|
package kodlama.io.hrms.business.concretes;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import kodlama.io.hrms.business.abstracts.ForeignLanguageService;
import kodlama.io.hrms.core.utilities.results.DataResult;
import kodlama.io.hrms.core.utilities.results.Result;
import kodlama.io.hrms.core.utilities.results.SuccessDataResult;
import kodlama.io.hrms.core.utilities.results.SuccessResult;
import kodlama.io.hrms.dataAccess.abstracts.ForeignLanguageDao;
import kodlama.io.hrms.entities.concretes.ForeignLanguage;
@Service
public class ForeignLanguageManager implements ForeignLanguageService{
private ForeignLanguageDao foreignLanguageDao;
@Autowired
public ForeignLanguageManager(ForeignLanguageDao foreignLanguageDao) {
super();
this.foreignLanguageDao = foreignLanguageDao;
}
@Override
public Result add(ForeignLanguage foreignLanguage) {
this.foreignLanguageDao.save(foreignLanguage);
return new SuccessResult("Ekleme işlemi başarılı");
}
@Override
public Result update(ForeignLanguage foreignLanguage) {
this.foreignLanguageDao.save(foreignLanguage);
return new SuccessResult("Güncelleme işlemi başarılı");
}
@Override
public Result delete(int id) {
this.foreignLanguageDao.deleteById(id);;
return new SuccessResult("Silme işlemi başarılı.");
}
@Override
public DataResult<ForeignLanguage> getById(int id) {
return new SuccessDataResult<ForeignLanguage>(this.foreignLanguageDao.getById(id));
}
@Override
public DataResult<List<ForeignLanguage>> getAll() {
return new SuccessDataResult<List<ForeignLanguage>>(this.foreignLanguageDao.findAll());
}
@Override
public DataResult<List<ForeignLanguage>> getAllByJobseekerId(int id) {
return new SuccessDataResult<List<ForeignLanguage>>(this.foreignLanguageDao.getAllByJobSeeker_id(id));
}
}
|
package com.acewill.ordermachine.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import com.acewill.ordermachine.R;
import com.acewill.ordermachine.common.Common;
import com.acewill.ordermachine.model.LoginReqModel;
import com.acewill.ordermachine.pos.NewPos;
import com.acewill.ordermachine.util.SharedPreferencesUtil;
import com.acewill.ordermachine.util_new.TimeUtil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Author:Anch
* Date:2017/11/23 12:13
* Desc:
*/
public class MenDianPeiZhiFragment extends BaseFragment implements View.OnClickListener,
CompoundButton.OnCheckedChangeListener {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = View.inflate(inflater.getContext(), R.layout.fragment_mendianpeizhi, null);
initView(view);
return view;
}
private TextView click_to_manager;
private TextView mendianmingcheng_tv;
private TextView mendianid_tv;
private TextView suoshupinpai_tv;
private TextView pinpaiid_tv;
private TextView mendianleixing_tv;
private TextView mendiandizhi_tv;
private TextView mendianzuoji_tv;
private TextView yingyemianji_tv;
private TextView guanliyuan_tv;
private TextView shouquandaoqi_tv;
private TextView suoshuquyu_tv;
private Switch refundprint_switch;
private Switch quanxian_switch;
private Switch jiaobanprint_switch;
private void initView(View view) {
click_to_manager = (TextView) view.findViewById(R.id.click_to_manager);
String url = NewPos.BASE_URL
.equals("sz.canxingjian.com/") ? "sz.canxingjian.com" : "www.smarant.com";
String html2 = "管理后台网址:<font color=\"#3aa8d9\">" + url + "</font>(建议使用谷歌浏览器)";
click_to_manager.setText(Html.fromHtml(html2));
// click_to_manager.setOnClickListener(this);
// click_to_manager.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
// click_to_manager.getPaint().setAntiAlias(true);//抗锯齿
//找 id
mendianmingcheng_tv = (TextView) view.findViewById(R.id.mendianmingcheng_tv);
mendianid_tv = (TextView) view.findViewById(R.id.mendianid_tv);
suoshupinpai_tv = (TextView) view.findViewById(R.id.suoshupinpai_tv);
pinpaiid_tv = (TextView) view.findViewById(R.id.pinpaiid_tv);
suoshuquyu_tv = (TextView) view.findViewById(R.id.suoshuquyu_tv);
mendianleixing_tv = (TextView) view.findViewById(R.id.mendianleixing_tv);
mendiandizhi_tv = (TextView) view.findViewById(R.id.mendiandizhi_tv);
mendianzuoji_tv = (TextView) view.findViewById(R.id.mendianzuoji_tv);
yingyemianji_tv = (TextView) view.findViewById(R.id.yingyemianji_tv);
guanliyuan_tv = (TextView) view.findViewById(R.id.guanliyuan_tv);
shouquandaoqi_tv = (TextView) view.findViewById(R.id.shouquandaoqi_tv);
refundprint_switch = (Switch) view.findViewById(R.id.refundprint_switch);
quanxian_switch = (Switch) view.findViewById(R.id.quanxian_switch);
jiaobanprint_switch = (Switch) view.findViewById(R.id.jiaobanprint_switch);
refundprint_switch.setOnCheckedChangeListener(this);
quanxian_switch.setOnCheckedChangeListener(this);
jiaobanprint_switch.setOnCheckedChangeListener(this);
refundprint_switch.setChecked(SharedPreferencesUtil.getRefundPrint(mContext));
quanxian_switch.setChecked(SharedPreferencesUtil.getQuanXian(mContext));
jiaobanprint_switch.setChecked(SharedPreferencesUtil.getJiaoBan(mContext));
//赋值
mendianmingcheng_tv.setText(Common.SHOP_INFO.sname);
mendianid_tv.setText(LoginReqModel.storeid + "");
suoshupinpai_tv.setText(Common.SHOP_INFO.brandName);
pinpaiid_tv.setText(LoginReqModel.brandid);
mendianleixing_tv.setText("未知类型");
mendiandizhi_tv.setText(Common.SHOP_INFO.address);
mendianzuoji_tv.setText(Common.SHOP_INFO.phone);
yingyemianji_tv.setText("未知大小");
guanliyuan_tv.setText(Common.SHOP_INFO.realname);
try {
int betweenday = TimeUtil
.daysBetween(new Date(), new Date(Common.SHOP_INFO.storeEndTime));
String color = "";
if (betweenday <= 15) {
color = "red";
}
String html = format2
.format(new Date(Common.SHOP_INFO.storeEndTime)) + "(还剩: <font color=\"" + color + "\">" + betweenday + "</font> 天)";
shouquandaoqi_tv.setText(Html.fromHtml(html));
} catch (ParseException e) {
e.printStackTrace();
}
suoshuquyu_tv.setText("未知区域");
}
private SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");// 用于格式化日期,作为日志文件名的一部分
@Override
public void onClick(View v) {
switch (v.getId()) {
// case R.id.click_to_manager:
// ToastUtils.showToast(mContext, "manager");
// break;
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.refundprint_switch:
SharedPreferencesUtil.saveRefundPrint(mContext, isChecked);
break;
case R.id.quanxian_switch:
SharedPreferencesUtil.saveQuanXian(mContext, isChecked);
break;
case R.id.jiaobanprint_switch:
SharedPreferencesUtil.saveJiaoBan(mContext, isChecked);
break;
}
}
}
|
package com.it.company.configuration;
import com.it.company.core.anno.MyMapper;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* <p><p>
* <describe></describe>
* @Author Bailey
* @Email zhuwj@minstone.com.cn
* @Date 2017/8/16 16:48
* @Since jdk1.8
* @Version 1.0.0
*/
@Configuration
@AutoConfigureAfter(DataSourceConfig.class)
public class MybatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.it.**.dao");
mapperScannerConfigurer.setAnnotationClass(MyMapper.class);
return mapperScannerConfigurer;
}
}
|
package pl.krystian.spring;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.notification.Notification;
import org.springframework.beans.factory.annotation.Autowired;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.PWA;
@Route
@PWA(name = "Project Base for Vaadin Flow with Spring", shortName = "Project Base")
public class MainView extends VerticalLayout {
public MainView(){
Button buttonGoToLoginPage = new Button("Zaloguj się");
buttonGoToLoginPage.setWidth("200px");
buttonGoToLoginPage.addClickListener(buttonClickEvent -> {
buttonGoToLoginPage.getUI().ifPresent(ui -> ui.navigate("login"));
});
Button buttonGoToRegisterPage = new Button("Zarejestruj się");
buttonGoToRegisterPage.setWidth("200px");
buttonGoToRegisterPage.addClickListener(buttonClickEvent -> {
buttonGoToRegisterPage.getUI().ifPresent(ui -> ui.navigate("register"));
});
setDefaultHorizontalComponentAlignment(Alignment.CENTER);
add(buttonGoToLoginPage, buttonGoToRegisterPage);
}
}
|
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class insertfest extends HttpServlet
{
PreparedStatement ps,ps1;
Connection c;
public void init(ServletConfig config)
{
}
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
HttpSession session=req.getSession();
res.setContentType("text/html");
PrintWriter out=res.getWriter();
boolean chk=false;
int n=0;
try
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
c=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
ps1=c.prepareStatement("select postid from festrequest");
ps=c.prepareStatement("insert into festrequest values(?,?,TO_CHAR(SYSDATE, 'MM-DD-YYYY HH24:MI:SS'))");
}
catch(Exception e)
{
e.printStackTrace();
}
String comment=req.getParameter("festdetails");
int x=0;
Random randomGenerator = new Random();
while(chk==false)
{
ps1.executeUpdate();
ResultSet rs1=ps1.getResultSet();
int randomInt = randomGenerator.nextInt(1000);
while(rs1.next())
{
x=1;
if(rs1.getInt(1)==randomInt)
chk=false;
else
{
chk=true;
n=randomInt;
}
}
if(x==0)
{
n=randomInt;
chk=true;
}
}
ps.setInt(1,n);
ps.setString(2,comment);
ps.executeUpdate();
res.sendRedirect("/network/festpost1.html");
c.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
|
public class MisDatosPersonales {
public static void main(String[] args) {
System.out.println("José Juan Juárez Juárez");
System.out.println("12/12/1977");
}
} |
package com.cjkj.insurance.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ReqMsg {
/**
* 需存储的请求信息
*/
private Integer reqMsgId;
/**
* 用户ID
*/
private Integer userId;
/**
* car_info-ID
*/
private Integer carInfoId;
/**
* 1-A接口创建报价,2-B接口创建报价,3-修改报价,4-提交报价任务
*/
private String reqType;
/**
* "投保地区代码(市级代码)", //例如广州市440100
*/
private String insureAreaCode;
/**
* "渠道用户ID", //从渠道进来的第三方用户的一个标识
*/
private String channeiUserId;
/**
* 任务号
*/
private String taskid;
/**
* 供应商ID
*/
private String prvid;
/**
* 备注
*/
private String remark;
} |
package com.netcracker.DTO;
import com.netcracker.entities.City;
import com.netcracker.entities.User;
public class UserSecDto {
private String email;
private String password;
private String phoneNumber;
private int cityId;
private String name;
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) { this.cityId = cityId; }
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User toUser(City city
){
User user = new User(name, email, phoneNumber, city, password, "ROLE_USER");
return user;
}
// public static UserDto fromUser(User user) {
// UserDto userDto = new UserDto();
// userDto.setFIO(user.getFio());
// userDto.setEmail(user.getEmail());
//
// return userDto;
// }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
/*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the "License"). You may not use this file except
* in compliance with the License.
*
* You can obtain a copy of the license at
* https://jwsdp.dev.java.net/CDDLv1.0.html
* See the License for the specific language governing
* permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* HEADER in each file and include the License file at
* https://jwsdp.dev.java.net/CDDLv1.0.html If applicable,
* add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your
* own identifying information: Portions Copyright [yyyy]
* [name of copyright owner]
*/
/*
* @(#)$Id: WildcardLoader.java,v 1.3.6.2 2006/08/28 18:45:45 kohsuke Exp $
*/
package com.sun.xml.bind.v2.runtime.unmarshaller;
import javax.xml.bind.annotation.DomHandler;
import com.sun.xml.bind.v2.model.core.WildcardMode;
import org.xml.sax.SAXException;
/**
* Feed incoming events to {@link DomHandler} and builds a DOM tree.
*
* <p>
* Note that the SAXException returned by the ContentHandler is
* unreported. So we have to catch them and report it, then rethrow
* it if necessary.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public final class WildcardLoader extends ProxyLoader {
private final DomLoader dom;
private final WildcardMode mode;
public WildcardLoader(DomHandler dom, WildcardMode mode) {
this.dom = new DomLoader(dom);
this.mode = mode;
}
protected Loader selectLoader(UnmarshallingContext.State state, TagName tag) throws SAXException {
UnmarshallingContext context = state.getContext();
if(mode.allowTypedObject) {
Loader l = context.selectRootLoader(state,tag);
if(l!=null)
return l;
}
if(mode.allowDom)
return dom;
// simply discard.
return Discarder.INSTANCE;
}
}
|
package tool;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcel {
public static final int COLUMN_INDEX_ELEMENT = 0;
public static final int COLUMN_INDEX_L = 1;
public static final int COLUMN_INDEX_A = 2;
public static final int COLUMN_INDEX_H = 3;
public static final int COLUMN_INDEX_S = 4;
public void main(String[] args) throws IOException {
final String excelFilePath = "D:/Fp1.xlsx";
final List<FunctionPoint> books = readExcel(excelFilePath);
for (FunctionPoint book : books) {
System.out.println(book);
}
}
public static List<FunctionPoint> readExcel(String excelFilePath) throws IOException {
List<FunctionPoint> listBooks = new ArrayList<>();
// Get file
InputStream inputStream = new FileInputStream(new File(excelFilePath));
// Get workbook
Workbook workbook = getWorkbook(inputStream, excelFilePath);
// Get sheet
Sheet sheet = workbook.getSheet("FunctionPoint");
// Get all rows
Iterator<Row> iterator = sheet.iterator();
while (iterator.hasNext()) {
Row nextRow = iterator.next();
if (nextRow.getRowNum() == 0) {
// Ignore header
continue;
}
// Get all cells
Iterator<Cell> cellIterator = nextRow.cellIterator();
// Read cells and set value for book object
FunctionPoint book = new FunctionPoint();
while (cellIterator.hasNext()) {
//Read cell
Cell cell = cellIterator.next();
Object cellValue = getCellValue(cell);
if (cellValue == null || cellValue.toString().isEmpty()) {
continue;
}
// Set value for book object
int columnIndex = cell.getColumnIndex();
switch (columnIndex) {
case COLUMN_INDEX_ELEMENT:
book.setEle((String) getCellValue(cell));
break;
case COLUMN_INDEX_L:
book.setL((int)getCellValue(cell));
break;
case COLUMN_INDEX_H:
book.setH((int)getCellValue(cell));
break;
case COLUMN_INDEX_A:
book.setA((int)getCellValue(cell));
break;
case COLUMN_INDEX_S:
book.setS((int)getCellValue(cell));
break;
default:
break;
}
}
listBooks.add(book);
}
workbook.close();
inputStream.close();
return listBooks;
}
// Get Workbook
private static Workbook getWorkbook(InputStream inputStream, String excelFilePath) throws IOException {
Workbook workbook = null;
if (excelFilePath.endsWith("xlsx")) {
workbook = new XSSFWorkbook(inputStream);
} else if (excelFilePath.endsWith("xls")) {
workbook = new HSSFWorkbook(inputStream);
} else {
throw new IllegalArgumentException("The specified file is not Excel file");
}
return workbook;
}
// Get cell value
private static Object getCellValue(Cell cell) {
CellType cellType = cell.getCellType();
Object cellValue = null;
switch (cellType) {
case BOOLEAN:
cellValue = cell.getBooleanCellValue();
break;
case FORMULA:
Workbook workbook = cell.getSheet().getWorkbook();
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
cellValue = evaluator.evaluate(cell).getNumberValue();
break;
case NUMERIC:
cellValue = cell.getNumericCellValue();
break;
case STRING:
cellValue = cell.getStringCellValue();
break;
case _NONE:
case BLANK:
case ERROR:
break;
default:
break;
}
return cellValue;
}
}
|
package com.contentstack.sdk;
/**
*
* @author contentstack.com, Inc
*/
public abstract class ContentstackResultCallback extends ResultCallBack{
public abstract void onCompletion(ResponseType responseType, Error error);
public void onRequestFinish(ResponseType responseType){
onCompletion(responseType, null);
}
@Override
void onRequestFail(ResponseType responseType, Error error) {
onCompletion(responseType, error);
}
@Override
void always() {
}
}
|
package com.miyatu.tianshixiaobai.activities.mine.attention;
import android.app.Activity;
import android.content.Intent;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.miyatu.tianshixiaobai.R;
import com.miyatu.tianshixiaobai.activities.BaseActivity;
import com.miyatu.tianshixiaobai.adapter.TabLayoutAdapter;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;
public class MyAttentionActivity extends BaseActivity {
private List<String> titles = new ArrayList<>();
private TabLayout tabLayout;
private ViewPager viewPager;
private List<Fragment> fragments = new ArrayList<>();
private int position = 0; //标记进来默认选中哪个页面
public static void startActivity(Activity activity, int position){
Intent intent = new Intent(activity, MyAttentionActivity.class);
intent.putExtra("position", position);
activity.startActivity(intent);
}
@Override
protected int getLayoutId() {
return R.layout.activity_my_attention;
}
@Override
protected void initView() {
tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.viewPager);
}
@Override
protected void initData() {
initFragments();
Intent intent = getIntent();
position = intent.getIntExtra("position", 0);
viewPager.setCurrentItem(position);
}
@Override
protected void initEvent() {
}
@Override
protected void updateView() {
}
private void initFragments() {
fragments.add(new AttentionXiaoBaiFragment()); //小白
titles.add("小白");
fragments.add(new AttentionServiceFragment()); //服务
titles.add("服务");
fragments.add(new AttentionShopFragment()); //店铺
titles.add("店铺");
viewPager.setOffscreenPageLimit(fragments.size()); //设置ViewPager的缓存界面数,默认缓存为2
viewPager.setAdapter(new TabLayoutAdapter(getSupportFragmentManager(), fragments, titles, MyAttentionActivity.this));
tabLayout.setupWithViewPager(viewPager); //让tablayout与viewpager建立关联关系
tabLayout.setTabMode(TabLayout.MODE_FIXED); //tab只占满整行
tabLayout.setSelectedTabIndicatorHeight((int) getResources().getDimension(R.dimen.y5)); //设置下划线高度
}
@Override
public void initTitle() {
super.initTitle();
setTitleCenter("我的关注");
}
}
|
package com.sinodynamic.hkgta.filter;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Map;
import java.util.Vector;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.io.IOUtils;
public class ResettableStreamHttpServletRequest extends HttpServletRequestWrapper
{
private byte[] rawData;
private String uri;
private HttpServletRequest request;
private ResettableServletInputStream servletStream;
private Map<String, String[]> params;
public ResettableStreamHttpServletRequest(HttpServletRequest request)
{
super(request);
this.request = request;
this.servletStream = new ResettableServletInputStream();
}
@Override
public String getParameter(String name) {
String result = "";
Object v = params.get(name);
if (v == null) {
result = null;
} else if (v instanceof String[]) {
String[] strArr = (String[]) v;
if (strArr.length > 0) {
result = strArr[0];
} else {
result = null;
}
} else if (v instanceof String) {
result = (String) v;
} else {
result = v.toString();
}
return result;
}
@Override
public Map<String, String[]> getParameterMap() {
return params;
}
public void setParameterMap(Map<String, String[]> newParams)
{
this.params = newParams;
}
@Override
public Enumeration getParameterNames() {
return new Vector(params.keySet()).elements();
}
@Override
public String[] getParameterValues(String name) {
String[] result = null;
Object v = params.get(name);
if (v == null) {
result = null;
} else if (v instanceof String[]) {
result = (String[]) v;
} else if (v instanceof String) {
result = new String[] { (String) v };
} else {
result = new String[] { v.toString() };
}
return result;
}
public void resetInputStream()
{
servletStream.stream = new ByteArrayInputStream(rawData);
}
public void resetInputStream(byte[] newData)
{
servletStream.stream = new ByteArrayInputStream(newData);
}
@Override
public ServletInputStream getInputStream() throws IOException
{
if (rawData == null)
{
rawData = IOUtils.toByteArray(this.request.getReader());
servletStream.stream = new ByteArrayInputStream(rawData);
}
return servletStream;
}
@Override
public String getRequestURI() {
return uri;
}
public void setRequestURI(String uri)
{
this.uri = uri;
}
@Override
public BufferedReader getReader() throws IOException
{
if (rawData == null)
{
rawData = IOUtils.toByteArray(this.request.getReader());
servletStream.stream = new ByteArrayInputStream(rawData);
}
return new BufferedReader(new InputStreamReader(servletStream));
}
private class ResettableServletInputStream extends ServletInputStream
{
private InputStream stream;
@Override
public int read() throws IOException
{
return stream.read();
}
}
} |
package com.javarush.task.task06.task0611;
/*
Класс StringHelper
*/
public class StringHelper {
public static String multiply(String s) {
String result = "";
//напишите тут ваш код
for (int i = 0; i <5; i++) {
result += s;
}
return result;
}
public static String multiply(String s, int count) {
String result = "";
//напишите тут ваш код
for (int i = 0; i < count; i++) {
result += s;
}
return result;
}
public static void main(String[] args) {
//System.out.println(multiply("slovo", 4));
int[] list = {5, 6, 7, 8, 1, 2, 5, -7, -9, 2, 0};
int min = list[0];
for (int i = 1; i < list.length; i++)
{
if (list[i] < min)
min = list[i];
}
System.out.println ("Min is " + min);
}
}
|
package com.isteel.myfaceit.data;
import android.content.Context;
import com.isteel.myfaceit.data.local.datebase.DbHelper;
import com.isteel.myfaceit.data.local.prefs.PreferencesHelper;
import com.isteel.myfaceit.data.model.ResponseGame;
import com.isteel.myfaceit.data.model.ResponseMatch;
import com.isteel.myfaceit.data.model.ResponsePlayer;
import com.isteel.myfaceit.data.model.db.PlayerByNickDB;
import com.isteel.myfaceit.data.remote.ApiHeader;
import com.isteel.myfaceit.data.remote.ApiHelper;
import java.util.List;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.Single;
public class AppDataManager implements DataManager{
private final ApiHelper mApiHelper;
private final Context mContext;
private final PreferencesHelper mPreferencesHelper;
private final DbHelper mDbHelper;
@Inject
public AppDataManager(ApiHelper mApiHelper,DbHelper dbHelper, Context mContext, PreferencesHelper mPreferencesHelper) {
this.mApiHelper = mApiHelper;
this.mDbHelper = dbHelper;
this.mContext = mContext;
this.mPreferencesHelper = mPreferencesHelper;
}
@Override
public Single<ResponsePlayer> getPlayerByNick(String query, String game) {
return mApiHelper.getPlayerByNick(query, game);
}
@Override
public Single<ResponseGame> getGames() {
return mApiHelper.getGames();
}
@Override
public Single<ResponseMatch> getRecentMatches(String id) {
return mApiHelper.getRecentMatches(id);
}
@Override
public Single<ResponseMatch> getRecentMatchesStats(String id) {
return mApiHelper.getRecentMatchesStats(id);
}
@Override
public Single<ResponseGame.Csgo> getStats(String player_id, String game) {
return mApiHelper.getStats(player_id, game);
}
@Override
public Single<ResponsePlayer.Player> getPlayerProfile(String id) {
return mApiHelper.getPlayerProfile(id);
}
@Override
public Single<ResponsePlayer> getTop(String game, String region) {
return mApiHelper.getTop(game,region);
}
@Override
public ApiHeader getApiHeader() {
return mApiHelper.getApiHeader();
}
@Override
public String getGame() {
return mPreferencesHelper.getGame();
}
@Override
public void setGame(String game) {
mPreferencesHelper.setGame(game);
}
@Override
public Integer getRegion() {
return mPreferencesHelper.getRegion();
}
@Override
public void setRegion(Integer region) {
mPreferencesHelper.setRegion(region);
}
@Override
public Observable<List<PlayerByNickDB>> getAllPlayers() {
return mDbHelper.getAllPlayers();
}
@Override
public Observable<Boolean> insertPlayer(PlayerByNickDB playerByNickDB) {
return mDbHelper.insertPlayer(playerByNickDB);
}
@Override
public Observable<Boolean> deletePlayer(PlayerByNickDB playerByNickDB) {
return mDbHelper.deletePlayer(playerByNickDB);
}
}
|
// **********************************************************
// 1. 제 목: 진도/목차 리스트Data
// 2. 프로그램명: EduListData.java
// 3. 개 요:
// 4. 환 경: JDK 1.3
// 5. 버 젼: 0.1
// 6. 작 성: LeeSuMin 2003. 08. 26
// 7. 수 정:
//
// **********************************************************
package com.ziaan.beta;
public class BetaEduListData {
private String recordType ; // DataType('STEP':진도,'EXAM':평가)
private String subj ;
private String year ;
private String subjseq ;
private String userid ;
private String lesson ;
private String sdesc ;
private String module ;
private String modulenm ;
private String isbranch ;
private String oid ;
private String oidnm ;
private String parameterstring ;
private String lessonstatus ;
private String prerequisites ;
private String exit ;
private String entry ;
private String type ;
private String credit ;
private String session_time ;
private String total_time ;
private String lesson_mode ;
private String first_edu ; // 진도: 최초학습시작일시, 평가:평가시작일시
private String first_end ; // 진도: 최초학습종료일시, 평가:평가종료일시
private String lessonstatusbest;
private String ldate ;
private String starting ;
// private String isbranched ;
private int score_raw = 0;
private int masteryscore = 0;
private int sequence = 0;
private int lesson_count = 0;
private int cntReport = 0; // 과제수
private int cntMyReport = 0; // 제출과제수
private int cntAct = 0; // 액티비티수
private int cntMyAct = 0; // 제출액티비티수
private String isEducated = "N"; // 학습여부
private int [] scoreExam ; // 평가점수 Array
private int [] scoreReport ; // Report점수 Array
private int [] scoreAct ; // Activity점수 Array
private int [] branchs ; // 분기 Array
private String [] branchnm ; // 분기명 Array
private String ptype ; // 평가일경우 평가타입
private double score = 0 ; // 평가일경우 점수
private int rowspan = 1 ;
private int rowspan_lesson = 1 ; // Rowspan (Lesson)
public BetaEduListData() { };
/**
* @return
*/
public String[] getBranchnm() {
return branchnm;
}
/**
* @return
*/
public int[] getBranchs() {
return branchs;
}
/**
* @return
*/
public int getCntAct() {
return cntAct;
}
/**
* @return
*/
public int getCntMyAct() {
return cntMyAct;
}
/**
* @return
*/
public int getCntMyReport() {
return cntMyReport;
}
/**
* @return
*/
public int getCntReport() {
return cntReport;
}
/**
* @return
*/
public String getCredit() {
return credit;
}
/**
* @return
*/
public String getEntry() {
return entry;
}
/**
* @return
*/
public String getExit() {
return exit;
}
/**
* @return
*/
public String getFirst_edu() {
return first_edu;
}
/**
* @return
*/
public String getFirst_end() {
return first_end;
}
/**
* @return
*/
public String getIsEducated() {
return isEducated;
}
/**
* @return
*/
public String getLdate() {
return ldate;
}
/**
* @return
*/
public String getLesson() {
return lesson;
}
/**
* @return
*/
public String getStarting() {
return starting;
}
/**
* @return
*/
public int getLesson_count() {
return lesson_count;
}
/**
* @return
*/
public String getLesson_mode() {
return lesson_mode;
}
/**
* @return
*/
public String getLessonstatus() {
return lessonstatus;
}
/**
* @return
*/
public String getLessonstatusbest() {
return lessonstatusbest;
}
/**
* @return
*/
public int getMasteryscore() {
return masteryscore;
}
/**
* @return
*/
public String getOid() {
return oid;
}
/**
* @return
*/
public String getParameterstring() {
return parameterstring;
}
/**
* @return
*/
public String getPrerequisites() {
return prerequisites;
}
/**
* @return
*/
public int getScore_raw() {
return score_raw;
}
/**
* @return
*/
public int[] getScoreAct() {
return scoreAct;
}
/**
* @return
*/
public int[] getScoreExam() {
return scoreExam;
}
/**
* @return
*/
public int[] getScoreReport() {
return scoreReport;
}
/**
* @return
*/
public int getSequence() {
return sequence;
}
/**
* @return
*/
public String getSession_time() {
return session_time;
}
/**
* @return
*/
public String getSubj() {
return subj;
}
/**
* @return
*/
public String getSubjseq() {
return subjseq;
}
/**
* @return
*/
public String getTotal_time() {
return total_time;
}
/**
* @return
*/
public String getType() {
return type;
}
/**
* @return
*/
public String getUserid() {
return userid;
}
/**
* @return
*/
public String getYear() {
return year;
}
/**
* @param strings
*/
public void setBranchnm(String[] strings) {
branchnm = strings;
}
/**
* @param is
*/
public void setBranchs(int[] is) {
branchs = is;
}
/**
* @param i
*/
public void setCntAct(int i) {
cntAct = i;
}
/**
* @param i
*/
/**
* @param i
*/
public void setCntMyAct(int i) {
cntMyAct = i;
}
/**
* @param i
*/
public void setCntMyReport(int i) {
cntMyReport = i;
}
/**
* @param i
*/
public void setCntReport(int i) {
cntReport = i;
}
/**
* @param string
*/
public void setCredit(String string) {
credit = string;
}
/**
* @param string
*/
public void setEntry(String string) {
entry = string;
}
/**
* @param string
*/
public void setExit(String string) {
exit = string;
}
/**
* @param string
*/
public void setFirst_edu(String string) {
first_edu = string;
}
/**
* @param string
*/
public void setFirst_end(String string) {
first_end = string;
}
/**
* @param string
*/
public void setIsEducated(String string) {
isEducated = string;
}
/**
* @param string
*/
public void setLdate(String string) {
ldate = string;
}
/**
* @param string
*/
public void setLesson(String string) {
lesson = string;
}
/**
* @param i
*/
public void setLesson_count(int i) {
lesson_count = i;
}
/**
* @param string
*/
public void setLesson_mode(String string) {
lesson_mode = string;
}
/**
* @param string
*/
public void setLessonstatus(String string) {
lessonstatus = string;
}
/**
* @param string
*/
public void setLessonstatusbest(String string) {
lessonstatusbest = string;
}
/**
* @param i
*/
public void setMasteryscore(int i) {
masteryscore = i;
}
/**
* @param string
*/
public void setOid(String string) {
oid = string;
}
/**
* @param string
*/
public void setParameterstring(String string) {
parameterstring = string;
}
/**
* @param string
*/
public void setPrerequisites(String string) {
prerequisites = string;
}
/**
* @param i
*/
public void setScore_raw(int i) {
score_raw = i;
}
/**
* @param is
*/
public void setScoreAct(int[] is) {
scoreAct = is;
}
/**
* @param is
*/
public void setScoreExam(int[] is) {
scoreExam = is;
}
/**
* @param is
*/
public void setScoreReport(int[] is) {
scoreReport = is;
}
/**
* @param i
*/
public void setSequence(int i) {
sequence = i;
}
/**
* @param string
*/
public void setSession_time(String string) {
session_time = string;
}
/**
* @param string
*/
public void setSubj(String string) {
subj = string;
}
/**
* @param string
*/
public void setSubjseq(String string) {
subjseq = string;
}
/**
* @param string
*/
public void setTotal_time(String string) {
total_time = string;
}
/**
* @param string
*/
public void setType(String string) {
type = string;
}
/**
* @param string
*/
public void setUserid(String string) {
userid = string;
}
/**
* @param string
*/
public void setYear(String string) {
year = string;
}
/**
* @return
*/
public String getIsbranch() {
return isbranch;
}
/**
* @return
*/
public String getModule() {
return module;
}
/**
* @return
*/
public String getModulenm() {
return modulenm;
}
/**
* @return
*/
public String getSdesc() {
return sdesc;
}
/**
* @param string
*/
public void setIsbranch(String string) {
isbranch = string;
}
/**
* @param string
*/
public void setModule(String string) {
module = string;
}
/**
* @param string
*/
public void setModulenm(String string) {
modulenm = string;
}
/**
* @param string
*/
public void setSdesc(String string) {
sdesc = string;
}
/**
* @return
*/
public String getRecordType() {
return recordType;
}
/**
* @return
*/
public double getScore() {
return score;
}
/**
* @param string
*/
public void setRecordType(String string) {
recordType = string;
}
/**
* @param d
*/
public void setScore(double d) {
score = d;
}
/**
* @return
*/
public String getPtype() {
return ptype;
}
/**
* @param string
*/
public void setPtype(String string) {
ptype = string;
}
/**
* @param string
*/
public void setOidnm(String string) {
oidnm = string;
}
/**
* @param string
*/
public void setStarting(String string) {
starting = string;
}
/**
* @return
*/
public String getOidnm() {
return oidnm;
}
/**
* @return
*/
public int getRowspan() {
return rowspan;
}
/**
* @param i
*/
public void setRowspan(int i) {
rowspan = i;
}
/**
* @return
*/
public int getRowspan_lesson() {
return rowspan_lesson;
}
/**
* @param i
*/
public void setRowspan_lesson(int i) {
rowspan_lesson = i;
}
}
|
package be.tarsos.dsp.example;
public class AutoBand {
private long prevTime = System.currentTimeMillis();
private long currTime = System.currentTimeMillis();
private long waitTime = 1500;
private float minValueSeen = Float.MAX_VALUE;
private float maxValueSeen = Float.MIN_VALUE;
private float lastMinSent = 0;
private float lastMaxSent = 0;
private float lowerSpacing = -0.05f;
private float upperSpacing = 0.1f;
private OnUpdateBands listener;
public AutoBand(OnUpdateBands listener) {
this.listener = listener;
}
public int getLowerSpacing() {
return Math.round(lowerSpacing * 100);
}
public void setLowerSpacing(int spacing) {
this.lowerSpacing = (float)spacing / 100;
}
public int getUpperSpacing() {
return Math.round(upperSpacing * 100);
}
public void setUpperSpacing(int spacing) {
this.upperSpacing = (float)spacing / 100;
}
public void newVolume(float volume){
if(volume < minValueSeen){
minValueSeen = volume;
}
if(volume > maxValueSeen){
maxValueSeen = volume;
}
currTime = System.currentTimeMillis();
if(currTime - prevTime > waitTime){
lastMinSent = (float) ((lastMinSent * 0.5) + (minValueSeen * 0.5));
lastMaxSent = (float) ((lastMaxSent * 0.5) + (maxValueSeen * 0.5));
listener.updateBands(Math.min(1, lastMaxSent + upperSpacing), Math.max(0, lastMinSent - lowerSpacing), lowerSpacing, upperSpacing);
reset();
}
}
public void reset(){
minValueSeen = Float.MAX_VALUE;
maxValueSeen = Float.MIN_VALUE;
prevTime = System.currentTimeMillis();
}
public interface OnUpdateBands{
void updateBands(float max, float min, float lowerSpacing, float upperSpacing);
}
}
|
package com.knightly.cor;
/**
* 销售,可以批准5%以内的折扣
* Created by knightly on 2018/2/19.
*/
public class Sales extends PriceHandler {
@Override
public void processDiscount(float discount) {
if (discount <= 0.05) {
System.out.format("%s批准了这口:%.2f%n", this.getClass().getName(), discount);
} else {
//交给上级处理
successor.processDiscount(discount);
}
}
}
|
package com.sparshik.yogicapple.ui.groups;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.sparshik.yogicapple.R;
import com.sparshik.yogicapple.model.SupportGroup;
import com.sparshik.yogicapple.model.UserChatProfile;
import com.sparshik.yogicapple.ui.BaseActivity;
import com.sparshik.yogicapple.ui.viewholders.GroupViewHolder;
import com.sparshik.yogicapple.utils.Constants;
public class GroupsActivity extends BaseActivity {
private static final String LOG_TAG = GroupsActivity.class.getSimpleName();
private GroupAdapter mGroupAdapter;
private RecyclerView mRecyclerViewUserGroups;
private DatabaseReference mChatProfileRef, userGroupsRef;
private ValueEventListener mChatProfileRefValueListener;
private TextView emptyTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_groups);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(GroupsActivity.this, JoinGroupActivity.class));
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Log.d(LOG_TAG, mEncodedEmail + "outside");
mChatProfileRef = FirebaseDatabase.getInstance().getReferenceFromUrl(Constants.FIREBASE_URL_GROUP_CHAT_PROFILES).child(mEncodedEmail);
mChatProfileRefValueListener = mChatProfileRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserChatProfile userChatProfile = dataSnapshot.getValue(UserChatProfile.class);
if (userChatProfile != null) {
String userChatName = userChatProfile.getNickName();
String userProfileUrl = userChatProfile.getChatProfilePicUrl();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(GroupsActivity.this);
SharedPreferences.Editor spe = preferences.edit();
spe.putString(Constants.KEY_CHAT_NICK_NAME, userChatName).apply();
spe.putString(Constants.KEY_CHAT_PROFILE_IMAGE_URL, userProfileUrl).apply();
Log.d(LOG_TAG, mEncodedEmail + userProfileUrl + userChatName);
} else {
Intent intentCreate = new Intent(GroupsActivity.this, CreateChatProfileActivity.class);
GroupsActivity.this.startActivity(intentCreate);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String userChatName = sharedPreferences.getString(Constants.KEY_CHAT_NICK_NAME, "navenduDefault");
String userProfileUrl = sharedPreferences.getString(Constants.KEY_CHAT_PROFILE_IMAGE_URL, "https://firebasestorage.googleapis.com/v0/b/yogicapple-b288e.appspot.com/o/supportGroups%2Fnavendu%2Cagarwal%40gmail%2Ccom_iconImage.jpg?alt=media&token=5cf87141-8d7a-42f7-b99b-c8c35323778f");
populateAdapter(userChatName, userProfileUrl);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mGroupAdapter != null) {
mGroupAdapter.cleanup();
}
mChatProfileRef.removeEventListener(mChatProfileRefValueListener);
}
public void populateAdapter(String userChatName, String userProfileUrl) {
userGroupsRef = FirebaseDatabase.getInstance()
.getReferenceFromUrl(Constants.FIREBASE_URL_USER_SUPPORT_GROUPS).child(mEncodedEmail);
emptyTextView = (TextView) findViewById(R.id.text_empty_groups);
mRecyclerViewUserGroups = (RecyclerView) findViewById(R.id.recycler_view_user_groups);
mRecyclerViewUserGroups.setHasFixedSize(true);
mRecyclerViewUserGroups.setLayoutManager(new LinearLayoutManager(GroupsActivity.this));
mGroupAdapter = new GroupAdapter(GroupsActivity.this, SupportGroup.class, R.layout.single_group_item, GroupViewHolder.class
, userGroupsRef, mEncodedEmail, userChatName, userProfileUrl);
mRecyclerViewUserGroups.setAdapter(mGroupAdapter);
userGroupsRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChildren()) {
emptyTextView.setVisibility(View.VISIBLE);
mRecyclerViewUserGroups.setVisibility(View.GONE);
} else {
mRecyclerViewUserGroups.setVisibility(View.VISIBLE);
emptyTextView.setVisibility(View.GONE);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
// RecyclerView.AdapterDataObserver mObserver = new RecyclerView.AdapterDataObserver(){
//
// @Override
// public void onItemRangeChanged(int positionStart, int itemCount) {
// super.onItemRangeChanged(positionStart, itemCount);
// Log.d(LOG_TAG,""+itemCount);
// }
//
//
// };
//
// mGroupAdapter.registerAdapterDataObserver(mObserver);
Log.d(LOG_TAG, mEncodedEmail + userProfileUrl + userChatName + "inside populate");
}
}
|
package com.beike.common.entity.trx;
import java.util.Date;
import com.beike.common.enums.trx.RefundHandleType;
import com.beike.common.enums.trx.RefundSourceType;
import com.beike.common.enums.trx.RefundStatus;
/**
* @Title: RefundRecord.java
* @Package com.beike.common.entity.trx
* @Description: 退款汇总记录
* @date May 14, 2011 2:35:20 PM
* @author wh.cheng
* @version v1.0
*/
public class RefundRecord {
private Long id;
/**
* 原TrxOrderID
*/
private Long trxOrderId;
/**
* 原用户ID
*/
private Long userId;
/**
* 订单商品明细Id
*/
private Long trxGoodsId;
/**
* 退款操作员
*/
private String operator="";
/**
* 退款处理状态
*/
private RefundStatus refundStatus;
/**
* 退款处理类型。人工还是自动
*/
private RefundHandleType handleType;
/**
* 退款来源
*/
private RefundSourceType refundSourceType;
/**
* 原下单时间
*/
private Date orderDate;
/**
* 原支付时间
*/
private Date confirmDate;
/**
* 退款请求时间
*/
private Date createDate;
/**
* 原商品名称
*/
private String productName;
/**
* 原订单金额
*/
private double orderAmount;
/**
* 原订单商品明细订单金额
*/
private double trxGoodsAmount;
/**
* 退款操作备注
*/
private String description="";
/**
* 乐观锁版本号
*/
private Long version = 0L;
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public RefundRecord(){
}
public RefundRecord(Long trxOrderId,Long userId,Long trxGoodsId,Date orderDate,Date confirmDate,Date createDate,String productName,double orderAmount,double trxGoodsAmount){
this.trxOrderId=trxOrderId;
this.userId=userId;
this.trxGoodsId=trxGoodsId;
this.orderDate=orderDate;
this.confirmDate=confirmDate;
this.createDate=createDate;
this.productName=productName;
this.orderAmount=orderAmount;
this.trxGoodsAmount=trxGoodsAmount;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTrxOrderId() {
return trxOrderId;
}
public void setTrxOrderId(Long trxOrderId) {
this.trxOrderId = trxOrderId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getTrxGoodsId() {
return trxGoodsId;
}
public void setTrxGoodsId(Long trxGoodsId) {
this.trxGoodsId = trxGoodsId;
}
public RefundStatus getRefundStatus() {
return refundStatus;
}
public void setRefundStatus(RefundStatus refundStatus) {
this.refundStatus = refundStatus;
}
public RefundHandleType getHandleType() {
return handleType;
}
public void setHandleType(RefundHandleType handleType) {
this.handleType = handleType;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public Date getConfirmDate() {
return confirmDate;
}
public void setConfirmDate(Date confirmDate) {
this.confirmDate = confirmDate;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getOrderAmount() {
return orderAmount;
}
public void setOrderAmount(double orderAmount) {
this.orderAmount = orderAmount;
}
public double getTrxGoodsAmount() {
return trxGoodsAmount;
}
public void setTrxGoodsAmount(double trxGoodsAmount) {
this.trxGoodsAmount = trxGoodsAmount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public RefundSourceType getRefundSourceType() {
return refundSourceType;
}
public void setRefundSourceType(RefundSourceType refundSourceType) {
this.refundSourceType = refundSourceType;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
}
|
/*
* 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 object;
import java.util.Vector;
/**
*
* @author PhiLong
*/
public class Publisher {
private String PublisherID;
private String PublisherName;
public Publisher(String PublisherID, String PublisherName) {
this.PublisherID = PublisherID;
this.PublisherName = PublisherName;
}
public String getPublisherID() {
return PublisherID;
}
public void setPublisherID(String PublisherID) {
this.PublisherID = PublisherID;
}
public String getPublisherName() {
return PublisherName;
}
public void setPublisherName(String PublisherName) {
this.PublisherName = PublisherName;
}
public Vector toVector(){
Vector v = new Vector();
v.addElement(this.PublisherID);
v.addElement(this.PublisherName);
return v;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.