text
stringlengths
10
2.72M
package LeetCode.Backtracking; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class IslandPerimeter { int res, m ,n; // O(mn) time and O(mn) space public int islandPerimeter(int[][] graph){ res = 0; m = graph.length; n = graph[0].length; List<int[]> set = new ArrayList<>(); for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(graph[i][j] == 1) { set.add(new int[]{i,j}); } } } for(int[] arr : set){ checkNeighbors(graph, arr[0], arr[1]); } return res; } // O(mn) time and O(1) space public int islandPerimeterII(int[][] graph){ res = 0; m = graph.length; n = graph[0].length; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(graph[i][j] == 1) { checkNeighbors(graph, i, j); } } } return res; } public void checkNeighbors(int[][] graph, int i, int j){ if(i == 0) res++; if(i == m-1) res++; if(j == 0) res++; if(j == n-1) res++; // top if(i-1 >= 0 && graph[i-1][j] == 0) res++; // bottom if(i+1 < m && graph[i+1][j] == 0) res++; // right if(j+1 < n && graph[i][j+1] == 0) res++; // left if(j-1 >= 0 && graph[i][j-1] == 0) res++; } public static void main(String[] args){ int[][] graph = {{0,1,0,0},{1,1,1,0},{0,1,0,0},{1,1,0,0}}; IslandPerimeter i = new IslandPerimeter(); System.out.print(i.islandPerimeterII(graph)); } }
package com.sarf.service; import java.util.List; import javax.inject.Inject; import org.springframework.stereotype.Service; import com.sarf.dao.Qna_ReplyDAO; import com.sarf.vo.Qna_ReplyVO; @Service public class Qna_ReplyServiceImpl implements Qna_ReplyService{ @Inject private Qna_ReplyDAO dao; // 댓글 목록 @Override public List<Qna_ReplyVO> readReply(int bno) throws Exception { return dao.readReply(bno); } // 댓글 작성 @Override public void writeReply(Qna_ReplyVO qna_vo) throws Exception { dao.writeReply(qna_vo); } // 댓글 수정 @Override public void updateReply(Qna_ReplyVO qna_vo) throws Exception { dao.updateReply(qna_vo); } // 선택된 댓글 조회 @Override public Qna_ReplyVO selectReply(int rno) throws Exception { return dao.selectReply(rno); } // 댓글 삭제 @Override public void deleteReply(Qna_ReplyVO qna_vo) throws Exception { dao.deleteReply(qna_vo); } }
/** * */ package fl.sabal.source.interfacePC.Codes.Event; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; /** * @author FL-AndruAnnohomy * */ public class lettersToUppsercase implements KeyListener { /** * */ public lettersToUppsercase() { // TODO Auto-generated constructor stub } /* * (non-Javadoc) * * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent) */ @Override public void keyTyped(KeyEvent event) { char c = event.getKeyChar(); int k = (int) event.getKeyChar(); if (k >= 97 && k <= 122 || k >= 65 && k <= 90) { if (event.getKeyCode() != KeyEvent.VK_BACK_SPACE) { event.setKeyChar(Character.toUpperCase(c)); } } } /* * (non-Javadoc) * * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent) */ @Override public void keyPressed(KeyEvent event) { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent) */ @Override public void keyReleased(KeyEvent event) { // TODO Auto-generated method stub } }
// A 2D Matrix ////// public class Matrix { // Fields /////////// private int[][] matrix; private int rows; private int columns; // Constructor ////// public Matrix(int rows, int columns) { this.rows = rows; this.columns = columns; matrix = new int[rows][columns]; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { matrix[i][j] = 1; } } } // Getters ////////// public int[][] getMatrix() { return matrix; } public int getRows() { return rows; } public int getColumns() { return columns; } // Setters ////////// public void setElement(int row, int column, int value) { if (validReference(row, column)) { matrix[row][column] = value; prettyPrintSleepFlush(); } } public void setRow(int row, String values) { String[] strArray = commaSplit(values); int[] intArray = toInt(strArray); if (valid(row, rows) && intArray.length == columns) { for(int i = 0; i < intArray.length; i++) { setElement(row, i, intArray[i]); } } else { printOutOfBounds(); } } public void setColumn(int column, String values) { String[] strArray = commaSplit(values); int[] intArray = toInt(strArray); if (valid(column, columns) && intArray.length == columns) { for(int i = 0; i < intArray.length; i++) { setElement(i, column, intArray[i]); } } else { printOutOfBounds(); } } public void fillMatrix(int value) { for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { setElement(i, j, value); } } } public void setMatrix(String values) { String [] rowsArray = semicolonSplit(values); for(int i = 0; i < rowsArray.length; i++) { setRow(i, rowsArray[i]); } } // Validators /////// private boolean validReference(int row, int column) { if (valid(row, rows) && valid(column, columns)) { return true; } else { return false; } } private boolean valid(int item, int set) { if (item < set && item >= 0) { return true; } else { printOutOfBounds(); return false; } } // Type conversion // private String[] commaSplit(String values) { return values.split(","); } private String[] semicolonSplit(String values) { return values.split(";"); } private int[] toInt(String[] strArray) { int[] intArray = new int[strArray.length]; for(int i = 0; i < strArray.length; i++) { intArray[i] = Integer.parseInt(strArray[i]); } return intArray; } public String toString() { String str = "["; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { str += matrix[i][j]; } str += ";"; } return str + "]"; } // Alerts /////////// private void printOutOfBounds() { System.out.println("The coordinates must be within the matrix!"); } // Printing ///////// private void prettyPrintSleepFlush() { prettyPrint(); sleep(); flush(); } private void prettyPrint() { for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { System.out.print(matrix[i][j] + "\t"); } System.out.println("\n\n"); } } private void sleep() { try { Thread.sleep(200); } catch (InterruptedException ie) { // Handle any exceptions } } public void flush() { try { Runtime.getRuntime().exec("clear"); } catch (final Exception e) { // Handle any exceptions } final String ANSI_CLS = "\u001b[2J"; final String ANSI_HOME = "\u001b[H"; System.out.print(ANSI_CLS + ANSI_HOME); System.out.flush(); } }
package com.inheritance.ex; public class ABImpl implements A1,B1{ @Override public int m1() { return B1.super.m1(); } }
public class Rectangle { double length,breadth; public Rectangle(double length,double breadth) { this.length=length; this.breadth=breadth; } public double area() { return length * breadth; } }
/* Generated SBE (Simple Binary Encoding) message codec */ package sbe.msg; import uk.co.real_logic.sbe.codec.java.CodecUtil; import uk.co.real_logic.agrona.DirectBuffer; @SuppressWarnings("all") public class LogoutDecoder { public static final int BLOCK_LENGTH = 20; public static final int TEMPLATE_ID = 3; public static final int SCHEMA_ID = 1; public static final int SCHEMA_VERSION = 0; private final LogoutDecoder parentMessage = this; private DirectBuffer buffer; protected int offset; protected int limit; protected int actingBlockLength; protected int actingVersion; public int sbeBlockLength() { return BLOCK_LENGTH; } public int sbeTemplateId() { return TEMPLATE_ID; } public int sbeSchemaId() { return SCHEMA_ID; } public int sbeSchemaVersion() { return SCHEMA_VERSION; } public String sbeSemanticType() { return ""; } public int offset() { return offset; } public LogoutDecoder wrap( final DirectBuffer buffer, final int offset, final int actingBlockLength, final int actingVersion) { this.buffer = buffer; this.offset = offset; this.actingBlockLength = actingBlockLength; this.actingVersion = actingVersion; limit(offset + actingBlockLength); return this; } public int encodedLength() { return limit - offset; } public int limit() { return limit; } public void limit(final int limit) { buffer.checkLimit(limit); this.limit = limit; } public static int reasonId() { return 1; } public static String reasonMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return "unix"; case TIME_UNIT: return "nanosecond"; case SEMANTIC_TYPE: return ""; } return ""; } public static byte reasonNullValue() { return (byte)0; } public static byte reasonMinValue() { return (byte)32; } public static byte reasonMaxValue() { return (byte)126; } public static int reasonLength() { return 20; } public byte reason(final int index) { if (index < 0 || index >= 20) { throw new IndexOutOfBoundsException("index out of range: index=" + index); } return CodecUtil.charGet(buffer, this.offset + 0 + (index * 1)); } public static String reasonCharacterEncoding() { return "UTF-8"; } public int getReason(final byte[] dst, final int dstOffset) { final int length = 20; if (dstOffset < 0 || dstOffset > (dst.length - length)) { throw new IndexOutOfBoundsException("dstOffset out of range for copy: offset=" + dstOffset); } CodecUtil.charsGet(buffer, this.offset + 0, dst, dstOffset, length); return length; } }
package collections.main_task.confection; import collections.main_task.assortment.ChocolateType; public class ChocolateBar extends Sweetness { private ChocolateType chocolateType; private int percentChocolate; public ChocolateBar(String nameSweetness, int weightSweetness, ChocolateType chocolateType, int percentChocolate) { super(nameSweetness, weightSweetness); this.chocolateType = chocolateType; this.percentChocolate = percentChocolate; } public ChocolateType getChocolateType() { return chocolateType; } public void setChocolateType(ChocolateType chocolateType) { this.chocolateType = chocolateType; } public int getPercentChocolate() { return percentChocolate; } public void setPercentChocolate(int percentChocolate) { if (percentChocolate > 100 || percentChocolate < 1) { throw new IllegalArgumentException("Percent of Chocolate should be more than 0 and less than 100"); } this.percentChocolate = percentChocolate; } public double getTotalCountSugarInChocolate() { return chocolateType.getCountSugar() * getWeightSweetness() / 100; } @Override public double getCountSugarOneHundredGrams() { return chocolateType.getCountSugar(); } @Override public String toString() { return "ChocolateBar " + super.toString().replace("]", ", chocolateType=" + chocolateType + ", countChocolate=" + percentChocolate + ", countSugar=" + getCountSugarOneHundredGrams() + "]"); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; ChocolateBar that = (ChocolateBar) o; if (percentChocolate != that.percentChocolate) return false; return chocolateType == that.chocolateType; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (chocolateType != null ? chocolateType.hashCode() : 0); result = 31 * result + percentChocolate; return result; } }
package com.gmail.volodymyrdotsenko.cms.be.domain.media; import java.io.Serializable; import javax.persistence.*; import com.gmail.volodymyrdotsenko.cms.be.domain.local.Language; @Embeddable public class AudioSubtitlePk implements Serializable { private static final long serialVersionUID = 1L; @ManyToOne @JoinColumn(name = "LANG_CODE") private Language lang; @ManyToOne @JoinColumn(name = "REF_ITEM_ID") private AudioItem item; @Column(name = "ORDER_NUM") private Integer orderNum; public Language getLang() { return lang; } public AudioSubtitlePk() { } public AudioSubtitlePk(Language lang, AudioItem item, Integer orderNum) { this.lang = lang; this.item = item; this.orderNum = orderNum; } public void setLang(Language lang) { this.lang = lang; } public AudioItem getItem() { return item; } public void setItem(AudioItem item) { this.item = item; } public Integer getOrderNum() { return orderNum; } public void setOrderNum(Integer orderNum) { this.orderNum = orderNum; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((item == null) ? 0 : item.hashCode()); result = prime * result + ((lang == null) ? 0 : lang.hashCode()); result = prime * result + ((orderNum == null) ? 0 : orderNum.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AudioSubtitlePk other = (AudioSubtitlePk) obj; if (item == null) { if (other.item != null) return false; } else if (!item.equals(other.item)) return false; if (lang == null) { if (other.lang != null) return false; } else if (!lang.equals(other.lang)) return false; if (orderNum == null) { if (other.orderNum != null) return false; } else if (!orderNum.equals(other.orderNum)) return false; return true; } }
package com.epam.restaurant.entity; import org.junit.Assert; import org.junit.Test; /** * Created by Вероника on 01.03.2016. */ public class CategoryTest { @Test public void testGetDescription() throws Exception { Category category = new Category("name","description"); Assert.assertEquals("description",category.getDescription()); } @Test public void testSetDescription() throws Exception { Category category = new Category(); category.setDescription("description"); Assert.assertEquals("description",category.getDescription()); } @Test public void testGetName() throws Exception { Category category = new Category("name","description"); Assert.assertEquals("name",category.getName()); } @Test public void testSetName() throws Exception { Category category = new Category(); category.setName("name"); Assert.assertEquals("name",category.getName()); } @Test public void testEquals() throws Exception { Category c1 = new Category("CommonName","CommonDescription"); Category c2 = new Category("CommonName","CommonDescription"); Assert.assertTrue(c1.equals(c2) && c2.equals(c1)); } @Test public void testHashCode() throws Exception { Category c1 = new Category("CommonName","CommonDescription"); Category c2 = new Category("CommonName","CommonDescription"); Assert.assertEquals(c1, c2); Assert.assertTrue( c1.hashCode()==c2.hashCode() ); } }
package com.espendwise.manta.service; import com.espendwise.manta.dao.OrderDAO; import com.espendwise.manta.dao.OrderDAOImpl; import com.espendwise.manta.model.data.*; import com.espendwise.manta.model.view.*; import com.espendwise.manta.util.criteria.OrderListViewCriteria; import com.espendwise.manta.util.validation.ServiceLayerValidation; import com.espendwise.manta.util.validation.rules.OrderUpdateNewSiteConstraint; import java.util.Collection; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List; @Service @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public class OrderServiceImpl extends DataAccessService implements OrderService { private static final Logger logger = Logger.getLogger(OrderServiceImpl.class); @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public List<OrderListView> findOrdersByCriteria(OrderListViewCriteria criteria) { EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); return orderDao.findOrdersByCriteria(criteria); } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public OrderHeaderView findOrderHeader(Long orderId) { EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); return orderDao.findOrderHeader(orderId); } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public OrderIdentView findOrderToEdit(Long storeId, Long orderId) { EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); return orderDao.findOrderToEdit(storeId, orderId); } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public List<OrderPropertyData> findOrderProperties(Long orderId, List<String> propertyTypes) { EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); return orderDao.findOrderProperties(orderId, propertyTypes); } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public List<OrderMetaData> findOrderMeta(Long orderId) { EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); return orderDao.findOrderMeta(orderId); } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public List<OrderItemIdentView> findOrderItems(Long orderId, String erpPoNum, Long purchaseOrderId) { EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); return orderDao.findOrderItems(orderId, erpPoNum, purchaseOrderId); } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public List<OrderItemData> findOrderItemDataList(Long orderId) { EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); return orderDao.findOrderItemDataList(orderId); } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public List<FreightHandlerView> getFreightHandlerDetails(List<Long> freightHandlerIds) { EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); return orderDao.getFreightHandlerDetails(freightHandlerIds); } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public List<OrderAddressData> findOrderAddresses(Long orderId) { EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); return orderDao.findOrderAddresses(orderId); } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public List<NoteJoinView> getSiteCrcNotes(Long siteId) { EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); return orderDao.getSiteCrcNotes(siteId); } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public List<InvoiceCustView> getInvoiceCustByWebOrderNum(String webOrderNum, Long storeId, Boolean fullInfo) { EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); return orderDao.getInvoiceCustByWebOrderNum(webOrderNum, storeId, fullInfo); } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public List<ItemContractCostView> getItemContractCost(Long accountId, Long itemSkuNum, Long distId, String distErpNum) { EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); return orderDao.getItemContractCost(accountId, itemSkuNum, distId, distErpNum); } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public List<ItemData> getItemDataList(Collection<Long> itemIds) { EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); return orderDao.getItemDataList(itemIds); } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public OrderData cancelOrder(Long orderId) { EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); return orderDao.cancelOrder(orderId); } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void updateOrder(OrderChangeRequestView changeRequest) { if (changeRequest.getNewSiteId() != null) { ServiceLayerValidation validation = new ServiceLayerValidation(); validation.addRule(new OrderUpdateNewSiteConstraint(changeRequest.getNewSiteId())); validation.validate(); } EntityManager entityManager = getEntityManager(); OrderDAO orderDao = new OrderDAOImpl(entityManager); orderDao.updateOrder(changeRequest); } }
package com.example.topics.details; import com.example.topics.BaseLocalDockerIT; import com.example.topics.core.Group; import com.example.topics.core.Topic; import com.example.topics.infra.GatewayResponse; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.SneakyThrows; import org.assertj.core.api.SoftAssertions; import org.junit.jupiter.api.Test; import org.testcontainers.shaded.org.apache.commons.io.FileUtils; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Optional; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; class GetTopicDetailsHandlerLocalDockerIT extends BaseLocalDockerIT { private final GetTopicDetailsHandler getTopicDetailsHandler = new GetTopicDetailsHandler(); @SneakyThrows @Test void givenTopicExistsInClusterAndDatabase_thenReturnsTopicInfoFromDatabase() { // GIVEN Group ownerGroup = new Group("group1"); Topic topic = new Topic(correlationId, ownerGroup); topicRepository.create(topic); String requestString = FileUtils.readFileToString(new File("src/test/resources/getTopicDetails.json"), StandardCharsets.UTF_8); JsonNode requestTree = mapper.readTree(requestString); ((ObjectNode) requestTree.at("/pathParameters")).put("topic", correlationId); Map<String, Object> request = mapper.convertValue(requestTree, new TypeReference<>() { }); // WHEN GatewayResponse<Optional<Topic>> gatewayResponse = getTopicDetailsHandler.handleRequest(request, testContext); Optional<Topic> actualTopicDatabaseInfo = mapper.readValue(gatewayResponse.getBody(), new TypeReference<>() { }); // THEN assertThat(actualTopicDatabaseInfo).hasValue(topic); } }
package com.smxknife.zookeeper.simple; import lombok.Getter; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import java.io.IOException; import java.util.Objects; import java.util.concurrent.ThreadLocalRandom; /** * @author smxknife * 2019/12/1 */ public abstract class Znode implements Watcher { @Getter protected ZooKeeper zk; protected String hostPort; @Getter protected String serverId; @Getter protected String path; protected Znode(String hostPort) { this.hostPort = hostPort; serverId = Integer.toHexString(ThreadLocalRandom.current().nextInt()); } public void startZK() throws IOException { startZK(15000); // zk = new ZooKeeper(hostPort, 15000, this); } public void startZK(int timeout) throws IOException { zk = new ZooKeeper(hostPort, timeout, this); } public void stopZK() throws InterruptedException { Objects.requireNonNull(zk); // 虽然在客户端关闭后,服务端也会关闭会话,但是需要有一定的延迟,这样会造成资源浪费,高峰时期,会造成一定的风险, // 所以最好在客户端主动调用ZooKeeper.close方法来显示关闭,这样就会立刻销毁会话 zk.close(); } }
package pl.gabinetynagodziny.officesforrent.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import pl.gabinetynagodziny.officesforrent.entity.Detail; import pl.gabinetynagodziny.officesforrent.entity.Office; import pl.gabinetynagodziny.officesforrent.service.DetailService; import javax.validation.Valid; import java.util.List; import java.util.Optional; @Controller @RequestMapping("/details") public class DetailController { private final DetailService detailService; public DetailController(DetailService detailService) { this.detailService = detailService; } @GetMapping public String details(Model model){ List<Detail> details = detailService.findAll(); model.addAttribute("details", details); return "details"; } @GetMapping("/add") public String addDetail(Model model){ Detail detail = new Detail(); model.addAttribute("detail", detail); return "adddetail"; } @PostMapping("/add") public String addDetailPost(@Valid Detail detail, BindingResult result, Model model){ Detail detailSaved = detailService.mergeDetail(detail); return "adddetail"; } // @ResponseBody @GetMapping("/{id}") public String detailId(@PathVariable("id") Long id, Model model){ Optional<Detail> optionalDetail= detailService.findByDetailId(id); if(optionalDetail.isEmpty()){ return "nie ma detaila o takim id"; } model.addAttribute("detail", optionalDetail.get()); return "adddetail"; } }
/** * */ package de.zarncke.lib.index; import java.util.Collection; import java.util.Comparator; import de.zarncke.lib.index.crit.Criteria; public interface Indexing<T> { void add(T entry); void clear(); Index<T> getIndex(final Criteria<?, T> crit); double getPredictivity(final Criteria<?, T> crit); Collection<? extends Comparator<T>> getOrdering(); Class<?> getType(); }
package com.fleet.xml.controller; import com.fleet.xml.entity.Protocol; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * SAX 方式 * * @author April Han */ @RestController @RequestMapping("/sax") public class SaxController { @RequestMapping("/read") public List<Protocol> read() { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); try { SAXParser saxParser = saxParserFactory.newSAXParser(); SaxHandler saxHandler = new SaxHandler(); saxParser.parse("classpath:xml/protocol.xml", saxHandler); return saxHandler.getProtocolList(); } catch (ParserConfigurationException | IOException | SAXException e) { e.printStackTrace(); } return new ArrayList<>(); } }
package com.foodie.homeslice.dto; import java.util.List; import org.springframework.stereotype.Component; @Component public class PreferenceReposnseDto { private Integer statuscode; private String message; private List<Favourite> favourites; private List<Like> likes; public Integer getStatuscode() { return statuscode; } public void setStatuscode(Integer statuscode) { this.statuscode = statuscode; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List<Favourite> getFavourites() { return favourites; } public void setFavourites(List<Favourite> favourites) { this.favourites = favourites; } public List<Like> getLikes() { return likes; } public void setLikes(List<Like> likes) { this.likes = likes; } }
package com.taikang.healthcare.cust.service; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.taikang.healthcare.cust.AddressService; import com.taikang.healthcare.cust.dao.AddressMapper; import com.taikang.healthcare.cust.model.Address; import com.taikang.healthcare.sdk.BeanUtil; @Service("addressService") public class AddressServiceImpl implements AddressService { @Resource private AddressMapper addressMapper; @Override public Map<String, Object> register(Map<String, Object> address) { //判断是否存在该地址 if(addressMapper.selectByAddress(address) == 0){ //若数据库中不存在该地址,则插入该地址,获得受影响行数 int num = addressMapper.insert(address); //判断受影响行数是否为0 if(num != 0){ //若不为0则表示插入成功 address.put("result", true); }else{ //若为0则表示插入失败 address.clear(); address.put("result", false); address.put("mesg", "服务器出错,请稍后再试"); } }else{ //若该地址已存在,则不插入 address.clear(); address.put("result", false); address.put("mesg", "地址已存在"); } return address; } @Override public List<Map<String, Object>> search(long customerId) { //定义一个List用于接收转换后的查询结果 List<Map<String, Object>> addressList = new ArrayList<Map<String, Object>>(); //根据客户id进行查询 List<Address> addresses = addressMapper.selectByCustomerId(customerId); //将查询结果遍历 for(Address address :addresses){ //将查询结果转换成Map,再添加到addressList中 addressList.add(BeanUtil.beanToMap(address)); } return addressList; } @Override public boolean delete(int id) { //创建一个Map用于封装执行sql语句要用到的一些信息 Map<String, Object> address = new HashMap<String, Object>(); address.put("id", id); address.put("lastUpdatedById", 1L); address.put("lastUpdatedTime", new Date()); //删除地址,获取受影响行数 int num = addressMapper.deleteById(address); //判断受影响行数是否为0 if(num != 0){ //受影响行数不为0则表示删除成功 return true; } return false; } @Override public Map<String, Object> alter(Map<String, Object> address) { //判断是否存在该地址 if(addressMapper.selectByAddress(address) == 0){ //若数据库中不存在相同地址信息,则修改该地址,获得受影响行数 int num = addressMapper.updateByPrimaryKeySelective(address); //判断受影响行数是否为0 if(num != 0){ //若不为0则表示修改成功 address.put("result", true); }else{ //若为0则表示修改失败 address.clear(); address.put("result", false); address.put("mesg", "服务器出错,请稍后再试"); } }else{ //若该地址已存在,则不修改 address.clear(); address.put("result", false); address.put("mesg", "地址已存在"); } return address; } }
package com.itheima.controller; import com.alibaba.dubbo.config.annotation.Reference; import com.itheima.constant.MessageConstant; import com.itheima.entity.Result; import com.itheima.pojo.Time; import com.itheima.service.MemberService; import com.itheima.service.ReportService; import com.itheima.service.SetmealService; import com.itheima.utils.DateUtils; import net.sf.jxls.transformer.XLSTransformer; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.*; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.util.*; /** * 报表控制层 */ @RestController @RequestMapping(value = "/report") public class ReportController { @Reference private MemberService memberService; @Reference private SetmealService setmealService; ///专门报表的服务 @Reference private ReportService reportService; /** *description:根据日期区间时间 会员数量折线图 * @param * @return com.itheima.entity.Result */ @RequestMapping(value = "/getMemberReportDefined",method = RequestMethod.POST) public Result getMemberReportDefined(@RequestBody Time time) throws Exception { String start = DateUtils.parseDate2String(time.getStart()); String end = DateUtils.parseDate2String(time.getEnd()); Map map = null; try { map = memberService.getMemberReportDefined(start, end); } catch (Exception e) { e.printStackTrace(); return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL); } return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map); } /** *description:默认查询当前月往前12月 会员数量折线图 * @param * @return com.itheima.entity.Result */ @RequestMapping(value = "/getMemberReport",method = RequestMethod.GET) public Result getMemberReport(){ //调用服务得到Map Map map = null; try { map = memberService.getMemberReport(); } catch (Exception e) { e.printStackTrace(); return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL); } return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map); } /** * 套餐预约占比饼形图 */ @RequestMapping(value = "/getSetmealReport",method = RequestMethod.GET) public Result getSetmealReport(){ try { Map rsMap = new HashMap(); //调用服务获取setmealNames setmealCount List<Map<String,Object>> setmealCount =setmealService.getSetmealReport(); List setmealNames = new ArrayList();//套餐名称 if(setmealCount!= null && setmealCount.size()>0){ for (Map<String, Object> map : setmealCount) { //{value:222,name:xxxx} String name = (String)map.get("name");//套餐名称. setmealNames.add(name); } } rsMap.put("setmealNames",setmealNames);//['套餐一','套餐二'] rsMap.put("setmealCount",setmealCount);//List<Map<String,Object>> [{value:222,name:xxxx},{value:222,name:xxxx}] return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,rsMap); } catch (Exception e) { e.printStackTrace(); return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL); } } /** * getBusinessReportData 获取运营数据统计报表(会员数据 预约数据 热门套餐数据) */ @RequestMapping(value = "/getBusinessReportData",method = RequestMethod.GET) public Result getBusinessReportData(){ try { Map rsMap = reportService.getBusinessReportData(); return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS,rsMap); } catch (Exception e) { e.printStackTrace(); return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL); } } /** * :导出运营数据统计 */ /*@RequestMapping(value = "/exportBusinessReport",method = RequestMethod.GET) public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){ try { //获取运营统计的数据 Map rsMap = reportService.getBusinessReportData(); //获取模板excel对象 template/report_template.xlsx String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx"; XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(new File(filePath))); //HSSFWorkbook//2003 XSSFWorkbook//2007 //统计获取map中数据 String reportDate = (String)rsMap.get("reportDate"); Integer todayNewMember = (Integer) rsMap.get("todayNewMember"); Integer totalMember = (Integer) rsMap.get("totalMember"); Integer thisWeekNewMember = (Integer) rsMap.get("thisWeekNewMember"); Integer thisMonthNewMember = (Integer) rsMap.get("thisMonthNewMember"); Integer todayOrderNumber = (Integer) rsMap.get("todayOrderNumber"); Integer thisWeekOrderNumber = (Integer) rsMap.get("thisWeekOrderNumber"); Integer thisMonthOrderNumber = (Integer) rsMap.get("thisMonthOrderNumber"); Integer todayVisitsNumber = (Integer) rsMap.get("todayVisitsNumber"); Integer thisWeekVisitsNumber = (Integer) rsMap.get("thisWeekVisitsNumber"); Integer thisMonthVisitsNumber = (Integer) rsMap.get("thisMonthVisitsNumber"); //获取sheet 获取第三行第6列单元格赋值 XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);//获取第一个sheet页 XSSFRow row = sheetAt.getRow(2);//获取第二行 row.getCell(5).setCellValue(reportDate); //......... row = sheetAt.getRow(4); row.getCell(5).setCellValue(todayNewMember);//新增会员数(本日) row.getCell(7).setCellValue(totalMember);//总会员数 row = sheetAt.getRow(5); row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数 row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数 row = sheetAt.getRow(7); row.getCell(5).setCellValue(todayOrderNumber);//今日预约数 row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数 row = sheetAt.getRow(8); row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数 row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数 row = sheetAt.getRow(9); row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数 row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数 //热门套餐 List<Map> hotSetmeal = (List<Map>)rsMap.get("hotSetmeal"); if(hotSetmeal != null && hotSetmeal.size()>0){ int setmealNum = 12; for (Map map : hotSetmeal) { //map每一行套餐数据 XSSFRow setmealRow = sheetAt.getRow(setmealNum); setmealRow.getCell(4).setCellValue((String)map.get("name")); setmealRow.getCell(5).setCellValue((String)map.get("setmeal_count").toString()); setmealRow.getCell(6).setCellValue((String)map.get("proportion").toString()); setmealRow.getCell(7).setCellValue((String)map.get("remark")); setmealNum++; } } //通过输出流返回浏览器 ServletOutputStream outputStream = response.getOutputStream();///outputStream输出流 //告知浏览器 excel文件类型 文件名 attachment:以附件形式下载文件 filename文件名 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//2007 response.setHeader("content-Disposition","attachment;filename=report.xlsx"); //application/vnd.ms-excel xssfWorkbook.write(outputStream); //释放资源 outputStream.flush(); outputStream.close(); xssfWorkbook.close(); return null; } catch (Exception e) { e.printStackTrace(); return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL); } }*/ /** * jxl针对poi提供的模板技术(扩展) * @param request * @param response * @return */ @RequestMapping(value = "/exportBusinessReport",method = RequestMethod.GET) public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){ try { //获取运营统计的数据 Map rsMap = reportService.getBusinessReportData(); //获取模板excel对象 template/report_template.xlsx String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx"; XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(new File(filePath))); XLSTransformer transformer = new XLSTransformer(); transformer.transformWorkbook(xssfWorkbook, rsMap);//将excel对象传入 excel模块中需要的输入传入 //通过输出流返回浏览器 ServletOutputStream outputStream = response.getOutputStream();///outputStream输出流 //告知浏览器 excel文件类型 文件名 attachment:以附件形式下载文件 filename文件名 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//2007 response.setHeader("content-Disposition","attachment;filename=report.xlsx"); //application/vnd.ms-excel xssfWorkbook.write(outputStream); //释放资源 outputStream.flush(); outputStream.close(); xssfWorkbook.close(); return null; } catch (Exception e) { e.printStackTrace(); return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL); } } }
package net.thumbtack.asurovenko.trainee; public enum TraineeErrorCodes { EMPTY("Строка null или пустая."), BAD_VALUE("Величина вне диапазона."); private String error; TraineeErrorCodes(String error) { this.error = error; } public String getError() { return error; } }
/* * Copyright (c) 2011. Peter Lawrey * * "THE BEER-WARE LICENSE" (Revision 128) * As long as you retain this notice you can do whatever you want with this stuff. * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return * There is no warranty. */ package com.google.code.java.core.javac.generated; public class PrivateField { private int num = 0; public class Inner { public void set(int n) { num = n; } public int get() { return num; } public void increment() { num++; } public void multiply(int n) { num *= n; } } }
package com.tencent.mm.plugin.appbrand.appcache.a.b; import android.util.Base64; import com.tencent.mm.plugin.appbrand.appcache.a.c.a; import com.tencent.mm.plugin.appbrand.config.WxaAttributes; import com.tencent.mm.plugin.appbrand.config.WxaAttributes.d; import com.tencent.mm.protocal.c.cgy; import com.tencent.mm.protocal.c.cgz; import com.tencent.mm.protocal.c.chl; import com.tencent.mm.protocal.c.chq; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.util.Iterator; public class e extends a<Boolean, chq> { final /* bridge */ /* synthetic */ chl bf(Object obj) { return ((chq) obj).sBu; } private static Boolean a(String str, String str2, chq chq) { d dVar = null; String str3 = chq.sBH; if (bi.oW(str3)) { x.e("MicroMsg.AppBrand.Predownload.CmdIssueContact", "call[%s | %s], empty base64", new Object[]{str, str2}); return Boolean.FALSE; } try { byte[] decode = Base64.decode(str3, 0); cgz cgz = new cgz(); cgz.aG(decode); WxaAttributes e = com.tencent.mm.plugin.appbrand.app.e.aba().e(str, "versionInfo"); d ael = e == null ? null : e.ael(); Iterator it = cgz.riC.iterator(); while (it.hasNext()) { d si; cgy cgy = (cgy) it.next(); if ("WxaAppVersionInfo".equals(cgy.riD)) { si = d.si(cgy.mEl); } else { si = dVar; } dVar = si; } int i; if (dVar == null) { i = a.fiY; a.n((long) chq.sBu.sBs, 87); return Boolean.FALSE; } boolean z; i = a.fiY; a.n((long) chq.sBu.sBs, 88); boolean z2 = ael == null || dVar == null || ael.cbu < dVar.cbu; if (z2) { boolean z3; com.tencent.mm.plugin.appbrand.app.e.aba().a(str, cgz.riB, cgz.riC); if (com.tencent.mm.plugin.appbrand.app.e.aba().e(str, new String[0]) != null) { z3 = true; } else { z3 = false; } int i2 = a.fiY; a.n((long) chq.sBu.sBs, z3 ? 85 : 86); z = z3; } else { i = a.fiY; a.n((long) chq.sBu.sBs, 84); z = false; } String str4 = "MicroMsg.AppBrand.Predownload.CmdIssueContact"; String str5 = "call[%s | %s], record.ver %d, issue.ver %d, doIssue %b, issueRet %b"; Object[] objArr = new Object[6]; objArr[0] = str; objArr[1] = str2; objArr[2] = Integer.valueOf(ael == null ? -1 : ael.cbu); objArr[3] = Integer.valueOf(dVar == null ? -1 : dVar.cbu); objArr[4] = Boolean.valueOf(z2); objArr[5] = Boolean.valueOf(z); x.i(str4, str5, objArr); return Boolean.valueOf(z); } catch (Throwable e2) { x.printErrStackTrace("MicroMsg.AppBrand.Predownload.CmdIssueContact", e2, "call[%s | %s], decode base64", new Object[]{str, str2}); return Boolean.FALSE; } } final String acp() { return "CmdIssueContact"; } }
package com.tencent.mm.plugin.sns.data; public final class a { public String bNH; public boolean nkG = false; public int scene; public String userName; public a(boolean z, String str, String str2, int i) { this.nkG = z; this.userName = str; this.bNH = str2; this.scene = i; } }
package com.training.ee.cdi; import java.io.Serializable; import javax.inject.Named; @Named("en") public class MyProcess1 implements IProcess, Serializable { private static final long serialVersionUID = -3959497786043724963L; @Override public String process(final String strParam) { return "Hello " + strParam; } }
package br.eti.ns.nssuite.requisicoes.bpe; import br.eti.ns.nssuite.requisicoes._genericos.ConsStatusProcessamentoReq; public class ConsStatusProcessamentoReqBPe extends ConsStatusProcessamentoReq { }
package guru.springframework.sfgpetclinc.service; import guru.springframework.sfgpetclinc.model.Owner; public interface OwnerService extends CrudService<Owner, Long> { Owner findByLastName(String lastName); }
package com.hedong.hedongwx.utils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.ByteBuffer; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.hedong.hedongwx.entity.User; import com.hedong.hedongwx.thread.Server; /** * * @author RoarWolf * */ public class DisposeUtil { private static final Logger logger = LoggerFactory.getLogger(Server.class); public static void main(String[] args) { // for (int i = 310100; i <= 310499; i++) { // for (int j = 1; j <= 20; j++) { // String str = "http://www.he360.com.cn/oauth2Portpay?codeAndPort="; // String str = ""; // if (j >= 10) { // str = str + i + j; // } else { // str = str + i + "0" + j; // } // logfile(str); // System.out.println(str); // } // } } public static List<String> quChong(List<String> list) { List<String> newList = new ArrayList<String>(); for (String str : list) { if(!newList.contains(str)) newList.add(str); } return newList; } public static User getUserBySessionId(HttpServletRequest request) { System.out.println("获取用户=" + request.getSession().getId()); // String userStr = JedisUtils.getnum(request.getSession().getId(), 2); // User user = JSONObject.toJavaObject((JSON)JSON.parse(userStr), User.class); User user = (User) request.getSession().getAttribute("user"); return user; } public static void setUserBySessionId(String sessionId,User user) { JedisUtils.setnum(sessionId, JSON.toJSONString(user), 28800, 2); } /** * 判断此map是否有值 * @param map * @return */ public static boolean checkMapIfHasValue(Map map) { if (map == null || map.isEmpty() || map.size() == 0) { return false; } else { return true; } } /** * 获取判断设备断网时间 * @param temp 1、获取系统时间 2、获取手动断电时间 * @return */ public static int getOfflineTime(int temp) { try { Map<String, String> hgetAll = JedisUtils.hgetAll("sysTime"); if (!checkMapIfHasValue(hgetAll)) { return noChongfu(temp); } else { if (temp == 1) { String sysOffline = hgetAll.get("sysOffline"); if (sysOffline == null || "".equals(sysOffline)) { return 8 * 60; } else { return Integer.parseInt(sysOffline); } } else if (temp == 2) { String handOffline = hgetAll.get("handOffline"); if (handOffline == null || "".equals(handOffline)) { return 30; } else { return Integer.parseInt(handOffline); } } else { return noChongfu(temp); } } } catch (Exception e) { return noChongfu(temp); } } public static int noChongfu(int temp) { if (temp == 1) { return 8 * 60; } else { return 30; } } public static boolean checkTimeIfExceed(String code,int temp) { Map<String, String> diviceOffline = JedisUtils.hgetAll("diviceOffline"); if (checkMapIfHasValue(diviceOffline)) { return false; } else { String updateTime = diviceOffline.get(code); if (updateTime == null || "".equals(updateTime)) { return false; } else { long currentTime = System.currentTimeMillis(); long updateTimeLong = CommUtil.DateTime(updateTime,"yyyy-MM-dd HH:mm:ss").getTime(); long differTime = currentTime - updateTimeLong; int offlineTime = getOfflineTime(temp); if (offlineTime > differTime) { return false; } else { return true; } } } } /** * @Description:获取某个目录下所有直接下级文件,不包括目录下的子目录的下的文件,所以不用递归获取 * @Date:2020/4/29 */ public static List<String> getFiles(String path) { List<String> files = new ArrayList<String>(); File file = new File(path); File[] tempList = file.listFiles(); for (int i = 0; i < tempList.length; i++) { if (tempList[i].isFile()) { files.add(tempList[i].toString()); //文件名,不包含路径 String fileName = tempList[i].getName(); long lastModified = tempList[i].lastModified(); Date date = new Date(lastModified); String format = CommUtil.toDateTime("yyyy-MM-dd", date); System.out.println(format); String wolfDate = "2020-06-01"; System.out.println(wolfDate.compareTo(format)); // if ("新标签1.pld".equals(fileName)) { // boolean delete = tempList[i].delete(); // if (delete) { // System.out.println("新标签1.pld删除成功"); // } else { // System.out.println("新标签1.pld删除失败"); // } // } System.out.println("---" + fileName); } if (tempList[i].isDirectory()) { //这里就不递归了, } } return files; } /** * @Description:删除多余的日志文件 * @Date:2020/4/29 */ public static List<String> delectFile(String path, String wolfTime) { List<String> files = new ArrayList<String>(); File file = new File(path); File[] tempList = file.listFiles(); for (int i = 0; i < tempList.length; i++) { if (tempList[i].isFile()) { files.add(tempList[i].toString()); //文件名,不包含路径 String fileName = tempList[i].getName(); System.out.println("filename===" + fileName); long lastModified = tempList[i].lastModified(); Date date = new Date(lastModified); String fileTime = CommUtil.toDateTime("yyyy-MM-dd", date); int compareTo = fileTime.compareTo(wolfTime); System.out.println("当前时间:" + wolfTime); System.out.println("文件时间:" + fileTime); System.out.println("时间比较:" + compareTo); if (compareTo < 0) { boolean delete = tempList[i].delete(); if (delete) { System.out.println(fileName + "删除成功"); } else { System.out.println(fileName + "删除失败"); } } } // if (tempList[i].isDirectory()) { //这里就不递归了, // } } return files; } /** * 获取redis中所有端口状态数据 * @param code * @param hardversion * @return */ public static List<Map<String, String>> addPortStatus(String code,String hardversion) { List<Map<String, String>> portStatus = new ArrayList<>(); Map<String, String> codeRedisMap = JedisUtils.hgetAll(code); int len = 10; if (codeRedisMap != null) { if ("02".equals(hardversion)) { len = 2; } else if ("01".equals(hardversion)) { len = 10; } else if ("05".equals(hardversion)) { len = 16; } else if ("06".equals(hardversion)) { len = 20; } else if ("07".equals(hardversion)) { len = 1; } } for (int i = 1; i < len + 1; i++) { try { String portStatusStr = codeRedisMap.get(i + ""); Map<String, String> portStatusMap = (Map<String, String>) JSON.parse(portStatusStr); portStatus.add(portStatusMap); } catch (Exception e) { break; } } return portStatus; } /** * 获取redis中端口状态数据 * @param code * @param hardversion * @return */ public static Map<String, String> addPortStatus(String code,int port) { Map<String, String> codeRedisMap = JedisUtils.hgetAll(code); try { String portStatusStr = codeRedisMap.get(port + ""); Map<String, String> portStatusMap = (Map<String, String>) JSON.parse(portStatusStr); return portStatusMap; } catch (Exception e) { return null; } } /** * 获取redis中端口状态数据 * @param code * @param hardversion * @return */ /** * 获取redis中端口状态数据 * @param code * @param hardversion * @return */ public static List<Integer> getPortStatusInt(String code,String hardversion) { List<Integer> portStatus = new ArrayList<>(); Map<String, String> codeRedisMap = JedisUtils.hgetAll(code); int len = 10; if (codeRedisMap != null) { if ("02".equals(hardversion) || "09".equals(hardversion)) { len = 2; } else if ("01".equals(hardversion)) { len = 10; } else if ("05".equals(hardversion)) { len = 16; } else if ("06".equals(hardversion) || "10".equals(hardversion)) { len = 20; } } for (int i = 1; i < len + 1; i++) { Integer temp = null; try { String portStatusStr = codeRedisMap.get(i + ""); Map<String, String> portStatusMap = (Map<String, String>) JSON.parse(portStatusStr); String string = portStatusMap.get("portStatus"); temp = Integer.parseInt(string); } catch (Exception e) { } if (temp != null) { portStatus.add(temp); } } return portStatus; } public static void printDeviceDataInfo(String code, ByteBuffer buffer, boolean flag) { StringBuffer sb = new StringBuffer(); while (buffer.hasRemaining()) { int b = buffer.get() & 0xff; String hexString = Integer.toHexString(b); if (hexString.length() == 1) { hexString = "0" + hexString; } sb.append(hexString); } if (code != null && !"".equals(code)) { if (flag) { String str = "接收设备上传指令:设备编号为-" + code + ": " + sb.toString(); // logFile.logResult(logFile.DEVICEPATH, code, CommUtil.toDateTime() + str); logger.info(str); } else { String str = "服务器发送指令:设备编号为-" + code + ": " + sb.toString(); // logFile.logResult(logFile.DEVICEPATH, code, CommUtil.toDateTime() + str); logger.info(str); } } else { if (flag) { String str = "接收设备上传指令:设备编号为-空" + ": " + sb.toString(); logger.info(str); } else { String str = "服务器发送指令:设备编号为-空" + ": " + sb.toString(); logger.info(str); } } } public static void logfile(String sWord) { FileWriter writer = null; try { writer = new FileWriter("D:/log/chargeCodeAndPort.log", true); writer.write(sWord + "\n"); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 获取过去的日期 * * @param past 具体数值 * @param flag 1、获取过去几天2、获取过去几月3、获取过去几年 * @return */ public static String getPastDate(int past,int flag) { Calendar calendar = Calendar.getInstance(); int param = Calendar.DAY_OF_YEAR; if (flag == 1) { param = Calendar.DAY_OF_YEAR; } else if (flag == 2) { param = Calendar.MONTH; } else if (flag == 3) { param = Calendar.YEAR; } calendar.set(param, calendar.get(param) - past); Date today = calendar.getTime(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String result = format.format(today); return result; } /** * 根据版本号检测设备是否为v3设备 * @param hardversion * @return */ public static boolean checkIfHasV3(String hardversion) { boolean flag = false; if ("08".equals(hardversion) || "09".equals(hardversion) || "10".equals(hardversion)) { flag = true; } return flag; } /** * 补全字符串所需的0,前补0,用于10进制转16进制位不够 * @param param 需要改动的字符串 * @param totalnum 总位数 * @return */ public static String completeNum(String param, int totalnum) { int length = param.length(); if (length < totalnum) { String needStr = ""; for (int i = length; i < totalnum; i++) { needStr += "0"; } param = needStr + param; } return param; } public static String intToHex(int i) { return Integer.toHexString(i); } public static int hexToInt(String str) { return Integer.parseInt(str, 16); } }
package com.zitiger.plugin.xdkt.utils; import org.apache.commons.lang.StringUtils; /** * * * @author linglh * @version 2.12.0 on 2018/9/18 */ public class NameUtils { public static String capitalize(String name) { return StringUtils.capitalize(name); } public static String uncapitalize(String name) { return StringUtils.uncapitalize(name); } private String getGetterName(String name) { if (name.length() == 1) { return "get" + name.toUpperCase(); } else { return "get" + name.substring(0, 1).toUpperCase() + name.substring(1); } } /** * 下划线中横线命名转驼峰命名(属性名) * * @param name 名称 * @return 结果 */ public static String getClassName(String name) { if (StringUtils.isEmpty(name)) { return name; } // 强转全小写 name = name.toLowerCase(); String[] words = name.split("_"); StringBuilder buffer = new StringBuilder(); for (String word : words) { buffer.append(capitalize(word)); } return buffer.toString(); } public static String getVarName(String name) { return uncapitalize(getClassName(name)); } }
package com.machineinteractive; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Paint.Align; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.AsyncTask.Status; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class GetTheWeatherActivity extends Activity { // time between location updates in milliseconds final long UPDATE_TIME = 60 * 60 * 1000; // apply location update iff distance exceeds threshold amount specified in // meters final static float DISTANCE_THRESHOLD = 1.0f; LocationManager locationManger; String cityState; String WOEID; Location lastKnownLocation; JSONObject weatherJSON; ProgressDialog progressDialog; Button refreshBtn; LocationListener locationListenerGPS; LocationListener locationListenerNetwork; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); locationManger = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); locationListenerGPS = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { Log.d("weather", "GPS Location Changed"); boolean update = false; if (lastKnownLocation != null) { float dist = lastKnownLocation.distanceTo(location); Log.d("weather", "distance between loc: " + dist); if (dist > DISTANCE_THRESHOLD) { lastKnownLocation = location; update = true; } } else { lastKnownLocation = location; update = true; } if (update) { updateWeather(); } } }; locationListenerNetwork = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { Log.d("weather", "Network Location Changed"); boolean update = false; if (lastKnownLocation != null) { float dist = lastKnownLocation.distanceTo(location); if (dist > DISTANCE_THRESHOLD) { lastKnownLocation = location; update = true; } } else { lastKnownLocation = location; update = true; } if (update) { updateWeather(); } } }; refreshBtn = (Button) findViewById(R.id.refresh); refreshBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { updateWeather(); } }); List<String> providers = locationManger.getProviders(false); // grab first provider which has last known location if possible for (String provider : providers) { lastKnownLocation = locationManger.getLastKnownLocation(provider); if (lastKnownLocation != null) { break; } } } @Override protected void onStart() { super.onStart(); updateWeather(); } @Override protected void onResume() { super.onResume(); locationManger.requestLocationUpdates(LocationManager.GPS_PROVIDER, UPDATE_TIME, 0, locationListenerGPS); locationManger.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, UPDATE_TIME, 0, locationListenerNetwork); } @Override protected void onPause() { super.onPause(); locationManger.removeUpdates(locationListenerGPS); locationManger.removeUpdates(locationListenerNetwork); } private void updateWeather() { if (isFinishing()) { return; } if (!isNetworkAvailable()) { setError("Unable to update weather. Network Unavailable. Please check network connections."); return; } if (lastKnownLocation != null) { new GetWOEIDTask().execute(); } } private void updateView() { if (isFinishing()) { return; } TextView tv; try { JSONArray forecast = weatherJSON.getJSONArray("forecast"); JSONObject today = forecast.getJSONObject(0); JSONObject condition = weatherJSON.getJSONObject("condition"); JSONObject astronomy = weatherJSON.getJSONObject("astronomy"); tv = (TextView) findViewById(R.id.location); tv.setText(cityState); tv = (TextView) findViewById(R.id.hi); tv.setText("hi: " + today.getString("high_temperature")); tv = (TextView) findViewById(R.id.low); tv.setText("low: " + today.getString("low_temperature")); tv = (TextView) findViewById(R.id.condition_text); tv.setText(today.getString("condition") + " / " + condition.getString("text")); new DownloadConditionImageTask().execute(condition .getString("image")); tv = (TextView) findViewById(R.id.sunrise); tv.setText("sunrise: " + astronomy.getString("sunrise")); tv = (TextView) findViewById(R.id.sunset); tv.setText("sunset: " + astronomy.getString("sunset")); } catch (JSONException e) { e.printStackTrace(); } } private void setError(String text) { TextView tv = (TextView) findViewById(R.id.location); tv.setText(text); } void showProgressDialog(String text) { progressDialog = ProgressDialog.show(this, null, text); } void closeProgressDialog() { if (progressDialog != null) { progressDialog.dismiss(); } } @Override protected void onStop() { super.onStop(); closeProgressDialog(); } /** * fetch WOEID (where on earth id) via Yahoo PlaceFinder API using last * known latitude and longitude * * */ private class GetWOEIDTask extends AsyncTask<Void, Void, JSONObject> { @Override protected void onPreExecute() { showProgressDialog("Updating Location..."); } @Override protected void onPostExecute(JSONObject json) { boolean error = true; if (json != null) { try { cityState = json.getString("city") + ", " + json.getString("statecode"); WOEID = json.getString("woeid"); if (WOEID != null) { error = false; } Log.d("weather", "city+state: " + cityState + " woeid: " + WOEID); } catch (JSONException e) { setError("Unable to determine location. Try again later."); e.printStackTrace(); } } closeProgressDialog(); if (error) { setError("Unable to determine location. Try again later."); } else { new GetForecastTask().execute(); } } @Override protected JSONObject doInBackground(Void... arg0) { // get yahoo WOEID (where on earth id) by performing reverse // geocoding look up StringBuffer sb = new StringBuffer(); sb.setLength(0); sb.append("http://where.yahooapis.com/geocode?location=") .append(lastKnownLocation.getLatitude()).append("+") .append(lastKnownLocation.getLongitude()) .append("&flags=J").append("&gflags=R"); String uri = sb.toString(); Log.d("weather", "uri: " + uri); JSONObject json = makeYahooApiRequest(uri); try { JSONObject resultSet = json.getJSONObject("ResultSet"); int numFound = resultSet.getInt("Found"); // just use first entry - don't care about accuracy if (numFound > 0) { JSONArray results = resultSet.getJSONArray("Results"); JSONObject entry = results.getJSONObject(0); return entry; } } catch (JSONException e) { e.printStackTrace(); } return null; } } /** * fetch current location's forecast via Yahoo Weather API */ private class GetForecastTask extends AsyncTask<Void, Void, JSONObject> { @Override protected void onPreExecute() { showProgressDialog("Fetching Forecast..."); } @Override protected void onPostExecute(JSONObject json) { if (json != null) { weatherJSON = json; Log.d("weather", weatherJSON.toString()); updateView(); } else { setError("Unable to fetch forecast. Try again later."); } closeProgressDialog(); } @Override protected JSONObject doInBackground(Void... params) { StringBuffer sb = new StringBuffer(); sb.append("http://weather.yahooapis.com/forecastjson?") .append("w=").append(WOEID); String uri = sb.toString(); return makeYahooApiRequest(uri); } } /** * download forecast condition image * * @param uri * location of condition image */ private class DownloadConditionImageTask extends AsyncTask<String, Void, Bitmap> { @Override protected Bitmap doInBackground(String... uris) { return fetchBitmap(uris[0]); } protected void onPostExecute(Bitmap bitmap) { if (bitmap != null) { ImageView iv = (ImageView) findViewById(R.id.condition_image); iv.setImageBitmap(bitmap); } } } /** * make a HTTP GET request to Yahoo API * * @param uri * http get request uri to some Yahoo api * @return JSONObject object containing results of Yahoo API request */ private JSONObject makeYahooApiRequest(String uri) { StringBuffer sb = new StringBuffer(); JSONObject json = null; try { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(uri); HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); String line = ""; while ((line = in.readLine()) != null) { sb.append(line); } json = new JSONObject(sb.toString()); in.close(); } catch (Exception e) { e.printStackTrace(); } return json; } /** * fetch a bitmap via a url * * @param uri * location of bitmap * @return Bitmap object */ private Bitmap fetchBitmap(String uri) { Bitmap bitmap = null; try { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(uri); HttpResponse response = client.execute(request); BufferedInputStream bis = new BufferedInputStream(response .getEntity().getContent()); bitmap = BitmapFactory.decodeStream(bis); bis.close(); } catch (Exception e) { e.printStackTrace(); } return bitmap; } /** * determines if device has network connectivity * * @return true if network connection available, false otherwise */ private boolean isNetworkAvailable() { // from http://www.vogella.de/articles/AndroidNetworking/article.html ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { return true; } return false; } }
package com.philippe.app.service.mapper; import com.philippe.app.domain.User; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; @ExtendWith(MockitoExtension.class) public class CustomMapperServiceImplTest { private static final Integer A_NUMBER = 13; private static final String USER_NAME = "John"; private static final String A_COLOUR = "green"; private static final UUID A_UUID = UUID.randomUUID(); @InjectMocks private CustomMapperServiceImpl customMapperService; @Test public void testConvertUser() { final User inputUser = new User(); inputUser.setId(A_UUID); inputUser.setName(USER_NAME); inputUser.setFavoriteColor(A_COLOUR); inputUser.setFavoriteNumber(A_NUMBER); final example.avro.User avroContainer = customMapperService.convert(inputUser); assertEquals(A_UUID.toString(), avroContainer.getId()); assertEquals(USER_NAME, avroContainer.getName()); assertEquals(A_COLOUR, avroContainer.getFavoriteColor()); assertEquals(A_NUMBER, avroContainer.getFavoriteNumber()); } }
/* * 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.mycompany.entities.asma; /** * * @author User */ public class Comment { private int user_ID; private String feed_ID; private String corp; public Comment() { } public Comment(int user_ID, String feed_ID, String corp) { this.user_ID = user_ID; this.feed_ID = feed_ID; this.corp = corp; } public int getUser_ID() { return user_ID; } public void setUser_ID(int user_ID) { this.user_ID = user_ID; } public String getFeed_ID() { return feed_ID; } public void setFeed_ID(String feed_ID) { this.feed_ID = feed_ID; } public String getCorp() { return corp; } public void setCorp(String corp) { this.corp = corp; } @Override public String toString() { return "Comment{" + "user_ID=" + user_ID + ", feed_ID=" + feed_ID + ", corp=" + corp + '}'; } }
package net.thumbtack.asurovenko.trainee.interfaces; public interface Square { double square(); }
package com.catalyst.zookeeper.entities; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import org.junit.Test; public class SpeciesTest { private Species species = new Species(); @Test public void testGetSetId() { int expected = 1; species.setId(expected); int actual = species.getId(); assertEquals(expected, actual); } @Test public void testGetSetCommonName() { String expected = "test"; species.setCommonName(expected); String actual = species.getCommonName(); assertEquals(expected, actual); } @Test public void testGetSetScientificName() { String expected = "test"; species.setScientificName(expected); String actual = species.getScientificName(); assertEquals(expected, actual); } @Test public void testGetSetInfoLink() { String expected = "test"; species.setInfoLink(expected); String actual = species.getInfoLink(); assertEquals(expected, actual); } @Test public void testGetSetFood() { Food expected = mock(Food.class); species.setFood(expected); Food actual = species.getFood(); assertEquals(expected, actual); } }
package br.com.service; import java.util.List; import java.util.Optional; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import br.com.model.Doc; import br.com.repository.UploadFileRepository; import lombok.RequiredArgsConstructor; @Service @RequiredArgsConstructor public class UploadFileService { private final UploadFileRepository uploadFileRepository; public Doc saveFile(MultipartFile file) { String docName = file.getOriginalFilename(); try { Doc doc = new Doc(null, docName,file.getContentType(),file.getBytes()); return uploadFileRepository.save(doc); } catch (Exception e) { e.printStackTrace(); } return null; } public Optional<Doc> getFile(Integer fileId){ return uploadFileRepository.findById(fileId); } public List<Doc> getFiles(){ return uploadFileRepository.findAll(); } }
import java.util.*; public class Kruskal { public static int []visited={0,0,0,0,0,0};//visited array public static List<Set<Integer>>connComponents; /*set of connected components...an edge can be selected only if it's vertices belong to two diff connected components else it will form a cycle*/ public static int connComp = 1; /*variable to count the number of connected components in the graph..atleast 1 connected component in the graph..*/ public void setVisitedUsingArr(int v1,int v2) { /*you can use reverse mapping wherein if two nodes belong to the same connected component, they have the same visited[i] value. When an edge is selected, and the two vertices already belong to different connected components then all the visited[i] of one of the connected components should take the value of the other connected component.*/ /* Else, if one of vertices has not yet been discoverd yet it takes the visited[i] of the other connected component and if both nodes have not been discovered yet, they both take a new Conn Comp value for visited[i] An edge cannot be selected if it's visited[v1] == visited[v2]; because this will form a cycle */ } public static void setVisited(int i,int j) { ListIterator<Set<Integer>> listIterator = connComponents.listIterator(); Set<Integer> v1Set =null; Set<Integer> v2Set = null; while(listIterator.hasNext()) { v1Set = listIterator.next(); if(v1Set.contains(new Integer(i))) { System.out.println("i = "+i); break; } } listIterator = connComponents.listIterator(); int remIndex=-1; while(listIterator.hasNext()) { v2Set = listIterator.next(); remIndex++; if(v2Set.contains(new Integer(j))) { System.out.println("j = "+j); break; } } System.out.println("remIndex = "+remIndex); if(remIndex !=-1) { /* both vertices have already been discovered but are in different connected components and so must be linked or the union of the two components must be formed*/ System.out.println("Printing v1 set"); for(Integer temp : v1Set) { System.out.print(temp.toString()+","); } System.out.println("\nPrinting v2 set"); for(Integer temp : v2Set) { System.out.print(temp.toString()+","); } connComponents.remove(remIndex); //removing connComp of node j and adding it to node i v1Set.addAll(v2Set); } else { //Both vertices are newly discovered and so must belong to a new connected component System.out.println("\nNewly discovered Vertices = "+i+" "+j+"\n"); v1Set = new HashSet<Integer>(); v1Set.add(new Integer(i)); v1Set.add(new Integer(j)); connComponents.add(v1Set); return; } } public static boolean ifCycle(int i,int j) { if(connComponents == null) { connComponents = new LinkedList<Set<Integer>>(); Set<Integer> connSet = new HashSet<Integer>(); connSet.add(new Integer(i)); connSet.add(new Integer(j)); connComponents.add(connSet); } else { ListIterator<Set<Integer>> listIterator = connComponents.listIterator(); Set<Integer> v1Set ; Set<Integer> v2Set; while(listIterator.hasNext()) { v1Set = listIterator.next(); if(v1Set.contains(new Integer(i))) { if(v1Set.contains(new Integer(j))) return true; //both are in same connected component } if(v1Set.contains(new Integer(j))) { if(v1Set.contains(new Integer(i))) return true; //both are in same connected component } } } return false; } public static boolean ifCycleUsingVisited(int i,int j) { if((visited[i]==0)&&(visited[j]==0)) { //both the vertices have not yet been discoverd..they belong to a new Connected Component visited[i]=connComp; visited[j]=connComp; connComp++; //incrementing } return false; } public static void main(String args[]) { int [][]arr = { {-1,3,1,6,-1,-1}, {-1,-1,5,-1,3,-1}, {-1,-1,-1,5,6,4}, {-1,-1,-1,-1,-1,2}, {-1,-1,-1,-1,-1,6}, {-1,-1,-1,-1,-1,-1}}; int v =6; int []visited={0,0,0,0,0,0}; //edge [] e_arr = new edge int noe=0; //count number of selected edges System.out.println("Starting traversals\n"); while(noe<(v-1)) //for 6 vertices 5 edges are selected { int v1=0; int v2=0; //vertices of the selected edge int min_edge = -1; for(int i=0;i<v;i++) { for(int j=i+1;j<v;j++) //main diagonal all -1s { if(arr[i][j]!=-1) { System.out.println("min_edge = "+min_edge); System.out.println("arr ["+i+"]["+j+"] = "+arr[i][j]); if((min_edge == -1)&&!ifCycle(i,j)) //min_edge cannot be set a vertice that can cause a cycle { min_edge = arr[i][j]; v1=i; //what if first non -1 edge is also the minimum edge v2=j; } else if((arr[i][j]<min_edge)&&!ifCycle(i,j)) //not <= because we can multiple min edges of the same weight { //edge weight is lower than min edge and the both vertices have not already been visited or else a cycle would form min_edge = arr[i][j]; System.out.println("Temporary min edge between "+i+" "+j+" = "+min_edge); v1=i; v2=j; } } } } setVisited(v1,v2); //function to mark visited so that cycles are not formed arr[v1][v2]=-1; //marking this edge so it's not selected again noe++;//incrementing number of selected edges System.out.println("Selected edge between "+v1+" "+v2+" = "+min_edge); } } }
package org.kuali.mobility.events.entity; public interface EventContact { public abstract String getName(); public abstract void setName(String name); public abstract String getEmail(); public abstract void setEmail(String email); public abstract String getUrl(); public abstract void setUrl(String url); }
package com.bozhong.lhdataaccess.infrastructure.dao; import com.bozhong.lhdataaccess.domain.InPatientDO; import com.bozhong.lhdataaccess.domain.OrganizStructureDO; import com.bozhong.lhdataaccess.domain.OutPatientDO; import com.zhicall.core.mybatis.page.Page; import com.zhicall.core.mybatis.page.PageRequest; import java.util.List; /** * User: 李志坚 * Date: 2018/11/5 * 门诊患者数据的DAO */ public interface OutPatientDAO { void updateOrInsertOutPatient(OutPatientDO outPatientDO); List<OutPatientDO> selectDataBylastUpdateTime(OutPatientDO outPatientDO); Page<OutPatientDO> selectDataByPage(PageRequest pageRequest); }
package com.example.demo.Model; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Customer { @Id //Fields private int customer_id; private String cus_first_name; private String cus_last_name; private int driver_licence; private String street; private int house_num; private String city; private int zip_code; private int address_id; // Spring require a empty construkctor public Customer() { } public Customer(int customer_id, String cus_first_name, String cus_last_name, int driver_licence, String street, int house_num, String city, int zip_code, int address_id) { this.customer_id = customer_id; this.cus_first_name = cus_first_name; this.cus_last_name = cus_last_name; this.driver_licence = driver_licence; this.street = street; this.house_num = house_num; this.city = city; this.zip_code = zip_code; this.address_id = address_id; } public int getCustomer_id() { return customer_id; } public void setCustomer_id(int customer_id) { this.customer_id = customer_id; } public String getCus_first_name() { return cus_first_name; } public void setCus_first_name(String cus_first_name) { this.cus_first_name = cus_first_name; } public String getCus_last_name() { return cus_last_name; } public void setCus_last_name(String cus_last_name) { this.cus_last_name = cus_last_name; } public int getDriver_licence() { return driver_licence; } public void setDriver_licence(int driver_licence) { this.driver_licence = driver_licence; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public int getHouse_num() { return house_num; } public void setHouse_num(int house_num) { this.house_num = house_num; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public int getZip_code() { return zip_code; } public void setZip_code(int zip_code) { this.zip_code = zip_code; } public int getAddress_id() { return address_id; } public void setAddress_id(int address_id) { this.address_id = address_id; } }
/* * 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 stockmanagement; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; /** * * @author haktu */ @Entity @Table(name = "CALISANLAR") @NamedQueries({ @NamedQuery(name = "Calisanlar.findAll", query = "SELECT c FROM Calisanlar c"), @NamedQuery(name = "Calisanlar.findById", query = "SELECT c FROM Calisanlar c WHERE c.id = :id"), @NamedQuery(name = "Calisanlar.findByAdi", query = "SELECT c FROM Calisanlar c WHERE c.adi = :adi"), @NamedQuery(name = "Calisanlar.findBySoyadi", query = "SELECT c FROM Calisanlar c WHERE c.soyadi = :soyadi"), @NamedQuery(name = "Calisanlar.findByMagazasi", query = "SELECT c FROM Calisanlar c WHERE c.magazasi = :magazasi"), @NamedQuery(name = "Calisanlar.findByMaas", query = "SELECT c FROM Calisanlar c WHERE c.maas = :maas")}) public class Calisanlar implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "ID") private Integer id; @Column(name = "ADI") private String adi; @Column(name = "SOYADI") private String soyadi; @Column(name = "MAGAZASI") private String magazasi; @Column(name = "MAAS") private Integer maas; public Calisanlar() { } public Calisanlar(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAdi() { return adi; } public void setAdi(String adi) { this.adi = adi; } public String getSoyadi() { return soyadi; } public void setSoyadi(String soyadi) { this.soyadi = soyadi; } public String getMagazasi() { return magazasi; } public void setMagazasi(String magazasi) { this.magazasi = magazasi; } public Integer getMaas() { return maas; } public void setMaas(Integer maas) { this.maas = maas; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Calisanlar)) { return false; } Calisanlar other = (Calisanlar) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "stockmanagement.Calisanlar[ id=" + id + " ]"; } }
package za.co.edusys.domain.repository; import org.springframework.data.jpa.repository.JpaRepository; import za.co.edusys.domain.model.User; import za.co.edusys.domain.model.event.Event; import za.co.edusys.domain.model.event.EventItem; import java.util.List; import java.util.stream.Stream; /** * Created by marc.marais on 2017/02/27. */ public interface EventItemRepository extends JpaRepository<EventItem, Long> { Stream<EventItem> findByUserAndEvent(User user, Event event); Stream<EventItem> findByUser(User user); }
package ua.project.protester.service.project; import ua.project.protester.exception.ProjectAlreadyExistsException; import ua.project.protester.exception.ProjectNotFoundException; import ua.project.protester.model.ProjectDto; import ua.project.protester.utils.Page; import ua.project.protester.utils.Pagination; public interface ProjectService { ProjectDto create(ProjectDto projectDto) throws ProjectAlreadyExistsException; ProjectDto update(ProjectDto projectDto) throws ProjectAlreadyExistsException; ProjectDto changeStatus(Long projectId) throws ProjectNotFoundException; Page<ProjectDto> findAll(Pagination pagination); Page<ProjectDto> findAllByStatus(Pagination pagination, Boolean isActive); ProjectDto getById(Long id) throws ProjectNotFoundException; }
package top.kylewang.bos.dao.system; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import top.kylewang.bos.domain.system.Menu; import java.util.List; /** * @author Kyle.Wang * 2018/1/10 0010 21:21 */ public interface MenuRepository extends JpaRepository<Menu,Integer> { /** * 根据用户id查询菜单 * @param id * @return */ @Query("select m from Menu m inner join fetch m.roles r inner join fetch r.users u where u.id = ?1 order by m.priority") List<Menu> findByUser(Integer id); }
package uta.cloud.email.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import uta.cloud.email.entity.Email; import uta.cloud.email.service.EmailService; @RestController @RequestMapping(value = "/email") public class EmailController { @Autowired EmailService emailService; @GetMapping(value = "/send") String sendRegisterEmail(@RequestParam String address, @RequestParam String username) { String subject = "Register-xxh8517.uta.cloud"; String text = "Hi, " + username + "\nCongratulations! Your registration is successful."; emailService.SendSimpleEmail(address, subject, text); return "Email send successful"; } }
package edu.nju.data.util.HQL_Helper.Enums; /** * Created by ss14 on 2016/7/15. */ public enum FromPara { Quesstion, Answer,Comment; }
package com.siossae.android.biodatasqlite.db; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * Created by pri on 19/08/16. */ public class DataHelper extends SQLiteOpenHelper { // Attribute private static final String DATABASE_NAME = "db_biodata"; private static final int DATABASE_VERSION = 1; // Constructor public DataHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // Method utk buat database dan table ketika aplikasi mengakses database dan database belum ada. @Override public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE tbl_biodata (_id INTEGER PRIMARY KEY AUTOINCREMENT, nama TEXT NULL, tgl TEXT NULL, jk TEXT NULL, alamat TEXT NULL)"; String sql1 = "CREATE TABLE tbl_depart (_id INTEGER PRIMARY KEY AUTOINCREMENT, depart TEXT NULL, kepala_id INTEGER NULL)"; db.execSQL(sql); db.execSQL(sql1); ContentValues values = new ContentValues(); values.put("depart", "analis"); values.put("kepala_id", 1); db.insert("tbl_depart", null, values); values.put("depart", "back-end"); values.put("kepala_id", 2); db.insert("tbl_depart", null, values); //Log.d("DATA", "onCreate: " + sql); } // Method untuk upgrade versi database jika ditemukan versi baru @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql = "DROP TABLE IF EXISTS tbl_biodata"; String sql1 = "DROP TABLE IF EXISTS tbl_depart"; db.execSQL(sql); db.execSQL(sql1); onCreate(db); } }
package com.shagaba.kickstarter.core.domain.profile; import java.time.DayOfWeek; import java.util.List; import java.util.Map; public class ContactPerson { protected String name; protected String firstName; protected String lastName; protected String email; protected Phone phonePrimary; protected Phone phoneSecondary; protected Map<DayOfWeek, List<TimePeriod>> availableHours; /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the firstName */ public String getFirstName() { return firstName; } /** * @param firstName the firstName to set */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * @return the lastName */ public String getLastName() { return lastName; } /** * @param lastName the lastName to set */ public void setLastName(String lastName) { this.lastName = lastName; } /** * @return the email */ public String getEmail() { return email; } /** * @param email the email to set */ public void setEmail(String email) { this.email = email; } /** * @return the phonePrimary */ public Phone getPhonePrimary() { return phonePrimary; } /** * @param phonePrimary the phonePrimary to set */ public void setPhonePrimary(Phone phonePrimary) { this.phonePrimary = phonePrimary; } /** * @return the phoneSecondary */ public Phone getPhoneSecondary() { return phoneSecondary; } /** * @param phoneSecondary the phoneSecondary to set */ public void setPhoneSecondary(Phone phoneSecondary) { this.phoneSecondary = phoneSecondary; } /** * @return the availableHours */ public Map<DayOfWeek, List<TimePeriod>> getAvailableHours() { return availableHours; } /** * @param availableHours the availableHours to set */ public void setAvailableHours(Map<DayOfWeek, List<TimePeriod>> availableHours) { this.availableHours = availableHours; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return String .format("ContactPerson {name=%s, firstName=%s, lastName=%s, email=%s, phonePrimary=%s, phoneSecondary=%s, availableHours=%s}", name, firstName, lastName, email, phonePrimary, phoneSecondary, availableHours); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((availableHours == null) ? 0 : availableHours.hashCode()); result = prime * result + ((email == null) ? 0 : email.hashCode()); result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((phonePrimary == null) ? 0 : phonePrimary.hashCode()); result = prime * result + ((phoneSecondary == null) ? 0 : phoneSecondary.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ContactPerson other = (ContactPerson) obj; if (availableHours == null) { if (other.availableHours != null) return false; } else if (!availableHours.equals(other.availableHours)) return false; if (email == null) { if (other.email != null) return false; } else if (!email.equals(other.email)) return false; if (firstName == null) { if (other.firstName != null) return false; } else if (!firstName.equals(other.firstName)) return false; if (lastName == null) { if (other.lastName != null) return false; } else if (!lastName.equals(other.lastName)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (phonePrimary == null) { if (other.phonePrimary != null) return false; } else if (!phonePrimary.equals(other.phonePrimary)) return false; if (phoneSecondary == null) { if (other.phoneSecondary != null) return false; } else if (!phoneSecondary.equals(other.phoneSecondary)) return false; return true; } }
package org.example.cayenne.persistent; import org.example.cayenne.persistent.auto._Invoice; public class Invoice extends _Invoice { private static final long serialVersionUID = 1L; }
package com.syzible.dublinnotifier.networking; import java.util.HashMap; import java.util.Iterator; import java.util.Set; /** * Created by ed on 18/12/2016 */ public class SearchHelper { public static String buildQuery(String url, HashMap<String, String> params) { Set<?> keys = params.keySet(); Iterator iterator = keys.iterator(); String paramBuilder = "", builtUrl = ""; int i = 0; while(iterator.hasNext()) { String key = iterator.next().toString(); paramBuilder += i == 0 ? "?" : "&"; paramBuilder += params.get(key); iterator.remove(); i++; } builtUrl += url.substring(url.length()).equals("/") ? url : url + "/"; return builtUrl + paramBuilder; } }
package com.hedong.hedongwx.utils; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hedong.hedongwx.thread.Server2; /** * * @author RoarWolf * @description 新1拖2设备的通信发送包、解析包处理 * */ public class NewSendmsgUtil { private static final Logger logger = LoggerFactory.getLogger(NewSendmsgUtil.class); public static void main(String[] args) { send_0x0A("000001", "00000001"); } public static byte clacSumVal(byte[] sums) { byte sum = 0x00; for (int i = 0; i < sums.length - 1; i++) { sum ^= sums[i]; } return sum; } /** * * @param code * @param addr */ public static void send_0x0A(String code, String addr) { ByteBuffer buffer = ByteBuffer.allocate(1024); byte sop = (byte) 0x55; byte len = (byte) 0x08; byte cmd = (byte) 0x10; int addrInt = DisposeUtil.hexToInt(addr); byte result = (byte) 0x01; byte data1 = (byte) 0x00; buffer.put(sop); buffer.put(len); buffer.put(cmd); buffer.putInt(addrInt); buffer.put(result); buffer.put(data1); buffer.position(1); byte[] sums = new byte[len & 0xff]; buffer.get(sums, 0, len); buffer.put(clacSumVal(sums)); buffer.flip(); // while (buffer.hasRemaining()) { // System.out.printf("0x%02x ", buffer.get()); // } // buffer.position(0); Server2.sendMsg(code, buffer); } public static void parse_0x0A(AsynchronousSocketChannel channel, byte len, byte cmd, byte result, ByteBuffer buffer, String addr) { // Map<String, Map> allMap = new HashMap<>(); // HashMap<String, String> map = new HashMap<>(); byte port = buffer.get(); short error_code = buffer.getShort(); byte sum = buffer.get(); String code = SendMsgUtil.getCodeByIpaddr(channel); String errorinfo = ""; if (error_code == 1) { errorinfo = "疑似继电器粘连"; } else { errorinfo = "其他错误"; } SendMsgUtil.deviceStatusFeedback(code, port + 0, errorinfo); logger.info(code + "号机端口:" + port + ", 错误码:" + error_code + "上传设备故障已接收"); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); byteBuffer.put(len); byteBuffer.put(cmd); byteBuffer.put(result); byteBuffer.put(port); byteBuffer.putShort(error_code); byteBuffer.flip(); byte[] datas = new byte[100]; byteBuffer.get(datas, 0, len); byte checkoutSum = SendMsgUtil.checkoutSum(datas); if (sum == checkoutSum) { logger.info("wolflog---" + "数据发送验证成功"); } else { logger.info("wolflog---" + "数据发送验证失败"); } send_0x0A(code, addr); } }
package com.example.here_usecases; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.here.android.common.GeoCoordinate; import com.here.android.mapping.FactoryInitListener; import com.here.android.mapping.InitError; import com.here.android.mapping.MapFactory; import com.here.android.search.ErrorCode; import com.here.android.search.Places; import com.here.android.search.ResultListener; import com.here.android.search.places.TextSuggestionRequest; import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; public class Text_suggestions extends Activity implements TextWatcher, ResultListener<List<String>> { SimpleAdapter m_adapter; List<java.util.Map<String, String>> m_SuggestionList = null; TextSuggestionRequest request = null; private Places map_places = null; private GeoCoordinate m_sydney = null; private static final double SYDNEY_lat = -33.87365; private static final double SYDNEY_lon = 151.20689; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.text_suggestions); m_SuggestionList = new ArrayList<java.util.Map<String,String>>(); ListView lv = (ListView) findViewById(R.id.listView); m_adapter = new SimpleAdapter(this, m_SuggestionList, android.R.layout.simple_list_item_1, new String[] {"suggestion"}, new int[] {android.R.id.text1}); lv.setAdapter(m_adapter); ((TextView)findViewById(R.id.geostring)).addTextChangedListener(this); MapFactory.initFactory(getApplicationContext(), new FactoryInitListener() { @Override public void onFactoryInitializationCompleted(InitError error) { // TODO Auto-generated method stub if(error == InitError.NONE){ map_places = MapFactory.getPlaces(); m_sydney = MapFactory.createGeoCoordinate(SYDNEY_lat, SYDNEY_lon); } else { Toast.makeText(getApplicationContext(),"MapFactory init error: " + error, Toast.LENGTH_LONG).show(); } } }); } @Override public void afterTextChanged(Editable arg0) { if(map_places == null){ Toast.makeText(getApplicationContext(),"Map places not initialized!", Toast.LENGTH_SHORT).show(); return; } if(request != null){ request.cancel(); request = null; } m_SuggestionList = new ArrayList<java.util.Map<String,String>>(); ListView lv = (ListView) findViewById(R.id.listView); m_adapter = new SimpleAdapter(this, m_SuggestionList, android.R.layout.simple_list_item_1, new String[] {"suggestion"}, new int[] {android.R.id.text1}); lv.setAdapter(m_adapter); TextView textviewDate=(TextView)findViewById(R.id.geostring); String selectedText =textviewDate.getText().toString(); if(selectedText.length() > 0){ Toast.makeText(getApplicationContext(),"now requesting", Toast.LENGTH_SHORT).show(); request = map_places.createTextSuggestionRequest(m_sydney,selectedText); request.execute(this); } } @Override public void onCompleted(List<String> data, ErrorCode error) { if(error == ErrorCode.NONE && data != null){ if(data.size() > 0){ for(int i=0; i < data.size(); i++){ m_SuggestionList.add(createSuggestion("suggestion", data.get(i))); } }else{ Toast.makeText(getApplicationContext(),"No results for Suggestions", Toast.LENGTH_SHORT).show(); } }else{ Toast.makeText(getApplicationContext(),"Suggestion finished with error: " + error, Toast.LENGTH_LONG).show(); } } private HashMap<String, String> createSuggestion(String key, String name) { HashMap<String, String> planet = new HashMap<String, String>(); planet.put(key, name); return planet; } @Override public void beforeTextChanged(CharSequence s, int start, int count,int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} }
package ch.rasc.eds.starter.service; import static ch.ralscha.extdirectspring.annotation.ExtDirectMethodType.FORM_POST; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import ch.ralscha.extdirectspring.annotation.ExtDirectMethod; import ch.ralscha.extdirectspring.bean.ExtDirectResponseBuilder; import ch.rasc.eds.starter.FormBean; @Controller public class FormSubmitController { @ExtDirectMethod(FORM_POST) @RequestMapping(value = "/handleFormSubmit", method = RequestMethod.POST) public void handleFormSubmit(final FormBean bean, final MultipartFile screenshot, final HttpServletRequest request, final HttpServletResponse response) { String result = "Server received: \n" + bean.toString(); result += "\n"; if (!screenshot.isEmpty()) { result += "ContentType: " + screenshot.getContentType() + "\n"; result += "Size: " + screenshot.getSize() + "\n"; result += "Name: " + screenshot.getOriginalFilename(); } ExtDirectResponseBuilder.create(request, response).addResultProperty("response", result).buildAndWrite(); } }
package gcodeviewer.toolpath.events; import gcodeviewer.toolpath.GCodeEvent; public class EndExtrusion implements GCodeEvent { }
package ua.project.protester.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor public class TestCaseWrapperResult { private Integer id; private List<ActionWrapper> actionWrapperList; private Integer scenarioId; private Integer testResultId; public TestCaseWrapperResult(Integer id, Integer scenarioId, Integer testResultId) { this.id = id; this.scenarioId = scenarioId; this.testResultId = testResultId; } }
/* * 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 cl.duoc.ptf8502.ejb.wrapper; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.EntityResult; import javax.persistence.FieldResult; import javax.persistence.Id; import javax.persistence.SqlResultSetMapping; /** * * @author Mauri */ @Entity @SqlResultSetMapping(name = "WrapperPorcentajePreparacionAreaPicking", entities = { @EntityResult(entityClass = WrapperPorcentajePreparacionAreaPicking.class, fields = { @FieldResult(name = "total", column = "total"), @FieldResult(name = "cumplidos", column = "cumplidos") }) }) public class WrapperPorcentajePreparacionAreaPicking implements Serializable { @Id private Integer total; private Integer cumplidos; public WrapperPorcentajePreparacionAreaPicking() { } public Integer getTotal() { return total; } public void setTotal(Integer total) { this.total = total; } public Integer getCumplidos() { return cumplidos; } public void setCumplidos(Integer cumplidos) { this.cumplidos = cumplidos; } }
package gupaoedu.vip.pattern.factory.factorymethod; import gupaoedu.vip.pattern.factory.ICourse; import gupaoedu.vip.pattern.factory.JavaCourse; /** * 2019/6/17 * suh **/ public class JavaCourseFactory implements ICourseFactory{ @Override public ICourse create() { return new JavaCourse(); } }
package com.sfa.controller; import java.util.List; import javax.mail.MessagingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.sfa.dto.JSONResult; import com.sfa.security.Auth; import com.sfa.security.AuthUser; import com.sfa.service.AffirmationService; import com.sfa.service.UserService; import com.sfa.util.CreatePasswd; import com.sfa.util.Push; import com.sfa.vo.UserVo; @Controller public class UserController { @Autowired private UserService userService; @Autowired private AffirmationService affirmationService; @Autowired private Push push; @Autowired private CreatePasswd cratePasswd; @RequestMapping(value = { "", "/login" }, method = RequestMethod.GET) public String login(@AuthUser UserVo authUser, Model model) { // login 페이지 forward // 긍정의 한줄 가져오기 String Affirmation = affirmationService.select(); model.addAttribute("affrimation", Affirmation); if (authUser != null) { // 세션이 끝나지 않으면 main 화면으로 이동 return "redirect:/main"; } else { // 세션이 끝나면 user/login 화면으로 이동 return "user/login"; } } @Auth(value = Auth.Role.팀장) @RequestMapping(value = "/join", method = RequestMethod.GET) public String join() { // 회원가입 페이지 forward return "user/join"; } @Auth(value = Auth.Role.팀장) @RequestMapping(value = "/join", method = RequestMethod.POST) public String join(@ModelAttribute UserVo userVo, Model model, BindingResult result, @AuthUser UserVo authUser) { // 정상적인 접근이 아닐 경우 if (userVo == null) { System.out.println("error_0x1"); return "user/join"; } else if ( // 회원가입 목록에 정상적으로 들어오지 않는 경우 userVo.getDept() == null || userVo.getGrade() == null || userVo.getId() == null || userVo.getName() == null || userVo.getPasswd() == null) { System.out.println("error_join_0x2"); return "user/join"; } else { // 정상적으로 회원가입 되었을 경우 if (userService.join(userVo) == true) { try { push.Mail(userVo.getCompany_email(), "[" + userVo.getId() + "]님 회원가입을 축하합니다.", "사원 아이디 : " + userVo.getId() + "\n" + "사원 이름 : " + userVo.getName() + "\n" + "사원 부서 : " + userVo.getDept() + "\n" + "사원 이메일 : " + userVo.getCompany_email() + "\n" + "사원 직급 :" + userVo.getGrade() + "\n" + "회원 가입을 진심으로 축하합니다.\n", "admin"); UserVo userVo2 = userService.getLeader(userVo.getId()); push.Message(userVo.getId(), userVo2.getId(), 0); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } model.addAttribute("userVo", userVo); return "user/joinsuccess"; } else if (userService.join(userVo) == false) { return "redirect:/join?result=fail"; } return "user/join"; } } @Auth(value = Auth.Role.팀장) @RequestMapping(value = "/delete", method = RequestMethod.POST) public String delete(@ModelAttribute UserVo userVo, Model model) { if (userVo == null) { return "user/login"; } else if (userVo.getClass() == null) { return "user/modify"; } int no = userService.delete(userVo); if (no == 1) { return "redirect:list"; } else { return "redirect:/modify?result=fail"; } } @Auth(value = Auth.Role.팀장) @RequestMapping(value = "/modify", method = RequestMethod.GET) public String modify(@RequestParam(value = "id", required = true, defaultValue = "") String id, @AuthUser UserVo authUser, Model model) { if (authUser.getId() == null) { return "user/login"; } UserVo userVo = userService.getId(id); model.addAttribute("userVo", userVo); return "user/modify"; } @Auth(value = Auth.Role.팀장) @RequestMapping(value = "/modify", method = RequestMethod.POST) public String modify(@ModelAttribute UserVo userVo, Model model) { System.out.println(userVo); if (userVo == null) { return "user/modify"; } else if (userVo.getId() == null || userVo.getName() == null || userVo.getGrade() == null || userVo.getDept() == null) { return "user/modify"; } int no = userService.modify(userVo); if (no == 1) { return "redirect:list"; } else { return "redirect:modify?result=fail&id=" + userVo.getId(); } } @Auth @ResponseBody @RequestMapping(value = "/check", method = RequestMethod.GET) public JSONResult search(@RequestParam(value = "id", required = true, defaultValue = "") String id) { if ("".equals(id)) { return JSONResult.error("cod_e0x1"); } UserVo userVo = userService.getId(id); System.out.println("[Controller] : " + userVo); if (userVo == null) { return JSONResult.fail(); } return JSONResult.success(id); } @Auth @ResponseBody @RequestMapping(value = "/checkEmail", method = RequestMethod.GET) public JSONResult searchEmail(@RequestParam(value = "email", required = true, defaultValue = "") String email) { if ("".equals(email)) { return JSONResult.error("cod_e0x1"); } List<UserVo> list = userService.getemail(email); System.out.println(list); if (list.isEmpty()) { return JSONResult.success("사용 가능한 메일입니다."); } return JSONResult.fail("중복된 메일이 존재합니다."); } @RequestMapping(value = "/joinsuccess", method = RequestMethod.GET) public String joinsceess(@ModelAttribute UserVo userVo, Model model) { model.addAttribute("userVo", userVo); return "user/joinsuccess"; } @Auth(value = Auth.Role.팀장) @RequestMapping(value = "/list", method = RequestMethod.GET) public String list(HttpSession authUser, Model model) { if (authUser.getAttribute("authUser") == null) { return "user/login"; } String dept = ((UserVo) authUser.getAttribute("authUser")).getDept(); List<UserVo> list = userService.getTotalMember(dept); model.addAttribute("list", list); return "user/list"; } @Auth(value = Auth.Role.팀장) @RequestMapping(value = "/list", method = RequestMethod.POST) public String list(@RequestParam(value = "name", required = true, defaultValue = "") String name, @RequestParam(value = "grade", required = true, defaultValue = "") String grade, HttpSession authUser, Model model) { if (authUser.getAttribute("authUser") == null) { return "user/login"; } String dept = ((UserVo) authUser.getAttribute("authUser")).getDept(); if ("".equals(name) && "".equals(grade)) { return "user/list"; } else if ("전체".equals(grade) && "".equals(name)) { List<UserVo> list = userService.getTotalMember(dept); model.addAttribute("list", list); return "user/list"; } else { List<UserVo> list = userService.getMember(name, grade, dept); model.addAttribute("list", list); return "user/list"; } } // 회원 아이디/비밀번호 찾기 페이지 들어가기 @RequestMapping(value = "/search", method = RequestMethod.GET) public String search() { return "user/search"; } // id 찾기 부분 통신 구현 @ResponseBody @RequestMapping(value = "/search/id", method = RequestMethod.POST) public JSONResult searchbyId(@RequestParam(value = "email", required = true, defaultValue = "") String email, @RequestParam(value = "name", required = true, defaultValue = "") String name) { if ("".equals(email) || "".equals(name)) { return JSONResult.error("이메일과 이름이 전달되지 않았습니다."); } else { UserVo userVo = userService.getId(email, name); if (userVo == null) { return JSONResult.fail("가입되어 잇는 정보가 없습니다."); } else { return JSONResult.success(userVo.getId()); } } } // pw 찾기 부분 통신 구현 @ResponseBody @RequestMapping(value = "/search/pw", method = RequestMethod.POST) public JSONResult searchbyPw(@RequestParam("id") String id, @RequestParam("email") String email) { if ("".equals(id) || "".equals(email)) { return JSONResult.error("아이디와 이름이 전달되지 않았습니다."); } else { UserVo userVo = userService.getUserByName(id, email); if (userVo != null) { String passwd = cratePasswd.create(); int no = userService.updatePasswd(id, passwd); if (no == 1) { try { push.Mail(userVo.getEmail(), id + "님 임시비밀번호 보내드립니다.", "임시 비밀번호는" + passwd + "입니다.", "admin"); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return JSONResult.success(userVo.getEmail()); } else { return JSONResult.fail("임시비밀번호 생성이 실패하였습니다."); } } } return JSONResult.error("서버에서 오류가 발생하였습니다."); } @Auth @RequestMapping(value = "/mypage", method = RequestMethod.GET) public String mypage(@AuthUser UserVo authUSer, Model model) { model.addAttribute("user", authUSer); return "mypage/mypage"; } @Auth @RequestMapping(value = "/mypage", method = RequestMethod.POST) public String mypage(@AuthUser UserVo authUser, Model model, @ModelAttribute UserVo userVo, HttpServletRequest request) { if (authUser == null) { return "user/login"; } else if (userVo == null) { return "mypage/mypage"; } userVo.setId(authUser.getId()); int no = userService.modify(userVo); if (no == 1) { HttpSession session = request.getSession(true); session.setAttribute("authUser", userVo); return "redirect:mypage?result=success"; } else { return "redirect:mypage?result=fail"; } } @Auth(value = Auth.Role.팀장) @ResponseBody @RequestMapping(value = "/pwd/reset", method = RequestMethod.POST) public JSONResult SendEmail(@RequestParam(value = "id", required = true, defaultValue = "") String id) { if ("".equals(id)) { return JSONResult.error("아이디값 넘겨주라고!!!!"); } UserVo userVo = userService.getId(id); String passwd = cratePasswd.create(); int no = userService.updatePasswd(id, passwd); if (no == 1) { try { push.Mail(userVo.getEmail(), id + "님 임시비밀번호 보내드립니다.", "임시 비밀번호는" + passwd + "입니다.", "admin"); return JSONResult.success(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); return JSONResult.success(); } } else { return JSONResult.fail("임시비밀번호 생성이 실패하였습니다."); } } }
package com.duanxr.yith.midium; import com.duanxr.yith.define.listNode.ListNode; import com.duanxr.yith.define.treeNode.TreeNode; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @author 段然 2021/3/17 */ public class ListOfDepthLCCI { /** * Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists). Return a array containing all the linked lists. * *   * * Example: * * Input: [1,2,3,4,5,null,7,8] * * 1 * / \ * 2 3 * / \ \ * 4 5 7 * / * 8 * * Output: [[1],[2,3],[4,5,7],[8]] * * 给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。 * *   * * 示例: * * 输入:[1,2,3,4,5,null,7,8] * * 1 * / \ * 2 3 * / \ \ * 4 5 7 * / * 8 * * 输出:[[1],[2,3],[4,5,7],[8]] * */ class Solution { public ListNode[] listOfDepth(TreeNode tree) { if (tree == null) { return new ListNode[0]; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(tree); List<List<ListNode>> nodes = new ArrayList<>(); while (!queue.isEmpty()) { int size = queue.size(); ArrayList<ListNode> list = new ArrayList<>(); nodes.add(list); for (int i = 0; i < size; i++) { TreeNode poll = queue.poll(); ListNode listNode = new ListNode(poll.val); if (!list.isEmpty()) { list.get(list.size() - 1).next = listNode; } list.add(listNode); if (poll.left != null) { queue.offer(poll.left); } if (poll.right != null) { queue.offer(poll.right); } } } ListNode[] result = new ListNode[nodes.size()]; for (int i = 0; i < result.length; i++) { result[i] = nodes.get(i).get(0); } return result; } } }
package gr.athena.innovation.fagi.preview.statistics; import java.util.Objects; /** * Class representing a group of statistics. * * @author nkarag */ public class StatGroup { private EnumStatGroup enumGroup; private String title; private String legendA; private String legendB; private String legendTotal; /** * Constructor of a statistic group object. * * @param enumGroup the group enumeration. */ public StatGroup(EnumStatGroup enumGroup){ switch(enumGroup) { case UNDEFINED: break; case PERCENT: this.enumGroup = enumGroup; this.title = "Percentages of property values"; this.legendA = "Non empty fields A(%)"; this.legendB = "Non empty fields B(%)"; this.legendTotal = "Total(%)"; break; case PROPERTY: this.enumGroup = enumGroup; this.title = "Number of property values"; this.legendA = "Properties of dataset A"; this.legendB = "Properties of dataset B"; this.legendTotal = "Total Properties"; break; case TRIPLE_BASED: this.enumGroup = enumGroup; this.title = "Number of Triples"; this.legendA = "Triples in A"; this.legendB = "Triples in B"; this.legendTotal = "Total Triples"; break; case POI_BASED: this.enumGroup = enumGroup; this.title = "Number of POIs"; this.legendA = "Number of POIs "; this.legendB = "Number of POIs"; this.legendTotal = "Total"; break; default: throw new IllegalArgumentException(); } } @Override public String toString() { return "StatGroup{" + "enumGroup=" + enumGroup + ", title=" + title + ", legendA=" + legendA + ", legendB=" + legendB + ", legendTotal=" + legendTotal + '}'; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.enumGroup); hash = 97 * hash + Objects.hashCode(this.title); hash = 97 * hash + Objects.hashCode(this.legendA); hash = 97 * hash + Objects.hashCode(this.legendB); hash = 97 * hash + Objects.hashCode(this.legendTotal); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final StatGroup other = (StatGroup) obj; if (!Objects.equals(this.title, other.title)) { return false; } if (!Objects.equals(this.legendA, other.legendA)) { return false; } if (!Objects.equals(this.legendB, other.legendB)) { return false; } if (!Objects.equals(this.legendTotal, other.legendTotal)) { return false; } return this.enumGroup == other.enumGroup; } /** * Return the enumeration of the statistic group. * * @return the statistic group enumeration. */ public EnumStatGroup getEnumGroup() { return enumGroup; } /** * Return the title. * * @return the title. */ public String getTitle() { return title; } /** * Return the legend of A. * * @return the legend. */ public String getLegendA() { return legendA; } /** * Return the legend of B. * * @return the legend. */ public String getLegendB() { return legendB; } /** * The legend that refers to the total value. * * @return the legend of the total value. */ public String getLegendTotal() { return legendTotal; } }
@javax.annotation.ParametersAreNonnullByDefault package samples.jsr305.nullness.annotatedpackage;
class if_Test6{ public static void main(String ar[]){ boolean b = true; if (b == true) { //조건-boolean b를 true에 대입, if(b)=if(b==true)-->boolean타입이기 때문에 가능^^^^^^^^^^^^^^^^^^^ System.out.println("참입니다"); } else { System.out.println("아닙니다"); } } }
package com.arkaces.aces_marketplace_api.account_service; import com.arkaces.aces_marketplace_api.error.FieldErrorCodes; import com.arkaces.aces_marketplace_api.error.ValidatorException; import com.arkaces.aces_marketplace_api.services.ServiceStatus; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.ResourceUtils; import org.springframework.util.StringUtils; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BindingResult; import java.util.Arrays; import java.util.List; @Service @RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class UpdateServiceRequestValidator { private final List<String> allowedServiceStatuses = Arrays.asList( ServiceStatus.ACTIVE, ServiceStatus.INACTIVE, ServiceStatus.DELETED ); public void validate(UpdateServiceRequest updateServiceRequest) { BindingResult bindingResult = new BeanPropertyBindingResult(updateServiceRequest, "updateServiceRequest"); if (updateServiceRequest.getLabel() != null) { if (StringUtils.isEmpty(updateServiceRequest.getLabel())) { bindingResult.rejectValue("label", FieldErrorCodes.REQUIRED, "Label is required."); } } String url = updateServiceRequest.getUrl(); if (url != null) { if (StringUtils.isEmpty(url)) { bindingResult.rejectValue("url", FieldErrorCodes.REQUIRED, "Service URL is required."); } else if (! ResourceUtils.isUrl(url)) { bindingResult.rejectValue("url", FieldErrorCodes.INVALID_URL, "Service URL must be a valid URL."); } } String status = updateServiceRequest.getStatus(); if (status != null) { if (! allowedServiceStatuses.contains(status)) { bindingResult.rejectValue("status", FieldErrorCodes.INVALID_SERVICE_STATUS, "Service status is invalid."); } } // todo: validate service info response if (bindingResult.hasErrors()) { throw new ValidatorException(bindingResult); } } }
/** * */ package org.ashah.sbcloudroleservice; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * @author avish * */ @Entity @Table(name="employee_roll") public class EmployeeRoll implements Serializable{ public EmployeeRoll() { } /** * */ private static final long serialVersionUID = -6325397956562805285L; @Id @Column(name="role_id") private Long roleId; @Column(name="role_name") private String roleName; @Column(name="role_description") private String description; public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
package hirondelle.web4j.ui.tag; import hirondelle.web4j.BuildImpl; import hirondelle.web4j.TESTAll.DateConverterImpl; import hirondelle.web4j.model.ModelCtorException; import hirondelle.web4j.model.ModelUtil; import hirondelle.web4j.request.DateConverter; import hirondelle.web4j.request.Formats; import hirondelle.web4j.ui.tag.Populate.Style; import hirondelle.web4j.util.Consts; import hirondelle.web4j.util.Util; import hirondelle.web4j.util.WebUtil; import java.io.FileNotFoundException; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Set; import java.util.TimeZone; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.jsp.JspException; import junit.framework.TestCase; /** (UNPUBLISHED) <a href="http://www.junit.org">JUnit</a> test cases for {@link PopulateHelper}. TO RUN THIS CLASS, some temporary adjustments need to be made to this class and the Formats class. - 1 change to this class - 2 changes to Formats See TESTAll as well! */ public final class TESTFormPopulator extends TestCase { /** Run the test cases. */ public static void main(String args[]) throws FileNotFoundException, ServletException { fLogger.setLevel(Level.OFF); String[] testCaseName = { TESTFormPopulator.class.getName() }; BuildImpl.adHocImplementationAdd(DateConverter.class, DateConverterImpl.class); junit.textui.TestRunner.main(testCaseName); } public TESTFormPopulator (String aName) { super(aName); } // TEST CASES // public void testSingleParamsWithInputTags() throws JspException, IOException { //test no alteration of tag which is not related to input testSingleParam("<IMG src='http://www.blah.com/images/blah.gif' ALT='blah'>", "<IMG src='http://www.blah.com/images/blah.gif' ALT='blah'>", "LoginName", "Strummer"); //test no alteration of tag whose type(submit) is not supported testSingleParam("<input type=\"submit\" value='REGISTER'>", "<input type=\"submit\" value='REGISTER'>", "LoginName", "Strummer"); //text testSingleParam("<input name='LoginName' type='text' size='30'>", "<input value=\"Strummer\" name='LoginName' type='text' size='30'>", "LoginName", "Strummer"); //caps, spacing, quotes testSingleParam("<INPUT NAME='LoginName' TYPE='TEXT' SIZE='30'>", "<INPUT value=\"Strummer\" NAME='LoginName' TYPE='TEXT' SIZE='30'>", "LoginName", "Strummer"); //additional extraneous attr's testSingleParam("<input name='LoginName' type='text' size='30' class='blah'>", "<input value=\"Strummer\" name='LoginName' type='text' size='30' class='blah'>", "LoginName", "Strummer"); //password testSingleParam("<input name='LoginPassword' type='password' size='30'>", "<input value=\"clash\" name='LoginPassword' type='password' size='30'>", "LoginPassword", "clash"); //hidden testSingleParam("<input name='LoginPassword' type='hidden'>", "<input value=\"clash\" name='LoginPassword' type='hidden'>", "LoginPassword", "clash"); //search testSingleParam("<input name='Bob' type='search'>", "<input value=\"clash\" name='Bob' type='search'>", "Bob", "clash"); //email testSingleParam("<input name='Bob' type='email'>", "<input value=\"joe&#064;clash&#046;com\" name='Bob' type='email'>", "Bob", "joe@clash.com"); //url testSingleParam("<input name='Bob' type='url'>", "<input value=\"http&#058;&#047;&#047;www&#046;date4j&#046;net\" name='Bob' type='url'>", "Bob", "http://www.date4j.net"); //tel testSingleParam("<input name='Bob' type='tel'>", "<input value=\"1&#045;800&#045;549&#045;BLAH\" name='Bob' type='tel'>", "Bob", "1-800-549-BLAH"); //number testSingleParam("<input name='Bob' type='number'>", "<input value=\"3&#046;14\" name='Bob' type='number'>", "Bob", "3.14"); //color testSingleParam("<input name='Bob' type='color'>", "<input value=\"&#035;001122\" name='Bob' type='color'>", "Bob", "#001122"); //range testSingleParam("<input name='Bob' type='range'>", "<input value=\"56\" name='Bob' type='range'>", "Bob", "56"); //radio with match testSingleParam("<INPUT type='RADIO' name=\"StarRating\" value='1'>", "<INPUT checked type='RADIO' name=\"StarRating\" value='1'>", "StarRating", "1"); //radio with no match testSingleParam("<INPUT type='RADIO' name=\"StarRating\" value='2'>", "<INPUT type='RADIO' name=\"StarRating\" value='2'>", "StarRating", "1"); //checkbox with match testSingleParam("<input type=\"CHECKBOX\" name=\"SendCard\" value='true'>", "<input checked type=\"CHECKBOX\" name=\"SendCard\" value='true'>", "SendCard", "true"); //checkbox with no match testSingleParam("<input type=\"CHECKBOX\" name=\"SendCard\" value='true'>", "<input type=\"CHECKBOX\" name=\"SendCard\" value='true'>", "SendCard", "false"); //text with default is overwritten testSingleParam("<input name='LoginName' value='Joe' type='text' size='30'>", "<input name='LoginName' value=\"Mick\" type='text' size='30'>", "LoginName", "Mick"); //as above, but with hidden testSingleParam("<input name='LoginName' value='Joe' type='hidden'>", "<input name='LoginName' value=\"Mick\" type='hidden'>", "LoginName", "Mick"); //as above, but with search testSingleParam("<input name='LoginName' value='Joe' type='search'>", "<input name='LoginName' value=\"Mick\" type='search'>", "LoginName", "Mick"); //as above, but with number testSingleParam("<input name='LoginName' value='3.14' type='number'>", "<input name='LoginName' value=\"7&#046;95\" type='number'>", "LoginName", "7.95"); //text with default is overwritten even if param is empty testSingleParam("<input name='LoginName' value='Mick' type='text' size='30'>", "<input name='LoginName' value=\"\" type='text' size='30'>", "LoginName", ""); //as above, but with hidden testSingleParam("<input name='LoginName' value='Mick' type='hidden'>", "<input name='LoginName' value=\"\" type='hidden'>", "LoginName", ""); //as above, but with search testSingleParam("<input name='LoginName' value='Mick' type='search'>", "<input name='LoginName' value=\"\" type='search'>", "LoginName", ""); //text with default is overwritten even if default is empty testSingleParam("<input name='LoginName' value='' type='text' size='30'>", "<input name='LoginName' value=\"Mick\" type='text' size='30'>", "LoginName", "Mick"); //radio is checked by default, but no match, so is unchecked testSingleParam("<INPUT type='RADIO' checked name=\"StarRating\" value='1'>", "<INPUT type='RADIO' name=\"StarRating\" value='1'>", "StarRating", "2"); //as previous, but checked attr at end testSingleParam("<INPUT type='RADIO' name=\"StarRating\" value='1' checked>", "<INPUT type='RADIO' name=\"StarRating\" value='1'>", "StarRating", "2"); //radio is checked by default, and matches, so is unchanged testSingleParam("<INPUT type='RADIO' checked name=\"StarRating\" value='1'>", "<INPUT type='RADIO' checked name=\"StarRating\" value='1'>", "StarRating", "1"); //checkbox is checked by default, but no match, so is removed testSingleParam("<input type=\"CHECKBOX\" name=\"SendCard\" checked value='true'>", "<input type=\"CHECKBOX\" name=\"SendCard\" value='true'>", "SendCard", "false"); //checkbox is checked by default, with match, so is retained testSingleParam("<input type=\"CHECKBOX\" name=\"SendCard\" value='true' checked>", "<input type=\"CHECKBOX\" name=\"SendCard\" value='true' checked>", "SendCard", "true"); } public void testInputTagWithSpecialRegexChar() throws JspException, IOException { //this test failed with the first version of PopulateHelper, since an item //was not 'escaped' for special regex chars. As well, this case was untested //in the original test cases. testSingleParam("<input name='DesiredSalary' type='text' size='30'>", "<input value=\"100&#046;00U&#036;\" name='DesiredSalary' type='text' size='30'>", "DesiredSalary", "100.00U$"); } public void testBigFailures() throws JspException, IOException { //invalid flavor testBigFailure("<inputt name='LoginName' type='text' size='30'>", "<input value=\"Strummer\" name='LoginName' type='text' size='30'>", "LoginName", "Strummer"); //compulsory attr not found (type) testBigFailure("<input name='LoginName' size='30'>", "<input value=\"Strummer\" name='LoginName' type='text' size='30'>", "LoginName", "Strummer"); //compulsory attr not found (name) testBigFailure("<input type='text' size='30'>", "<input value=\"Strummer\" name='LoginName' type='text' size='30'>", "LoginName", "Strummer"); //no param of expected name in scope testBigFailure("<input name='LoginName' type='text' size='30'>", "<input value=\"Strummer\" name='LoginName' type='text' size='30'>", "Login", "Strummer"); } public void testModelObjectWithInputTags() throws JspException, IOException, ModelCtorException { User user = getUser(); //text testModelObject("<input name='LoginName' type='text' size='30'>", "<input value=\"Strummer\" name='LoginName' type='text' size='30'>", user); //test no alteration of tag which is not related to input testModelObject("<IMG src='http://www.blah.com/images/blah.gif' ALT='blah'>", "<IMG src='http://www.blah.com/images/blah.gif' ALT='blah'>", user); //test no alteration of tag whose type(submit) is not supported testModelObject("<input type=\"submit\" value='REGISTER'>", "<input type=\"submit\" value='REGISTER'>", user); //caps, spacing, quotes testModelObject("<INPUT NAME='LoginName' TYPE='TEXT' SIZE='30'>", "<INPUT value=\"Strummer\" NAME='LoginName' TYPE='TEXT' SIZE='30'>", user); //additional extraneous attr's testModelObject("<input name='LoginName' type='text' size='30' class='blah'>", "<input value=\"Strummer\" name='LoginName' type='text' size='30' class='blah'>", user); //password testModelObject("<input name='LoginPassword' type='password' size='30'>", "<input value=\"clash\" name='LoginPassword' type='password' size='30'>", user); //hidden testModelObject("<input name='LoginPassword' type='hidden'>", "<input value=\"clash\" name='LoginPassword' type='hidden'>", user); //search testModelObject("<input name='LoginPassword' type='search'>", "<input value=\"clash\" name='LoginPassword' type='search'>", user); //email testModelObject("<input name='EmailAddress' type='email'>", "<input value=\"joe&#064;clash&#046;com\" name='EmailAddress' type='email'>", user); //number testModelObject("<input name='DesiredSalary' type='number'>", "<input value=\"17500&#046;00\" name='DesiredSalary' type='number'>", user); //range testModelObject("<input name='Range' type='range'>", "<input value=\"17&#046;5\" name='Range' type='range'>", user); //color testModelObject("<input name='Color' type='color'>", "<input value=\"&#035;001122\" name='Color' type='color'>", user); //radio with match testModelObject("<INPUT type='RADIO' name=\"StarRating\" value='1'>", "<INPUT checked type='RADIO' name=\"StarRating\" value='1'>", user); //radio with no match testModelObject("<INPUT type='RADIO' name=\"StarRating\" value='2'>", "<INPUT type='RADIO' name=\"StarRating\" value='2'>", user); //checkbox with match testModelObject("<input type=\"CHECKBOX\" name=\"SendCard\" value='false'>", "<input checked type=\"CHECKBOX\" name=\"SendCard\" value='false'>", user); //checkbox with no match testModelObject("<input type=\"CHECKBOX\" name=\"SendCard\" value='true'>", "<input type=\"CHECKBOX\" name=\"SendCard\" value='true'>", user); //text with default is overwritten testModelObject("<input name='LoginName' value='Mick' type='text' size='30'>", "<input name='LoginName' value=\"Strummer\" type='text' size='30'>", user); //as above, but for hidden testModelObject("<input name='LoginName' value='Mick' type='hidden'>", "<input name='LoginName' value=\"Strummer\" type='hidden'>", user); //text with default is overwritten even if default is empty testModelObject("<input name='LoginName' value='' type='text' size='30'>", "<input name='LoginName' value=\"Strummer\" type='text' size='30'>", user); //as above, but with hidden testModelObject("<input name='LoginName' value='' type='hidden'>", "<input name='LoginName' value=\"Strummer\" type='hidden'>", user); //as above, but with search testModelObject("<input name='LoginName' value='' type='search'>", "<input name='LoginName' value=\"Strummer\" type='search'>", user); //radio is checked by default, but no match, so is unchecked testModelObject("<INPUT type='RADIO' checked name=\"StarRating\" value='2'>", "<INPUT type='RADIO' name=\"StarRating\" value='2'>", user); //as previous, but checked attr at end testModelObject("<INPUT type='RADIO' name=\"StarRating\" value='2' checked>", "<INPUT type='RADIO' name=\"StarRating\" value='2'>", user); //radio is checked by default, and matches, so is unchanged testModelObject("<INPUT type='RADIO' checked name=\"StarRating\" value='1'>", "<INPUT type='RADIO' checked name=\"StarRating\" value='1'>", user); //checkbox is checked by default, but no match, so is removed testModelObject("<input type=\"CHECKBOX\" name=\"SendCard\" checked value='true'>", "<input type=\"CHECKBOX\" name=\"SendCard\" value='true'>", user); //checkbox is checked by default, with match, so is retained testModelObject("<input type=\"CHECKBOX\" name=\"SendCard\" value='false' checked>", "<input type=\"CHECKBOX\" name=\"SendCard\" value='false' checked>", user); //basic sanity for Locale and TimeZone testModelObject("<input name='Country' type='text' size='30'>", "<input value=\"en&#095;ca\" name='Country' type='text' size='30'>", user); testModelObject("<input name='TZ' type='text' size='30'>", "<input value=\"Canada&#047;Atlantic\" name='TZ' type='text' size='30'>", user); } public void testFailBeanMethod() throws JspException, IOException, ModelCtorException { try { //name of tag does not match any bean getXXX method testModelObject("<input name='LoginNameB' type='text' size='30'>", "<input value=\"Strummer\" name='LoginName' type='text' size='30'>", getUser()); } catch(Throwable ex){ return; } fail("Should have failed."); } public void testParamsWithSelectTags() throws JspException, IOException { //basic prepop testSelect( "<select name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option selected>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Electrodynamics"} ); //extra attr's testSelect( "<select name='FavoriteTheory'>"+NL+ " <option class='blah'>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option selected class='blah'>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Electrodynamics"} ); //with value attr and selected testSelect( "<select name='FavoriteTheory'>"+NL+ " <option class='blah'>Quantum Electrodynamics</option>"+NL+ " <option value='Quantum Flavordynamics'>QFD</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option class='blah'>Quantum Electrodynamics</option>"+NL+ " <option selected value='Quantum Flavordynamics'>QFD</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Flavordynamics"} ); //with value attr and not selected testSelect( "<select name='FavoriteTheory'>"+NL+ " <option class='blah'>Quantum Electrodynamics</option>"+NL+ " <option value='Quantum Flavordynamics'>QFD</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option selected class='blah'>Quantum Electrodynamics</option>"+NL+ " <option value='Quantum Flavordynamics'>QFD</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Electrodynamics"} ); //caps, spaces, and quotes testSelect( "<SELECT NAME=\"FavoriteTheory\">"+NL+ " <OPTION class=\"blah\" >Quantum Electrodynamics</OPTION>"+NL+ " <OPTION value=\"Quantum Flavordynamics\" >QFD</OPTION>"+NL+ " <OPTION >Quantum Chromodynamics</OPTION>"+NL+ "</SELECT>", "<SELECT NAME=\"FavoriteTheory\">"+NL+ " <OPTION class=\"blah\" >Quantum Electrodynamics</OPTION>"+NL+ " <OPTION value=\"Quantum Flavordynamics\" >QFD</OPTION>"+NL+ " <OPTION selected >Quantum Chromodynamics</OPTION>"+NL+ "</SELECT>", "FavoriteTheory", new Object[] {"Quantum Chromodynamics"} ); //retain default selected testSelect( "<select name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option selected>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option selected>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Flavordynamics"} ); //retain default selected when other attr's present testSelect( "<select name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option value='Quantum Flavordynamics' selected class='blah'>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option value='Quantum Flavordynamics' selected class='blah'>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Flavordynamics"} ); //remove default selected when no match testSelect( "<select name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option value='Quantum Flavordynamics' selected class='blah'>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option value='Quantum Flavordynamics' class='blah'>Quantum Flavordynamics</option>"+NL+ " <option selected>Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Chromodynamics"} ); //extra attrs in select tag testSelect( "<select class='blah' name='FavoriteTheory' size='30'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select class='blah' name='FavoriteTheory' size='30'>"+NL+ " <option selected>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Electrodynamics"} ); //test leading and trailing spaces in body of option tag testSelect( "<select name='FavoriteTheory'>"+NL+ " <option> Quantum Electrodynamics </option>"+NL+ " <option> Quantum Flavordynamics </option>"+NL+ " <option> Quantum Chromodynamics</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option selected> Quantum Electrodynamics </option>"+NL+ " <option> Quantum Flavordynamics </option>"+NL+ " <option> Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Electrodynamics"} ); //as above, with different selected testSelect( "<select name='FavoriteTheory'>"+NL+ " <option> Quantum Electrodynamics </option>"+NL+ " <option> Quantum Flavordynamics </option>"+NL+ " <option> Quantum Chromodynamics</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option> Quantum Electrodynamics </option>"+NL+ " <option selected> Quantum Flavordynamics </option>"+NL+ " <option> Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Flavordynamics"} ); //as above, with different selected testSelect( "<select name='FavoriteTheory'>"+NL+ " <option> Quantum Electrodynamics </option>"+NL+ " <option> Quantum Flavordynamics </option>"+NL+ " <option> Quantum Chromodynamics</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option> Quantum Electrodynamics </option>"+NL+ " <option> Quantum Flavordynamics </option>"+NL+ " <option selected> Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Chromodynamics"} ); //multiple selects testSelect( "<select multiple name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select multiple name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option selected>Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Chromodynamics"} ); //special regex chars in extra attrs in option tag testSelect( "<select class='blah' name='FavoriteTheory'>"+NL+ " <option title='Aliases [utf-1-1-unicode]'>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select class='blah' name='FavoriteTheory'>"+NL+ " <option selected title='Aliases [utf-1-1-unicode]'>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Electrodynamics"} ); } public void testFailedSelects() throws JspException, IOException, ModelCtorException { testFailSelect( "<select name='FaveTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select name='FaveTheory'>"+NL+ " <option selected>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "FaveTheory", new Object[] {"Quantum Electrodynamics"} ); } public void testMultipleParamsWithSelectTags() throws JspException, IOException { //basic testSelect( "<select multiple name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select multiple name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option selected>Quantum Flavordynamics</option>"+NL+ " <option selected>Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Flavordynamics","Quantum Chromodynamics"} ); //value attr testSelect( "<select multiple name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option value='Quantum Flavordynamics'>QFD</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select multiple name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option selected value='Quantum Flavordynamics'>QFD</option>"+NL+ " <option selected>Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Flavordynamics","Quantum Chromodynamics"} ); //retain default selected testSelect( "<select multiple name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option selected value='Quantum Flavordynamics'>QFD</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select multiple name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option selected value='Quantum Flavordynamics'>QFD</option>"+NL+ " <option selected>Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Flavordynamics","Quantum Chromodynamics"} ); //remove default selected testSelect( "<select multiple name='FavoriteTheory'>"+NL+ " <option selected>Quantum Electrodynamics</option>"+NL+ " <option selected value='Quantum Flavordynamics'>QFD</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select multiple name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option selected value='Quantum Flavordynamics'>QFD</option>"+NL+ " <option selected>Quantum Chromodynamics</option>"+NL+ "</select>", "FavoriteTheory", new Object[] {"Quantum Flavordynamics","Quantum Chromodynamics"} ); } public void testBeanWithSelectTags() throws JspException, IOException, ModelCtorException { //basic prepop testModelObject( "<select name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option selected>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", getUser() ); //value attr, but not selected testModelObject( "<select name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option value='Quantum Chromodynamics'>QCD</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option selected>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option value='Quantum Chromodynamics'>QCD</option>"+NL+ "</select>", getUser() ); //value attr, and selected testModelObject( "<select name='FavoriteTheory'>"+NL+ " <option value='Quantum Electrodynamics'>QED</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option value='Quantum Chromodynamics'>QCD</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option selected value='Quantum Electrodynamics'>QED</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option value='Quantum Chromodynamics'>QCD</option>"+NL+ "</select>", getUser() ); //retain default selected testModelObject( "<select name='FavoriteTheory'>"+NL+ " <option selected value='Quantum Electrodynamics'>QED</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option selected value='Quantum Electrodynamics'>QED</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", getUser() ); //remove default selected testModelObject( "<select name='FavoriteTheory'>"+NL+ " <option value='Quantum Electrodynamics'>QED</option>"+NL+ " <option selected>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select name='FavoriteTheory'>"+NL+ " <option selected value='Quantum Electrodynamics'>QED</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", getUser() ); } public void testBeanWithMultiSelectTags() throws JspException, IOException, ModelCtorException { //User is taken as a bean which does not return a Set, but a String - this can //of course cause only one item to be selected testModelObject( "<select multiple name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select multiple name='FavoriteTheory'>"+NL+ " <option selected>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", getUser() ); //bean which returns a Set //this class the bean whose getFavoriteTheory method returns a Set //(A fake bean was attempted, but PopulateHelper barfs on nested classes.) testModelObject( "<select multiple name='FavoriteTheory'>"+NL+ " <option>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option>Quantum Chromodynamics</option>"+NL+ "</select>", "<select multiple name='FavoriteTheory'>"+NL+ " <option selected>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option selected>Quantum Chromodynamics</option>"+NL+ "</select>", this ); //defaults retained and removed testModelObject( "<select multiple name='FavoriteTheory'>"+NL+ " <option selected>Quantum Electrodynamics</option>"+NL+ " <option selected>Quantum Flavordynamics</option>"+NL+ " <option selected>Quantum Chromodynamics</option>"+NL+ "</select>", "<select multiple name='FavoriteTheory'>"+NL+ " <option selected>Quantum Electrodynamics</option>"+NL+ " <option>Quantum Flavordynamics</option>"+NL+ " <option selected>Quantum Chromodynamics</option>"+NL+ "</select>", this ); } /* See above method. */ public Set getFavoriteTheory(){ Set result = new LinkedHashSet(); result.add("Quantum Electrodynamics"); result.add("Quantum Chromodynamics"); return result; } public void testArgsWithTextAreaTag() throws JspException, IOException, ModelCtorException { //with default text testSingleParam("<textarea name='Comment'> This is a comment. </textarea>", "<textarea name='Comment'>The Clash</textarea>", "Comment", "The Clash"); //add other attr's testSingleParam("<textarea name='Comment' wrap='virtual' rows=20 cols=50> This is a comment. </textarea>", "<textarea name='Comment' wrap='virtual' rows=20 cols=50>The Clash</textarea>", "Comment", "The Clash"); //caps, spacing, quotes testSingleParam("<TEXTAREA NAME='Comment'> This is a comment. </TEXTAREA>", "<TEXTAREA NAME='Comment'>The Clash</TEXTAREA>", "Comment", "The Clash"); testSingleParam("<textarea NAME='Comment'> This is a comment. </TEXTAREA>", "<textarea NAME='Comment'>The Clash</TEXTAREA>", "Comment", "The Clash"); //without default text testSingleParam("<textarea name='Comment'> </textarea>", "<textarea name='Comment'>The Clash</textarea>", "Comment", "The Clash"); testSingleParam("<textarea name='Comment'></textarea>", "<textarea name='Comment'>The Clash</textarea>", "Comment", "The Clash"); testSingleParam("<textarea name='Comment'> </textarea>", "<textarea name='Comment'>The Clash</textarea>", "Comment", "The Clash"); //with new lines and white space testSingleParam("<textarea name='Comment'>" +Consts.NEW_LINE+ " This is a comment. " +Consts.NEW_LINE+ " </textarea>", "<textarea name='Comment'>The Clash</textarea>", "Comment", "The Clash"); testSingleParam("<textarea name='Comment'>" +Consts.NEW_LINE+ "</textarea>", "<textarea name='Comment'>The Clash</textarea>", "Comment", "The Clash"); testSingleParam("<textarea name='Comment'> " +Consts.NEW_LINE+ "</textarea>", "<textarea name='Comment'>The Clash</textarea>", "Comment", "The Clash"); testSingleParam("<textarea name='Comment'> " +Consts.NEW_LINE+ " </textarea>", "<textarea name='Comment'>The Clash</textarea>", "Comment", "The Clash"); testSingleParam("<textarea name='Comment'> " +Consts.NEW_LINE+ " </textarea>", "<textarea name='Comment'>The Clash</textarea>", "Comment", "The Clash"); //special regex chars in default body testSingleParam("<textarea name='Comment'> $This is a comment. </textarea>", "<textarea name='Comment'>The Clash</textarea>", "Comment", "The Clash"); testSingleParam("<textarea name='Comment'> This is a comment.$ </textarea>", "<textarea name='Comment'>The Clash</textarea>", "Comment", "The Clash"); testSingleParam("<textarea name='Comment'> $This is a comment.$ </textarea>", "<textarea name='Comment'>The Clash</textarea>", "Comment", "The Clash"); testSingleParam("<textarea name='Comment'> Thi$s is a comment. </textarea>", "<textarea name='Comment'>The Clash</textarea>", "Comment", "The Clash"); testSingleParam("<textarea name='Comment'> \\This is a comment. </textarea>", "<textarea name='Comment'>The Clash</textarea>", "Comment", "The Clash"); //special regex chars in replacememt testSingleParam("<textarea name='Comment'>This is a comment. </textarea>", "<textarea name='Comment'>The Cla&#036;h</textarea>", "Comment", "The Cla$h"); testSingleParam("<textarea name='Comment'>This is a comment. </textarea>", "<textarea name='Comment'>&#036;The Clash&#036;</textarea>", "Comment", "$The Clash$"); testSingleParam("<textarea name='Comment'>This is a comment. </textarea>", "<textarea name='Comment'>&#092;The Clash</textarea>", "Comment", "\\The Clash"); } public void testBeanWithTextAreaTag() throws JspException, IOException, ModelCtorException { User user = getUser(); //with default text testModelObject("<textarea name='LoginName'>This is a comment</textarea>", "<textarea name='LoginName'>Strummer</textarea>", user); //with other attr's testModelObject("<textarea name='LoginName' cols='20' rows='35'>This is a comment</textarea>", "<textarea name='LoginName' cols='20' rows='35'>Strummer</textarea>", user); //caps, spacing, quotes testModelObject("<TEXTAREA NAME='LoginName'>This is a comment</TEXTAREA>", "<TEXTAREA NAME='LoginName'>Strummer</TEXTAREA>", user); testModelObject("<textarea NAME='LoginName'>This is a comment</TEXTAREA>", "<textarea NAME='LoginName'>Strummer</TEXTAREA>", user); //without default text testModelObject("<textarea name='LoginName'></textarea>", "<textarea name='LoginName'>Strummer</textarea>", user); //with new lines and white space testModelObject("<textarea name='LoginName'>" +Consts.NEW_LINE+ "</textarea>", "<textarea name='LoginName'>Strummer</textarea>", user); testModelObject("<textarea name='LoginName'> " +Consts.NEW_LINE+ "This is a comment" + Consts.NEW_LINE + " </textarea>", "<textarea name='LoginName'>Strummer</textarea>", user); } // FIXTURE // protected void setUp(){ //empty } protected void tearDown() { //empty } // PRIVATE // private static final String NL = Consts.NEW_LINE; private User getUser(){ User result = null; try { result = new User( "Strummer", "clash", "joe@clash.com", new Integer(1), "Quantum Electrodynamics", Boolean.FALSE, new Integer(42), new BigDecimal("17500.00"), new Date(0), new BigDecimal("17.5"), "#001122" ); } catch (ModelCtorException ex){ fail("Cannot build User object."); } return result; } private static final Logger fLogger = Util.getLogger(TESTFormPopulator.class); private static void log(Object aThing){ System.out.println(String.valueOf(aThing)); } private void testSingleParam(String aIn, String aOut, String aParamName, String aParamValue) throws JspException, IOException { PopulateHelper.Context fakeParam = new FakeSingleParam(aParamName, aParamValue); PopulateHelper populator = new PopulateHelper( fakeParam, aIn, Style.MUST_RECYCLE_PARAMS ); String editedBody = populator.getEditedBody(); assertTrue( editedBody.equals(aOut) ); } private void testModelObject(String aIn, String aOut, Object aBean) throws JspException, IOException { PopulateHelper.Context myUserBean = new FakeBeanOnly(aBean); PopulateHelper populator = new PopulateHelper( myUserBean, aIn, Style.USE_MODEL_OBJECT); String populatedBody = populator.getEditedBody(); if( ! populatedBody.equals(aOut) ){ System.out.println("Populated Body : " + populatedBody); } assertTrue( populator.getEditedBody().equals(aOut) ); } private void testSelect(String aIn, String aOut, String aParamName, Object[] aParamValues) throws JspException, IOException { PopulateHelper.Context selectParams = new FakeSelectParams(aParamName, aParamValues); PopulateHelper populator = new PopulateHelper( selectParams, aIn, Style.MUST_RECYCLE_PARAMS); assertTrue( populator.getEditedBody().equals(aOut) ); } private void testBigFailure(String aIn, String aOut, String aParamName, String aParamValue) throws JspException, IOException { try { testSingleParam(aIn, aOut, aParamName, aParamValue); } catch(Throwable ex){ return; } fail("Should have failed."); } private void testFailSelect(String aIn, String aOut, String aParamName, Object[] aParamValues) throws JspException, IOException { try { testSelect(aIn, aOut, aParamName, aParamValues); } catch(Throwable ex){ return; } fail("Select should have failed."); } /** Fake the case where a single request parameter is present. */ static private final class FakeSingleParam implements PopulateHelper.Context { FakeSingleParam(String aParamName, String aParamValue){ fParamName = aParamName; fParamValue = aParamValue; } public String getReqParamValue(String aName){ return aName.equals(fParamName) ? fParamValue : null; } public boolean hasRequestParamNamed(String aParamName) { return fParamName.equals(aParamName); } public Object getModelObject(){ return null; } public boolean isModelObjectPresent() { return false; } public Formats getFormats(){ return new Formats(new Locale("en"), TimeZone.getTimeZone("GMT")); } public Collection<String> getReqParamValues(String aParamName){ Collection<String> result = new ArrayList<String>(); result.add(fParamValue); return aParamName.equals(fParamName) ? result : Collections.EMPTY_LIST; } private final String fParamName; private final String fParamValue; } /** Fake the case where a bean is present, but no request parameters. */ static private final class FakeBeanOnly implements PopulateHelper.Context { FakeBeanOnly(Object aObject){ fBean = aObject; } public String getReqParamValue(String aName){ return null; } public boolean hasRequestParamNamed(String aParamName) { return false; } public boolean isModelObjectPresent(){ return fBean != null; } public Object getModelObject(){ return fBean; } public Formats getFormats(){ return new Formats(new Locale("en"), TimeZone.getTimeZone("GMT") ); } public Collection<String> getReqParamValues(String aParamName){ return null; } private final Object fBean; } /** Fake the case where request parameters are possibly multi-valued. */ static private final class FakeSelectParams implements PopulateHelper.Context { FakeSelectParams(String aParamName, Object[] aParamValues){ fParamName = aParamName; fParamValues = Collections.unmodifiableCollection( Arrays.asList(aParamValues) ); } public String getReqParamValue(String aName){ return null; } public boolean hasRequestParamNamed(String aParamName) { return fParamName.equals(aParamName); } public boolean isModelObjectPresent(){ return false; } public Object getModelObject(){ return null; } public Formats getFormats(){ return new Formats(new Locale("en"), TimeZone.getTimeZone("GMT") ); } public Collection<String> getReqParamValues(String aParamName){ return aParamName.equals(fParamName) ? fParamValues : null; } private final String fParamName; private final Collection fParamValues; } private static final Pattern fLOGIN_NAME_PATTERN = Pattern.compile("(.){3,30}"); private static final Pattern fLOGIN_PASSWORD_PATTERN = Pattern.compile("(\\S){3,20}"); /** Typical model class stolen from exampleA. Even though this is repetition, it is the only area where the library uses the example. It would be a shame to have to link the projects for only this reason, as it is dangerous to attach the library to an app. */ public static final class User { /** @param aLoginName has trimmed length in range <tt>3..30</tt>. @param aLoginPassword has length in range <tt>3..20</tt>, and contains no whitespace. @param aEmailAddress satisfies {@link WebUtil#isValidEmailAddress} @param aStarRating rating of last meal in range <tt>1..4</tt>; optional - if null, replace with value of <tt>0</tt>. @param aFavoriteTheory favorite quantum field theory ; optional - may be <tt>null</tt>. @param aSendCard toggle for sending Christmas card to user ; optional - if <tt>null</tt>, replace with <tt>false</tt>. @param aAge of the user, in range <tt>0..150</tt> ; optional - may be <tt>null</tt>. @param aDesiredSalary is <tt>0</tt> or more ; optional - may be <tt>null</tt>. @param aBirthDate is not in the future ; optional - may be <tt>null</tt>. */ public User( String aLoginName, String aLoginPassword, String aEmailAddress, Integer aStarRating, String aFavoriteTheory, Boolean aSendCard, Integer aAge, BigDecimal aDesiredSalary, Date aBirthDate, BigDecimal aRange, String aColor ) throws ModelCtorException { fLoginName = Util.trimPossiblyNull(aLoginName); fLoginPassword = aLoginPassword; fEmailAddress = Util.trimPossiblyNull(aEmailAddress); fStarRating = Util.replaceIfNull(aStarRating, ZERO); fFavoriteTheory = aFavoriteTheory; fSendCard = Util.replaceIfNull(aSendCard, Boolean.FALSE); fAge = aAge; fDesiredSalary = aDesiredSalary; //defensive copy fBirthDate = aBirthDate == null ? null : new Long(aBirthDate.getTime()); fRange = aRange; fColor = aColor; validateState(); } public String getLoginName() { return fLoginName; } public String getLoginPassword() { return fLoginPassword; } public String getEmailAddress() { return fEmailAddress; } public Integer getStarRating(){ return fStarRating; } public String getFavoriteTheory(){ return fFavoriteTheory; } public Boolean getSendCard(){ return fSendCard; } public Integer getAge(){ return fAge; } public BigDecimal getDesiredSalary(){ return fDesiredSalary; } public Date getBirthDate(){ //defensive copy return fBirthDate == null ? null : new Date(fBirthDate.longValue()); } public Locale getCountry(){ return new Locale("en_ca"); } public TimeZone getTZ(){ return TimeZone.getTimeZone("Canada/Atlantic"); } public BigDecimal getRange(){ return fRange; } public String getColor(){ return fColor; } /** Intended for debugging only. */ public String toString() { return ModelUtil.toStringFor(this); } public boolean equals( Object aThat ) { if ( this == aThat ) return true; if ( !(aThat instanceof User) ) return false; User that = (User)aThat; return ModelUtil.equalsFor(this.getSignificantFields(), that.getSignificantFields()); } public int hashCode() { return ModelUtil.hashCodeFor(getSignificantFields()); } private Object[] getSignificantFields(){ return new Object[]{ fLoginName, fLoginPassword, fEmailAddress, fStarRating, fFavoriteTheory, fSendCard, fAge, fDesiredSalary, fBirthDate }; } // PRIVATE // private final String fLoginName; private final String fLoginPassword; private final String fEmailAddress; private final Integer fStarRating; private final String fFavoriteTheory; private final Boolean fSendCard; private final Integer fAge; private final BigDecimal fDesiredSalary; private final Long fBirthDate; private final BigDecimal fRange; private final String fColor; private static final Integer ZERO = new Integer(0); private void validateState() throws ModelCtorException { ModelCtorException ex = new ModelCtorException(); if ( ! isValidLoginName(fLoginName) ) { ex.add("Login name must have 3..30 characters"); } if ( ! isValidLoginPassword(fLoginPassword) ) { ex.add("Password must have 3..20 characters, with no spaces"); } if ( ! isValidEmailAddress(fEmailAddress) ){ ex.add("Email address has an invalid form"); } if ( ! isValidStarRating(fStarRating) ){ ex.add("Star Rating (optional) must be in range 1..4"); } //no validation needed for favoriteTheory, sendCard if ( ! isValidAge(fAge) ) { ex.add("Age must be in range 0..150"); } if ( ! isValidDesiredSalary(fDesiredSalary) ) { ex.add("Desired Salary must be 0 or more."); } if ( ! isValidBirthDate(fBirthDate) ){ ex.add("Birth Date must be in the past."); } if ( ! ex.isEmpty() ) throw ex; } private boolean isValidLoginName(String aLoginName){ return Util.matches(fLOGIN_NAME_PATTERN, aLoginName); } private boolean isValidLoginPassword(String aLoginPassword){ return Util.matches(fLOGIN_PASSWORD_PATTERN, aLoginPassword); } private boolean isValidEmailAddress(String aEmailAddress){ return WebUtil.isValidEmailAddress(aEmailAddress); } private boolean isValidStarRating(Integer aStarRating){ return Util.isInRange(aStarRating.intValue(), 0, 4); } private boolean isValidAge(Integer aAge){ boolean result = true; if ( aAge != null ){ if ( ! Util.isInRange(aAge.intValue(), 0, 150) ){ result = false; } } return result; } private boolean isValidDesiredSalary(BigDecimal aDesiredSalary){ final BigDecimal ZERO_MONEY = new BigDecimal("0"); boolean result = true; if ( aDesiredSalary != null ) { if ( aDesiredSalary.compareTo(ZERO_MONEY) < 0 ) { result = false; } } return result; } private boolean isValidBirthDate(Long aBirthDate){ boolean result = true; if ( aBirthDate != null ) { if ( aBirthDate.longValue() > System.currentTimeMillis()) { result = false; } } return result; } } }
package com.osce.vo.biz.plan.template; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.io.Serializable; /** * @ClassName: TdInsStationDetailVo * @Description: 排站信息 * @Author yangtongbin * @Date 2019-06-01 */ @Setter @Getter @ToString public class TdInsStationDetailVo implements Serializable { private static final long serialVersionUID = -467996255017463083L; /** * 主键 * 排站ID */ private Long idInsStation; /** * 模板ID */ private Long idModel; /** * 实例说明: 1 第一天上午 1.5 第一天下午 2 第二天上午 2.5 第二天下午 以此类推 */ private Float timeSection; /** * 考场ID */ private Long idArea; /** * 考场名称 */ private Long naArea; /** * 考站ID */ private Long idStation; /** * 考站名称 */ private Long naStation; /** * 1 内科 2 外科 3 妇产科 4 儿科 5 急诊 6 医患沟通 7 神经内科 8 眼鼻喉 9 皮肤科 10 肿瘤 11 传染 12 心理精神 13 循证医学 14 康复 15 伦理 */ private String sdStationCa; /** * 1 理论试题 2 技能操作 3 病史采集 */ private String sdSkillCa; /** * 主键 * 排站明细ID */ private Long idInsStationDetail; /** * 虚拟学生编码 */ private String cdInventedStudent; /** * 开始时间 */ private String timeBegin; /** * 结束时间 */ private String timeEnd; }
package ru.lischenko_dev.fastmessenger.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import org.greenrobot.eventbus.EventBus; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import ru.lischenko_dev.fastmessenger.common.Account; import ru.lischenko_dev.fastmessenger.util.Utils; import ru.lischenko_dev.fastmessenger.vkapi.Api; import ru.lischenko_dev.fastmessenger.vkapi.KException; import ru.lischenko_dev.fastmessenger.vkapi.models.VKMessage; public class LongPollService extends Service { public static final String TAG = "VKLongPollService"; public boolean isRunning; private Thread updateThread; private String key; private String server; private Long ts; private Object[] pollServer; private Account account; private Api api; public LongPollService() { } @Override public void onCreate() { super.onCreate(); account = Account.get(this); Log.d(TAG, "Created"); api = Api.init(account); isRunning = true; updateThread = new Thread(new MessageUpdater()); updateThread.start(); } @Override public void onDestroy() { super.onDestroy(); isRunning = false; } @Override public IBinder onBind(Intent intent) { return null; } private class MessageUpdater implements Runnable { @Override public void run() { while (isRunning) { Log.d(TAG, "Updater Task Started..."); if (!Utils.hasConnection(getApplicationContext())) { try { Thread.sleep(5_000); } catch (InterruptedException e) { e.printStackTrace(); } continue; } try { if (server == null) { getServer(); } String response = getResponse(); JSONObject root = new JSONObject(response); Long tsResponse = root.optLong("ts"); JSONArray updates = root.getJSONArray("updates"); ts = tsResponse; if (updates.length() != 0) { process(updates); } } catch (Exception e) { e.printStackTrace(); server = null; } } } private String getResponse() throws IOException { String request = "https://" + server + "?act=a_check&key=" + key + "&ts=" + ts + "&wait=25&mode=2"; return Api.sendRequestInternal(request, "", false); } private void messageEvent(JSONArray item) throws JSONException { VKMessage message = VKMessage.parse(item); EventBus.getDefault().postSticky(message); } private void messageClearFlags(int id, int mask) { if (VKMessage.isUnread(mask)) { EventBus.getDefault().post(id); } } private void getServer() throws IOException, JSONException, KException { pollServer = api.getLongPollServer(null, null); key = (String) pollServer[0]; server = (String) pollServer[1]; ts = (Long) pollServer[2]; } private void process(JSONArray updates) throws JSONException { if (updates.length() == 0) { return; } for (int i = 0; i < updates.length(); i++) { JSONArray item = updates.optJSONArray(i); int type = item.optInt(0); switch (type) { case 3: int id = item.optInt(1); int mask = item.optInt(2); messageClearFlags(id, mask); break; case 4: messageEvent(item); break; } } } } }
package sokrisztian.todo.admin.logic.service; import org.springframework.stereotype.Service; import sokrisztian.todo.admin.persistance.domain.TodoEntity; import sokrisztian.todo.admin.persistance.repository.TodoBasicRepository; @Service public class CreateTodoService { private static final String DEFAULT_DESCRIPTION = "What will be your next interesting TODO?"; private final TodoBasicRepository repository; public CreateTodoService(TodoBasicRepository repository) { this.repository = repository; } public void createBlank(int userId) { repository.save(createBlankTodo(userId)); } private TodoEntity createBlankTodo(int userId) { TodoEntity blank = new TodoEntity(); blank.setUserId(userId); blank.setDescription(DEFAULT_DESCRIPTION); return blank; } }
package com.goodhealth.design.advanced.BusinessAndScene.ationChain.action; import com.goodhealth.design.advanced.BusinessAndScene.ActionEnum; import com.goodhealth.design.advanced.BusinessAndScene.command.Command; /** * @ClassName AbstractAction * @Description TODO * @Author WDH * @Date 2019/8/20 21:07 * @Version 1.0 **/ public abstract class AbstractAction { abstract public ActionEnum getActionEnum(); abstract public Command getCommandGroup(); public void act(){ getCommandGroup().ation(); } }
package com.sample.observer.view.observer; import java.util.Observable; import java.util.Observer; import com.sample.observer.model.WeatherData; public class StatisticsPanel implements Observer{ @Override public void update(Observable obs, Object arg) { WeatherData weatherData = (WeatherData)arg; System.out.println("StatisticsPanel temperature:" + weatherData.temperature); System.out.println("StatisticsPanel humidity :" + weatherData.humidity); System.out.println("StatisticsPanel pressure :" + weatherData.pressure); } }
package com.bierocratie.ui.component; import com.vaadin.data.Container; import com.vaadin.data.Property; import java.math.BigDecimal; import java.math.BigInteger; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * Created with IntelliJ IDEA. * User: pir * Date: 13/11/14 * Time: 17:47 * To change this template use File | Settings | File Templates. */ public class Table extends com.vaadin.ui.Table { /** * */ private static final long serialVersionUID = -4340997217320528325L; public static final SimpleDateFormat simpleDateFormatter = new SimpleDateFormat("dd/MM/yyyy"); public static final NumberFormat doubleFormatter = NumberFormat.getNumberInstance(); public static final NumberFormat integerFormatter = NumberFormat.getNumberInstance(); static { doubleFormatter.setMinimumFractionDigits(2); doubleFormatter.setMaximumFractionDigits(2); } public Table(String tableName, Container dataSource) { super(tableName, dataSource); for (Object propertyId : this.getContainerPropertyIds()) { setColumnAlignment(propertyId, getColumnAlignment(getType(propertyId))); } } public Table(String tableName) { super(tableName); } @Override public boolean addContainerProperty(Object propertyId, Class<?> type, Object defaultValue) throws UnsupportedOperationException { setColumnAlignment(propertyId, getColumnAlignment(type)); return super.addContainerProperty(propertyId, type, defaultValue); } private Align getColumnAlignment(Class<?> type) { if (type == Date.class) { return Align.CENTER; } if (type == Boolean.class) { return Align.CENTER; } if (type == Double.class) { return Align.RIGHT; } if (type == BigInteger.class) { return Align.RIGHT; } if (type == BigDecimal.class) { return Align.RIGHT; } return Align.LEFT; } @Override protected String formatPropertyValue(Object rowId, Object colId, Property property) { if (property.getValue() == null) { return ""; } if (property.getType() == Date.class) { return simpleDateFormatter.format((Date) property.getValue()); } if (property.getType() == Boolean.class) { return (Boolean) property.getValue() ? "X" : ""; } if (property.getType() == Double.class) { return doubleFormatter.format((Double) property.getValue()); } if (property.getType() == BigInteger.class) { return integerFormatter.format(((BigInteger) property.getValue()).longValue()); } if (property.getType() == BigDecimal.class) { return doubleFormatter.format(((BigDecimal) property.getValue()).doubleValue()); } return super.formatPropertyValue(rowId, colId, property); } }
package com.prog5; import org.junit.Test; import static org.junit.Assert.assertEquals; public class LevenshteinTest { Levenshtein levenshtein = new Levenshtein(); @Test public void levQWERTY() { assertEquals(levenshtein.LevQWERTY("kot","kita"),1.5); assertEquals(levenshtein.LevQWERTY("drab","dal"),(double)2); } }
package com.tencent.mm.plugin.exdevice.model; import com.tencent.mm.plugin.exdevice.service.c.a; class d$7 extends a { final /* synthetic */ boolean fEU; final /* synthetic */ d itl; final /* synthetic */ String its; final /* synthetic */ long itt; d$7(d dVar, int i, String str, long j, boolean z) { this.itl = dVar; this.its = str; this.itt = j; this.fEU = z; super(i); } public final void onServiceConnected() { d.a(this.itl).iyE = null; this.itl.b(this.its, this.itt, this.bLL, this.fEU); } }
package com.spbsu.flamestream.example.labels; import com.spbsu.flamestream.core.DataItem; import com.spbsu.flamestream.core.Equalz; import com.spbsu.flamestream.core.Graph; import com.spbsu.flamestream.core.HashFunction; import com.spbsu.flamestream.core.TrackingComponent; import com.spbsu.flamestream.core.data.meta.LabelsPresence; import com.spbsu.flamestream.core.graph.FlameMap; import com.spbsu.flamestream.core.graph.Grouping; import com.spbsu.flamestream.core.graph.LabelMarkers; import com.spbsu.flamestream.core.graph.LabelSpawn; import com.spbsu.flamestream.core.graph.SerializableBiFunction; import com.spbsu.flamestream.core.graph.SerializableComparator; import com.spbsu.flamestream.core.graph.SerializableFunction; import com.spbsu.flamestream.core.graph.Sink; import com.spbsu.flamestream.core.graph.Source; import org.jetbrains.annotations.NotNull; import scala.Tuple2; import scala.util.Either; import scala.util.Left; import scala.util.Right; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; public class Materializer { private final Map<Operator<?>, TrackingComponent> operatorTrackingComponent; private final Map<Graph.Vertex, TrackingComponent> vertexTrackingComponent = new HashMap<>(); private final List<Graph.Vertex> labelSpawns = new ArrayList<>(); private final Map<Operator.LabelSpawn<?, ?>, List<LabelMarkers>> labelSpawnMarkers = new HashMap<>(); public static Graph materialize(Flow<?, ?> flow) { return new Materializer(flow).graph; } private final Graph graph; private <In, Out> Materializer(Flow<In, Out> flow) { final Map<Operator<?>, StronglyConnectedComponent> operatorStronglyConnectedComponent = buildStronglyConnectedComponents(flow); final StronglyConnectedComponent sinkComponent = new StronglyConnectedComponent(); sinkComponent.inbound.add(operatorStronglyConnectedComponent.get(flow.output)); final Map<StronglyConnectedComponent, TrackingComponent> stronglyConnectedComponentTracking = buildTrackingComponents(sinkComponent); operatorTrackingComponent = operatorStronglyConnectedComponent.entrySet().stream().collect(Collectors.toMap( Map.Entry::getKey, entry -> stronglyConnectedComponentTracking.get(entry.getValue()) )); final Source source = new Source(); final Sink sink = new Sink(); vertexTrackingComponent.put(source, operatorTrackingComponent.get(flow.input)); vertexTrackingComponent.put(sink, stronglyConnectedComponentTracking.get(sinkComponent)); graphBuilder .link(source, operatorVertex(flow.input)) .link(operatorVertex(flow.output), sink) .vertexTrackingComponent(vertexTrackingComponent::get) .init(flow.init); graphBuilder.colocate(vertexTrackingComponent.keySet().toArray(Graph.Vertex[]::new)); graph = graphBuilder.build(source, sink); } public static class StronglyConnectedComponent { final List<Operator<?>> operators = new ArrayList<>(); final Set<StronglyConnectedComponent> inbound = new HashSet<>(); } private final Graph.Builder graphBuilder = new Graph.Builder(); private final Map<Operator<?>, Graph.Vertex> cachedOperatorVertex = new HashMap<>(); Graph.Vertex operatorVertex(Operator<?> operator) { { final Graph.Vertex vertex = cachedOperatorVertex.get(operator); if (vertex != null) { return vertex; } } if (operator instanceof Operator.Input) { return processInput((Operator.Input<?>) operator); } else if (operator instanceof Operator.Map) { return processMap((Operator.Map<?, ?>) operator); } else if (operator instanceof Operator.StatefulMap) { return processStatefulMap((Operator.StatefulMap<?, ?, ?, ?, ?>) operator); } else if (operator instanceof Operator.Grouping) { return processGrouping((Operator.Grouping<?, ?, ?>) operator); } else if (operator instanceof Operator.LabelSpawn) { return processLabelSpawn((Operator.LabelSpawn<?, ?>) operator); } else if (operator instanceof Operator.LabelMarkers) { return processLabelMarkers((Operator.LabelMarkers<?, ?>) operator); } else { throw new IllegalArgumentException(operator.toString()); } } <T> Graph.Vertex processInput(Operator.Input<T> input) { final FlameMap<T, T> flameMap = new FlameMap.Builder<T, T>(Stream::of, input.typeClass).build(); cachedOperatorVertex.put(input, flameMap); vertexTrackingComponent.put(flameMap, operatorTrackingComponent.get(input)); for (final Operator<? extends T> source : input.sources) { graphBuilder.link(operatorVertex(source), flameMap); } return flameMap; } <In, Out> Graph.Vertex processMap(Operator.Map<In, Out> map) { final FlameMap<In, Out> flameMap = new FlameMap.Builder<>(map.mapper, map.source.typeClass) .hashFunction(hashFunction(dataItem -> dataItem.payload(map.source.typeClass), map.hash)).build(); cachedOperatorVertex.put(map, flameMap); vertexTrackingComponent.put(flameMap, operatorTrackingComponent.get(map)); graphBuilder.link(operatorVertex(map.source), flameMap); return flameMap; } private static final class Grouped<Key, Order, Item, State> { final Key key; final Order order; final Item item; final State state; final boolean isState; private Grouped(Key key, Order order, Item item, State state, boolean isState) { this.key = key; this.order = order; this.item = item; this.state = state; this.isState = isState; } } private static class StatefulMapGroupingEqualz<Key> implements Equalz { final LabelsPresence labels; final SerializableFunction<DataItem, Key> dataItemKey; private StatefulMapGroupingEqualz(LabelsPresence labels, SerializableFunction<DataItem, Key> dataItemKey) { this.labels = labels; this.dataItemKey = dataItemKey; } @Override public LabelsPresence labels() { return labels; } @Override public boolean testPayloads(DataItem o1, DataItem o2) { return Objects.equals(dataItemKey.apply(o1), dataItemKey.apply(o2)); } } public <K> HashFunction hashFunction( SerializableFunction<DataItem, K> function, Operator.Hashing<? super K> hashing ) { if (hashing == Operator.Hashing.Special.Broadcast) { return HashFunction.Broadcast.INSTANCE; } else if (hashing == Operator.Hashing.Special.PostBroadcast) { return HashFunction.PostBroadcast.INSTANCE; } else if (hashing == null) { return null; } final LabelsPresence labelsPresence = labelsPresence(hashing.labels()); return dataItem -> labelsPresence.hash(hashing.applyAsInt(function.apply(dataItem)), dataItem.meta().labels()); } <In, Key, O extends Comparable<O>, S, Out> Graph.Vertex processStatefulMap(Operator.StatefulMap<In, Key, O, S, Out> statefulMap) { @SuppressWarnings("unchecked") final Class<Tuple2<Grouped<Key, O, In, S>, Stream<Out>>> tupleClass = (Class<Tuple2<Grouped<Key, O, In, S>, Stream<Out>>>) (Class<?>) Tuple2.class; final Class<In> inClass = statefulMap.keyed.source.typeClass; @SuppressWarnings("unchecked") final Class<Grouped<Key, O, In, S>> groupedClass = (Class<Grouped<Key, O, In, S>>) (Class<?>) Grouped.class; final LabelsPresence keyLabelsPresence = labelsPresence(statefulMap.keyed.key.labels()); final FlameMap<In, Grouped<Key, O, In, S>> source = new FlameMap.Builder<>((In input) -> Stream.of( new Grouped<>( statefulMap.keyed.key.function().apply(input), statefulMap.keyed.order.apply(input), input, (S) null, false ) ), inClass) .hashFunction(hashFunction( dataItem -> statefulMap.keyed.key.function().apply(dataItem.payload(inClass)), statefulMap.keyed.hash )).build(); final SerializableFunction<DataItem, Key> dataItemKey = dataItem -> dataItem.payload(groupedClass).key; final Grouping<Grouped<Key, O, In, S>> grouping = new Grouping<>(new Grouping.Builder( hashFunction(dataItemKey, statefulMap.keyed.hash), new StatefulMapGroupingEqualz<>(keyLabelsPresence, dataItemKey), 2, groupedClass ).order(SerializableComparator.comparing(dataItem -> dataItem.payload(groupedClass).order))); final SerializableBiFunction<S, Grouped<Key, O, In, S>, Tuple2<Grouped<Key, O, In, S>, Stream<Out>>> reduce = (state, in) -> { final Tuple2<S, Stream<Out>> result = statefulMap.reducer.apply(in.item, state); return new Tuple2<>(new Grouped<>(in.key, in.order, in.item, result._1, true), result._2); }; final FlameMap<List<Grouped<Key, O, In, S>>, Tuple2<Grouped<Key, O, In, S>, Stream<Out>>> reducer = new FlameMap.Builder<>((List<Grouped<Key, O, In, S>> items) -> { switch (items.size()) { case 1: { final Grouped<Key, O, In, S> in = items.get(0); if (!in.isState) { return Stream.of(reduce.apply(null, in)); } return Stream.empty(); } case 2: { final Grouped<Key, O, In, S> state = items.get(0), in = items.get(1); if (state.isState && !in.isState) { return Stream.of(reduce.apply(state.state, in)); } return Stream.empty(); } default: throw new IllegalStateException("Group size should be 1 or 2"); } }, List.class).build(); final FlameMap<Tuple2<Grouped<Key, O, In, S>, Stream<Out>>, Grouped<Key, O, In, S>> regrouper = new FlameMap.Builder<>( (Tuple2<Grouped<Key, O, In, S>, Stream<Out>> item1) -> Stream.of(item1._1), tupleClass ).build(); final FlameMap<Tuple2<Grouped<Key, O, In, S>, Stream<Out>>, Out> sink = new FlameMap.Builder<>((Tuple2<Grouped<Key, O, In, S>, Stream<Out>> item) -> item._2, tupleClass).build(); cachedOperatorVertex.put(statefulMap, sink); final TrackingComponent trackingComponent = operatorTrackingComponent.get(statefulMap); vertexTrackingComponent.put(source, trackingComponent); vertexTrackingComponent.put(grouping, trackingComponent); vertexTrackingComponent.put(reducer, trackingComponent); vertexTrackingComponent.put(regrouper, trackingComponent); vertexTrackingComponent.put(sink, trackingComponent); graphBuilder .link(operatorVertex(statefulMap.keyed.source), source) .link(source, grouping) .link(grouping, reducer) .link(reducer, regrouper) .link(regrouper, grouping) .link(reducer, sink); return sink; } <In, Key, O extends Comparable<O>> Graph.Vertex processGrouping(Operator.Grouping<In, Key, O> grouping) { final Operator.Keyed<In, Key, O> keyed = grouping.keyed; final LabelsPresence keyLabelsPresence = labelsPresence(keyed.key.labels()); final Class<In> typeClass = keyed.source.typeClass; final SerializableFunction<DataItem, Key> dataItemKey = dataItem -> keyed.key.function().apply(dataItem.payload(typeClass)); final HashFunction hash = hashFunction(dataItemKey, keyed.hash); final Grouping<In> vertex = new Grouping<>( new Grouping.Builder( hash, new StatefulMapGroupingEqualz<>(keyLabelsPresence, dataItemKey), grouping.window, typeClass ).order(SerializableComparator.comparing(dataItem -> keyed.order.apply(dataItem.payload(typeClass)))) .undoPartialWindows(grouping.undoPartialWindows) ); cachedOperatorVertex.put(grouping, vertex); vertexTrackingComponent.put(vertex, operatorTrackingComponent.get(grouping)); graphBuilder.link(operatorVertex(keyed.source), vertex); return vertex; } @NotNull private LabelsPresence labelsPresence(Set<Operator.LabelSpawn<?, ?>> labels) { return new LabelsPresence( labels.stream().mapToInt(labelSpawn -> labelSpawns.indexOf(operatorVertex(labelSpawn))).toArray() ); } <Value, L> Graph.Vertex processLabelSpawn(Operator.LabelSpawn<Value, L> labelSpawn) { final List<LabelMarkers> labelMarkers = new ArrayList<>(); labelSpawnMarkers.put(labelSpawn, labelMarkers); final LabelSpawn<Value, L> vertex = new LabelSpawn<>(labelSpawn.typeClass, labelSpawns.size(), labelSpawn.mapper, labelMarkers); labelSpawns.add(vertex); cachedOperatorVertex.put(labelSpawn, vertex); vertexTrackingComponent.put(vertex, operatorTrackingComponent.get(labelSpawn)); graphBuilder.link(operatorVertex(labelSpawn.source), vertex); return vertex; } <In, L> Graph.Vertex processLabelMarkers(Operator.LabelMarkers<In, L> labelMarkers) { final Operator.Hashing<? super Either<In, L>> hashing = labelMarkers.hashing; final LabelMarkers vertex = new LabelMarkers( operatorTrackingComponent.get(labelMarkers), hashFunction( dataItem -> dataItem.marker() ? new Right<>(dataItem.payload(labelMarkers.labelSpawn.lClass)) : new Left<>(dataItem.payload(labelMarkers.source.typeClass)), hashing ) ); operatorVertex(labelMarkers.source); labelSpawnMarkers.get(labelMarkers.labelSpawn).add(vertex); vertexTrackingComponent.put(vertex, operatorTrackingComponent.get(labelMarkers)); cachedOperatorVertex.put(labelMarkers, vertex); graphBuilder.link(operatorVertex(labelMarkers.source), vertex); return vertex; } public static Map<StronglyConnectedComponent, TrackingComponent> buildTrackingComponents( StronglyConnectedComponent sink ) { final Map<StronglyConnectedComponent, Set<Operator.LabelMarkers<?, ?>>> componentLabelMarkers = new HashMap<>(); new Consumer<StronglyConnectedComponent>() { final Set<StronglyConnectedComponent> visited = new HashSet<>(); @Override public void accept(StronglyConnectedComponent current) { if (this.visited.add(current)) { componentLabelMarkers.put(current, new HashSet<>()); current.inbound.forEach(this); for (final Operator<?> operator : current.operators) { if (operator instanceof Operator.LabelMarkers) { if (current.operators.size() > 1) { throw new IllegalArgumentException(); } final Operator.LabelMarkers<?, ?> labelMarkers = (Operator.LabelMarkers<?, ?>) operator; new Consumer<StronglyConnectedComponent>() { @Override public void accept(StronglyConnectedComponent inbound) { if (componentLabelMarkers.get(inbound).add(labelMarkers)) { inbound.inbound.forEach(this); } } }.accept(current); } } } } }.accept(sink); final Map<Set<Operator.LabelMarkers<?, ?>>, Set<StronglyConnectedComponent>> trackingComponentsSet = componentLabelMarkers.entrySet().stream().collect(Collectors.groupingBy( Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toSet()) )); final Map<Set<Operator.LabelMarkers<?, ?>>, TrackingComponent> trackingComponents = new HashMap<>(); final Function<Set<Operator.LabelMarkers<?, ?>>, TrackingComponent> getTrackingComponent = new Function<>() { @Override public TrackingComponent apply(Set<Operator.LabelMarkers<?, ?>> labelMarkers) { { final TrackingComponent trackingComponent = trackingComponents.get(labelMarkers); if (trackingComponent != null) { return trackingComponent; } } final Set<TrackingComponent> allInbound = new HashSet<>(); for (final StronglyConnectedComponent component : trackingComponentsSet.get(labelMarkers)) { for (final StronglyConnectedComponent inbound : component.inbound) { final Set<Operator.LabelMarkers<?, ?>> inboundLabelMarkers = componentLabelMarkers.get(inbound); if (!inboundLabelMarkers.equals(labelMarkers)) { allInbound.add(this.apply(inboundLabelMarkers)); } } } final TrackingComponent trackingComponent = new TrackingComponent( trackingComponents.size(), allInbound ); trackingComponents.put(labelMarkers, trackingComponent); return trackingComponent; } }; return componentLabelMarkers.entrySet().stream().collect(Collectors.toMap( Map.Entry::getKey, entry -> getTrackingComponent.apply(entry.getValue()) )); } public static Map<Operator<?>, StronglyConnectedComponent> buildStronglyConnectedComponents(Flow<?, ?> flow) { final Map<Operator<?>, Set<Operator<?>>> transposed = new HashMap<>(); final List<Operator<?>> exited = new ArrayList<>(); { final Set<Operator<?>> discovered = new HashSet<>(); new Consumer<Operator<?>>() { @Override public void accept(Operator<?> operator) { if (discovered.add(operator)) { transposed.put(operator, new HashSet<>()); final Collection<? extends Operator<?>> inboundOperators; if (operator instanceof Operator.Input) { inboundOperators = ((Operator.Input<?>) operator).sources; } else if (operator instanceof Operator.Map) { inboundOperators = Collections.singleton(((Operator.Map<?, ?>) operator).source); } else if (operator instanceof Operator.StatefulMap) { inboundOperators = Collections.singleton(((Operator.StatefulMap<?, ?, ?, ?, ?>) operator).keyed.source); } else if (operator instanceof Operator.Grouping) { inboundOperators = Collections.singleton(((Operator.Grouping<?, ?, ?>) operator).keyed.source); } else if (operator instanceof Operator.LabelSpawn) { inboundOperators = Collections.singleton(((Operator.LabelSpawn<?, ?>) operator).source); } else if (operator instanceof Operator.LabelMarkers) { inboundOperators = Collections.singleton(((Operator.LabelMarkers<?, ?>) operator).source); } else { throw new IllegalArgumentException(operator.toString()); } inboundOperators.forEach(this); for (final Operator<?> inbound : inboundOperators) { transposed.get(inbound).add(operator); } exited.add(operator); } } }.accept(flow.output); } final Map<Operator<?>, StronglyConnectedComponent> operatorComponent = new HashMap<>(); for (int i = exited.size() - 1; i >= 0; i--) { final Operator<?> initialOperator = exited.get(i); if (!operatorComponent.containsKey(initialOperator)) { final StronglyConnectedComponent currentComponent = new StronglyConnectedComponent(); new Consumer<Operator<?>>() { @Override public void accept(Operator<?> outboundOperator) { final StronglyConnectedComponent connectedComponent = operatorComponent.get(outboundOperator); if (connectedComponent != null) { if (connectedComponent != currentComponent) { connectedComponent.inbound.add(currentComponent); } } else { operatorComponent.put(outboundOperator, currentComponent); currentComponent.operators.add(outboundOperator); transposed.get(outboundOperator).forEach(this); } } }.accept(initialOperator); } } return operatorComponent; } }
package net.asurovenko.netexam.events; public class OpenLoginFragmentEvent { }
package com.jcintegration.OrderProcessingApplication.CCValidation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(path="/creditcardmanage") public class CreditCardController { @Autowired private CreditCardRepository creditcardRepo; @GetMapping(path="/addCreditCardInfo") public @ResponseBody String addCreditCardInfo(@RequestParam String ccNo,@RequestParam String ccName,@RequestParam String ccStatus) { CreditCardInfo ccInfo = new CreditCardInfo(); ccInfo.setCcNo("1234-1234-1234-1234"); ccInfo.setCcName("James"); ccInfo.setCcStatus("Valid"); creditcardRepo.save(ccInfo); return "Saved"; } @GetMapping(path="/all") public @ResponseBody Iterable<CreditCardInfo> getAllCreditCardInfo() { // This returns a JSON or XML with the users return creditcardRepo.findAll(); } }
package com.xzj.lerning.aop.aspect; import com.xzj.lerning.aop.DefaultPerformanceProxyImpl; import com.xzj.lerning.aop.PerformanceProxy; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.DeclareParents; import org.springframework.stereotype.Component; /** * @Author: XuZhiJun * @Description: * @Date: Created in 15:13 2019/5/13 */ @Aspect @Component public class PerformanceEnhanceAspect { @DeclareParents(value = "com.xzj.lerning.aop.Performance+",defaultImpl = DefaultPerformanceProxyImpl.class) public static PerformanceProxy proxy; }
package com.thoughtpropulsion.fj; @FunctionalInterface public interface F00<T> { T apply(final T x); static <T> T identity(final T x) { return x; } static <T> F00<T> constantly(final T x) { return _dont_care -> x; } static <T> F00<T> compose(final F00<T> f, final F00<T> g) { return x -> f.apply( g.apply(x) ); } }
package org.nishkarma.petclinic.repository; import java.util.Collection; import org.nishkarma.petclinic.model.Vets; import org.springframework.dao.DataAccessException; public interface VetsMapper { Collection<Vets> findAll() throws DataAccessException; }
package com.lubarov.daniel.blog.post; import com.lubarov.daniel.bdb.SerializingDatabase; import com.lubarov.daniel.blog.Config; import com.lubarov.daniel.data.collection.Collection; import com.lubarov.daniel.data.option.Option; import com.lubarov.daniel.data.serialization.StringSerializer; public final class PostStorage { private static final SerializingDatabase<String, Post> byUuid = new SerializingDatabase<>( Config.getDatabaseHome("posts"), StringSerializer.singleton, PostSerializer.singleton); private PostStorage() {} public static void saveNewPost(Post post) { byUuid.put(post.getUuid(), post); } public static void updatePost(Post post) { byUuid.put(post.getUuid(), post); } public static void deletePost(Post post) { byUuid.delete(post.getUuid()); } public static Option<Post> getPostByUuid(String uuid) { return byUuid.get(uuid); } public static Collection<Post> getAllPosts() { return byUuid.getAllValues(); } private static void refreshAll() { for (Post post : getAllPosts()) updatePost(post); } }
package com.yinghai.a24divine_user.module.order; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.KeyEvent; import android.view.View; import android.widget.ImageView; import com.example.fansonlib.widget.textview.TextViewDrawable; import com.yinghai.a24divine_user.R; import com.yinghai.a24divine_user.base.MyBaseActivity; import com.yinghai.a24divine_user.callback.IBackFragmentListener; import com.yinghai.a24divine_user.module.order.all.AllOrderFragment; import com.yinghai.a24divine_user.module.order.book.BookFragment; import com.yinghai.a24divine_user.module.order.complete.CompleteOrderFragment; import com.yinghai.a24divine_user.utils.MyStatusBarUtil; import java.util.ArrayList; import java.util.List; /** * @author Created by:fanson * Created on:2017/10/24 16:44 * Description:我的订单Activity */ public class MyOrderActivity extends MyBaseActivity implements IBackFragmentListener, ChooseOrderTypeWindow.IChooseTypeListener { private static final String TAG = MyOrderActivity.class.getSimpleName(); private TabLayout mTabLayout; private ViewPager mViewPager; private OrderViewPagerAdapter mVpAdapter; private ImageView mBtnBack; private List<Fragment> mFragmentList; private AllOrderFragment mAllOrderFragment; private BookFragment mBookFragment; private CompleteOrderFragment mHistoryOrderFragment; private TextViewDrawable mTdChooseType; private ChooseOrderTypeWindow mChooseTypeWindow; @Override protected int getContentView() { return R.layout.activity_my_order; } @Override protected void initView() { super.initView(); mTabLayout = findMyViewId(R.id.tl_order); mViewPager = findMyViewId(R.id.vp_order); mBtnBack = findMyViewId(R.id.btn_back_toolbar); mTdChooseType = findMyViewId(R.id.td_choose); initTabLayout(); } @Override protected void initData() { mTvTitle.setText(getString(R.string.my_order)); MyStatusBarUtil.setDrawableStatus(this, R.drawable.shape_toolbar_bg); } @Override protected void listenEvent() { mBtnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MyOrderActivity.this.finish(); overridePendingTransition(R.anim.bottom_in, R.anim.top_out); } }); mTdChooseType.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mChooseTypeWindow==null){ mChooseTypeWindow = new ChooseOrderTypeWindow(MyOrderActivity.this,MyOrderActivity.this); } if (mChooseTypeWindow.isShowing()){ mChooseTypeWindow.dismiss(); }else { mChooseTypeWindow.showPopupWindow(view); } } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { this.finish(); overridePendingTransition(R.anim.bottom_in, R.anim.top_out); return true; } return super.onKeyDown(keyCode, event); } private void initTabLayout() { if (mVpAdapter == null) { //Add Fragment mFragmentList = new ArrayList<>(); mAllOrderFragment = new AllOrderFragment(); mBookFragment = new BookFragment(); mHistoryOrderFragment = new CompleteOrderFragment(); mFragmentList.add(mAllOrderFragment); mFragmentList.add(mBookFragment); mFragmentList.add(mHistoryOrderFragment); //Add Tab Title List<String> titleList = new ArrayList<>(); titleList.add(getString(R.string.all)); titleList.add(getString(R.string.to_be_complete)); titleList.add(getString(R.string.completed)); mVpAdapter = new OrderViewPagerAdapter(getSupportFragmentManager(), mFragmentList, titleList); mViewPager.setOffscreenPageLimit(2); mViewPager.setAdapter(mVpAdapter); mTabLayout.setupWithViewPager(mViewPager); mTabLayout.setTabMode(TabLayout.GRAVITY_FILL); } } @Override public void currentFragmentBack(Fragment fragment) { mCurrentFragmentList.add(fragment); } @Override protected void onDestroy() { super.onDestroy(); if (mCurrentFragmentList != null) { mCurrentFragmentList.clear(); mCurrentFragmentList = null; } if (mFragmentList != null) { mFragmentList.clear(); mFragmentList = null; } if (mChooseTypeWindow!=null){ mChooseTypeWindow.removeListener(); mChooseTypeWindow = null; } mAllOrderFragment = null; mBookFragment = null; mHistoryOrderFragment = null; } /** * 帅选类型的回调 * @param type 结果 */ @Override public void onChooseType(int type) { switch (type) { //占卜 case ChooseOrderTypeWindow.TYPE_DIVINE: mTdChooseType.setText(getString(R.string.divine)); mAllOrderFragment.resetDataType(AllOrderFragment.TYPE_DIVINE); mBookFragment.resetDataType(AllOrderFragment.TYPE_DIVINE); mHistoryOrderFragment.resetDataType(AllOrderFragment.TYPE_DIVINE); break; //商品 case ChooseOrderTypeWindow.TYPE_PRODUCT: mTdChooseType.setText(getString(R.string.string_shop)); mAllOrderFragment.resetDataType(AllOrderFragment.TYPE_PRODUCT); mBookFragment.resetDataType(AllOrderFragment.TYPE_PRODUCT); mHistoryOrderFragment.resetDataType(AllOrderFragment.TYPE_PRODUCT); break; default: break; } } }
package myproject.game.config; import javax.servlet.http.HttpSession; public abstract class BaseController { public void handleSession(HttpSession session) { if (session.isNew()) { session.setAttribute("Param", "Value"); } else { session.getAttribute("Param"); } } }
/* * 文 件 名: UploadUrlResponse.java * 描 述: UploadUrlResponse.java * 时 间: 2013-6-21 */ package com.babyshow.rest.uploadurl; import com.babyshow.rest.RestResponse; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * <一句话功能简述> * * @author ztc * @version [BABYSHOW V1R1C1, 2013-6-21] */ public class UploadUrlResponse extends RestResponse { /** * 七牛上次路径 */ @JsonProperty("qiniu_key") @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) private String qiniuKey; /** * 获取 qiniuKey * * @return 返回 qiniuKey */ public String getQiniuKey() { return qiniuKey; } /** * 设置 qiniuKey * * @param 对qiniuKey进行赋值 */ public void setQiniuKey(String qiniuKey) { this.qiniuKey = qiniuKey; } }
package com.takshine.core.service; import com.takshine.wxcrm.base.util.WxHttpConUtil; import com.takshine.wxcrm.service.ScheduledScansService; import com.takshine.wxcrm.service.WxAddressInfoService; import com.takshine.wxcrm.service.WxCoreService; import com.takshine.wxcrm.service.WxPushMsgService; import com.takshine.wxcrm.service.WxReplyService; import com.takshine.wxcrm.service.WxRespMsgService; import com.takshine.wxcrm.service.WxSubscribeHisService; import com.takshine.wxcrm.service.WxTodayInHistoryService; import com.takshine.wxcrm.service.WxUserLocationService; import com.takshine.wxcrm.service.WxUserinfoService; import com.takshine.wxcrm.service.ZJWKSystemTaskService; /** * 系统中微信通用接口 * @author dengbo * */ public interface WxService{ public WxAddressInfoService getWxAddressInfoService(); public WxCoreService getWxCoreService(); public WxReplyService getWxReplyService(); public WxRespMsgService getWxRespMsgService(); public WxSubscribeHisService getWxSubscribeHisService(); public WxTodayInHistoryService getWxTodayInHistoryService(); public WxUserinfoService getWxUserinfoService(); public WxUserLocationService getWxUserLocationService(); public ZJWKSystemTaskService getZjwkSystemTaskService(); public WxHttpConUtil getWxHttpConUtil(); public WxPushMsgService getWxPushMsgService(); public ScheduledScansService getScheduledScansService(); }
package com.hxsb.model.BUY_ERP_GET_REFUND_RECORD; public class SMSTemplate { private String Mobile; private Double Amount; public String getMobile() { return Mobile; } public void setMobile(String mobile) { Mobile = mobile; } public Double getAmount() { return Amount; } public void setAmount(Double amount) { Amount = amount; } @Override public String toString() { return "SMSTemplate [Mobile=" + Mobile + ", Amount=" + Amount + "]"; } }
package my_package; import java.util.ArrayList; import java.util.Objects; public class Directory extends ArrayList<File> { private String path; private String name; public Directory(String path, String name) { this.path = path; this.name = name; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Directory files = (Directory) o; return Objects.equals(path, files.path) && Objects.equals(name, files.name); } @Override public int hashCode() { return Objects.hash(super.hashCode(), path, name); } @Override public String toString() { StringBuffer buffer = new StringBuffer("Directory:\"" + path + '\\' + name + '\"'); for (File file : this) { buffer.append(this); } return new String(buffer); } public void printAll() { System.out.println("Directory:\"" + path + '\\' + name + '\"'); for (File file : this) { file.printOnConsole(); } } }
package rhtn_homework; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public class BOJ_11657_타임머신 { private static int N,M; private static List<Edge>[] adList; // 너무너무 중요한 long형 int의 max값에서 플러스가 되면 값이 변하기 때문 private static long[] dist; private static StringBuilder sb = new StringBuilder(); public static void main(String[] args) throws IOException{ // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); adList = new ArrayList[N+1]; dist = new long[N+1]; Arrays.fill(dist, Integer.MAX_VALUE); for (int i = 1; i <= N; i++) { adList[i] = new ArrayList<>(); } for (int i = 0; i < M; i++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int c = Integer.parseInt(st.nextToken()); adList[a].add(new Edge(b,c)); } // 벨만-포드를 실행하고 음수순환이 없다면 if(BF(1)) { for (int i = 2; i <= N; i++) { if(dist[i]!= Integer.MAX_VALUE) sb.append(dist[i] +"\n"); else { sb.append(-1 + "\n"); } } }else { sb.append(-1); } System.out.println(sb); } private static boolean BF(int i) { dist[i] = 0; // N번 반복한다(N-1 이면 충분하지만 음수 순환있는지 확인을 위해 한번더) for (int j = 1; j <= N; j++) { // 매번 "모든 간선"을 확인한다 for (int s = 1; s <= N; s++) { for (Edge ed : adList[s]) { int e = ed.x; int v = ed.v; // 현재 간선을 거쳐서 다른 노드를 가는게 더 짧다면 교체 if(dist[s]!=Integer.MAX_VALUE && dist[e] > dist[s] + v) { dist[e] = dist[s] + v; // 다만 맨 마지막임에도 불구하고 교체가된다면, 음수 순환이 잇다는것! if(j == N) return false; } } } } return true; } public static class Edge{ int x, v; public Edge(int x, int v) { super(); this.x = x; this.v = v; } } }
/* * 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 shifu.model.dao.elementaire; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import shifu.model.dao.CustomArgument; import shifu.model.dao.DAO; import shifu.model.dao.tables.TableStatutIndividu; /** * * @author antoine */ public class StatutIndividuDAO extends DAO<TableStatutIndividu>{ @Override public TableStatutIndividu create(TableStatutIndividu object) { try { preparedStatement = this.connection .prepareStatement( "INSERT INTO Statut_individu (ID_individu, ID_statut) VALUES (?, ?);" ); preparedStatement.setInt(1, object.getIdIndividu()); preparedStatement.setInt(2, object.getIdStatut()); preparedStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(StatutIndividuDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { preparedStatement.close(); } catch (SQLException ex) { Logger.getLogger(StatutIndividuDAO.class.getName()).log(Level.SEVERE, null, ex); } } return object; } @Override public TableStatutIndividu getByID(int ID) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public TableStatutIndividu update(TableStatutIndividu object) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public List<TableStatutIndividu> getByEqualsCustomArgument(CustomArgument argument) { List<TableStatutIndividu> listTableStatuIndividu = new ArrayList(); try { preparedStatement = connection.prepareStatement( "SELECT * FROM Statut_individu WHERE ? = ?" ); listTableStatuIndividu = executeCustomSearch( preparedStatement, argument ); } catch (SQLException ex) { Logger.getLogger(StatutIndividuDAO.class.getName()).log(Level.SEVERE, null, ex); } return listTableStatuIndividu; } @Override public List<TableStatutIndividu> getByLikeCustomArgument(CustomArgument argument) { throw new UnsupportedOperationException( "On ne peut faire de recherche à base de String ici." ); } @Override protected List<TableStatutIndividu> executeCustomSearch(PreparedStatement statement, CustomArgument argument) throws SQLException { List<TableStatutIndividu> listTableStatuIndividu = new ArrayList(); try { preparedStatement.setString( 1, argument.getFieldName() ); Object value = argument.getValue(); if ( value instanceof String ) { preparedStatement.setString( 2, ( String ) value ); } else if ( value instanceof Integer ) { preparedStatement.setInt( 2, ( int ) value ); } resultSet = preparedStatement.executeQuery(); while ( resultSet.next() ) { listTableStatuIndividu.add( new TableStatutIndividu( resultSet.getInt( "ID_individu" ), resultSet.getInt( "ID_statut" ) ) ); } } catch (Exception e) { e.printStackTrace(); }finally { resultSet.close(); preparedStatement.close(); } return listTableStatuIndividu; } @Override public List<TableStatutIndividu> findAll() { throw new UnsupportedOperationException( "Not supported yet." ); //To change body of generated methods, choose Tools | Templates. } @Override public void delete( TableStatutIndividu object ) { throw new UnsupportedOperationException( "Not supported yet." ); //To change body of generated methods, choose Tools | Templates. } }
/* * 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 nilaipas; import java.util.Scanner; /** * * @author MOKLET-2 */ public class Bag2 { String Nama,Nik,Kelas,sklh; int N; Scanner I = new Scanner(System.in); void buka(){//method pembukaaan System.out.println("Silakan konversi nilai mapel anda"); System.out.println("================================="); } void input(){//method void yang isinya syntax inputan user System.out.print("Masukkan Nama\t\t: "); Nama = I.nextLine(); System.out.print("Masukkan Nis\t\t: "); Nik = I.nextLine(); System.out.print("Masukkan Kelas\t\t: "); Kelas = I.nextLine(); System.out.print("Masukkan sekolah\t: "); sklh = I.nextLine(); } void pilah(){//method untuk input nilai serta percabagan kelas nilai System.out.print("Masukkan Nilai Mapel\t: "); // N = I.nextInt(); //inputan nilai oleh user System.out.print("Nilai mapel anda\t: "); if (N >= 90)//percabangan yang digunakan untuk menentukan kelas nilai System.out.println("A\nSemangat!!\nPertahankan nilai anda"); else if (N >= 75) System.out.println("B\nSemangat!!\nTingkatkan nilainyaa"); else if (N >= 50) System.out.println("C\nSemangat!!\nBelajar lagi yaa"); else if (N >= 35) System.out.println("D\nSemangat!!\nBelajarnya ditingkatkan yaa"); else System.out.println("E\nBelajarnya ditingkatkan yaa\nHati-hati dengan nilai mu"); } }
package com.noteshare.note.notetype.services.impl; import java.util.HashMap; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.noteshare.common.model.Page; import com.noteshare.common.utils.page.PageConstants; import com.noteshare.common.utils.page.PageUtil; import com.noteshare.note.notetype.dao.NoteTypeMapper; import com.noteshare.note.notetype.model.NoteType; import com.noteshare.note.notetype.services.NoteTypeService; @Service public class NoteTypeServiceImpl implements NoteTypeService { @Resource private NoteTypeMapper noteTypeMapper; @SuppressWarnings("boxing") @Override public Page<NoteType> selectNoteTypeListByPage(int currentPage, int startPageNumber, int endPageNumber, int size) { Page<NoteType> page = new Page<NoteType>(); //查询总数 HashMap<String,Object> totalCondition = new HashMap<String,Object>(); int total = noteTypeMapper.selectNoteTypeListTotal(totalCondition); //基础查询参数 HashMap<String,Object> paramMap = PageUtil.getBaseParamMap(page,total,currentPage,size); List<NoteType> list = noteTypeMapper.selectNoteTypeListByPage(paramMap); page.setList(list); PageUtil.setPage(page,currentPage, startPageNumber, endPageNumber,PageConstants.PAGEFLAGNUMBER,PageConstants.MAXPAGENUMBER); return page; } @Override public void insertSelective(NoteType noteType) { noteTypeMapper.insertSelective(noteType); } @Override public List<NoteType> selectNoteTypeByTypename(String typename) { return noteTypeMapper.selectNoteTypeByTypename(typename); } }
package com.irfandev.project.simplemarket.helpers; /** * created by Irfan Assidiq * email : assidiq.irfan@gmail.com **/ public class Const { public static String BASEURL ="http://simplesample.ngopidevteam.com/"; }
package com.example.quanlichitieu1; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.example.quanlichitieu1.data.DBManager; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import com.github.mikephil.charting.data.PieEntry; import com.github.mikephil.charting.utils.ColorTemplate; import java.util.ArrayList; import java.util.List; public class BieuDoActivity extends AppCompatActivity { Button btnBack; public float rainfall[]={50f,20f,30f}; String chiteu[]={"Đồ ăn","Thể thao","Giải trí"}; public final DBManager dbManager = new DBManager(this); float AnUong,TheThao,GiaiTri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bieu_do); GUI(); getData(); setupPieChart(); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent1 = new Intent(BieuDoActivity.this,OptionActivity.class); startActivity(intent1); overridePendingTransition(R.anim.anim_enter_to_up,R.anim.anim_exit_to_up); } }); } private void setupPieChart() { List<PieEntry> pieEntries=new ArrayList<>(); for (int i=0;i<rainfall.length;i++){ pieEntries.add(new PieEntry(rainfall[i],chiteu[i])); } PieDataSet dataSet=new PieDataSet(pieEntries,"Biểu đồ chi tiêu"); dataSet.setColors(ColorTemplate.COLORFUL_COLORS); PieData data=new PieData(dataSet); PieChart chart=(PieChart) findViewById(R.id.chart); chart.setData(data); chart.animateY(1000); chart.invalidate(); } public void GUI(){ btnBack = findViewById(R.id.btn_back); } public void getData(){ AnUong = dbManager.getAnUong(); TheThao = dbManager.getTheThao(); GiaiTri = dbManager.getGiaiTri(); rainfall[0]=AnUong; rainfall[1]=TheThao; rainfall[2]=GiaiTri; } }
package logic; import java.util.Stack; import java.util.HashSet; import enums.FieldType; import enums.PlayerIndex; public class HexLogicUnionFind { public int boardLength, n; public PlayerIndex currentPlayer, winner; private FieldType[][] board; private HexUnionFind uf; private int[] lastMove; public static int[][] fieldRelations = { {1, -1}, {1, 0}, {0, 1}, {0, -1}, {-1, 1}, {-1, 0} }; public HexLogicUnionFind (int n) { this.boardLength = this.n = n; this.currentPlayer = PlayerIndex.PLAYER0; this.uf = new HexUnionFind(n); this.board = new FieldType[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) this.board[i][j] = FieldType.EMPTY; } private FieldType fieldAt (int i, int j) { if (i >= 0 && i < this.boardLength && j >= 0 && j < this.boardLength ) return this.board[i][j]; else return FieldType.INVALID; } private void joinComponentsAround(FieldType t, int i, int j) { for (int[] dij : HexLogicUnionFind.fieldRelations) { int di = i + dij[0]; int dj = j + dij[1]; if (this.fieldAt(di, dj).equals(t)) this.uf.joinComponents(i, j, di, dj); } } private void setFieldType0 (int i, int j) { this.board[i][j] = FieldType.TYPE0; if (i == 0) this.uf.joinComponents(i, j, -1, 0); if (i == n - 1) this.uf.joinComponents(i, j, n, 0); this.joinComponentsAround(FieldType.TYPE0, i, j); } private void setFieldType1 (int i, int j) { this.board[i][j] = FieldType.TYPE1; if (j == 0) this.uf.joinComponents(i, j, 0, -1); if (j == n - 1) this.uf.joinComponents(i, j, 0, n); this.joinComponentsAround(FieldType.TYPE1, i, j); } public boolean fieldEmpty (int i, int j) { return this.fieldAt(i, j).equals(FieldType.EMPTY); } public boolean moveValid (PlayerIndex player, int i, int j) { return ( this.fieldAt(i, j).equals(FieldType.EMPTY) && this.currentPlayer.equals(player) ); } public void makeMove(PlayerIndex player, int i, int j) { switch (player) { case PLAYER0: this.setFieldType0(i, j); this.currentPlayer = PlayerIndex.PLAYER1; break; case PLAYER1: this.setFieldType1(i, j); this.currentPlayer = PlayerIndex.PLAYER0; break; } lastMove = new int[] {i, j}; } public boolean hasWon (PlayerIndex player) { switch (player) { case PLAYER0: if (this.uf.inSameComponent(-1,0,n,0)) { this.winner = player; return true; } case PLAYER1: if (this.uf.inSameComponent(0,-1,0,n)) { this.winner = player; return true; } } return false; } public HashSet<int[]> winningPath () { FieldType type = null; switch (this.winner) { case PLAYER0: type = FieldType.TYPE0; break; case PLAYER1: type = FieldType.TYPE1; break; } return pathDfs(type, lastMove); } private HashSet<int[]> pathDfs ( FieldType t, int[] source ) { boolean[][] marked = new boolean[n][n]; for (int k = 0; k < n; k++) for (int l = 0; l < n; l++) marked[k][l] = false; HashSet<int[]> path = new HashSet<int[]> (); Stack<int[]> stack = new Stack<int[]> (); stack.add(source); while (!stack.empty()) { source = stack.pop(); path.add(source); int i = source[0]; int j = source[1]; if (!marked[i][j]) { marked[i][j] = true; for (int[] dij : HexLogicUnionFind.fieldRelations) { int ti = i + dij[0]; int tj = j + dij[1]; if (ti >= 0 && ti < n && tj >= 0 && tj < n) { if (!marked[ti][tj] && this.board[ti][tj].equals(t)) stack.push(new int[] {ti, tj}); } } } } return path; } public void repr () { for (int i = 0; i < this.boardLength; i++) { for (int j = 0; j < this.boardLength; j++) System.out.print(this.board[i][j].name()); System.out.println(); } } }
package Exercicio02; public interface ContratoAgenda { String getNome(); }
package pulau.com.pulauterunik; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.*; public class Utama extends AppCompatActivity implements View.OnClickListener { Button keluar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_utama); Button daftar = (Button) findViewById(R.id.Button11); daftar.setOnClickListener(new View.OnClickListener() { public void onClick(View bebek) { Intent myIntent = new Intent(bebek.getContext(), DaftarPulau.class); startActivityForResult(myIntent, 0); } }); Button file = (Button) findViewById(R.id.Button12); file.setOnClickListener(new View.OnClickListener() { public void onClick(View bebek) { Intent myIntent = new Intent(bebek.getContext(), Profile.class); startActivityForResult(myIntent, 0); } }); Button view = (Button) findViewById(R.id.Button14); view.setOnClickListener(new View.OnClickListener() { public void onClick(View bebek) { Intent myIntent = new Intent(bebek.getContext(), webb.class); startActivityForResult(myIntent, 0); } }); keluar = (Button) findViewById(R.id.Button13); keluar.setOnClickListener(this); } public void onClick(View clicked) { switch (clicked.getId()) { case R.id.Button13: exit(); break; } } private void exit() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Apakah kamu Benar-Benar ingin keluar?") .setCancelable(false) .setPositiveButton("Ya", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id){ Utama.this.finish(); } }) .setNegativeButton("Tidak", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int arg1) { //Todo Auto-generate method stub dialog.cencel() dialog.cancel(); } }).show(); } }
package com.tencent.mm.plugin.appbrand.widget.input; class x$1 implements Runnable { final /* synthetic */ x gIT; x$1(x xVar) { this.gIT = xVar; } public final void run() { if (this.gIT.gIR != null) { this.gIT.gIR.agA(); } } }
package com.tencent.mm.plugin.appbrand.jsapi.auth; import com.tencent.mm.plugin.appbrand.jsapi.auth.JsApiLogin.LoginTask; import com.tencent.mm.plugin.appbrand.jsapi.auth.JsApiLogin.LoginTask.a; import com.tencent.mm.protocal.c.bio; import com.tencent.mm.sdk.platformtools.x; import java.util.LinkedList; class JsApiLogin$LoginTask$1 implements a { final /* synthetic */ LoginTask fJD; JsApiLogin$LoginTask$1(LoginTask loginTask) { this.fJD = loginTask; } public final void qe(String str) { x.i("MicroMsg.JsApiLogin", "onSuccess !"); this.fJD.code = str; this.fJD.fJw = "ok"; LoginTask.a(this.fJD); } public final void aid() { x.i("MicroMsg.JsApiLogin", "onFailure !"); this.fJD.fJw = "fail"; LoginTask.b(this.fJD); } public final void a(LinkedList<bio> linkedList, String str, String str2, String str3) { x.i("MicroMsg.JsApiLogin", "onConfirm !"); this.fJD.fJy = linkedList.size(); int i = 0; while (i < this.fJD.fJy) { try { this.fJD.fJz.putByteArray(String.valueOf(i), ((bio) linkedList.get(i)).toByteArray()); i++; } catch (Throwable e) { x.e("MicroMsg.JsApiLogin", "IOException %s", new Object[]{e.getMessage()}); x.printErrStackTrace("MicroMsg.JsApiLogin", e, "", new Object[0]); this.fJD.fJw = "fail"; LoginTask.c(this.fJD); return; } } this.fJD.fHN = str3; this.fJD.mAppName = str; this.fJD.fyq = str2; this.fJD.fJw = "needConfirm"; LoginTask.d(this.fJD); } }
package jpa.project.response; import lombok.Getter; import lombok.Setter; import java.util.List; @Getter @Setter public class ListResult<T> extends CommonResult { private List<T> list; }
package identity.equality; public class Main { public static void main(String[] args) { ClassA a1 = new ClassA(5); ClassA a2 = new ClassA(5); ClassA a3 = a2; System.out.println(a1 == a2); System.out.println(a3 == a2); //System.out.println(a1.equals(a2)); //System.out.println(a3.equals(a2)); } }
/* * Created on 04.08.2005 by cse * * Copyright 2009, ByteRefinery * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * $Id: TableSorter.java 666 2007-10-01 19:32:51Z cse $ */ package com.byterefinery.rmbench.views; import java.util.Comparator; import java.util.List; import org.eclipse.jface.viewers.ITableLabelProvider; /** * helper class which sorts the table entries according to the selected column and * sort direction * * @author cse */ @SuppressWarnings("rawtypes") public class TableSorter implements Comparator { private int sortColumn; private boolean ascending; private ITableLabelProvider labelProvider; private List<?> entries; public TableSorter(ITableLabelProvider labelProvider) { this.labelProvider = labelProvider; } public int getSortColumn() { return sortColumn; } @SuppressWarnings("unchecked") public void reverseOrder() { ascending = !ascending; if(entries != null) java.util.Collections.sort(entries, this); } public Object getEntries() { return entries; } public void setEntries(List entries) { this.entries = entries; } @SuppressWarnings("unchecked") public void setSortColumn(int column) { sortColumn = column; if(entries != null) java.util.Collections.sort(entries, this); } @SuppressWarnings("unchecked") public void resort() { if(entries != null) java.util.Collections.sort(entries, this); } public int compare(Object o1, Object o2) { String t1 = labelProvider.getColumnText(o1, sortColumn); String t2 = labelProvider.getColumnText(o2, sortColumn); return ascending ? t1.compareTo(t2) : t2.compareTo(t1); } }
/** * Discord Objects * <p> * {@link org.alienideology.jcord.handle.IDiscordObject} are any objects that are under a {@link org.alienideology.jcord.Identity}. * This package is full of Discord Objects and their builders. * </p> * @since 0.0.1 * @author AlienIdeology */ package org.alienideology.jcord.handle;
package com.acme.test; import com.ibm.streams.operator.metrics.Metric.Kind; import com.ibm.streams.operator.model.InputPortSet.WindowMode; import com.ibm.streams.operator.model.InputPortSet.WindowPunctuationInputMode; import com.ibm.streams.operator.model.OutputPortSet.WindowPunctuationOutputMode; @com.ibm.streams.operator.model.PrimitiveOperator(name="MyJavaOp", namespace="com.acme.test", description="Java Operator MyJavaOp") @com.ibm.streams.operator.model.InputPorts(value={@com.ibm.streams.operator.model.InputPortSet(description="Port that ingests tuples", cardinality=1, optional=false, windowingMode=WindowMode.NonWindowed, windowPunctuationInputMode=WindowPunctuationInputMode.Oblivious), @com.ibm.streams.operator.model.InputPortSet(description="Optional input ports", optional=true, windowingMode=WindowMode.NonWindowed, windowPunctuationInputMode=WindowPunctuationInputMode.Oblivious)}) @com.ibm.streams.operator.model.OutputPorts(value={@com.ibm.streams.operator.model.OutputPortSet(description="Port that produces tuples", cardinality=1, optional=false, windowPunctuationOutputMode=WindowPunctuationOutputMode.Generating), @com.ibm.streams.operator.model.OutputPortSet(description="Optional output ports", optional=true, windowPunctuationOutputMode=WindowPunctuationOutputMode.Generating)}) @com.ibm.streams.operator.internal.model.ShadowClass("com.acme.test.MyJavaOp") @javax.annotation.Generated("com.ibm.streams.operator.internal.model.processors.ShadowClassGenerator") public class MyJavaOp$StreamsModel extends com.ibm.streams.operator.AbstractOperator { @com.ibm.streams.operator.model.Parameter(name="floatVal", optional=true) public void setFloatVal(float f) {} @com.ibm.streams.operator.model.Parameter(name="intVal", optional=false) public void setIntVal(int i) {} }