text
stringlengths
10
2.72M
package com.pisen.ott.launcher.movie; public class QiyiCache { }
import processing.core.PApplet; import com.hookedup.processing.ExtraWindow; public class MyExtraWindow extends ExtraWindow { public MyExtraWindow(PApplet theApplet, String theName, int theWidth, int theHeight) { super( theApplet, theName, theWidth, theHeight); // TODO Auto-generated constructor stub } float counter = 0f; int randomCol = 0; int randomColBlock = 0xffffff; @Override public void setup() { frameRate(10); super.setup(); } @Override public void draw() { // fill(random(255, 255, 0); background(randomCol); fill(randomColBlock); noStroke(); int size = (int) map(counter, 0.0f, 45.0f, 0.0f, 15.0f); rect(0, 0, size, height-1); super.draw(); counter++; if (counter==45){ counter = 0; randomCol = color(random(255), random(255), random(255)); randomColBlock = color(random(255), random(255), random(255)); } } public void logIt(String s){ println(s); } }
/* * 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.http.codec.json; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.logging.Log; import org.springframework.core.GenericTypeResolver; import org.springframework.core.MethodParameter; import org.springframework.core.ResolvableType; import org.springframework.core.codec.Hints; import org.springframework.http.HttpLogging; import org.springframework.http.MediaType; import org.springframework.http.ProblemDetail; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.MimeType; import org.springframework.util.ObjectUtils; /** * Base class providing support methods for Jackson 2.x encoding and decoding. * * @author Sebastien Deleuze * @author Rossen Stoyanchev * @since 5.0 */ public abstract class Jackson2CodecSupport { /** * The key for the hint to specify a "JSON View" for encoding or decoding * with the value expected to be a {@link Class}. * @see <a href="https://www.baeldung.com/jackson-json-view-annotation">Jackson JSON Views</a> */ public static final String JSON_VIEW_HINT = Jackson2CodecSupport.class.getName() + ".jsonView"; /** * The key for the hint to access the actual ResolvableType passed into * {@link org.springframework.http.codec.HttpMessageReader#read(ResolvableType, ResolvableType, ServerHttpRequest, ServerHttpResponse, Map)} * (server-side only). Currently set when the method argument has generics because * in case of reactive types, use of {@code ResolvableType.getGeneric()} means no * MethodParameter source and no knowledge of the containing class. */ static final String ACTUAL_TYPE_HINT = Jackson2CodecSupport.class.getName() + ".actualType"; private static final String JSON_VIEW_HINT_ERROR = "@JsonView only supported for write hints with exactly 1 class argument: "; private static final List<MimeType> defaultMimeTypes = List.of( MediaType.APPLICATION_JSON, new MediaType("application", "*+json"), MediaType.APPLICATION_NDJSON); protected final Log logger = HttpLogging.forLogName(getClass()); private ObjectMapper defaultObjectMapper; @Nullable private Map<Class<?>, Map<MimeType, ObjectMapper>> objectMapperRegistrations; private final List<MimeType> mimeTypes; /** * Constructor with a Jackson {@link ObjectMapper} to use. */ protected Jackson2CodecSupport(ObjectMapper objectMapper, MimeType... mimeTypes) { Assert.notNull(objectMapper, "ObjectMapper must not be null"); this.defaultObjectMapper = objectMapper; this.mimeTypes = (!ObjectUtils.isEmpty(mimeTypes) ? List.of(mimeTypes) : defaultMimeTypes); } /** * Configure the default ObjectMapper instance to use. * @param objectMapper the ObjectMapper instance * @since 5.3.4 */ public void setObjectMapper(ObjectMapper objectMapper) { Assert.notNull(objectMapper, "ObjectMapper must not be null"); this.defaultObjectMapper = objectMapper; } /** * Return the {@link #setObjectMapper configured} default ObjectMapper. */ public ObjectMapper getObjectMapper() { return this.defaultObjectMapper; } /** * Configure the {@link ObjectMapper} instances to use for the given * {@link Class}. This is useful when you want to deviate from the * {@link #getObjectMapper() default} ObjectMapper or have the * {@code ObjectMapper} vary by {@code MediaType}. * <p><strong>Note:</strong> Use of this method effectively turns off use of * the default {@link #getObjectMapper() ObjectMapper} and supported * {@link #getMimeTypes() MimeTypes} for the given class. Therefore it is * important for the mappings configured here to * {@link MediaType#includes(MediaType) include} every MediaType that must * be supported for the given class. * @param clazz the type of Object to register ObjectMapper instances for * @param registrar a consumer to populate or otherwise update the * MediaType-to-ObjectMapper associations for the given Class * @since 5.3.4 */ public void registerObjectMappersForType(Class<?> clazz, Consumer<Map<MimeType, ObjectMapper>> registrar) { if (this.objectMapperRegistrations == null) { this.objectMapperRegistrations = new LinkedHashMap<>(); } Map<MimeType, ObjectMapper> registrations = this.objectMapperRegistrations.computeIfAbsent(clazz, c -> new LinkedHashMap<>()); registrar.accept(registrations); } /** * Return ObjectMapper registrations for the given class, if any. * @param clazz the class to look up for registrations for * @return a map with registered MediaType-to-ObjectMapper registrations, * or empty if in case of no registrations for the given class. * @since 5.3.4 */ @Nullable public Map<MimeType, ObjectMapper> getObjectMappersForType(Class<?> clazz) { for (Map.Entry<Class<?>, Map<MimeType, ObjectMapper>> entry : getObjectMapperRegistrations().entrySet()) { if (entry.getKey().isAssignableFrom(clazz)) { return entry.getValue(); } } return Collections.emptyMap(); } protected Map<Class<?>, Map<MimeType, ObjectMapper>> getObjectMapperRegistrations() { return (this.objectMapperRegistrations != null ? this.objectMapperRegistrations : Collections.emptyMap()); } /** * Subclasses should expose this as "decodable" or "encodable" mime types. */ protected List<MimeType> getMimeTypes() { return this.mimeTypes; } protected List<MimeType> getMimeTypes(ResolvableType elementType) { Class<?> elementClass = elementType.toClass(); List<MimeType> result = null; for (Map.Entry<Class<?>, Map<MimeType, ObjectMapper>> entry : getObjectMapperRegistrations().entrySet()) { if (entry.getKey().isAssignableFrom(elementClass)) { result = (result != null ? result : new ArrayList<>(entry.getValue().size())); result.addAll(entry.getValue().keySet()); } } if (!CollectionUtils.isEmpty(result)) { return result; } return (ProblemDetail.class.isAssignableFrom(elementClass) ? getMediaTypesForProblemDetail() : getMimeTypes()); } /** * Return the supported media type(s) for {@link ProblemDetail}. * By default, an empty list, unless overridden in subclasses. * @since 6.0.5 */ protected List<MimeType> getMediaTypesForProblemDetail() { return Collections.emptyList(); } protected boolean supportsMimeType(@Nullable MimeType mimeType) { if (mimeType == null) { return true; } for (MimeType supportedMimeType : this.mimeTypes) { if (supportedMimeType.isCompatibleWith(mimeType)) { return true; } } return false; } /** * Determine whether to log the given exception coming from a * {@link ObjectMapper#canDeserialize} / {@link ObjectMapper#canSerialize} check. * @param type the class that Jackson tested for (de-)serializability * @param cause the Jackson-thrown exception to evaluate * (typically a {@link JsonMappingException}) * @since 5.3.1 */ protected void logWarningIfNecessary(Type type, @Nullable Throwable cause) { if (cause == null) { return; } if (logger.isDebugEnabled()) { String msg = "Failed to evaluate Jackson " + (type instanceof JavaType ? "de" : "") + "serialization for type [" + type + "]"; logger.debug(msg, cause); } } protected JavaType getJavaType(Type type, @Nullable Class<?> contextClass) { return this.defaultObjectMapper.constructType(GenericTypeResolver.resolveType(type, contextClass)); } protected Map<String, Object> getHints(ResolvableType resolvableType) { MethodParameter param = getParameter(resolvableType); if (param != null) { Map<String, Object> hints = null; if (resolvableType.hasGenerics()) { hints = new HashMap<>(2); hints.put(ACTUAL_TYPE_HINT, resolvableType); } JsonView annotation = getAnnotation(param, JsonView.class); if (annotation != null) { Class<?>[] classes = annotation.value(); Assert.isTrue(classes.length == 1, () -> JSON_VIEW_HINT_ERROR + param); hints = (hints != null ? hints : new HashMap<>(1)); hints.put(JSON_VIEW_HINT, classes[0]); } if (hints != null) { return hints; } } return Hints.none(); } @Nullable protected MethodParameter getParameter(ResolvableType type) { return (type.getSource() instanceof MethodParameter methodParameter ? methodParameter : null); } @Nullable protected abstract <A extends Annotation> A getAnnotation(MethodParameter parameter, Class<A> annotType); /** * Select an ObjectMapper to use, either the main ObjectMapper or another * if the handling for the given Class has been customized through * {@link #registerObjectMappersForType(Class, Consumer)}. * @since 5.3.4 */ @Nullable protected ObjectMapper selectObjectMapper(ResolvableType targetType, @Nullable MimeType targetMimeType) { if (targetMimeType == null || CollectionUtils.isEmpty(this.objectMapperRegistrations)) { return this.defaultObjectMapper; } Class<?> targetClass = targetType.toClass(); for (Map.Entry<Class<?>, Map<MimeType, ObjectMapper>> typeEntry : getObjectMapperRegistrations().entrySet()) { if (typeEntry.getKey().isAssignableFrom(targetClass)) { for (Map.Entry<MimeType, ObjectMapper> objectMapperEntry : typeEntry.getValue().entrySet()) { if (objectMapperEntry.getKey().includes(targetMimeType)) { return objectMapperEntry.getValue(); } } // No matching registrations return null; } } // No registrations return this.defaultObjectMapper; } }
package com.codingchili.instance.model.stats; import java.util.HashMap; /** * @author Robin Duda */ public class Modifiers extends HashMap<Attribute, Float> { public Modifiers add(Attribute attribute, Float value) { Float current = getOrDefault(attribute, 1.0f); put(attribute, current + value); return this; } public Modifiers set(Attribute attribute, Float value) { put(attribute, value); return this; } public Float get(Attribute attribute) { return getOrDefault(attribute, 1.0f); } public Stats apply(Stats stats) { for (Attribute attribute : keySet()) { if (stats.has(attribute)) { stats.set(attribute, Math.round(stats.get(attribute) * get(attribute))); } } return stats; } }
package de.csiebmanns.graphqlexample.fetchers; import de.csiebmanns.graphqlexample.data.Author; import de.csiebmanns.graphqlexample.data.Data; import de.csiebmanns.graphqlexample.data.HasAuthorName; import graphql.schema.DataFetcher; import graphql.schema.DataFetchingEnvironment; public class AuthorFetcher implements DataFetcher<Author> { private Data data; public AuthorFetcher(Data data) { this.data = data; } @Override public Author get(DataFetchingEnvironment environment) { HasAuthorName object = environment.getSource(); String authorName = object.getAuthorName(); return this.data.getAuthor(authorName); } }
/* * 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 com.ok.sudoku.background; import javax.swing.ImageIcon; /** * * @author okan */ public class BackgroundSet implements Command { private BackgroundImage Item; public BackgroundSet( BackgroundImage Item) { this.Item=Item; } public ImageIcon change(String value) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. return Item.GetBackground( value); } }
package protocol; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; /** * Reference https://github.com/haochending/Go-Back-N/ */ public class GBNReceiver { private InetAddress hostAddress; private int senderPort; private static FileOutputStream output; private static DatagramSocket receiverSocket; private byte[] window = new byte[1024]; private int nextSequenceNumber = 0; private int endOfFile = 0; public GBNReceiver(InetAddress address, Integer senderPort, Integer receiverPort, File writtenFile) throws IOException { hostAddress = address; this.senderPort = senderPort; receiverSocket = new DatagramSocket(receiverPort); output = new FileOutputStream(writtenFile); } public void start() throws IOException { GBNPacket packet; DatagramPacket receiverPacket; int type; while (endOfFile != 1) { receiverPacket = new DatagramPacket(window, window.length); try { receiverSocket.receive(receiverPacket); } catch (IOException e) { System.err.println("Receiver Socket I/O exception!!!"); } packet = GBNPacket.parseUDPData(window); type = packet.getType(); if (type == GBNPacket.DATA_PACKET) { if (packet.getSequenceNumber() == nextSequenceNumber) { writeToFile(packet); System.out.print("Debug: ack"); sendACK(nextSequenceNumber % GBNPacket.SEQUENCE_MOD); nextSequenceNumber += 1; return; } System.out.print("Debug: resend"); if (nextSequenceNumber != 0) { sendACK(nextSequenceNumber % GBNPacket.SEQUENCE_MOD - 1); } return; } else if (type == GBNPacket.END_OF_TRANSMISSION_PACKET) { if (packet.getLength() != 0) { System.err.println("Invalid packet length for EOT received."); return; } // if it's the expected packet means it's the end of file // send EOT to the sender and close the file output stream // update endOfFile to break the while loop if (packet.getSequenceNumber() == nextSequenceNumber % GBNPacket.SEQUENCE_MOD) { endOfFile = 1; sendEndOfTransmission(packet.getSequenceNumber()); return; } // if it's not just send the ACK packet with the sequenceNumber // of the packet before the expected one if (nextSequenceNumber != 0) { sendACK(nextSequenceNumber % GBNPacket.SEQUENCE_MOD - 1); } } else if (type == GBNPacket.ACK_PACKET) { System.err.println("Invalid packet type received!!!"); return; } } receiverSocket.close(); } private void sendEndOfTransmission(int sequenceNumber) throws IOException { GBNPacket eot = GBNPacket.createEndOfTransmission(sequenceNumber); byte[] eotBuffer = eot.getUDPData(); DatagramPacket eotPacket = new DatagramPacket(eotBuffer, eotBuffer.length, hostAddress, senderPort); receiverSocket.send(eotPacket); System.out.println("Debug:Send EOT " + sequenceNumber); } private void sendACK(int sequenceNumber) throws IOException { GBNPacket ack = new GBNPacket(GBNPacket.DATA_PACKET, sequenceNumber, new String()); byte[] ackBuffer = ack.getUDPData(); DatagramPacket ackPacket = new DatagramPacket(ackBuffer, ackBuffer.length, hostAddress, senderPort); receiverSocket.send(ackPacket); System.out.println("Debug:Send ACK " + sequenceNumber); } private void writeToFile(GBNPacket p) { try { System.out.println("Debug:Write to file " + p.getSequenceNumber()); output.write(p.getData()); } catch (IOException e) { System.err.println("I/O exception while writing to file!!!"); } } }
package com.stagged.auth.services; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.AmazonS3EncryptionClientBuilder; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.PutObjectRequest; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.annotation.PostConstruct; import javax.mail.Multipart; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; @Service public class S3Operation { private AmazonS3 amazonS3Client; @Value("${amazonProperties.endpointUrl}") private String endpointUrl; @Value("${amazonDynamo.endpointUrl}") private String dynamoEndPoint; @Value("${amazonProperties.accessKey}") private String accessKey; @Value("${amazonProperties.secretKey}") private String secretKey; @Value("${amazonProperties.bucketName}") private String bucketName; @PostConstruct private void initializeAmazon() { BasicAWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey); this.amazonS3Client = AmazonS3Client.builder().withRegion("us-west-1") .withCredentials(new AWSStaticCredentialsProvider(credentials)) .build(); } private File convertMultiPartToFile(MultipartFile file) throws IOException { File convFile = new File(file.getOriginalFilename()); FileOutputStream fos = new FileOutputStream(convFile); fos.write(file.getBytes()); fos.close(); return convFile; } private String generateFileName(MultipartFile file) { return new Date().getTime() + "-" + file.getOriginalFilename().replace(" ","_"); } private void uploadFileToS3Bucket(String fileName, File file) { amazonS3Client.putObject(new PutObjectRequest(bucketName, fileName, file) .withCannedAcl(CannedAccessControlList.PublicRead)); } public String uploadFile(MultipartFile multipartFile) { String fileUrl = ""; try { File file = convertMultiPartToFile(multipartFile); String fileName = generateFileName(multipartFile); fileUrl = endpointUrl + "/" + bucketName + "/" + fileName; uploadFileToS3Bucket(fileName, file); file.delete(); } catch (Exception e) { e.printStackTrace(); } return fileUrl; } }
import java.util.Scanner; public class PromTicket { private String name = ""; private String gradeClass = ""; private int guestCount = 0; private String type = ""; private String amountDue = ""; private double payment = 0; public PromTicket() { Scanner keyboard = new Scanner(System.in); System.out.println("What is the students name?"); name = keyboard.nextLine(); System.out.println("What is their grade classification?"); gradeClass = keyboard.nextLine(); gradeClass = gradeClass.toLowerCase(); System.out.println("What is the number of guests for the ticket?"); guestCount = keyboard.nextInt(); System.out.println("The student is ordering a " + ticketType() + " ticket."); System.out.println("The student owes $" + ticketPrice()); System.out.println("How much is the student paying?"); payment = keyboard.nextDouble(); System.out.println("You owe the student $" + transaction() + " in change."); keyboard.close(); } public String ticketType() { if(guestCount == 1) { type = "solo"; } else if(guestCount == 2) { type = "couples"; } else if(guestCount == 3 || guestCount == 4) { type = "group"; } return type; } public String ticketPrice() { if(type.equals("solo") && gradeClass.equals("freshman")) { amountDue = "65.00"; } else if(type.equals("couples") && gradeClass.equals("freshman")) { amountDue = "98.00"; } else if(type.equals("group") && gradeClass.equals("freshman")) { amountDue = "163.00"; } else if(type.equals("solo") && gradeClass.equals("sophomore")) { amountDue = "55.00"; } else if(type.equals("couples") && gradeClass.equals("sophomore")) { amountDue = "83.00"; } else if(type.equals("group") && gradeClass.equals("sophomore")) { amountDue = "138.00"; } else if(type.equals("solo") && gradeClass.equals("junior")) { amountDue = "45.00"; } else if(type.equals("couples") && gradeClass.equals("junior")) { amountDue = "68.00"; } else if(type.equals("group") && gradeClass.equals("junior")) { amountDue = "113.00"; } else if(type.equals("solo") && gradeClass.equals("senior")) { amountDue = "40.00"; } else if(type.equals("couples") && gradeClass.equals("senior")) { amountDue = "60.00"; } else if(type.equals("group") && gradeClass.equals("senior")) { amountDue = "100.00"; } return amountDue; } public double transaction () { double price = Double.parseDouble(amountDue); double amountPaid = payment; double transaction = price - amountPaid; double changeDue = transaction * -1; return changeDue; } public String confirmation() { int count = 0; int rand = 0; String confirmation = ""; String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; while(count < 6) { rand = (int) (Math.random() * characters.length()); confirmation += characters.substring(rand, rand + 1); count ++; } System.out.println(name + " purchased a " + gradeClass + " " + ticketType() + " ticket for $" + ticketPrice() + ". the confirmation number for this sale is " + confirmation + "."); return confirmation; } }
/* * Copyright Daon. * * 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.daon.identityx.uaf; /** * Created by Daon */ public enum UAFIntentType { DISCOVER(0, "DISCOVER"), DISCOVER_RESULT(1, "DISCOVER_RESULT"), CHECK_POLICY(2, "CHECK_POLICY"), CHECK_POLICY_RESULT(3, "CHECK_POLICY_RESULT"), UAF_OPERATION(4, "UAF_OPERATION"), UAF_OPERATION_RESULT(5, "UAF_OPERATION_RESULT"), UAF_OPERATION_COMPLETION_STATUS(6, "UAF_OPERATION_COMPLETION_STATUS"); private final int VALUE; private final String DESCRIPTION; public static UAFIntentType getByValue(final String description) { for (final UAFIntentType uafIntentType : values()) { if (uafIntentType.getDescription().equals(description)) { return uafIntentType; } } throw new IllegalArgumentException("Invalid uaf intent type description: " + description); } public int getValue() { return VALUE; } public String getDescription() { return DESCRIPTION; } UAFIntentType(final int value, final String description) { this.VALUE = value; this.DESCRIPTION = description; } }
package com.zc.schedule.product.scheduleRule.controller; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.zc.schedule.common.base.BaseController; import com.zc.schedule.common.entity.ResultData; import com.zc.schedule.common.entity.ResultPage; import com.zc.schedule.common.util.DataFormat; import com.zc.schedule.common.util.SysConstant; import com.zc.schedule.product.scheduleRule.entity.CountBean; import com.zc.schedule.product.scheduleRule.entity.GroupBean; import com.zc.schedule.product.scheduleRule.service.RuleService; /** * * 排班规则控制类 * * @author Justin * @version v1.0 */ @Controller @RequestMapping("/scheduleRule") public class RuleController extends BaseController { private static Logger logger = Logger.getLogger(RuleController.class); /** * 排班规则service层 */ @Resource(name = "ruleServiceImpl") private RuleService ruleService; /** * * 初始化排班规则页面 * @return String */ @RequestMapping(value = "/index", method = RequestMethod.GET) public String initManager() { return "/schedule/scheduleRule/RuleSetting"; } /** * * 初始化排班规则数据 * @param model * @param request * @param reqParam * @return ResultPage */ @ResponseBody @RequestMapping(value="/getWorkCountInfo", method = RequestMethod.POST) public ResultPage getWorkCountInfo(ModelMap model, HttpServletRequest request, @RequestBody Map<String,Object> reqParam) { List<CountBean> list = ruleService.getWorkCountInfo(reqParam); return DataFormat.formatPageData(list) ; } /** * * 更新每日次数 * * @param request * @param countBean * @return ResultData */ @ResponseBody @RequestMapping(value="/updateCount", method = RequestMethod.POST) public ResultData updateCount(HttpServletRequest request,CountBean countBean) { //判断班次是否存在 int row = ruleService.updateCount(countBean); //日志添加 addLogSucc(request, SysConstant.SCHEDULEMGR, SysConstant.排班规则, "修改每日次数成功"); return DataFormat.formatUpd(row) ; } /** * * 初始化分组规则数据 * @param model * @param request * @param reqParam * @return ResultPage */ @ResponseBody @RequestMapping(value="/getGroupInfo", method = RequestMethod.POST) public ResultPage getGroupInfo(ModelMap model, HttpServletRequest request, @RequestBody Map<String,Object> reqParam) { List<GroupBean> list = ruleService.getGroupInfo(reqParam); return DataFormat.formatPageData(list); } /** * * 根据分组实时刷新班次 * * @param request * @param groupBean * @return ResultPage */ @ResponseBody @RequestMapping(value="/getWorkInfoByGroup", method = RequestMethod.POST) public ResultPage getWorkInfoByGroup(HttpServletRequest request, GroupBean groupBean) { List<GroupBean> list = ruleService.getWorkInfo(groupBean); return DataFormat.formatPageData(list); } /** * * 更新分组与班次的信息 * * @param request * @param groupBean * @return ResultData */ @ResponseBody @RequestMapping(value="/updateGroup", method = RequestMethod.POST) public ResultData updateGroup(HttpServletRequest request, GroupBean groupBean ) { int row = ruleService.updateGroup(groupBean); return DataFormat.formatUpd(row); } }
package org.jude.demo.companycatalog.repository; import org.jude.demo.companycatalog.model.Company; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface CompanyRepository extends CrudRepository<Company, Long> { @Override List<Company> findAll(); }
package tech.liujin.drawable.widget; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.DrawableRes; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.design.widget.TabLayout; import android.support.design.widget.TabLayout.OnTabSelectedListener; import android.support.design.widget.TabLayout.Tab; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import tech.liujin.drawable.R; /** * 用于创建TabLayout和ViewPager联动 * * @author Liujin 2018-11-03:20:05 */ public class TabItemBuilder { protected TabLayout mTabLayout; protected ViewPager mViewPager; protected ProgressColorTextView[] mTextViews; protected ProgressAlphaDrawable[] mDrawables; protected int mImageViewId; protected boolean isTabSelect; protected boolean isSetting; /** * 当前滚动状态 */ protected int mState = ViewPager.SCROLL_STATE_IDLE; public TabItemBuilder ( TabLayout tabLayout, ViewPager viewPager ) { this( tabLayout, viewPager, R.layout.tab_layout_progress_item, R.id.tabText, R.id.tabImage ); } public TabItemBuilder ( TabLayout tabLayout, ViewPager viewPager, @LayoutRes int itemLayout, @IdRes int textId, @IdRes int imageId ) { mTabLayout = tabLayout; mViewPager = viewPager; mImageViewId = imageId; mTabLayout.setupWithViewPager( mViewPager ); Context context = tabLayout.getContext(); LayoutInflater inflater = LayoutInflater.from( context ); int tabCount = mTabLayout.getTabCount(); mTextViews = new ProgressColorTextView[ tabCount ]; mDrawables = new ProgressAlphaDrawable[ tabCount ]; for( int i = 0; i < tabCount; i++ ) { TabLayout.Tab tab = tabLayout.getTabAt( i ); View view = inflater.inflate( itemLayout, null ); tab.setCustomView( view ); mTextViews[ i ] = view.findViewById( textId ); } } public TabItemBuilder setTitles ( String... titles ) { for( int i = 0; i < mTextViews.length; i++ ) { mTextViews[ i ].setText( titles[ i ] ); } return this; } public TabItemBuilder setTextColor ( @ColorInt int colorNormal, @ColorInt int colorSelect ) { for( ProgressColorTextView mTextView : mTextViews ) { mTextView.setTextColor( colorNormal, colorSelect ); } return this; } public TabItemBuilder setTextColorRes ( @ColorRes int colorNormal, @ColorRes int colorSelect ) { Context context = mTabLayout.getContext(); Resources resources = context.getResources(); int normal = resources.getColor( colorNormal ); int select = resources.getColor( colorSelect ); for( ProgressColorTextView mTextView : mTextViews ) { mTextView.setTextColor( normal, select ); } return this; } public TabItemBuilder setDrawable ( int position, @DrawableRes int normalDrawable, @DrawableRes int selectDrawable ) { Context context = mTabLayout.getContext(); Resources resources = context.getResources(); Bitmap normal = BitmapFactory.decodeResource( resources, normalDrawable ); Bitmap select = BitmapFactory.decodeResource( resources, selectDrawable ); ProgressAlphaDrawable drawable = new ProgressAlphaDrawable( normal, select ); return setDrawable( position, drawable ); } public TabItemBuilder setDrawable ( int position, ProgressAlphaDrawable drawable ) { Tab tab = mTabLayout.getTabAt( position ); View customView = tab.getCustomView(); ImageView imageView = customView.findViewById( mImageViewId ); imageView.setImageDrawable( drawable ); mDrawables[ position ] = drawable; return this; } public void build ( int currentItem ) { mTabLayout.addOnTabSelectedListener( new TabItemSelectListener() ); mViewPager.addOnPageChangeListener( new PagerScrollListener() ); mTextViews[ currentItem ].setTextColorProgress( 1 ); mDrawables[ currentItem ].setProgress( 1 ); } protected void setProgress ( int current, int next, float progress ) { float abs = Math.abs( progress ); for( int i = 0; i < mTextViews.length; i++ ) { if( i != current || i != next ) { mTextViews[ i ].setTextColorProgress( 0 ); mDrawables[ i ].setProgress( 0 ); } } mTextViews[ current ].setTextColorProgress( 1 - abs ); mDrawables[ current ].setProgress( 1 - abs ); mTextViews[ next ].setTextColorProgress( abs ); mDrawables[ next ].setProgress( abs ); } protected class PagerScrollListener implements ViewPager.OnPageChangeListener { /** * 按下时位置 */ protected int mDragPosition; /** * 选中时位置 */ protected int mSettPosition; @Override public void onPageScrolled ( int position, float positionOffset, int positionOffsetPixels ) { if( mState == ViewPager.SCROLL_STATE_DRAGGING ) { if( position == mDragPosition ) { onScrolled( mState, mDragPosition, -positionOffset, positionOffsetPixels ); } if( position == mDragPosition - 1 ) { onScrolled( mState, mDragPosition, 1 - positionOffset, positionOffsetPixels ); } } if( mState == ViewPager.SCROLL_STATE_SETTLING ) { if( positionOffset == 0 ) { if( mDragPosition + 1 == mSettPosition ) { onScrolled( mState, mDragPosition, -1f, positionOffsetPixels ); } } if( position == mDragPosition ) { onScrolled( mState, mDragPosition, -positionOffset, positionOffsetPixels ); } if( position == mDragPosition - 1 ) { onScrolled( mState, mDragPosition, 1 - positionOffset, positionOffsetPixels ); } } } protected void onScrolled ( int state, int current, float offset, int offsetPixels ) { if( isTabSelect ) { return; } int next = current; if( offset < 0 ) { next += 1; setProgress( current, next, offset ); } if( offset > 0 ) { next -= 1; setProgress( current, next, offset ); } } @Override public void onPageSelected ( int position ) { } @Override public void onPageScrollStateChanged ( int state ) { if( state == ViewPager.SCROLL_STATE_DRAGGING ) { mDragPosition = mViewPager.getCurrentItem(); isTabSelect = false; isSetting = false; } if( state == ViewPager.SCROLL_STATE_SETTLING ) { mSettPosition = mViewPager.getCurrentItem(); if( mState == ViewPager.SCROLL_STATE_DRAGGING ) { isSetting = true; } } if( state == ViewPager.SCROLL_STATE_IDLE ) { isSetting = false; } mState = state; } } protected class TabItemSelectListener implements OnTabSelectedListener { @Override public void onTabSelected ( Tab tab ) { if( isTabSelect ) { for( ProgressAlphaDrawable drawable : mDrawables ) { drawable.setProgress( 0 ); } for( ProgressColorTextView textView : mTextViews ) { textView.setTextColorProgress( 0 ); } int position = tab.getPosition(); mDrawables[ position ].setProgress( 1 ); mTextViews[ position ].setTextColorProgress( 1 ); } if( mState == ViewPager.SCROLL_STATE_SETTLING ) { if( isSetting ) { isSetting = false; return; } } isTabSelect = true; int position = tab.getPosition(); for( int i = 0; i < mTextViews.length; i++ ) { if( i != position ) { mTextViews[ i ].setTextColorProgress( 0 ); mDrawables[ i ].setProgress( 0 ); } } mDrawables[ position ].setProgress( 1 ); mTextViews[ position ].setTextColorProgress( 1 ); } @Override public void onTabUnselected ( Tab tab ) { } @Override public void onTabReselected ( Tab tab ) { } } private String scrollStateString ( int state ) { if( state == ViewPager.SCROLL_STATE_IDLE ) { return "SCROLL_STATE_IDLE"; } if( state == ViewPager.SCROLL_STATE_DRAGGING ) { return "SCROLL_STATE_DRAGGING"; } if( state == ViewPager.SCROLL_STATE_SETTLING ) { return "SCROLL_STATE_SETTLING"; } return null; } }
package com.nextLevel.hero.mngPay.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.nextLevel.hero.member.model.dto.UserImpl; import com.nextLevel.hero.mngPay.model.dto.MngPayDTO; import com.nextLevel.hero.mngPay.model.dto.MngPayListDTO; import com.nextLevel.hero.mngPay.model.service.MngPayService; import com.nextLevel.hero.mngSalary.model.dto.SalaryAndBonusDTO; @Controller @RequestMapping("/mngPay") public class MngPayController { private final MngPayService mngPayService; @Autowired public MngPayController(MngPayService mngPayService) { this.mngPayService = mngPayService; } /* 급상여 지급 리스트 조회 */ @GetMapping("/paySalaryAndBonus") public ModelAndView mngPaySalaryAndBonus (ModelAndView mv, @AuthenticationPrincipal UserImpl user, MngPayDTO search) { search.setCompanyNo(user.getCompanyNo()); List<MngPayDTO> confirmPayList = mngPayService.selectPayList(search); mv.addObject("confirmPayList", confirmPayList); mv.setViewName("mngPay/paySalaryAndBonus"); return mv; } /* 급상여 지급 승인 */ @PostMapping(value="paySalAndBonusConfirm", produces="application/json; charset=UTF-8") @ResponseBody public String updateSalAndBonusConfirm(@AuthenticationPrincipal UserImpl user, SalaryAndBonusDTO update) { update.setCompanyNo(user.getCompanyNo()); String result = mngPayService.updateSalAndBonusConfirm(update); Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd") .setPrettyPrinting() .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY) .serializeNulls() .disableHtmlEscaping() .create(); return gson.toJson(result); } /* 급상여 지급 세부 내역 조회 */ @PostMapping(value="payListDetail", produces="application/json; charset=UTF-8") @ResponseBody public String selectPayListDetail(@AuthenticationPrincipal UserImpl user, MngPayListDTO search) { search.setCompanyNo(user.getCompanyNo()); List<MngPayListDTO> detailList = mngPayService.selectPayListDetail(search); Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd") .setPrettyPrinting() .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY) .serializeNulls() .disableHtmlEscaping() .create(); return gson.toJson(detailList); } }
package com.gedesys.ws; import com.gedesys.ifacade.OpcionesFacadeRemote; import com.gedesys.persistence.Opcion; import javax.ejb.EJB; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; /** * * @author econtreras */ @WebService() public class SecurityWS { @EJB private OpcionesFacadeRemote opcionesFR; @WebMethod(operationName = "login") public int login(@WebParam(name = "usuario") String usuario, @WebParam(name = "password") String password) { int logon = 0; if (usuario.equals("mcaro") && password.equals("1234")) { logon = 1; } else if (usuario.equals("econtreras") && password.equals("1234")) { logon = 2; } return logon; } @WebMethod(operationName = "getOpcion") public String getOpcion(@WebParam(name = "opcionId") short opcionId) { Opcion opcion = opcionesFR.getOpcion(opcionId); return opcion.getOpcion(); } }
package de.fraunhofer.iem.StudentService.service; import de.fraunhofer.iem.StudentService.model.Student; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.*; @Service public class StudentService { private final ArrayList<Student> students; int ind = 0; public StudentService() { students = new ArrayList<>() {{ add(new Student("Sam", "Wart", 111111L,"NLG") { }); add(new Student("Bill", "Beggins", 222222L,"HYD") { }); add(new Student("Stuward", "Gil", 333333L,"GER") { }); }}; } public Collection<Student> getStudents() { return students; } public boolean addStudents(Student student) { return students.add(student); } public Student findStudents(Long mn) { Student s,s1 = null; Iterator<Student> it = students.iterator(); //System.out.println(mn); while (it.hasNext()) { s = it.next(); if(s.matriculationNumber.equals(mn)){ s1 = s; ind = students.indexOf(s); } } System.out.println(ind); return s1; } public ArrayList<Student> editStudents(Student s) { students.set(ind, s); return students; } }
package stormedpanda.simplyjetpacks.items; import net.minecraft.item.IArmorMaterial; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.util.ResourceLocation; import stormedpanda.simplyjetpacks.SimplyJetpacks; import stormedpanda.simplyjetpacks.client.particle.JetpackParticleType; import stormedpanda.simplyjetpacks.config.JetpackConfigDefaults; import stormedpanda.simplyjetpacks.integration.IntegrationList; import stormedpanda.simplyjetpacks.lists.ArmorMaterialList; import stormedpanda.simplyjetpacks.util.NBTHelper; import java.util.EnumSet; public enum JetpackType { CREATIVE("jetpack_creative", 6, "jetpackCreative", JetpackParticleType.RAINBOW), CREATIVE_ARMORED("jetpack_creative_armored", 6, "jetpackCreative", JetpackParticleType.RAINBOW, true), VANILLA1("jetpack_vanilla1", 1, "jetpack1"), VANILLA1_ARMORED("jetpack_vanilla1_armored", 1, "jetpack1", true, 0), VANILLA2("jetpack_vanilla2", 2, "jetpack2"), VANILLA2_ARMORED("jetpack_vanilla2_armored", 2, "jetpack2", true, 1), VANILLA3("jetpack_vanilla3", 3, "jetpack3"), VANILLA3_ARMORED("jetpack_vanilla3_armored", 3, "jetpack3", true, 2), VANILLA4("jetpack_vanilla4", 4, "jetpack4"), VANILLA4_ARMORED("jetpack_vanilla4_armored", 4, "jetpack4", true, 3), IE1("jetpack_ie1", 1, "jetpack1"), IE1_ARMORED("jetpack_ie1_armored", 1, "jetpack1", true, 4), IE2("jetpack_ie2", 2, "jetpack2"), IE2_ARMORED("jetpack_ie2_armored", 2, "jetpack2", true, 5), IE3("jetpack_ie3", 3, "jetpack3"), IE3_ARMORED("jetpack_ie3_armored", 3, "jetpack3", true, 6), MEK1("jetpack_mek1", 1, "jetpack1"), MEK1_ARMORED("jetpack_mek1_armored", 1, "jetpack1", true, 7), MEK2("jetpack_mek2", 2, "jetpack2"), MEK2_ARMORED("jetpack_mek2_armored", 2, "jetpack2", true, 8), MEK3("jetpack_mek3", 3, "jetpack3"), MEK3_ARMORED("jetpack_mek3_armored", 3, "jetpack3", true, 9), MEK4("jetpack_mek4", 4, "jetpack4"), MEK4_ARMORED("jetpack_mek4_armored", 4, "jetpack4", true, 10); protected static final EnumSet<JetpackType> JETPACK_ALL = EnumSet.allOf(JetpackType.class); public static final EnumSet<JetpackType> JETPACK_SJ = EnumSet.range(CREATIVE, CREATIVE_ARMORED); public static final EnumSet<JetpackType> JETPACK_VANILLA = EnumSet.range(VANILLA1, VANILLA4_ARMORED); public static final EnumSet<JetpackType> JETPACK_IE = EnumSet.range(IE1, IE3_ARMORED); public static final EnumSet<JetpackType> JETPACK_MEK = EnumSet.range(MEK1, MEK4_ARMORED); private final String name; private final int tier; private final ResourceLocation armorTexture; private boolean isArmored; private int platingID; private final Item.Properties properties; // Configurations: public final JetpackConfigDefaults defaults; //public int energyCapacity; //public int energyPerTickIn; //public int energyPerTickOut; private int capacity; private int maxReceive; private int maxExtract; private int enchantability; public int armorEnergyPerHit; public int armorReduction; public int energyUsage; public double speedVertical; public double accelVertical; public double speedVerticalHover; public double speedVerticalHoverSlow; public double speedSideways; public double sprintSpeedModifier; public double sprintEnergyModifier; public boolean emergencyHoverMode; public boolean chargerMode; public JetpackParticleType particleType; JetpackType(String name, int tier, String defaultConfigKey, JetpackParticleType particleType, boolean isArmored) { this(name, tier, defaultConfigKey); this.particleType = particleType; this.isArmored = isArmored; } JetpackType(String name, int tier, String defaultConfigKey, JetpackParticleType particleType) { this(name, tier, defaultConfigKey); this.particleType = particleType; } JetpackType(String name, int tier, String defaultConfigKey, boolean isArmored) { this(name, tier, defaultConfigKey); this.isArmored = isArmored; } JetpackType(String name, int tier, String defaultConfigKey, boolean isArmored, int platingID ) { this(name, tier, defaultConfigKey); this.isArmored = isArmored; this.platingID = platingID; } JetpackType(String name, int tier, String defaultConfigKey) { this.name = name; this.tier = tier; this.armorTexture = new ResourceLocation(("simplyjetpacks:textures/models/armor/" + name + ".png")); this.isArmored = false; this.properties = new Item.Properties().group(SimplyJetpacks.tabSimplyJetpacks).maxStackSize(1); this.defaults = JetpackConfigDefaults.get(defaultConfigKey); this.particleType = JetpackParticleType.DEFAULT; } public String getName() { return name; } public int getTier() { return tier; } public Rarity getRarity() { switch (tier) { case 2: return Rarity.UNCOMMON; case 3: return Rarity.RARE; case 4: return Rarity.EPIC; default: return Rarity.COMMON; } } public int getCapacity() { return capacity; } public int getMaxReceive() { return maxReceive; } public int getMaxExtract() { return maxExtract; } public int getEnergyUsage() { return energyUsage; } public double getSpeedVertical() { return speedVertical; } public double getAccelVertical() { return accelVertical; } public double getSpeedVerticalHoverSlow() { return speedVerticalHoverSlow; } public double getSpeedVerticalHover() { return speedVerticalHover; } public double getSpeedSideways() { return speedSideways; } public double getSprintSpeedModifier() { return sprintSpeedModifier; } public double getSprintEnergyModifier() { return sprintEnergyModifier; } public boolean canEHover() { return emergencyHoverMode; } public boolean canCharge() { return chargerMode; } public String getArmorTexture() { return armorTexture.toString(); } public IArmorMaterial getArmorMaterial() { //ArmorMaterialList.setArmorReduction(ArmorMaterialList.JETPACK_ARMORED, getArmorReduction()); //return isArmored ? ArmorMaterialList.JETPACK_ARMORED : ArmorMaterialList.JETPACK; ArmorMaterialList armorMaterial = isArmored ? ArmorMaterialList.JETPACK_ARMORED : ArmorMaterialList.JETPACK; ArmorMaterialList.setStats(armorMaterial, isArmored, getEnchantability(), getArmorReduction()); return armorMaterial; } public boolean getIsArmored() { return isArmored; } public int getArmorReduction() { return armorReduction; } public int getEnchantability() { return enchantability; } public Item.Properties getProperties() { return properties; } public int getPlatingID() { return platingID; } public JetpackParticleType getParticleType(ItemStack stack) { if (stack.getTag() != null && NBTHelper.hasKey(stack, JetpackItem.TAG_PARTICLE)) { int particle = NBTHelper.getInt(stack, JetpackItem.TAG_PARTICLE);//, particleType.ordinal()); JetpackParticleType particleType = JetpackParticleType.values()[particle]; if (particleType != null) { return particleType; } } NBTHelper.setInt(stack, JetpackItem.TAG_PARTICLE, particleType.ordinal()); return this.particleType; } public static void loadAllConfigs() { /* for (JetpackType jetpackType : JETPACK_ALL) { jetpackType.loadJetpackConfigurations(); }*/ for (JetpackType jetpackType : JETPACK_SJ) { jetpackType.loadJetpackConfigurations(); } if (IntegrationList.integrateVanilla) { for (JetpackType jetpackType : JETPACK_VANILLA) { jetpackType.loadJetpackConfigurations(); } } if (IntegrationList.integrateImmersiveEngineering) { for (JetpackType jetpackType : JETPACK_IE) { jetpackType.loadJetpackConfigurations(); } } if (IntegrationList.integrateMekanism) { for (JetpackType jetpackType : JETPACK_MEK) { jetpackType.loadJetpackConfigurations(); } } } protected void loadJetpackConfigurations() { this.capacity = this.defaults.energyCapacity; this.maxReceive = this.defaults.energyPerTickIn; this.maxExtract = this.defaults.energyPerTickOut; this.enchantability = this.defaults.enchantability; this.armorEnergyPerHit = this.defaults.armorEnergyPerHit; this.armorReduction = this.defaults.armorReduction; this.energyUsage = this.defaults.energyUsage; this.speedVertical = this.defaults.speedVertical; this.accelVertical = this.defaults.accelVertical; this.speedVerticalHover = this.defaults.speedVerticalHover; this.speedVerticalHoverSlow = this.defaults.speedVerticalHoverSlow; this.speedSideways = this.defaults.speedSideways; this.sprintSpeedModifier = this.defaults.sprintSpeedModifier; this.sprintEnergyModifier = this.defaults.sprintEnergyModifier; this.emergencyHoverMode = this.defaults.emergencyHoverMode; this.chargerMode = this.defaults.chargerMode; } }
package com.redsun.platf.web.controller.system; import com.redsun.platf.dao.base.IPagedDao; import com.redsun.platf.entity.sys.SystemTxn; import com.redsun.platf.service.account.AccountManager; import com.redsun.platf.util.treenode.TreeNode; import com.redsun.platf.util.treenode.TreeNodeBuilder; import com.redsun.platf.util.treenode.entitynode.TxnNode; import com.redsun.platf.web.controller.AbstractStandardController; import org.hibernate.SQLQuery; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.sql.SQLException; import java.util.List; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 2012/12/25 * Time: 下午 4:03 * To change this template use File | Settings | File Templates. * history: * * @author pyc 2012/12/25 created */ @Controller @RequestMapping("/system/txn") @Transactional @SuppressWarnings("unchecked") public class TxnController extends AbstractStandardController<SystemTxn> { @Resource AccountManager userManager; @Override public String getUrl() { return "system/txn"; } @Override public IPagedDao<SystemTxn, Long> getDao() { return getDaoFactory().getSystemTxnDao(); } @Override protected void prepareModel() throws Exception { SystemTxn entity; if (id != null) { entity = getDao().get(id); } else { entity = new SystemTxn(); entity.setParentId(null); } this.setModel(entity); } @Override protected boolean beforeSave() { //沒有parent| parentid =id if (getModel().getParentId() == null || getModel().getParentId().getId() == null ||getModel().getParentId().getId().equals(getModel().getId()) ) getModel().setParentId(null); return true; } /** * 存在上级不能删除 * @param idList * @return */ @Override protected boolean beforeDelete(String[] idList) throws Exception{ for (String id :idList){ List<SystemTxn> en=getDao().findBy("parentId.id" ,Long.parseLong( id)); if (en.size()>0){ // System.out.println(en); throw new SQLException(id+":存在下级,请先删除下级项目,无法删除!"); } } return true; } @RequestMapping(method = RequestMethod.GET, value = "/txn_menu") private ModelAndView validModel(HttpServletRequest request) throws Exception { // List<SystemTxn> txns=getDao().findBy("parentId.id",null); String hql = "select {c.*} from sys_txn as c where c.parent_id=:p or (c.parent_id is null) "; SQLQuery query = getDao().createSQLQuery(hql); query.addEntity("c", SystemTxn.class); //必须为add query.setParameter("p",0L); List<SystemTxn> txns=query.list(); ModelMap map=new ModelMap(); map.put("txns",txns); System.out.println(txns.size()); return new ModelAndView(getUrl()+"/menu",map); } @ResponseBody @RequestMapping(method = RequestMethod.POST, value = "/tree") @SuppressWarnings("unchecked") private List<TreeNode> listTreeModel(String id) throws Exception { TxnNode node = new TxnNode(getDao()); return new TreeNodeBuilder().buildTree("0", node); } }
/* * 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 Formularios; /** * * */ public class frminicio extends javax.swing.JFrame { /** * Creates new form */ public frminicio() { initComponents(); this.setExtendedState(frminicio.MAXIMIZED_BOTH); this.setTitle("Sistema de Registros Academicos RECOL INSTITUCION EDUCATIVA EL PORVENIR"); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { escritorio = new javax.swing.JDesktopPane(); jPanel1 = new javax.swing.JPanel(); lblidpersona = new javax.swing.JLabel(); lblNombres = new javax.swing.JLabel(); lblP_apellido = new javax.swing.JLabel(); lblS_apellido = new javax.swing.JLabel(); lblacceso = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); menuBar = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); openMenuItem = new javax.swing.JMenuItem(); saveMenuItem = new javax.swing.JMenuItem(); mnuarchivos = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); jMenuItem2 = new javax.swing.JMenuItem(); jMenu4 = new javax.swing.JMenu(); jMenuItem4 = new javax.swing.JMenuItem(); jMenuItem5 = new javax.swing.JMenuItem(); helpMenu = new javax.swing.JMenu(); contentMenuItem = new javax.swing.JMenuItem(); aboutMenuItem = new javax.swing.JMenuItem(); jMenu3 = new javax.swing.JMenu(); mnuconfiguraciones = new javax.swing.JMenu(); cutMenuItem = new javax.swing.JMenuItem(); jMenu5 = new javax.swing.JMenu(); jMenuItem3 = new javax.swing.JMenuItem(); jMenuItem6 = new javax.swing.JMenuItem(); jMenuItem7 = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setAutoRequestFocus(false); setBackground(new java.awt.Color(153, 153, 0)); setIconImages(null); escritorio.setBackground(new java.awt.Color(204, 51, 0)); lblidpersona.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N lblidpersona.setText("jLabel1"); lblNombres.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N lblNombres.setText("jLabel2"); lblP_apellido.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N lblP_apellido.setText("jLabel3"); lblS_apellido.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N lblS_apellido.setText("jLabel4"); lblacceso.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N lblacceso.setText("jLabel7"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblidpersona, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblNombres, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblP_apellido, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblS_apellido, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblacceso, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(lblidpersona) .addGap(18, 18, 18) .addComponent(lblNombres) .addGap(18, 18, 18) .addComponent(lblP_apellido) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblS_apellido) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblacceso) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); escritorio.add(jPanel1); jPanel1.setBounds(20, 40, 140, 200); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("USUARIO ACTUAL"); escritorio.add(jLabel1); jLabel1.setBounds(20, 10, 140, 20); menuBar.setBackground(new java.awt.Color(204, 255, 204)); fileMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/Archivo.png"))); // NOI18N fileMenu.setMnemonic('f'); fileMenu.setText("Estudiantes"); openMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK)); openMenuItem.setMnemonic('o'); openMenuItem.setText("Ingreso Estudiantes nuevos"); openMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openMenuItemActionPerformed(evt); } }); fileMenu.add(openMenuItem); saveMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.CTRL_MASK)); saveMenuItem.setMnemonic('s'); saveMenuItem.setText("Matricular Estudiantes "); saveMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveMenuItemActionPerformed(evt); } }); fileMenu.add(saveMenuItem); menuBar.add(fileMenu); mnuarchivos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/clientes.png"))); // NOI18N mnuarchivos.setText("Personal "); jMenuItem1.setText("Ingreso de Personal "); jMenuItem1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jMenuItem1MouseClicked(evt); } }); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); mnuarchivos.add(jMenuItem1); menuBar.add(mnuarchivos); jMenu2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/folder_blue_printer_10980.png"))); // NOI18N jMenu2.setText("Informes "); jMenuItem2.setText("Listados Matriculado"); jMenu2.add(jMenuItem2); jMenu4.setText("Listados "); jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem4.setText("Planillas de Asistencias"); jMenuItem4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem4ActionPerformed(evt); } }); jMenu4.add(jMenuItem4); jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem5.setText("Planillas de Calificaciones "); jMenu4.add(jMenuItem5); jMenu2.add(jMenu4); helpMenu.setMnemonic('h'); helpMenu.setText("Procesos"); contentMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/folder_blue_printer_10980.png"))); // NOI18N contentMenuItem.setMnemonic('c'); contentMenuItem.setText("Generar Informes Academicos "); helpMenu.add(contentMenuItem); aboutMenuItem.setMnemonic('a'); aboutMenuItem.setText("About"); helpMenu.add(aboutMenuItem); jMenu3.setText("jMenu3"); helpMenu.add(jMenu3); jMenu2.add(helpMenu); menuBar.add(jMenu2); mnuconfiguraciones.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/Configuraciones.png"))); // NOI18N mnuconfiguraciones.setMnemonic('e'); mnuconfiguraciones.setText("Configuracion "); cutMenuItem.setMnemonic('t'); cutMenuItem.setText("Actualizaciones "); cutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cutMenuItemActionPerformed(evt); } }); mnuconfiguraciones.add(cutMenuItem); jMenu5.setText("Actualizar tablas "); jMenuItem3.setText("Tabla Asignaturas"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu5.add(jMenuItem3); jMenuItem6.setText("Tabla grados "); jMenu5.add(jMenuItem6); jMenuItem7.setText("Tabla Logros y Deficiencias"); jMenuItem7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem7ActionPerformed(evt); } }); jMenu5.add(jMenuItem7); mnuconfiguraciones.add(jMenu5); menuBar.add(mnuconfiguraciones); setJMenuBar(menuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(escritorio, javax.swing.GroupLayout.DEFAULT_SIZE, 728, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(escritorio, javax.swing.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jMenuItem1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenuItem1MouseClicked // TODO add your handling code here: }//GEN-LAST:event_jMenuItem1MouseClicked private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed frmtrabajador form =new frmtrabajador(); escritorio.add(form); form.toFront(); form.setVisible(true); // TODO add your handling code here: }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed frmPlanillas form =new frmPlanillas(); escritorio.add(form); form.toFront(); form.setVisible(true); // TODO add your handling code here: }//GEN-LAST:event_jMenuItem4ActionPerformed private void saveMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveMenuItemActionPerformed frmMatricula form =new frmMatricula(); escritorio.add(form); form.toFront(); form.setVisible(true); // TODO add your handling code here: }//GEN-LAST:event_saveMenuItemActionPerformed private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMenuItemActionPerformed frmEstudiantes form =new frmEstudiantes(); escritorio.add(form); form.toFront(); form.setVisible(true); // TODO add your handling code here: }//GEN-LAST:event_openMenuItemActionPerformed private void cutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cutMenuItemActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cutMenuItemActionPerformed private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed frmasignaturas form =new frmasignaturas(); escritorio.add(form); form.toFront(); form.setVisible(true); // TODO add your handling code here: }//GEN-LAST:event_jMenuItem3ActionPerformed private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed frmlogros form =new frmlogros(); escritorio.add(form); form.toFront(); form.setVisible(true); // // TODO add your handling code here: }//GEN-LAST:event_jMenuItem7ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(frminicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(frminicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(frminicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(frminicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new frminicio().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenuItem aboutMenuItem; private javax.swing.JMenuItem contentMenuItem; private javax.swing.JMenuItem cutMenuItem; private javax.swing.JDesktopPane escritorio; private javax.swing.JMenu fileMenu; private javax.swing.JMenu helpMenu; private javax.swing.JLabel jLabel1; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JMenu jMenu4; private javax.swing.JMenu jMenu5; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem jMenuItem4; private javax.swing.JMenuItem jMenuItem5; private javax.swing.JMenuItem jMenuItem6; private javax.swing.JMenuItem jMenuItem7; private javax.swing.JPanel jPanel1; public static javax.swing.JLabel lblNombres; public static javax.swing.JLabel lblP_apellido; public static javax.swing.JLabel lblS_apellido; public static javax.swing.JLabel lblacceso; public static javax.swing.JLabel lblidpersona; private javax.swing.JMenuBar menuBar; public static javax.swing.JMenu mnuarchivos; public static javax.swing.JMenu mnuconfiguraciones; private javax.swing.JMenuItem openMenuItem; private javax.swing.JMenuItem saveMenuItem; // End of variables declaration//GEN-END:variables }
package fmi; public interface Sound { void play(); }
package com.bwardweb.iterator.model; public class ApplianceShop implements Shop{ private StockItem[] items; public ApplianceShop(StockItem[] items){ this.items = items; } @Override public Iterator createIterator() { return new ApplianceShopIterator(items); } }
package net.kkolyan.elements.game.tmx; import net.kkolyan.elements.engine.core.Locatable; import net.kkolyan.elements.engine.core.definition.sdl.SdlLoader; import net.kkolyan.elements.engine.core.physics.Border; import net.kkolyan.elements.engine.core.templates.Object2d; import net.kkolyan.elements.engine.core.templates.Ray; import net.kkolyan.elements.engine.core.templates.Sprite; import net.kkolyan.elements.engine.core.templates.Vector; import net.kkolyan.elements.engine.utils.ResourcesUtil; import net.kkolyan.elements.game.Level; import net.kkolyan.elements.game.UniObject; import net.kkolyan.elements.game.tmx.model.*; import net.kkolyan.elements.tactics.Surface; import org.simpleframework.xml.core.Persister; import java.io.ByteArrayInputStream; import java.io.File; import java.util.*; /** * https://github.com/bjorn/tiled/wiki/TMX-Map-Format * * @author nplekhanov */ public class TmxLoader { public static Level loadTmxLevel(String resource, SdlLoader sdlLoader) { Map<String,List<String>> tmxMapping = (Map) sdlLoader.createObject("tmxMapping"); Level level = new Level(); String parent = new File(resource).getParent(); Persister persister = new Persister(); TmxMap map; try { map = persister.read(TmxMap.class, new ByteArrayInputStream(ResourcesUtil.getResourceContent(resource))); } catch (Exception e) { throw new IllegalStateException(e); } if (map.getLayers().size() != 1 || !map.getLayers().get(0).getName().equals("Tiles")) { throw new IllegalStateException(); } List<String> tileNames = tmxMapping.get("Tiles"); TmxLayer tilesLayer = map.getLayers().get(0); int[][] tiles = tilesLayer.getData().getGidMatrix(); for (int x = 0; x < tilesLayer.getWidth(); x ++) { for (int y = 0; y < tilesLayer.getHeight(); y ++) { int gid = tiles[y][x]; if (gid == 0) { continue; } TmxTileSet tileSet = map.getTileSetByGid(gid); int imageIndex = gid - tileSet.getFirstgid(); if (imageIndex < 0) { throw new IllegalStateException(); } String tileName = tileNames.get(gid); Surface tile = (Surface) sdlLoader.createObject(tileName); tile.setImageSetId(new File(parent, tileSet.getImage().getSource()).toString() + "#" + (imageIndex)); tile.setX(x * map.getTilewidth() + map.getTilewidth()/2); tile.setY(y * map.getTileheight() + map.getTileheight()/2); level.getObjects().add(tile); } } for (TmxObjectGroup objectGroup: map.getObjectGroups()) { if (objectGroup.getObjects() == null) { continue; } List<String> objectNames = tmxMapping.get(objectGroup.getName()); for (TmxObject object: objectGroup.getObjects()) { Integer gid = object.getGid(); if (gid != null) { TmxTileSet tileSet = map.getTileSetByGid(gid); int index = gid - tileSet.getFirstgid(); if (index < 0 || index >= objectNames.size()) { throw new IllegalStateException(); } String objectName = objectNames.get(index); Object o = sdlLoader.createObject(objectName); Locatable locatable = optionalLocatable(o); if (locatable != null) { locatable.set(new Vector(object.getX() + 16, object.getY() + 16)); } if (objectGroup.getName().equals("PlayerUnits")) { level.getPlayers().add(o); } else { level.getObjects().add(o); } } else { List<Vector> polyLine = object.getPolyline().getPoints(); Vector offset = new Vector(object.getX(), object.getY()); for (int i = 1; i < polyLine.size(); i ++) { Vector begin = polyLine.get(i - 1).getTranslated(offset); Vector end = polyLine.get(i).getTranslated(offset); level.getObjects().add(new Border(begin, end)); } } } } return level; } private static Locatable optionalLocatable(Object o) { if (o instanceof Locatable) { return (Locatable) o; } if (o instanceof UniObject) { if (((UniObject) o).is(Locatable.class)) { return ((UniObject) o).as(Locatable.class); } } return null; } }
package com.edasaki.rpg.spells.paladin; import org.bukkit.Location; import org.bukkit.entity.Player; import com.edasaki.core.utils.RParticles; import com.edasaki.core.utils.RScheduler; import com.edasaki.rpg.PlayerDataRPG; import com.edasaki.rpg.spells.Spell; import com.edasaki.rpg.spells.SpellEffect; import de.slikey.effectlib.util.ParticleEffect; public class FlameCharge extends SpellEffect { public static final String BUFF_ID = "flame charge"; @Override public boolean cast(final Player p, PlayerDataRPG pd, int level) { int tier = 1; switch (level) { case 1: tier = 1; break; case 2: tier = 2; break; case 3: tier = 3; break; case 4: tier = 4; break; case 5: tier = 5; break; } Location start = p.getLocation().add(0, p.getEyeHeight() * 0.75, 0).clone(); final Location loc = start.clone().add(0, -0.3, 0); for (int k = 0; k < 5; k++) { RScheduler.schedule(Spell.plugin, new Runnable() { public void run() { RParticles.showWithOffset(ParticleEffect.FLAME, loc, 0.6, 10); loc.add(0, 0.6, 0); } }, k); } pd.giveBuff(FlameCharge.BUFF_ID, tier, 5000); Spell.notify(p, "You charge your mace with the power of fire."); Spell.notifyDelayed(p, "Flame charge has worn off.", 6); return true; } }
package com.itobuz.android.awesomechat.main.database; import com.itobuz.android.awesomechat.user.data_model.User; import rx.Observable; /** * Created by Debasis on 17/12/16. */ public interface CloudMessagingDatabase { Observable<String> readToken(User user); void setToken(User user); void enableToken(String userId); void disableToken(String userId); }
package com.ctg.itrdc.janus.rpc.cluster.router.condition; import com.ctg.itrdc.janus.common.URL; import com.ctg.itrdc.janus.rpc.cluster.Router; import com.ctg.itrdc.janus.rpc.cluster.RouterFactory; /** * ConditionRouterFactory * * @author Administrator */ public class ConditionRouterFactory implements RouterFactory { public static final String NAME = "condition"; public Router getRouter(URL url) { return new ConditionRouter(url); } }
package com.oa.email.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.directwebremoting.annotations.RemoteMethod; import org.directwebremoting.annotations.RemoteProxy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.oa.email.form.MailInfo; import com.oa.email.form.MailServer; import com.oa.email.service.MailInfoService; import com.oa.email.service.MailServerService; import com.oa.user.form.UserInfo; import com.oa.user.service.UserInfoService; @Controller @RequestMapping("/setting/mail") @RemoteProxy(name="mailController") public class EmailController { @Autowired private MailServerService mailServerService; @Autowired private MailInfoService mailInfoService; @Autowired private UserInfoService userService; @RequestMapping("/emailSetting") public String settingEmailServer( @ModelAttribute("mailServer") MailServer mailServer, HttpServletRequest request, Map<String, Object> model) { /** * 假设session中存储userId 为1 */ int userId = 1; UserInfo userInfo = userService.selectUserById(userId); MailServer mailServer2 = mailServerService .findMailServerByUserId(userId); if (mailServer2 == null) { mailServer.setUserInfo(userInfo); mailServerService.updateMailServer(mailServer); mailServer = mailServerService.findMailServerByUserId(userId); model.put("mailServer", mailServer); } else if (mailServer2.getMailServerId() != null && mailServer.getMailAddress() == null && mailServer.getPassword() == null) { mailServerService.updateMailServer(mailServer2); model.put("mailServer", mailServer2); } else { mailServer2.setMailAddress(mailServer.getMailAddress()); mailServer2.setPassword(mailServer.getPassword()); mailServerService.updateMailServer(mailServer2); model.put("mailServer", mailServer2); } return "/setting/mail/emailSetting"; } @RequestMapping(value = "/ajaxRequestAllEmails", method = RequestMethod.GET) public @ResponseBody Map<String, Object> ajaxRequestAllEmails(HttpServletRequest request) { String mailAddress = request.getParameter("query"); List<MailServer> findAllMailServer = mailServerService .findMailServersByMailAddress(mailAddress); Map<String, Object> map = new HashMap<String, Object>(); List<String> lists = new ArrayList<String>(); for (MailServer server : findAllMailServer) { lists.add(server.getMailAddress()); } map.put("mailServerList", lists); map.put("code", "200"); return map; } @RequestMapping("/editEmail") public String editEmail(Map<String, Object> model) { model.put("mailInfo", new MailInfo()); return "/setting/mail/editMail"; } @RequestMapping("/saveAsDraft") public String saveAsDraft(MailInfo mailInfo, Map<String, Object> model) { /** * 假设session中存储userId 为1 */ int userId = 1; MailServer mailServer = mailServerService .findMailServerByUserId(userId); mailInfo.setMailServer(mailServer); mailInfo.setFromAddress(mailServer.getMailAddress()); mailInfo.setHeader(mailInfo.getSubject()); mailInfo.setIsdraft(true); mailInfoService.addMailInfo(mailInfo); return "redirect:/setting/mail/findAllEmails"; } @RequestMapping("/saveAndSendEmail") public String saveAndSendEmail(MailInfo mailInfo, Map<String, Object> model) { /** * 假设session中存储userId 为1 */ int userId = 1; MailServer mailServer = mailServerService .findMailServerByUserId(userId); mailInfo.setMailServer(mailServer); mailInfo.setFromAddress(mailServer.getMailAddress()); mailInfo.setHeader(mailInfo.getSubject()); try { mailInfoService.sendHTMLMail(mailServer, mailInfo); mailInfo.setIsdraft(false); mailInfoService.addMailInfo(mailInfo); } catch (Exception e) { mailInfo.setIsdraft(true); mailInfoService.addMailInfo(mailInfo); } model.put("mailInfo", new MailInfo()); return "/setting/mail/editMail"; } @RequestMapping("/modifyEmail/{mailId}") public String modifyEmail(@PathVariable("mailId") int mailId, Map<String, Object> model) { MailInfo mailInfo = mailInfoService.findMailInfoById(mailId); /** * 假设session中存储userId 为1 */ model.put("mailInfo", mailInfo); return "/setting/mail/editMail"; } @RequestMapping("/findAllEmails") public String findAllEmails(Map<String, Object> model, HttpServletRequest request) { int userId = 1; MailServer mailServer = mailServerService .findMailServerByUserId(userId); List<MailInfo> listMailInfo = mailInfoService .findAllMailInfoByUserId(userId); /** * 假设session中存储userId 为1 */ model.put("listMailInfo", listMailInfo); return "/setting/mail/listMailInfo"; } @RemoteMethod public List<MailInfo> findAllEmails() { int userId = 1; MailServer mailServer = mailServerService .findMailServerByUserId(userId); List<MailInfo> listMailInfo = mailInfoService .findAllMailInfoByUserId(userId); return listMailInfo; } @RequestMapping("/findDraftEmails") public String findDraftEmails(Map<String, Object> model, HttpServletRequest request) { int userId = 1; MailServer mailServer = mailServerService .findMailServerByUserId(userId); List<MailInfo> listMailInfo = mailInfoService .findDraftEmailsByUserId(userId); /** * 假设session中存储userId 为1 */ model.put("listMailInfo", listMailInfo); return "/setting/mail/listMailInfo"; } }
import java.util.Scanner; /** * A simple class to run the Magpie class. * @author Laurie White * @version April 2012 */ public class MagpieRunner { /** * Create a Magpie, give it user input, and print its replies. */ public static void main(String[] args) { Magpie maggie = new Magpie(); System.out.println (maggie.getGreeting()); Scanner in = new Scanner (System.in); String statement = in.nextLine(); while (!statement.equals("Bye")) { if (statement.indexOf("cat") != -1){ System.out.println("Tell me more about your pets"); statement = in.nextLine(); } if (statement.indexOf("dog") != -1 ){ System.out.println("Tell me more about your pets"); statement = in.nextLine(); } if (statement.indexOf("Mr.") != -1|| statement.indexOf("Miss") != -1){ System.out.println("He sounds like a good teacher."); statement = in.nextLine(); } if (statement.trim().length() == 0) { System.out.println("Please say something please"); } else { System.out.println (maggie.getResponse(statement)); statement = in.nextLine(); } } in.close(); } }
/** * Dedicated support for matching HTTP request paths. * * <p>{@link org.springframework.web.util.pattern.PathPatternParser} is used to * parse URI path patterns into * {@link org.springframework.web.util.pattern.PathPattern org.springframework.web.util.pattern.PathPatterns} that can then be * used for matching purposes at request time. */ @NonNullApi @NonNullFields package org.springframework.web.util.pattern; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
package Provedor_Consumidor; /** * * @author Garcia Garcia Jose Angel */ public class Drop { // Mensaje enviado del productor al consumidor private String message; // True si el consumidor debe esperar para que el productor envie el mensaje // false si el productor deberia esperar para que el consumidor reciba el mensaje private boolean empty = true; public synchronized String take() { // Espera hasta que el mensaje esté disponible while (empty) { try { System.out.println("A esperar take"); wait(); } catch (Exception e) { } } // cambia el estado empty = true; System.out.println("Mensaje consumido"); // Notifica el productor que el estatus ha cambiado notifyAll(); return message; } public synchronized void put(String message){ System.out.println(empty); while (!empty) { try { System.out.println("Esperar a take"); wait(); } catch (Exception e) { System.out.println("Cach"); } } empty = false; System.out.println("Mensaje colocado"); this.message = message; // Notifica al proveedor que el estatus ha cambiado notifyAll(); } }
package com.jgw.supercodeplatform.trace.constants; public enum DefaultFieldEnum { ORGANIZATION_ID("OrganizationId","组织id","1"), TRACETEMPLATE_ID("TraceTemplateId","溯源模板id","1"), TRACEBATCHINFO_ID("TraceBatchInfoId","批次唯一id","1"), SYSId_ID("SysId","系统id","1"), SORTDATETIME("SortDateTime","排序时间",""), DELETE_STATUS("DeleteStatus","隐藏删除状态",""), ID("Id","主键",""), USERID("UserId","用户id","1"), PRODUCTID("ProductId","产品id","1"), ParentId("ParentId","主表数据id","1"); private DefaultFieldEnum(String fieldCode, String fieldName, String fieldType) { this.fieldCode = fieldCode; this.fieldName = fieldName; this.fieldType = fieldType; } private String fieldCode; private String fieldName; private String fieldType; public String getFieldCode() { return fieldCode; } public void setFieldCode(String fieldCode) { this.fieldCode = fieldCode; } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getFieldType() { return fieldType; } public void setFieldType(String fieldType) { this.fieldType = fieldType; } }
/* Copyright 2017 Stratumn SAS. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.stratumn.sdk.model.trace; import com.stratumn.sdk.TraceLink; public class PushTransferInput<TLinkData> extends ParentLink<TLinkData> { private String recipient; private TLinkData data; public PushTransferInput(String recipient, TLinkData data,String traceId) throws IllegalArgumentException { super(traceId); if (recipient == null) { throw new IllegalArgumentException("recipient cannot be null in PushTransferInput"); } this.data = data; this.recipient = recipient; } public PushTransferInput(String recipient, TLinkData data, TraceLink<TLinkData> prevLink) throws IllegalArgumentException { super( prevLink); if (recipient == null) { throw new IllegalArgumentException("recipient cannot be null in PushTransferInput"); } this.data = data; this.recipient = recipient; } public TLinkData getData() { return this.data; } public void setData(TLinkData data) { this.data = data; } public String getRecipient() { return this.recipient; } public void setRecipient(String recipient) { this.recipient = recipient; } }
package org.notice.beans; import java.io.Serializable; public class UserSkills implements Serializable { private int skillID = 0 , level = 0; private String userId = null; public UserSkills( String userId, int skillID, int level) { this.skillID = skillID; this.level = level; this.userId = userId; } public int getSkillID() { return skillID; } public void setSkillID(int skillID) { this.skillID = skillID; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @Override public String toString() { return "UserSkills [skillID=" + skillID + ", level=" + level + ", userId=" + userId + "]"; } }
package com.leetcode.oj.binarytree; import java.util.ArrayDeque; import java.util.Deque; import java.util.Iterator; public class BinaryTreePreOrderIterator implements Iterator<TreeNode> { private Deque<TreeNode> stack; private TreeNode current; public BinaryTreePreOrderIterator(TreeNode root) { this.stack = new ArrayDeque<>(); this.current = root; } @Override public boolean hasNext() { return stack.size() > 0 || current != null; } @Override public TreeNode next() { TreeNode node = null; while (hasNext()) { if (current != null) { node = current; if (current.right != null) stack.push(current.right); current = current.left; break; } else { current = stack.pop(); } } return node; } @Override public void remove() { throw new UnsupportedOperationException(); } public static void main(String[] args) { TreeNode n = new TreeNode(3); TreeNode a = new TreeNode(2); TreeNode b = new TreeNode(4); TreeNode c = new TreeNode(1); TreeNode d = new TreeNode(11); n.left = a; n.right = b; a.left = c; a.right = d; BinaryTreePreOrderIterator iter = new BinaryTreePreOrderIterator(n); while (iter.hasNext()) { System.out.println(iter.next()); } } }
package com.wangzhu.other; import org.junit.Test; /** * Created by wang.zhu on 2021-03-10 00:17. **/ public class TestException { private int getResult() throws Exception { int a = 100; try { a = a + 10; throw new RuntimeException(); } catch (Exception e) { System.out.println("截获异常并重新抛出异常"); throw new Exception(); } finally { return a; } } @Test public void test1() { try { System.out.println(getResult()); } catch (Exception e) { e.printStackTrace(); System.out.println("截获异常catch"); } finally { System.out.println("异常处理finally"); } } }
package com.lx.method; public class method { /* 1000 以内 每位上面的数字的幂次方 之和 等于他本身的数字有几个 */ // bcd; int a, b, c, d, i = 0; public String shuixianhua() { System.out.println("您要找的水仙花数为:"); for (a = 100; a < 1000; a++) { b = a / 100; c = (a / 10) % 10; d = a % 100 % 10; if (a == b * b * b + c * c * c + d * d * d) { System.out.println(a); i++; } } return String.valueOf(i); } public static void main(String[] args) { method mh = new method(); System.out.print(mh.shuixianhua()); } }
package com.github.tobby48.engineering.scene3.builder; /** * <pre> * com.github.tobby48.engineering.scene3.builder * TextBuilder.java * * 설명 :일반 텍스트 파일을 사용하여 문서를 만드는 클래스 * </pre> * * @since : 2017. 10. 3. * @author : tobby48 * @version : v1.0 */ public class TextBuilder extends Builder { private StringBuffer buffer = new StringBuffer(); public void makeTitle(String title){ buffer.append("==============================\n"); buffer.append("『" + title + "』\n"); buffer.append("\n"); } public void makeString(String str) { buffer.append('■' + str + "\n"); buffer.append("\n"); } public void makeItems(String[] items) { for(int i = 0; i < items.length; i++) { buffer.append("●" + items[i] + "\n"); } buffer.append("\n"); } public Object getResult(){ buffer.append("==============================\n"); return buffer.toString(); } }
package com.example.myapplication; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDialogFragment; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.widget.Toast; import com.google.android.material.snackbar.Snackbar; public class HalKedua extends AppCompatActivity { EditText inputTinggi,inputAlas; Button hitungLuas; TextView tampilHasil;//tombolDialog @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); inputTinggi=(EditText) findViewById(R.id.inputTinggi); inputAlas=(EditText) findViewById(R.id.inputAlas); hitungLuas=(Button) findViewById(R.id.tombolhitung); tampilHasil=(TextView) findViewById(R.id.tampilhasil); hitungLuas.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { hitungLuasSegitiga(); snackbarTest(); } }); } private void snackbarTest() { Snackbar snackbar = Snackbar.make( findViewById(R.id.tombolhitung), "Luas Segitiga t'lah Tampil", Snackbar.LENGTH_SHORT ); snackbar.show(); } public void hitungLuasSegitiga(){ try{ Double alas=Double.parseDouble(inputAlas.getText().toString()); Double tinggi=Double.parseDouble(inputTinggi.getText().toString()); Double luas=0.5*alas*tinggi; tampilHasil.setText(luas.toString()); } catch(NumberFormatException e){ tampilHasil.setText("Masukkan angka"); } } public void Pindahs(View view) { Intent intent = new Intent(SecondActivity.this,ThirdActivity.class); startActivity(intent); } }
package com.zantong.mobilecttx.user.dto; /** * Created by zhoujie on 2017/2/22. * 营销代码 */ public class JiaoYiDaiMaDTO { private String filenum; public String getFilenum() { return filenum; } public void setFilenum(String filenum) { this.filenum = filenum; } }
package firstfactor.security.provider; import firstfactor.model.User; import firstfactor.repository.UserRepository; import firstfactor.security.authentication.OTPAuthentication; import firstfactor.security.authentication.UsernamePasswordAuthentication; import firstfactor.security.proxy.OTPAuthenticationServerProxy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import java.util.Optional; @Component public class OTPAuthenticationProvider implements AuthenticationProvider { @Autowired private OTPAuthenticationServerProxy proxy; @Autowired private UserRepository userRepository; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = String.valueOf(authentication.getPrincipal()); String otp = String.valueOf(authentication.getCredentials()); if (username != null && otp != null) { Optional<User> optionalUser = this.userRepository.findByUsername(username); if (optionalUser.isEmpty()) { throw new UsernameNotFoundException("Wrong Credentials"); } User user = optionalUser.get(); boolean result = proxy.validateOTP(user.getId(), otp); if (result) { return new OTPAuthentication(username, otp); } throw new BadCredentialsException("Wrong OTP provided ..."); } else { throw new BadCredentialsException("Username and OTP must not be null"); } } @Override public boolean supports(Class<?> authType) { return OTPAuthentication.class.equals(authType); } }
package com.xh.save; import java.util.List; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.xh.ifaces.IDB; import com.xh.util.XhLog; /** * @version 创建时间:2017-12-26 下午12:44:56 项目:repair 包名:com.xh.save 文件名:DBImpl.java * 作者:lhl 说明: */ public class DBImpl implements IDB { private final static String TAG = DBImpl.class.getName(); @Override public void deleteTable(SQLiteDatabase db, String tableName) { // TODO Auto-generated method stub db.execSQL(DBHelper.dropTable(tableName)); } @Override public void clear(SQLiteDatabase db, String tableName) { // TODO Auto-generated method stub db.execSQL(DBHelper.empty(tableName)); } @Override public void createTable(SQLiteDatabase db, String tableName, List<DBTableEntity> entities) { // TODO Auto-generated method stub XhLog.e(TAG, DBHelper.createTable(tableName, entities)); try { db.execSQL(DBHelper.createTable(tableName, entities)); } catch (Exception e) { // TODO: handle exception } } @Override public long insert(SQLiteDatabase db, String table, ContentValues values) { // TODO Auto-generated method stub return db.insert(table, null, values); } @Override public int delete(SQLiteDatabase db, String table, String whereClause, String[] whereArgs) { // TODO Auto-generated method stub return db.delete(table, whereClause, whereArgs); } @Override public int update(SQLiteDatabase db, String table, ContentValues values, String whereClause, String[] whereArgs) { // TODO Auto-generated method stub return db.update(table, values, whereClause, whereArgs); } @Override public Cursor select(SQLiteDatabase db, String table) { // TODO Auto-generated method stub return db.rawQuery(DBContants.SELECT.replace("tableName", table), null); } @Override public Cursor select(SQLiteDatabase db, String table, List<String> names) { // TODO Auto-generated method stub StringBuffer sb = new StringBuffer(""); for (int i = 0; i < names.size(); i++) { sb.append(names.get(i)).append(","); } String string = sb.substring(0, sb.length() - 1); return db.rawQuery(DBContants.SELECT_COLUMNS.replace("columns", string) .replace("tableName", table), null); } @Override public Cursor select(SQLiteDatabase db, String table, String whereClause, String[] whereArgs) { // TODO Auto-generated method stub return db.rawQuery(DBContants.SELECT.replace("tableName", table) + " WHERE " + whereClause, whereArgs); } @Override public Cursor select(SQLiteDatabase db, String table, String whereClause, String[] whereArgs, List<String> names) { // TODO Auto-generated method stub StringBuffer sb = new StringBuffer(""); for (int i = 0; i < names.size(); i++) { sb.append(names.get(i)).append(","); } String string = sb.substring(0, sb.length() - 1); return db.rawQuery(DBContants.SELECT_COLUMNS.replace("columns", string) .replace("tableName", table) + " WHERE " + whereClause, whereArgs); } }
package dwz.framework.user; /** * @Author: LCF * @Date: 2020/1/8 17:16 * @Package: dwz.framework.user */ public enum UserStatus { PENDING, ACTIVE, INACTIVE, DELETED }
package com.grostore.dao; import java.util.List; import com.grostore.model.Product; public interface ProductDAO { public List<Product> list(); public Product get(String id); public void saveOrUpdate(Product product); public boolean delete(String id); }
package com.hjc.java_common_tools; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Categories.ExcludeCategory; import org.junit.rules.ExpectedException; /** * 个人总结的JDK中容易用错的api。 */ public class JdkEasyWrongPoint { public static void main(String[] args) { } @Test public void testBoolean() { // 坑:Returns true if and only if the system property named by the // argument exists and is equal to the string "true". Assert.assertFalse(Boolean.getBoolean("true")); } /** * 对数字运用要保持敏感:涉及数字计算就要考虑溢出;涉及除法就要考虑被除数是0;实在容纳不下了可以考虑BigDecimal之类。 */ @Test public void testInteger() { // 坑:溢出 long x = Integer.MAX_VALUE + 1; Assert.assertTrue(x < 0); long y = Integer.MAX_VALUE + (long) 1; Assert.assertTrue(y > 0); } @Test public void testSplit() { /** * 坑:String的split,第二个参数为-1,会根据字符串中的分隔符,一直切分到底。 * 默认切分方式是第二个参数为0,则切分到分隔符后端为空值时,就切分结束了。 */ String str1 = ",a,,"; String[] splitResult0 = str1.split(","); Assert.assertEquals(2, splitResult0.length); Assert.assertEquals("[, a]", Arrays.toString(splitResult0)); String[] splitResult1 = str1.split(",", -1); Assert.assertEquals(4, splitResult1.length); Assert.assertEquals("[, a, , ]", Arrays.toString(splitResult1)); // 对比str1,仅仅是分隔符后多了感叹号,这样split参数为0,和-1效果一样。 String str2 = ",a,,!"; String[] split2Result0 = str2.split(","); Assert.assertEquals(4, split2Result0.length); Assert.assertEquals("[, a, , !]", Arrays.toString(split2Result0)); String[] split2Result1 = str2.split(",", -1); Assert.assertEquals(4, split2Result1.length); Assert.assertEquals("[, a, , !]", Arrays.toString(split2Result1)); } @Rule public ExpectedException excepteEX = ExpectedException.none(); @Test public void testAsList() { /** * ArrayList.asList返回的List是不可变的。add,remove等都会抛出异常 */ List<String> aList = Arrays.asList("one", "tow"); Assert.assertEquals("java.util.Arrays$ArrayList", aList.getClass() .getName()); excepteEX.expect(UnsupportedOperationException.class); aList.add("hjc"); } @Test public void testEnumValueOf() { /** * Enum 的 valueOf 方法 */ DB_TYPE mysql = null; // wrong try { mysql = DB_TYPE.valueOf("mysql"); } catch (Exception e) { Assert.assertTrue(true); } // right mysql = DB_TYPE.valueOf("MYSQL"); // right mysql = DB_TYPE.getByTypeName("mysql"); } enum DB_TYPE { MYSQL("mysql"), ORACLE("oracle"), SQLSERVER("sqlserver"),; private String typeName; DB_TYPE(String typeName) { this.typeName = typeName; } @Override public String toString() { return this.typeName; } /** * 用于取代 valueOf()方法;或者内部采用一个 Map 来进行查询都可以. */ public static DB_TYPE getByTypeName(String typeName) { for (DB_TYPE type : values()) { if (type.typeName.equalsIgnoreCase(typeName)) { return type; } } throw new RuntimeException(String.format("cant find typeName:%s. DB_TYPE name should be:%s", typeName, Arrays.asList(values()))); } } }
/** * Copyright 2014 Google * * 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.example.android.io2014; import android.app.Activity; import android.app.ActivityOptions; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.util.SparseArray; import android.view.Menu; import android.view.View; import android.widget.ImageView; public class MainActivity extends Activity { public static SparseArray<Bitmap> sPhotoCache = new SparseArray<Bitmap>(4); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @SuppressWarnings("UnusedDeclaration") public void showPhoto(View view) { Intent intent = new Intent(); intent.setClass(this, DetailActivity.class); switch (view.getId()) { case R.id.show_photo_1: intent.putExtra("lat", 37.6329946); intent.putExtra("lng", -122.4938344); intent.putExtra("zoom", 14.0f); intent.putExtra("title", "Pacifica Pier"); intent.putExtra("description", getResources().getText(R.string.lorem)); intent.putExtra("photo", R.drawable.photo1); break; case R.id.show_photo_2: intent.putExtra("lat", 37.73284); intent.putExtra("lng", -122.503065); intent.putExtra("zoom", 15.0f); intent.putExtra("title", "Pink Flamingo"); intent.putExtra("description", getResources().getText(R.string.lorem)); intent.putExtra("photo", R.drawable.photo2); break; case R.id.show_photo_3: intent.putExtra("lat", 36.861897); intent.putExtra("lng", -111.374438); intent.putExtra("zoom", 11.0f); intent.putExtra("title", "Antelope Canyon"); intent.putExtra("description", getResources().getText(R.string.lorem)); intent.putExtra("photo", R.drawable.photo3); break; case R.id.show_photo_4: intent.putExtra("lat", 36.596125); intent.putExtra("lng", -118.1604282); intent.putExtra("zoom", 9.0f); intent.putExtra("title", "Lone Pine"); intent.putExtra("description", getResources().getText(R.string.lorem)); intent.putExtra("photo", R.drawable.photo4); break; } ImageView hero = (ImageView) ((View) view.getParent()).findViewById(R.id.photo); sPhotoCache.put(intent.getIntExtra("photo", -1), ((BitmapDrawable) hero.getDrawable()).getBitmap()); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(this, hero, "photo_hero"); startActivity(intent, options.toBundle()); } }
/* * 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.web.servlet.view; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Properties; import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.BeanUtils; import org.springframework.context.ApplicationContext; import org.springframework.core.Ordered; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.PatternMatchUtils; import org.springframework.web.servlet.View; /** * Simple implementation of the {@link org.springframework.web.servlet.ViewResolver} * interface, allowing for direct resolution of symbolic view names to URLs, * without explicit mapping definitions. This is useful if your symbolic names * match the names of your view resources in a straightforward manner * (i.e. the symbolic name is the unique part of the resource's filename), * without the need for a dedicated mapping to be defined for each view. * * <p>Supports {@link AbstractUrlBasedView} subclasses like {@link InternalResourceView} * and {@link org.springframework.web.servlet.view.freemarker.FreeMarkerView}. * The view class for all views generated by this resolver can be specified * via the "viewClass" property. * * <p>View names can either be resource URLs themselves, or get augmented by a * specified prefix and/or suffix. Exporting an attribute that holds the * RequestContext to all views is explicitly supported. * * <p>Example: prefix="/WEB-INF/jsp/", suffix=".jsp", viewname="test" &rarr; * "/WEB-INF/jsp/test.jsp" * * <p>As a special feature, redirect URLs can be specified via the "redirect:" * prefix. E.g.: "redirect:myAction" will trigger a redirect to the given * URL, rather than resolution as standard view name. This is typically used * for redirecting to a controller URL after finishing a form workflow. * * <p>Furthermore, forward URLs can be specified via the "forward:" prefix. * E.g.: "forward:myAction" will trigger a forward to the given URL, rather than * resolution as standard view name. This is typically used for controller URLs; * it is not supposed to be used for JSP URLs - use logical view names there. * * <p>Note: This class does not support localized resolution, i.e. resolving * a symbolic view name to different resources depending on the current locale. * * <p><b>Note:</b> When chaining ViewResolvers, a UrlBasedViewResolver will check whether * the {@linkplain AbstractUrlBasedView#checkResource specified resource actually exists}. * However, with {@link InternalResourceView}, it is not generally possible to * determine the existence of the target resource upfront. In such a scenario, * a UrlBasedViewResolver will always return a View for any given view name; * as a consequence, it should be configured as the last ViewResolver in the chain. * * @author Juergen Hoeller * @author Rob Harrop * @author Sam Brannen * @since 13.12.2003 * @see #setViewClass * @see #setPrefix * @see #setSuffix * @see #setRequestContextAttribute * @see #REDIRECT_URL_PREFIX * @see AbstractUrlBasedView * @see InternalResourceView * @see org.springframework.web.servlet.view.freemarker.FreeMarkerView */ public class UrlBasedViewResolver extends AbstractCachingViewResolver implements Ordered { /** * Prefix for special view names that specify a redirect URL (usually * to a controller after a form has been submitted and processed). * Such view names will not be resolved in the configured default * way but rather be treated as special shortcut. */ public static final String REDIRECT_URL_PREFIX = "redirect:"; /** * Prefix for special view names that specify a forward URL (usually * to a controller after a form has been submitted and processed). * Such view names will not be resolved in the configured default * way but rather be treated as special shortcut. */ public static final String FORWARD_URL_PREFIX = "forward:"; @Nullable private Class<?> viewClass; private String prefix = ""; private String suffix = ""; @Nullable private String contentType; private boolean redirectContextRelative = true; private boolean redirectHttp10Compatible = true; @Nullable private String[] redirectHosts; @Nullable private String requestContextAttribute; /** Map of static attributes, keyed by attribute name (String). */ private final Map<String, Object> staticAttributes = new HashMap<>(); @Nullable private Boolean exposePathVariables; @Nullable private Boolean exposeContextBeansAsAttributes; @Nullable private String[] exposedContextBeanNames; @Nullable private String[] viewNames; private int order = Ordered.LOWEST_PRECEDENCE; /** * Set the view class that should be used to create views. * @param viewClass a class that is assignable to the required view class * (by default: AbstractUrlBasedView) * @see #requiredViewClass() * @see #instantiateView() * @see AbstractUrlBasedView */ public void setViewClass(@Nullable Class<?> viewClass) { if (viewClass != null && !requiredViewClass().isAssignableFrom(viewClass)) { throw new IllegalArgumentException("Given view class [" + viewClass.getName() + "] is not of type [" + requiredViewClass().getName() + "]"); } this.viewClass = viewClass; } /** * Return the view class to be used to create views. * @see #setViewClass */ @Nullable protected Class<?> getViewClass() { return this.viewClass; } /** * Set the prefix that gets prepended to view names when building a URL. */ public void setPrefix(@Nullable String prefix) { this.prefix = (prefix != null ? prefix : ""); } /** * Return the prefix that gets prepended to view names when building a URL. */ protected String getPrefix() { return this.prefix; } /** * Set the suffix that gets appended to view names when building a URL. */ public void setSuffix(@Nullable String suffix) { this.suffix = (suffix != null ? suffix : ""); } /** * Return the suffix that gets appended to view names when building a URL. */ protected String getSuffix() { return this.suffix; } /** * Set the content type for all views. * <p>May be ignored by view classes if the view itself is assumed * to set the content type, e.g. in case of JSPs. */ public void setContentType(@Nullable String contentType) { this.contentType = contentType; } /** * Return the content type for all views, if any. */ @Nullable protected String getContentType() { return this.contentType; } /** * Set whether to interpret a given redirect URL that starts with a * slash ("/") as relative to the current ServletContext, i.e. as * relative to the web application root. * <p>Default is "true": A redirect URL that starts with a slash will be * interpreted as relative to the web application root, i.e. the context * path will be prepended to the URL. * <p><b>Redirect URLs can be specified via the "redirect:" prefix.</b> * E.g.: "redirect:myAction" * @see RedirectView#setContextRelative * @see #REDIRECT_URL_PREFIX */ public void setRedirectContextRelative(boolean redirectContextRelative) { this.redirectContextRelative = redirectContextRelative; } /** * Return whether to interpret a given redirect URL that starts with a * slash ("/") as relative to the current ServletContext, i.e. as * relative to the web application root. */ protected boolean isRedirectContextRelative() { return this.redirectContextRelative; } /** * Set whether redirects should stay compatible with HTTP 1.0 clients. * <p>In the default implementation, this will enforce HTTP status code 302 * in any case, i.e. delegate to {@code HttpServletResponse.sendRedirect}. * Turning this off will send HTTP status code 303, which is the correct * code for HTTP 1.1 clients, but not understood by HTTP 1.0 clients. * <p>Many HTTP 1.1 clients treat 302 just like 303, not making any * difference. However, some clients depend on 303 when redirecting * after a POST request; turn this flag off in such a scenario. * <p><b>Redirect URLs can be specified via the "redirect:" prefix.</b> * E.g.: "redirect:myAction" * @see RedirectView#setHttp10Compatible * @see #REDIRECT_URL_PREFIX */ public void setRedirectHttp10Compatible(boolean redirectHttp10Compatible) { this.redirectHttp10Compatible = redirectHttp10Compatible; } /** * Return whether redirects should stay compatible with HTTP 1.0 clients. */ protected boolean isRedirectHttp10Compatible() { return this.redirectHttp10Compatible; } /** * Configure one or more hosts associated with the application. * All other hosts will be considered external hosts. * <p>In effect, this property provides a way turn off encoding on redirect * via {@link HttpServletResponse#encodeRedirectURL} for URLs that have a * host and that host is not listed as a known host. * <p>If not set (the default) all URLs are encoded through the response. * @param redirectHosts one or more application hosts * @since 4.3 */ public void setRedirectHosts(@Nullable String... redirectHosts) { this.redirectHosts = redirectHosts; } /** * Return the configured application hosts for redirect purposes. * @since 4.3 */ @Nullable public String[] getRedirectHosts() { return this.redirectHosts; } /** * Set the name of the RequestContext attribute for all views. * @param requestContextAttribute name of the RequestContext attribute * @see AbstractView#setRequestContextAttribute */ public void setRequestContextAttribute(@Nullable String requestContextAttribute) { this.requestContextAttribute = requestContextAttribute; } /** * Return the name of the RequestContext attribute for all views, if any. */ @Nullable protected String getRequestContextAttribute() { return this.requestContextAttribute; } /** * Set static attributes from a {@code java.util.Properties} object, * for all views returned by this resolver. * <p>This is the most convenient way to set static attributes. Note that * static attributes can be overridden by dynamic attributes, if a value * with the same name is included in the model. * <p>Can be populated with a String "value" (parsed via PropertiesEditor) * or a "props" element in XML bean definitions. * @see org.springframework.beans.propertyeditors.PropertiesEditor * @see AbstractView#setAttributes */ public void setAttributes(Properties props) { CollectionUtils.mergePropertiesIntoMap(props, this.staticAttributes); } /** * Set static attributes from a Map, for all views returned by this resolver. * This allows to set any kind of attribute values, for example bean references. * <p>Can be populated with a "map" or "props" element in XML bean definitions. * @param attributes a Map with name Strings as keys and attribute objects as values * @see AbstractView#setAttributesMap */ public void setAttributesMap(@Nullable Map<String, ?> attributes) { if (attributes != null) { this.staticAttributes.putAll(attributes); } } /** * Allow {@code Map} access to the static attributes for views returned by * this resolver, with the option to add or override specific entries. * <p>Useful for specifying entries directly, for example via * {@code attributesMap[myKey]}. This is particularly useful for * adding or overriding entries in child view definitions. */ public Map<String, Object> getAttributesMap() { return this.staticAttributes; } /** * Specify whether views resolved by this resolver should add path * variables to the model or not. * <p>The default setting is to let each View decide * (see {@link AbstractView#setExposePathVariables}). However, you * can use this property to override that. * @param exposePathVariables * <ul> * <li>{@code true} - all Views resolved by this resolver will expose path variables * <li>{@code false} - no Views resolved by this resolver will expose path variables * <li>{@code null} - individual Views can decide for themselves (this is used by default) * </ul> * @see AbstractView#setExposePathVariables */ public void setExposePathVariables(@Nullable Boolean exposePathVariables) { this.exposePathVariables = exposePathVariables; } /** * Return whether views resolved by this resolver should add path variables to the model or not. */ @Nullable protected Boolean getExposePathVariables() { return this.exposePathVariables; } /** * Set whether to make all Spring beans in the application context accessible * as request attributes, through lazy checking once an attribute gets accessed. * <p>This will make all such beans accessible in plain {@code ${...}} * expressions in a JSP 2.0 page, as well as in JSTL's {@code c:out} * value expressions. * <p>Default is "false". * @see AbstractView#setExposeContextBeansAsAttributes */ public void setExposeContextBeansAsAttributes(boolean exposeContextBeansAsAttributes) { this.exposeContextBeansAsAttributes = exposeContextBeansAsAttributes; } @Nullable protected Boolean getExposeContextBeansAsAttributes() { return this.exposeContextBeansAsAttributes; } /** * Specify the names of beans in the context which are supposed to be exposed. * If this is non-null, only the specified beans are eligible for exposure as * attributes. * @see AbstractView#setExposedContextBeanNames */ public void setExposedContextBeanNames(@Nullable String... exposedContextBeanNames) { this.exposedContextBeanNames = exposedContextBeanNames; } @Nullable protected String[] getExposedContextBeanNames() { return this.exposedContextBeanNames; } /** * Set the view names (or name patterns) that can be handled by this * {@link org.springframework.web.servlet.ViewResolver}. View names can contain * simple wildcards such that 'my*', '*Report' and '*Repo*' will all match the * view name 'myReport'. * @see #canHandle */ public void setViewNames(@Nullable String... viewNames) { this.viewNames = viewNames; } /** * Return the view names (or name patterns) that can be handled by this * {@link org.springframework.web.servlet.ViewResolver}. */ @Nullable protected String[] getViewNames() { return this.viewNames; } /** * Specify the order value for this ViewResolver bean. * <p>The default value is {@code Ordered.LOWEST_PRECEDENCE}, meaning non-ordered. * @see org.springframework.core.Ordered#getOrder() */ public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } @Override protected void initApplicationContext() { super.initApplicationContext(); if (getViewClass() == null) { throw new IllegalArgumentException("Property 'viewClass' is required"); } } /** * This implementation returns just the view name, * as this ViewResolver doesn't support localized resolution. */ @Override protected Object getCacheKey(String viewName, Locale locale) { return viewName; } /** * Overridden to implement check for "redirect:" prefix. * <p>Not possible in {@code loadView}, since overridden * {@code loadView} versions in subclasses might rely on the * superclass always creating instances of the required view class. * @see #loadView * @see #requiredViewClass */ @Override protected View createView(String viewName, Locale locale) throws Exception { // If this resolver is not supposed to handle the given view, // return null to pass on to the next resolver in the chain. if (!canHandle(viewName, locale)) { return null; } // Check for special "redirect:" prefix. if (viewName.startsWith(REDIRECT_URL_PREFIX)) { String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length()); RedirectView view = new RedirectView(redirectUrl, isRedirectContextRelative(), isRedirectHttp10Compatible()); String[] hosts = getRedirectHosts(); if (hosts != null) { view.setHosts(hosts); } return applyLifecycleMethods(REDIRECT_URL_PREFIX, view); } // Check for special "forward:" prefix. if (viewName.startsWith(FORWARD_URL_PREFIX)) { String forwardUrl = viewName.substring(FORWARD_URL_PREFIX.length()); InternalResourceView view = new InternalResourceView(forwardUrl); return applyLifecycleMethods(FORWARD_URL_PREFIX, view); } // Else fall back to superclass implementation: calling loadView. return super.createView(viewName, locale); } /** * Indicates whether this {@link org.springframework.web.servlet.ViewResolver} can * handle the supplied view name. If not, {@link #createView(String, java.util.Locale)} will * return {@code null}. The default implementation checks against the configured * {@link #setViewNames view names}. * @param viewName the name of the view to retrieve * @param locale the Locale to retrieve the view for * @return whether this resolver applies to the specified view * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) */ protected boolean canHandle(String viewName, Locale locale) { String[] viewNames = getViewNames(); return (viewNames == null || PatternMatchUtils.simpleMatch(viewNames, viewName)); } /** * Return the required type of view for this resolver. * This implementation returns {@link AbstractUrlBasedView}. * @see #instantiateView() * @see AbstractUrlBasedView */ protected Class<?> requiredViewClass() { return AbstractUrlBasedView.class; } /** * Instantiate the specified view class. * <p>The default implementation uses reflection to instantiate the class. * @return a new instance of the view class * @since 5.3 * @see #setViewClass */ protected AbstractUrlBasedView instantiateView() { Class<?> viewClass = getViewClass(); Assert.state(viewClass != null, "No view class"); return (AbstractUrlBasedView) BeanUtils.instantiateClass(viewClass); } /** * Delegates to {@code buildView} for creating a new instance of the * specified view class. Applies the following Spring lifecycle methods * (as supported by the generic Spring bean factory): * <ul> * <li>ApplicationContextAware's {@code setApplicationContext} * <li>InitializingBean's {@code afterPropertiesSet} * </ul> * @param viewName the name of the view to retrieve * @return the View instance * @throws Exception if the view couldn't be resolved * @see #buildView(String) * @see org.springframework.context.ApplicationContextAware#setApplicationContext * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet */ @Override protected View loadView(String viewName, Locale locale) throws Exception { AbstractUrlBasedView view = buildView(viewName); View result = applyLifecycleMethods(viewName, view); return (view.checkResource(locale) ? result : null); } /** * Creates a new View instance of the specified view class and configures it. * Does <i>not</i> perform any lookup for pre-defined View instances. * <p>Spring lifecycle methods as defined by the bean container do not have to * be called here; those will be applied by the {@code loadView} method * after this method returns. * <p>Subclasses will typically call {@code super.buildView(viewName)} * first, before setting further properties themselves. {@code loadView} * will then apply Spring lifecycle methods at the end of this process. * @param viewName the name of the view to build * @return the View instance * @throws Exception if the view couldn't be resolved * @see #loadView(String, java.util.Locale) */ protected AbstractUrlBasedView buildView(String viewName) throws Exception { AbstractUrlBasedView view = instantiateView(); view.setUrl(getPrefix() + viewName + getSuffix()); view.setAttributesMap(getAttributesMap()); String contentType = getContentType(); if (contentType != null) { view.setContentType(contentType); } String requestContextAttribute = getRequestContextAttribute(); if (requestContextAttribute != null) { view.setRequestContextAttribute(requestContextAttribute); } Boolean exposePathVariables = getExposePathVariables(); if (exposePathVariables != null) { view.setExposePathVariables(exposePathVariables); } Boolean exposeContextBeansAsAttributes = getExposeContextBeansAsAttributes(); if (exposeContextBeansAsAttributes != null) { view.setExposeContextBeansAsAttributes(exposeContextBeansAsAttributes); } String[] exposedContextBeanNames = getExposedContextBeanNames(); if (exposedContextBeanNames != null) { view.setExposedContextBeanNames(exposedContextBeanNames); } return view; } /** * Apply the containing {@link ApplicationContext}'s lifecycle methods * to the given {@link View} instance, if such a context is available. * @param viewName the name of the view * @param view the freshly created View instance, pre-configured with * {@link AbstractUrlBasedView}'s properties * @return the {@link View} instance to use (either the original one * or a decorated variant) * @since 5.0 * @see #getApplicationContext() * @see ApplicationContext#getAutowireCapableBeanFactory() * @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#initializeBean */ protected View applyLifecycleMethods(String viewName, AbstractUrlBasedView view) { ApplicationContext context = getApplicationContext(); if (context != null) { Object initialized = context.getAutowireCapableBeanFactory().initializeBean(view, viewName); if (initialized instanceof View initializedView) { return initializedView; } } return view; } }
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations; import org.giddap.dreamfactory.leetcode.onlinejudge.BestTimeToBuyAndSellStockIII; public class BestTimeToBuyAndSellStockIIIOn2Impl implements BestTimeToBuyAndSellStockIII { @Override public int maxProfit(int[] prices) { // Note: The Solution object is instantiated only once and is reused by each test case. int mp = Integer.MIN_VALUE; for (int i = 1; i < prices.length - 1; i++) { mp = Math.max( mp, Math.max(0, maxProfitByRange(prices, 0, i)) + Math.max(0, maxProfitByRange(prices, i + 1, prices.length - 1))); } return mp; } private int maxProfitByRange(int[] prices, int start, int end) { if (start >= end) { return 0; } int[] minValues = new int[prices.length]; minValues[start] = prices[start]; int mp = Integer.MIN_VALUE; for (int i = start + 1; i <= end; i++) { minValues[i] = Math.min(minValues[i - 1], prices[i - 1]); mp = Math.max(mp, prices[i] - minValues[i]); } return mp; } }
// // Decompiled by Procyon v0.5.36 // package com.davivienda.sara.tablas.confmodulosaplicacion.servicio; import com.davivienda.sara.base.exception.EntityServicioExcepcion; import javax.persistence.EntityManager; import com.davivienda.sara.entitys.config.ConfModulosAplicacion; import com.davivienda.sara.base.BaseEntityServicio; public class ConfModulosAplicacionServicio extends BaseEntityServicio<ConfModulosAplicacion> { public ConfModulosAplicacionServicio(final EntityManager em) { super(em, ConfModulosAplicacion.class); } @Override public ConfModulosAplicacion actualizar(final ConfModulosAplicacion objetoModificado) throws EntityServicioExcepcion { ConfModulosAplicacion objetoActual = super.buscar(objetoModificado.getConfModulosAplicacionPK()); if (objetoActual == null) { super.adicionar(objetoModificado); objetoActual = super.buscar(objetoModificado.getConfModulosAplicacionPK()); } else { objetoActual.actualizarEntity(objetoModificado); objetoActual = super.actualizar(objetoActual); } return objetoActual; } @Override public void borrar(final ConfModulosAplicacion entity) throws EntityServicioExcepcion { final ConfModulosAplicacion objetoActual = super.buscar(entity.getConfModulosAplicacionPK()); super.borrar(objetoActual); } }
public class GeneratorAppliance extends Appliance { private int time;// measures how many times timePasses() has been called /** * timeOn here shows how many timePasses() calls it takes for GeneratorAppliance to generate electricity * The electricityUse represents how much electricity it generates */ public GeneratorAppliance(int electricityUse, int gasUse, int waterUse, int timeOn, House myhouse) { super(electricityUse, gasUse, waterUse, timeOn, myhouse); taskName = "Generate"; time = timeOn; } /** * It can work only if the meter can generate electricity. * It will appear as an error if there is a GeneratorAppliance but the electric meter cannot generate */ protected void setMeter(House myhouse) { if (myhouse.getElectricMeter().canGenerate()) { this.electricMeter = myhouse.getElectricMeter(); } else System.err.println("The meter cannot generate electricity"); } /** * It generates electricity when time is 0 . * It depends on how many timePasses calls ahve to pass. */ protected void timePasses() { time--; if (time == 0) { if (electricityUse == 1) { electricMeter.incrementGenerated(); } else for (int i = 1; i <= electricityUse; i++) { electricMeter.incrementGenerated(); } time = timeOn; } } }
package com.spring.boot.rocks.controller; import com.spring.boot.rocks.domain.Pet; import com.spring.boot.rocks.repository.PetRepository; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.ResponseBody; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.time.Duration; @Controller public class PetController { private final PetRepository petRepository; public PetController(PetRepository petRepository) { this.petRepository = petRepository; } @GetMapping(value = "/pets", produces = MediaType.TEXT_EVENT_STREAM_VALUE) @ResponseBody Flux<Pet> findPets() { return petRepository.findWithTailableCursorBy().delayElements(Duration.ofMillis(3000)); } @GetMapping(value = "/pets/{id}") Mono<Pet> findById(@PathVariable String id) { return petRepository.findPetById(id); } @GetMapping("/") Mono<String> home() { return Mono.just("pets"); } }
package com.mabang.android.okhttp.loadimg; import android.graphics.Bitmap; import android.os.Environment; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * Created by suxq on 2017/4/7. */ public class ImgFileUtils { private static final String TAG = "ImgFileUtils"; /** * 判断外部存储是否可用 * * @return true: 可用 */ public static boolean isSDcardAvailable() { String state = Environment.getExternalStorageState(); return Environment.MEDIA_MOUNTED.equals(state); } /** * 复制文件,默认删除原文件 * * @param sourceFile * @param destFile destFile的所在文件夹必须先存在 */ public static void copyFile(File sourceFile, File destFile) { copyFile(sourceFile, destFile, true); } /** * 复制文件, 默认 * * @param sourceFile * @param destFile destFile的所在文件夹必须先存在 * @param isDeleteSource */ public static boolean copyFile(File sourceFile, File destFile, boolean isDeleteSource) { try { if (!sourceFile.exists()) { Log.i("walke", "copyFile: --------------sourceFile不存在"); return false; } if (!checkAndInitFile(destFile)) {//当目标文件不存在 Log.i("walke", "copyFile: --------------destFile 初始化失败"); return false; } int byteRead = 0; if (sourceFile.exists()) { FileInputStream is = new FileInputStream(sourceFile); FileOutputStream os = new FileOutputStream(destFile); byte[] buffer = new byte[1024]; while ((byteRead = is.read(buffer)) != -1) { os.write(buffer, 0, byteRead); } if (isDeleteSource) { sourceFile.delete(); } is.close(); os.close(); } } catch (Exception e) { e.printStackTrace(); } return false; } /** 检测file,当存在是直接return true, * @param destFile * @return true:文件存在或者初始化成功,false:文件不存在或初始化失败 */ public static boolean checkAndInitFile(File destFile) { try { if (destFile.exists()) return true; File parentFile = destFile.getParentFile(); if (!parentFile.exists()) { boolean mkdirs = parentFile.mkdirs();//当有比较多层文件夹时使用,只有一层父目录也推荐使用 Log.i("walke", "checkAndInitFile: mkdirs = " + mkdirs); if (mkdirs) { destFile.createNewFile(); return true; } } else { destFile.createNewFile(); return true; } } catch (IOException e) { e.printStackTrace(); } return false; } /** * 检测file,当存在并可以转成图片 return true,否则初始化文件,并return false * //3.用Bitmap工厂转化。try catch一下,异常则删除并重新下载 * * @param destFile * @return */ public static boolean checkInitImageFile(File destFile) { try { Bitmap bitmap = ImgBitmapUtil.getBitmap(destFile.getAbsolutePath()); if (bitmap != null) { return true; } else { if (!destFile.exists()) { File parentFile = destFile.getParentFile(); if (!parentFile.exists()) { boolean mkdirs = parentFile.mkdirs();//当有比较多层文件夹时使用,只有一层父目录也推荐使用 Log.i("walke", "checkAndInitFile: mkdirs = " + mkdirs); if (mkdirs) destFile.createNewFile(); } else { destFile.createNewFile(); } } } } catch (Exception e) { e.printStackTrace(); } return false; } }
/* NMS-DRIVERS -- Free NMS packages. * Copyright (C) 2009 Andrew A. Porohin * * NMS-DRIVERS is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 2.1 of the License. * * NMS-DRIVERS 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with NMS-DRIVERS. If not, see <http://www.gnu.org/licenses/>. */ package org.aap.nms.performance.server; import java.util.Calendar; import java.util.TimeZone; import java.util.logging.Level; import org.doomdark.uuid.UUID; import org.valabs.odisp.common.Message; import org.valabs.odisp.common.StandartODObject; import org.valabs.stdmsg.ODObjectLoadedMessage; import com.novel.nms.messages.LogEventMessage; import com.novel.nms.server.devices.common.Device; /** * This class developed to measure performance of logEvent store * process. * * @author (C) 2008 Andrew Porokhin <andrew.porokhin@gmail.com> * @version 1.0 */ public class LogEventGenerator extends StandartODObject implements Runnable { private static final String NAME = "loggenerator"; private static final String FULLNAME = "Log Event Generator"; private static final String VERSION = "0.0"; private static final String COPYRIGHT = "(C) 2008 Andrew Porokhin"; private static final String DEVICE_NAME = "one"; /** Report about progress every 10 second. */ private static final long REPORT_TIME = 5000; /** Worker thread. */ private Thread worker; public LogEventGenerator() { super(NAME, FULLNAME, VERSION, COPYRIGHT); } public void handleMessage(Message msg) { if (ODObjectLoadedMessage.equals(msg)) { worker = new Thread(this, "EventGeneratorThread"); worker.start(); } } public int cleanUp(int type) { worker.interrupt(); return super.cleanUp(type); } /* (non-Javadoc) * @see org.valabs.odisp.common.ODObject#getDepends() */ public String[] getDepends() { String[] result = { "dispatcher", com.novel.nms.server.storage.Storage.class.getName(), // com.novel.nms.server.devices.common.DeviceList.class.getName(), }; return result; } /* (non-Javadoc) * @see org.valabs.odisp.common.ODObject#getProviding() */ public String[] getProviding() { String[] result = { NAME }; return result; } public void run() { long logEventSent = 0; long logEventSentReport = 0; Calendar c = Calendar.getInstance(TimeZone.getDefault()); long initialTime = c.getTimeInMillis(); long currentTime = initialTime; long lastReportTime = currentTime; logger.info("Event generator thread started."); while (!Thread.interrupted()) { c = Calendar.getInstance(TimeZone.getDefault()); currentTime = c.getTimeInMillis(); Long date = new Long(currentTime / 1000); Message m = dispatcher.getNewMessage(); LogEventMessage.setup(m, "nmslog", getObjectName(), UUID.getNullUUID()); LogEventMessage.setName(m, DEVICE_NAME); LogEventMessage.setSource(m, DEVICE_NAME); LogEventMessage.setDate(m, date); LogEventMessage.setLDate(m, date); LogEventMessage.setIndex(m, Device.POLL_TIMEOUT_EVENT_IDX); LogEventMessage.setEvent(m, LogEventMessage.ALARM_POLL_TIMEOUT); LogEventMessage.setObject(m, ""); LogEventMessage.setPC(m, "Poll timeout"); LogEventMessage.setAI(m, ""); LogEventMessage.setEquipStatus(m, LogEventMessage.ALARM_POLL_TIMEOUT); m.setRoutable(false); dispatcher.send(m); logEventSent++; logEventSentReport++; if (logger.isLoggable(Level.INFO)) { if (currentTime - lastReportTime > REPORT_TIME) { logger.info("LOG GENERATOR REPORT...\n" + "Elapsed: " + (currentTime - lastReportTime) + " msec\n" + "Messages: " + logEventSentReport + " in " + (currentTime - lastReportTime) + " ms\n" + "Rate aprox.: " + (logEventSentReport/((currentTime - lastReportTime)/1000)) + " log per second\n" + "Total messages: " + logEventSent + " in " + (currentTime - initialTime) + " ms\n" + "Global rate aprox.: " + (logEventSent/((currentTime - initialTime)/1000)) + " log per second"); logEventSentReport = 0; lastReportTime = currentTime; } } /* c = Calendar.getInstance(TimeZone.getDefault()); if (c.getTimeInMillis() - currentTime < 1) { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } */ } logger.info("Event generator thread stopped."); } }
package com.framgia.fsalon.screen.booking; import android.text.TextUtils; import com.framgia.fsalon.R; import com.framgia.fsalon.data.model.BookingOder; import com.framgia.fsalon.data.model.BookingRender; import com.framgia.fsalon.data.model.BookingResponse; import com.framgia.fsalon.data.model.DateBooking; import com.framgia.fsalon.data.model.Salon; import com.framgia.fsalon.data.model.Stylist; import com.framgia.fsalon.data.model.UserRespone; import com.framgia.fsalon.data.source.BookingRepository; import com.framgia.fsalon.data.source.SalonRepository; import com.framgia.fsalon.data.source.StylistRepository; import com.framgia.fsalon.data.source.UserRepository; import com.framgia.fsalon.utils.Utils; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import io.reactivex.observers.DisposableObserver; import io.reactivex.schedulers.Schedulers; import static com.framgia.fsalon.utils.Constant.A_DAY; import static com.framgia.fsalon.utils.Constant.Permission.PERMISSION_NOMAL; /** * Listens to user actions from the UI ({@link BookingFragment}), retrieves the data and updates * the UI as required. */ public class BookingPresenter implements BookingContract.Presenter { private static final String TAG = BookingPresenter.class.getName(); private final BookingContract.ViewModel mViewModel; private CompositeDisposable mCompositeDisposable = new CompositeDisposable(); private BookingRepository mBookingRepository; private SalonRepository mSalonRepository; private StylistRepository mStylistRepository; private UserRepository mUserRepository; public BookingPresenter(BookingContract.ViewModel viewModel, BookingRepository bookingRepository, SalonRepository salonRepository, StylistRepository stylistRepository, UserRepository userRepository) { mViewModel = viewModel; mBookingRepository = bookingRepository; mSalonRepository = salonRepository; mStylistRepository = stylistRepository; mUserRepository = userRepository; } @Override public void onStart() { getDateBooking(); getAllSalons(); } @Override public void onStop() { mCompositeDisposable.clear(); } @Override public void getCustomer() { Disposable disposable = mUserRepository.getCurrentUser() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(new DisposableObserver<UserRespone>() { @Override public void onNext(@NonNull UserRespone userRespone) { if (userRespone.getUser().getPermission() == PERMISSION_NOMAL) { mViewModel.onCustomer(userRespone.getUser().getName(), userRespone.getUser().getPhone()); } } @Override public void onError(@NonNull Throwable e) { mViewModel.onNotCustomer(); } @Override public void onComplete() { } }); mCompositeDisposable.add(disposable); } @Override public void getAllSalons() { Disposable disposable = mSalonRepository.getAllSalons() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(@NonNull Disposable disposable) throws Exception { mViewModel.showProgressbar(); } }) .subscribeWith( new DisposableObserver<List<Salon>>() { @Override public void onNext(@NonNull List<Salon> salons) { mViewModel.onGetSalonsSuccess(salons); } @Override public void onError(@NonNull Throwable e) { mViewModel.hideProgressbar(); mViewModel.onError(e.getMessage()); } @Override public void onComplete() { mViewModel.hideProgressbar(); } }); mCompositeDisposable.add(disposable); } @Override public void getAllStylists(int id) { Disposable disposable = mStylistRepository.getAllStylists(id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(@NonNull Disposable disposable) throws Exception { mViewModel.showProgressbar(); } }).subscribeWith(new DisposableObserver<List<Stylist>>() { @Override public void onNext(@NonNull List<Stylist> stylists) { mViewModel.onGetStylistSuccess(stylists); } @Override public void onError(@NonNull Throwable e) { mViewModel.hideProgressbar(); mViewModel.onError(e.getMessage()); } @Override public void onComplete() { mViewModel.hideProgressbar(); } }); mCompositeDisposable.add(disposable); } @Override public void getBookings(int salonId, long time, int stylelistId) { Disposable disposable = mBookingRepository.getBookings(salonId, time, stylelistId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(@NonNull Disposable disposable) throws Exception { mViewModel.showProgressbar(); } }).subscribeWith(new DisposableObserver<BookingResponse>() { @Override public void onNext(@NonNull BookingResponse bookingResponse) { mViewModel.onGetBookingSuccess(bookingResponse); } @Override public void onError(@NonNull Throwable e) { mViewModel.hideProgressbar(); mViewModel.onError(e.getMessage()); } @Override public void onComplete() { mViewModel.hideProgressbar(); } }); mCompositeDisposable.add(disposable); } @Override public void getBookings(int salonId, long time) { Disposable disposable = mBookingRepository.getBookings(salonId, time) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(@NonNull Disposable disposable) throws Exception { mViewModel.showProgressbar(); } }).subscribeWith(new DisposableObserver<BookingResponse>() { @Override public void onNext(@NonNull BookingResponse bookingResponse) { mViewModel.onGetBookingSuccess(bookingResponse); } @Override public void onError(@NonNull Throwable e) { mViewModel.hideProgressbar(); mViewModel.onError(e.getMessage()); } @Override public void onComplete() { mViewModel.hideProgressbar(); } }); mCompositeDisposable.add(disposable); } @Override public void getDateBooking() { List<DateBooking> dateBookings = new ArrayList<>(); dateBookings.add(new DateBooking(mViewModel.getStringRes(R.string.title_today), System.currentTimeMillis())); dateBookings.add( new DateBooking(mViewModel.getStringRes(R.string.title_tomorrow), System.currentTimeMillis() + A_DAY)); dateBookings .add(new DateBooking(mViewModel.getStringRes(R.string.title_after_tomorrow), System.currentTimeMillis() + A_DAY * 2)); mViewModel.onGetDateBookingSuccess(dateBookings); } @Override public void book(String phone, String name, int renderBookingId, int stylistId) { if (!validateDataInput(phone, name, renderBookingId)) { return; } mUserRepository.saveCurrentPhone(phone); Disposable disposable = mBookingRepository.book(phone, name, renderBookingId, stylistId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(@NonNull Disposable disposable) throws Exception { mViewModel.showProgressbar(); } }).subscribeWith(new DisposableObserver<BookingOder>() { @Override public void onNext(@NonNull BookingOder bookingOder) { mViewModel.onBookSuccess(bookingOder); } @Override public void onError(@NonNull Throwable e) { mViewModel.hideProgressbar(); mViewModel.onError(e.getMessage()); } @Override public void onComplete() { mViewModel.hideProgressbar(); } }); mCompositeDisposable.add(disposable); } @Override public void setDatePosition(BookingOder bookingOder, List<DateBooking> dateBookings) { if (bookingOder.getStatus() != BookingOder.STATUS_IN_LATE) { for (DateBooking dateBooking : dateBookings) { try { if (Utils.isSameDate(dateBooking.getDateTime(), bookingOder.getRender().getDay())) { mViewModel.setDateAndTime(dateBookings.indexOf(dateBooking), dateBooking.getTimeMillis()); } } catch (ParseException e) { mViewModel.onNoDate(); } } return; } mViewModel.setDateAndTime(BookingViewModel.FIRST_ITEM, System.currentTimeMillis() / 1000); } @Override public void setSalonPosition(BookingOder bookingOder, List<Salon> salons) { for (Salon s : salons) { if (s.getName().equals(bookingOder.getDepartment().getName())) { mViewModel.selectedSalonPosition(salons.indexOf(s), s); } } } @Override public void setTimePosition(BookingOder bookingOder, BookingResponse bookingResponse) { for (BookingRender render : bookingResponse.getRenders()) { if (render.getTimeStart().equals(bookingOder.getRender().getTimeStart())) { mViewModel .selectedTimePosition(bookingResponse.getRenders().indexOf(render), render); } } } @Override public void setStylist(BookingOder bookingOder, List<Stylist> stylists) { for (Stylist s : stylists) { if (s.getName().equals(bookingOder.getStylist().getName())) { mViewModel.setStylist(stylists.indexOf(s)); } } } public boolean validateDataInput(String phone, String name, int renderBookingId) { boolean isValid = true; if (TextUtils.isEmpty(phone)) { isValid = false; mViewModel.onInputPhoneError(); } if (TextUtils.isEmpty(name)) { isValid = false; mViewModel.onInputNameError(); } if (renderBookingId <= 0) { isValid = false; mViewModel.onInputTimeError(); } return isValid; } }
public class HeadTailPlacement { public INode head; public INode tail; public HeadTailPlacement() { this.head = null; this.tail = null; } public void add(INode newNode) { if (this.tail == null) { this.tail = newNode; } if (this.head == null) { this.head = newNode; } else { INode tempNode = this.head; this.head = newNode; this.head.setNext(tempNode); } } }
package org.security.authentication; import org.data.persistance.model.Users; import org.data.persistance.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; public class CustomAuthenticationProvider extends DaoAuthenticationProvider{ @Autowired private UserRepository userRepo; @Override public Authentication authenticate(Authentication auth) throws AuthenticationException { Users user = userRepo.findByUsernameAndActive(auth.getName(),true); if(user==null) { throw new BadCredentialsException("Invalid username or password"); } final Authentication result = super.authenticate(auth); return new UsernamePasswordAuthenticationToken(user, result.getCredentials(),result.getAuthorities()); } }
package LojaCadastro.Controller.Dto; import java.util.List; import java.util.stream.Collectors; import LojaCadastro.Modelo.Produto; ////////////// CLASSE DTO/////////// public class ProdutoDto { ////// INFOS///////////////// private Long id; private String descricao; private double precoUnitario; //// GET E SET public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public double getPrecoUnitario() { return precoUnitario; } public void setPrecoUnitario(double precoUnitario) { this.precoUnitario = precoUnitario; } ////////////////CONSTRUCTOR//////////////// public static ProdutoDto converter(Produto produto) { ProdutoDto pDto = new ProdutoDto(); pDto.setDescricao(produto.getNomeProduto()); pDto.setPrecoUnitario(produto.getPreco()); return pDto; } public static List<ProdutoDto> converter(List<Produto> produto){ return produto.stream().map(prod -> converter (prod)).collect(Collectors.toList()); } }
package hello.data.holo; /** * Created by arabbani on 11/19/16. */ public class HoloDto { }
package com.github.jearls.SPRaceTracker.data; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.SequenceGenerator; import javax.persistence.Transient; import com.github.jearls.SPRaceTracker.data.SeasonObserver.SeasonElement; /** * @author jearls */ @Entity @IdentifiedBy("name") public class Season { // When adding new fields or changing fields, make sure to update // serialVersionUID. public static final long serialVersionUID = 1L; @Id public UUID id; public String name; @ManyToMany(cascade = CascadeType.ALL) public List<Team> teams; @OneToMany(mappedBy = "season", cascade = CascadeType.ALL) public List<Race> races; @OrderBy @SequenceGenerator(name = "SeasonOrder", allocationSize = 1, initialValue = 1) public int seasonOrder; // The observer handling code /** * The list of observers for this Team. */ @Transient Set<SeasonObserver> observers = new HashSet<SeasonObserver>(); /** * Adds a new observer. * * @param observer * The object to be notified when this season changes. */ public void addObserver(SeasonObserver observer) { observers.add(observer); } /** * Removes an observer. * * @param observer * The object that should no longer be notified when this season * changes. */ public void removeObserver(SeasonObserver observer) { observers.remove(observer); } /** * Notifies observers that this season has changed. * * @param whatChanged * What element in the season has changed. */ public void notify(SeasonElement whatChanged) { for (SeasonObserver observer : observers) { observer.seasonChanged(this, whatChanged); } } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; this.notify(SeasonElement.NAME); } /** * @return the teams */ public List<Team> getTeams() { return teams; } /** * @param teams * the teams to set */ public void setTeams(List<Team> teams) { this.teams = teams; this.notify(SeasonElement.TEAMS); } /** * Adds a team to the season, if the team is not already in the season. Also * tells the team to set the season, if the team's season is not already set * to this season. * * @param team * The team to add. */ public void addTeams(Team team) { if (!this.teams.contains(team)) { this.teams.add(team); this.notify(SeasonElement.TEAMS); if (team.getSeasons() == null || !team.getSeasons().contains(this)) { team.addSeasons(this); } } } /** * Removes a team from the season, if the team is in the season. Also tells * the team to remove the season, if the team includes the season. * * @param team * The team to remove. */ public void removeTeams(Team team) { if (this.teams.contains(team)) { this.teams.remove(team); this.notify(SeasonElement.TEAMS); if (team.getSeasons() != null && team.getSeasons().contains(this)) { team.removeSeasons(this); } } } /** * @return the races */ public List<Race> getRaces() { return races; } /** * @param races * the races to set */ public void setRaces(List<Race> races) { this.races = races; this.notify(SeasonElement.RACES); } /** * Adds a race to the season, if the race is not already in the season. Also * tells the race to set the season, if the race's season is not already set * to this season. * * @param race * The race to add. */ public void addRace(Race race) { if (!this.races.contains(race)) { this.races.add(race); this.notify(SeasonElement.TEAMS); if (race.getSeason() == null || !race.getSeason().equals(this)) { race.setSeason(this); } } } /** * Removes a race from the season, if the race is in the season. Also tells * the race to remove the season, if the race includes the season. * * @param race * The race to remove. */ public void removeRace(Race race) { if (this.races.contains(race)) { this.races.remove(race); this.notify(SeasonElement.TEAMS); if (race.getSeason() != null && race.getSeason().equals(this)) { race.setSeason(null); } } } /** * @return the seasonOrder */ public int getSeasonOrder() { return seasonOrder; } /** * @param seasonOrder * the seasonOrder to set */ public void setSeasonOrder(int seasonOrder) { this.seasonOrder = seasonOrder; this.notify(SeasonElement.SEASON_ORDER); } /** * @return the id */ public UUID getId() { return id; } /** * @param id * the id to set */ public void setId(UUID id) { this.id = id; } /** * Returns true if "other" is a Season and both Seasons have the same ID. * * @param other * The object to compare against * @return true if both Seasons have the same ID. * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object other) { if (other instanceof Season) { return this.getId().equals(((Season) other).getId()); } else return false; } }
package com.karya.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.karya.dao.ILeaveDao; import com.karya.model.HolidayList001MB; import com.karya.model.LeaveApp001MB; import com.karya.model.LeaveBlockList001MB; import com.karya.model.LeaveType001MB; import com.karya.service.ILeaveService; @Service("leaveService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class LeaveServiceImpl implements ILeaveService{ @Autowired private ILeaveDao leaveDao; @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addLeaveApp(LeaveApp001MB leaveapp001MB) { leaveDao.addLeaveApp(leaveapp001MB); } public List<LeaveApp001MB> listleaveapps() { return leaveDao.listleaveapps(); } public LeaveApp001MB getleaveapp(int lvappId) { return leaveDao.getleaveapp(lvappId); } public void deleteleaveapp(int lvappId) { leaveDao.deleteleaveapp(lvappId); } @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addLeaveType(LeaveType001MB leavetype001MB) { leaveDao.addLeaveType(leavetype001MB); } public List<LeaveType001MB> listleavetype() { return leaveDao.listleavetype(); } public LeaveType001MB getleavetype(int lvtypeId) { return leaveDao.getleavetype(lvtypeId); } public void deleteleavetype(int lvtypeId) { leaveDao.deleteleavetype(lvtypeId); } //Holiday Service @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addholidayList(HolidayList001MB holidaylist001MB) { leaveDao.addholidayList(holidaylist001MB); } public List<HolidayList001MB> listholidays() { return leaveDao.listholidays(); } public HolidayList001MB getholidaylist(int hlistId) { return leaveDao.getholidaylist(hlistId); } public void deleteholiday(int hlistId) { leaveDao.deleteholiday(hlistId); } //Block List @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addleaveblock(LeaveBlockList001MB leaveblocklist001MB) { leaveDao.addleaveblock(leaveblocklist001MB); } public List<LeaveBlockList001MB> listleaveblock() { return leaveDao.listleaveblock(); } public LeaveBlockList001MB getblocklist(int lvblockId) { return leaveDao.getblocklist(lvblockId); } public void deleteleaveblock(int lvblockId) { leaveDao.deleteleaveblock(lvblockId); } }
public class DungeonGame { public int calculateMinimumHP(int[][] dungeon) { int rows = dungeon.length; int cols = dungeon[0].length; int[][] dp = new int[rows][cols]; dp[rows - 1][cols - 1] = dungeon[rows - 1][cols - 1] > 0 ? 1 : -dungeon[rows - 1][cols - 1] + 1; for (int i = rows - 2; i >= 0; --i) { dp[i][cols - 1] = Math.max(dp[i + 1][cols - 1] - dungeon[i][cols - 1], 1); } for (int i = cols - 2; i >= 0; --i) { dp[rows - 1][i] = Math.max(dp[rows - 1][i + 1] - dungeon[rows - 1][i], 1); } for (int i = rows - 2; i >= 0; --i) { for (int j = cols - 2; j >= 0; --j) { dp[i][j] = Math.max(1, Math.min( dp[i][j + 1] - dungeon[i][j], dp[i + 1][j] - dungeon[i][j] ) ); } } return dp[0][0]; } public static void main(String[] args) { int[][] dungeon = new int[][]{{-2, -3, 3}, {-5, -10, 1}, {10, 30, -5}}; System.out.println(new DungeonGame().calculateMinimumHP(dungeon)); } }
package entity; import java.io.Serializable; /** * Created by Smirnov-VN on 18.04.2017. * Человек, который едет на лифте */ public class Person implements Serializable, Comparable<Person> { /** * Имя */ private String name; /** * Точка отправления */ private transient Floor departure; /** * Точка назначения */ private Floor destination; /** * Этот человек не может подсесть в лифт, который везет пассажира, имеющего самый длинный путь */ private boolean marked; public String getName() { return name; } public Floor getDeparture() { return departure; } public Floor getDestination() { return destination; } public boolean isMarked() { return marked; } public void setMarked(boolean marked) { this.marked = marked; } public Person(String name, Floor departure, Floor destination) { this.name = name; this.destination = destination; departure.addPerson(this); this.departure = departure; } @Override public String toString() { return name + ", who wants to " + destination + " floor"; } @Override public int compareTo(Person o) { return name.compareTo(o.name); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return name.equals(person.name); } @Override public int hashCode() { return name.hashCode(); } }
package io.snice.buffer; import io.snice.buffer.impl.EmptyBuffer; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; /** * Obviously, no matter what kind of underlying buffer is used, all the tests * should pass. Hence, we are putting all tests in this class and then each * sub-class just needs to override the createBuffer-factory method * * @author jonas@jonasborjesson.com */ public abstract class AbstractBufferTest { /** * Factory method for creating the type of buffer that you need to test * * @param array * @return */ public abstract Buffer createBuffer(final byte[] array); public abstract Buffer createBuffer(final byte[] array, int offset, int length); public Buffer createBuffer(final String s) { return createBuffer(s.getBytes()); } @Test public void testGetContent() throws Exception { final var buffer = createBuffer(generateContent(100)); final var content = buffer.getContent(); ensureContent(content, 0); // slice it out... ensureContent(buffer.slice(10, 100).getContent(), 10); ensureContent(buffer.slice(10, 20).getContent(), 10); // boundary testing... ensureContent(buffer.slice(10, 10).getContent(), 10); ensureContent(buffer.slice(99, 100).getContent(), 99); ensureContent(buffer.slice(100, 100).getContent(), 100); // slice of slice... final var slice = buffer.slice(10, 50); // remember we already sliced 10 out so the slice of 10 of 10 means we should be // at 20... ensureContent(slice.slice(10, 30).getContent(), 20); // again, the slice started at 10 so... and we sliced out // 10 to 50 which means that there are only 40 bytes in the slice so // ask for 40... ensureContent(slice.slice(0, 40).getContent(), 10); ensureContent(slice.slice(1, 40).getContent(), 11); ensureContent(slice.slice(1, 30).getContent(), 11); } /** * Ensure that the given byte-array contains the bytes from (inclusive) start * to the end and it is assumed that the content is +1 as far as values * goes for every new byte up the index. */ private void ensureContent(final byte[] content, int start) { for (int i = 0; i < content.length; ++i) { assertThat(content[i], is((byte)(start + i))); } } private final byte[] generateContent(int length) { final byte[] content = new byte[length]; for (int i = 0; i < length; ++i) { content[i] = (byte)i; } return content; } @Test public void testWrapLong() throws Exception { assertThat(Buffers.wrap(123L).toString(), is("123")); assertThat(Buffers.wrap(-123L).toString(), is("-123")); } @Test public void testWrapInt() throws Exception { assertThat(Buffers.wrap(123).toString(), is("123")); assertThat(Buffers.wrap(-123).toString(), is("-123")); } @Test public void testConvertToIpv4String() { final Buffer b = Buffers.wrap((byte)0x00, (byte)0x01, (byte)0xac, (byte)0x16, (byte)0x12, (byte)0x78, (byte)0xaa); assertThat(b.toIPv4String(2), is("172.22.18.120")); } @Test public void testIsNullOrEmpty() { assertThat(Buffers.isNullOrEmpty(null), is(true)); assertThat(Buffers.isNullOrEmpty(createBuffer("")), is(true)); assertThat(Buffers.isNullOrEmpty(EmptyBuffer.EMPTY), is(true)); assertThat(Buffers.isNullOrEmpty(createBuffer(" ")), is(false)); } @Test public void testIsNotNullOrEmpty() { assertThat(Buffers.isNotNullOrEmpty(null), is(false)); assertThat(Buffers.isNotNullOrEmpty(createBuffer("")), is(false)); assertThat(Buffers.isNotNullOrEmpty(EmptyBuffer.EMPTY), is(false)); assertThat(Buffers.isNotNullOrEmpty(createBuffer(" ")), is(true)); } @Test public void testCreateWithOffsetAndLength() { ensureBuffer(0, 3, "hej", 'h', 'e', 'j'); ensureBuffer(0, 3, "hej", 'h', 'e', 'j', null, null, null, null); ensureBuffer(2, 3, "hej", null, null, 'h', 'e', 'j', null, null, null, null); // empty buffer but should be legal ensureBuffer(2, 0, "", null, null, 'h', 'e', 'j', null, null, null, null); ensureBuffer(2, 1, "h", null, null, 'h', 'e', 'j', null, null, null, null); } private void ensureBuffer(final int offset, final int length, final String expected, final Character... content) { final byte[] buf = new byte[content.length]; for (int i = 0; i < content.length; ++i) { buf[i] = content[i] != null ? (byte)content[i].charValue() : buf[i]; } final Buffer buffer = createBuffer(buf, offset, length); if (expected.isEmpty()) { assertThat("This should be an empty buffer", buffer.isEmpty(), is(true)); } assertThat(buffer.toString(), is(expected)); } @Test public void testEndsWithByte() { ensureEndsWith(createBuffer("hello world grejor"), (byte)'r'); ensureEndsWith(createBuffer("hello world grejor"), (byte)'o', (byte)'r'); ensureEndsWith(createBuffer("hello world grejor"), (byte)'j', (byte)'o', (byte)'r'); ensureEndsWith(createBuffer("hello world grejor"), (byte)'e', (byte)'j', (byte)'o', (byte)'r'); assertThat(createBuffer("hello world grejor\r\n").endsWithCRLF(), is(true)); assertThat(createBuffer("hello world grejor\r\n nisse").endsWithCRLF(), is(false)); assertThat(createBuffer("\r\n").endsWithCRLF(), is(true)); assertThat(createBuffer("\r\n\r\n").endsWithDoubleCRLF(), is(true)); } @Test public void testEndsWith() { ensureEndsWith(createBuffer("hello world ena goa grejor"), "grejor"); ensureEndsWith(createBuffer("hello ena goa "), "goa "); ensureEndsWith(createBuffer("hello ena goa "), " "); ensureEndsWith(createBuffer("hello ena goa "), "a "); ensureEndsWith(createBuffer("hello ena goa "), "oa "); ensureEndsWith(createBuffer("hello ena goa "), "goa "); ensureEndsWith(createBuffer("hello ena goa "), "hello ena goa "); ensureEndsWith(createBuffer("hello ena goa\r\n"), "goa\r\n"); ensureEndsWith(createBuffer("hello \r\nERROR\r\n"), "\r\nERROR\r\n"); ensureEndsWith(createBuffer("hello \r\nOK\r\n"), "\r\nOK\r\n"); // no match... ensureNotEndsWith(createBuffer("nope doesnt fit"), "nisse"); ensureNotEndsWith(createBuffer("nope"), "nisse and this is way too long"); // zero length is considered bad... ensureEndsWithFails(createBuffer("nope"), "".getBytes()); ensureEndsWithFails(createBuffer("nope"), null); ensureEndsWithFails(createBuffer("nope"), new byte[0]); // make sure that when we slice things out that the end is still maintained... final Buffer orig = createBuffer("hello world ena goa grejor"); final Buffer slice01 = orig.slice(5, 15); assertThat(slice01.toString(), is(" world ena")); ensureEndsWith(slice01, "ena"); final Buffer slice01b = slice01.slice(1, 6); assertThat(slice01b.toString(), is("world")); ensureEndsWith(slice01b, "world"); ensureEndsWith(slice01b, "d"); } @Test public void testEndsWithEOL() { assertThat(createBuffer("hello yes\n").endsWithEOL(), is(true)); assertThat(createBuffer("hello yes\r").endsWithEOL(), is(true)); assertThat(createBuffer("hello yes\r\n").endsWithEOL(), is(true)); assertThat(createBuffer("hello yes\r\n\n").endsWithEOL(), is(true)); assertThat(createBuffer("hello yes\r\n\n\r").endsWithEOL(), is(true)); assertThat(createBuffer("\n").endsWithEOL(), is(true)); assertThat(createBuffer("\r").endsWithEOL(), is(true)); assertThat(createBuffer("\r\n").endsWithEOL(), is(true)); } @Test public void testStartsWith() { assertThat(createBuffer("hello world").startsWith(createBuffer("hello")), is(true)); assertThat(createBuffer("hello world").startsWith(createBuffer("hello world this is too long")), is(false)); // testing for 1-off errors... assertThat(createBuffer("hello world").startsWith(createBuffer("hello worl")), is(true)); assertThat(createBuffer("hello world").startsWith(createBuffer("hello world")), is(true)); assertThat(createBuffer("hello world").startsWith(createBuffer("hello world!")), is(false)); // other 1-off error types... assertThat(createBuffer("").startsWith(createBuffer("nope")), is(false)); assertThat(createBuffer("").startsWith(createBuffer("")), is(true)); assertThat(createBuffer("empty should match I guess").startsWith(createBuffer("")), is(true)); // do some slicing final String s = "hello world"; assertThat(createBuffer(s).slice(6, s.length()).startsWith(createBuffer("world")), is(true)); assertThat(createBuffer(s).slice(6, s.length()).startsWith(createBuffer(s).slice(6, 7)), is(true)); } @Test public void testStartsWithIgnoreCase() { assertThat(createBuffer("hello world").startsWithIgnoreCase(createBuffer("heLlO")), is(true)); assertThat(createBuffer("hello world").startsWithIgnoreCase(createBuffer("hello world this is too long")), is(false)); // testing for 1-off errors... assertThat(createBuffer("hello World").startsWithIgnoreCase(createBuffer("hello worl")), is(true)); assertThat(createBuffer("hello World").startsWithIgnoreCase(createBuffer("hello world")), is(true)); assertThat(createBuffer("hello World").startsWithIgnoreCase(createBuffer("hello world!")), is(false)); // other 1-off error types... assertThat(createBuffer("").startsWithIgnoreCase(createBuffer("nope")), is(false)); assertThat(createBuffer("").startsWithIgnoreCase(createBuffer("")), is(true)); assertThat(createBuffer("empty should match I guess").startsWithIgnoreCase(createBuffer("")), is(true)); // do some slicing final String s = "hello world"; assertThat(createBuffer(s.toUpperCase()).slice(6, s.length()).startsWithIgnoreCase(createBuffer("world")), is(true)); assertThat(createBuffer(s.toUpperCase()).slice(6, s.length()).startsWithIgnoreCase(createBuffer(s).slice(6, 7)), is(true)); } private static void ensureEndsWith(final Buffer buffer, final byte b) { assertThat(buffer.endsWith(b), is(true)); } private static void ensureEndsWith(final Buffer buffer, final byte b1, final byte b2) { assertThat(buffer.endsWith(b1, b2), is(true)); } private static void ensureEndsWith(final Buffer buffer, final byte b1, final byte b2, final byte b3) { assertThat(buffer.endsWith(b1, b2, b3), is(true)); } private static void ensureEndsWith(final Buffer buffer, final byte b1, final byte b2, final byte b3, final byte b4) { assertThat(buffer.endsWith(b1, b2, b3, b4), is(true)); } private static void ensureNotEndsWith(final Buffer buffer, final byte[] bytes) { assertThat(buffer.endsWith(bytes), is(false)); } private static void ensureNotEndsWith(final Buffer buffer, final String str) { ensureNotEndsWith(buffer, str.getBytes()); } private static void ensureEndsWith(final Buffer buffer, final byte[] bytes) { assertThat(buffer.endsWith(bytes), is(true)); } private static void ensureEndsWith(final Buffer buffer, final String str) { ensureEndsWith(buffer, str.getBytes()); } private static void ensureEndsWithFails(final Buffer buffer, final byte[] bytes) { try { buffer.endsWith(bytes); fail("Expected the Buffer.endsWith to fail here"); } catch (final IllegalArgumentException e) { // expected } } @Test public void testIndexOf() throws Exception { final Buffer buffer = createBuffer("hello world ena goa grejor"); assertThat(buffer.indexOf(100, (byte) 'h'), is(0)); assertThat(buffer.indexOf(100, (byte) 'e'), is(1)); assertThat(buffer.indexOf(100, (byte) 'l'), is(2)); assertThat(buffer.indexOf(100, (byte) 'o'), is(4)); assertThat(buffer.indexOf(100, (byte) ' '), is(5)); assertThat(buffer.indexOf(100, (byte) 'w'), is(6)); assertThat(buffer.getByte(6), is((byte) 'w')); // indexOf should not affect the reader index so // everything should still be there. assertThat(buffer.toString(), is("hello world ena goa grejor")); } @Test public void testCountOccurances() { final Buffer buffer = createBuffer("127.0.0.1"); assertThat(buffer.countOccurences('.'), is(3)); ensureCountOccurances(3, '.', "127.0.0.1", 3); // start after the first . ensureCountOccurances(4, '.', "127.0.0.1", 2); // boundary testing. ensureCountOccurances(7, '.', "127.0.0.1", 1); ensureCountOccurances(8, '.', "127.0.0.1", 0); try { ensureCountOccurances(9, '.', "127.0.0.1", 0); fail("expected to blow up because we are out of bounds"); } catch (final IndexOutOfBoundsException e) { // expected } } @Test public void testCountOccurancesOnSlices() { final Buffer buffer = createBuffer("127.0.0.1"); // slice operations... final Buffer slice1 = buffer.slice(3, buffer.capacity()); assertThat(slice1.toString(), is(".0.0.1")); // really just to make it easier to read the unit test. assertThat(slice1.countOccurences('.'), is(3)); ensureCountOccurances(1, '.', slice1, 2); ensureCountOccurances(5, '.', slice1, 0); // slice of the slice final Buffer slice1_1 = slice1.slice(1, 5); assertThat(slice1_1.toString(), is("0.0.")); // really just to make it easier to read the unit test. assertThat(slice1_1.countOccurences('.'), is(2)); ensureCountOccurances(1, '.', slice1_1, 2); ensureCountOccurances(2, '.', slice1_1, 1); ensureCountOccurances(3, '.', slice1_1, 1); try { ensureCountOccurances(4, '.', slice1_1, 0); fail("expected to blow up because we are out of bounds"); } catch (final IndexOutOfBoundsException e) { // expected } } /** * Ensure that the max bytes parameter is honored... */ @Test public void testCountOccurencesWithMaxBytes() { // this one is 48 characters long. // (zero indexed) 3 7 13 18 23 27 33 39 44 // v v v v v v v v v final Buffer buffer = createBuffer("one two three four five six seven eight nine ten"); // really just to validate that I counted the spaces above correctly... final List<Integer> indices = Arrays.asList(3, 7, 13, 18, 23, 27, 33, 39, 44); for (int i = 0; i < indices.size(); ++i) { final int start = i == 0 ? 0 : indices.get(i - 1) + 1; assertThat(buffer.indexOf(start, 1024, (byte)' '), is(indices.get(i))); } ensureCountOccurances(0, ' ', buffer, 9); ensureCountOccurances(0, 11, ' ', buffer, 2); // only go to about half way into "three" so two spaces ensureCountOccurances(4, 11 - 4, ' ', buffer, 1); // note that the // boundary testing... ensureCountOccurances(2, 0, ' ', buffer, 0); // dumb but allowed ensureCountOccurances(2, 1, ' ', buffer, 0); // only checking the 'e' in "one" ensureCountOccurances(3, 1, ' ', buffer, 1); // now we are "standing" on the first space between "one" and "two" ensureCountOccurances(2, 2, ' ', buffer, 1); // starting from the 'e' in "one", checking 2 bytes, which will include the first space. ensureCountOccurances(33, 2, ' ', buffer, 1); // starting at the white space between seven and eight // boundary testing at the end of the array and also // making sure if we go beyond the capacity for "maxbytes" then the // capacity will be used instead. ensureCountOccurances(33, 1000, ' ', buffer, 3); ensureCountOccurances(39, 1000, ' ', buffer, 2); ensureCountOccurances(44, 1000, ' ', buffer, 1); ensureCountOccurances(45, 1000, ' ', buffer, 0); ensureCountOccurances(46, 1000, ' ', buffer, 0); ensureCountOccurances(47, 1000, ' ', buffer, 0); try { ensureCountOccurances(48, 1000, ' ', buffer, 0); fail("expected to blow up because we are out of bounds"); } catch (final IndexOutOfBoundsException e) { // expected } } /** * Ensure that the max bytes parameter is honored even with slices... */ @Test public void testCountOccurencesWithMaxBytesOnSlices() { // this one is 48 characters long. // (zero indexed) 3 7 13 18 23 27 33 39 44 // v v v v v v v v v final Buffer buffer = createBuffer("one two three four five six seven eight nine ten"); final Buffer slice1 = buffer.slice(18, 34); // should contain 4 white spaces assertThat(slice1.toString(), is(" five six seven ")); ensureCountOccurances(0, 1000, ' ', slice1, 4); ensureCountOccurances(5, 1000, ' ', slice1, 3); ensureCountOccurances(15, 1000, ' ', slice1, 1); // standing on the last space ensureCountOccurances(15, 1, ' ', slice1, 1); } private void ensureCountOccurances(final int start, final char ch, final String s, final int expected) { final Buffer buffer = createBuffer(s); ensureCountOccurances(start, ch, buffer, expected); } private static void ensureCountOccurances(final int start, final char ch, final Buffer buffer, final int expected) { ensureCountOccurances(start, 1024, ch, buffer, expected); } private static void ensureCountOccurances(final int start, final int max, final char ch, final Buffer buffer, final int expected) { assertThat(buffer.countOccurences(start, max, ch), is(expected)); } @Test public void testCountWhiteSpace() throws Exception { assertThat(createBuffer("").countWhiteSpace(), is(0)); assertThat(createBuffer(" ").countWhiteSpace(), is(1)); assertThat(createBuffer("\t").countWhiteSpace(), is(1)); assertThat(createBuffer(" \t").countWhiteSpace(), is(2)); assertThat(createBuffer("\t ").countWhiteSpace(), is(2)); assertThat(createBuffer("not until later \t ").countWhiteSpace(), is(0)); assertThat(createBuffer("nothing").countWhiteSpace(), is(0)); // slice and then count. assertThat(createBuffer("hello world").slice(5, 10).countWhiteSpace(), is(1)); assertThat(createBuffer("hello world").slice(5, 10).countWhiteSpace(), is(2)); assertThat(createBuffer("hello \t\tworld").slice(5, 10).countWhiteSpace(), is(4)); // start counting from a different spot assertThat(createBuffer("hello world").countWhiteSpace(5), is(1)); assertThat(createBuffer("hello world").countWhiteSpace(6), is(0)); assertThat(createBuffer("hello world").countWhiteSpace(5), is(3)); assertThat(createBuffer("hello world").countWhiteSpace(6), is(2)); // start one space in... } /** * index of white space is just a convenience method but still * better work! * * @throws Exception */ @Test public void testIndexOfWhitespace() throws Exception { final Buffer buffer = createBuffer("hello ena goa grejor"); final int index = buffer.indexOfWhiteSpace(); assertThat(index, is(5)); assertThat(buffer.getByte(index), is((byte)' ')); // slice out the first word and then the new // index of white space should be 3 (zero index remember!) final Buffer slice01 = buffer.slice(index + 1, buffer.capacity()); assertThat(slice01.indexOfWhiteSpace(), is(3)); // test to start later in the original buffer assertThat(buffer.indexOfWhiteSpace(index + 1), is(9)); assertThat(buffer.slice(9).toString(), is("hello ena")); // Also, if we slice and keep the white space then // zero should be returned of course assertThat(buffer.slice(index, buffer.capacity()).indexOfWhiteSpace(), is(0)); // and just make sure we catch HTAB as well assertThat(createBuffer("hello\ttab").indexOfWhiteSpace(), is(5)); assertThat(createBuffer("hello\t tab and then space").indexOfWhiteSpace(), is(5)); assertThat(createBuffer("hello \tspace first then tab").indexOfWhiteSpace(), is(5)); } /** * The index is based off of the window of the slice so even if the underlying * buffer is much larger, the index is still zero based from the beginning of the window. * * Ensure this is true so slice a bunch of times... * * @throws Exception */ @Test public void testIndexOfAfterSlicing() throws Exception { final Buffer buffer = createBuffer("hello world ena goa grejor"); final Buffer hello = buffer.slice(5); assertThat(hello.indexOf((byte)'h'), is(0)); assertThat(hello.indexOf((byte)'e'), is(1)); assertThat(hello.indexOf((byte)'l'), is(2)); // skip the second 'l' because we would find the first again assertThat(hello.indexOf((byte)'o'), is(4)); assertThat(hello.indexOf((byte)' '), is(-1)); // outside of our window assertThat(hello.indexOf((byte)'w'), is(-1)); // outside of our window // also, index of white space should also be -1, // which really should be exactly the same as searching for // space but just in case we fat-finger something at some point assertThat(hello.indexOfWhiteSpace(), is(-1)); // slice further in... final Buffer world = buffer.slice(6, 6 + 5); assertThat(world.indexOf((byte)'w'), is(0)); assertThat(world.indexOf((byte)'o'), is(1)); assertThat(world.indexOf((byte)'r'), is(2)); assertThat(world.indexOf((byte)'l'), is(3)); assertThat(world.indexOf((byte)'d'), is(4)); assertThat(world.indexOf((byte)'h'), is(-1)); // outside of our window assertThat(world.indexOf((byte)' '), is(-1)); // outside of our window // and as always, check boundaries at the end as well. // btw, 'grejor' means stuff in swedish... in case you wondered... final Buffer grejor = buffer.slice(20, buffer.capacity()); assertThat(grejor.indexOf((byte)'g'), is(0)); assertThat(grejor.indexOf((byte)'r'), is(1)); assertThat(grejor.indexOf((byte)'e'), is(2)); assertThat(grejor.indexOf((byte)'j'), is(3)); assertThat(grejor.indexOf((byte)'o'), is(4)); assertThat(grejor.indexOf(2, 100, (byte)'r'), is(5)); // skip passed the first 'r' } @Test public void testSlicing() throws Exception { final Buffer orig = createBuffer("hello world ena goa grejor"); assertThat(orig.slice(0).toString(), is("")); assertThat(orig.slice(1).toString(), is("h")); assertThat(orig.slice(2).toString(), is("he")); assertThat(orig.slice(3).toString(), is("hel")); assertThat(orig.slice(4).toString(), is("hell")); assertThat(orig.slice(5).toString(), is("hello")); assertThat(orig.slice(6).toString(), is("hello ")); assertThat(orig.slice(7).toString(), is("hello w")); assertThat(orig.slice(8).toString(), is("hello wo")); assertThat(orig.slice(9).toString(), is("hello wor")); assertThat(orig.slice(10).toString(), is("hello worl")); assertThat(orig.slice(11).toString(), is("hello world")); assertThat(orig.slice(12).toString(), is("hello world ")); assertThat(orig.slice(13).toString(), is("hello world e")); assertThat(orig.slice(14).toString(), is("hello world en")); assertThat(orig.slice(15).toString(), is("hello world ena")); assertThat(orig.slice(0, 0).toString(), is("")); assertThat(orig.slice(0, 1).toString(), is("h")); assertThat(orig.slice(0, 2).toString(), is("he")); assertThat(orig.slice(0, 3).toString(), is("hel")); assertThat(orig.slice(0, 4).toString(), is("hell")); assertThat(orig.slice(0, 5).toString(), is("hello")); assertThat(orig.slice(0, 6).toString(), is("hello ")); assertThat(orig.slice(0, 7).toString(), is("hello w")); assertThat(orig.slice(0, 8).toString(), is("hello wo")); assertThat(orig.slice(0, 9).toString(), is("hello wor")); assertThat(orig.slice(0, 10).toString(), is("hello worl")); assertThat(orig.slice(0, 11).toString(), is("hello world")); assertThat(orig.slice(0, 12).toString(), is("hello world ")); assertThat(orig.slice(0, 13).toString(), is("hello world e")); assertThat(orig.slice(0, 14).toString(), is("hello world en")); assertThat(orig.slice(0, 15).toString(), is("hello world ena")); assertThat(orig.slice(5, 11).toString(), is(" world")); assertThat(orig.slice(6, 11).toString(), is("world")); assertThat(orig.slice(9, 10).toString(), is("l")); assertThat(orig.slice(12, orig.capacity()).toString(), is("ena goa grejor")); assertThat(orig.toString(), is("hello world ena goa grejor")); } /** * Whenever we slice out a new buffer, that buffer has it's own buffer window and all * operations is in relation to that window. * * @throws Exception */ @Test public void testSliceOfSlices() throws Exception { final Buffer orig = createBuffer("hello world ena goa grejor"); final Buffer slice01 = orig.slice(6, 19); assertThat(slice01.toString(), is("world ena goa")); final Buffer slice01a = slice01.slice(6, 9); assertThat(slice01a.toString(), is("ena")); assertThat(slice01a.indexOf((byte)'e'), is(0)); assertThat(slice01a.indexOf((byte)'n'), is(1)); assertThat(slice01a.indexOf((byte)'a'), is(2)); // but of course, the slice01 is still un-affected so // looking for the same stuff will yield different // indexes because slice01's window is different. assertThat(slice01.indexOf((byte)'e'), is(0 + 6)); assertThat(slice01.indexOf((byte)'n'), is(1 + 6)); assertThat(slice01.indexOf((byte)'a'), is(2 + 6)); // and same is true for the original, which is yet // another 6 bytes "earlier"... but note that there // is an e earlier in the original buffer assertThat(orig.indexOf((byte)'e'), is(1)); // the e in 'hello' assertThat(orig.indexOf((byte)'n'), is(1 + 6 + 6)); assertThat(orig.indexOf((byte)'a'), is(2 + 6 + 6)); final Buffer slice01b = slice01.slice(1, 4); assertThat(slice01b.toString(), is("orl")); assertThat(slice01b.indexOf((byte)'o'), is(0)); assertThat(slice01b.indexOf((byte)'r'), is(1)); assertThat(slice01b.indexOf((byte)'l'), is(2)); } @Test public void testHashCode() { final Buffer a = createBuffer("hello"); final Buffer b = createBuffer("hello"); final Buffer c = createBuffer("world"); assertThat(a.hashCode(), is(b.hashCode())); assertThat(c.hashCode(), not(b.hashCode())); } @Test public void testEqualsBasicStuff() throws Exception { assertBufferEquality("hello", "hello", true); assertBufferEquality("hello", "world", false); assertBufferEquality("hello ", "world", false); assertBufferEquality("hello world", "world", false); assertBufferEquality("Hello", "hello", false); assertBufferEquality("h", "h", true); } @Test public void testEqualsAfterSlice() throws Exception { final Buffer b1 = createBuffer("hello world"); final Buffer b2 = createBuffer("hello"); assertThat(b1.slice(b2.capacity()), is(b2)); assertThat(b1.slice(b2.capacity()).equals(b2), is(true)); } @Test public void testEqualsIgnoreCase() throws Exception { assertBufferEqualityIgnoreCase("Hello", "hello", true); assertBufferEqualityIgnoreCase("this is A lOng string...", "tHis iS a long string...", true); assertBufferEqualityIgnoreCase("Hello", "HEllo", true); assertBufferEqualityIgnoreCase("Hello", "HEllO", true); assertBufferEqualityIgnoreCase("Hello", "HEllO ", false); // space at the end assertBufferEqualityIgnoreCase("123 abC", "123 abc", true); assertBufferEqualityIgnoreCase("123 abC !@#$", "123 ABc !@#$", true); } @Test public void testUtf8EqualsIgnoreCase() throws Exception { // case-insensitive comparison looks only at the 5 least significant bits for characters // that are in the 7-bit ASCII range. // 1-byte UTF-8 characters assertThat(createBuffer(new byte[] {0x40}).equalsIgnoreCase(createBuffer(new byte[] {0x40})), is(true)); assertThat(createBuffer(new byte[] {0x40}).equalsIgnoreCase(createBuffer(new byte[] {0x60})), is(false)); assertThat(createBuffer(new byte[] {0x41}).equalsIgnoreCase(createBuffer(new byte[] {0x41})), is(true)); assertThat(createBuffer(new byte[] {0x41}).equalsIgnoreCase(createBuffer(new byte[] {0x61})), is(true)); // 'A' and 'a' assertThat(createBuffer(new byte[] {0x5a}).equalsIgnoreCase(createBuffer(new byte[] {0x5a})), is(true)); assertThat(createBuffer(new byte[] {0x5a}).equalsIgnoreCase(createBuffer(new byte[] {0x7a})), is(true)); // 'Z' and 'z' assertThat(createBuffer(new byte[] {0x5b}).equalsIgnoreCase(createBuffer(new byte[] {0x5b})), is(true)); assertThat(createBuffer(new byte[] {0x5b}).equalsIgnoreCase(createBuffer(new byte[] {0x7b})), is(false)); // 2-byte UTF-8 characters. The second byte has the 5 least significant bits the same. In Java, // bytes are signed, so we need to convert unsigned notation to signed for the compiler to take it. assertThat(createBuffer(new byte[] {0xc0 - 256, 0x80 - 256}).equalsIgnoreCase(createBuffer(new byte[] {0xc0 - 256, 0x80 - 256})), is(true)); assertThat(createBuffer(new byte[] {0xc0 - 256, 0x80 - 256}).equalsIgnoreCase(createBuffer(new byte[] {0xc0 - 256, 0xa0 - 256})), is(false)); assertThat(createBuffer(new byte[] {0xc0 - 256, 0x8f - 256}).equalsIgnoreCase(createBuffer(new byte[] {0xc0 - 256, 0x8f - 256})), is(true)); assertThat(createBuffer(new byte[] {0xc0 - 256, 0x8f - 256}).equalsIgnoreCase(createBuffer(new byte[] {0xc0 - 256, 0xaf - 256})), is(false)); } private void assertBufferEqualityIgnoreCase(final String a, final String b, final boolean equals) { final Buffer bufA = createBuffer(a); final Buffer bufB = createBuffer(b); assertThat(bufA.equalsIgnoreCase(bufB), is(equals)); assertThat(bufB.equalsIgnoreCase(bufA), is(equals)); } private void assertBufferEquality(final String a, final String b, final boolean equals) { final Buffer bufA = createBuffer(a); final Buffer bufB = createBuffer(b); assertThat(bufA.equals(bufB), is(equals)); assertThat(bufB.equals(bufA), is(equals)); } @Test public void testEqualsHashCode() throws Exception { final Buffer b1 = createBuffer("hello world"); final Buffer b2 = createBuffer("hello world"); assertThat(b1, is(b2)); assertThat(b1.hashCode(), is(b2.hashCode())); final Buffer b3 = createBuffer("hello not world"); assertThat(b1, is(not(b3))); assertThat(b1.hashCode(), is(not(b3.hashCode()))); assertThat(b2, is(not(b3))); } /** * A buffer can be parsed as an integer assuming there are no bad characters * in there. * * @throws Exception */ @Test public void testParseAsInt() throws Exception { assertParseAsInt("1234", 1234); assertParseAsInt("-1234", -1234); assertParseAsInt("0", 0); assertParseAsInt("5060", 5060); // negative tests assertParseAsIntBadInput("apa"); assertParseAsIntBadInput(""); assertParseAsIntBadInput("-5 nope, everything needs to be digits"); assertParseAsIntBadInput("5 nope, everything needs to be digits"); // assertParseAsIntSliceFirst("hello:5060:asdf", 6, 10, 5060); // assertParseAsIntSliceFirst("hello:-5:asdf", 6, 8, -5); } @Test public void testWriteToOutputStream() throws Exception { ensureWriteToOutputStream("one two three"); ensureWriteToOutputStream("a"); // off by 1 bugs... ensureWriteToOutputStream(""); } @Test public void testMap() throws Exception { final Buffer a = createBuffer("hello"); final Map<Buffer, String> map = new HashMap<Buffer, String>(); map.put(a, "fup"); assertThat(map.get(a), is("fup")); final Buffer b = createBuffer("hello"); assertThat(map.get(b), is("fup")); final Buffer c = createBuffer("world"); map.put(c, "apa"); assertThat(map.containsKey(c), is(true)); final Buffer d = createBuffer("nope"); assertThat(map.containsKey(d), is(false)); } private void ensureWriteToOutputStream(final String data) throws IOException { final Buffer b1 = createBuffer(data); final ByteArrayOutputStream out = new ByteArrayOutputStream(); b1.writeTo(out); assertThat(b1.toString(), is(out.toString())); } @Test public void testStripEOL() throws Exception { ensureStripEOL("no CRLF in this one", false, false); ensureStripEOL("Just a CR here...\r", true, false); ensureStripEOL("Just a LF in this one...\n", false, true); ensureStripEOL("Alright, got both!\r\n", true, true); ensureStripEOL("Note, this is not readUntilCRLF, this \r\n is strip so we should have the entire thing left", false, false); // and ensure we don't have a +1 off bug resulting, usually, in blowing up // in a spectacular way... ensureStripEOL("", false, false); ensureStripEOL("a", false, false); ensureStripEOL("a\r", true, false); ensureStripEOL("a\n", false, true); ensureStripEOL("a\r\n", true, true); ensureStripEOL("ab", false, false); ensureStripEOL("ab\r", true, false); ensureStripEOL("ab\n", false, true); ensureStripEOL("ab\r\n", true, true); ensureStripEOL("\r", true, false); ensureStripEOL("\n", false, true); ensureStripEOL("\r\n", true, true); } @Test public void testComposeBuffers() { final Buffer hello = createBuffer("hello"); final Buffer space = createBuffer(" "); final Buffer world = createBuffer("world"); final Buffer helloWorld = Buffers.wrap(hello, space, world); assertThat(helloWorld.toString(), is("hello world")); // should be fine to slice assertThat(helloWorld.slice(3, 8).toString(), is("lo wo")); // and we shouldn't "notice" the boundaries of course... assertThat(helloWorld.getByte(0), is((byte)'h')); assertThat(helloWorld.getByte(1), is((byte)'e')); assertThat(helloWorld.getByte(2), is((byte)'l')); assertThat(helloWorld.getByte(3), is((byte)'l')); assertThat(helloWorld.getByte(4), is((byte)'o')); assertThat(helloWorld.getByte(5), is((byte)' ')); assertThat(helloWorld.getByte(6), is((byte)'w')); assertThat(helloWorld.getByte(7), is((byte)'o')); assertThat(helloWorld.getByte(8), is((byte)'r')); assertThat(helloWorld.getByte(9), is((byte)'l')); assertThat(helloWorld.getByte(10), is((byte)'d')); } protected void ensureStripEOL(final String line, final boolean cr, final boolean lf) { final Buffer buffer = createBuffer(line); final Buffer stripped = buffer.stripEOL(); if (cr && lf) { assertThat(buffer.capacity(), is(stripped.capacity() + 2)); assertThat(stripped.toString(), is(line.substring(0, line.length() - 2))); } else if (cr || lf) { assertThat(buffer.capacity(), is(stripped.capacity() + 1)); assertThat(stripped.toString(), is(line.substring(0, line.length() - 1))); } else { // neither so should be the exact same. assertThat(buffer, is(stripped)); } } protected void assertParseAsInt(final String number, final int expectedNumber) throws NumberFormatException { final Buffer buffer = createBuffer(number); assertThat(buffer.parseToInt(), is(expectedNumber)); } protected void assertParseAsIntBadInput(final String badNumber) { try { final Buffer buffer = createBuffer(badNumber); buffer.parseToInt(); fail("Expected a NumberFormatException"); } catch (final NumberFormatException e) { // expected } } }
package cn.kim.controller.manager; import cn.kim.common.annotation.NotEmptyLogin; import cn.kim.common.annotation.SystemControllerLog; import cn.kim.common.eu.UseType; import cn.kim.exception.CustomException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Created by 余庚鑫 on 2019/12/13 * 图形报表 */ @Controller @RequestMapping("/admin/Echarts") public class EchartsController extends BaseController { /** * 柱形 */ private static final String ECHARTS_BAR = "bar"; /** * 饼图 */ private static final String ECHARTS_PIE = "pie"; /** * 雷达 */ private static final String ECHARTS_RADAR = "radar"; /** * 柱形图 * * @param model * @return * @throws Exception */ @GetMapping("/bar") @SystemControllerLog(useType = UseType.SEE, isEcharts = true, event = "查看柱形图") @NotEmptyLogin public String bar(@RequestParam Map<String, Object> mapParam, Model model) throws Exception { String v = toString(mapParam.get("v")); if (isEmpty(v)) { throw new CustomException("参数错误"); } String title = "统计数据"; String subtext = getDate(); //动作 String action = toString(mapParam.get("action")); model.addAttribute("v", v); model.addAttribute("title", title); model.addAttribute("subtext", subtext); model.addAttribute("chartId", UUID.randomUUID().toString()); return "admin/system/echarts/bar"; } /** * 饼图 * * @param model * @return * @throws Exception */ @GetMapping("/pie") @SystemControllerLog(useType = UseType.SEE, isEcharts = true, event = "查看饼图") @NotEmptyLogin public String pie(@RequestParam Map<String, Object> mapParam, Model model) throws Exception { String v = toString(mapParam.get("v")); if (isEmpty(v)) { throw new CustomException("参数错误"); } String title = "统计数据"; String subtext = getDate(); //动作 String action = toString(mapParam.get("action")); //获得数据 model.addAttribute("v", v); model.addAttribute("title", title); model.addAttribute("subtext", subtext); model.addAttribute("chartId", UUID.randomUUID().toString()); return "admin/system/echarts/pie"; } /** * list转为bar可以使用的参数 * * @param list 数据 * @param xAxisField X轴字段 * @param legendField 组字段 * @param valueFields 参数字段 * @param valueNameFields 参数名称字段 * @return */ public Map<String, Object> toBarGroupData(List<Map<String, Object>> list, String xAxisField, String legendField, String[] valueFields, String[] valueNameFields) { Map<String, Object> resultMap = new HashMap<>(); if (list == null || list.size() == 0) { return resultMap; } //X轴参数 List<String> xAxisList = xAxisListSort(list, xAxisField); //统计组参数 Set<String> legendSet = new LinkedHashSet<>(); Map<String, Double> valueMap = new HashMap<>(); list.forEach(map -> { for (int i = 0; i < valueFields.length; i++) { String valueField = valueFields[i]; String valueNameField = valueNameFields[i]; String legend = toString(map.get(legendField)) + valueNameField; Double val = toBigDecimal(map.get(valueField)).doubleValue(); valueMap.put(toString(map.get(xAxisField)) + legend, val == null ? 0d : val); legendSet.add(legend); } }); //补充每个组缺少的参数 legendSet.forEach(legend -> { xAxisList.forEach(xAxis -> { for (String valueNameField : valueNameFields) { if (valueMap.get(xAxis + legend + valueNameField) == null) { valueMap.put(xAxis + legend + valueNameField, 0d); } } }); }); //转为参数集合 List<Map<String, Object>> seriesList = new LinkedList<>(); legendSet.forEach(legend -> { Map<String, Object> series = new HashMap<>(); //组名 series.put("name", legend); //参数 series.put("data", doubleArrayToValue(xAxisList, valueMap, legend)); seriesList.add(series); }); resultMap.put("legendArray", joinArray(legendSet.stream())); resultMap.put("xAxisArray", joinArray(xAxisList.stream())); resultMap.put("seriesList", seriesList); return resultMap; } /** * list转为bar可以使用的参数 * * @param list 数据 * @param xAxisField X轴字段 * @param valueFields 参数字段 * @param legendFields 转换参数名称字段 * @return */ public Map<String, Object> toBarGroupSplitData(List<Map<String, Object>> list, String xAxisField, String[] valueFields, String[] legendFields) { Map<String, Object> resultMap = new HashMap<>(); //X轴参数 List<String> xAxisList = xAxisListSort(list, xAxisField); //统计组参数 Map<String, Double> valueMap = new HashMap<>(); list.forEach(map -> { for (String valueField : valueFields) { Double val = toBigDecimal(map.get(valueField)).doubleValue(); valueMap.put(toString(map.get(xAxisField)) + valueField, val == null ? 0d : val); } }); //补充每个组缺少的参数 for (String valueField : valueFields) { xAxisList.forEach(xAxis -> { if (valueMap.get(xAxis + valueField) == null) { valueMap.put(xAxis + valueField, 0d); } }); } //转为参数集合 List<Map<String, Object>> seriesList = new LinkedList<>(); for (int i = 0; i < valueFields.length; i++) { String valueField = valueFields[i]; Map<String, Object> series = new HashMap<>(); //组名 series.put("name", legendFields[i]); //参数 series.put("data", doubleArrayToValue(xAxisList, valueMap, valueField)); seriesList.add(series); } resultMap.put("legendArray", joinArray(Arrays.stream(legendFields))); resultMap.put("xAxisArray", joinArray(xAxisList.stream())); resultMap.put("seriesList", seriesList); return resultMap; } /** * 转为饼图数据 * * @param name * @param value * @return */ public String toPieArray(String[] name, int[] value) { if (name.length != value.length) { return ""; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < name.length; i++) { builder.append("{"); builder.append("value:" + value[i] + ','); builder.append("name:'" + name[i] + "'"); builder.append("},"); } return builder.toString(); } /** * 排序 * * @param list * @param xAxisField * @return */ public List<String> xAxisListSort(List<Map<String, Object>> list, String xAxisField) { Set<String> xAxisSet = new HashSet<>(); List<String> xAxisList = new LinkedList<>(); list.forEach(map -> { xAxisSet.add(toString(map.get(xAxisField))); }); xAxisSet.forEach(s -> { xAxisList.add(s); }); //排序坐标 Collections.sort(xAxisList); return xAxisList; } public String joinArray(Stream<?> steam) { return joinArray(steam, ","); } public String joinArray(Stream<?> steam, String delimiter) { return steam.map(i -> "'" + i + "'").collect(Collectors.joining(delimiter)); } public String joinValueArray(Stream<?> steam) { return steam.map(i -> toString(i)).collect(Collectors.joining(",")); } public String doubleArrayToValue(List<?> xAxisList, Map<String, Double> valueMap, String valueField) { Double[] valueArray = xAxisList.stream().map(xAxis -> valueMap.get(xAxis + valueField)).toArray(Double[]::new); return joinValueArray(Arrays.stream(valueArray)); } }
package com.softeem.utils; import java.io.Serializable; import java.util.Collection; import java.util.List; public class VOResult implements Serializable { private List result = null; private Object[] rs = null; private int rowNumber = -1; private int totalRow = 0; private int beginPage = 1; private int pageSize = Constants.GLOABAL_PAGESIZE; public VOResult() { } public VOResult(List result) { this.result = result; if (result != null) { this.rowNumber = result.size(); this.totalRow = result.size(); } } public VOResult(List result, int totalRow) { this.result = result; this.totalRow = totalRow; if (result != null) this.rowNumber = result.size(); } public Collection getResult() { return this.result; } public Object getObject(int i) { if (this.rs == null) this.rs = this.result.toArray(); return this.rs[i]; } public void setBeginPage(int beginPage) { this.beginPage = beginPage; } public int getBeginPage() { return this.beginPage; } public int getRowNumber() { return this.rowNumber; } public void setRowNumber(int rowNumber) { this.rowNumber = rowNumber; } public int getTotalRow() { return this.totalRow; } public void setTotalRow(int totalRow) { this.totalRow = totalRow; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getPageSize() { return this.pageSize; } }
package instanceoftest; /** * Created by 罗选通 on 2017/11/13. */ public class B extends A{ }
/* ==================================================================== * * Copyright (c) Atos Origin INFORMATION TECHNOLOGY All rights reserved. * * ==================================================================== * */ package com.aof.webapp.form; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import org.apache.struts.upload.FormFile; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; /** * @author xxp * @version 2003-9-23 * */ public class ContentForm extends ActionForm { /** * The file that the user has uploaded */ protected FormFile theFile; protected String DESCRIPTION = null; protected String CONTENT_NAME = null; /** * Retrieve a representation of the file the user has uploaded */ public FormFile getTheFile() { return theFile; } /** * Set a representation of the file the user has uploaded */ public void setTheFile(FormFile theFile) { this.theFile = theFile; } /** * @return */ public String getCONTENT_NAME() { if(CONTENT_NAME!=null){ return new String(CONTENT_NAME); }else{ return CONTENT_NAME; } } /** * @return */ public String getDESCRIPTION() { if(DESCRIPTION!=null){ return new String(DESCRIPTION); }else{ return DESCRIPTION; } } /** * @param string */ public void setCONTENT_NAME(String string) { CONTENT_NAME = string; } /** * @param string */ public void setDESCRIPTION(String string) { DESCRIPTION = string; } /** * Reset all properties to their default values. * * @param mapping The mapping used to select this instance * @param request The servlet request we are processing */ public void reset() { this.CONTENT_NAME = ""; this.DESCRIPTION = ""; this.theFile = null; } }
package com.test.base; public class Node { private static final int[] ARRAY = {5, 8, 4, 12, 32, -12, -43, 0, 9, 43, -23, 8, -4, 43, 5}; public static Node[] createNodeArray() { Node[] nodeArray = new Node[ARRAY.length]; for (int i = 0; i < nodeArray.length; i++) { nodeArray[i] = new Node(ARRAY[i], i); } return nodeArray; } public int value; public int index; public Node(int value, int index) { super(); this.value = value; this.index = index; } @Override public String toString() { return value + "(" + index + ")"; } }
package entities; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class CategorieModeEnvoi implements Serializable{ @Id private int IdCategorieModeEnvoi; private ModeEnvoi modeEnvoi; public int getIdCategorieModeEnvoi() { return IdCategorieModeEnvoi; } public void setIdCategorieModeEnvoi(int idCategorieModeEnvoi) { IdCategorieModeEnvoi = idCategorieModeEnvoi; } public ModeEnvoi getModeEnvoi() { return modeEnvoi; } public void setModeEnvoi(ModeEnvoi modeEnvoi) { this.modeEnvoi = modeEnvoi; } }
package com.alten.main.rest; import com.alten.main.model.Room; import com.alten.main.service.RoomService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/room/") public class RoomRest { @Autowired private RoomService roomService; @GetMapping @ResponseStatus(HttpStatus.OK) private List<Room> getReservations(){ return roomService.findAll(); } }
package com.example.melanieh.traveltabrxflux; import com.hardsoftstudio.rxflux.action.RxError; import com.hardsoftstudio.rxflux.store.RxStoreChange; /** * Created by melanieh on 8/3/17. */ public interface ViewDispatch { void onRxStoreChanged(RxStoreChange change); void onRxError(RxError error); void onRxViewRegistered(); void onRxViewUnRegistered(); void onRxStoresRegister(); }
package com.mindtree.spring.serviceImpl; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Service; import com.mindtree.spring.daoImpl.EmployeeDAOImpl; import com.mindtree.spring.entity.Employee; @Service public class EmployeeServiceImpl { public List<String> getemployeedata(int id) { EmployeeDAOImpl ser = new EmployeeDAOImpl(); List<Object[]> list = ser.getProjectEmployeeName(id); List<Employee> employees = new ArrayList<Employee>(); for (Object[] result : list) { Employee employee = (Employee) result[0]; employees.add(employee); } List<String> projects = new ArrayList<String>(); for (Employee employee : employees) { projects.add(employee.getEname()+" "+employee.getMid()); System.out.println(); } return projects; } }
package com.experian.core.nlp.bayesian; import java.util.Set; /** * @author e00898a * */ public class BayesianData { /** * 特征 */ private Set<String> features; /** * 最终分类 */ private String category; public Set<String> getFeatures() { return features; } public void setFeatures(Set<String> features) { this.features = features; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
/** * */ package net.sf.taverna.t2.component.ui.file; import static java.util.Collections.sort; import static net.sf.taverna.t2.component.ComponentHealthCheck.FAILS_PROFILE; import static net.sf.taverna.t2.component.annotation.SemanticAnnotationUtils.getDisplayName; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Set; import javax.swing.JComponent; import javax.swing.JTextArea; import net.sf.taverna.t2.component.ComponentHealthCheck; import net.sf.taverna.t2.component.profile.SemanticAnnotationProfile; import net.sf.taverna.t2.visit.VisitKind; import net.sf.taverna.t2.visit.VisitReport; import net.sf.taverna.t2.workbench.report.explainer.VisitExplainer; /** * @author alanrw * */ public class ComponentDataflowHealthCheckExplainer implements VisitExplainer { private static final Comparator<SemanticAnnotationProfile> comparator = new Comparator<SemanticAnnotationProfile>() { @Override public int compare(SemanticAnnotationProfile arg0, SemanticAnnotationProfile arg1) { return getDisplayName(arg0.getPredicate()).compareTo( getDisplayName(arg1.getPredicate())); } }; @Override public boolean canExplain(VisitKind vk, int resultId) { return (vk instanceof ComponentHealthCheck) && (resultId == FAILS_PROFILE); } @Override public JComponent getExplanation(VisitReport vr) { @SuppressWarnings("unchecked") Set<SemanticAnnotationProfile> problemProfiles = (Set<SemanticAnnotationProfile>) vr .getProperty("problemProfiles"); List<SemanticAnnotationProfile> sortedList = new ArrayList<SemanticAnnotationProfile>( problemProfiles); sort(sortedList, comparator); String text = ""; for (SemanticAnnotationProfile profile : sortedList) { text += getSemanticProfileExplanation(profile) + "\n"; } return new JTextArea(text); } @Override public JComponent getSolution(VisitReport vr) { return new JTextArea("Correct the semantic annotation"); } private static String getSemanticProfileExplanation( SemanticAnnotationProfile p) { Integer minOccurs = p.getMinOccurs(); Integer maxOccurs = p.getMaxOccurs(); String displayName = getDisplayName(p.getPredicate()); if (maxOccurs == null) { return (displayName + " must have at least " + minOccurs + " value"); } if (minOccurs.equals(maxOccurs)) { return (displayName + " must have " + minOccurs + " value(s)"); } return (displayName + " must have between " + minOccurs + " and " + maxOccurs + " value(s)"); } }
package br.com.gestor.database.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JRResultSetDataSource; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.design.JasperDesign; import net.sf.jasperreports.engine.export.JRPdfExporter; import net.sf.jasperreports.engine.xml.JRXmlLoader; import br.com.gestor.database.dao.FormularioDao; import br.com.gestor.database.dao.FormularioJPADao; import br.com.gestor.database.modelo.Sprint; public class ReportUtil { private static final String user = "postgres"; private static final String url = "jdbc:postgresql://localhost:5432/game-empreendedorismo"; private static final String password = "1234"; public byte[] geraRelatorioPontuacao(Sprint form, String path) throws SQLException, JRException { JasperDesign design = JRXmlLoader.load(path); JasperReport report = JasperCompileManager.compileReport(design); Connection con = DriverManager.getConnection(url, user, password); PreparedStatement stmt = con .prepareStatement(" select u.login, u.nome, f.descricao, p.pontos from PontuacaoRodada " + "p inner join Usuario u on u.login = p.dev inner join dev a on u.login = a.login" + " inner join Formulario f on f.id = p.formulario where formulario = ?" + " order by p.pontos;"); stmt.setInt(1, form.getId()); ResultSet rs = stmt.executeQuery(); JRDataSource data = new JRResultSetDataSource(rs); Map<String, Object> map = new HashMap<>(); map.put("formulario", form.getId()); JasperPrint print = JasperFillManager.fillReport(report, map, data); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JRPdfExporter exporter = new JRPdfExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, print); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos); exporter.exportReport(); byte[] bytes = baos.toByteArray(); con.close(); return bytes; } public byte[] geraRelatorioMelhoresEquipes(Sprint form, String path) throws SQLException, JRException { JasperDesign design = JRXmlLoader.load(path); JasperReport report = JasperCompileManager.compileReport(design); Connection con = DriverManager.getConnection(url, user, password); PreparedStatement stmt = con .prepareStatement("select distinct(e.nome), sum(a.valor*f.fator) as soma," + " a.id_formulario, f.fator " + "from aposta a inner join fatorequipe f on " + "f.id_equipe = a.id_equipe inner join equipe e on " + "e.id = a.id_equipe where a.id_formulario = f.id_formulario " + "and a.id_formulario = ? group by e.nome, a.id_formulario, f.fator " + "order by a.id_formulario, soma desc"); stmt.setInt(1, form.getId()); ResultSet rs = stmt.executeQuery(); JRDataSource data = new JRResultSetDataSource(rs); Map<String, Object> map = new HashMap<>(); map.put("formulario", form.getId()); JasperPrint print = JasperFillManager.fillReport(report, map, data); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JRPdfExporter exporter = new JRPdfExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, print); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos); exporter.exportReport(); byte[] bytes = baos.toByteArray(); con.close(); return bytes; } public byte[] geraRelatorioMelhoresApostadores(Sprint form, String path) throws SQLException, JRException { JasperDesign design = JRXmlLoader.load(path); JasperReport report = JasperCompileManager.compileReport(design); Connection con = DriverManager.getConnection(url, user, password); PreparedStatement stmt = con .prepareStatement("select u.nome,a.id_dev,sum(a.valor * f.fator) as Soma," + " form.descricao from aposta a inner join fatorequipe f on f.id_equipe = a.id_equipe" + " left join usuario u on u.login = a.id_dev" + " inner join formulario form on form.id = a.id_formulario" + " where f.id_formulario = ? and a.id_formulario = ?" + " group by a.id_dev,u.nome,a.id_formulario, form.descricao"); stmt.setInt(1, form.getId()); stmt.setInt(2, form.getId()); ResultSet rs = stmt.executeQuery(); JRDataSource data = new JRResultSetDataSource(rs); Map<String, Object> map = new HashMap<>(); map.put("formulario", form.getId()); JasperPrint print = JasperFillManager.fillReport(report, map, data); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JRPdfExporter exporter = new JRPdfExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, print); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos); exporter.exportReport(); byte[] bytes = baos.toByteArray(); con.close(); return bytes; } public static void main(String[] args) throws SQLException, JRException, IOException { Sprint f = new Sprint(); f.setId(1); FormularioDao dao = new FormularioJPADao(); f = dao.find(1); dao.begin(); dao.realizaCalculoPontos(f); dao.commit(); byte[] bytes = new ReportUtil().geraRelatorioPontuacao(f, "WebContent/WEB-INF/relatorios/relatorioPontuacao.jrxml"); System.out.println(bytes); Path path = Paths.get("/home/alex/relat.pdf"); Files.write(path, bytes); } }
package com.zc.pivas.mainMenu.bean; import java.io.Serializable; import java.util.ArrayList; public class MainMenuBean implements Serializable { /** * 注释内容 */ private static final long serialVersionUID = 8253280514484982061L; private String id; private String num1; private String num2; private String state; private String levelnum; private String deptname; private String deptcode; private ArrayList<MainMenuBean> subMenuList; public String getDeptcode() { return deptcode; } public void setDeptcode(String deptcode) { this.deptcode = deptcode; } /** * @return 返回 deptname */ public String getDeptname() { return deptname; } /** * @param 对deptname进行赋值 */ public void setDeptname(String deptname) { this.deptname = deptname; } /** * @return 返回 num1 */ public String getNum1() { return num1; } /** * @param 对num1进行赋值 */ public void setNum1(String num1) { this.num1 = num1; } /** * @return 返回 num2 */ public String getNum2() { return num2; } /** * @param 对num2进行赋值 */ public void setNum2(String num2) { this.num2 = num2; } /** * @return 返回 state */ public String getState() { return state; } /** * @param 对state进行赋值 */ public void setState(String state) { this.state = state; } /** * @return 返回 levelnum */ public String getLevelnum() { return levelnum; } /** * @param 对levelnum进行赋值 */ public void setLevelnum(String levelnum) { this.levelnum = levelnum; } /** * @return 返回 subMenuList */ public ArrayList<MainMenuBean> getSubMenuList() { return subMenuList; } /** * @param 对subMenuList进行赋值 */ public void setSubMenuList(ArrayList<MainMenuBean> subMenuList) { this.subMenuList = subMenuList; } /** * @return 返回 id */ public String getId() { return id; } /** * @param 对id进行赋值 */ public void setId(String id) { this.id = id; } }
package com.mhframework.platform.android; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import android.annotation.SuppressLint; import android.os.Environment; import com.mhframework.core.io.MHTextFile; @SuppressLint("WorldReadableFiles") public class MHAndroidTextFile extends MHTextFile { // TODO: Make platform function to instantiate this class. private BufferedReader inputReader; private BufferedWriter outputWriter; public MHAndroidTextFile(String filename, Mode mode) { super(filename); if (mode == Mode.READ) { try { InputStream in = MHAndroidApplication.getContext().getAssets().open(filename); //FileInputStream in = MHAndroidApplication.getContext().openFileInput(filename); inputReader = new BufferedReader(new InputStreamReader(in)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else //if (mode == Mode.APPEND) { try { //File f = new File(MHAndroidApplication.getContext().getExternalFilesDir(null), filename); File path = Environment.getExternalStorageDirectory(); File file = new File(path, filename); path.mkdirs(); // if (!getName().startsWith("files/")) // filename = "files/" + filename; // if (!f.exists()) // f.createNewFile(); OutputStream outputStream = new FileOutputStream(file);//MHAndroidApplication.getContext().openFileOutput(filename, Context.MODE_APPEND | Context.MODE_WORLD_READABLE); outputWriter = new BufferedWriter(new OutputStreamWriter(outputStream)); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("ERROR - FileNotFoundException: Failed to open file " + filename + " for output."); } catch (IOException e) { e.printStackTrace(); System.out.println("ERROR - IOException: Failed to open file " + filename + " for output."); } } } @Override public void close() { try { if (inputReader != null) inputReader.close(); if (outputWriter != null) outputWriter.close(); } catch (IOException ioe) { System.out.println("IOException thrown while closing file " + getName() + "."); } } @Override public void write(String data) { try { outputWriter.write(data); } catch (IOException e) { e.printStackTrace(); System.out.println("ERROR - IOException: Error writing to file " + getName() + "."); } } @Override public void append(String data) { try { outputWriter.append(data); } catch (IOException e) { e.printStackTrace(); System.out.println("ERROR - IOException: Error appending to file " + getName() + "."); } } @Override public String readLine() { if (inputReader == null) return null; String inputString = null; //StringBuffer stringBuffer = new StringBuffer(); try { inputString = inputReader.readLine(); // stringBuffer = new StringBuffer(); // while (inputString != null) // { // stringBuffer.append(inputString + "\n"); // inputString = inputReader.readLine(); // } } catch (IOException e) { e.printStackTrace(); } return inputString; //stringBuffer.toString(); } @Override protected void finalize() throws Throwable { close(); } }
package com.eichiba.demo.service; import com.eichiba.demo.entitys.User; import com.eichiba.demo.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class UserService { @Autowired private UserRepository userRepository; public User saveUser(User user){ userRepository.save(user); return user; } public User getUser(String id){ return userRepository.getOne(Integer.parseInt(id)); } }
/* * © Copyright 2016 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied * verbatim in the file “COPYING“. In applying this licence, CERN does not waive the privileges and immunities granted * to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction. */ package cern.molr.mole.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation used by the {@link cern.molr.mole.impl.RunnableSpringMole} to generate the * {@link org.springframework.context.ApplicationContext} * * @author tiagomr */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface MoleSpringConfiguration { /** * @return An array of {@link String}s with all the resources to be used by the Spring injection engine */ public String[] locations(); }
package com.cs240.famillymap.net; import android.app.Person; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ServiceConfigurationError; import request.AuthRequest; import request.LoginRequest; import request.PersonsRequest; import request.RegisterRequest; import result.ClearResult; import result.EventResult; import result.EventsResult; import result.LoginResult; import result.PersonsResult; import result.RegisterResult; import static org.junit.jupiter.api.Assertions.*; /*** * Test each method for the server Proxy to make sure that it works. */ class ServerProxyTest { private ServerProxy proxy; private RegisterRequest rr; private LoginRequest lr; /*** * Set up the host, port, and clear the DB. */ @BeforeEach void preGame(){ proxy = ServerProxy.getInstance(); proxy.setHostname("localhost"); proxy.setPort(8080); proxy.clear(); //Make sure to clear DB each time. } /*** * Personal text to make sure that clear works as * it is integral to the other tests. */ @Test void clear(){ ClearResult result = proxy.clear(); assertTrue(result.isSuccess()); } /*** * Relatively straightforward. If it works, then you were registered. */ @Test void registerNewUser() { RegisterRequest request = new RegisterRequest("Bob","Bob","Bob", "Bob","Robert","m"); assertTrue(proxy.register(request).isSuccess()); } /*** * If you were registered a second time, we should succeed the first time, * and fail the second with a message that you already registered. */ @Test void registerExisting() { RegisterRequest request = new RegisterRequest("John","John","John", "John","Johnathan","m"); RegisterResult resultOne = proxy.register(request); RegisterResult resultTwo = proxy.register(request); assertTrue(resultOne.isSuccess()); assertFalse(resultTwo.isSuccess()); assertEquals("Error: User already registered",resultTwo.getMessage()); } /*** * If you login to a person who was just created, you should get back success. * Also, If you login again, you should get back a new AuthToken. */ @Test void loginExistingUser() { //Register Bob RegisterRequest rr = new RegisterRequest("Bob","Bob","Bob", "Bob","Robert","m"); assertTrue(proxy.register(rr).isSuccess()); LoginRequest lrOne = new LoginRequest("Bob","Bob"); LoginResult r1 = proxy.login(lrOne); assertTrue(r1.isSuccess()); LoginRequest lrTwo = new LoginRequest("Bob","Bob"); LoginResult r2 = proxy.login(lrTwo); assertTrue(r2.isSuccess()); //Check that authTokens differ. This shows Login is working properly assertNotNull(r1.getAuthtoken()); assertNotNull(r2.getAuthtoken()); assertNotEquals(r1.getAuthtoken(),r2.getAuthtoken()); } /*** * If you try to login to an empty database, you should get back an error, * and no important information. */ @Test void loginNonExistingUser() { LoginRequest lrOne = new LoginRequest("Bob","Bob"); LoginResult r1 = proxy.login(lrOne); assertFalse(r1.isSuccess()); assertNull(r1.getAuthtoken()); assertNull(r1.getPersonID()); assertNull(r1.getUsername()); } /*** * If you register a person, and then ask to retrieve those people, * You should be authorized and receive 31 people. */ @Test void personsAuthorized() { RegisterRequest rRequest = new RegisterRequest("Bob","Bob","Bob", "Bob","Robert","m"); //Check to make sure it succeeded. RegisterResult rResult = proxy.register(rRequest); assertTrue(rResult.isSuccess()); assertNotNull(rResult.getPersonID()); //Setup a Person Request. AuthRequest request = new AuthRequest(rResult.getAuthtoken()); PersonsResult result = proxy.persons(request); assertTrue(result.isSuccess()); assertEquals(31,result.getData().size()); } /*** * If you have attempt to use an invalid token to request person information * You should be rejected, and get and Invalid auth Token error. */ @Test void personsInvalidAuthToken() { AuthRequest request = new AuthRequest("1234567890987654321"); PersonsResult result = proxy.persons(request); assertFalse(result.isSuccess()); assertNull(result.getData()); assertEquals("Error: Invalid auth token",result.getMessage()); } /*** * If you register a person, and then ask to retrieve those events, * You should be authorized and receive 93 events. */ @Test void eventsAuthorized() { RegisterRequest rRequest = new RegisterRequest("Bob","Bob","Bob", "Bob","Robert","m"); //Check to make sure it succeeded. RegisterResult rResult = proxy.register(rRequest); assertTrue(rResult.isSuccess()); assertNotNull(rResult.getPersonID()); //Setup a Person Request. AuthRequest request = new AuthRequest(rResult.getAuthtoken()); EventsResult result = proxy.events(request); assertTrue(result.isSuccess()); assertEquals(93,result.getData().size()); } /*** * If you have attempt to use an invalid token to request event information * You should be rejected, and get and Invalid auth Token error. */ @Test void eventsInvalidAuthToken() { AuthRequest request = new AuthRequest("1234567890987654321"); EventsResult result = proxy.events(request); assertFalse(result.isSuccess()); assertNull(result.getData()); assertEquals("Error: Invalid auth token",result.getMessage()); } }
package example; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/v1/time") public class TimeResource { @Inject private TimeService timeService; @GET @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_HTML}) public Long time() { return timeService.time(); } }
package br.com.drem.entity; /** * @author AndreMart * @contacts: andremartins@outlook.com.br;andre.drem@gmail.com * @tel: 63 8412 1921 * @site: drem.com.br */ import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="produto") public class Produto implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.SEQUENCE) private Long idProduto; private String nomeProduto; private String especificacaoProduto; private String precoDeMetroVenda; private String medidaX; private String medidaY; public Long getIdProduto() { return idProduto; } public void setIdProduto(Long idProduto) { this.idProduto = idProduto; } public String getNomeProduto() { return nomeProduto; } public void setNomeProduto(String nomeProduto) { this.nomeProduto = nomeProduto; } public String getEspecificacaoProduto() { return especificacaoProduto; } public void setEspecificacaoProduto(String especificacaoProduto) { this.especificacaoProduto = especificacaoProduto; } public String getPrecoDeMetroVenda() { return precoDeMetroVenda; } public void setPrecoDeMetroVenda(String precoDeMetroVenda) { this.precoDeMetroVenda = precoDeMetroVenda; } public String getMedidaX() { return medidaX; } public void setMedidaX(String medidaX) { this.medidaX = medidaX; } public String getMedidaY() { return medidaY; } public void setMedidaY(String medidaY) { this.medidaY = medidaY; } }
package hw6.task3; public class MyMatrix { public static void main(String[] args) { Matrix matr1 = new Matrix(3, 5, false); Matrix matr11 = new Matrix(3, 5, false); Matrix matr2 = new Matrix(5, 4, false); System.out.println("Матрица (А):"); matr1.showMatrix(); System.out.println("Матрица (AA):"); matr11.showMatrix(); System.out.println("Матрица (A) + (AA):"); matr1.addMatrix(matr11); matr1.showMatrix(); System.out.println("------------------"); System.out.println(); System.out.println("Матрица (A) * 8:"); matr1.multMatrix(8); matr1.showMatrix(); System.out.println("------------------"); System.out.println(); System.out.println("Матрица (AA) * (В):"); Matrix matrixC = matr11.multMatrix(matr2); matrixC.showMatrix(); } }
package my.luftbohne.books; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class BooksController { @GetMapping public ResponseEntity<String> index() { return new ResponseEntity<>("These are my books!", HttpStatus.OK); } }
package shoplistgener.ui; import java.util.List; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import shoplistgener.domain.ShoplistgenerService; /** * Returns HBox-objects that represent the changing view on the right side of the window */ public class UIContructChangingView { private HBox components; /** * Constructor, initializes HBox-object that is returned */ public UIContructChangingView() { this.components = new HBox(); this.components.setSpacing(10); this.components.setPadding(new Insets(10, 10, 10, 10)); } /** * Creates the view for editing recipes * @param name pre-fetches recipe parts if not "" * @param domainHandler object containing application logic * @param recipeName pre-fetched recipe name * @param recipeInstructions pre-fetched recipe instructions * @param ingredientItems pre-fetched ingredients * @param ingredientItemView JavaFX component for viewing pre-fetched ingredients * @param listOfIngredients pre-fetched ingredients * @param ingredientName pre-fetched ingredient name(s) * @param ingredientQuantity pre-fetched ingredient quanti * @param editSceneGridPane JavaFX component for placement of other components * @param addNewRecipeButton for adding new recipe * @param modifyExistingRecipeButton for modifying existing recipe * @return HBox-object representing the changing view on the right * @throws Exception */ public HBox createEditView(String name, ShoplistgenerService domainHandler, TextField recipeName, TextField recipeInstructions, ObservableList<String> ingredientItems, ListView<String> ingredientItemView, List<String> listOfIngredients, TextField ingredientName, TextField ingredientQuantity, GridPane editSceneGridPane, Button addNewRecipeButton, Button modifyExistingRecipeButton) throws Exception { recipeName.setText("Recipe name"); recipeInstructions.setText("Recipe instructions"); listOfIngredients.clear(); ingredientItems.clear(); ingredientItems.add("Ingredients:"); if (!name.equals("")) { this.populateEditView(name, domainHandler, recipeName, recipeInstructions, ingredientItems, listOfIngredients, editSceneGridPane, addNewRecipeButton, modifyExistingRecipeButton); recipeName.setDisable(true); } else { recipeName.setDisable(false); editSceneGridPane.getChildren().removeAll(addNewRecipeButton, modifyExistingRecipeButton); editSceneGridPane.add(addNewRecipeButton, 3, 3); } ingredientName.clear(); ingredientQuantity.clear(); this.components.getChildren().clear(); this.components.getChildren().addAll(editSceneGridPane); return this.components; } private void populateEditView(String name, ShoplistgenerService domainHandler, TextField recipeName, TextField recipeInstructions, ObservableList<String> ingredientItems, List<String> listOfIngredients, GridPane editSceneGridPane, Button addNewRecipeButton, Button modifyExistingRecipeButton) throws Exception { List<String> modifiedRecipeInList = domainHandler.fetchRecipeList(name); recipeName.setText(modifiedRecipeInList.get(0)); recipeInstructions.setText(modifiedRecipeInList.get(1)); for (String ing : modifiedRecipeInList.get(2).split("\n")) { if (ing.isEmpty()) { continue; } String toWhitespace = ing.replace(";", " "); ingredientItems.add(toWhitespace); listOfIngredients.add(toWhitespace); } editSceneGridPane.getChildren().removeAll(addNewRecipeButton, modifyExistingRecipeButton); editSceneGridPane.add(modifyExistingRecipeButton, 3, 3); } /** * Creates the view for error messages * @param message error message to be displayed * @return HBox-object representing the changing view on the right */ public HBox createErrorView(String message) { Label errorMessage = new Label(); errorMessage.setText(message); this.components.getChildren().clear(); this.components.getChildren().add(errorMessage); return this.components; } /** * Creates the view for Menu * @param newCourses names of the courses * @param newShoppingList names and quantities of the ingredients * @param listMenu JavaFX component for viewing Menu * @param listShoppingList JavaFX component for viewing shopping list * @param menuItems list of the courses * @param menuPlacement JavaFX component for placement of other components * @return HBox-object representing the changing view on the right * @throws Exception */ public HBox createMenuView(String newCourses, String newShoppingList, String newShoppingListModifiedByKitchenIngredients, Label listMenu, Label listShoppingList, Label listShoppingListwithKitchenIngredients, ObservableList<String> menuItems, HBox menuPlacement) throws Exception { listMenu.setText("Menu:\n" + newCourses); listShoppingList.setText("Shopping List from Recipes:\n" + newShoppingList); listShoppingListwithKitchenIngredients.setText("Shopping List without Kitchen Ingredients:\n" + newShoppingListModifiedByKitchenIngredients); menuItems.setAll(listMenu.getText().split("\\n")); VBox shoppingListPlacement = new VBox(); shoppingListPlacement.getChildren().addAll(listShoppingList, listShoppingListwithKitchenIngredients); this.components.getChildren().clear(); this.components.getChildren().addAll(menuPlacement, shoppingListPlacement); return this.components; } /** * Creates the view for viewing recipes * @param listRecipes list of all the recipes in the database * @param recipeSearchOptions JavaFX component holding other components for recipe searches * @param showRecipe space for displaying a single recipe * @param recipeModifications JavaFX component holding other components for recipe modifications * @return HBox-object representing the changing view on the right * @throws Exception */ public HBox createRecipeView(ScrollPane listRecipes, VBox recipeSearchOptions, Label showRecipe, VBox recipeModifications) throws Exception { this.components.getChildren().clear(); this.components.getChildren().addAll(listRecipes, recipeSearchOptions, recipeModifications); return this.components; } /** * Creates the view for manipulating ingredients in the kitchen * @param listAllIngredients list of all ingredients in the database * @param addselectedIngredientToKitchen JavaFX component for adding selected ingredient to the kitchen * @param listIngredientsInKitchen list of ingredients in the kitchen * @param removeSelectedIngredientInKitchen JavaFX component for removing ingredient from the kitchen * @param updateSelectedIngredientInKitchen JavaFX component for updating the quantity of an ingredient in the kitchen * @return HBox-object representing the changing view on the right */ public HBox createKitchenView(ScrollPane listAllIngredients, Button addselectedIngredientToKitchen, ScrollPane listIngredientsInKitchen, Button removeSelectedIngredientInKitchen, Button updateSelectedIngredientInKitchen) { VBox ingredientModifications = new VBox(); ingredientModifications.getChildren().addAll(removeSelectedIngredientInKitchen, updateSelectedIngredientInKitchen); this.components.getChildren().clear(); this.components.getChildren().addAll(listAllIngredients, addselectedIngredientToKitchen, listIngredientsInKitchen, ingredientModifications); return this.components; } }
/** * Write a description of class PlayACSLLAND here. * * @author Hannah Pang * @version February 1, 2016 */ import java.util.*; public class PlayACSLLAND { public static void main(String[] args) { Scanner console = new Scanner(System.in); // Play 5 games for (int i = 1; i <= 5; i++) { Game g = new Game(); System.out.print("Output #" + i + ": "); g.play(console); } } }
/* ### PROGRAMMKOPF ### Lineare Programmierung; Fallauswahl Aufgabe 3 FS23 Marc Freytag Version: 1.1 20121106 addiert, subtrahiert, multipliziert und dividiert zwei Zahlen mit Fallauswahl ### ENDE PROGRAMMKOPF ### */ public class aslp6fallauswahl { // ### HAUPTFUNKTION ### public static void main(String[] args ) { // ### DEKLARATIONSTEIL ### // float - Variablen werden deklariert und der Wert 0 zugewiesen float zahl1 = 0f, zahl2 = 0f; float ergebnisaddition = 0f; float ergebnissubtraktion = 0f; float ergebnismultiplikation = 0f; float ergebnisdivision = 0f; float ergebnisdivrest = 0f; // char Variable fuer switch-Anweisung char wahl = ' '; // ### ENDE DEKLARATIONSTEIL ### // gibt Text auf Bildschirm aus System.out.print("Bitte geben Sie eine Zahl ein: "); // wartet auf Eingabe einer Zahl zahl1 = Tastatur.liesInt(); // gibt Text auf Bildschirm aus System.out.print("Bitte geben Sie eine zweite Zahl ein: "); // wartet auf Eingabe einer Zahl zahl2 = Tastatur.liesInt(); // addiere zahl1 und zahl2 und speichere es in ergebnisaddition ergebnisaddition = zahl1 + zahl2; // subtrahiere zahl2 von zahl1 und speichere es in ergebnissubtraktion ergebnissubtraktion = zahl1 - zahl2; // multipliziere zahl1 und zahl2 und speichere es in ergebnismultiplikation ergebnismultiplikation = zahl1 * zahl2; // dividiere zahl2 durch zahl1 und speichere es in ergebnisdivision ergebnisdivision = zahl1 / zahl2; // dividiere zahl2 durch zahl1 und speichere Rest in ergebnisdivrest ergebnisdivrest = zahl1 % zahl2; // gibt Text auf Bildschirm aus System.out.print("Welche Operation soll durchgeführt werden? \n Auswahl: \n1. +\n2. -\n3. *\n4. /\n5. %\n Ihre Eingabe: "); wahl = Tastatur.liesChar(); // Beginn der switch-Anweisung switch (wahl) { case '+': case '1': System.out.print(" Addition gewaehlt\n"); System.out.print(zahl1 + " + " + zahl2 + " = " + ergebnisaddition + "\n"); break; case '-': case '2': System.out.print(" Subtraktion gewaehlt\n"); System.out.print(zahl1 + " - " + zahl2 + " = " + ergebnissubtraktion + "\n"); break; case '*': case '3': System.out.print(" Multiplikation gewaehlt\n"); System.out.print(zahl1 + " * " + zahl2 + " = " + ergebnismultiplikation + "\n"); break; case '/': case '4': System.out.print(" Division gewaehlt\n"); System.out.print(zahl1 + " / " + zahl2 + " = " + ergebnisdivision + "\n"); break; case '%': case '5': System.out.print(" Divisionsrest gewaehlt\n"); System.out.print(zahl1 + " / " + zahl2 + " = " + ergebnisdivrest + "\n"); break; default: System.out.print(" Fehleingabe "); } // Ende der switch-Anweisung System.out.print(" Ende "); } // ### ENDE HAUPTFUNKTION ### }
package com.ymhd.mifei.user; import android.content.Context; import android.content.SharedPreferences; import com.ymhd.main.MyApplication; import com.ymhd.mifei.annotation.NotNull; /** * Created by Administrator on 2016/2/17. */ public class ShareManager { public final static String FILE_USER = "mifei.com.user"; protected static SharedPreferences getUserSharePreferences() { return MyApplication.getInstance().getSharedPreferences(FILE_USER, Context.MODE_PRIVATE); } public static void saveUserAnyString(@NotNull String key, @NotNull String value) { if (value == null) return; getUserSharePreferences().edit().putString(key, value).apply(); } public static String getUserAnyString(@NotNull String key) { return getUserSharePreferences().getString(key, null); } }
package com.kkwli.springcloud.service; /** * @Classname IMessageProviderService * @Date 2021/9/27 8:46 * @Created by kkwli */ public interface IMessageProviderService { String send(); }
package leader.game.event; public interface GameEventProducer { public void publishGameEvent(GameEvent event); }
package com.utils; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; /** * 文件编码获取与转换 * * @作者 张剑 * @版本 1.0 * @日期 2014年8月18日 * @时间 上午11:49:17 */ public class ZJ_TxtUtils { private static final Logger logger = Logger.getLogger(Object.class); /** * 获取classpath * * @return */ public static String getClassPath() { String classPath = ""; classPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); return classPath; } /** * 读取文件内容(以指定编码读) * * @param filePath * @param charset */ public static void readTxtFile(String filePath, String charset) { if (null == charset || "".equals(charset)) { charset = "UTF-8"; } try { File file = new File(filePath); if (file.isFile() && file.exists()) { // 判断文件是否存在 InputStreamReader read = new InputStreamReader(new FileInputStream(file), charset);// 考虑到编码格式 BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { System.out.println(lineTxt); } read.close(); } else { logger.info("找不到文件:" + filePath); } } catch (Exception e) { logger.info("读取文件内容出错"); e.printStackTrace(); } } /** * 读取文件内容(智能判断文件编码) * * @param filePath * @param charset */ public static void readTxtFile(String filePath) { String charset = getFilecharset(new File(filePath)); logger.info("文件的编码为:" + charset); readTxtFile(filePath, charset); } /** * 获取文件编码 * * @param sourceFile * @return */ private static String getFilecharset(File sourceFile) { String charset = "GBK"; byte[] first3Bytes = new byte[3]; BufferedInputStream bis = null; try { boolean checked = false; bis = new BufferedInputStream(new FileInputStream(sourceFile)); bis.mark(0); int read = bis.read(first3Bytes, 0, 3); if (read == -1) { return charset; // 文件编码为 ANSI } else if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) { charset = "UTF-16LE"; // 文件编码为 Unicode checked = true; } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) { charset = "UTF-16BE"; // 文件编码为 Unicode big endian checked = true; } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF) { charset = "UTF-8"; // 文件编码为 UTF-8 checked = true; } bis.reset(); if (!checked) { while ((read = bis.read()) != -1) { if (read >= 0xF0) break; if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK break; if (0xC0 <= read && read <= 0xDF) { read = bis.read(); if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF) continue; else break; } else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小 read = bis.read(); if (0x80 <= read && read <= 0xBF) { read = bis.read(); if (0x80 <= read && read <= 0xBF) { charset = "UTF-8"; break; } else break; } else break; } } } } catch (IOException e) { logger.info("找不到文件:" + sourceFile); return null; } finally { if (null != bis) { try { bis.close(); } catch (IOException e) { } } } return charset; } /** * 读取配置文件 * * @param fileName * @param charset * @return */ public static Set<String> getConfigSet(String fileName, String charset) { Set<String> set = new HashSet<String>(); if (null == charset || "".equals(charset)) { charset = "UTF-8"; } String filePath = getClassPath() + fileName; try { File file = new File(filePath); if (file.isFile() && file.exists()) { // 判断文件是否存在 InputStreamReader read = new InputStreamReader(new FileInputStream(file), charset);// 考虑到编码格式 BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { if (!"".equals(lineTxt)) { set.add(lineTxt); } } read.close(); } else { logger.info("找不到文件:" + filePath); } } catch (Exception e) { logger.info("读取文件内容出错"); e.printStackTrace(); } return set; } /** * 读取配置文件 * * @param fileName * @param charset * @return */ public static List<String> getConfigList(String fileName, String charset) { List<String> list = new LinkedList<String>(); if (null == charset || "".equals(charset)) { charset = "UTF-8"; } String filePath = getClassPath() + fileName; try { filePath = URLDecoder.decode(filePath, "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } try { File file = new File(filePath); if (file.isFile() && file.exists()) { // 判断文件是否存在 InputStreamReader read = new InputStreamReader(new FileInputStream(file), charset);// 考虑到编码格式 BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { if (!"".equals(lineTxt)) { list.add(lineTxt); } } read.close(); } else { logger.info("找不到文件:" + filePath); } } catch (Exception e) { logger.info("读取文件内容出错"); e.printStackTrace(); } return list; } public static void main(String[] args) { try { readTxtFile("D://1.txt"); System.out.println(new String("我是好人".getBytes(), "UTF-8")); System.out.println(getClassPath()); System.out.println(getConfigSet("excludeUrls.txt", "UTF-8")); } catch (Exception e) { e.printStackTrace(); } } }
package edu.ucsb.cs56.pconrad.parsing.syntax; public class GreaterThan extends OperatorScaffold { // begin constants public static final GreaterThan GREATERTHAN = new GreaterThan(); // end constants public GreaterThan() { super(">"); } }
package com.fgtit.app; import java.io.File; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Environment; public class LogsList { private static LogsList instance; public static LogsList getInstance() { if(null == instance) { instance = new LogsList(); } return instance; } public List<LogItem> logsList=new ArrayList<LogItem>(); private SQLiteDatabase db; public static boolean IsFileExists(String filename){ File f=new File(filename); if(f.exists()){ return true; } return false; } public void Init(){ if(IsFileExists(Environment.getExternalStorageDirectory() + "/OnePass/logs.db")){ db=SQLiteDatabase.openOrCreateDatabase(Environment.getExternalStorageDirectory() + "/OnePass/logs.db",null); }else{ db=SQLiteDatabase.openOrCreateDatabase(Environment.getExternalStorageDirectory() + "/OnePass/logs.db",null); String sql="CREATE TABLE TB_LOGS(userid INTEGER," + "username CHAR[24]," + "status1 INTEGER," + "status2 INTEGER," + "datetime DATETIME);"; db.execSQL(sql); } } public void Clear(){ logsList.clear(); String sql = "delete from TB_LOGS"; db.execSQL(sql); } public String getStringDate() { Date currentTime = new Date(System.currentTimeMillis()); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = formatter.format(currentTime); return dateString; } public void Append(int userid,String username,int statu1,int statu2){ String sql="insert into TB_LOGS(userid,username,status1,status2,datetime) " + "values(?,?,?,?,?)"; //String datetime=getStringDate(); Date currentTime = new Date(System.currentTimeMillis()); Timestamp timestamp = new Timestamp(currentTime.getTime()); Object[] args = new Object[]{userid,username,statu1,statu2,timestamp}; db.execSQL(sql,args); } public List<LogItem> Query(int qtype,String qname,String qval){ logsList.clear(); switch(qtype){ case 0:{ Cursor cursor = db.query ("TB_LOGS",null,null,null,null,null,null); if(cursor!=null){ if(cursor.moveToFirst()){ for(int i=0;i<cursor.getCount();i++){ LogItem li=new LogItem(); li.userid=cursor.getInt(0); li.username=cursor.getString(1); li.status1=cursor.getInt(2); li.status2=cursor.getInt(3); li.datetime=cursor.getString(4); logsList.add(li); cursor.moveToNext(); } } cursor.close(); } } break; case 1: break; case 2: break; } return logsList; } public byte[] LogItemToBytes(LogItem li){ byte[] lb=new byte[10]; Date date=null; int year,month,day,hour,min,sec; try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); date = (Date)format.parse(li.datetime); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); year = calendar.get(Calendar.YEAR); month = calendar.get(Calendar.MONTH)+1; //月份是从0开始。 day = calendar.get(Calendar.DAY_OF_MONTH); hour = calendar.get(Calendar.HOUR_OF_DAY); min = calendar.get(Calendar.MINUTE); sec = calendar.get(Calendar.SECOND); lb[0]=(byte) (li.userid&0xFF); lb[1]=(byte) ((li.userid>>8)&0xFF); lb[2]=(byte) li.status1; lb[3]=(byte) li.status2; lb[4]=(byte) (year-2000); lb[5]=(byte) month; lb[6]=(byte) day; lb[7]=(byte) hour; lb[8]=(byte) min; lb[9]=(byte) sec; return lb; } catch (ParseException e) { } return null; } }
/*********************************************************** * @Description : * @author : 梁山广(Liang Shan Guang) * @date : 2020/5/17 16:25 * @email : liangshanguang2@gmail.com ***********************************************************/ package 第04章_工厂方法模式.第9节_习题.第5题; public class HistogramChartFactory implements ChartFactory { @Override public Chart draw() { return new HistogramChart(); } }
package com.tdd.potter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; class BookOrganizer { private List<Set<Integer>> booksSet = new ArrayList<Set<Integer>>(); public List<Set<Integer>> addBooks(int[] books) { booksSet.clear(); for (int book : books) { if (!bookAddedToBookSet(booksSet, book)) { createNewBookSet(booksSet, book); } reorderBookSets(booksSet); } return booksSet; } public List<Set<Integer>> getBooksSet() { return booksSet; } private void reorderBookSets(List<Set<Integer>> bookSets) { Collections.sort(bookSets, new Comparator<Set<Integer>>() { @Override public int compare(Set<Integer> firstBookSet, Set<Integer> secondBookSet) { if (firstBookSet.size() == 3) { return -1; } if (secondBookSet.size() == 3) { return 1; } return 0; } }); } private boolean bookAddedToBookSet(List<Set<Integer>> bookSets, int book) { for (Set<Integer> bookSet : bookSets) { if (!bookSet.contains(book)) { bookSet.add(book); return true; } } return false; } private void createNewBookSet(List<Set<Integer>> bookSets, int book) { Set<Integer> bookSet = new HashSet<Integer>(); bookSet.add(book); bookSets.add(bookSet); } }
package com.esum.wp.ims.monitorinfo.dao; import java.util.List; import java.util.Map; import com.esum.appframework.dao.IBaseDAO; import com.esum.wp.ims.monitorinfo.MonitorInfo; public interface IMonitorInfoDAO extends IBaseDAO{ public Map saveMonitorInfoExcel(MonitorInfo info); public List selectNodeList(); }
package it.univr.domain.tajs.original; import org.junit.Assert; import org.junit.Test; import it.univr.main.Analyzer; import it.univr.state.AbstractEnvironment; import it.univr.state.Variable; public class TAJSWhileTest { private TAJSAbstractDomain domain = new TAJSAbstractDomain(); @Test public void testWhile001() throws Exception { String file = "src/test/resources/while/while001.js"; AbstractEnvironment state = Analyzer.analyze(file, domain, true); // State sizeStore Assert.assertEquals(state.sizeStore(), 1); Assert.assertEquals(state.sizeHeap(), 0); // State values Assert.assertEquals(state.getValue(new Variable("x")), TAJSNumbers.createUnsigned()); } @Test public void testWhile002() throws Exception { String file = "src/test/resources/while/while002.js"; AbstractEnvironment state = Analyzer.analyze(file, domain, true); // State sizeStore Assert.assertEquals(state.sizeStore(), 1); Assert.assertEquals(state.sizeHeap(), 0); // State values Assert.assertEquals(state.getValue(new Variable("x")), TAJSStrings.createNotUnsignedString()); } @Test public void testWhile003() throws Exception { String file = "src/test/resources/while/while003.js"; AbstractEnvironment state = Analyzer.analyze(file, domain, true); // State sizeStore Assert.assertEquals(state.sizeStore(), 1); Assert.assertEquals(state.sizeHeap(), 0); // State values Assert.assertEquals(state.getValue(new Variable("x")), new TAJSStrings("")); } @Test public void testWhile004() throws Exception { String file = "src/test/resources/while/while004.js"; AbstractEnvironment state = Analyzer.analyze(file, domain, true); // State sizeStore Assert.assertEquals(state.sizeStore(), 1); Assert.assertEquals(state.sizeHeap(), 0); // State values Assert.assertEquals(state.getValue(new Variable("x")), TAJSNumbers.createUnsigned()); } @Test public void testWhile005() throws Exception { String file = "src/test/resources/while/while005.js"; AbstractEnvironment state = Analyzer.analyze(file, domain, true); // State sizeStore Assert.assertEquals(state.sizeStore(), 2); Assert.assertEquals(state.sizeHeap(), 0); // State values Assert.assertEquals(state.getValue(new Variable("x")), TAJSNumbers.createUnsigned()); Assert.assertEquals(state.getValue(new Variable("y")), TAJSNumbers.createUnsigned()); } @Test public void testWhile006() throws Exception { String file = "src/test/resources/while/while006.js"; AbstractEnvironment state = Analyzer.analyze(file, domain, true); // State sizeStore Assert.assertEquals(state.sizeStore(), 2); Assert.assertEquals(state.sizeHeap(), 0); // State values Assert.assertEquals(state.getValue(new Variable("x")), TAJSNumbers.createUnsigned()); Assert.assertEquals(state.getValue(new Variable("y")), TAJSNumbers.createUnsigned()); } }
package com.pibs.form; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import com.pibs.constant.MiscConstant; import com.pibs.model.AdditionalServices; import com.pibs.model.AdditionalServicesCategory; import com.pibs.model.Building; import com.pibs.model.Discount; import com.pibs.model.Employee; import com.pibs.model.Equipment; import com.pibs.model.LaboratoryExamination; import com.pibs.model.ListValue; import com.pibs.model.MedicalSupply; import com.pibs.model.MonitorNursery; import com.pibs.model.Patient; import com.pibs.model.Professional; import com.pibs.model.Radiology; import com.pibs.model.Room; import com.pibs.model.RoomCategory; import com.pibs.model.Specialization; import com.pibs.model.Surgery; import com.pibs.model.User; /** * * @author dward * @since 16Apr2018 */ public class ArchiveFormBean extends PIBSFormBean { /** * */ private static final long serialVersionUID = 1L; private int entityId; private String entity; private List<Professional> profList; private List<Surgery> surgeryList; private List<Room> roomList; private List<RoomCategory> roomCategList; private List<Equipment> equipList; private List<Discount> discountList; private List<AdditionalServices> addServList; private List<AdditionalServicesCategory> addServCategList; private List<Radiology> radList; private List<MedicalSupply> medList; private List<Specialization> specList; private List<Building> buildList; private List<LaboratoryExamination> labList; private List<Patient> patientList; private List<MonitorNursery> nurseryList; private List<Employee> empList; private List<User> userList; private int noOfPages; private int currentPage; private boolean transactionStatus; private String transactionMessage; private List<ListValue> entityTypeLOV; private boolean gotRecords; public ArchiveFormBean(){} public List<ListValue> getEntityTypeLOV() { return entityTypeLOV; } public void setEntityTypeLOV(List<ListValue> entityTypeLOV) { this.entityTypeLOV = entityTypeLOV; } public int getNoOfPages() { return noOfPages; } public void setNoOfPages(int noOfPages) { this.noOfPages = noOfPages; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public boolean isTransactionStatus() { return transactionStatus; } public void setTransactionStatus(boolean transactionStatus) { this.transactionStatus = transactionStatus; } public String getTransactionMessage() { return transactionMessage; } public void setTransactionMessage(String transactionMessage) { this.transactionMessage = transactionMessage; } public int getEntityId() { return entityId; } public void setEntityId(int entityId) { this.entityId = entityId; } public String getEntity() { return entity; } public void setEntity(String entity) { this.entity = entity; } public List<Professional> getProfList() { return profList; } public void setProfList(List<Professional> profList) { this.profList = profList; } public List<Surgery> getSurgeryList() { return surgeryList; } public void setSurgeryList(List<Surgery> surgeryList) { this.surgeryList = surgeryList; } public List<Room> getRoomList() { return roomList; } public void setRoomList(List<Room> roomList) { this.roomList = roomList; } public List<RoomCategory> getRoomCategList() { return roomCategList; } public void setRoomCategList(List<RoomCategory> roomCategList) { this.roomCategList = roomCategList; } public List<Equipment> getEquipList() { return equipList; } public void setEquipList(List<Equipment> equipList) { this.equipList = equipList; } public List<Discount> getDiscountList() { return discountList; } public void setDiscountList(List<Discount> discountList) { this.discountList = discountList; } public List<AdditionalServices> getAddServList() { return addServList; } public void setAddServList(List<AdditionalServices> addServList) { this.addServList = addServList; } public List<AdditionalServicesCategory> getAddServCategList() { return addServCategList; } public void setAddServCategList( List<AdditionalServicesCategory> addServCategList) { this.addServCategList = addServCategList; } public List<Radiology> getRadList() { return radList; } public void setRadList(List<Radiology> radList) { this.radList = radList; } public List<MedicalSupply> getMedList() { return medList; } public void setMedList(List<MedicalSupply> medList) { this.medList = medList; } public List<Specialization> getSpecList() { return specList; } public void setSpecList(List<Specialization> specList) { this.specList = specList; } public List<Building> getBuildList() { return buildList; } public void setBuildList(List<Building> buildList) { this.buildList = buildList; } public List<LaboratoryExamination> getLabList() { return labList; } public void setLabList(List<LaboratoryExamination> labList) { this.labList = labList; } public List<Patient> getPatientList() { return patientList; } public void setPatientList(List<Patient> patientList) { this.patientList = patientList; } public List<MonitorNursery> getNurseryList() { return nurseryList; } public void setNurseryList(List<MonitorNursery> nurseryList) { this.nurseryList = nurseryList; } public List<Employee> getEmpList() { return empList; } public void setEmpList(List<Employee> empList) { this.empList = empList; } public List<User> getUserList() { return userList; } public void setUserList(List<User> userList) { this.userList = userList; } public boolean isGotRecords() { if ((profList!=null && !profList.isEmpty()) || (surgeryList!=null && !surgeryList.isEmpty()) || (roomList!=null && !roomList.isEmpty()) || (roomCategList!=null && !roomCategList.isEmpty()) || (equipList!=null && !equipList.isEmpty()) || (discountList!=null && !discountList.isEmpty()) || (addServList!=null && !addServList.isEmpty()) || (addServCategList!=null && !addServCategList.isEmpty()) || (radList!=null && !radList.isEmpty()) || (medList!=null && !medList.isEmpty()) || (specList!=null && !specList.isEmpty()) || (buildList!=null && !buildList.isEmpty()) || (labList!=null && !labList.isEmpty()) || (patientList!=null && !patientList.isEmpty()) || (nurseryList!=null && !nurseryList.isEmpty()) || (empList!=null && !empList.isEmpty()) || (userList!=null && !userList.isEmpty()) ) { gotRecords = true; } return gotRecords; } public void setGotRecords(boolean gotRecords) { this.gotRecords = gotRecords; } public void populateEntityTypeDropdownList(HttpServletRequest request) throws Exception{ @SuppressWarnings("unchecked") List<ListValue> lovList = (ArrayList<ListValue>) request.getSession().getAttribute(MiscConstant.LOVTYPE_ENTITY_TYPE_SESSION); if (lovList!=null) { setEntityTypeLOV(lovList); } } @Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { // TODO Auto-generated method stub ActionErrors errors = new ActionErrors(); return errors; } }
/** * Clasa Senzor implementeaza interfata Subject */ package observer2; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Random; /** * Implementeaza interfata Subject * @author Ali */ public class Senzor implements Subject { private List<Observer> obs = new LinkedList<Observer>(); private int valCurenta = 0; /** Adauga un Obsever*/ public void addObserver(Observer o) { obs.add(o); } /** Sterge un Obsever*/ public void removeObserver(Observer o) { obs.remove(o); } /** Notifica Observerii*/ public void notifyObserver() { Iterator i = obs.iterator(); while (i.hasNext()) { Observer o = (Observer) i.next(); o.upDate(this); } } /** Genereaza un numar random*/ public void generare() { Random serieRandom = new Random(); valCurenta = serieRandom.nextInt(80); notifyObserver(); } /** Returneaza valoarea curenta*/ public int getVal() { return valCurenta; } }
import com.sun.xml.internal.bind.v2.runtime.reflect.Lister; import java.awt.*; import javax.swing.*; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ActionListener; public class Impuestos extends JFrame implements ActionListener { //Inicializar Paneles private JPanel Panel1; private JPanel Panel2; private JPanel Panel3; //Inicializar Botones private JButton B1, B2, B3; private JCheckBox CH1, CH2, CH3; //Inicializar Labels private JLabel L1, L2, L3, L4; private JLabel L5, L6, L7; private JLabel L8; //Inicializar Text Field private JTextField T1, T2, T3, T4; private JTextField T5; //Referenciar paneles public Impuestos() { super("Calculo de Impuestos"); this.setLayout(new BorderLayout()); Panel1 = new JPanel(); Panel2 = new JPanel(); Panel3 = new JPanel(); Container ContentPane = getContentPane(); ContentPane.setLayout(new FlowLayout()); //Pertenece Panel 1 L1 = new JLabel("Marca: "); T1 = new JTextField(10); L2 = new JLabel("Linea"); T2 = new JTextField(10); L3 = new JLabel("Modelo"); T3 = new JTextField(10); L4 = new JLabel("Valor"); T4 = new JTextField(10); B1 = new JButton("Buscar"); // Pertenece Panel 2 CH1 = new JCheckBox("Descuento", false); CH2 = new JCheckBox("Traslado Cuenta", false); CH3 = new JCheckBox("servicio publico", false); //Pertenece Panel 3 L8 = new JLabel("Total a Pagar"); T5 = new JTextField(10); B2 = new JButton("Limpiar"); B3 = new JButton("Calcular"); this.add(Panel1, BorderLayout.NORTH); this.add(Panel2, BorderLayout.CENTER); this.add(Panel3, BorderLayout.SOUTH); this.setDefaultCloseOperation(EXIT_ON_CLOSE); // Panel 1 Ubicado en el norte Panel1.setLayout(new BoxLayout(Panel1, BoxLayout.X_AXIS)); // L1.setBounds(10,60,100,30); Panel1.add(L1); //T1.setBounds(120,60,150,30); Panel1.add(T1); Panel1.add(L2); Panel1.add(T2); Panel1.add(L3); Panel1.add(T3); Panel1.add(L4); Panel1.add(T4); Panel1.add(B1); // Panel 2 ubicado en el centro Panel2.add(CH1); Panel2.add(CH2); Panel2.add(CH3); //Panel 3 Ubicado en el sur Panel3.setLayout(new BoxLayout(Panel3, BoxLayout.X_AXIS)); Panel3.add(L8); Panel3.add(T5); Panel3.add(B2); Panel3.add(B3); B3.setLayout(new BoxLayout(B3, BoxLayout.X_AXIS)); this.B2.addActionListener(this); this.B3.addActionListener(this); this.CH1.addActionListener(this); this.CH2.addActionListener(this); this.CH3.addActionListener(this); pack(); setResizable(false); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource().equals(CH1) == true) { JOptionPane.showMessageDialog(null, "Se Realizo el proceso"); double n1 = Double.parseDouble(T4.getText()); double Sum = n1 * .10; double res = n1 - Sum; String valorTotal = Double.toString(res); T5.setText(valorTotal); // this.T1.setText("Hola Mundo"); } if (e.getSource().equals(CH2)) { JOptionPane.showMessageDialog(null, "Se realizo el proceso"); double n1 = Double.parseDouble(T4.getText()); double Sum = n1 - 50000; String valorTotal = Double.toString(Sum); T5.setText(valorTotal); } if (e.getSource().equals(CH3)) { JOptionPane.showMessageDialog(null, "Se realizo el proceso"); double n1 = Double.parseDouble(T4.getText()); double Sum = n1 * .5; double res = n1 - Sum; String valorTotal = Double.toString(res); T5.setText(valorTotal); } if (e.getSource().equals(B2)) { this.T1.setText("Oprimiste boton 2"); T1.setText(""); T2.setText(""); T3.setText(""); T4.setText(""); T5.setText(""); } } public static void main(String[] args) { /*Ventana2 v = new Ventana2(); v.setVisible(true); v.setBounds(200,200,400,250); */ Impuestos I = new Impuestos(); I.setVisible(true); I.setBounds(100,200,700,200); I.setResizable(true); } }
package ru.orbot90.guestbook.services; import ru.orbot90.guestbook.model.SignUpRequest; import ru.orbot90.guestbook.model.User; import javax.transaction.Transactional; /** * @author Iurii Plevako orbot90@gmail.com **/ public interface UserService { @Transactional User createUser(SignUpRequest user); }
import java.util.Scanner; public class ATM { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s = input.nextLine(); String[] array = s.split(" "); int withdraw = Integer.parseInt(array[0]); double totalAmount = Double.parseDouble(array[1]); if(withdraw%5==0 && (totalAmount-withdraw-0.5>=0)) { totalAmount = totalAmount-withdraw-0.5; } System.out.printf("%.2f", totalAmount); } }