text
stringlengths 10
2.72M
|
|---|
package com.laoji.business.controller;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.laoji.business.BusinessException;
import com.laoji.business.BusinessStatus;
import com.laoji.commons.dto.ResponseResult;
import com.laoji.provider.api.UmsAdminService;
import com.laoji.provider.api.UmsRoleService;
import com.laoji.provider.domain.UmsAdmin;
import com.laoji.provider.domain.UmsRole;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 系统用户controller
* @author: laoji
* @date:2020/4/14 14:23
*/
@RestController
@RequestMapping(value="/system/user")
public class SystemUserController {
@Reference(version = "1.0.0")
public UmsAdminService umsAdminService;
@Reference
public UmsRoleService umsRoleService;
@GetMapping(value = "/getAll")
public ResponseResult<PageInfo> getAll(Integer pageSize, Integer pageNum){
PageInfo<UmsAdmin> pageInfo = umsAdminService.getAll(pageSize,pageNum);
if(pageInfo==null){
throw new BusinessException(BusinessStatus.DATA_NOT_FOUNT);
}
return new ResponseResult<PageInfo>(ResponseResult.OK,"查询成功",pageInfo);
}
@GetMapping(value="/getRoleList")
public ResponseResult<List<UmsRole>> getRoleList(){
List<UmsRole> roleList = umsRoleService.getAll();
return new ResponseResult<List<UmsRole>>(ResponseResult.OK,"查询成功",roleList);
}
@GetMapping(value="/getRoleByAdminId")
public ResponseResult<List<Integer>> getRoleByAdminId(Integer id){
if(id==null){
throw new BusinessException(BusinessStatus.ILLEGAL_REQUEST);
}
List<Integer> roleLists = umsAdminService.getRoleByAdminId(id);
List<Integer> emptyList= Lists.newArrayList();
if(roleLists.get(0)==null){
return new ResponseResult<List<Integer>>(ResponseResult.OK,"查询成功",emptyList);
}
return new ResponseResult<List<Integer>>(ResponseResult.OK,"查询成功",roleLists);
}
@PostMapping(value = "/updateRole")
@PreAuthorize("hasAuthority('ums:admin:update')")
public ResponseResult<Void> updateRole(@RequestBody List<Integer> newList,Integer id){
System.out.println(newList);
System.out.println(id);
boolean b = umsAdminService.updateRole(newList, id);
if(b){
return new ResponseResult<Void>(ResponseResult.OK,"修改成功");
}else{
return new ResponseResult<Void>(ResponseResult.FAIL,"修改失败");
}
}
@PostMapping(value="/addAdmin")
@PreAuthorize("hasAuthority('ums:admin:create')")
public ResponseResult<Void> addAdmin(@RequestBody UmsAdmin umsAdmin){
String message=validateReg(umsAdmin);
if(message==null){
//验证通过
int result = umsAdminService.insert(umsAdmin);
if(result>0){
//注册成功
return new ResponseResult<Void>(ResponseResult.OK,"添加成功!");
}
}
return new ResponseResult<Void>(ResponseResult.FAIL,message != null ? message : "添加新用户失败");
}
/**
* 验证注册信息
* @param umsAdmin {@link UmsAdmin}
* @return 错误信息
*/
private String validateReg(UmsAdmin umsAdmin) {
if(umsAdmin.getUsername()==null||umsAdmin.getUsername().length()<6){
return "用户名格式有误或者为空,用户名不能低于六位字符";
}
if(umsAdmin.getPassword()==null||umsAdmin.getPassword().length()<6){
return "密码格式有误或者为空,密码不能低于六位字符";
}
UmsAdmin admin = umsAdminService.get(umsAdmin.getUsername());
if (admin != null) {
return "用户名已存在,请重新输入";
}
return null;
}
}
|
package com.example.starsonicerr;
public class User {
private String userid;
private String username;
public User(String userid, String username, String userdate, String userday, String usercategory) {
this.userid = userid;
this.username = username;
this.userdate = userdate;
this.userday = userday;
this.usercategory = usercategory;
}
private String userdate;
private String userday;
private String usercategory;
public User() {
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserdate() {
return userdate;
}
public void setUserdate(String userdate) {
this.userdate = userdate;
}
public String getUserday() { return userday;}
public String getUsercategory() { return usercategory; }
public void setUsercategory(String usercategory) {
this.usercategory = usercategory;
}
}
|
package com.tencent.mm.plugin.sns.model;
import com.tencent.mm.bt.h.d;
import com.tencent.mm.plugin.sns.storage.o;
class af$37 implements d {
af$37() {
}
public final String[] xb() {
return o.diD;
}
}
|
package com.herokuapp.apimotooto.service;
import com.herokuapp.apimotooto.dto.SaleAnnouncementDto;
import com.herokuapp.apimotooto.exception.AnnouncementAlreadyExistsException;
import com.herokuapp.apimotooto.exception.AnnouncementLimitException;
import com.herokuapp.apimotooto.exception.UserNotExistsException;
import com.herokuapp.apimotooto.exception.UserNotPermittedException;
import com.herokuapp.apimotooto.model.Car;
import com.herokuapp.apimotooto.model.SaleAnnouncement;
import com.herokuapp.apimotooto.model.User;
import com.herokuapp.apimotooto.repository.SaleAnnouncementRepository;
import com.herokuapp.apimotooto.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
@Service
@Slf4j
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final SaleAnnouncementRepository saleAnnouncementRepository;
private static final int ANNOUNCEMENT_LIMIT = 3;
public List<SaleAnnouncement> getUsersAllSaleAnnouncements(Long userId) {
if (!userRepository.existsById(userId)) {
throw new UserNotExistsException(userId);
}
log.info("Getting all sale announcements for user with id " + userId);
return saleAnnouncementRepository.findSaleAnnouncementByOwner_Id(userId);
}
@Transactional
public void addSaleAnnouncement(Long userId, User user, SaleAnnouncementDto saleAnnouncementDto) {
if (!userId.equals(user.getId())) {
throw new UserNotPermittedException("You can only add announcements to your account!");
}
if(saleAnnouncementRepository.countSaleAnnouncementsByOwner_Id(userId) >= ANNOUNCEMENT_LIMIT) {
throw new AnnouncementLimitException();
}
SaleAnnouncement saleAnnouncement = new SaleAnnouncement(saleAnnouncementDto, user);
Car newCar = saleAnnouncementDto.getCar();
if (saleAnnouncementRepository
.existsByCar_BrandAndCar_ModelAndOwner_Id(newCar.getBrand(), newCar.getModel(), userId)) {
throw new AnnouncementAlreadyExistsException();
}
saleAnnouncementRepository.save(saleAnnouncement);
log.info("Sale announcement added: " + saleAnnouncement);
}
}
|
/**
*
*/
/**
* @author jinweizhang
*
*/
public class Regex {
/**
* @param args
* https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String any = ".*";
String test1 = "Hello", test2 = "29", test3 = "";
System.out.println(test1.matches(any));
System.out.println(test2.matches(any));
System.out.println(test3.matches(any));
}
}
|
/* HTML VALIDATOR USING REGEX */
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class HtmlRegex {
private static Pattern pattern;
private static Matcher matcher;
//private static final String HtmlPattern = "<(\"[^\"]*\"|'[^']*'|[^'\">])*>";
private static final String HtmlPattern = "<.*?>([^<]+)</.*?>";
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int testCases = scanner.nextInt();
scanner.nextLine();
while(testCases-->0) {
String input = scanner.nextLine();
boolean valid = validate(input);
if(valid==true)
System.out.println("Valid tag");
else
System.out.println("Invalid tag");
}
}
public static boolean validate(String input) {
pattern = Pattern.compile(HtmlPattern);
matcher = pattern.matcher(input);
return matcher.matches();
}
}
|
package com.e6soft.form.service.impl;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.e6soft.core.common.Constants;
import com.e6soft.core.mybatis.EntityDao;
import com.e6soft.core.util.ConstantsUtil;
import com.e6soft.form.FormService;
import com.e6soft.form.dao.MetadataDao;
import com.e6soft.form.dao.MetadataValueDao;
import com.e6soft.form.model.Metadata;
import com.e6soft.form.model.MetadataValue;
import com.e6soft.form.service.MetadataValueService;
@Transactional
@Service("metadataValueService")
public class MetadataValueServiceImpl extends FormService<MetadataValue, String> implements MetadataValueService{
@Autowired
private MetadataValueDao metadataValueDao;
@Autowired
private MetadataDao metadataDao;
public EntityDao<MetadataValue, String> getEntityDao() {
return metadataValueDao;
}
@Override
public List<MetadataValue> getAllMetadataValueByMetadataId(String metadataId) {
return metadataValueDao.getListByMetadataId(metadataId);
}
@Override
public int getMaxValueByMetadataId(String metadataId) {
return metadataValueDao.getMaxValueByMetadataId(metadataId);
}
@Override
public String validMetadataValue(MetadataValue metadataValue) {
String msg = "";
if(metadataValue==null){
msg = "字典值不存在";
}else{
if(StringUtils.isNotEmpty(metadataValue.getId())){
MetadataValue mValue = metadataValueDao.getById(metadataValue.getId());
if(!metadataValue.getLabelName().equals(mValue.getLabelName()) && metadataValueDao.hasExistLabel(metadataValue)){
msg = "该字典值名称已存在!";
}
}else{
if(StringUtils.isNotEmpty(metadataValue.getLabelName()) && StringUtils.isNotEmpty(metadataValue.getMetadataId())){
if(metadataValueDao.hasExistLabel(metadataValue)){
msg = "该字典值名称已存在!";
}
}
}
}
return msg;
}
@Override
public void save(MetadataValue t) {
super.save(t);
Metadata metadata = this.metadataDao.getById(t.getMetadataId());
Constants constants = new Constants();
constants.setCode(t.getValueCode());
constants.setExt("");
constants.setGroup(metadata.getMetadataCode());
constants.setLabel(metadata.getMetadataName());
constants.setValue(t.getValue());
ConstantsUtil.addConstants(metadata.getMetadataCode(), t.getValue(), constants);
}
@Override
public void deleteById(String id) {
MetadataValue t = this.getById(id);
Metadata metadata = this.metadataDao.getById(t.getMetadataId());
super.deleteById(id);
ConstantsUtil.deleteConstants(metadata.getMetadataCode(), t.getValue());
}
}
|
/*
* 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 fbmain;
/**
*
* @author jorgeaceves
*/
public class Graph {
public static int MAX_VERTICES = 6;
private GraphNode vertices[];
public int count;
public Graph() {
vertices = new GraphNode[MAX_VERTICES];
count = 0;
}
public void addNode(GraphNode x) {
if (count < vertices.length) {
vertices[count] = x;
count++;
} else {
System.out.print("Graph full");
}
}
public GraphNode[] getNodes() {
return vertices;
}
}
|
package com.zzjmay.netty.lesson1;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
/**
*
* Created by zzjmay on 2019/3/3.
*/
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
if (httpObject instanceof HttpRequest) {
System.out.println("测试代码....");
ByteBuf content = Unpooled.copiedBuffer("Hello World zzjmay", CharsetUtil.UTF_8);
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
//返回给客户端
channelHandlerContext.writeAndFlush(response);
}
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel register");
super.channelRegistered(ctx);
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel unregister");
super.channelUnregistered(ctx);
}
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel active");
super.channelActive(ctx);
}
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel inactive");
super.channelInactive(ctx);
}
}
|
package com.dm.hibernate.entities.n21.both;
import static org.junit.Assert.*;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class HibernateTest {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Before
public void init(){
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry =
new ServiceRegistryBuilder().applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
transaction = session.beginTransaction();
}
@After
public void destory(){
transaction.commit();
session.close();
sessionFactory.close();
}
@Test
public void testCascade(){
Customer customer = (Customer) session.get(Customer.class, 3);
customer.getOrders().clear();
}
@Test
public void testDelete(){
Customer customer = (Customer) session.get(Customer.class, 2);
session.delete(customer);
}
@Test
public void testGet(){
Customer customer = (Customer) session.get(Customer.class, 3);
System.out.println(customer.getOrders());
}
@Test
public void testMany2One(){
Customer customer = new Customer();
customer.setCustomerName("lideming");
Order order1 = new Order();
order1.setOrderName("order-1");
Order order2 = new Order();
order2.setOrderName("order-2");
order1.setCustomer(customer);
order2.setCustomer(customer);
customer.getOrders().add(order1);
customer.getOrders().add(order2);
session.save(customer);
// session.save(order1);
// session.save(order2);
}
}
|
package com.osce.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
/**
* @ClassName: ErpRoom
* @Description: 资源_房间管理
* @Author yangtongbin
* @Date 2019-05-10
*/
@Setter
@Getter
@ToString
public class ErpRoom implements Serializable {
private static final long serialVersionUID = 1557497596098L;
/**
* 主键
* 房间ID
*/
private Long idRoom;
/**
* 机构ID
*/
private Long idOrg;
/**
* 房号
*/
private String naRoom;
/**
* 描述
*/
private String desRoom;
/**
* 布局图
*/
private String picRoom;
/**
* 0 未激活 1 已激活
*/
private String fgActive;
/**
* 0 正常 1 删除
*/
private String fgValid;
/**
* 排序
*/
private Integer sort;
/**
* 创建人员
*/
private String creator;
/**
* 创建时间
*/
private Date gmtCreate;
/**
* 修改人员
*/
private String operator;
/**
* 修改时间
*/
private Date gmtModify;
/**
* 设备数量
*/
private Long deviceNum;
}
|
package com.node.javese.day09.test003;
/**
* 封装步骤
* 1.属性私有化,用private关键字
* 2.提供简单操作入口
*
* 访问属性两种方式
* 1.读取 get
* 2.修改 set
*
* get方法命名规范(读取有返回值)
* public int getAge(){
* return age;
* }
*
* set方法命名规范(修改无返回值)
* public void getAge(int a){
* age = a;
* }
*
*setter and getter方法无static关键字
*有static关键字调用:类名.方法名(实参)
*无static关键字调用:引用.方法名(实参)
*/
class User {
private int age;
public void setAge(int a) {
if(a<0||a>150) {
System.out.println("不合法");
return;
}
age = a;
}
public int getAge() {
return age;
}
}
public class UserTest {
public static void main(String[] args) {
User user = new User();
//System.out.println(user.age);
//修改
user.setAge(-100);
//读取
System.out.println(user.getAge());
}
}
|
package com.saif.ui.demo;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Component;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.components.grid.DetailsGenerator;
import com.vaadin.ui.renderers.TextRenderer;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import saif.com.vaadin.ui.GridPanel.DefaultGridConfiguration;
import saif.com.vaadin.ui.GridPanel.GridPanel;
import saif.com.vaadin.ui.GridPanel.utils.GridPanelItemProvider;
@Theme("demo")
@Title("TablePanel Test..")
@SuppressWarnings("serial")
public class DemoUI extends UI {
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = DemoUI.class)
public static class Servlet extends VaadinServlet {
}
@Override
protected void init(VaadinRequest request) {
setLocale(new Locale("pl", "PL"));
final VerticalLayout layout = new VerticalLayout();
layout.setSizeFull();
layout.setWidth("100%");
List<Bean> list = new ArrayList();
for (int x = 0; x < 20; x++) {
Bean u = new Bean();
u.setFirstName("Fname " + x);
u.setLastName("Fname " + x);
u.setMan(true);
u.setAge(x);
u.setType(Bean.Type.MAN);
u.setPrice(1223);
u.setAllowed(Boolean.FALSE);
list.add(u);
}
GridPanel<Bean> grid = new GridPanel<Bean>(Bean.class, new DefaultGridConfiguration());
//grid.getGrid().getColumn("firstName").setRenderer(new ButtonRenderer().);
grid.addItems(list);
layout.addComponent(grid);
setContent(layout);
setSizeFull();
grid.setItemProvider(new GridPanelItemProvider<Bean>() {
@Override
public List<Bean> supply(int offset, int limit, Map<String, Object> filters, GridPanelItemProvider.Option option) {
if (option.isTotalCountRequire()) {
int num = new Random().nextInt(2999);
System.out.println("Random count : " + num + " Filter : " + filters);
option.setTotalItemCount(num);
}
System.out.println("Updating list......");
return list;
}
});
grid.addColumnCollapsedListener((id, isCollapsed) -> {
System.out.println(String.format("Collapsed Event id %s isCollapsed %s", id, isCollapsed));
});
grid.getGrid().setDetailsGenerator(new DetailsGenerator<Bean>() {
@Override
public Component apply(Bean t) {
grid.getGrid().setDetailsVisible(t, true);
return new Label(t.getFirstName());
}
});
grid.pack();
}
}
|
package org.webmaple.admin.service;
import org.webmaple.common.model.NodeDTO;
import org.webmaple.common.model.Result;
import java.util.List;
/**
* @author lyifee
* on 2021/1/7
*/
public interface NodeManageService {
List<NodeDTO> queryNodeList();
Result<Void> addWorker(String ip, String user, String password, Integer port, String fileName);
void removeWorker(String workerName);
}
|
/*
* 文 件 名: Page.java
* 描 述: Page.java
* 时 间: 2013-8-4
*/
package com.babyshow.util;
/**
* <一句话功能简述>
*
* @author ztc
* @version [BABYSHOW V1R1C1, 2013-8-4]
*/
public class Page
{
/**
* 当前页
*/
private int curPage;
/**
* 当前开始记录数,用作mysql limit查询
*/
private int curRecord;
/**
* 总记录数
*/
private int totalRecord;
/**
* 每页显示的记录数
*/
private int recordPerPage;
/**
* 总页数
*/
private int totalPages;
/**
* 获取 curPage
*
* @return 返回 curPage
*/
public int getCurPage()
{
return curPage;
}
/**
* 设置 curPage
*
* @param 对curPage进行赋值
*/
public void setCurPage(int curPage)
{
this.curPage = curPage;
}
/**
* 获取 totalRecord
*
* @return 返回 totalRecord
*/
public int getTotalRecord()
{
return totalRecord;
}
/**
* 设置 totalRecord
*
* @param 对totalRecord进行赋值
*/
public void setTotalRecord(int totalRecord)
{
this.totalRecord = totalRecord;
}
/**
* 获取 recordPerPage
*
* @return 返回 recordPerPage
*/
public int getRecordPerPage()
{
return recordPerPage;
}
/**
* 设置 recordPerPage
*
* @param 对recordPerPage进行赋值
*/
public void setRecordPerPage(int recordPerPage)
{
this.recordPerPage = recordPerPage;
}
/**
* 获取 totalPages
*
* @return 返回 totalPages
*/
public int getTotalPages()
{
return totalPages;
}
/**
* 设置 totalPages
*
* @param 对totalPages进行赋值
*/
public void setTotalPages(int totalPages)
{
this.totalPages = totalPages;
}
/**
* 获取 curRecord
* @return 返回 curRecord
*/
public int getCurRecord()
{
return curRecord;
}
/**
* 设置 curRecord
* @param 对curRecord进行赋值
*/
public void setCurRecord(int curRecord)
{
this.curRecord = curRecord;
}
}
|
package com.tencent.mm.ui.widget.listview;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import com.tencent.mm.ui.widget.listview.AnimatedExpandableListView.a;
import com.tencent.mm.ui.widget.listview.AnimatedExpandableListView.b;
class AnimatedExpandableListView$a$1 implements AnimationListener {
final /* synthetic */ int nXM;
final /* synthetic */ b uKC;
final /* synthetic */ a uKD;
AnimatedExpandableListView$a$1(a aVar, int i, b bVar) {
this.uKD = aVar;
this.nXM = i;
this.uKC = bVar;
}
public final void onAnimationEnd(Animation animation) {
a.b(this.uKD, this.nXM);
this.uKD.notifyDataSetChanged();
this.uKC.setTag(Integer.valueOf(0));
}
public final void onAnimationRepeat(Animation animation) {
}
public final void onAnimationStart(Animation animation) {
}
}
|
package SwordOffer;
/**
* @author renyujie518
* @version 1.0.0
* @ClassName num2Str_46.java
* @Description 把数字翻译成字符串
* 给定一个数字,按照如下规则翻译成字符串:1 翻译成“a”,2 翻译成“b”... 26 翻译成“z”。
* 一个数字有多种翻译可能,例如 12258 一共有 5 种,分别是 abbeh,lbeh,aveh,abyh,lyh。
* 实现一个函数,用来计算一个数字有多少种不同的翻译方法。
* <p>
* 动态规划:dp[i]代表以 xi为结尾的数字的翻译方案数量。
* 转移方程: 若 xi和xi-1组成的两位数字可以被翻译,则 dp[i] = dp[i - 1] + dp[i - 2];否则dp[i]=dp[i−1]
* <p>
* 但是得注意区间 当 xi-1=0 时,组成的两位数是无法被翻译的 例如 00, 01, 02,因此区间为 [10, 25]。
* dp[2]=dp[1]+dp[0]=2 dp[2]代表总共两位数字的翻译方式 有2种组合 而dp[0]无数字的翻译方法就肯定是1,所以dp[1] = 1
* @createTime 2021年08月25日 14:45:00
*/
public class num2Str_46 {
public static int num2StrWithDP(int num) {
String str = String.valueOf(num);
int[] dp = new int[str.length() + 1];
dp[0] = dp[1] = 1;
for (int i = 2; i <= str.length(); i++) {
String strTemp = str.substring(i - 2, i); //substring左闭右开 所以是【i-2,i-1】 取出i位置的前两位
//翻译时,翻译到第i位时有两种可能,仅采用第i位数字进行翻译或者结合i-1位进行翻译
if (strTemp.compareTo("10") >= 0 && strTemp.compareTo("25") <= 0) {
dp[i] = dp[i - 1] + dp[i - 2];
} else {
dp[i] = dp[i - 1];
}
}
return dp[dp.length - 1];
}
}
|
package com.lspring.annotation3;
import org.springframework.stereotype.Component;
@Component
public class HelloImp {
}
|
package com.tencent.mm.modelappbrand.b;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.bi;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
final class b$d {
private final ag dGb;
final Map<String, List<a>> dGc;
final Map<String, Boolean> dGd;
interface a {
void Kf();
void Kg();
}
/* synthetic */ b$d(ag agVar, byte b) {
this(agVar);
}
private b$d(ag agVar) {
this.dGc = new HashMap();
this.dGd = new HashMap();
this.dGb = agVar;
}
final void jA(String str) {
if (!bi.oW(str)) {
List<a> list = (List) this.dGc.remove(str);
if (!bi.cX(list)) {
for (a Kf : list) {
Kf.Kf();
}
}
}
}
final void jB(String str) {
if (!bi.oW(str)) {
this.dGd.remove(str);
}
}
final void a(String str, a aVar) {
if (!bi.oW(str) && aVar != null) {
List list = (List) this.dGc.get(str);
if (list != null) {
list.remove(aVar);
}
}
}
final void jC(String str) {
if (!bi.oW(str)) {
List<a> list = (List) this.dGc.remove(str);
if (!bi.cX(list)) {
for (a Kg : list) {
Kg.Kg();
}
list.clear();
}
}
}
final void j(Runnable runnable) {
this.dGb.post(runnable);
}
}
|
package com.duofei.stream;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 流式的源码研究
* @author duofei
* @date 2019/9/3
*/
public class StreamCodeStu {
public static void main(String[] args) {
List<Integer> testData = Stream.of(1, 2, 3).collect(Collectors.toList());
testData.stream().forEach(i->{
System.out.println(i);
});
}
}
|
package com.company;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
/*
Recursion
Keep Distance For Identical Elements(C++ not ready)
Given an integer k, arrange the sequence of integers [1, 1, 2, 2, 3, 3, ...., k - 1, k - 1, k, k], such that the output integer array satisfy this condition:
Between each two i's, they are exactly i integers (for example: between the two 1s, there is one number, between the two 2's there are two numbers).
If there does not exist such sequence, return null.
Assumptions:
k is guaranteed to be > 0
Examples:
k = 3, The output = { 2, 3, 1, 2, 1, 3 }.
Approach:
Generate the sequence 112233... and then permute it.
1. Take care of deduplication when permuting sequence with duplicate elements.
2. Eliminate invalid branch. When first time adding a number to the current search,
put its index to a hash map. When the same number is encountered later on, make sure
only recurse to the next level if the right index (current index) - left index - 1
contains the same number(the number itself) it's supposed to contain.
*/
class SolutionKeepDistanceForIdenticalElements {
private void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private int[] helper(int[] seq, int idx, HashMap<Integer, Integer> leftMap) {
if (idx == seq.length) {
return seq;
}
HashSet<Integer> dedup = new HashSet<Integer>();
for (int i = idx; i < seq.length; i++) {
if (!dedup.contains(seq[i])) {
dedup.add(seq[i]);
if (leftMap.containsKey(seq[i])) {
int leftIndex = leftMap.get(seq[i]);
int rightIndex = idx;
int numElems = rightIndex - leftIndex - 1;
swap(seq, idx, i);
if (numElems == seq[idx]) {
int[] res = helper(seq, idx + 1, leftMap);
if (res != null) {
return res;
}
}
swap(seq, idx, i);
} else {
leftMap.put(seq[i], idx);
swap(seq, i, idx);
int[] res = helper(seq, idx + 1, leftMap);
if (res != null) {
return res;
}
swap(seq, i, idx);
leftMap.remove(seq[i]);
}
}
}
return null;
}
public int[] keepDistance(int k) {
int[] seq = new int[2*k];
for (int i = 0; i < seq.length; i++) {
seq[i] = (i / 2) + 1;
}
HashMap<Integer, Integer> leftMap = new HashMap<Integer, Integer>();
int[] res = helper(seq, 0, leftMap);
return res;
}
}
public class Main {
public static void main(String[] args) {
SolutionKeepDistanceForIdenticalElements sol1 = new SolutionKeepDistanceForIdenticalElements();
int[] ans1 = sol1.keepDistance(3);
System.out.println(Arrays.toString(ans1));
}
}
|
/**
* BlockBreakEvent Listener
* @author Dartanman (Austin Dart)
*/
package main.dartanman.egghunt.events;
import java.util.ArrayList;
import java.util.List;
import main.dartanman.egghunt.Main;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
public class BlockBreak implements Listener {
public Main plugin;
/**
* Constructs the BlockBreakEvent Listener class with the Main class for access
* @param pl
* The Main class
*/
public BlockBreak(Main pl) {
this.plugin = pl;
}
/**
* Listens to an event. In this case, the BlockBreakEvent
* In this particular method, it is used to decide whether or not a block can be destroyed, as Easter Eggs cannot be destroyed.
* @param event
* The event to listen to
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void onBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
Block block = event.getBlock();
if (block.getType() == Material.PLAYER_HEAD || block.getType() == Material.PLAYER_WALL_HEAD) {
Location blockLoc = block.getLocation();
String locStr = String.valueOf(blockLoc.getWorld().getName()) + "/" + blockLoc.getBlockX() + "/"
+ blockLoc.getBlockY() + "/" + blockLoc.getBlockZ();
List<String> eggList = new ArrayList<>();
eggList = this.plugin.getEggDataFile().getStringList("EggLocations");
if (eggList.contains(locStr)) {
event.setCancelled(true);
player.sendMessage(ChatColor.translateAlternateColorCodes('&',
this.plugin.getConfig().getString("Messages.CannotDestroy")));
}
}
}
}
|
package com.example.siddiqsami.intrepido;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class Register extends AppCompatActivity {
private static Button Signin;
private static Button Signup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
}
public void onsignin(View view)
{
Signin = (Button) findViewById (R.id.signin);
Signin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.example.siddiqsami.intrepido.Signin");
startActivity(intent);
}
});
}
public void onsignup(View view)
{
Signup=(Button)findViewById(R.id.signup);
Signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.example.siddiqsami.intrepido.Signup");
startActivity(intent);
}
});
}
}
|
import java.util.NoSuchElementException;
/**
* Your implementation of a circular singly linked list.
*
* @author
* @version 1.0
* @userid
* @GTID
*/
public class SinglyLinkedList<T> implements LinkedListInterface<T> {
// Do not add new instance variables or modify existing ones.
public LinkedListNode<T> head;
public int size;
@Override
public void addAtIndex(T data, int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("Index is out of bounds. "
+ "Index must be between 0 and " + size);
} else if (data == null) {
throw new IllegalArgumentException("Data cannot be null");
} else {
if (index == 0) {
addToFront(data);
} else if (index == size) {
addToBack(data);
} else {
int i = 0;
LinkedListNode<T> newNode = new LinkedListNode<T>(null, null);
LinkedListNode<T> tempNode = head;
while (i <= index) {
if (i == index) {
newNode.setNext(tempNode.getNext());
newNode.setData(tempNode.getData());
tempNode.setNext(newNode);
tempNode.setData(data);
size++;
} else {
tempNode = tempNode.getNext();
}
i++;
}
}
}
}
@Override
public void addToFront(T data) {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null");
} else {
if (size == 0) {
head = new LinkedListNode<T>(data, head);
head.setNext(this.head);
size++;
} else {
LinkedListNode<T> newNode = new LinkedListNode<T>(data, null);
if (size == 1) {
newNode.setNext(head);
head.setNext(newNode);
head = newNode;
size++;
} else {
newNode.setNext(head.getNext());
newNode.setData(head.getData());
head.setNext(newNode);
head.setData(data);
size++;
}
}
}
}
@Override
public void addToBack(T data) {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null");
} else {
if (size == 0) {
head = new LinkedListNode<T>(data, head);
head.setNext(this.head);
size++;
} else {
LinkedListNode<T> newNode = new LinkedListNode<T>(data, null);
LinkedListNode<T> temp = head;
if (size == 1) {
newNode.setNext(head);
head.setNext(newNode);
size++;
} else {
newNode.setNext(head.getNext());
newNode.setData(head.getData());
head.setNext(newNode);
head.setData(data);
head = newNode;
size++;
}
}
}
}
@Override
public T removeAtIndex(int index) {
LinkedListNode<T> pointer = head;
LinkedListNode<T> returnNode = new LinkedListNode<T>(null);
if (index >= size || index < 0 || size == 0) {
throw new IndexOutOfBoundsException("Index out of bounds. "
+ "Value must be between 0 and " + (size - 1));
} else {
returnNode.setData(head.getData());
if (size == 1) {
removeFromFront();
} else if (index == 0) {
removeFromFront();
} else {
int i = 0;
while (i <= index) {
if (i == index - 1) {
returnNode = pointer.getNext();
pointer.setNext(pointer.getNext().getNext());
size--;
i++;
} else {
pointer = pointer.getNext();
i++;
}
}
}
}
return returnNode.getData();
}
@Override
public T removeFromFront() {
LinkedListNode<T> temp = new LinkedListNode<T>(null);
if (size == 0) {
return null;
} else {
if (size == 1) {
temp = head;
head = null;
size--;
} else {
temp.setData(head.getData());
head.setData(head.getNext().getData());
head.setNext(head.getNext().getNext());
size--;
}
}
return temp.getData();
}
@Override
public T removeFromBack() {
LinkedListNode<T> temp = head;
LinkedListNode<T> returnNode = head;
if (size == 0) {
return null;
} else {
if (size == 1) {
removeFromFront();
} else {
int i = 0;
while (i < size - 1) {
if (temp.getNext().getNext() == head) {
returnNode = temp.getNext();
temp.setNext(temp.getNext().getNext());
size--;
} else {
temp = temp.getNext();
}
i++;
}
}
}
return returnNode.getData();
}
@Override
public T removeLastOccurrence(T data) {
LinkedListNode<T> pointer = head;
LinkedListNode<T> storageNode = null;
if (data == null) {
throw new IllegalArgumentException("Data cannot be null");
}
if (head == null) {
return null;
} else {
if (size == 1 && pointer.getData().equals(data)) {
removeFromFront();
clear();
} else if (size == 2 && head.getData().equals(data)) {
pointer = head;
removeFromFront();
} else if (size == 2 && head.getNext().getData().equals(data)) {
pointer = head.getNext();
removeFromBack();
} else {
int i = 0;
if (head.getData().equals(data)) {
storageNode = head;
}
while (i < size - 1) {
if (pointer.getNext().getData().equals(data)) {
storageNode = pointer;
}
pointer = pointer.getNext();
i++;
}
if (storageNode == head) {
pointer = storageNode;
removeFromFront();
} else {
if (storageNode != null) {
pointer = storageNode.getNext();
storageNode.setNext(storageNode.getNext().getNext());
size--;
} else {
return null;
}
}
}
}
return pointer.getData();
}
@Override
public T get(int index) {
LinkedListNode<T> temp = head;
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index is out of bounds. "
+ "Index must be between 0 and " + (size - 1));
} else if (index == 0) {
return head.getData();
} else {
int i = 0;
while (i <= index) {
if (i == index) {
return temp.getData();
} else {
temp = temp.getNext();
}
i++;
}
}
return null;
}
@Override
public Object[] toArray() {
int count = 0;
LinkedListNode<T> temp = head;
Object[] toArray = new Object[size];
while (count < size) {
toArray[count] = temp.getData();
temp = temp.getNext();
count++;
}
return toArray;
}
@Override
public boolean isEmpty() {
if (size == 0) {
return true;
}
return false;
}
@Override
public void clear() {
head = null;
size = 0;
}
@Override
public int size() {
// DO NOT MODIFY!
return size;
}
@Override
public LinkedListNode<T> getHead() {
// DO NOT MODIFY!
return head;
}
public void removeFirst(T data) {
LinkedListNode<T> temp = head;
if (size == 1 && head.getData().equals(data)) {
head = null;
size--;
} else if (head.data.equals(data)) {
head.data = head.next.data;
head.next = head.next.next;
size--;
} else {
int i = 0;
while (i < size) {
if (temp.getNext().getData().equals(data)) {
temp.setNext(temp.getNext().getNext());
size--;
return;
} else {
temp = temp.getNext();
i++;
}
if(i == size - 1){
throw new NoSuchElementException();
}
}
}
}
public int getSize() {
return size;
}
public static void main(String[] args) {
SinglyLinkedList<Integer> list = new SinglyLinkedList<>();
list.addToFront(3);
list.addToFront(2);
// list.addToFront(1);
// list.addToBack(4);
// //list.addToBack(5);
// list.addToBack(6);
// list.addToBack(7);
// list.addToBack(5);
LinkedListNode<Integer> node = list.getHead();
for (int i = 0; i < list.getSize(); i++) {
System.out.println(node.getData());
node = node.getNext();
}
System.out.println();
// list.removeFirst(5);
// list.removeFirst(6);
list.removeFirst(3);
System.out.println(list.getHead().getData());
System.out.println(list.head.getNext().getData());
System.out.println(list.size);
System.out.println();
for (int i = 0; i < list.getSize(); i++) {
System.out.println(node.getData());
node = node.getNext();
}
}
}
|
package com.lubarov.daniel.data.serialization;
import com.google.gson.Gson;
public final class GsonSerializer<A> extends AbstractSerializer<A> {
private final Class<A> clazz;
private final Gson gson;
public GsonSerializer(Class<A> clazz) {
this(clazz, new Gson());
}
public GsonSerializer(Class<A> clazz, Gson gson) {
this.clazz = clazz;
this.gson = gson;
}
@Override
public void writeToSink(A object, ByteSink sink) {
StringSerializer.singleton.writeToSink(gson.toJson(object), sink);
}
@Override
public A readFromSource(ByteSource source) {
return gson.fromJson(StringSerializer.singleton.readFromSource(source), clazz);
}
}
|
package servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import com.alibaba.fastjson.JSONObject;
import utils.AESUtils;
import utils.Sha1EncodeUtils;
/**
* Servlet implementation class AIUITppServlet
*/
@WebServlet("/AIUITppServlet")
public class AIUITppServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String token = "c49287381948d874";
private static final String aeskey = "2a8cbe7ba85d6344";
/**
* @see HttpServlet#HttpServlet()
*/
public AIUITppServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String rand = request.getParameter("rand");
if (signature == null || timestamp == null || rand == null) {
return;
}
if (signature.isEmpty() || rand.isEmpty() || timestamp.isEmpty()) {
return;
}
List<String> list = new ArrayList<String>();
list.add(token);
list.add(timestamp);
list.add(rand);
Collections.sort(list);
String localSig = "";
for (int i = 0; i < list.size(); i++) {
localSig += list.get(i);
}
String sigtureSha1 = Sha1EncodeUtils.encode(localSig);
if (sigtureSha1.equals(signature)) {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().append(Sha1EncodeUtils.encode(token));
} else {
response.getWriter().append("check token failed" + sigtureSha1);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Logger aiui = Logger.getLogger("aiui_get");
String encrypttype = request.getParameter("encrypttype");
// NOTE !!!!
// AES decrypt and encrypt may mot be used in your server
// you may debug it again and again to make it.
// welcome to email me: lmliu@iflytek.com if something wrong with you.
if (encrypttype.equals("aes")) {
aiui.log(Level.INFO, "AES Decrypt Mode.");
int len = request.getContentLength();
ServletInputStream inputStream = request.getInputStream();
byte[] buffer = new byte[len];
inputStream.read(buffer, 0, len);
//FileUtils.saveBytesToFile(buffer);
try {
String content = AESUtils.decrypt(aeskey, aeskey, buffer);
aiui.log(Level.INFO, "decrypt data: " + content);
} catch (Exception e) {
e.printStackTrace();
aiui.log(Level.WARNING, "error when decrypt data " + e.getMessage());
}
JSONObject customData = new JSONObject();
customData.put("key", "custome");
customData.put("content", "这是一条来自后处理的测试结果");
response.setContentType("application/json;charset=utf-8");
response.getWriter().append(AESUtils.encrypt(aeskey, aeskey, customData.toString()));
} else {
aiui.log(Level.INFO, "Normal Mode.");
// get request body.
ServletInputStream inputStream = request.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = "";
StringBuilder aiuiPostData = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
aiuiPostData.append(line);
}
aiui.log(Level.INFO, "aiui data post " + aiuiPostData.toString());
JSONObject aiuiPostJson = (JSONObject) JSONObject.parse(aiuiPostData.toString());
String sub = aiuiPostJson.getString("FromSub");
aiui.log(Level.INFO, "aiui data sub = " + sub);
JSONObject msgJson = aiuiPostJson.getJSONObject("Msg");
String content = msgJson.getString("Content");
content = new String(Base64.decodeBase64(content.getBytes()));
aiui.log(Level.INFO, "content = " + content);
// do something what you wanted.
// For example, request third platform or your own server, etc.
// ....
// build your custom data used to transmit to client(sdk/webapi) which can get
// these data from sub "tpp". "key" and "content" are just samples, not necessary.
JSONObject customData = new JSONObject();
customData.put("key", "custom");
customData.put("content", "这是一条来自后处理的测试结果");
aiui.log(Level.INFO, "resonse: customData = " + customData.toJSONString());
//repsonse to AIUI server
response.setContentType("application/json;charset=utf-8");
response.getWriter().append(customData.toString());
}
}
}
|
import javax.swing.*;
import java.util.Scanner;
//A上的二元关系R的自反,对称和传递的判断
public class Main {
public static void main(String[] args) {
int[] A=new int[100];
int[][] R=new int[100][100];
int i=1;
int max=0,min=0;
int x=0;
int y;
Underline u=new Underline();
Judge judge=new Judge();
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个集合A,中间以空格隔开,输入32767结束输入\n");
for(int n=0;n<100;n++){
A[n]=sc.nextInt();
if(n==0){
min=A[0];
}
if(A[n]==32767) {
break;
}
if(A[n]>=100){
System.out.println("输入的元素超出范围,请输入1-99以内的元素");
break;
}
if(max<A[n]){
max=A[n];
}
if(min>A[n]){
min=A[n];
}
}
u.underline();
System.out.println("请输入A上的关系矩阵R,输入32767输入结束");
while(true){
System.out.println("请输入第"+i+"个序偶的第一个元素");
x=sc.nextInt();//序偶的第一个元素
System.out.println("请输入第"+i+"个序偶的第二个元素");
y=sc.nextInt();//序偶的第二个元素
if(x==32767||y==32767)break;
Boolean bool=judge.judge_R(x,y,max,A);
if(bool){
R[x][y]=1;
i++;
}else{
System.out.println("输入的序偶不在A中!!!");
}
}
u.underline();
int ZF=judge.judge_ZFAndFZF(R,max,min);
int DC=judge.judge_DCAndFDC(R,max,min);
int CD=judge.CD(R,max,min);
System.out.println(ZF);
System.out.println(DC);
System.out.println(CD);
//判断是否为偏序关系
if(ZF==1&&DC==3&&CD==1){
System.out.println("该关系拥有偏序关系");
}
if(ZF==2&&DC==3&&CD==1){
System.out.println("该关系是拟序");
}
if(ZF==1&&DC==2&&CD==1){
System.out.println("该关系是等价关系的");
}else {
System.out.println("啥也不是");
}
}
}
|
package com.ctac.jpmc.game.conway;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import com.ctac.jpmc.game.ICoordinates;
public class Coordinates2DTest {
@Test
public void testGetValues() {
ICoordinates c = new Coordinates2D (33,57);
int [] values = c.getValues();
assertEquals("size", 2, values.length);
assertEquals("Equals x", 33, values[0]);
assertEquals("Equals y", 57, values[1]);
}
@Test
public void testEquals() {
ICoordinates a = new Coordinates2D (33,57);
ICoordinates b = new Coordinates2D (33,57);
assertEquals("Equals", a, b);
}
@Test
public void testNotEquals() {
ICoordinates a = new Coordinates2D (33,57);
ICoordinates b = new Coordinates2D (57,33);
assertNotEquals("Not Equals", a, b);
}
@Test
public void testSet() {
Set <ICoordinates> set = new HashSet <ICoordinates> ();
ICoordinates a = new Coordinates2D (2,2);
set.add(a);
ICoordinates b = new Coordinates2D (0,1);
set.add( b);
ICoordinates c = new Coordinates2D (2,2);
set.add( c);
set.add( a);
assertEquals("set size", 2, set.size());
}
}
|
package io.moquette.persistence;
import io.moquette.spi.*;
import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.ISubscriptionsStore.ClientTopicCouple;
import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.Topic;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.mqtt.MqttQoS;
import org.junit.Test;
import java.util.List;
import static io.moquette.spi.impl.subscriptions.Topic.asTopic;
import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE;
import static io.netty.handler.codec.mqtt.MqttQoS.EXACTLY_ONCE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Defines all test that an implementation of a IMessageStore should satisfy.
* */
public abstract class MessageStoreTCK {
public static final String TEST_CLIENT = "TestClient";
protected ISessionsStore sessionsStore;
protected IMessagesStore messagesStore;
@Test
public void testDropMessagesInSessionDoesntCleanAnyRetainedStoredMessages() {
final ClientSession session = sessionsStore.createNewSession(TEST_CLIENT, true);
StoredMessage publishToStore = new StoredMessage("Hello".getBytes(), EXACTLY_ONCE, "/topic");
publishToStore.setClientID(TEST_CLIENT);
publishToStore.setRetained(true);
messagesStore.storeRetained(new Topic("/topic"), publishToStore);
// Exercise
session.cleanSession();
// Verify the message store for session is empty.
StoredMessage storedPublish = messagesStore.searchMatching(new IMatchingCondition() {
@Override
public boolean match(Topic key) {
return key.match(new Topic("/topic"));
}
}).iterator().next();
assertNotNull("The stored retained message must be present after client's session drop", storedPublish);
}
@Test
public void testStoreRetained() {
StoredMessage msgStored = new StoredMessage("Hello".getBytes(), MqttQoS.AT_LEAST_ONCE, "/topic");
msgStored.setClientID(TEST_CLIENT);
messagesStore.storeRetained(asTopic("/topic"), msgStored);
//Verify the message is in the store
StoredMessage msgRetrieved = messagesStore.searchMatching(new IMatchingCondition() {
@Override
public boolean match(Topic key) {
return key.match(new Topic("/topic"));
}
}).iterator().next();
final ByteBuf payload = msgRetrieved.getPayload();
byte[] content = new byte[payload.readableBytes()];
payload.readBytes(content);
assertEquals("Hello", new String(content));
}
@Test
public void givenSubscriptionAlreadyStoredIsOverwrittenByAnotherWithSameTopic() {
ClientSession session1 = sessionsStore.createNewSession("SESSION_ID_1", true);
// Subscribe on /topic with QOSType.MOST_ONE
Subscription oldSubscription = new Subscription(session1.clientID, new Topic("/topic"), AT_MOST_ONCE);
session1.subscribe(oldSubscription);
// Subscribe on /topic again that overrides the previous subscription.
Subscription overridingSubscription = new Subscription(session1.clientID, new Topic("/topic"), EXACTLY_ONCE);
session1.subscribe(overridingSubscription);
// Verify
final ISubscriptionsStore subscriptionsStore = sessionsStore.subscriptionStore();
List<ClientTopicCouple> subscriptions = subscriptionsStore.listAllSubscriptions();
assertEquals(1, subscriptions.size());
Subscription sub = subscriptionsStore.getSubscription(subscriptions.get(0));
assertEquals(overridingSubscription.getRequestedQos(), sub.getRequestedQos());
}
}
|
package com.github.jrubygradle.jem;
import java.io.File;
/**
* Plain-old-Java-object containing properties to tell the consumer something about
* an attempted (or successful) gem installation
*/
public class GemInstallResult {
public static enum Type { SUCCESS, FAILURE };
protected Type resultType;
protected Gem gem;
protected File gemFile;
protected File installationDir;
protected Exception exception;
public GemInstallResult(Gem gem,
File gemFile,
File installDir,
Exception exception) {
this.gem = gem;
this.gemFile = gemFile;
this.installationDir = installDir;
this.exception = exception;
this.resultType = Type.FAILURE;
if (exception == null) {
this.resultType = Type.SUCCESS;
}
}
/**
* @return Metadata about the gem, null if the metadata could not be passed
*/
public Gem getGem() {
return gem;
}
/**
* @return In the case of a failed installation, this contains a caught exception
*/
public Exception getException() {
return exception;
}
/**
* @return File object for the .gem file which was used for the install
*/
public File getGemFile() {
return gemFile;
}
/**
* @return File object for the intallation dir used for the install
*/
public File getInstallationDir() {
return installationDir;
}
public Type getType() {
return resultType;
}
}
|
package com.box.androidsdk.content.models;
import android.content.Context;
import java.util.ArrayList;
/**
* Session created from a shared link.
*/
public class BoxSharedLinkSession extends BoxSession {
String mSharedLink;
String mPassword;
public BoxSharedLinkSession(BoxSession session) {
super(session);
if (session instanceof BoxSharedLinkSession) {
BoxSharedLinkSession sharedLinkSession = (BoxSharedLinkSession) session;
setSharedLink(sharedLinkSession.getSharedLink());
setPassword(sharedLinkSession.getPassword());
}
}
public BoxSharedLinkSession(Context context) {
super(context);
}
public BoxSharedLinkSession(Context context, String userId ) {
super(context, userId);
}
public BoxSharedLinkSession(Context context, String userId, String clientId, String clientSecret, String redirectUrl) {
super(context, userId, clientId, clientSecret, redirectUrl);
}
public String getSharedLink() {
return mSharedLink;
}
public BoxSharedLinkSession setSharedLink(String sharedLink) {
mSharedLink = sharedLink;
return this;
}
public String getPassword() {
return mPassword;
}
public BoxSharedLinkSession setPassword(String password) {
mPassword = password;
return this;
}
}
|
package week2.day2;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class Ass1part4radiobutton {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("http://leafground.com/pages/radio.html");
driver.manage().window().maximize();
driver.findElement(By.id("yes")).click();
WebElement enable = driver.findElement(By.xpath("//label[@for='Checked']"));
boolean flag = enable.isEnabled();
if(flag)
System.out.println(" Default Radio button selected is Checked");
else
System.out.println(" Default Radio button selected is Unchecked");
boolean agegroup = driver.findElement(By.xpath("(//input[@class='myradio'])[4]")).isSelected();
if(!agegroup)
driver.findElement(By.xpath("(//input[@class='myradio'])[4]")).click();
else
System.out.println(" Age group choice already selected");
}
}
|
package com.arkaces.aces_marketplace_api.error;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
public class NotFoundException extends RuntimeException {
private String code;
private String message;
public NotFoundException(String code, String message) {
super(message);
this.code = code;
this.message = message;
}
}
|
package com.yc.biz;
import com.yc.LogAspectCglib;
/**
* @program: testspring
* @description:
* @author: 作者
* @create: 2021-04-11 19:49
*/
public class Test {
public static void main(String[] args) {
StudentBizImpl sbi=new StudentBizImpl();
LogAspectCglib lc=new LogAspectCglib(sbi);
//生成代理
Object obj=lc.createProxy();
System.out.println(obj);//obj.toString()
if (obj instanceof StudentBizImpl){
StudentBizImpl s=(StudentBizImpl)obj;
s.find("张三");
s.update("李四");
s.add("王五");
}
}
}
|
package com.faraonelife;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
public class TipController {
private int currentPercentage = 10;
@FXML
private TextField txtAmount;
@FXML
private Label lblPercentage;
@FXML
private Slider slrPercentage;
@FXML
private TextField txtTip;
@FXML
private TextField txtTotal;
@FXML
private TextField txtNumPeople;
@FXML
private TextField txtEachPays;
@FXML
public void initialize(){
slrPercentage.valueProperty().addListener(new ChangeListener() {
@Override
public void changed(ObservableValue observableValue, Object o, Object t1) {
handleSlider();
}
});
}
@FXML
public void handleSlider(){
this.currentPercentage = (int)slrPercentage.getValue();
lblPercentage.setText(String.format("%d%%", this.currentPercentage));
}
@FXML
public void handleCalculateTip(){
double amount = Double.parseDouble(txtAmount.getText());
double tip = (this.currentPercentage / 100.0) * amount;
double total = amount + tip;
int numOfPeople = Integer.parseInt(txtNumPeople.getText());
double eachPays = total / numOfPeople;
txtTip.setText(""+tip);
txtTotal.setText(""+total);
txtEachPays.setText(""+eachPays);
}
}
|
package com.spring.command;
public class LoginCommand {
private String id;
private String pwd;
public final String getId() {
return id;
}
public final void setId(String id) {
this.id = id;
}
public final String getPwd() {
return pwd;
}
public final void setPwd(String pwd) {
this.pwd = pwd;
}
}
|
package com.woohun.lang.String;
public class String_test3 {
public static void main(String[] args) {
String s ="iu,suji,choa,hani";
String[] names = s.split(",");
for(int i=0;i<names.length;i++) {
System.out.println(names[i]);
}
//향상된 for
for(String str:names) {
System.out.println(str);
} //배열의 길이만큼 돌아감.
}
}
|
package tech42.sathish.inventorymanagement.activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.weiwangcn.betterspinner.library.material.MaterialBetterSpinner;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import tech42.sathish.inventorymanagement.R;
import tech42.sathish.inventorymanagement.constant.Constant;
import tech42.sathish.inventorymanagement.firebasehelper.ProductStorageHelper;
import tech42.sathish.inventorymanagement.model.Product;
import static tech42.sathish.inventorymanagement.constant.Constant.quantity_Unit_Array;
/*
1.INITIALIZE FIREBASE DB
2.INITIALIZE UI
3.DATA INPUT
*/
public class ExportActivity extends AppCompatActivity implements View.OnClickListener{
private DatabaseReference databaseReference;
private ProductStorageHelper firebaseHelper;
private EditText edittext_item, edittext_quantity, edittext_price, editText_buyer;
private Button button_export;
private MaterialBetterSpinner unit_materialDesignSpinner;
private String string_quantity, string_buyer, string_unit, string_item, string_price, import_price, import_date, import_seller;
private Integer import_qty, export_qty, export_children_count;
private ArrayList<String> itemList = new ArrayList<>();
@Override
protected final void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_export);
initializeFirebaseDatabase();
initializeViews();
getItemCount();
showSearchDialog();
}
private void initializeFirebaseDatabase()
{
databaseReference = FirebaseDatabase.getInstance().getReference();
firebaseHelper = new ProductStorageHelper(databaseReference);
}
private void initializeViews()
{
edittext_item = (EditText)findViewById(R.id.item);
edittext_quantity = (EditText)findViewById(R.id.qty);
edittext_price = (EditText)findViewById(R.id.price);
editText_buyer = (EditText)findViewById(R.id.buyer);
button_export = (Button)findViewById(R.id.btn_import);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, quantity_Unit_Array);
unit_materialDesignSpinner = (MaterialBetterSpinner)
findViewById(R.id.unit);
unit_materialDesignSpinner.setAdapter(arrayAdapter);
Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/Lato-Light.ttf");
unit_materialDesignSpinner.setTypeface(tf);
button_export.setOnClickListener( this );
}
@Override
public final void onClick(View v) {
getData();
if ( v. equals( button_export ) )
{
if(editTextValidation()) {
if(quantityValidation())
{setData();}
else {
Toast.makeText(getApplicationContext(), "Exported quantity " + string_quantity + " is more than stock quantity : " + import_qty, Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(getApplicationContext(),"Details must not be empty..",Toast.LENGTH_SHORT).show();}
}
}
private void getData()
{
string_item = edittext_item.getText().toString().toUpperCase();
string_price = edittext_price.getText().toString();
string_quantity = edittext_quantity.getText().toString();
string_buyer = editText_buyer.getText().toString();
string_unit = unit_materialDesignSpinner.getText().toString();
}
private void setData()
{
// Update Import Array
Product product = new Product();
product.setItem( string_item );
product.setPrice( import_price );
product.setQuantity( export_qty.toString() );
product.setSeller( import_seller );
product.setUnit( string_unit );
product.setDate( import_date );
// Add Export Array
Product arrayProduct = new Product();
arrayProduct.setItem( string_item );
arrayProduct.setPrice( string_price );
arrayProduct.setQuantity( string_quantity );
arrayProduct.setBuyer( string_buyer );
arrayProduct.setUnit( string_unit );
arrayProduct.setDate( getCurrentDate() );
if(firebaseHelper.update(product) && firebaseHelper.addExportTransaction(export_children_count,arrayProduct)) {
clearEditText();
Toast.makeText(getApplicationContext(), "Product Exported successfully..", Toast.LENGTH_SHORT).show();
refresh();
}
else{
Toast.makeText(getApplicationContext(),"Product didn't export..",Toast.LENGTH_SHORT).show();}
}
private boolean editTextValidation()
{
return !(string_item.isEmpty() || string_quantity.isEmpty() || string_price.isEmpty() || string_buyer.isEmpty() || string_unit.isEmpty());
}
private void clearEditText()
{
edittext_quantity.setText(Constant.EMPTY);
edittext_item.setText(Constant.EMPTY);
editText_buyer.setText(Constant.EMPTY);
edittext_price.setText(Constant.EMPTY);
unit_materialDesignSpinner.clearFocus();
unit_materialDesignSpinner.setText(Constant.EMPTY);
}
private String getCurrentDate()
{
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat(Constant.DATEFORMAT);
return df.format(c.getTime());
}
private void getItemDetails()
{
DatabaseReference getChildListener = databaseReference.child(HomeActivity.USERMAIL).child(Constant.STORAGE).child(Constant.PRODUCT).child(string_item.toUpperCase());
getChildListener.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
Product product = dataSnapshot.getValue(Product.class);
editText_buyer.setText(product.getBuyer());
edittext_price.setText(product.getPrice());
import_price = product.getPrice();
edittext_quantity.setText(product.getQuantity());
import_qty = Integer.parseInt(product.getQuantity());
unit_materialDesignSpinner.setText(product.getUnit());
import_date = product.getDate();
}
else
{
Toast.makeText(getApplicationContext(),"Item Not Found..",Toast.LENGTH_SHORT).show();
showSearchDialog();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
}
private void getItemCount()
{
try {
DatabaseReference getChildListener = databaseReference.child(HomeActivity.USERMAIL).child(Constant.STORAGE).child(Constant.EXPORT_TRANSACTIONS);
getChildListener.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
export_children_count = (int) dataSnapshot.getChildrenCount() ;
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
catch (Exception e)
{
export_children_count = 0;
}
}
private Boolean quantityValidation()
{
if((Integer.parseInt(string_quantity) < (import_qty))) {
export_qty = import_qty - (Integer.parseInt(string_quantity));
return true;
}
else{
return false;}
}
public final void refresh()
{
Intent refresh = getIntent();
finish();
startActivity(refresh);
}
private void showSearchDialog()
{
final Dialog dialog = new Dialog(ExportActivity.this);
//setting custom layout to dialog
dialog.setContentView(R.layout.layout_export_item_search);
dialog.setTitle(Constant.ITEMSEARCH);
dialog.setCanceledOnTouchOutside(false);
final AutoCompleteTextView editextSearch;
editextSearch = (AutoCompleteTextView) dialog.findViewById(R.id.item);
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,getItemList());
editextSearch.setAdapter(adapter);
editextSearch.setThreshold(0);
//adding button click event
Button search = (Button) dialog.findViewById(R.id.btn_search);
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!editextSearch.getText().toString().isEmpty()) {
edittext_item.setText(editextSearch.getText().toString());
getData();
getItemDetails();
dialog.dismiss();
}
else{
Toast.makeText(getApplicationContext(),"Item must not empty..",Toast.LENGTH_SHORT).show();
}
}
});
dialog.show();
}
@Override
public final void onBackPressed() {
super.onBackPressed();
finish();
}
private ArrayList<String> getItemList()
{
DatabaseReference getItemListener = databaseReference.child(HomeActivity.USERMAIL).child(Constant.STORAGE).child(Constant.PRODUCT);
getItemListener.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
itemList.add(String.valueOf(dsp.getKey())); //add result into array list
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return itemList;
}
}
|
package com.midashnt.taekwondo.app.mapper;
import com.midashnt.taekwondo.app.dto.Event;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
@Mapper
public interface EventMapper {
String createEvent(Event event);
void updateEvent(Event event);
Event getEventByIndex(int eventIndex);
List<Event> getEventListByCompetitionIndex(int competitionIndex);
List<Map<String,Object>> getEventMapListByCompetitionIndex(int competitionIndex);
void deleteEvent(int eventIndex);
}
|
package at.xirado.bean.command;
import at.xirado.bean.data.GuildData;
import at.xirado.bean.data.GuildManager;
import at.xirado.bean.data.LinkedDataObject;
import at.xirado.bean.translation.LocaleLoader;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.exceptions.ErrorHandler;
import net.dv8tion.jda.api.requests.ErrorResponse;
import net.dv8tion.jda.api.utils.messages.MessageCreateData;
import java.awt.*;
import java.time.Instant;
import java.util.EnumSet;
import java.util.List;
import java.util.function.Consumer;
public class CommandContext {
public static final String LOADING_EMOTE = "<a:loading:779763323821359104>";
public static final String WARNING_EMOTE = "⚠";
public static final String ERROR_EMOTE = "❌";
public static final String SUCCESS_EMOTE = "✅";
private final MessageReceivedEvent event;
private final Command command;
private final Member member;
private final CommandArgument commandArgument;
public CommandContext(MessageReceivedEvent event, CommandArgument commandArgument, Command command, Member member) {
this.event = event;
this.commandArgument = commandArgument;
this.command = command;
this.member = member;
}
public GuildData getGuildData() {
return GuildManager.getGuildData(event.getGuild());
}
public MessageReceivedEvent getEvent() {
return event;
}
public CommandArgument getArguments() {
return commandArgument;
}
public Command getCommand() {
return command;
}
public Member getMember() {
return member;
}
public void replyError(String message) {
this.event.getChannel().sendMessageEmbeds(
new EmbedBuilder()
.setColor(Color.red)
.setDescription(ERROR_EMOTE + " " + message)
.build()
).queue();
}
public void deleteInvokeMessage() {
this.event.getMessage().delete().queue(s ->
{
}, e ->
{
});
}
public void replyInLogChannel(String message) {
TextChannel logChannel = getGuildData().getLogChannel();
if (logChannel != null) logChannel.sendMessage(message).queue();
}
public TextChannel getLogChannel() {
return getGuildData().getLogChannel();
}
public boolean hasLogChannel() {
return getGuildData().getLogChannel() != null;
}
public void replyInLogChannel(Message message) {
TextChannel logChannel = getGuildData().getLogChannel();
if (logChannel != null) logChannel.sendMessage(MessageCreateData.fromMessage(message)).queue();
}
public void replyInLogChannel(MessageEmbed message) {
TextChannel logChannel = getGuildData().getLogChannel();
if (logChannel != null) logChannel.sendMessageEmbeds(message).queue();
}
public void replyErrorUsage() {
EmbedBuilder builder = new EmbedBuilder()
.setColor(Color.red)
.setTitle(LocaleLoader.ofGuild(event.getGuild()).get("general.invalid_arguments", String.class))
.setTimestamp(Instant.now());
String usage = getGuildData().getPrefix() + getCommand().getUsage();
List<String> aliases = this.getCommand().getAliases();
StringBuilder sb = new StringBuilder();
String aliasesstring = null;
if (aliases.size() > 0) {
for (String alias : aliases) {
sb.append(alias).append(", ");
}
aliasesstring = sb.toString().trim();
}
String description = "`" + usage + "`\n" + this.getCommand().getDescription();
if (aliases.size() > 0 && aliasesstring != null) {
description += "\n" + LocaleLoader.ofGuild(event.getGuild()).get("general.aliases", String.class) + ": `" + aliasesstring + "`";
}
builder.setDescription(description);
event.getChannel().sendMessageEmbeds(builder.build()).queue();
}
public void replyWarning(String message) {
this.event.getChannel().sendMessageEmbeds(
new EmbedBuilder()
.setColor(Color.yellow)
.setTimestamp(Instant.now())
.setDescription(WARNING_EMOTE + " " + message)
.build()
).queue();
}
public void replySuccess(String message) {
this.event.getChannel().sendMessageEmbeds(
new EmbedBuilder()
.setColor(Color.green)
.setDescription(SUCCESS_EMOTE + " " + message)
.build()
).queue();
}
public void reply(Message message, Consumer<Message> success, Consumer<Throwable> failure) {
event.getChannel().sendMessage(MessageCreateData.fromMessage(message)).queue(success, failure);
}
public void reply(Message message, Consumer<Message> success) {
event.getChannel().sendMessage(MessageCreateData.fromMessage(message)).queue(success);
}
public void reply(Message message) {
event.getChannel().sendMessage(MessageCreateData.fromMessage(message)).queue();
}
public void reply(String message, Consumer<Message> success, Consumer<Throwable> failure) {
event.getChannel().sendMessage(message).queue(success, failure);
}
public void reply(String message, Consumer<Message> success) {
event.getChannel().sendMessage(message).queue(success);
}
public void reply(String message) {
event.getChannel().sendMessage(message).queue();
}
public void reply(MessageEmbed embed, Consumer<Message> success, Consumer<Throwable> failure) {
event.getChannel().sendMessageEmbeds(embed).queue(success, failure);
}
public void reply(MessageEmbed embed, Consumer<Message> success) {
event.getChannel().sendMessageEmbeds(embed).queue(success);
}
public void reply(MessageEmbed embed) {
event.getChannel().sendMessageEmbeds(embed).queue();
}
public void replyInDM(Message message, Consumer<Message> success, Consumer<Throwable> failure) {
User user = this.event.getAuthor();
user.openPrivateChannel().queue(
(pc) ->
{
pc.sendMessage(MessageCreateData.fromMessage(message)).queue(success, failure);
}
);
}
public void replyInDM(Message message, Consumer<Message> success) {
User user = this.event.getAuthor();
user.openPrivateChannel().queue(
(pc) ->
{
pc.sendMessage(MessageCreateData.fromMessage(message)).queue(success, new ErrorHandler()
.ignore(EnumSet.allOf(ErrorResponse.class)));
}
);
}
public void replyInDM(Message message) {
User user = this.event.getAuthor();
user.openPrivateChannel().queue(
(pc) ->
{
pc.sendMessage(MessageCreateData.fromMessage(message)).queue(null, new ErrorHandler()
.ignore(EnumSet.allOf(ErrorResponse.class)));
}
);
}
public void replyInDM(MessageEmbed embed, Consumer<Message> success, Consumer<Throwable> failure) {
User user = this.event.getAuthor();
user.openPrivateChannel().queue(
(pc) ->
{
pc.sendMessageEmbeds(embed).queue(success, failure);
}
);
}
public void replyInDM(MessageEmbed embed, Consumer<Message> success) {
User user = this.event.getAuthor();
user.openPrivateChannel().queue(
(pc) ->
{
pc.sendMessageEmbeds(embed).queue(success, new ErrorHandler()
.ignore(EnumSet.allOf(ErrorResponse.class)));
}
);
}
public void replyInDM(MessageEmbed embed) {
User user = this.event.getAuthor();
user.openPrivateChannel().queue(
(pc) ->
{
pc.sendMessageEmbeds(embed).queue(null, new ErrorHandler()
.ignore(EnumSet.allOf(ErrorResponse.class)));
}
);
}
public void replyInDM(String message, Consumer<Message> success, Consumer<Throwable> failure) {
User user = this.event.getAuthor();
user.openPrivateChannel().queue(
(pc) ->
{
pc.sendMessage(message).queue(success, failure);
}
);
}
public LinkedDataObject getLanguage() {
Guild g = event.getGuild();
return LocaleLoader.ofGuild(g);
}
public void replyInDM(String message, Consumer<Message> success) {
User user = this.event.getAuthor();
user.openPrivateChannel().queue(
(pc) ->
{
pc.sendMessage(message).queue(success, new ErrorHandler()
.ignore(EnumSet.allOf(ErrorResponse.class)));
}
);
}
public String getLocalized(String query, Object... objects) {
return String.format(LocaleLoader.ofGuild(event.getGuild()).get(query, String.class), objects);
}
public String parseDuration(long seconds, String delimiter) {
return LocaleLoader.parseDuration(seconds, getLanguage(), delimiter);
}
public void replyInDM(String message) {
User user = this.event.getMember().getUser();
user.openPrivateChannel().queue(
(pc) ->
{
pc.sendMessage(message).queue(null, new ErrorHandler()
.ignore(EnumSet.allOf(ErrorResponse.class)));
}
);
}
}
|
package com.stem.core.commons;
import java.util.List;
public class Pagination<T> {
public static int ROWS = 5;
private int pageIndex;
private int pageSize;
private int total;
private List<T> data;
private int pages;
private int start;
private int end;
private int next;
private int prev;
public Pagination() {
this(0, 1);
}
public Pagination(int total, int pageIndex) {
this(total, pageIndex, ROWS);
}
public Pagination(int total, int pageIndex, int pageSize) {
super();
this.total = total;
this.pageIndex = pageIndex == 0 ? 1 : pageIndex;
this.pageSize = pageSize;
this.pages = (int) Math.ceil((total + 0.0) / pageSize);
if(this.pageIndex>=pages){
this.pageIndex = pages;
}
count();
nextAndPrevious(this.pageIndex);
}
private void nextAndPrevious(int pageIndex) {
next = pageIndex + 1;
prev = pageIndex - 1;
if (!hasPreview())
prev = pageIndex;
if (!hasNext())
next = pageIndex;
}
private void count() {
this.start = pageSize * (pageIndex - 1);
this.end = pageSize * (pageIndex);
if (this.end > total) {
this.end = total;
}
}
/**
* 当前页是否有上一页
*
* @return
*/
public boolean hasPreview() {
if (pages > 1 && pageIndex > 1) {
return true;
}
return false;
}
/**
* 当前页是否有下一页
*
* @return
*/
public boolean hasNext() {
if (pages > 1 && pageIndex < pages) {
return true;
}
return false;
}
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public int getNext() {
return next;
}
public void setNext(int next) {
this.next = next;
}
public int getPrev() {
return prev;
}
public void setPrev(int prev) {
this.prev = prev;
}
}
|
import javax.swing.UIManager;
public class Driver {
public static void main(String args[]) {
try {
UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
} catch (Exception e) {
e.printStackTrace();
}
IconSizePicker test = new IconSizePicker();
}
}
|
package com.hcl.service;
import java.util.List;
import com.hcl.dao.CategoryDAO;
import com.hcl.dao.CategoryDAO;
import com.hcl.entity.Category;
public class CategoryService {
public boolean addCategory(String name, String desc)
{
CategoryDAO edao=new CategoryDAO();
return edao.addCategory(name, desc);
}
public boolean deleteCategory(int cat_id)
{
CategoryDAO edao=new CategoryDAO();
return edao.deleteCategory(cat_id);
}
public boolean updateCategory(int id,String name,String desc)
{
CategoryDAO edao=new CategoryDAO();
return edao.updateCategory(id,name,desc);
}
public List<Category> display()
{
CategoryDAO edao=new CategoryDAO();
List<Category> list=edao.display();
return list;
}
}
|
package com.mrhan.db.allrounddaos;
import java.util.Set;
public interface ITable {
/**
* 获取实体类对于的表名称
* @return
*/
String getTableName();
/**
* 获取实体类对于的Class
* @return
*/
Class<?> getEntityClass();
/**
* 获取指定表中字段所绑定 字段信息
* @param colName
* @return
*/
com.mrhan.db.allrounddaos.IFeild getFeild(String colName);
/**
* 获取当前 实体下所有的字段信息
* @return
*/
Set<com.mrhan.db.allrounddaos.IFeild> getFeild();
/**
* 创建实体
* @return
*/
Object createEntityObject();
/**
* 创建查询语句
* @return
*/
com.mrhan.db.SQLStatement createInsertSql(Object obj);
/**
* 创建修改语句
* @return
*/
com.mrhan.db.SQLStatement createUpdateSql(Object obj, String key, Object value);
/**
* 创建修改语句
* @return
*/
com.mrhan.db.SQLStatement createDeleteSql(Object obj, String key, Object value);
/**
* 获取主键
* @return
*/
com.mrhan.db.allrounddaos.IFeild[] getPirmaryKey();
/**
* 获取外键键
* @return
*/
com.mrhan.db.allrounddaos.IFeild[] getUnqiueKey();
/**
* 获取指定类型的建
* @param type
* @return
*/
com.mrhan.db.allrounddaos.IFeild[] getFeildByType(com.mrhan.db.allrounddaos.ColumentType type);
}
|
package com.wipe.zc.journey.domain;
import com.easemob.chat.EMMessage;
import java.util.Calendar;
/**
* Chat信息
*/
public class ChatMessage {
private String receiveAvatar;
private String content;
private Calendar chatTime;
private String sendAvatar;
private String messageId;
private EMMessage.Type type;
public EMMessage.Type getType() {
return type;
}
public void setType(EMMessage.Type type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public String getReceiveAvatar() {
return receiveAvatar;
}
public void setReceiveAvatar(String receiveAvatar) {
this.receiveAvatar = receiveAvatar;
}
public Calendar getChatTime() {
return chatTime;
}
public void setChatTime(Calendar chatTime) {
this.chatTime = chatTime;
}
public String getSendAvatar() {
return sendAvatar;
}
public void setSendAvatar(String sendAvatar) {
this.sendAvatar = sendAvatar;
}
}
|
/**
* Escreva a descrição da classe Normal aqui.
*
* @author (seu nome)
* @version (número de versão ou data)
*/
public class Normal extends Ingresso
{
public void ingressoNormal(){
System.out.println("Ingresso Normal: "+ this.valor + "R$");
}
}
|
//FILE: Main.Java
//PROG: Adam Barker
//PURP: Initiates Cab object and UI
package edu.trident.barker.cpt237;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
boolean done = false;
while (!done) {
try {
String strGasInput = JOptionPane
.showInputDialog("Please enter initial amount of gas! It's free :)");
double gasInput = Double.parseDouble(strGasInput);
Cab2 cab = new Cab2(gasInput);
@SuppressWarnings("unused")
UserInterface2 cabUi2 = new UserInterface2(cab);
@SuppressWarnings("unused")
UserInterface cabUi = new UserInterface(cab);
done = true;
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(null,
"That is an invalid number! Please try again!");
} catch (NullPointerException e2) {
System.exit(0);
}
}
}
}
|
package net.osmd.repository;
import net.osmd.models.Services;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Created by WEO on 11/22/16.
*/
public interface ServicesRepository extends JpaRepository <Services, Integer> {
}
|
package uk.gov.gchq.palisade.example.rule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import uk.gov.gchq.palisade.Context;
import uk.gov.gchq.palisade.User;
import uk.gov.gchq.palisade.example.common.Purpose;
import uk.gov.gchq.palisade.example.hrdatagenerator.types.Address;
import uk.gov.gchq.palisade.example.hrdatagenerator.types.Employee;
import uk.gov.gchq.palisade.rule.Rule;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeThat;
@RunWith(Theories.class)
public class TestAddressRule extends TestCommonRuleTheories {
@DataPoint
public static final AddressRule rule = new AddressRule();
@Theory
public void testUnchangedWithProfileAccess(Rule<Employee> rule, final Employee record, final User user, final Context context) {
// Given - Purpose == PROFILE_ACCESS
assumeThat(context.getPurpose(), is(Purpose.PROFILE_ACCESS.name()));
// Given - Employee.Uid == User.Uid
assumeThat(record.getUid(), is(user.getUserId()));
// When
Employee recordWithRule = rule.apply(new Employee(record), user, context);
// Then
assertThat(recordWithRule, equalTo(record));
}
@Theory
public void testUnchangedWithHealthPurpose(Rule<Employee> rule, final Employee record, final User user, final Context context) {
// Given - Purpose == HEALTH_SCREENING
assumeThat(context.getPurpose(), is(Purpose.HEALTH_SCREENING.name()));
// When
Employee recordWithRule = rule.apply(new Employee(record), user, context);
Employee maskedRecord = new Employee(record);
// Then
assertThat(recordWithRule.getAddress(), is(record.getAddress()));
assertThat(recordWithRule, is(maskedRecord));
}
@Theory
public void testAddressRedacted(Rule<Employee> rule, final Employee record, final User user, final Context context) {
// Given - Does satisfy Salary rule
assumeThat(context.getPurpose(), is(Purpose.SALARY_ANALYSIS.name()));
// When
Employee recordWithRule = rule.apply(new Employee(record), user, context);
// Then - Expected
Employee redactedRecord = new Employee(record);
Address employeeAddress = redactedRecord.getAddress();
employeeAddress.setStreetAddressNumber(null);
employeeAddress.setStreetName(null);
employeeAddress.setZipCode(employeeAddress.getZipCode().substring(0, employeeAddress.getZipCode().length() - 1) + "*");
// Then - Observed
assertThat(recordWithRule, is(redactedRecord));
}
}
|
package com.example.demo.sl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.bl.MessageService;
import com.example.demo.dl.MessageEntity;
import lombok.extern.slf4j.Slf4j;
/**
* Rest controller responsible for handling next list of Http requests:
* <P>
* <i>Messages/</i> - returns a list of all MessageEntity objects stored
* inside the database.<br>
* This request is handled by showMessages() method.
* <p>
* <i>Message/id</i> - returns data stored in MessageEntity object with
* provided ID.<br>
* This request is handled by getMessageById(int id) method
* <p>
* <i>deleteMessage/id</i> - request which provides to delete the
* MessageEntity stored inside the database with provided ID.<br>
* This request is handled by deleteMessage(int id) method.
* <p>
* <i>postMessage/id/text</i> - request which provides to posting a new
* MessageEntity object with provided parameters inside the database.<br>
* This request is handled by postMessage(int id, String text) method.
* <p>
* <i>putMessage/id/newText</i> - request which provides to put an
* existing MessageEntity by provided ID with new text value.<br>
* This request is handled by putMessage(int id, String text) method.
*
* @author serhii.shvets
*
*/
@Slf4j // dodaj logowanie na poziomach error, debug, info
@RestController
public class MessageController implements MessagerControllerInterface {
private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MessageController.class);
@Autowired
private MessageService messageService;
@Override
public ResponseEntity<String> showMessages() {
try {
String resultString = "\tMessages stored inside DB:\n\n";
List<MessageEntity> messages = (List<MessageEntity>) messageService.findAll();
messages.get(0);
for (int i = 0; i < messages.size(); i++) {
resultString += messageService.getDataFromMessageEntity(messages.get(i));
}
log.debug("Obtained messages count: {}", messages.size());
return new ResponseEntity<String>(resultString, HttpStatus.OK);
} catch (CannotCreateTransactionException e) {
log.error("Check database connection parameters" + e.toString());
return new ResponseEntity<String>("Check your database connection parameters.\n" + e.toString(),
HttpStatus.INTERNAL_SERVER_ERROR);
} catch (IndexOutOfBoundsException e) {
log.debug("There are no messages stored inside the database");
String resultString = "There are no messages stored inside the database.\n";
return new ResponseEntity<String>(resultString, HttpStatus.OK);
} catch (Exception e) {
log.error("Exception caught" + e.toString());
return new ResponseEntity<String>(e.toString(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Override
public ResponseEntity<String> postMessage(int id, String text) {
try {
if (!messageService.checkMessageIfExixting(id)) {
String resultString = "Created new message with the following parameters:\n";
MessageEntity message = messageService.postMessage(id, text, 1);
log.debug("Posted new message with id= " + message.getMesId());
return new ResponseEntity<String>(resultString + messageService.getDataFromMessageEntity(message),
HttpStatus.CREATED);
} else {
log.debug("Unable to post a new message with ID " + id
+ " since message with provided ID is already exists.");
return new ResponseEntity<String>("Unable to post a new message with ID " + id
+ " since message with provided ID is already exists.", HttpStatus.BAD_REQUEST);
}
} catch (CannotCreateTransactionException e) {
log.error("Wrong database connection parameters. " + e.toString());
return new ResponseEntity<String>("Check your database connection parameters.\n" + e.toString(),
HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
log.error("Exception caught" + e.toString());
return new ResponseEntity<String>(e.toString(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Override
public ResponseEntity<String> putMessage(int id, String text) {
try {
if (messageService.checkMessageIfExixting(id)) {
MessageEntity message = messageService.postMessage(id, text, 1);
log.debug("Message was updated successfully.");
return new ResponseEntity<String>(
"Message updated successfully :\n" + messageService.getDataFromMessageEntity(message),
HttpStatus.OK);
} else {
log.debug("Unable to update a new message with ID " + id + " since such message is not existing");
return new ResponseEntity<String>(
"Unable to update a new message with ID " + id + " since such message is not existing",
HttpStatus.NOT_FOUND);
}
} catch (CannotCreateTransactionException e) {
log.error("Wrong database connection parameters. " + e.toString());
return new ResponseEntity<String>("Check your database connection parameters.\n" + e.toString(),
HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
log.error("Exception caught. " + e.toString());
return new ResponseEntity<String>(e.toString(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Override
public ResponseEntity<String> deleteMessage(int id) {
try {
if (messageService.checkMessageIfExixting(id)) {
messageService.deleteMessage(id);
log.debug("Message with id " + id + " was deleted successfully");
return new ResponseEntity<String>("Message with id " + id + " was deleted successfully :\n",
HttpStatus.OK);
} else {
log.debug("Unable to delete a message with ID " + id + " since such message is not existing.");
return new ResponseEntity<String>(
"Unable to delete a message with ID " + id + " since such message is not existing.\n",
HttpStatus.NOT_FOUND);
}
} catch (CannotCreateTransactionException e) {
return new ResponseEntity<String>("Check your database connection parameters.\n" + e.toString(),
HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
log.error("Exception caught. " + e.toString());
return new ResponseEntity<String>(e.toString(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Override
public ResponseEntity<String> getMessageById(int id) {
try {
return new ResponseEntity<String>(
messageService.getDataFromMessageEntity(messageService.getMessageById(id)), HttpStatus.OK);
} catch (NullPointerException e) {
log.debug("Message with ID " + id + " isnt exeisting yet");
return new ResponseEntity<String>("Message with ID " + id + " isnt exeisting yet", HttpStatus.NOT_FOUND);
} catch (CannotCreateTransactionException e) {
log.error("Wrong database connection parameters. " + e.toString());
return new ResponseEntity<String>("Check your database connection parameters.\n" + e.toString(),
HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
log.error("Exception caught. " + e.toString());
return new ResponseEntity<String>(e.toString(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
|
package com.app.gamaacademy.cabrasdoagrest.bankline.dtos;
import com.app.gamaacademy.cabrasdoagrest.bankline.models.TipoOperacao;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PlanoContaDTO {
private Integer id = 0;
private String nome;
private TipoOperacao tipo;
}
|
package lib.game.gui;
import static org.lwjgl.opengl.GL11.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import graphics.Color3f;
import lib.game.RenderUtils;
import lib.text.TextRenderer;
import math.geom.Point2i;
import math.geom.Rectangle;
public abstract class TextComponent extends Component {
protected static int borderWidth = 10;
protected static int paddingy = 3;
protected String text = "";
protected int textLength;
protected static int fontSize = 10;
protected static double fontRatio = 1.5;
protected TextRenderer tr;
public TextComponent(Rectangle bounds) {
super(bounds);
try {
tr = new TextRenderer(new File("res/font.png"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public TextComponent(String text, Point2i pos) {
this(new Rectangle());
this.text = text;
this.textLength = text.length(); //chars
int textLength = fontSize * text.length(); //pixels
int textHeight = (int) ((double) fontSize * fontRatio);
this.setBounds(new Rectangle(pos, textLength + 2*borderWidth, textHeight + 2*borderWidth));
}
public TextComponent(int chars, Point2i pos) {
this(new Rectangle());
this.textLength = chars; //in characters
int textLength = fontSize * chars; //in pixels
int textHeight = (int) ((double) fontSize * fontRatio);
this.setBounds(new Rectangle(pos, textLength + 2*borderWidth, textHeight + 2*borderWidth));
}
public TextComponent setText(String text) {
this.text = text;
if(text.length() > textLength) textLength = text.length();
return this;
}
public TextComponent setTextColor(Color3f c) {
this.textColor = c;
return this;
}
public TextComponent setFontSize(int fontSize) {
TextComponent.fontSize = fontSize;
int textLength = fontSize * text.length();
int textHeight = (int) ((double) fontSize * fontRatio);
return (TextComponent) this.setBounds(new Rectangle(bounds.getp1(), textLength + 2*TextComponent.borderWidth, textHeight + 2*borderWidth));
}
public TextComponent setTextLength(int chars) {
this.textLength = chars;
int textLength = fontSize * chars;
int textHeight = (int) ((double) fontSize * fontRatio);
return (TextComponent) this.setBounds(new Rectangle(bounds.getp1(), textLength + 2*borderWidth, textHeight + 2*borderWidth));
}
public String getText() {
return text;
}
@Override
public void render() {
RenderUtils.applyColor(bgColor);
glBegin(GL_QUADS); {
if(hasTexture) glTexCoord2f(0.0f, 0.0f); glVertex2i(super.bounds.getp1().x, super.bounds.getp1().y);
if(hasTexture) glTexCoord2f(1.0f, 0.0f); glVertex2i(super.bounds.getp2().x, super.bounds.getp1().y);
if(hasTexture) glTexCoord2f(1.0f, 1.0f); glVertex2i(super.bounds.getp2().x, super.bounds.getp2().y);
if(hasTexture) glTexCoord2f(0.0f, 1.0f); glVertex2i(super.bounds.getp1().x, super.bounds.getp2().y);
} glEnd();
RenderUtils.applyColor(borderColor);
glBegin(GL_LINES); {
glVertex2i(super.bounds.getp1().x, super.bounds.getp1().y);
glVertex2i(super.bounds.getp2().x, super.bounds.getp1().y);
glVertex2i(super.bounds.getp2().x, super.bounds.getp1().y);
glVertex2i(super.bounds.getp2().x, super.bounds.getp2().y);
glVertex2i(super.bounds.getp2().x, super.bounds.getp2().y);
glVertex2i(super.bounds.getp1().x, super.bounds.getp2().y);
glVertex2i(super.bounds.getp1().x, super.bounds.getp2().y);
glVertex2i(super.bounds.getp1().x, super.bounds.getp1().y);
} glEnd();
RenderUtils.applyColor(textColor);
Point2i textStart = new Point2i(bounds.getp1().x + borderWidth, bounds.getp1().y + borderWidth);
glPushMatrix();
tr.renderText(text, textStart, fontSize, (int) ((double)fontSize * fontRatio));
glPopMatrix();
}
@Override
public abstract void onClick(Point2i pos, int button);
@Override
public abstract void onMouseMove(Point2i pos);
@Override
public abstract void onKeyDown(Key key);
@Override
public abstract void onKeyUp(Key key);
}
|
package cn.stormbirds.expressDelivery.service.impl;
import cn.stormbirds.expressDelivery.entity.SysRole;
import cn.stormbirds.expressDelivery.mapper.SysRoleMapper;
import cn.stormbirds.expressDelivery.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 权限列表 服务实现类
* </p>
*
* @author stormbirds
* @since 2019-09-09
*/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
}
|
package com.mysql.cj.conf;
import com.mysql.cj.Messages;
import com.mysql.cj.exceptions.ExceptionFactory;
import com.mysql.cj.exceptions.ExceptionInterceptor;
import com.mysql.cj.exceptions.PropertyNotModifiableException;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.naming.RefAddr;
import javax.naming.Reference;
public abstract class AbstractRuntimeProperty<T> implements RuntimeProperty<T>, Serializable {
private static final long serialVersionUID = -3424722534876438236L;
private PropertyDefinition<T> propertyDefinition;
protected T value;
protected T initialValue;
protected boolean wasExplicitlySet = false;
private List<WeakReference<RuntimeProperty.RuntimePropertyListener>> listeners;
public AbstractRuntimeProperty() {}
protected AbstractRuntimeProperty(PropertyDefinition<T> propertyDefinition) {
this.propertyDefinition = propertyDefinition;
this.value = propertyDefinition.getDefaultValue();
this.initialValue = propertyDefinition.getDefaultValue();
}
public PropertyDefinition<T> getPropertyDefinition() {
return this.propertyDefinition;
}
public void initializeFrom(Properties extractFrom, ExceptionInterceptor exceptionInterceptor) {
String name = getPropertyDefinition().getName();
String alias = getPropertyDefinition().getCcAlias();
if (extractFrom.containsKey(name)) {
String extractedValue = (String)extractFrom.remove(name);
if (extractedValue != null) {
setValueInternal(extractedValue, exceptionInterceptor);
this.initialValue = this.value;
}
} else if (alias != null && extractFrom.containsKey(alias)) {
String extractedValue = (String)extractFrom.remove(alias);
if (extractedValue != null) {
setValueInternal(extractedValue, exceptionInterceptor);
this.initialValue = this.value;
}
}
}
public void initializeFrom(Reference ref, ExceptionInterceptor exceptionInterceptor) {
RefAddr refAddr = ref.get(getPropertyDefinition().getName());
if (refAddr != null) {
String refContentAsString = (String)refAddr.getContent();
if (refContentAsString != null) {
setValueInternal(refContentAsString, exceptionInterceptor);
this.initialValue = this.value;
}
}
}
public void resetValue() {
this.value = this.initialValue;
invokeListeners();
}
public boolean isExplicitlySet() {
return this.wasExplicitlySet;
}
public void addListener(RuntimeProperty.RuntimePropertyListener l) {
if (this.listeners == null)
this.listeners = new ArrayList<>();
boolean found = false;
for (WeakReference<RuntimeProperty.RuntimePropertyListener> weakReference : this.listeners) {
if (l.equals(weakReference.get())) {
found = true;
break;
}
}
if (!found)
this.listeners.add(new WeakReference<>(l));
}
public void removeListener(RuntimeProperty.RuntimePropertyListener listener) {
if (this.listeners != null)
for (WeakReference<RuntimeProperty.RuntimePropertyListener> wr : this.listeners) {
RuntimeProperty.RuntimePropertyListener l = wr.get();
if (l.equals(listener)) {
this.listeners.remove(wr);
break;
}
}
}
protected void invokeListeners() {
if (this.listeners != null)
for (WeakReference<RuntimeProperty.RuntimePropertyListener> wr : this.listeners) {
RuntimeProperty.RuntimePropertyListener l = wr.get();
if (l != null) {
l.handlePropertyChange(this);
continue;
}
this.listeners.remove(wr);
}
}
public T getValue() {
return this.value;
}
public T getInitialValue() {
return this.initialValue;
}
public String getStringValue() {
return (this.value == null) ? null : this.value.toString();
}
public void setValueInternal(String value, ExceptionInterceptor exceptionInterceptor) {
setValueInternal(getPropertyDefinition().parseObject(value, exceptionInterceptor), value, exceptionInterceptor);
}
public void setValueInternal(T value, String valueAsString, ExceptionInterceptor exceptionInterceptor) {
if (getPropertyDefinition().isRangeBased())
checkRange(value, valueAsString, exceptionInterceptor);
this.value = value;
this.wasExplicitlySet = true;
}
protected void checkRange(T val, String valueAsString, ExceptionInterceptor exceptionInterceptor) {}
public void setValue(T value) {
setValue(value, null);
}
public void setValue(T value, ExceptionInterceptor exceptionInterceptor) {
if (getPropertyDefinition().isRuntimeModifiable()) {
setValueInternal(value, null, exceptionInterceptor);
invokeListeners();
} else {
throw (PropertyNotModifiableException)ExceptionFactory.createException(PropertyNotModifiableException.class,
Messages.getString("ConnectionProperties.dynamicChangeIsNotAllowed", new Object[] { "'" + getPropertyDefinition().getName() + "'" }));
}
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\conf\AbstractRuntimeProperty.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com.base.crm.extension.check;
public class ExtentensionCheckInfo {
private Long id;
private String number;
private String netWork;
private String dateTime;
private int status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getNetWork() {
return netWork;
}
public void setNetWork(String netWork) {
this.netWork = netWork;
}
public String getDateTime() {
return dateTime;
}
public void setDateTime(String dateTime) {
this.dateTime = dateTime;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
|
package com.darkania.darkers.eventos;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.material.Door;
public class Refrigerador2 implements Listener {
boolean EventFixed = false;
@EventHandler
public void onPlayerInteract (PlayerInteractEvent event){
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)){
if(event.getHand() == EquipmentSlot.OFF_HAND)return;
Material P = event.getClickedBlock().getType();
Player pl = event.getPlayer();
if (P==Material.IRON_DOOR_BLOCK){
Door Puerta = (Door) event.getClickedBlock().getState().getData();
Block block = event.getClickedBlock();
if(Puerta.isTopHalf()){
Puerta= (Door)event.getClickedBlock().getRelative(0,-1,0).getState().getData();
block = event.getClickedBlock().getRelative(0,-1,0);
}
if(!isOpen(Puerta)){
openDoor(block,Puerta,pl);
}
if(isOpen(Puerta)){
closeDoor(block,Puerta,pl);
}
}
}
}
@SuppressWarnings("deprecation")
public boolean isOpen(Door puerta)
{
if(puerta.getData()>4)return true;
else return false;
}
@SuppressWarnings("deprecation")
public void openDoor(Block block, Door puerta, Player p)
{
if(puerta.getData()<4)
{
block.setData((byte) (puerta.getData()+4));
p.playSound(p.getLocation(), Sound.valueOf("BLOCK_IRON_DOOR_OPEN"), 2.0F, 0.0F);
}
}
@SuppressWarnings("deprecation")
public void closeDoor(Block block, Door puerta, Player p)
{
if(puerta.getData()>4)
{
block.setData((byte)(puerta.getData()-4));
p.playSound(p.getLocation(), Sound.valueOf("BLOCK_IRON_DOOR_CLOSE"), 2.0F, 0.0F);
}
}
}
|
/*
* Copyright 2009 Kjetil Valstadsve
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vanadis.osgi;
import vanadis.common.io.Location;
import vanadis.core.properties.PropertySet;
import java.net.URI;
import java.util.Collection;
/**
* Adapter class for implementing contexts.
*/
public class ContextAdapter implements Context {
@Override
public String getName() {
throw new UnsupportedOperationException();
}
@Override
public URI getHome() {
throw new UnsupportedOperationException();
}
@Override
public URI getRepo() {
throw new UnsupportedOperationException();
}
@Override
public Location getLocation() {
throw new UnsupportedOperationException();
}
@Override
public <T> Registration<T> register(T service) {
return register(service, (Class<T>) service.getClass());
}
@Override
public <T, S extends T> Registration<T> register(S service, Class<T> serviceInterface) {
return register(service, ServiceProperties.create(serviceInterface));
}
@Override
public <T> Registration<T> register(T service, ServiceProperties<T> serviceProperties) {
throw new UnsupportedOperationException();
}
@Override
public <T> void addContextListener(Class<T> serviceInterface, ContextListener<T> listener, Filter filter) {
throw new UnsupportedOperationException();
}
@Override
public <T> void addContextListener(Class<T> serviceInterface,
ContextListener<T> listener,
Filter filter,
boolean rewind) {
throw new UnsupportedOperationException();
}
@Override
public <T> void removeContextListener(ContextListener<T> contextListener) {
throw new UnsupportedOperationException();
}
@Override
public Reference<?> getSingleReference(String serviceInterfaceName, Filter filter) {
throw new UnsupportedOperationException();
}
@Override
public <T> Reference<T> getSingleReference(Class<T> serviceInterface, Filter filter) {
throw new UnsupportedOperationException();
}
@Override
public Reference<?> getReference(String serviceInterfaceName, Filter filter) {
throw new UnsupportedOperationException();
}
@Override
public <T> Reference<T> getReference(Class<T> serviceInterface, Filter filter) {
throw new UnsupportedOperationException();
}
@Override
public <T> Reference<T> getReference(Class<T> serviceInterface) {
throw new UnsupportedOperationException();
}
@Override
public Reference<?> getReference(String serviceInterfaceName) {
throw new UnsupportedOperationException();
}
@Override
public <T> Collection<Reference<T>> getReferences(Class<T> serviceInterface) {
return getReferences(serviceInterface, null);
}
@Override
public <T> Collection<Reference<T>> getReferences(Class<T> serviceInterface, Filter filter) {
throw new UnsupportedOperationException();
}
@Override
public Collection<Reference<?>> getReferences(String serviceInterfaceName) {
return getReferences(serviceInterfaceName, null);
}
@Override
public Collection<Reference<?>> getReferences(String serviceInterfaceName, Filter filter) {
throw new UnsupportedOperationException();
}
@Override
public String getProperty(String property) {
throw new UnsupportedOperationException();
}
@Override
public URI getResource(String location) {
throw new UnsupportedOperationException();
}
@Override
public URI getEntry(String location) {
throw new UnsupportedOperationException();
}
@Override
public PropertySet getPropertySet() {
throw new UnsupportedOperationException();
}
@Override
public final <T> Mediator<T> createMediator(Class<T> serviceInterface, MediatorListener<T> listener) {
return createMediator(serviceInterface, null, listener);
}
@Override
public <T> Mediator<T> createMediator(Class<T> serviceInterface, Filter filter, MediatorListener<T> listener) {
throw new UnsupportedOperationException();
}
@Override
public BundleMediator createBundleMediator(BundleMediatorListener bundleMediatorListener) {
throw new UnsupportedOperationException();
}
@Override
public <T> T getPersistentServiceProxy(Class<T> serviceInterface) {
return getPersistentServiceProxy(serviceInterface, null);
}
@Override
public <T> T getPersistentServiceProxy(Class<T> serviceInterface, Filter filter) {
throw new UnsupportedOperationException();
}
@Override
public ServiceProxyFactory getServiceProxyFactory() {
throw new UnsupportedOperationException();
}
@Override
public void closePersistentServiceProxy(Object service) {
throw new UnsupportedOperationException();
}
@Override
public <T> T getServiceProxy(Class<T> serviceInterface) {
return getServiceProxy(serviceInterface, null);
}
@Override
public <T> T getServiceProxy(Class<T> serviceInterface, Filter filter) {
throw new UnsupportedOperationException();
}
}
|
package versuch_3.vorbereitung;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by Marvin Kirsch on 25.11.2016.
* Matrikelnr.: 11118687
*/
public class Hashwert {
public void main(String args[]) throws IOException {
while(true) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Geben sie eine Zeichenkette ein: ");
String s = in.readLine();
System.out.println("Geben sie einen Wert fuer die Konstante m ein: ");
int m = Integer.parseInt(in.readLine());
System.out.println("Der Hashwert betraegt: " + hashwert(m, s));
String antwort;
do {
System.out.println("Moechten sie das Programm erneut starten ? y/n");
antwort = in.readLine();
} while(!(antwort.equals("y") || antwort.equals("n")));
if(antwort.equals("n")) {
return;
}
}
}
public int hashwert(int m, String s) {
int h = 0;
for (int i = 0; i < s.length(); i++) {
h += (int) s.charAt(i);
}
return h % m;
}
}
|
package com.a3live.cacanindin.artemio.medcentral;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final int MEDS = 0;
private static final int SEFFECTS = 1;
private static final int INTERS = 2;
private Fragment[] fragments = new Fragment[3];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction tempTrans = getFragmentManager().beginTransaction();
fragments[MEDS] = getFragmentManager().findFragmentById(R.id.meds);
fragments[SEFFECTS] = getFragmentManager().findFragmentById(R.id.seffects);
fragments[INTERS] = getFragmentManager().findFragmentById(R.id.inters);
for (int i = 0; i < fragments.length; i++) {
tempTrans.hide(fragments[i]);
}
tempTrans.commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// // .setAction("Action", null).show();
//
// }
// });
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_meds) {
transFragment(fragments[MEDS]);
}
else if (id == R.id.nav_seffects) {
transFragment(fragments[SEFFECTS]);
}
else if (id == R.id.nav_inters) {
transFragment(fragments[INTERS]);
}
else if (id == R.id.nav_share) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void transFragment(Fragment tempFrag) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment newInstance = recreateFragment(tempFrag);
ft.replace(R.id.frag_layout, newInstance);
ft.addToBackStack(null);
ft.commit();
}
private Fragment recreateFragment(Fragment tempFrag)
{
try {
Fragment.SavedState savedState = getFragmentManager().saveFragmentInstanceState(tempFrag);
Fragment newInstance = tempFrag.getClass().newInstance();
newInstance.setInitialSavedState(savedState);
return newInstance;
}
catch (Exception e) // InstantiationException, IllegalAccessException
{
throw new RuntimeException("Cannot reinstantiate fragment " + tempFrag.getClass().getName(), e);
}
}
}
|
import org.junit.Before;
import org.junit.Test;
import java.io.PrintStream;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
/**
* Created by egalperi on 6/18/15.
*/
public class PlayerTest {
private PrintStream printStream;
private Board board;
private PlayerInput playerInput;
private String name;
@Before
public void setup() {
playerInput = mock(PlayerInput.class);
printStream = mock(PrintStream.class);
board = mock(Board.class);
name = "Player 1";
}
@Test
public void shouldMakeMoveOnBoardWhenMoving() {
Player player = new Player("Player 1", "X", board, playerInput, printStream);
when(playerInput.getPlayerMove(name)).thenReturn(3);
player.move();
verify(board).addMove(3, "X");
}
}
|
package uo.sdi.rest.services;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import uo.sdi.dto.rest.RestClientCategory;
import uo.sdi.dto.rest.RestClientTask;
@Path("/TaskServiceRs")
public interface TaskServiceRest {
@GET
@Path("/login")
@Produces(MediaType.APPLICATION_JSON)
public Long login(@HeaderParam("Authorization") String authentication);
@POST
@Path("/users/{userId}/categories/{catId}/tasks")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public RestClientTask createTask(@PathParam("userId") Long userId,
@PathParam("catId") Long catId,
@HeaderParam("Authorization") String authorization, RestClientTask task);
@GET
@Path("/users/{userId}/categories")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<RestClientCategory> findCategoriesByUserId(
@PathParam("userId") Long userId,
@HeaderParam("Authorization") String authentication);
@PUT
@Path("/users/{userId}/tasks/{taskId}")
public void markTaskAsFinished(@PathParam("userId") Long userId,
@PathParam("taskId") Long taskId,
@HeaderParam("Authorization") String authentication);
@GET
@Path("/users/{userId}/categories/{catId}/tasks")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<RestClientTask> findTasksByCategoryId(@PathParam("userId") Long userId,
@PathParam("catId") Long catId,
@HeaderParam("Authorization") String authentication);
}
|
package com.weique.commonres.adapter;
import com.chad.library.adapter.base.BaseProviderMultiAdapter;
import com.chad.library.adapter.base.module.LoadMoreModule;
import com.chad.library.adapter.base.provider.BaseItemProvider;
import com.google.gson.Gson;
import com.jess.arms.http.imageloader.ImageLoader;
import com.weique.commonres.base.commonbean.RecordsBean;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* Provider adapter
*/
public class ProviderMultiAdapter extends BaseProviderMultiAdapter<RecordsBean> implements LoadMoreModule {
ImageLoader mImageLoader;
Gson gson;
public ProviderMultiAdapter() {
}
public ProviderMultiAdapter( ImageLoader mImageLoader, Gson gson) {
this.mImageLoader = mImageLoader;
this.gson = gson;
}
public ImageLoader getmImageLoader() {
return mImageLoader;
}
public void setmImageLoader(ImageLoader mImageLoader) {
this.mImageLoader = mImageLoader;
}
public Gson getGson() {
return gson;
}
public void setGson(Gson gson) {
this.gson = gson;
}
public void addItemProvider(List<? extends BaseItemProvider> list) {
for (BaseItemProvider provider : list) {
addItemProvider(provider);
}
}
/**
* 自行根据数据、位置等内容,返回 item 类型
*
* @param data
* @param position
* @return
*/
@Override
protected int getItemType(@NotNull List<? extends RecordsBean> data, int position) {
return data.get(position).getParamtype();
}
}
|
package com.example.demo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.model.Answer;
import com.example.demo.repository.QuestionRepository;
@SpringBootTest
class DemoApplicationTests {
@Test
void ProbarBot() {
Page<Answer> Expected = "No";
Pageable Expected;
Assertions.assertEquals(Expected,Answer.findByQuestionId(5,Expected));
}
}
|
package boj;
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.Stack;
import java.util.StringTokenizer;
public class BOJ_2644_촌수계산 {
private static int c;
private static int N;
private static int result = -1;
private static List<Integer>[] graph;
private static boolean[] visited;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
N = Integer.parseInt(br.readLine());
graph = new ArrayList[N+1];
visited = new boolean[N+1];
for (int i = 1; i <= N; i++) {
graph[i]= new ArrayList<>();
}
st = new StringTokenizer(br.readLine());
int S = Integer.parseInt(st.nextToken());
int E = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(br.readLine());
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
graph[a].add(b);
graph[b].add(a);
}
//System.out.println(Arrays.toString(graph));
dfs(S,E);
System.out.println(result);
}
public static void dfs(int d, int end) {
visited[d] =true;
if(d == end) {
result = c;
return;
}
List<Integer> childs = graph[d];
for (int i = 0; i < childs.size(); i++) {
Integer child = childs.get(i);
if(!visited[child]) {
c++;
dfs(child, end);
c--;
}
}
}
}
|
package com.es.phoneshop.model.product.exceptions;
public class OutOfStockException extends Exception {
private int maxStock;
public OutOfStockException(int maxStock) {
this.maxStock = maxStock;
}
@Override
public String getMessage() {
return "Out of stock. Max stock is " + this.getMaxStock();
}
public int getMaxStock() {
return maxStock;
}
}
|
package com.smxknife.java2.thread.thread._03yield;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author smxknife
* 2019/10/11
*/
public class _Run {
public static void main(String[] args) {
ThreadGroup group = new ThreadGroup("MyGroup");
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 2; i++) {
Thread thread = new Thread(group, () -> {
while (true) {
System.out.println(Thread.currentThread().getName() + " - yield");
Thread.yield();
System.out.println(Thread.currentThread().getName() + " activeCount: " + group.activeCount());
}
}, "th-" + i);
executorService.execute(thread);
}
}
}
|
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class TCPServer {
public static final int PORT = 12345;
public static void main(String[] args) {
try {
InetSocketAddress bindAddress = new InetSocketAddress(PORT);
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(bindAddress);
serverSocketChannel.configureBlocking(true);
System.out.println("Listening on port: " + PORT);
while (true) {
SocketChannel socket = serverSocketChannel.accept();
SocketAddress address = socket.socket().getRemoteSocketAddress();
System.out.println("Accepted connection from PVA client: " + address);
socket.socket().setTcpNoDelay(true);
socket.socket().setKeepAlive(true);
ByteBuffer msg = ByteBuffer.wrap("from Server".getBytes());
socket.write(msg);
System.out.println("Message sent, sleeping for 5s.");
Thread.sleep(5000);
socket.close();
System.out.println("Connection closed.");
}
} catch (Throwable th) {
th.printStackTrace();
}
}
}
|
import java.util.Scanner;
public class ComputeFibonacci {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an index for a Fibonacci number: ");
int index = input.nextInt();
System.out.println("The Fibonacci number at index " + index + " is " + fib(index));
input.close();
}
public static long fib(long index) {
return fibo(index, 1); //memory only needs to store last 2 numbers?
}
private static long fibo(long index, long sum){
if (index == 0){ // Base case
return 0;
} else if (index == 1){ // Base case
return 1;
} else{
return fibo(index - 1, sum + index) + fibo(index - 2, sum + index);
}
}
}
|
package com.hp.service;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.hp.dto.AcRepairFormDatadto;
import com.hp.entity.AcRepairFormEntity;
@Component
public class ConverterService {
@Autowired
private ModelMapper modelMapper;
public AcRepairFormDatadto convertToDto(AcRepairFormEntity acRepairFormEntity) {
return modelMapper.map(acRepairFormEntity, AcRepairFormDatadto.class);
}
}
|
package com.example.Service;
import com.example.Bean.User;
import com.example.Dao.Userdao;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class Modifypass extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter printWriter = response.getWriter();
Object name = request.getSession().getAttribute("username");
String password = request.getParameter("password");
Userdao userdao = new Userdao();
boolean flag = userdao.Modifypass(name.toString(),password);
if (flag)
printWriter.println("修改密码成功");
else {
printWriter.println("修改失败");
printWriter.println( name);
}
}
}
|
/*Check if a graph has an ordering of vertices that is a path and a topological sort*/
import java.io.*;
import java.util.*;
public class TopoPath
{
boolean [][] adjMatrix;
// converts text file's graph into an adjacency matrix
public TopoPath(String filename) throws IOException
{
try
{
Scanner in = new Scanner(new File(filename));
int numVertices = in.nextInt();
adjMatrix = new boolean [numVertices][numVertices];
int numEdges;
for (int i = 0 ; i < numVertices ; i++)
{
// grab first integer of each line
numEdges = in.nextInt();
// initializes matrix based on the adjacency list given
for (int j = 0 ; j < numEdges ; j++)
adjMatrix[i][in.nextInt()-1] = true;
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static boolean hasTopoPath(String filename) throws IOException
{
TopoPath t = new TopoPath(filename);
return t.checkTopoPath();
}
// from Webcourses
private boolean checkTopoPath()
{
int [] indegree = new int[adjMatrix.length];
int numNextPossibleVertices = 0;
int numVerticesVisited = 0;
int currentVertex;
Queue<Integer> queue = new ArrayDeque<Integer>();
// determine indegree for each vertex
for (int i = 0; i < adjMatrix.length; i++)
for (int j = 0; j < adjMatrix.length; j++)
indegree[j] += (adjMatrix[i][j] ? 1 : 0);
// vertices with no incoming edges are added to the queue
for (int i = 0; i < adjMatrix.length; i++)
if (indegree[i] == 0)
{
queue.add(i);
numNextPossibleVertices++;
}
// more than one starting point means no path possible
if (numVerticesAdded != 1)
return false;
while (!queue.isEmpty())
{
numVerticesVisited++;
numNextPossibleVertices = 0;
// all vertices visited
if (numVerticesVisited == adjMatrix.length)
return true;
// pull off next vertex in path
currentVertex = queue.remove();
// if current vertex is last edge to next vertex, add next vertex to queue
// otherwise, next vertex's edge count is decremented by 1
for (int i = 0; i < adjMatrix.length; i++)
if (adjMatrix[currentVertex][i] && --indegree[i] == 0)
{
queue.add(i);
numNextPossibleVertices++;
}
// all vertices (except last) should lead to exactly 1 vertex
if (numNextPossibleVertices != 1)
return false;
}
// did not reach all vertices in graph
return false;
}
}
|
/*
* Copyright (C) 2017 GetMangos
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package eu.mangos.characters.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author GetMangos
*/
@Entity
@Table(name = "instance_reset")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "InstanceReset.findAll", query = "SELECT i FROM InstanceReset i"),
@NamedQuery(name = "InstanceReset.findByMapid", query = "SELECT i FROM InstanceReset i WHERE i.mapid = :mapid"),
@NamedQuery(name = "InstanceReset.findByResettime", query = "SELECT i FROM InstanceReset i WHERE i.resettime = :resettime")})
public class InstanceReset implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
private Integer mapid;
@Basic(optional = false)
private long resettime;
public InstanceReset() {
}
public InstanceReset(Integer mapid) {
this.mapid = mapid;
}
public InstanceReset(Integer mapid, long resettime) {
this.mapid = mapid;
this.resettime = resettime;
}
public Integer getMapid() {
return mapid;
}
public void setMapid(Integer mapid) {
this.mapid = mapid;
}
public long getResettime() {
return resettime;
}
public void setResettime(long resettime) {
this.resettime = resettime;
}
@Override
public int hashCode() {
int hash = 0;
hash += (mapid != null ? mapid.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 InstanceReset)) {
return false;
}
InstanceReset other = (InstanceReset) object;
if ((this.mapid == null && other.mapid != null) || (this.mapid != null && !this.mapid.equals(other.mapid))) {
return false;
}
return true;
}
@Override
public String toString() {
return "eu.mangos.characters.model.InstanceReset[ mapid=" + mapid + " ]";
}
}
|
package com.lab3;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class C extends Thread{
static Lock lock = new ReentrantLock();
static Condition condition = lock.newCondition();
@Override
public void run() {
try{
for (int i = 0; i < 5; i++) {
lock.lock();
if(A.flag==0){
A.conditionA.signalAll();
condition.await();
}
if (MyData.getAchar() < MyData.getBchar()) MyData.addApoint(2);
else if (MyData.getAchar() > MyData.getBchar()) MyData.addBpoint(2);
else {
MyData.addApoint(1);
MyData.addBpoint(1);
}
System.out.println(i+1 + " " + MyData.getAsleepTime() + " " + MyData.getAchar() + " " + MyData.getaPoint() + " " + MyData.getBsleepTime() + " " + MyData.getBchar() + " " + MyData.getbPoint());
if(A.i<4){
A.conditionA.signalAll();
condition.await();
}
lock.unlock();
}
if (MyData.getaPoint() > MyData.getbPoint()) {
System.out.println("A is the winner!!!");
} else if (MyData.getaPoint() < MyData.getbPoint()) {
System.out.println("B is the winner!!!");
} else
System.out.println("None is the winner!!!");
}catch (Exception e){
e.printStackTrace();
}
}
}
|
package com.avogine.junkyard.scene;
import java.util.HashMap;
import java.util.Map;
import com.avogine.junkyard.scene.entity.EntityComponent;
public class ComponentMap extends HashMap<Class<?>, EntityComponent> {
private static final long serialVersionUID = 1L;
public ComponentMap(Map<Class<?>, EntityComponent> components) {
super(components);
}
public <T> T getAs(Class<T> key) {
if(!containsKey(key)) {
return null;
}
EntityComponent component = get(key);
if(key.isAssignableFrom(component.getClass())) {
return key.cast(component);
}
throw new IllegalArgumentException("Somehow the object: " + key.getName() + " is not assignable from: " + component.getClass().getName());
}
}
|
package me.themgrf.skooblock.island.roles;
import me.themgrf.skooblock.island.permissions.IslandMemberPermissionSet;
public class IslandMemberModRole extends IslandMemberRole {
public IslandMemberModRole() {
super("mod", "Mod", new IslandMemberPermissionSet(
true,
true,
true,
true,
true,
true,
true,
false,
false,
false,
true,
false,
true));
}
}
|
/*
* Created on Jan 4, 2012
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package it.usi.xframe.xas.bfimpl.sms.providers.acotel;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author US00081
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class AcotelPageDestination {
/* DEPRECATED 2016.07.18
private static Log log = LogFactory.getLog(AcotelPageDestination.class);
private Pattern phoneNumberPat = null;
private String pageUrl = null;
private String description = null;
public AcotelPageDestination(String phonePattern, String url, String desc)
throws PatternSyntaxException {
phoneNumberPat = Pattern.compile(phonePattern);
pageUrl = url;
description = desc;
log.debug("Acotel page destination ["+description+"]");
log.debug("Acotel page url ["+pageUrl+"]");
log.debug("Acotel phone number pattern ["+phoneNumberPat.pattern()+"]");
}
public boolean matches(String phoneNumber) {
Matcher m = phoneNumberPat.matcher( phoneNumber );
return m.matches();
}
public String getPageUrl() {
return pageUrl;
}
public String getDescription() {
return description;
}
*/
}
|
import java.util.Scanner;
public class MethodRecursion {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num=sc.nextInt();
System.out.println(recursion(num));
}
static int recursion(int num) {
if (num <= 2) {
return num;
}
else return num*recursion(num-1);
}
}
|
package com.zhouyi.business.core.dao;
import com.zhouyi.business.core.model.SysLogData;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
@Mapper
public interface SysLogDataMapper {
int deleteByPrimaryKey(String pkId);
int insert(SysLogData record);
int insertSelective(SysLogData record);
SysLogData selectByPrimaryKey(String pkId);
int updateByPrimaryKeySelective(SysLogData record);
int updateByPrimaryKey(SysLogData record);
/**
* 根据条件分页查询数据日志
* @param conditions
* @return
*/
List<SysLogData> listSysLogDataByConditions(Map<String,Object> conditions);
/**
* 根据条件查询总记录数
* @param conditions
* @return
*/
int getSysLogDataCountByConditions(Map<String,Object> conditions);
}
|
package com.cybx.salesorder.dao;
import java.util.List;
import com.cybx.salesorder.model.Salesorder;
public interface SalesorderDao {
int insert(Salesorder order);
List<Salesorder> getSalesorder(String status);
}
|
package com.gtfs.service.interfaces;
import java.io.Serializable;
import java.util.List;
import com.gtfs.bean.UserRoleRlns;
public interface UserRoleRlnsService extends Serializable{
List<UserRoleRlns> findActiveUserRoleByUserId(Long userId);
Long insertIntoUserRoleRlns(UserRoleRlns userRoleRlns);
Integer deleteFromUserRoleRlnsByRoleIdAndUserId(Long roleId,Long userid, Long loginUserId);
}
|
package cn.creable.android.demo;
import cn.creable.gridgis.display.ISymbol;
import cn.creable.gridgis.display.UniqueValueRenderer;
import cn.creable.gridgis.geodatabase.IFeature;
import cn.creable.gridgis.shapefile.IShapefileLayer;
public class MyRenderer extends UniqueValueRenderer {
public int fieldIndex;
public String key;
private IShapefileLayer layer;
public MyRenderer(ISymbol arg0, IShapefileLayer layer) {
super(arg0, layer);
this.layer=layer;
}
@Override
public ISymbol getSymbolByFeature(IFeature ft) {
String[] values=ft.getValues();
if (values==null)
{
layer.loadFeatureAttribute(ft);
values=ft.getValues();
}
if (!ft.getValue(fieldIndex).equalsIgnoreCase(key)) return null;
return super.getSymbolByFeature(ft);
}
}
|
package com.ua;
import com.ua.domain.Order;
import com.ua.domain.Position;
import com.ua.ejb.OrdersManagerBean;
import com.ua.ejb.PositionsManagerBean;
import javafx.geometry.Pos;
import javax.ejb.EJB;
import javax.faces.bean.SessionScoped;
import javax.inject.Named;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
@Named
@SessionScoped
public class OrderBean implements Serializable {
private Order order;
private String name;
private int price;
private int quantity;
@EJB
private OrdersManagerBean ordersManagerBean;
@EJB
private PositionsManagerBean positionsManagerBean;
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public void createOrder(){
if(order == null){
order = ordersManagerBean.createOrder();
}
}
public void createPosition(){
positionsManagerBean.cretatePosition(name, price);
}
public List<Position> getPosition(){
return positionsManagerBean.getPosition();
}
public void addPosition(Position position){
if (order == null){
return;
}
ordersManagerBean.addOrder(position.getId(), order.getId(), 1);
}
public List<Position> getPositionInOrder(){
if(order == null){
return Collections.emptyList();
}
return ordersManagerBean.getPositionInOrder(order.getId());
}
}
|
package com.tencent.mm.plugin.sns.ui;
import com.tencent.mm.plugin.sns.ui.SnsAdNativeLandingPagesUI.18;
import com.tencent.mm.ui.widget.a.d.a;
class SnsAdNativeLandingPagesUI$18$2 implements a {
final /* synthetic */ 18 nTa;
SnsAdNativeLandingPagesUI$18$2(18 18) {
this.nTa = 18;
}
public final void onDismiss() {
SnsAdNativeLandingPagesUI.b(this.nTa.nSR);
}
}
|
package com.example.michal.booklisting;
import android.app.LoaderManager;
import android.content.Context;
import android.content.Loader;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/*
Main activity containing list view and search input on main action bar
Activity displays books relevant to submitted topic or info if no book was found
activity also displays round progress bar to indicate progress on slow internet connections
*/
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Book>> {
private String requestUrlPart1 = "https://www.googleapis.com/books/v1/volumes?q=";
private String requestUrlPart2 = "&maxResults=10";
private String submittedQuery;
private ArrayList<Book> books;
private BookArrayAdapter bookArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setting default welcoming message and empty list view
books = new ArrayList<>();
bookArrayAdapter = new BookArrayAdapter(this, books);
ListView listView = findViewById(R.id.book_info_list_view);
listView.setAdapter(bookArrayAdapter);
TextView textView = findViewById(R.id.empty_list_text_view);
textView.setText("Enter query to search for books.");
ProgressBar progressBar = findViewById(R.id.loading_books_progress);
progressBar.setVisibility(View.GONE);
}
/*
Handling menu action bar with search text input and implementing its listener
*/
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem search = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) search.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
/*
when user submits query to search list of found books is displayed
*/
@Override
public boolean onQueryTextSubmit(String s) {
submittedQuery = s;
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
/*
Checking for internet connection
*/
if (networkInfo != null && networkInfo.isConnected()){
getLoaderManager().restartLoader(0, null, MainActivity.this);
} else {
ProgressBar progressBar = findViewById(R.id.loading_books_progress);
progressBar.setVisibility(View.GONE);
TextView textView = findViewById(R.id.empty_list_text_view);
textView.setText("No internet connection.");
}
return true;
}
/*
Changing displayed books when user changes search query
*/
@Override
public boolean onQueryTextChange(String s) {
submittedQuery = s;
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()){
getLoaderManager().restartLoader(0, null, MainActivity.this);
} else {
ProgressBar progressBar = findViewById(R.id.loading_books_progress);
progressBar.setVisibility(View.GONE);
TextView textView = findViewById(R.id.empty_list_text_view);
textView.setText("No internet connection.");
}
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
/*
Methods handling loader which downloads data from internet
*/
//Creating new loader
@Override
public Loader<List<Book>> onCreateLoader(int i, Bundle bundle) {
return new BookLoader(MainActivity.this, requestUrlPart1 + submittedQuery + requestUrlPart2);
}
/*
Displaying downloaded book info or message if no data was found
*/
@Override
public void onLoadFinished(Loader<List<Book>> loader, List<Book> books) {
ProgressBar loadingEarthquakes = findViewById(R.id.loading_books_progress);
loadingEarthquakes.setVisibility(View.GONE);
if (books.isEmpty()){
TextView emptyListMessage = findViewById(R.id.empty_list_text_view);
emptyListMessage.setText("Sorry, but there's nothing to display");
} else {
TextView emptyListMessage = findViewById(R.id.empty_list_text_view);
emptyListMessage.setText("");
}
if (bookArrayAdapter!=null){
bookArrayAdapter.clear();
}
if (books!=null && !books.isEmpty()){
bookArrayAdapter.addAll(books);
}
}
@Override
public void onLoaderReset(Loader<List<Book>> loader) {
bookArrayAdapter.clear();
}
}
|
package com.example.callnetworkapi;
import android.app.Application;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
public class CallApiViewModel extends AndroidViewModel {
private ExecutorService executor;
private final MutableLiveData<Result<String>> _response = new MutableLiveData<>();
public LiveData<Result<String>> response = _response;
public CallApiViewModel(@NonNull Application application) {
super(application);
executor = ((CallApiApplication) application).executorService;
}
public void callNetworkApi(String input) {
/* String jsonBody = "{ username: \"" + username + "\", token: \"" + token + "\" }";*/
executor.execute(new Runnable() {
@Override
public void run() {
makeSynchronousNetworkRequest(input, new ResponseCallback<String>() {
@Override
public void onComplete(Result<String> result) {
_response.postValue(result);
}
});
}
});
}
public void makeSynchronousNetworkRequest(String jsonBody, ResponseCallback<String> callback) {
try {
URL url = new URL("https://jsonplaceholder.typicode.com/todos/5");
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("GET");
Log.d("TAG", httpConnection.getResponseCode() + "");
InputStream in = new BufferedInputStream(httpConnection.getInputStream());
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String read;
while ((read = br.readLine()) != null) {
//System.out.println(read);
sb.append(read);
}
br.close();
String response = sb.toString();
Result<String> result = new Result.Success<String>(response);
callback.onComplete(result);
} catch (Exception e) {
Result<String> errorResult = new Result.Error<String>(e);
callback.onComplete(errorResult);
}
}
interface ResponseCallback<T> {
void onComplete(Result<T> result);
}
}
|
/**
* FileName: SysUserService
* Author: Carty.Li
* Date: 2018/8/5 11:13
* Description: 用户
*/
package com.weixin.service;
import com.weixin.mapper.SysUserMapper;
import com.weixin.model.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 〈用户〉
*
* @author Administrator
* @create 2018/8/5
* @since 1.0.0
*/
@Service
public class SysUserService {
@Autowired
private SysUserMapper sysUserMapper;
/**
* <查询全部>
*
* @param
* @return java.util.List<com.weixin.model.SysUser>
* @author Lifeifei
* @date 2018/8/9 9:03
*/
public List<SysUser> selectAll(){
return sysUserMapper.selectAll();
}
}
|
// Generated from /home/manosetro/IdeaProjects/cql-parser/parser/Eql.g4 by ANTLR 4.5.3
package org.iptc.extra.core.eql.antlr;
import org.antlr.v4.runtime.tree.ParseTreeVisitor;
/**
* This interface defines a complete generic visitor for a parse tree produced
* by {@link EqlParser}.
*
* @param <T> The return type of the visit operation. Use {@link Void} for
* operations with no return type.
*/
public interface EqlVisitor<T> extends ParseTreeVisitor<T> {
/**
* Visit a parse tree produced by {@link EqlParser#prefixClause}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitPrefixClause(EqlParser.PrefixClauseContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#statement}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitStatement(EqlParser.StatementContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#booleanOp}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitBooleanOp(EqlParser.BooleanOpContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#searchClause}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitSearchClause(EqlParser.SearchClauseContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#commentClause}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitCommentClause(EqlParser.CommentClauseContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#referenceClause}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitReferenceClause(EqlParser.ReferenceClauseContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#referencedRule}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitReferencedRule(EqlParser.ReferencedRuleContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#ref}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitRef(EqlParser.RefContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#relation}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitRelation(EqlParser.RelationContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#modifierList}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitModifierList(EqlParser.ModifierListContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#modifier}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitModifier(EqlParser.ModifierContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#comparitor}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitComparitor(EqlParser.ComparitorContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#namedComparitor}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitNamedComparitor(EqlParser.NamedComparitorContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#comparitorSymbol}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitComparitorSymbol(EqlParser.ComparitorSymbolContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#modifierName}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitModifierName(EqlParser.ModifierNameContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#modifierValue}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitModifierValue(EqlParser.ModifierValueContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#searchTerm}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitSearchTerm(EqlParser.SearchTermContext ctx);
/**
* Visit a parse tree produced by {@link EqlParser#index}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitIndex(EqlParser.IndexContext ctx);
}
|
package domain;
// Generated Jan 20, 2010 12:31:25 AM by Hibernate Tools 3.2.1.GA
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Users generated by hbm2java
*/
@Entity
@Table(name="users"
,catalog="catalog"
)
public class User implements java.io.Serializable {
private int id;
private Grupa groups;
private String username;
private String firstname;
private String lastname;
private String password;
private String confirmpassword;
private String email;
private Date created;
private Date modified;
private int enabled;
private Set<Range> rangieses = new HashSet<Range>(0);
public User() {
}
public User(int id, Grupa groups, String username, String firstname, String lastname, String password, String email, Date created, Date modified, int enabled) {
this.id = id;
this.groups = groups;
this.username = username;
this.firstname = firstname;
this.lastname = lastname;
this.password = password;
this.email = email;
this.created = created;
this.modified = modified;
this.enabled = enabled;
}
public User(int id, Grupa groups, String username, String firstname, String lastname, String password, String email, Date created, Date modified, int enabled, Set<Range> rangieses) {
this.id = id;
this.groups = groups;
this.username = username;
this.firstname = firstname;
this.lastname = lastname;
this.password = password;
this.email = email;
this.created = created;
this.modified = modified;
this.enabled = enabled;
this.rangieses = rangieses;
}
@Id
@Column(name="id", unique=true, nullable=false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="group_id", nullable=false)
public Grupa getGroups() {
return this.groups;
}
public void setGroups(Grupa groups) {
this.groups = groups;
}
@Column(name="username", nullable=false)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name="firstname", nullable=false)
public String getFirstname() {
return this.firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
@Column(name="lastname", nullable=false)
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
@Column(name="password", nullable=false)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name="confirmpassword", nullable=false)
public String getConfirmpassword() {
return this.confirmpassword;
}
public void setConfirmpassword(String password) {
this.confirmpassword = password;
}
@Column(name="email", nullable=false)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name="created", nullable=false, length=19)
public Date getCreated() {
return this.created;
}
public void setCreated(Date created) {
this.created = created;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name="modified", nullable=false, length=19)
public Date getModified() {
return this.modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
@Column(name="enabled", nullable=false)
public int getEnabled() {
return this.enabled;
}
public void setEnabled(int enabled) {
this.enabled = enabled;
}
@ManyToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@JoinTable(name="usersrangies", catalog="catalog", joinColumns = {
@JoinColumn(name="user_id", nullable=false, updatable=false) }, inverseJoinColumns = {
@JoinColumn(name="range_id", nullable=false, updatable=false) })
public Set<Range> getRangieses() {
return this.rangieses;
}
public void setRangieses(Set<Range> rangieses) {
this.rangieses = rangieses;
}
}
|
package org.rebioma.server;
import java.lang.reflect.Method;
import org.rebioma.client.bean.Occurrence;
public class Script {
static String fields[] = new String[] { "id", "owner", "public_", "vettable",
"validated", "vetted", "tapirAccessible", "ownerEmail", "vettingError",
"validationError", "basisOfRecord", "yearCollected", "genus",
"specificEpithet", "decimalLatitude", "decimalLongitude",
"geodeticDatum", "coordinateUncertaintyInMeters", "dateLastModified",
"institutionCode", "collectionCode", "catalogNumber", "scientificName",
"globalUniqueIdentifier", "informationWithheld", "remarks",
"higherTaxon", "kingdom", "phylum", "class_", "order", "family",
"taxonRank"/*"infraspecificRank"*/, "infraspecificEpithet",
"authorYearOfScientificName", "nomenclaturalCode",
"identificationQualifer", "higherGeography", "continent", "waterBody",
"islandGroup", "island", "country", "stateProvince", "county",
"locality", "minimumElevationInMeters", "maximumElevationInMeters",
"minimumDepthInMeters", "maximumDepthInMeters", "collectingMethod",
"validDistributionFlag", "earliestDateCollected", "latestDateCollected",
"dayOfYear", "monthCollected", "dayCollected", "collector", "sex",
"lifeStage", "attributes", "imageUrl", "relatedInformation",
"catalogNumberNumeric", "identifiedBy", "dateIdentified",
"collectorNumber", "fieldNumber", "fieldNotes", "verbatimCollectingDate",
"verbatimElevation", "verbatimDepth", "preparations", "typeStatus",
"genBankNumber", "otherCatalogNumbers", "relatedCatalogedItems",
"disposition", "individualCount", "pointRadiusSpatialFit",
"verbatimCoordinates", "verbatimLatitude", "verbatimLongitude",
"verbatimCoordinateSystem", "georeferenceProtocol",
"georeferenceSources", "georeferenceVerificationStatus",
"georeferenceRemarks", "footprintWkt", "footprintSpatialFit",
"verbatimSpecies", "acceptedSpecies", "acceptedNomenclaturalCode",
"acceptedKingdom", "acceptedPhylum", "acceptedClass", "acceptedOrder",
"acceptedSuborder", "acceptedFamily", "acceptedSubfamily",
"acceptedGenus", "acceptedSubgenus", "acceptedSpecificEpithet",
"decLatInWgs84", "decLongInWgs84",
"adjustedCoordinateUncertaintyInMeters", "demelevation", "etpTotal2000",
"etpTotalfuture", "etpTotal1950", "geolStrech", "maxPerc2000",
"maxPercfuture", "maxPerc1950", "maxTemp2000", "maxTempfuture",
"maxtemp1950", "minPerc2000", "minPercfuture", "minPerc1950",
"minTemp2000", "minTempfuture", "minTemp1950", "pfc1950", "pfc1970",
"pfc1990", "pfc2000", "realMar2000", "realMarfuture", "realMar1950",
"realMat2000", "realMatfuture", "realMat1950", "wbpos2000",
"wbposfuture", "wbpos1950", "wbyear2000", "wbyearfuture", "wbyear1950" };
public static void main(String args[]) {
// Arrays.sort(fields);
// for (String field : fields) {
// String capField = (field.charAt(0) + "").toUpperCase()
// + field.substring(1, field.length());
// if (field.contains("_")) {
// capField = capField.substring(0, field.length() - 1);
// }
// System.out
// .println(" if (fieldName.equals(\""
// + capField
// + "\")) { \n"
// + "\tif (fieldValue.equals(\"----\")) {\n"
// + "\tmyOccurrence.set"
// + capField
// + "(\"\");\n"
// + "\t} else {\n"
// + "\tmyOccurrence.set"
// + capField
// + "(fieldValue);\n"
// + "\t}\n"
// + "\tcurrentChanges.remove(currentChanges.firstKey());\n"
// + "\tfieldName = currentChanges.firstEntry().getKey();\n"
// + "\tfieldValue = currentChanges.firstEntry().getValue().contents;\n"
// + "\t}");
// }
//
wah();
}
public static void wah() {
Class<Occurrence> c = Occurrence.class;
Method fields[] = c.getMethods();
for (Method field : fields) {
System.out.println(field.getName());
}
try {
System.out.println(c.getMethod("getBasisOfRecord", c));
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.campus.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
/**
* 考卷表
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class TestBean implements Serializable {
/**
* 考卷编号
*/
private Long testid;
/**
* 考卷名称
*/
private String testname;
/**
* 总分数
*/
private Double totalscore;
/**
* 通过分数
*/
private Double passscore;
/**
* 考试时长
*/
private Integer testtime;
/**
* 开始时间
*/
// @DateTimeFormat(pattern="yyyy-MM-dd HH:mm")
private Date starttime;
/**
* 结束时间
*/
private Date endtime;
/**
* 上传时间
*/
private Date updatetime = new Date();
/**
* 发布人
*/
private String testauthor;
/**
* 发布人编号
*/
private Long authorid;
/**
* 得分
*/
private Double score;
/**
* 客观分数
*/
private Double cscore;
/**
* 主观分数
*/
private Double qscore;
/**
* 学生考试时长
*/
private Long stesttime;
/**
* 学生考试结束时间
*/
private Date testendtime;
/**
* 主观rediskey
*/
private String qrediskey;
/**
* 客观rediskey
*/
private String crediskey;
/**
* 是否在考试时间
*/
private String testStatus;
/**
* 阅卷时需要的
*/
private String sname;
}
|
package javaAssesment1;
public class Question11 {
/*
* Write a Java program to print the following string in a specific format (see the output).
Sample Output
Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are
*/
public static void main(String[] args) {
String s = "Twinkle, twinkle, little star,\n" + " How I wonder what you are! \n"
+ " Up above the world so high, \n" + " Like a diamond in the sky. \n"
+ "Twinkle, twinkle, little star, \n" + " How I wonder what you are\n" + "";
System.out.println(s);
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.common.predicate;
import de.hybris.platform.servicelayer.exceptions.UnknownIdentifierException;
import de.hybris.platform.servicelayer.type.TypeService;
import java.util.function.Predicate;
import org.springframework.beans.factory.annotation.Required;
/**
* Predicate to test if a given type code maps to an existing composed type.
* <p>
* Returns <tt>TRUE</tt> if the composed type exists; <tt>FALSE</tt> otherwise.
* </p>
*/
public class TypeCodeExistsPredicate implements Predicate<String>
{
private TypeService typeService;
@Override
public boolean test(String target)
{
boolean result = true;
try
{
getTypeService().getComposedTypeForCode(target);
}
catch (final UnknownIdentifierException e)
{
result = false;
}
return result;
}
protected TypeService getTypeService()
{
return typeService;
}
@Required
public void setTypeService(TypeService typeService)
{
this.typeService = typeService;
}
}
|
package com.example.ComicToon.Models.RequestResponseModels;
public class GetRatingForm{
private String comicID;
public String getComicID() {
return this.comicID;
}
public void setComicID(String comicID) {
this.comicID = comicID;
}
}
|
package com.rc.portal.vo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.rc.app.framework.webapp.model.BaseModel;
public class TPromItemExample extends BaseModel{
protected String orderByClause;
protected List oredCriteria;
public TPromItemExample() {
oredCriteria = new ArrayList();
}
protected TPromItemExample(TPromItemExample example) {
this.orderByClause = example.orderByClause;
this.oredCriteria = example.oredCriteria;
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public List getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
}
public static class Criteria {
protected List criteriaWithoutValue;
protected List criteriaWithSingleValue;
protected List criteriaWithListValue;
protected List criteriaWithBetweenValue;
protected Criteria() {
super();
criteriaWithoutValue = new ArrayList();
criteriaWithSingleValue = new ArrayList();
criteriaWithListValue = new ArrayList();
criteriaWithBetweenValue = new ArrayList();
}
public boolean isValid() {
return criteriaWithoutValue.size() > 0
|| criteriaWithSingleValue.size() > 0
|| criteriaWithListValue.size() > 0
|| criteriaWithBetweenValue.size() > 0;
}
public List getCriteriaWithoutValue() {
return criteriaWithoutValue;
}
public List getCriteriaWithSingleValue() {
return criteriaWithSingleValue;
}
public List getCriteriaWithListValue() {
return criteriaWithListValue;
}
public List getCriteriaWithBetweenValue() {
return criteriaWithBetweenValue;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteriaWithoutValue.add(condition);
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
Map map = new HashMap();
map.put("condition", condition);
map.put("value", value);
criteriaWithSingleValue.add(map);
}
protected void addCriterion(String condition, List values, String property) {
if (values == null || values.size() == 0) {
throw new RuntimeException("Value list for " + property + " cannot be null or empty");
}
Map map = new HashMap();
map.put("condition", condition);
map.put("values", values);
criteriaWithListValue.add(map);
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
List list = new ArrayList();
list.add(value1);
list.add(value2);
Map map = new HashMap();
map.put("condition", condition);
map.put("values", list);
criteriaWithBetweenValue.add(map);
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return this;
}
public Criteria andIdEqualTo(Long value) {
addCriterion("id =", value, "id");
return this;
}
public Criteria andIdNotEqualTo(Long value) {
addCriterion("id <>", value, "id");
return this;
}
public Criteria andIdGreaterThan(Long value) {
addCriterion("id >", value, "id");
return this;
}
public Criteria andIdGreaterThanOrEqualTo(Long value) {
addCriterion("id >=", value, "id");
return this;
}
public Criteria andIdLessThan(Long value) {
addCriterion("id <", value, "id");
return this;
}
public Criteria andIdLessThanOrEqualTo(Long value) {
addCriterion("id <=", value, "id");
return this;
}
public Criteria andIdIn(List values) {
addCriterion("id in", values, "id");
return this;
}
public Criteria andIdNotIn(List values) {
addCriterion("id not in", values, "id");
return this;
}
public Criteria andIdBetween(Long value1, Long value2) {
addCriterion("id between", value1, value2, "id");
return this;
}
public Criteria andIdNotBetween(Long value1, Long value2) {
addCriterion("id not between", value1, value2, "id");
return this;
}
public Criteria andTargetIdIsNull() {
addCriterion("target_id is null");
return this;
}
public Criteria andTargetIdIsNotNull() {
addCriterion("target_id is not null");
return this;
}
public Criteria andTargetIdEqualTo(Long value) {
addCriterion("target_id =", value, "targetId");
return this;
}
public Criteria andTargetIdNotEqualTo(Long value) {
addCriterion("target_id <>", value, "targetId");
return this;
}
public Criteria andTargetIdGreaterThan(Long value) {
addCriterion("target_id >", value, "targetId");
return this;
}
public Criteria andTargetIdGreaterThanOrEqualTo(Long value) {
addCriterion("target_id >=", value, "targetId");
return this;
}
public Criteria andTargetIdLessThan(Long value) {
addCriterion("target_id <", value, "targetId");
return this;
}
public Criteria andTargetIdLessThanOrEqualTo(Long value) {
addCriterion("target_id <=", value, "targetId");
return this;
}
public Criteria andTargetIdIn(List values) {
addCriterion("target_id in", values, "targetId");
return this;
}
public Criteria andTargetIdNotIn(List values) {
addCriterion("target_id not in", values, "targetId");
return this;
}
public Criteria andTargetIdBetween(Long value1, Long value2) {
addCriterion("target_id between", value1, value2, "targetId");
return this;
}
public Criteria andTargetIdNotBetween(Long value1, Long value2) {
addCriterion("target_id not between", value1, value2, "targetId");
return this;
}
public Criteria andPriceIsNull() {
addCriterion("price is null");
return this;
}
public Criteria andPriceIsNotNull() {
addCriterion("price is not null");
return this;
}
public Criteria andPriceEqualTo(BigDecimal value) {
addCriterion("price =", value, "price");
return this;
}
public Criteria andPriceNotEqualTo(BigDecimal value) {
addCriterion("price <>", value, "price");
return this;
}
public Criteria andPriceGreaterThan(BigDecimal value) {
addCriterion("price >", value, "price");
return this;
}
public Criteria andPriceGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("price >=", value, "price");
return this;
}
public Criteria andPriceLessThan(BigDecimal value) {
addCriterion("price <", value, "price");
return this;
}
public Criteria andPriceLessThanOrEqualTo(BigDecimal value) {
addCriterion("price <=", value, "price");
return this;
}
public Criteria andPriceIn(List values) {
addCriterion("price in", values, "price");
return this;
}
public Criteria andPriceNotIn(List values) {
addCriterion("price not in", values, "price");
return this;
}
public Criteria andPriceBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("price between", value1, value2, "price");
return this;
}
public Criteria andPriceNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("price not between", value1, value2, "price");
return this;
}
public Criteria andLimitCountIsNull() {
addCriterion("limit_count is null");
return this;
}
public Criteria andLimitCountIsNotNull() {
addCriterion("limit_count is not null");
return this;
}
public Criteria andLimitCountEqualTo(Integer value) {
addCriterion("limit_count =", value, "limitCount");
return this;
}
public Criteria andLimitCountNotEqualTo(Integer value) {
addCriterion("limit_count <>", value, "limitCount");
return this;
}
public Criteria andLimitCountGreaterThan(Integer value) {
addCriterion("limit_count >", value, "limitCount");
return this;
}
public Criteria andLimitCountGreaterThanOrEqualTo(Integer value) {
addCriterion("limit_count >=", value, "limitCount");
return this;
}
public Criteria andLimitCountLessThan(Integer value) {
addCriterion("limit_count <", value, "limitCount");
return this;
}
public Criteria andLimitCountLessThanOrEqualTo(Integer value) {
addCriterion("limit_count <=", value, "limitCount");
return this;
}
public Criteria andLimitCountIn(List values) {
addCriterion("limit_count in", values, "limitCount");
return this;
}
public Criteria andLimitCountNotIn(List values) {
addCriterion("limit_count not in", values, "limitCount");
return this;
}
public Criteria andLimitCountBetween(Integer value1, Integer value2) {
addCriterion("limit_count between", value1, value2, "limitCount");
return this;
}
public Criteria andLimitCountNotBetween(Integer value1, Integer value2) {
addCriterion("limit_count not between", value1, value2, "limitCount");
return this;
}
public Criteria andSaleCountIsNull() {
addCriterion("sale_count is null");
return this;
}
public Criteria andSaleCountIsNotNull() {
addCriterion("sale_count is not null");
return this;
}
public Criteria andSaleCountEqualTo(Integer value) {
addCriterion("sale_count =", value, "saleCount");
return this;
}
public Criteria andSaleCountNotEqualTo(Integer value) {
addCriterion("sale_count <>", value, "saleCount");
return this;
}
public Criteria andSaleCountGreaterThan(Integer value) {
addCriterion("sale_count >", value, "saleCount");
return this;
}
public Criteria andSaleCountGreaterThanOrEqualTo(Integer value) {
addCriterion("sale_count >=", value, "saleCount");
return this;
}
public Criteria andSaleCountLessThan(Integer value) {
addCriterion("sale_count <", value, "saleCount");
return this;
}
public Criteria andSaleCountLessThanOrEqualTo(Integer value) {
addCriterion("sale_count <=", value, "saleCount");
return this;
}
public Criteria andSaleCountIn(List values) {
addCriterion("sale_count in", values, "saleCount");
return this;
}
public Criteria andSaleCountNotIn(List values) {
addCriterion("sale_count not in", values, "saleCount");
return this;
}
public Criteria andSaleCountBetween(Integer value1, Integer value2) {
addCriterion("sale_count between", value1, value2, "saleCount");
return this;
}
public Criteria andSaleCountNotBetween(Integer value1, Integer value2) {
addCriterion("sale_count not between", value1, value2, "saleCount");
return this;
}
public Criteria andPidIsNull() {
addCriterion("pid is null");
return this;
}
public Criteria andPidIsNotNull() {
addCriterion("pid is not null");
return this;
}
public Criteria andPidEqualTo(Long value) {
addCriterion("pid =", value, "pid");
return this;
}
public Criteria andPidNotEqualTo(Long value) {
addCriterion("pid <>", value, "pid");
return this;
}
public Criteria andPidGreaterThan(Long value) {
addCriterion("pid >", value, "pid");
return this;
}
public Criteria andPidGreaterThanOrEqualTo(Long value) {
addCriterion("pid >=", value, "pid");
return this;
}
public Criteria andPidLessThan(Long value) {
addCriterion("pid <", value, "pid");
return this;
}
public Criteria andPidLessThanOrEqualTo(Long value) {
addCriterion("pid <=", value, "pid");
return this;
}
public Criteria andPidIn(List values) {
addCriterion("pid in", values, "pid");
return this;
}
public Criteria andPidNotIn(List values) {
addCriterion("pid not in", values, "pid");
return this;
}
public Criteria andPidBetween(Long value1, Long value2) {
addCriterion("pid between", value1, value2, "pid");
return this;
}
public Criteria andPidNotBetween(Long value1, Long value2) {
addCriterion("pid not between", value1, value2, "pid");
return this;
}
}
}
|
package com.getronics.quarkus.api.sensors.model;
public class GasResponse {
}
|
package com.pine.template.mvvm.ui.activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import com.pine.template.base.BaseConstants;
import com.pine.template.base.access.UiAccessAction;
import com.pine.template.base.access.UiAccessType;
import com.pine.template.base.architecture.mvvm.ui.activity.BaseMvvmActionBarTextMenuActivity;
import com.pine.template.base.component.editor.bean.TextImageEntity;
import com.pine.template.base.component.uploader.FileUploadComponent;
import com.pine.template.base.component.uploader.bean.FileUploadBean;
import com.pine.template.base.component.uploader.bean.RemoteUploadFileInfo;
import com.pine.template.base.util.DialogUtils;
import com.pine.template.base.widget.dialog.DateSelectDialog;
import com.pine.template.base.widget.dialog.InputTextDialog;
import com.pine.template.config.ConfigKey;
import com.pine.template.mvvm.MvvmUrlConstants;
import com.pine.template.mvvm.R;
import com.pine.template.mvvm.bean.MvvmShopItemEntity;
import com.pine.template.mvvm.bean.MvvmTravelNoteDetailEntity;
import com.pine.template.mvvm.databinding.MvvmTravelNoteReleaseActivityBinding;
import com.pine.template.mvvm.vm.MvvmTravelNoteReleaseVm;
import com.pine.tool.access.UiAccessAnnotation;
import com.pine.tool.util.StringUtils;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by tanghongfeng on 2018/10/23
*/
@UiAccessAnnotation(AccessTypes = {UiAccessType.LOGIN, UiAccessType.CONFIG_SWITCHER},
AccessArgs = {"", ConfigKey.FUN_ADD_TRAVEL_NOTE_KEY},
AccessActions = {UiAccessAction.LOGIN_ACCESS_FALSE_ON_RESUME_NOT_GO_LOGIN,
UiAccessAction.LOGIN_ACCESS_FALSE_ON_CREATE_NOT_FINISH_UI,
UiAccessAction.CONFIG_SWITCHER_ACCESS_FALSE_ON_CREATE_SHOW_TOAST})
public class MvvmTravelNoteReleaseActivity extends
BaseMvvmActionBarTextMenuActivity<MvvmTravelNoteReleaseActivityBinding, MvvmTravelNoteReleaseVm> {
private final int REQUEST_CODE_SELECT_BELONG_SHOP = 1;
private InputTextDialog mDayCountInputDialog;
private DateSelectDialog mSetOutDateSelectDialog;
private FileUploadComponent.OneByOneUploadAdapter mUploadAdapter = new FileUploadComponent.OneByOneUploadAdapter() {
@Override
public String getUploadUrl() {
return MvvmUrlConstants.Upload_Single_File;
}
@Override
public String getFileKey(FileUploadBean fileUploadBean) {
// Test code begin
return "file";
// Test code end
}
@Override
public Map<String, String> getUploadParam(FileUploadBean fileUploadBean) {
HashMap<String, String> params = new HashMap<>();
// Test code begin
params.put("bizType", "10");
params.put("orderNum", "100");
params.put("descr", "");
params.put("fileType", "1");
// Test code end
return params;
}
@Override
public RemoteUploadFileInfo getRemoteFileInfoFromResponse(FileUploadBean fileUploadBean, JSONObject
response) {
// Test code begin
if (response == null) {
return null;
}
if (!response.optBoolean(BaseConstants.SUCCESS)) {
return null;
}
JSONObject data = response.optJSONObject(BaseConstants.DATA);
if (data == null) {
return null;
}
RemoteUploadFileInfo fileInfo = new RemoteUploadFileInfo();
fileInfo.setUrl(data.optString("fileUrl"));
return fileInfo;
// Test code end
}
};
@Override
public void observeInitLiveData(Bundle savedInstanceState) {
mViewModel.getBelongShopListData().observe(this, new Observer<ArrayList<MvvmShopItemEntity>>() {
@Override
public void onChanged(@Nullable ArrayList<MvvmShopItemEntity> list) {
String names = "";
if (list != null) {
for (MvvmShopItemEntity entity : list) {
names += entity.getName() + ",";
}
}
if (!TextUtils.isEmpty(names) && names.lastIndexOf(",") == names.length() - 1) {
names = names.substring(0, names.length() - 1);
}
mBinding.belongShopTv.setText(names);
mBinding.belongShopTv.setData(list);
}
});
mViewModel.getNoteDetailData().observe(this, new Observer<MvvmTravelNoteDetailEntity>() {
@Override
public void onChanged(@Nullable MvvmTravelNoteDetailEntity mvvmTravelNoteDetailEntity) {
mBinding.setNoteDetail(mvvmTravelNoteDetailEntity);
}
});
}
@Override
protected int getActivityLayoutResId() {
return R.layout.mvvm_activity_travel_note_release;
}
@Override
protected void init(Bundle savedInstanceState) {
mBinding.setPresenter(new Presenter());
initView();
}
private void initView() {
mBinding.swipeRefreshLayout.setColorSchemeResources(
R.color.red,
R.color.yellow,
R.color.green
);
mBinding.swipeRefreshLayout.setEnabled(false);
}
@Override
protected void setupActionBar(View actionbar, ImageView goBackIv, TextView titleTv, TextView menuBtnTv) {
titleTv.setText(R.string.mvvm_note_release_title);
menuBtnTv.setText(R.string.mvvm_note_release_confirm_menu);
menuBtnTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onAddNoteBtnClicked();
}
});
}
@Override
public void observeSyncLiveData(int liveDataObjTag) {
}
@Override
public void onDestroy() {
if (mDayCountInputDialog != null && mDayCountInputDialog.isShowing()) {
mDayCountInputDialog.dismiss();
}
if (mSetOutDateSelectDialog != null && mSetOutDateSelectDialog.isShowing()) {
mSetOutDateSelectDialog.dismiss();
}
super.onDestroy();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_SELECT_BELONG_SHOP) {
if (resultCode == RESULT_OK) {
mViewModel.onBelongShopSelected(data);
}
}
}
private void onAddNoteBtnClicked() {
mViewModel.addNote(mBinding.aevView.getSectionList());
}
@Override
public void setLoadingUiVisibility(boolean processing) {
if (mBinding.swipeRefreshLayout == null) {
return;
}
mBinding.swipeRefreshLayout.setRefreshing(processing);
}
public class Presenter {
public void onSetOutDateClick(View view) {
if (mSetOutDateSelectDialog == null) {
int year = Calendar.getInstance().get(Calendar.YEAR);
mSetOutDateSelectDialog = DialogUtils.createDateSelectDialog(MvvmTravelNoteReleaseActivity.this,
year, year + 1, new DateSelectDialog.IDialogDateSelected() {
@Override
public void onSelected(Calendar calendar) {
mBinding.setOutDateTv
.setText(new SimpleDateFormat("yyyy-MM-dd")
.format(calendar.getTime()));
}
});
}
mSetOutDateSelectDialog.show();
}
public void onDayCountClick(View view) {
if (mDayCountInputDialog == null) {
mDayCountInputDialog = DialogUtils.createTextInputDialog(MvvmTravelNoteReleaseActivity.this,
getString(R.string.mvvm_shop_release_day_count_hint),
"", 3,
EditorInfo.TYPE_CLASS_NUMBER, new InputTextDialog.IActionClickListener() {
@Override
public boolean onSubmitClick(Dialog dialog, List<String> textList) {
if (textList != null && textList.size() > 0 &&
!TextUtils.isEmpty(textList.get(0))) {
mBinding.dayCountTv.setText(textList.get(0));
int count = Integer.parseInt(textList.get(0));
mBinding.dayCountTv.setData(count);
List<String> titleList = null;
if (count > 1) {
titleList = new ArrayList<>();
for (int i = 0; i < count; i++) {
titleList.add(getString(R.string.mvvm_note_release_day_note_title, StringUtils.toChineseNumber(i + 1)));
}
}
mBinding.aevView.setSectionCount(MvvmTravelNoteReleaseActivity.this,
count, titleList, mUploadAdapter);
}
return false;
}
@Override
public boolean onCancelClick(Dialog dialog) {
return false;
}
});
}
mDayCountInputDialog.show();
}
public void onBelongShopClick(View view) {
Intent intent = new Intent(MvvmTravelNoteReleaseActivity.this, MvvmShopSearchCheckActivity.class);
intent.putParcelableArrayListExtra(MvvmShopSearchCheckActivity.REQUEST_CHECKED_LIST_KEY, mViewModel.getBelongShopListData().getValue());
startActivityForResult(intent, REQUEST_CODE_SELECT_BELONG_SHOP);
}
public void onPreviewNoteClick(View view) {
List<TextImageEntity> noteDayList = mBinding.aevView.getSectionList();
if (noteDayList != null && noteDayList.size() > 0) {
mBinding.notePreviewRl.setVisibility(View.VISIBLE);
mBinding.notePreviewAdv.init(noteDayList);
}
}
public void onPreviewContainerClick(View view) {
mBinding.notePreviewRl.setVisibility(View.GONE);
}
}
}
|
class Publicacao {
private String nome;
private double precoExemplar;
protected double valorAnuidade;
public calcularAnuidade(){
12 * precoExemplar;
}
public imprimirDados(){
}
}
|
/*
* 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 salas_lopez_ismael_pf;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.datatransfer.Transferable;
import java.io.Serializable;
/**
*
* @author Ismael Salas López ft Stack Overflow
* Esta clase permite manejar los eventos soltado. También es una de las clases
* adaptada del código de Stack Overflow
* Classe adaptada: DropHandler
* https://stackoverflow.com/questions/11201734/java-how-to-drag-and-drop-jpanel-with-its-components
*
* Reemplazo la interfaz DropTargetListener y hago que extienda de DropTargetAdapter
* para implementar las funciones que necesito para que funcione el arratre y el soltado.
* Bueno, este es el manejador de eventos para el soltado.
*/
public class Suelta extends DropTargetAdapter implements Serializable
{
// Referencia a sí mismo (el objeto que admite el dropeo del objeto)
PilaCartas pilaCartas;
// Constructor
public Suelta( PilaCartas pila )
{
this.pilaCartas = pila;
}
/** Cuando el usuario ejecuta un drop.
*/
@Override
public void drop( DropTargetDropEvent evento )
{
// ¿Se está soltando un elemento válido?
if( evento.isDataFlavorSupported( DataFlavorPila.INSTANCIA_COMPARTIDA ) ){
// Obtenemos el transferable creado en la función dragGestureRecognizer de la clase Arrastra
Transferable paqueteRecibir = evento.getTransferable();
// Itentamos...
try{
// Obtener el objeto PilaCartas que almacena el paquete que contenía el objeto TransferData
Object pilaCartas = paqueteRecibir.getTransferData( DataFlavorPila.INSTANCIA_COMPARTIDA );
// Convierte el objeto pilaCartas
PilaCartas cartas = (PilaCartas)pilaCartas;
// Función polimórfica apilarCartas, por eso no es necesario checar
// que tipo de objeto es con instanceof
// Apila las cartas, si el apilamiento fue exitoso entonces...
if( this.pilaCartas.apilarCartas( cartas ) ){
// Indica que el drop fue aceptado
evento.acceptDrop( DnDConstants.ACTION_MOVE );
// Activa la bandera static de que la pila cartas fue transferida exitosamente
this.pilaCartas.setTransferido( true );
}
else{
// Desactiva la bandera static de que la pila cartas fue transferida exitosamente
this.pilaCartas.setTransferido( false );
// rechaza el drop
evento.rejectDrop();
}
// Vacia la pila con la copia de las cartas
cartas.vaciar();
cartas = null;
// Actualiza la pantalla, ya sea si se actualizó o no
this.pilaCartas.repaint();
}
catch( Exception e ){
// Recha el drop
evento.rejectDrop();
}
}
}
}
|
package com.samples.sorting;
import java.util.Arrays;
public class SelectionSort {
//will select minimum
public static void main(String[] args) {
int[] arr= {1,23,43,2,33,44,55,44,22,29,3,54};
int[] selectedArray=selectionSort(arr);
Arrays.stream(selectedArray).forEach(System.out::println);
}
//also includes logic find minimum in a array
private static int[] selectionSort(int[] arr) {
int[] sortedArray= {};
int size=arr.length-1;
int minIndex=0;
while(size>0) {
for(int j=0;j< arr.length-1;j++) {
if(arr[j]<arr[minIndex]) {
minIndex=j;
}
}
sortedArray[minIndex]=arr[minIndex];
}
return sortedArray;
}
}
|
package com.bingo.code.example.design.command.log;
import java.io.Serializable;
/**
* ��������̶��Ź���
*/
public class ChopCommand implements Command,Serializable{
/**
* ���о������˵ij�ʦ�Ķ���
*/
private CookApi cookApi = null;
/**
* ���þ������˵ij�ʦ�Ķ���
* @param cookApi �������˵ij�ʦ�Ķ���
*/
public void setCookApi(CookApi cookApi) {
this.cookApi = cookApi;
}
/**
* ��˵�����
*/
private int tableNum;
/**
* ���췽���������˵�����
* @param tableNum ��˵�����
*/
public ChopCommand(int tableNum){
this.tableNum = tableNum;
}
public int getTableNum(){
return this.tableNum;
}
public void execute() {
this.cookApi.cook(tableNum,"�̶��Ź���");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.