text stringlengths 10 2.72M |
|---|
package domain.model;
import java.util.Date;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.validation.constraints.NotNull;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=true)
@Entity
@DiscriminatorValue("B")
public class Bond extends Security {
@NotNull
private Date maturityDate;
}
|
package br.com.sdad.entidades.informacoes;
import javax.persistence.*;
import java.sql.Timestamp;
@MappedSuperclass
public class InformacaoVital {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int idRegistro;
private int idUsuario;
@Column(columnDefinition="TimestampTimeFormat")
private Timestamp dataHora;
public InformacaoVital () {}
public InformacaoVital (int idRegistro,
int idUsuario,
Timestamp dataHora){
this.idRegistro = idRegistro;
this.idUsuario = idUsuario;
this.dataHora = dataHora;
}
public int getIdRegistro() {
return idRegistro;
}
public void setIdRegistro(int idRegistro) {
this.idRegistro = idRegistro;
}
public int getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(int idUsuario) {
this.idUsuario = idUsuario;
}
public Timestamp getDataHora() {
return dataHora;
}
public void setDataHora(Timestamp dataHora) {
this.dataHora = dataHora;
}
}
|
package com.lbsp.promotion.core.key;
import java.util.UUID;
public class PrimaryKeyGenerator implements KeyGenerate{
@Override
public String generate() {
return String.valueOf(UUID.randomUUID().hashCode());
}
}
|
package com.mcf.manage.web.controller.common;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.mcf.base.common.utils.QiniuUtils;
import com.mcf.base.config.ConfigUtils;
/**
* Title. <br>
* Description.
* <p>
* Copyright: Copyright (c) 2016年12月17日 下午2:42:09
* <p>
* Author: 10003/sunaiqiang saq691@126.com
* <p>
* Version: 1.0
* <p>
*/
@RestController
@RequestMapping("/upload")
public class UploadController extends BaseController {
@Autowired
private QiniuUtils qiniuUtils;
/**
* 多文件上传支持
*
* @param upfile
* @return
* @throws Exception
*/
@ResponseBody
@RequestMapping(value = "/toImage", method = RequestMethod.POST)
public Map<String, Object> uploadFile(MultipartHttpServletRequest request)
throws Exception {
Map<String, Object> valMap = new HashMap<String, Object>();
Iterator<String> iterator = request.getFileNames();
MultipartFile multipartFile = null;
try {
while (iterator.hasNext()) {
multipartFile = request.getFile(iterator.next());
String fileName = multipartFile.getOriginalFilename();
byte[] fileByte = multipartFile.getBytes();
qiniuUtils.uploadFile(fileByte, fileName);
valMap.put("error", 0);
valMap.put("url", ConfigUtils.getProperty("qiniu.withlink") + fileName);
}
} catch (Exception e) {
valMap.put("error", 500);
valMap.put("message", "系统异常,上传失败!");
}
return valMap;
}
}
|
package dao;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import common.msgs;
public class Add_Book {
msgs thismessage;
Connection localdbConnection;
public void getAdd_Book(msgs loginmsgs,Connection dbConnection){
thismessage = loginmsgs;
localdbConnection=dbConnection;
PreparedStatement ps=null;
int i,j;
try {
String insertTableSQL = "INSERT INTO books"
+ "(bookname, category, summary) VALUES"
+ "(?,?,?)";
ps = (PreparedStatement) localdbConnection.prepareStatement(insertTableSQL);
ps.setString(1,thismessage.getMapValue("book"));
ps.setString(2,thismessage.getMapValue("category"));
ps.setString(3,thismessage.getMapValue("summary"));
ps.executeUpdate();
String insertTableSQL1 = "INSERT INTO bookauthors"
+ "(bookname, author) VALUES"
+ "(?,?)";
ps.clearParameters();
ps = (PreparedStatement) localdbConnection.prepareStatement(insertTableSQL1);
for (i=0;i<Integer.parseInt(thismessage.getMapValue("numberofauthors"));i++)
{
j=i+1;
ps.setString(1,thismessage.getMapValue("book"));
ps.setString(2,thismessage.getMapValue("author"+j));
ps.executeUpdate();
}
String insertTableSQL2 = "INSERT INTO bookcategory"
+ "(bookname, category) VALUES"
+ "(?,?)";
ps.clearParameters();
ps = (PreparedStatement) localdbConnection.prepareStatement(insertTableSQL2);
for (i=0;i<Integer.parseInt(thismessage.getMapValue("numberofcategory"));i++)
{
j=i+1;
ps.setString(1,thismessage.getMapValue("book"));
ps.setString(2,thismessage.getMapValue("category"+j));
ps.executeUpdate();
}
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
package com.system.controller;
import com.system.constants.BaseErrorConstants;
import com.system.entity.UserMasterEntity;
import com.system.service.UserMasterService;
import com.system.util.*;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class UserMasterController {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(UserMasterController.class);
@Autowired
private UserMasterService userMasterService;
/**
* find list
*
* @Author qinwanli
* @Description //TODO
* @Date 2019/5/20 14:15
* @Param [request]
**/
@GetMapping(value = "/user/findList")
public ServiceResult<List<UserMasterEntity>> findList(HttpServletRequest request) {
ServiceResult<List<UserMasterEntity>> result = new ServiceResult<List<UserMasterEntity>>();
PagerInfo<?> pagerInfo = null;
Map<String, Object> params = null;
int userId = ConvertUtil.toInt(request.getParameter("userId"), 0);
try {
if (!StringUtil.isEmpty(request.getParameter("pageSize"))) {
pagerInfo = BaseWebUtil.getPageInfoForPC(request);
}
params = new HashMap<String, Object>();
if (userId > 0) {
params.put("userId", userId);
}
result = userMasterService.findList(params, pagerInfo);
} catch (Exception e) {
LOGGER.error("[UserMasterController][findList]:query findList occur exception", e);
result.setError(BaseErrorConstants.ERROR_CODE_SERVICE_CONTROLLER, "Find user order list error.");
}
return result;
}
/**
* find info
*
* @Author qinwanli
* @Description //TODO
* @Date 2019/5/20 14:15
* @Param [request]
**/
@GetMapping(value = "/user/findInfo")
public ServiceResult<UserMasterEntity> findInfo(HttpServletRequest request) {
ServiceResult<UserMasterEntity> result = new ServiceResult<UserMasterEntity>();
Map<String, Object> params = null;
int userId = ConvertUtil.toInt(request.getParameter("userId"), 0);
try {
params = new HashMap<String, Object>();
if (userId > 0) {
params.put("userId", userId);
}
result = userMasterService.findInfo(params);
} catch (Exception e) {
LOGGER.error("[UserMasterController][findInfo]:query findInfo occur exception", e);
result.setError(BaseErrorConstants.ERROR_CODE_SERVICE_CONTROLLER, "Find user order error.");
}
return result;
}
/**
* do insert
*
* @Author qinwanli
* @Description //TODO
* @Date 2019/5/20 14:14
* @Param [userMasterEntity]
**/
@PostMapping(value = "/user/doInsert")
public ServiceResult<Integer> doInsert(@RequestBody UserMasterEntity userMasterEntity) {
ServiceResult<Integer> result = new ServiceResult<Integer>();
try {
result = userMasterService.doInsert(userMasterEntity);
} catch (Exception e) {
LOGGER.error("[UserMasterController][doInsert]:Insert occur exception", e);
result.setError(BaseErrorConstants.ERROR_CODE_SERVICE_CONTROLLER, "Insert error.");
}
return result;
}
/**
* do update
*
* @Author qinwanli
* @Description //TODO
* @Date 2019/5/20 14:14
* @Param [userMasterEntity]
**/
@PostMapping(value = "/user/doUpdate")
public ServiceResult<Integer> doUpdate(@RequestBody UserMasterEntity userMasterEntity) {
ServiceResult<Integer> result = new ServiceResult<Integer>();
try {
result = userMasterService.doUpdate(userMasterEntity);
} catch (Exception e) {
LOGGER.error("[UserMasterController][doUpdate]:Update occur exception", e);
result.setError(BaseErrorConstants.ERROR_CODE_SERVICE_CONTROLLER, "Update error.");
}
return result;
}
/**
* do delete
*
* @Author qinwanli
* @Description //TODO
* @Date 2019/5/20 14:14
* @Param [userId]
**/
@PostMapping(value = "/user/doDelete")
public ServiceResult<Boolean> doDelete(@RequestParam("userId") int userId) {
ServiceResult<Boolean> result = new ServiceResult<>();
try {
result = userMasterService.doDelete(userId);
} catch (Exception e) {
LOGGER.error("[UserMasterController][doDelete]:Delete occur exception", e);
result.setError(BaseErrorConstants.ERROR_CODE_SERVICE_CONTROLLER, "Delete error.");
}
return result;
}
} |
package alice.af.tileentity;
import alice.af.FillerMode;
import alice.af.client.entity.EntityFillerFrame;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
public final class TileEntityAdvFiller extends TileEntity implements IInventory
{
private final ItemStack[] inventory = new ItemStack[26];
public int startX;
public int startY;
public int startZ;
public int endX;
public int endY;
public int endZ;
public FillerMode mode = FillerMode.QUARRY;
public boolean loop;
public boolean iterate;
public boolean drop;
public EntityFillerFrame frame;
@Override
public void updateEntity()
{
super.updateEntity();
World world = this.worldObj;
if(world.isRemote)
{
this.spawnFrameEntity();
return;
}
int meta = world.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord);
int newMeta = meta;
if(world.isBlockIndirectlyGettingPowered(this.xCoord, this.yCoord, this.zCoord))
{
newMeta |= 0x4;
}
else
{
newMeta &= 0xB;
}
if(newMeta != meta)
{
world.setBlockMetadataWithNotify(this.xCoord, this.yCoord, this.zCoord, newMeta, 2);
}
}
public void spawnFrameEntity()
{
if(this.frame == null)
{
this.frame = new EntityFillerFrame(this);
this.worldObj.addWeatherEffect(this.frame);
}
}
@Override
public Packet getDescriptionPacket()
{
NBTTagCompound tag = new NBTTagCompound();
this.writeNBT(tag, true);
return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, 0, tag);
}
@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt)
{
this.readNBT(pkt.func_148857_g(), true);
}
@Override
public void readFromNBT(NBTTagCompound tag)
{
super.readFromNBT(tag);
this.readNBT(tag, true);
}
private void readNBT(NBTTagCompound tag, boolean updateInventory)
{
this.startX = tag.getInteger("stx");
this.startY = tag.getInteger("sty");
this.startZ = tag.getInteger("stz");
this.endX = tag.getInteger("enx");
this.endY = tag.getInteger("eny");
this.endZ = tag.getInteger("enz");
this.mode = FillerMode.getMode(tag.getByte("mod"));
this.loop = tag.getBoolean("lop");
this.iterate = tag.getBoolean("itr");
this.drop = tag.getBoolean("drp");
if(updateInventory && tag.hasKey("inv"))
{
NBTTagList inventoryNbt = tag.getTagList("inv", 10);
int inventoryNbtSize = inventoryNbt.tagCount();
for(int indexNbt = 0; indexNbt < inventoryNbtSize; indexNbt++)
{
NBTTagCompound itemNbt = inventoryNbt.getCompoundTagAt(indexNbt);
if(itemNbt == null)
{
continue;
}
ItemStack item = null;
try
{
item = ItemStack.loadItemStackFromNBT(itemNbt);
}
catch(Exception e)
{
}
if(item != null)
{
int index = itemNbt.getByte("idx") - 1;
this.setInventorySlotContents(index, item);
}
}
}
}
@Override
public void writeToNBT(NBTTagCompound tag)
{
super.writeToNBT(tag);
this.writeNBT(tag, true);
}
private void writeNBT(NBTTagCompound tag, boolean sendInventory)
{
tag.setInteger("stx", this.startX);
tag.setInteger("sty", this.startY);
tag.setInteger("stz", this.startZ);
tag.setInteger("enx", this.endX);
tag.setInteger("eny", this.endY);
tag.setInteger("enz", this.endZ);
tag.setByte("mod", (byte)this.mode.toInteger());
tag.setBoolean("lop", this.loop);
tag.setBoolean("itr", this.iterate);
tag.setBoolean("drp", this.drop);
if(sendInventory)
{
NBTTagList inventoryNbt = new NBTTagList();
for(int i = 0; i < this.getSizeInventory(); i++)
{
ItemStack item = this.getStackInSlot(i);
if((item == null) || (item.stackSize < 0))
{
continue;
}
NBTTagCompound itemNbt = new NBTTagCompound();
item.writeToNBT(itemNbt);
itemNbt.setByte("idx", (byte)(1 + i));
inventoryNbt.appendTag(itemNbt);
}
tag.setTag("inv", inventoryNbt);
}
}
public int getLeft()
{
int meta = this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord);
switch(meta & 3)
{
case 0:
return this.xCoord - this.startX;
case 1:
return this.zCoord - this.startZ;
case 2:
return this.endX - this.xCoord;
case 3:
return this.endZ - this.zCoord;
}
return 0;
}
public void setLeft(int blocks)
{
int meta = this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord);
switch(meta & 3)
{
case 0:
this.startX = this.xCoord - blocks;
break;
case 1:
this.startZ = this.zCoord - blocks;
break;
case 2:
this.endX = this.xCoord + blocks;
break;
case 3:
this.endZ = this.zCoord + blocks;
break;
}
}
public int getRight()
{
int meta = this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord);
switch(meta & 3)
{
case 0:
return this.endX - this.xCoord;
case 1:
return this.endZ - this.zCoord;
case 2:
return this.xCoord - this.startX;
case 3:
return this.zCoord - this.startZ;
}
return 0;
}
public void setRight(int blocks)
{
int meta = this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord);
switch(meta & 3)
{
case 0:
this.endX = this.xCoord + blocks;
break;
case 1:
this.endZ = this.zCoord + blocks;
break;
case 2:
this.startX = this.xCoord - blocks;
break;
case 3:
this.startZ = this.zCoord - blocks;
break;
}
}
public int getUpper()
{
return this.endY - this.yCoord;
}
public void setUpper(int blocks)
{
this.endY = this.yCoord + blocks;
}
public int getBottom()
{
return this.yCoord - this.startY;
}
public void setBottom(int blocks)
{
this.startY = this.yCoord - blocks;
}
public int getForward()
{
int meta = this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord);
switch(meta & 3)
{
case 0:
return this.zCoord - this.startZ;
case 1:
return this.endX - this.xCoord;
case 2:
return this.endZ - this.zCoord;
case 3:
return this.xCoord - this.startX;
}
return 0;
}
public void setForward(int blocks)
{
int meta = this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord);
switch(meta & 3)
{
case 0:
this.startZ = this.zCoord - blocks;
break;
case 1:
this.endX = this.xCoord + blocks;
break;
case 2:
this.endZ = this.zCoord + blocks;
break;
case 3:
this.startX = this.xCoord - blocks;
break;
}
}
@Override
public int getSizeInventory()
{
return inventory.length;
}
@Override
public ItemStack getStackInSlot(int index)
{
if((index < 0) || (index >= getSizeInventory()))
{
return null;
}
return this.inventory[index];
}
@Override
public ItemStack decrStackSize(int index, int amount)
{
ItemStack item = this.getStackInSlot(index);
if(item == null)
{
return null;
}
if(item.stackSize >= amount)
{
item.stackSize -= amount;
if(item.stackSize <= 0)
{
this.setInventorySlotContents(index, null);
}
item = item.copy();
item.stackSize = amount;
}
return item;
}
@Override
public ItemStack getStackInSlotOnClosing(int index)
{
return null;
}
@Override
public void setInventorySlotContents(int index, ItemStack item)
{
if((index >= 0) && (index < getSizeInventory()))
{
if((item != null) && (item.stackSize > 0))
{
this.inventory[index] = item;
}
else
{
this.inventory[index] = null;
}
}
}
@Override
public String getInventoryName()
{
return "container.advfiller";
}
@Override
public boolean hasCustomInventoryName()
{
return false;
}
@Override
public int getInventoryStackLimit()
{
return 64;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player)
{
return true;
}
@Override
public void openInventory()
{
}
@Override
public void closeInventory()
{
}
@Override
public boolean isItemValidForSlot(int index, ItemStack item)
{
return ((index >= 0) && (index < getSizeInventory()));
}
}
|
package fr.polytech.lechat.moviereview;
public class IRecyclerViewManager {
}
|
package bnorm.virtual;
import org.junit.Assert;
import org.junit.Test;
import bnorm.utils.Trig;
/**
* A group of unit tests for {@link Vector}s.
*
* @author Brian Norman
*/
public class VectorTest {
/**
* A test for the {@link Vector#getDeltaX()} method.
*/
@Test
public void testGetDeltaX() {
final double EPSILON = 1.0E-14;
final double SQRT2 = Math.sqrt(2.0);
final double EIGHTH_CIRCLE = Trig.CIRCLE / 8.0;
Assert.assertEquals(6.0, new Vector(6.0, 0.0).getDeltaX(), EPSILON);
Assert.assertEquals(-3.33, new Vector(-3.33, 0.0).getDeltaX(), EPSILON);
Assert.assertEquals(3.14159, new Vector(3.14159, 0.0).getDeltaX(), EPSILON);
Assert.assertEquals(-365.25, new Vector(-365.25, 0.0).getDeltaX(), EPSILON);
Assert.assertEquals(42.0, new Vector(42.0, 0.0).getDeltaX(), EPSILON);
Assert.assertEquals(-0.0, new Vector(-0.0, 0.0).getDeltaX(), EPSILON);
Assert.assertEquals(0.0, new Vector(0.0, 0.0, 0.0 * EIGHTH_CIRCLE, 4.0).getDeltaX(), EPSILON);
Assert.assertEquals(0.0, new Vector(0.0, 0.0, 0.0 * EIGHTH_CIRCLE, 9.0).getDeltaX(), EPSILON);
Assert.assertEquals(4.0 / SQRT2, new Vector(1.0, 1.0, 1.0 * EIGHTH_CIRCLE, 4.0).getDeltaX(), EPSILON);
Assert.assertEquals(9.0 / SQRT2, new Vector(1.0, 1.0, 1.0 * EIGHTH_CIRCLE, 9.0).getDeltaX(), EPSILON);
Assert.assertEquals(4.0, new Vector(2.0, 2.0, 2.0 * EIGHTH_CIRCLE, 4.0).getDeltaX(), EPSILON);
Assert.assertEquals(9.0, new Vector(2.0, 2.0, 2.0 * EIGHTH_CIRCLE, 9.0).getDeltaX(), EPSILON);
Assert.assertEquals(4.0 / SQRT2, new Vector(3.0, 3.0, 3.0 * EIGHTH_CIRCLE, 4.0).getDeltaX(), EPSILON);
Assert.assertEquals(9.0 / SQRT2, new Vector(3.0, 3.0, 3.0 * EIGHTH_CIRCLE, 9.0).getDeltaX(), EPSILON);
Assert.assertEquals(0.0, new Vector(-0.0, -0.0, 4.0 * EIGHTH_CIRCLE, 4.0).getDeltaX(), EPSILON);
Assert.assertEquals(0.0, new Vector(-0.0, -0.0, 4.0 * EIGHTH_CIRCLE, 9.0).getDeltaX(), EPSILON);
Assert.assertEquals(-4.0 / SQRT2, new Vector(-1.0, -1.0, 5.0 * EIGHTH_CIRCLE, 4.0).getDeltaX(), EPSILON);
Assert.assertEquals(-9.0 / SQRT2, new Vector(-1.0, -1.0, 5.0 * EIGHTH_CIRCLE, 9.0).getDeltaX(), EPSILON);
Assert.assertEquals(-4.0, new Vector(-2.0, -2.0, 6.0 * EIGHTH_CIRCLE, 4.0).getDeltaX(), EPSILON);
Assert.assertEquals(-9.0, new Vector(-2.0, -2.0, 6.0 * EIGHTH_CIRCLE, 9.0).getDeltaX(), EPSILON);
Assert.assertEquals(-4.0 / SQRT2, new Vector(-3.0, -3.0, 7.0 * EIGHTH_CIRCLE, 4.0).getDeltaX(), EPSILON);
Assert.assertEquals(-9.0 / SQRT2, new Vector(-3.0, -3.0, 7.0 * EIGHTH_CIRCLE, 9.0).getDeltaX(), EPSILON);
Assert.assertEquals(0.0, new Vector(0.0, -0.0, 8.0 * EIGHTH_CIRCLE, 4.0).getDeltaX(), EPSILON);
Assert.assertEquals(0.0, new Vector(-1.0, 1.0, 8.0 * EIGHTH_CIRCLE, 9.0).getDeltaX(), EPSILON);
}
/**
* A test for the {@link Vector#getDeltaY()} method.
*/
@Test
public void testGetDeltaY() {
final double EPSILON = 1.0E-14;
final double SQRT2 = Math.sqrt(2.0);
final double EIGHTH_CIRCLE = Trig.CIRCLE / 8.0;
Assert.assertEquals(6.0, new Vector(0.0, 6.0).getDeltaY(), 0.0);
Assert.assertEquals(-3.33, new Vector(0.0, -3.33).getDeltaY(), 0.0);
Assert.assertEquals(3.14159, new Vector(0.0, 3.14159).getDeltaY(), 0.0);
Assert.assertEquals(-365.25, new Vector(0.0, -365.25).getDeltaY(), 0.0);
Assert.assertEquals(42.0, new Vector(0.0, 42.0).getDeltaY(), 0.0);
Assert.assertEquals(-0.0, new Vector(0.0, -0.0).getDeltaY(), 0.0);
Assert.assertEquals(4.0, new Vector(0.0, 0.0, 0.0 * EIGHTH_CIRCLE, 4.0).getDeltaY(), EPSILON);
Assert.assertEquals(9.0, new Vector(0.0, 0.0, 0.0 * EIGHTH_CIRCLE, 9.0).getDeltaY(), EPSILON);
Assert.assertEquals(4.0 / SQRT2, new Vector(1.0, 1.0, 1.0 * EIGHTH_CIRCLE, 4.0).getDeltaY(), EPSILON);
Assert.assertEquals(9.0 / SQRT2, new Vector(1.0, 1.0, 1.0 * EIGHTH_CIRCLE, 9.0).getDeltaY(), EPSILON);
Assert.assertEquals(0.0, new Vector(2.0, 2.0, 2.0 * EIGHTH_CIRCLE, 4.0).getDeltaY(), EPSILON);
Assert.assertEquals(0.0, new Vector(2.0, 2.0, 2.0 * EIGHTH_CIRCLE, 9.0).getDeltaY(), EPSILON);
Assert.assertEquals(-4.0 / SQRT2, new Vector(3.0, 3.0, 3.0 * EIGHTH_CIRCLE, 4.0).getDeltaY(), EPSILON);
Assert.assertEquals(-9.0 / SQRT2, new Vector(3.0, 3.0, 3.0 * EIGHTH_CIRCLE, 9.0).getDeltaY(), EPSILON);
Assert.assertEquals(-4.0, new Vector(-0.0, -0.0, 4.0 * EIGHTH_CIRCLE, 4.0).getDeltaY(), EPSILON);
Assert.assertEquals(-9.0, new Vector(-0.0, -0.0, 4.0 * EIGHTH_CIRCLE, 9.0).getDeltaY(), EPSILON);
Assert.assertEquals(-4.0 / SQRT2, new Vector(-1.0, -1.0, 5.0 * EIGHTH_CIRCLE, 4.0).getDeltaY(), EPSILON);
Assert.assertEquals(-9.0 / SQRT2, new Vector(-1.0, -1.0, 5.0 * EIGHTH_CIRCLE, 9.0).getDeltaY(), EPSILON);
Assert.assertEquals(0.0, new Vector(-2.0, -2.0, 6.0 * EIGHTH_CIRCLE, 4.0).getDeltaY(), EPSILON);
Assert.assertEquals(0.0, new Vector(-2.0, -2.0, 6.0 * EIGHTH_CIRCLE, 9.0).getDeltaY(), EPSILON);
Assert.assertEquals(4.0 / SQRT2, new Vector(-3.0, -3.0, 7.0 * EIGHTH_CIRCLE, 4.0).getDeltaY(), EPSILON);
Assert.assertEquals(9.0 / SQRT2, new Vector(-3.0, -3.0, 7.0 * EIGHTH_CIRCLE, 9.0).getDeltaY(), EPSILON);
Assert.assertEquals(4.0, new Vector(0.0, -0.0, 8.0 * EIGHTH_CIRCLE, 4.0).getDeltaY(), EPSILON);
Assert.assertEquals(9.0, new Vector(-1.0, 1.0, 8.0 * EIGHTH_CIRCLE, 9.0).getDeltaY(), EPSILON);
}
/**
* A test for the {@link Vector#getHeading()} method.
*/
@Test
public void testGetHeading() {
final double EPSILON = 1.0E-14;
final double EIGHTH_CIRCLE = Trig.CIRCLE / 8.0;
Assert.assertEquals(0.0, new Vector(0.0, 0.0, 0.0, 0.0).getHeading(), 0.0);
Assert.assertEquals(-3.33, new Vector(0.0, 0.0, -3.33, 1.0).getHeading(), 0.0);
Assert.assertEquals(3.14159, new Vector(0.0, 0.0, 3.14159, -1.0).getHeading(), 0.0);
Assert.assertEquals(-365.25, new Vector(0.0, 0.0, -365.25, -0.0).getHeading(), 0.0);
Assert.assertEquals(42.0, new Vector(0.0, 0.0, 42.0, 2.0).getHeading(), 0.0);
Assert.assertEquals(-0.0, new Vector(0.0, 0.0, -0.0, -2.0).getHeading(), 0.0);
Assert.assertEquals(0.0 * EIGHTH_CIRCLE, new Vector(0.0, 1.0).getHeading(), EPSILON);
Assert.assertEquals(1.0 * EIGHTH_CIRCLE, new Vector(1.0, 1.0).getHeading(), EPSILON);
Assert.assertEquals(2.0 * EIGHTH_CIRCLE, new Vector(1.0, 0.0).getHeading(), EPSILON);
Assert.assertEquals(3.0 * EIGHTH_CIRCLE, new Vector(1.0, -1.0).getHeading(), EPSILON);
Assert.assertEquals(4.0 * EIGHTH_CIRCLE, new Vector(0.0, -1.0).getHeading(), EPSILON);
Assert.assertEquals(-3.0 * EIGHTH_CIRCLE, new Vector(-1.0, -1.0).getHeading(), EPSILON);
Assert.assertEquals(-2.0 * EIGHTH_CIRCLE, new Vector(-1.0, 0.0).getHeading(), EPSILON);
Assert.assertEquals(-1.0 * EIGHTH_CIRCLE, new Vector(-1.0, 1.0).getHeading(), EPSILON);
Assert.assertEquals(0.0 * EIGHTH_CIRCLE, new Vector(0.0, 1.0).getHeading(), EPSILON);
}
/**
* A test for the {@link Vector#getVelocity()} method.
*/
@Test
public void testGetVelocity() {
final double EPSILON = 1.0E-14;
final double SQRT2 = Math.sqrt(2.0);
Assert.assertEquals(0.0, new Vector(0.0, 0.0, 0.0, 0.0).getVelocity(), 0.0);
Assert.assertEquals(-3.33, new Vector(0.0, 0.0, 1.0, -3.33).getVelocity(), 0.0);
Assert.assertEquals(3.14159, new Vector(0.0, 0.0, -1.0, 3.14159).getVelocity(), 0.0);
Assert.assertEquals(-365.25, new Vector(0.0, 0.0, -0.0, -365.25).getVelocity(), 0.0);
Assert.assertEquals(42.0, new Vector(0.0, 0.0, 2.0, 42.0).getVelocity(), 0.0);
Assert.assertEquals(-0.0, new Vector(0.0, 0.0, -2.0, -0.0).getVelocity(), 0.0);
Assert.assertEquals(1.0, new Vector(0.0, 1.0).getVelocity(), EPSILON);
Assert.assertEquals(1.0 * SQRT2, new Vector(1.0, 1.0).getVelocity(), EPSILON);
Assert.assertEquals(2.0, new Vector(2.0, 0.0).getVelocity(), EPSILON);
Assert.assertEquals(2.0 * SQRT2, new Vector(2.0, -2.0).getVelocity(), EPSILON);
Assert.assertEquals(42.0, new Vector(0.0, -42.0).getVelocity(), EPSILON);
Assert.assertEquals(42.0 * SQRT2, new Vector(-42.0, -42.0).getVelocity(), EPSILON);
Assert.assertEquals(3.33, new Vector(-3.33, 0.0).getVelocity(), EPSILON);
Assert.assertEquals(3.33 * SQRT2, new Vector(-3.33, 3.33).getVelocity(), EPSILON);
Assert.assertEquals(365.25, new Vector(0.0, 365.25).getVelocity(), EPSILON);
Assert.assertEquals(365.25 * SQRT2, new Vector(365.25, 365.25).getVelocity(), EPSILON);
}
/**
* A test for the {@link Vector#toString()} method.
*/
@Test
public void testToString() {
Assert.assertEquals("Vector[x=0.0, y=0.0, dx=0.0, dy=0.0]", new Vector(0.0, 0.0).toString());
Assert.assertEquals("Vector[x=0.0, y=0.0, dx=1.0, dy=-1.0]", new Vector(1.0, -1.0).toString());
Assert.assertEquals("Vector[x=0.0, y=0.0, dx=-42.0, dy=3.33]", new Vector(-42.0, 3.33).toString());
Assert.assertEquals("Vector[x=0.0, y=0.0, dx=3.14159, dy=-365.25]", new Vector(3.14159, -365.25).toString());
Assert.assertEquals("Vector[x=0.0, y=0.0, h=0.0, v=0.0]", new Vector(0.0, 0.0, 0.0, 0.0).toString());
Assert.assertEquals("Vector[x=1.0, y=-1.0, h=1.0, v=-1.0]", new Vector(1.0, -1.0, 1.0, -1.0).toString());
Assert.assertEquals("Vector[x=3.14159, y=-365.25, h=-42.0, v=3.33]",
new Vector(3.14159, -365.25, -42.0, 3.33).toString());
Vector vector = new Vector(1.0, 42.0);
vector.getHeading();
vector.getVelocity();
Assert.assertEquals("Vector[x=0.0, y=0.0, h=0.023805026185069942, v=42.01190307520001]", vector.toString());
}
/**
* A test for the {@link Vector#equals(Object)} method.
*/
@Test
public void testEquals() {
final double SQRT2 = Math.sqrt(2.0);
final double EIGHTH_CIRCLE = Trig.CIRCLE / 8.0;
Assert.assertEquals(0.0, new Vector(0.0, 0.0, 0.0, 0.0).getHeading(), 0.0);
Assert.assertEquals(-3.33, new Vector(0.0, 0.0, -3.33, 1.0).getHeading(), 0.0);
Assert.assertEquals(3.14159, new Vector(0.0, 0.0, 3.14159, -1.0).getHeading(), 0.0);
Assert.assertEquals(-365.25, new Vector(0.0, 0.0, -365.25, -0.0).getHeading(), 0.0);
Assert.assertEquals(42.0, new Vector(0.0, 0.0, 42.0, 2.0).getHeading(), 0.0);
Assert.assertEquals(-0.0, new Vector(0.0, 0.0, -0.0, -2.0).getHeading(), 0.0);
Assert.assertEquals(new Vector(0.0, 1.0), new Vector(0.0, 0.0, 0.0 * EIGHTH_CIRCLE, 1.0));
Assert.assertEquals(new Vector(1.0, 1.0), new Vector(0.0, 0.0, 1.0 * EIGHTH_CIRCLE, 1.0 * SQRT2));
Assert.assertEquals(new Vector(2.0, 0.0), new Vector(0.0, 0.0, 2.0 * EIGHTH_CIRCLE, 2.0));
Assert.assertEquals(new Vector(2.0, -2.0), new Vector(0.0, 0.0, 3.0 * EIGHTH_CIRCLE, 2.0 * SQRT2));
Assert.assertEquals(new Vector(0.0, 0.0, 4.0 * EIGHTH_CIRCLE, 42.0), new Vector(0.0, -42.0));
Assert.assertEquals(new Vector(0.0, 0.0, 5.0 * EIGHTH_CIRCLE, 42.0 * SQRT2), new Vector(-42.0, -42.0));
Assert.assertEquals(new Vector(0.0, 0.0, 6.0 * EIGHTH_CIRCLE, 3.33), new Vector(-3.33, 0.0));
Assert.assertEquals(new Vector(0.0, 0.0, 7.0 * EIGHTH_CIRCLE, 3.33 * SQRT2), new Vector(-3.33, 3.33));
Assert.assertFalse(new Vector(0.0, -42.0).equals(null));
Assert.assertFalse(new Vector(0.0, 0.0, 8.0 * EIGHTH_CIRCLE, 3.14159).equals("string"));
Assert.assertFalse(new Vector(365.0, 0.0).equals(2.0));
}
}
|
package javadateclassical;
import java.util.Calendar;
import java.util.TimeZone;
public class JavaTimeZoneExample
{
public static void main(String[] args)
{
String[] id=TimeZone.getAvailableIDs(); // return an array of IDs.
System.out.println("In TimeZone class available Ids are : ");
for(int i=0;i<id.length;i++)
{
System.out.println(id[i]);
}
TimeZone zone=TimeZone.getTimeZone("Asia/Kolkata");//Gets the TimeZone for the given ID.
System.out.println("The offset value of TimeZone: "+zone.getOffset(Calendar.ZONE_OFFSET));
System.out.println("Value of ID is:"+zone.getID());
TimeZone zone1=TimeZone.getDefault();//Gets the default TimeZone of the Java virtual machine
String name=zone1.getDisplayName();//Returns a long standard time name of this TimeZone suitable for presentation to the user in the default locale.
System.out.println("Display name for default time zone: "+name);
}
}
|
package porto.barrier;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.barriers.DistributedDoubleBarrier;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.log4j.PropertyConfigurator;
import java.util.logging.Logger;
/*
* This is a simple project to showcase how to use zookeeper and curator
* to build a barrier
* */
public class Main {
private static final Logger LOGGER = Logger.getLogger(Main.class.getName());
public static void main(String[] args) throws Exception {
// set logging capabilities
String log4jConfPath = "log4j.properties";
System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tF %1$tT %4$s: %2$s - %5$s%6$s%n");
PropertyConfigurator.configure(log4jConfPath);
initializeClientCoodinator();
LOGGER.info("Bye!!");
}
public static void initializeClientCoodinator() throws Exception {
//coordination
CuratorFramework curatorClient;
String connectionString = "";
RetryPolicy retryPolicy;
int connectionDelay = 0;
int connectionRetries = 0;
DistributedDoubleBarrier barrier;
int numberOfServiceReplicas = 0;
String name = "zookeeper-3.5.3-beta";
String groupName;
String zkPath = "";
connectionString = "zoo1:2181";
// connectionString = "zoo1:2181,zoo2:2181,zoo3:2181,";
connectionDelay = 1000;
connectionRetries = 3;
groupName = "barrier_group";
numberOfServiceReplicas = 2;
zkPath = "/" + groupName + "/barrier/g" + numberOfServiceReplicas;
retryPolicy = new ExponentialBackoffRetry(connectionDelay, connectionRetries);
curatorClient = CuratorFrameworkFactory.newClient(connectionString, retryPolicy);
barrier = new DistributedDoubleBarrier(curatorClient, zkPath, numberOfServiceReplicas);
LOGGER.info("Zookeeper communication layer created.");
// connect to the controller
curatorClient.start();
LOGGER.info("Zookeeper communication layer starting. Block until connection is established.");
// block until connection is established
curatorClient.blockUntilConnected();
LOGGER.info("Zookeeper communication layer started successfully!!");
LOGGER.info("waiting on the barrier");
barrier.enter();
LOGGER.info("Leaving the barrier");
barrier.leave();
LOGGER.info("Closing connection to gracefully");
curatorClient.close();
}
}
|
package LessonsJavaCore_14.Task_1;
public class lessons14 implements Comparable<lessons14> {
private String s;
private int i;
public lessons14(){
}
public lessons14(String s,int i){
this.s=s;
this.i = i;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
@Override
public String toString(){
return " int : " + i + " , " + " String : " + s;
}
@Override
public int compareTo(lessons14 o) {
return this.s.compareTo(o.getS());
}
}
|
package se.kb222vt.app;
import static spark.Spark.exception;
import static spark.Spark.get;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import com.google.gson.Gson;
import se.kb222vt.endpoint.SearchController;
import se.kb222vt.entity.Page;
import se.kb222vt.logic.PageRankLogic;
import se.kb222vt.logic.WordUtils;
import spark.servlet.SparkApplication;
//Start Application by web.xml
public class Application implements SparkApplication {
//putting some logic here since it will be so much overhead to put it somewhere else
private Gson gson = new Gson();
private HashMap<String, String> dataFolders = new HashMap<>();
public static HashMap<String, Page> articles = new HashMap<String, Page>();//<Title, Page>
//we need this to translate a hashCode -> word
public static HashMap<String, Integer> wordMap = new HashMap<>();//<String representation of a word, Id for word>
@Override
public void init() {
System.out.println("Start endpoints");
exception(IllegalArgumentException.class, (e, req, res) -> {
res.status(404);
res.body(gson.toJson(e));
});
get("/API/article/search/", SearchController.articleSearch);
get("/API/article/", SearchController.articles);
//add data folders if we didn't start from Initalize.java
if(dataFolders.size() < 1) {
dataFolders.put("Games", "webapps/searchengine/WEB-INF/classes/data/wikipedia/Words/Games");
dataFolders.put("Programming", "webapps/searchengine/WEB-INF/classes/data/wikipedia/Words/Programming");
}
try {
getArticlesFromDataFolders();
} catch (IOException e1) {
System.err.println("Couldnt read articles");
e1.printStackTrace();
}
System.out.println("Found: " + articles.size() + " pages");
System.out.println("Found: " + wordMap.size() + " different words");
//calculate the PageRank for articles
PageRankLogic.calculatePageRank(articles, 20);
}
/**
* Get articles from folders.
* Will use the paths to folders thats in the map dataFolders.
* Will ignore duplicate articles
* @throws IOException
*/
private void getArticlesFromDataFolders() throws IOException {
for(String folderPath : dataFolders.values()) {
System.out.println(folderPath);
//read all files in folder and send to readData
File folder = new File(folderPath);
File[] listOfFiles = folder.listFiles();
for(int i = 0; i < listOfFiles.length; i++) {
String articleName = listOfFiles[i].getName();
if(articles.containsKey(articleName)) {
continue;
}
articles.put(articleName, getArticle(listOfFiles[i].getPath(), articleName));
}
}
}
/**
* Gets articles from file at path. The file should only contain whitespace separated words.
* Note: assumes there is a corresponding folder for Links for articles
* @param path path to file thats an article,
* @param articleName name of the article to fetch
* @return Page representing the article fetched
* @throws IOException
*/
private Page getArticle(String path, String articleName) throws IOException {
String content = new String(Files.readAllBytes(Paths.get(path).toAbsolutePath()));
//for the content, create a page and fix all the words
//so split the content and do whats needs to be done for the words
Page article = new Page(articleName);
String linkPath = path.replace("\\Words\\", "\\Links\\");
setOutgoingLinks(linkPath, article);
String[] wordsArr = WordUtils.getArrayOfWords(content);
for(int i = 0; i < wordsArr.length; i++){
String word = wordsArr[i].toLowerCase();
int wordID = wordMap.size();
if(wordMap.containsKey(word)) {
//wordMap contains word since before, get the id for that word
wordID = wordMap.get(word);
}else {
//wordMap doesn't contain word since before, insert it and set ID for the word to wordMap.size();
wordMap.put(word, wordID);
}
//add word to article
article.addWord(wordID);
}
return article;
}
/**
* Set outgoing links for article
* @param path string representing path to file with outgoing links for article, outgoing links in file need to be new line separated
* @param p page to set outgoing links from
* @throws IOException
*/
public void setOutgoingLinks(String path, Page p) throws IOException {
String linkFile = new String(Files.readAllBytes(Paths.get(path).toAbsolutePath()));
String[] links = linkFile.split("\n");
for(int i = 0; i < links.length; i++) {
p.addOutgoingLink(links[i]);
}
}
public void addDataFolder(String title, String path) {
dataFolders.put(title, path);
}
public static HashMap<String, Page> getArticles(){
return articles;
}
public static HashMap<String, Integer> getWordMap(){
return wordMap;
}
} |
package ua.project.protester.model.executable;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@NoArgsConstructor
@Getter
@Setter
public class ActionRepresentation {
private Integer id;
private String className;
private String description;
}
|
package com.zebra.pay.base;
public interface QueryDAO {
/**
* 方法说明:返回LIST集合
* @param key
* @param obj
* @return
*/
public Object queryList(String key, Object obj);
/**
* 方法说明:返回LIST集合
* @param key
* @param obj
* @param offset 偏移值
* @param count 一次查询数值
* @return
*/
public Object queryList(String key, Object obj, int offset, int count);
/**
* 方法说明:返回单个对象信息
* @param key
* @param obj
* @return
*/
public Object queryOne(String key, Object obj);
/**
* 方法说明:信息数统计
* @param key
* @param obj
* @return
*/
public Object countQuery(String key, Object obj);
}
|
package chessProgram;
import java.util.Random;
public class HumanPlayerGUI implements Player
{
@Override
public double getFitness(Board board, BlackWhite color)
{
return 0;
}
@Override
public Move chooseMove(Board board, BlackWhite color, int milliSeconds, Random random)
{
PlayerGUI theGUI = new PlayerGUI(board, color);
theGUI.setAlwaysOnTop(true);
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
theGUI.setBounds(10, 10, 420, 180);
theGUI.show();
}
});
thread.start();
while(theGUI.move == null)
{
try
{
Thread.sleep((int)50);
}
catch(Exception l) {};
}
theGUI.dispose();
return theGUI.move;
}
}
|
package com.pel.mathias.merob;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.util.Log;
import java.util.Collection;
/**
* Created by Mathias on 18/12/2015.
*/
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
private Collection<WifiP2pDevice> deviceList;
private WifiP2pManager.PeerListListener myPeerListListener=new WifiP2pManager.PeerListListener() {
@Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
Log.d("test group peers","peers available");
deviceList=peers.getDeviceList();
}
};
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel,
MainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// Check to see if Wi-Fi is enabled and notify appropriate activity
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// request available peers from the wifi p2p manager. This is an
// asynchronous call and the calling activity is notified with a
// callback on PeerListListener.onPeersAvailable()
Log.d("test group action","changed action");
if (mManager != null) {
mManager.requestPeers(mChannel, myPeerListListener);
}
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Respond to new connection or disconnections
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Respond to this device's wifi state changing
}
}
public Collection<WifiP2pDevice> getDeviceList() {
return deviceList;
}
}
|
package Quizizz;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class CharacterFreqFromStringArray {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array");
int length = sc.nextInt();
sc.nextLine();
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int i;
//Count the freq of each character and store them in a hashmap
for(i = 0; i < length; i++){
System.out.println("Enter String at position: " + i);
String s = sc.nextLine();
for(int j = 0; j < s.length(); j ++){
char c = s.charAt(j);
Integer val = map.get(new Character(c));
if(val != null){
map.put(c, new Integer(val + 1));
}else{
map.put(c, 1);
}
}
}
//Get the character occuring the most number of time
Character maxFreqChar = null;
int max = 0;
Set key = map.keySet();
for(Iterator iter = key.iterator(); iter.hasNext();){
Character k = (Character) iter.next();
if(map.get(k) > max){
max = map.get(k);
maxFreqChar = k;
}
}
System.out.println(maxFreqChar);
sc.close();
}
}
|
package enduro.sorter;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class PersonalInfoParser {
private Map<String, String> map = new TreeMap<String, String>();
private String delimiter;
public PersonalInfoParser(String delimiter) {
this.delimiter = delimiter;
}
public Map<String, String> parse(List<String> list) {
for(String line : list) {
String[] tokens = line.split(delimiter);
String id = tokens[0].trim();
String name = tokens[1].trim();
map.put(id, name);
}
return map;
}
}
|
package schr0.tanpopo.capabilities;
import javax.annotation.Nullable;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.FluidTankProperties;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.IFluidTankProperties;
import schr0.tanpopo.init.TanpopoFluids;
import schr0.tanpopo.init.TanpopoItems;
import schr0.tanpopo.item.ItemEssenceGlassBottle;
public class FluidHandlerItemEssenceGlassBottle implements IFluidHandler, ICapabilityProvider
{
private static final int CAPACITY = TanpopoFluids.BOTTLE_VOLUME;
private final ItemStack container;
public FluidHandlerItemEssenceGlassBottle(ItemStack container)
{
this.container = container;
}
@Override
public IFluidTankProperties[] getTankProperties()
{
return new FluidTankProperties[]
{
new FluidTankProperties(this.getFluid(), CAPACITY)
};
}
@Override
public int fill(FluidStack resource, boolean doFill)
{
FluidStack fluidStack = this.getFluid();
if (fluidStack != null)
{
return 0;
}
else
{
if (doFill)
{
this.setFill();
}
return CAPACITY;
}
}
@Override
@Nullable
public FluidStack drain(FluidStack resource, boolean doDrain)
{
FluidStack fluidStack = this.getFluid();
if (((fluidStack != null) && (resource != null)) && fluidStack.isFluidEqual(resource))
{
return this.drain(resource.amount, doDrain);
}
return (FluidStack) null;
}
@Override
@Nullable
public FluidStack drain(int maxDrain, boolean doDrain)
{
FluidStack fluidStack = this.getFluid();
if (fluidStack == null)
{
return (FluidStack) null;
}
else
{
if (doDrain)
{
this.setEmpty();
}
return fluidStack;
}
}
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing)
{
return capability.equals(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY);
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing)
{
if (capability.equals(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY))
{
return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(this);
}
return null;
}
// TODO /* ======================================== MOD START =====================================*/
private FluidStack getFluid()
{
if (ItemEssenceGlassBottle.isFill(this.container))
{
return new FluidStack(TanpopoFluids.ESSENCE, CAPACITY);
}
else
{
return (FluidStack) null;
}
}
private void setFill()
{
this.container.deserializeNBT(new ItemStack(TanpopoItems.ESSENCE_GLASS_BOTTLE).serializeNBT());
}
private void setEmpty()
{
this.container.deserializeNBT(new ItemStack(Items.GLASS_BOTTLE).serializeNBT());
}
}
|
package com.ducph.consoledrawing.command;
import com.ducph.consoledrawing.exception.InvalidCommandParams;
import org.junit.Test;
public class BucketFillCommandTest {
@Test
public void testCreate() {
new BucketFillCommand( "1", "1", "o");
}
@Test(expected = InvalidCommandParams.class)
public void testCreateInvalid() {
new BucketFillCommand( "-1", "1", "o");
}
@Test(expected = InvalidCommandParams.class)
public void testCreateInvalid1() {
new BucketFillCommand( "1", "-1", "o");
}
@Test(expected = InvalidCommandParams.class)
public void testCreateInvalid2() {
new BucketFillCommand( "1", "1");
}
@Test(expected = InvalidCommandParams.class)
public void testCreateInvalid3() {
new BucketFillCommand( "1");
}
@Test(expected = InvalidCommandParams.class)
public void testCreateInvalid4() {
new BucketFillCommand();
}
} |
package com.example.jh.picdemo.bean;
import java.io.File;
/**
* Created by lenovo on 2016/11/27.
*/
public class Bean {
private String filePath;
private boolean isChecked;
private boolean isShow;
private int id;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
public boolean isShow() {
return isShow;
}
public void setShow(boolean show) {
isShow = show;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
|
/*******************************************************
* Created by Marneus901 *
* © 2013 Dynamac.org *
********************************************************
* Dynamac's custom log system. *
********************************************************/
package org.dynamac.enviroment;
import java.util.ArrayList;
public class Logger {
private static ArrayList<String> logs = new ArrayList<String>();
private String parent;
public Logger(){
this.parent="[Client]";
}
public Logger(String parent){
this.parent="["+parent+"]";
}
public void log(String s){
//Setup custom output stream
logs.add(parent+" "+s);
System.out.println(parent+" "+s);
if(logs.size()>100)
logs.remove(0);
Data.clientGUI.updateLog();
}
public static void debug(String s){
System.out.println("[DEBUG] "+s);
}
public static String[] getLogs(){
return logs.toArray(new String[]{});
}
}
|
package Exceptions;
public class ClientNotFoundException extends Exception {
public ClientNotFoundException() {
super("The client is not found in the system.");
}
}
|
package com.bulldozer.simulation.console;
import com.bulldozer.domain.bulldozer.BulldozerFactory;
import com.bulldozer.domain.bulldozer.IBulldozerController;
import com.bulldozer.domain.site.SiteFactory;
import com.bulldozer.domain.site.TraversableSite;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ConsoleSimulationRunner {
public static void main(String[] args) {
String[][] input = readFile(args[0]);
ConsoleView consoleView = new ConsoleView();
TraversableSite site = SiteFactory.createSite(input);
IBulldozerController bulldozer = BulldozerFactory.createBulldozer(site);
ConsoleSimulationController consoleSimulationController = new ConsoleSimulationController(consoleView, bulldozer, site, input);
consoleSimulationController.start();
}
private static String[][] readFile(String fileName) {
BufferedReader reader;
List<String[]> result = new ArrayList<>();
try {
reader = new BufferedReader(new FileReader(fileName));
String line = reader.readLine();
while (line != null) {
String[] blocksStr = line.split("");
result.add(blocksStr);
// read next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return result.toArray(new String[result.size()][result.get(0).length]);
}
}
|
package org.ah.minecraft.tweaks;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class TenHourSleep extends Tweak {
@Override
public void init(final Server server, Plugin plugin) {
server.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override
public void run() {
for (Player p : Bukkit.getOnlinePlayers()) {
p.setSleepingIgnored(true);
if (p.isSleeping()) {
if (p.getSleepTicks() > 20) {
p.getWorld().setFullTime(p.getWorld().getFullTime() + 8000);
}
}
}
}
}, 4, 4);
}
}
|
package com.myhome.lee;
import org.apache.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApimockSpringboot2Application {
private static Logger logger = Logger.getLogger(ApimockSpringboot2Application.class);
public static void main(String[] args) {
SpringApplication.run(ApimockSpringboot2Application.class, args);
logger.info("输出info");
logger.debug("输出debug");
logger.error("输出error");
}
}
|
package com.telecom.controller;
import com.telecom.model.PageResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by lee on 01/01/2017.
*/
@Controller
@RequestMapping(value = "/user")
public class UserController {
@RequestMapping("/valid")
@ResponseBody
public PageResult<Boolean> valid(@RequestParam(value = "name", required = true, defaultValue = "") String name,
@RequestParam(value = "password", required = true, defaultValue = "") String password) {
return null;
}
}
|
package com.penzias.entity;
import java.util.Date;
/**
*
* 描述:机构状态信息表<br/>
* 作者:Bob <br/>
* 修改日期:2015年12月16日 - 下午5:26:37<br/>
* E-mail: sireezhang@163.com<br/>
*
*/
public class DepartStatusInfo {
private Integer infoid;
//机构编码
private String depbm;
//数据来自于sm_codeitem的code字段,codeid值为ZA
private String status;
//生成时间
private Date createdate;
//机构信息
private String description;
public Integer getInfoid() {
return infoid;
}
public void setInfoid(Integer infoid) {
this.infoid = infoid;
}
public String getDepbm() {
return depbm;
}
public void setDepbm(String depbm) {
this.depbm = depbm;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
} |
package com.rs.utils.spawning;
import com.rs.game.World;
import com.rs.game.WorldObject;
import com.rs.game.WorldTile;
//import com.rs.game.player.Player;
public enum ObjectSpawning {
/** START HOME OBJECTS */
EXIT_PORTAL(11368, 3994, 6108, 0, 1 ),
DUEL_PORTAL(11356, 3604, 3375, 0, 0), //white portal
ARMOUR_STAND(13715, 2655, 4560, 1, 2), //repair armor
BANK_BOOTH_1(36786, 4383, 5923, 0, 0),
BANK_BOOTH_2(36786, 4382, 5923, 0, 0),
STATUE(26969, 3609, 3367, 0, 0), // Bank Deposit
BANK_BOOTH_3(36786, 4381, 5923, 0, 0),
BANK_BOOTH_4(36786, 4380, 5923, 0, 0),
ALTAR(409, 3601, 3375, 0, 2),
ANVIL_1(24744, 0, 0, 0, 0),
ANVIL_2(2783, 4377, 5915, 0, 0), // Two extra anvils aren't really
ANVIL_3(2783, 4377, 5911, 0, 0),
BCHEST(4111, 2854, 3532, 0, 0),
THIEF_STALL_1(4875, 2476, 4466, 0, 0), // Food Stall
THIEF_STALL_2(4876, 2476, 4465, 0, 0), // Gen. Stall
THIEF_STALL_3(4877, 2476, 4464, 0, 0), // Magic Stall
THIEF_STALL_4(4878, 2476, 4463, 0, 0), // Scimitar Stall
PORTAL(13405, 3602, 3362, 0, 1), //purple portal
PORTAL_2(2469, 3615, 3362, 0, 1), //eternal boss portal
PORTAL_3(6282, 3602, 3366, 0, 1), //overlord reaper portal
COMP_CAPE(2563, 3611, 3367, 0, 0), //completionist cape stand
/** END HOME OBJECTS */
/* The DUNG spawns are pretty useless,
* you can move them somewhere else if
* you want! --------------------------v end below
DUNG_1(49766, 89, 721, 2, 0), v
DUNG_2(49768, 88, 721, 2, 0), v
DUNG_3(49770, 87, 721, 2, 0), v
DUNG_4(49772, 86, 721, 2, 0), v
DUNG_5(49774, 85, 721, 2, 0), */
//Donator zone
DONATOR_1(1306, 1619, 4533, 0, 0),
DONATOR_2(1306, 1619, 4529, 0, 0),
DONATOR_3(1306, 1627, 4532, 0, 0),
DONATOR_4(1306, 1627, 4526, 0, 0),
DONATOR_5(1306, 1626, 4523, 0, 0),
DONATOR_6(1306, 1620, 4523, 0, 0),
DONATOR_7(1309, 1631, 4530, 0, 0),
DONATOR_8(1309, 1635, 4529, 0, 0),
DONATOR_9(1309, 1637, 4526, 0, 0),
DONATOR_10(1309, 1638, 4524, 0, 0),
DONATOR_11(1309, 1639, 4519, 0, 0),
DONATOR_12(1309, 1637, 4516, 0, 0),
DONATOR_13(1307, 1636, 4509, 0, 0),
DONATOR_14(1307, 1639, 4506, 0, 0),
DONATOR_15(1307, 1637, 4503, 0, 0),
DONATOR_16(1307, 1636, 4498, 0, 0),
DONATOR_17(1307, 1635, 4501, 0, 0),
DONATOR_18(1307, 1632, 4501, 0, 0),
DONATOR_19(1307, 1630, 4503, 0, 0),
DONATOR_20(1307, 1628, 4501, 0, 0),
DONATOR_21(114, 1605, 4510, 0, 0),
DONATOR_22(45076, 1594, 4536, 0, 0),
DONATOR_23(45076, 1597, 4536, 0, 0),
DONATOR_24(45076, 1600, 4536, 0, 0),
DONATOR_25(45076, 1603, 4536, 0, 0),
DONATOR_26(45076, 1606, 4536, 0, 0),
DONATOR_27(45076, 1609, 4536, 0, 0),
DONATOR_28(45076, 1612, 4536, 0, 0),
DONATOR_29(5999, 1582, 4535, 0, 0),
DONATOR_30(5999, 1585, 4535, 0, 0),
DONATOR_31(5999, 1588, 4535, 0, 0),
DONATOR_32(5999, 1591, 4535, 0, 0),
DONATOR_33(5999, 1594, 4535, 0, 0),
DONATOR_34(37651, 1600, 4503, 0, 3),
DONATOR_35(49037, 1607, 4507, 0, 0),
DONATOR_36(37823, 1568, 4515, 0, 0),
DONATOR_37(37823, 1564, 4524, 0, 0),
DONATOR_38(37823, 1561, 4520, 0, 0),
DONATOR_39(37823, 1562, 4515, 0, 0),
DONATOR_40(37823 ,1567, 4530, 0, 0),
DONATOR_41(37823, 1561, 4528, 0, 0),
DONATOR_42(37823, 1573, 4523, 0, 0),
DONATOR_43(37823, 1579, 4513, 0, 0),
DONATOR_44(37823, 1583, 4509, 0, 0),
DONATOR_45(14859, 1574, 4535, 0, 0),
DONATOR_46(14859, 1574, 4538, 0, 0),
DONATOR_47(14859, 1575, 4538, 0, 0),
DONATOR_48(14859, 1576, 4538, 0, 0),
DONATOR_49(14859, 1577, 4538, 0, 0),
DONATOR_50(14859, 1578, 4538, 0, 0),
DONATOR_51(14859, 1579, 4538, 0, 0),
DONATOR_52(14859, 1581, 4537, 0, 0),
DONATOR_53(14859, 1580, 4537, 0, 0),
DONATOR_54(14859, 1574, 4536, 0, 0),
DONATOR_55(14859, 1573, 4535, 0, 0),
DONATOR_56(14859, 1572, 4535, 0, 0),
DONATOR_57(14859, 1572, 4533, 0, 0),
DONATOR_58(14859, 1573, 4533, 0, 0),
DONATOR_59(14859, 1574, 4533, 0, 0),
DONATOR_60(14859, 1575, 4533, 0, 0),
DONATOR_61(14859, 1576, 4533, 0, 0),
DONATOR_62(14859, 1577, 4533, 0, 0),
DONATOR_63(14859, 1576, 4536, 0, 0),
DONATOR_64(14859, 1577, 4536, 0, 0),
DONATOR_65(14859, 1578, 4536, 0, 0),
DONATOR_66(6650, 1597, 4536, 0, 0),
DONATOR_67(78041, 1603, 4504, 0, 0),
RUNITE_ORE_1(14860, 3295, 3310, 0, -3), // Nearest to furnace
RUNITE_ORE_2(14860, 3296, 3307, 0, -3),
RUNITE_ORE_3(14860, 3303, 3307, 0, -3),
RUNITE_ORE_4(14860, 3293, 3297, 0, -3),
RUNITE_ORE_5(14860, 3302, 3298, 0, -3),
RUNITE_ORE_6(14860, 3303, 3311, 0, -3),
MAGIC_TREE_1(1306, 4450, 4540, 0, 0),
MAGIC_TREE_2(1306, 4450, 4545, 0, 0),
FURNACE1(11666, 4376, 5912, 0, 0),
OBELISK(29945, 4389, 5916, 0, 0), // Summoning Obelisk
ZAROS_ALTAR_PC(47120, 4389, 5911, 0, 1),
CORP(-1, 3671, 2976, 0, 0),
RC_ALTAR_1(2478, 4465, 4542, 0, -2),
RC_ALTAR_2(2479, 4468, 4542, 0, -2),
RC_ALTAR_3(2480, 4471, 4542, 0, -2),
RC_ALTAR_4(2481, 4474, 4542, 0, -2),
RC_ALTAR_5(2482, 4477, 4542, 0, -2),
RC_ALTAR_6(2483, 4465, 4537, 0, -2),
RC_ALTAR_7(2484, 4468, 4537, 0, -2),
RC_ALTAR_8(2485, 4471, 4537, 0, -2),
RC_ALTAR_9(2486, 4474, 4537, 0, -2),
RC_ALTAR_10(2487, 4477, 4537, 0, -2),
RC_ALTAR_11(2488, 4470, 4534, 0, -2),
RC_AREA_1(36786, 4472, 4540, 0, 2),
RC_AREA_2(36786, 2510, 3169, 0, -2),
WALL_1(848, 4456, 4533, 0, -1), // Just walls
WALL_2(848, 4456, 4531, 0, -1), // at RC area
WALL_3(848, 4456, 4529, 0, -1),
WALL_4(848, 4456, 4553, 0, -1),
WALL_5(848, 4456, 4555, 0, -1),
WALL_6(848, 4456, 4556, 0, -1),
WALL_7(848, 4456, 4559, 0, -1),
WALL_8(848, 4456, 4561, 0, -1),
WALL_9(848, 4456, 4563, 0, -1),
NOTICE_BOARD(40760, 3600, 3352, 0, 0), // TODO: Put this somewhere
SKELY_1(666, 2830, 3277, 0, 0),
SKELY_2(666, 2830, 3281, 0, 0),
SKELY_3(666, 2829, 3278, 0, 0),
SKULL_1(736, 2830, 3279, 0, 0),
SKULL_2(736, 2830, 3280, 0, 0),
SKULL_3(736, 2829, 3277, 0, 0),
BOX_1(1, 3186, 5729, 0, 0),
BOX_2(1, 3185, 5729, 0, 0),
BOX_3(1, 3187, 5729, 0, 0),
BOX_4(1, 3188, 5729, 0, 0);
private int id;
private int x;
private int y;
private int z;
private int face;
ObjectSpawning(int id, int x, int y, int z, int face) {
this.id = id;
this.x = x;
this.y = y;
this.z = z;
this.face = face;
}
public static void spawnObjects() {
/*Random Objects*/
World.spawnObject(new WorldObject(38150, 10, 0, 3420, 5272, 0), true);//portal at dung
//World.spawnObject(new WorldObject(2213, 10, 1, 3622, 3364, 0), true);//Bank new home
//World.spawnObject(new WorldObject(2213, 10, 1, 3622, 3365, 0), true);//Bank new home
World.spawnObject(new WorldObject(172, 10, 0, 3611, 3361, 0), true);//Chest
World.spawnObject(new WorldObject(13715, 10, 0, 3615, 3368, 0), true);//repair armour stand
World.spawnObject(new WorldObject(2213, 10, 1, 3594, 3357, 0), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 3594, 3358, 0), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 3594, 3359, 0), true);//Bank
//newhome
//World.spawnObject(new WorldObject(2213, 10, 1, 3617, 3368, 0), true);//Bank
//World.spawnObject(new WorldObject(2213, 10, 1, 3617, 3367, 0), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 3617, 3366, 0), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 3617, 3365, 0), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 3617, 3364, 0), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 3617, 3363, 0), true);//Bank
//World.spawnObject(new WorldObject(2213, 10, 1, 3617, 3362, 0), true);//Bank
//World.spawnObject(new WorldObject(2213, 10, 1, 3617, 3361, 0), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2656, 4575, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2655, 4575, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2654, 4575, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2653, 4575, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2652, 4575, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2651, 4575, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2650, 4575, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2649, 4575, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2648, 4575, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2647, 4575, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2647, 4576, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2647, 4577, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2647, 4578, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2647, 4579, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2647, 4580, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2647, 4581, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2647, 4582, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2647, 4583, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2656, 4584, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2655, 4584, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2654, 4584, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2653, 4584, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2652, 4584, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2651, 4584, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2649, 4584, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2648, 4584, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2656, 4583, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2656, 4582, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2656, 4581, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2656, 4580, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2656, 4579, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2656, 4578, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2656, 4577, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 0, 2650, 4584, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2647, 4584, 1), true);//Bank
World.spawnObject(new WorldObject(2213, 10, 1, 2656, 4576, 1), true);//Bank
/**end of bank**/
World.spawnObject(new WorldObject(1, 10, 1, 2671, 4579, 1), true);//Box
World.spawnObject(new WorldObject(1, 10, 1, 2651, 4598, 1), true);//Box
World.spawnObject(new WorldObject(1, 10, 1, 2632, 4578, 1), true);//Box
World.spawnObject(new WorldObject(1, 10, 1, 2651, 4559, 1), true);//Box
World.spawnObject(new WorldObject(172, 10, 0, 2658, 4560, 1), true);//Chest
World.spawnObject(new WorldObject(13715, 10, 0, 2595, 5586, 0), true);//repair armour stand
World.spawnObject(new WorldObject(13704, 10, 0, 2582, 5607, 0), true);//Work bench at home
/** Delete Objects **/
/**Dele Objects List**/
World.deleteObject(new WorldTile(3056, 5484, 0));
World.deleteObject(new WorldTile(2476, 4444, 0));
World.deleteObject(new WorldTile(2475, 4446, 0));
World.deleteObject(new WorldTile(2478, 4447, 0));
World.deleteObject(new WorldTile(2488, 4421, 0));
World.deleteObject(new WorldTile(2486, 4421, 0));
World.deleteObject(new WorldTile(2486, 4424, 0));
World.deleteObject(new WorldTile(2471, 4450, 0));
World.deleteObject(new WorldTile(2467, 4423, 0));
World.deleteObject(new WorldTile(2464, 4423, 0));
World.deleteObject(new WorldTile(2464, 4421, 0));
World.deleteObject(new WorldTile(2485, 4436, 0));
World.deleteObject(new WorldTile(2483, 4438, 0));
World.deleteObject(new WorldTile(2487, 4439, 0));
World.deleteObject(new WorldTile(2486, 4437, 0));
World.deleteObject(new WorldTile(2484, 4436, 0));
World.deleteObject(new WorldTile(2401, 2843, 0));
World.deleteObject(new WorldTile(2404, 2833, 0));
World.deleteObject(new WorldTile(2401, 2833, 0));
World.deleteObject(new WorldTile(2405, 2828, 0));
World.deleteObject(new WorldTile(2405, 2827, 0));
World.deleteObject(new WorldTile(2400, 2828, 0));
World.deleteObject(new WorldTile(2400, 2827, 0));
World.deleteObject(new WorldTile(2410, 2834, 0));
World.deleteObject(new WorldTile(1634, 5253, 0));
World.deleteObject(new WorldTile(1605, 5265, 0));
World.deleteObject(new WorldTile(1610, 5289, 0));
World.deleteObject(new WorldTile(1626, 5302, 0));
World.deleteObject(new WorldTile(2592, 5591, 0));
World.deleteObject(new WorldTile(2587, 5602, 0));
World.deleteObject(new WorldTile(2590, 5605, 0));
World.deleteObject(new WorldTile(2592, 5602, 0));
World.deleteObject(new WorldTile(2590, 5603, 0));
World.deleteObject(new WorldTile(2588, 5604, 0));
World.deleteObject(new WorldTile(2586, 5603, 0));
World.deleteObject(new WorldTile(2582, 5606, 0));
World.deleteObject(new WorldTile(2590, 5606, 0));
World.deleteObject(new WorldTile(2586, 5602, 0));
World.deleteObject(new WorldTile(2585, 5602, 0));
World.deleteObject(new WorldTile(2590, 5602, 0));
World.deleteObject(new WorldTile(2585, 5605, 0));
World.deleteObject(new WorldTile(2589, 5602, 0));
World.deleteObject(new WorldTile(2588, 5602, 0));
World.deleteObject(new WorldTile(2588, 5606, 0));
World.deleteObject(new WorldTile(2585, 5606, 0));
World.deleteObject(new WorldTile(2586, 5606, 0));
World.deleteObject(new WorldTile(2589, 5606, 0));
World.deleteObject(new WorldTile(2589, 5605, 0));
World.deleteObject(new WorldTile(2588, 5605, 0));
World.deleteObject(new WorldTile(2587, 5605, 0));
World.deleteObject(new WorldTile(2586, 5605, 0));
World.deleteObject(new WorldTile(2581, 5605, 0));
World.deleteObject(new WorldTile(2592, 5600, 0));
World.deleteObject(new WorldTile(2591, 5600, 0));
World.deleteObject(new WorldTile(2590, 5600, 0));
World.deleteObject(new WorldTile(2589, 5600, 0));
World.deleteObject(new WorldTile(2588, 5600, 0));
World.deleteObject(new WorldTile(2582, 5603, 0));
World.deleteObject(new WorldTile(2582, 5604, 0));
World.deleteObject(new WorldTile(2582, 5601, 0));
World.deleteObject(new WorldTile(2583, 5600, 0));
World.deleteObject(new WorldTile(2582, 5600, 0));
World.deleteObject(new WorldTile(2586, 5607, 0));
World.deleteObject(new WorldTile(2587, 5607, 0));
World.deleteObject(new WorldTile(2592, 5607, 0));
World.deleteObject(new WorldTile(2593, 5607, 0));
World.deleteObject(new WorldTile(2593, 5606, 0));
World.deleteObject(new WorldTile(2593, 5605, 0));
World.deleteObject(new WorldTile(2593, 5604, 0));
World.deleteObject(new WorldTile(2593, 5603, 0));
World.deleteObject(new WorldTile(2787, 4247, 0));
World.deleteObject(new WorldTile(2785, 4252, 0));
World.deleteObject(new WorldTile(2786, 4249, 0));
World.deleteObject(new WorldTile(2781, 4249, 0));
World.deleteObject(new WorldTile(2784, 4247, 0));
World.deleteObject(new WorldTile(2780, 4247, 0));
World.deleteObject(new WorldTile(2787, 4247, 0));
World.deleteObject(new WorldTile(2782, 4252, 0));
World.deleteObject(new WorldTile(2442, 3082, 0));
World.deleteObject(new WorldTile(2441, 3082, 0));
World.deleteObject(new WorldTile(2446, 3089, 0)); //castle wars door
World.deleteObject(new WorldTile(2446, 3090, 0)); //castle wars door
World.deleteObject(new WorldTile(2700, 3247, 0));
World.deleteObject(new WorldTile(2696, 3250, 0));
World.deleteObject(new WorldTile(2696, 3250, 1));
World.deleteObject(new WorldTile(2831, 3275, 0));
World.deleteObject(new WorldTile(2837, 3272, 0));
World.deleteObject(new WorldTile(4510, 5607, 0));
World.deleteObject(new WorldTile(3296, 3306, 0));
World.deleteObject(new WorldTile(4382, 5914, 0));
World.deleteObject(new WorldTile(1579, 4513, 0));
World.deleteObject(new WorldTile(1580, 4519, 0));
World.deleteObject(new WorldTile(1568, 4522, 0));
World.deleteObject(new WorldTile(1564, 4515, 0));
World.deleteObject(new WorldTile(1555, 4506, 0));
World.deleteObject(new WorldTile(1568, 4498, 0));
World.deleteObject(new WorldTile(1575, 4498, 0));
World.deleteObject(new WorldTile(1584, 4494, 0));
World.deleteObject(new WorldTile(1584, 4508, 0));
World.deleteObject(new WorldTile(1618, 4517, 0));
World.deleteObject(new WorldTile(1623, 4510, 0));
World.deleteObject(new WorldTile(1627, 4514, 0));
World.deleteObject(new WorldTile(1576, 4524, 0));
World.deleteObject(new WorldTile(1576, 4531, 0));
World.deleteObject(new WorldTile(1582, 4530, 0));
World.deleteObject(new WorldTile(1587, 4534, 0));
World.deleteObject(new WorldTile(1572, 4515, 0));
World.deleteObject(new WorldTile(1567, 4530, 0));
World.deleteObject(new WorldTile(1561, 4525, 0));
World.deleteObject(new WorldTile(1561, 4519, 0));
World.deleteObject(new WorldTile(1598, 4526, 0));
World.deleteObject(new WorldTile(1608, 4531, 0));
World.deleteObject(new WorldTile(1612, 4526, 0));
World.deleteObject(new WorldTile(1617, 4524, 0));
World.deleteObject(new WorldTile(1618, 4531, 0));
World.deleteObject(new WorldTile(1614, 4534, 0));
World.deleteObject(new WorldTile(1622, 4527, 0));
World.deleteObject(new WorldTile(1629, 4526, 0));
World.deleteObject(new WorldTile(1634, 4523, 0));
World.deleteObject(new WorldTile(1638, 4520, 0));
World.deleteObject(new WorldTile(1626, 4532, 0));
World.deleteObject(new WorldTile(1621, 4521, 0));
World.deleteObject(new WorldTile(1625, 4519, 0));
World.deleteObject(new WorldTile(1631, 4517, 0));
World.deleteObject(new WorldTile(1638, 4511, 0));
World.deleteObject(new WorldTile(1634, 4506, 0));
World.deleteObject(new WorldTile(1635, 4501, 0));
World.deleteObject(new WorldTile(1629, 4502, 0));
World.deleteObject(new WorldTile(1629, 4496, 0));
World.deleteObject(new WorldTile(1623, 4496, 0));
World.deleteObject(new WorldTile(1619, 4504, 0));
World.deleteObject(new WorldTile(1617, 4508, 0));
for (ObjectSpawning obj : ObjectSpawning.values()) {
World.spawnObject(new WorldObject(obj.id, 10, obj.face, obj.x, obj.y, obj.z), true);
}
}
}
|
package ai;
import enemy.Enemy;
import java.awt.Point;
public interface AI {
public Point move();
public void reset();
public void playerSeen();
public void setEnemy(Enemy enemy);
}
|
package com.szcinda.express.dto;
import lombok.Data;
import java.io.Serializable;
@Data
public class RPAInsertToDBDto implements Serializable {
private String financialReportId;//报表ID
private double volume;//体积
private double inShippingFee;//运费
private double inDeliveryFee;//送货费
private double inUnloadFee;//卸货费
private double inPickupFee;//提货费
private double inSpecialFee;//特殊费用
private double insuranceFee;//保险费
private double outPickupFee;//提货费
private double outTransportFee;//运费
private double outShippingFee;//配送费
public static void main(String[] args) {
double d1 = 89.67;
double d2 = 56.98;
System.out.println(d1 + d2);
}
}
|
/*
* 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 Modelos;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**
*
* @author Pc
*/
public class Conexion {
/*
Comentario Jesús Aldea 13/01/2020: clase Conexion para construir método Driver y de conexión
a la base de datos mediante el objeto 'jdbc' que facilita Spring.
Esta clase será instanciada para realizar la conexión desde cada una de las clases
'Controller' que realicen operaciones CRUD sobre la base de datos especificada en el
setUrl.
*/
public DriverManagerDataSource conectar()
{
DriverManagerDataSource dataSource=new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost/motorland");
dataSource.setUsername("root");
dataSource.setPassword("");
return dataSource;
}
}
|
package playground.ds;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.core.IsNot.not;
import static org.junit.jupiter.api.Assertions.*;
class VectorTest {
Vector vector;
int[] values = {1, 2, 3, 2, 5};
@BeforeEach
void setUp() {
vector = new Vector(values);
}
@Test
void size() {
assertEquals(values.length, vector.size());
}
@Test
void capacity() {
assertEquals(16, vector.capacity());
}
@Test
void isEmpty() {
Vector emptyVector = new Vector();
assertTrue(emptyVector.isEmpty());
assertFalse(vector.isEmpty());
}
@Test
void at() {
assertEquals(values[2], vector.at(2));
}
@Test
void push() {
int element = 6;
vector.push(element);
assertEquals(element, vector.at(vector.length - 1));
int currentLength = vector.size();
for (int i = 0; i < 20; i++) {
vector.push(i);
}
System.out.println(vector);
assertEquals(currentLength + 20, vector.size());
}
@Test
void insert() {
int element = 2;
int idx = 2;
vector.insert(idx, element);
assertEquals(element, vector.at(idx));
}
@Test
void prepend() {
int element = 9;
vector.prepend(element);
assertEquals(element, vector.at(0));
}
@Test
void pop() {
int lastElement = values[values.length - 1];
assertEquals(lastElement, vector.pop());
}
@Test
void delete() {
int idxToDelete = 3;
System.out.println(vector);
int deletedElement = vector.delete(idxToDelete);
int expectedElement = values[idxToDelete + 1];
System.out.println(vector);
assertEquals(expectedElement, vector.at(idxToDelete));
}
@Test
void remove() {
int elementToDelete = 2;
System.out.println(vector);
vector.remove(elementToDelete);
System.out.println(vector);
List<Integer> vectorList = IntStream.of(vector.arr).boxed().collect(Collectors.toList());
assertThat(vectorList, not(hasItem(elementToDelete)));
}
@Test
void find() {
int idxToFind = 2;
int elementToFind = values[2];
int idx = vector.find(elementToFind);
assertEquals(idxToFind, idx);
elementToFind = 99;
idx = vector.find(elementToFind);
assertEquals(-1, idx);
}
@Test
void resize() {
int newCapacity = 21;
vector.resize(newCapacity);
System.out.println(vector);
assertEquals(newCapacity, vector.capacity());
}
} |
package com.hb.rssai.view.iView;
import com.hb.rssai.bean.ResBase;
import com.hb.rssai.bean.ResInfo;
import com.hb.rssai.bean.ResUserInformation;
/**
* Created by Administrator on 2017/10/28 0028.
*/
public interface IRecordView {
void loadError(Throwable throwable);
void setInfoResult(ResInfo resInfo);
void setListResult(ResUserInformation resUserInformation);
String getUserId();
String getInfoId();
int getPageNum();
void showDeleteResult(ResBase resBase);
}
|
package file;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
public class FileOps {
String str = "";
public static void writeTo(String list) throws IOException {
File f = new File("myData.txt");
FileWriter fw = new FileWriter(f, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.newLine();
bw.write(list + " ");
bw.flush();
bw.close();
}
public static String readFrom() throws FileNotFoundException, IOException {
String str = "";
File f = new File("myData.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
while (br.ready()) {
str += br.readLine()+" \n";
}
return str;
}
static String st;
static int occ;
public static int countForLine() throws FileNotFoundException, IOException {
InputStream is = new BufferedInputStream(new FileInputStream("myData.txt"));
try {
byte[] c = new byte[1024];
int readChars = is.read(c);
if (readChars == -1) {
// bail out if nothing to read
return 0;
}
// make it easy for the optimizer to tune this loop
int count = 0;
while (readChars == 1024) {
for (int i = 0; i < 1024;) {
if (c[i++] == '\n') {
++count;
}
}
readChars = is.read(c);
}
// count remaining characters
while (readChars != -1) {
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
readChars = is.read(c);
}
return count == 0 ? 1 : count;
} finally {
is.close();
}
}
}
|
package com.maven.threadPool;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.concurrent.Future;
public class TaskExecutor {
/**
* 标注@Async注解的方法和调用的方法一定不能在同一个类下,这样的话注解会失效
* 因为@Transactional和@Async注解的实现都是基于Spring的AOP,而AOP的实现是基于动态代理模式实现的。
* 那么注解失效的原因就很明显了,有可能因为调用方法的是对象本身而不是代理对象,因为没有经过Spring容器。
*/
public static void main(String[] args) {
AnnotationConfigApplicationContext taskExecutorConfig = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
AsyncTaskService asyncTaskService = taskExecutorConfig.getBean(AsyncTaskService.class);
for (int i = 1; i <= 5; i++) {
asyncTaskService.executeAsyncTask(i);
Future<String> stringFuture = asyncTaskService.executeAsyncFuture(i);
System.out.println(stringFuture);
}
AnnotationConfigApplicationContext taskExecutorConfigImpl = new AnnotationConfigApplicationContext(TaskExecutorConfigImpl.class);
AsyncTaskService asyncTaskServiceImpl = taskExecutorConfigImpl.getBean(AsyncTaskService.class);
for (int i = 6; i <= 10; i++) {
asyncTaskServiceImpl.executeAsyncTaskPlus(i);
}
System.out.println("主线程继续执行222222222222222:::::" + Thread.currentThread().getName());
}
} |
package edu.monash.mymonashmate.entities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class MatchCriteria implements Serializable{
public final static int COND_DISTANCE = 99;
private List<Integer> sourceIDs = new ArrayList<Integer>();
public List<Integer> getSourceIDs() {
return sourceIDs;
}
public void setSourceIDs(List<Integer> sourceIDs) {
this.sourceIDs = sourceIDs;
}
public List<MatchCriteriaItem> getCriteriaItems() {
return criteriaItems;
}
public void setCriteriaItems(List<MatchCriteriaItem> criteriaItems) {
this.criteriaItems = criteriaItems;
}
private List<MatchCriteriaItem> criteriaItems = new ArrayList<MatchCriteriaItem>();
}
|
package examen2p2_andresnuila;
public class Procesador extends Parte {
private int nucleos;
private double velocidad;
public Procesador() {
}
public Procesador(int nucleos, double velocidad, int tiempo) {
super(tiempo);
this.nucleos = nucleos;
this.velocidad = velocidad;
}
public int getNucleos() {
return nucleos;
}
public void setNucleos(int nucleos) {
this.nucleos = nucleos;
}
public double getVelocidad() {
return velocidad;
}
public void setVelocidad(double velocidad) {
this.velocidad = velocidad;
}
@Override
public String toString() {
return "Procesador: nucleos: " + nucleos + ", velocidad=" + velocidad + '}';
}
}
|
package com.uptc.prg.maze.resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* <b>Image Converter class</b>
* Utilities for converting and changing the values of the pixels of a certain image.
*
* @author Luis Alejandro Quiroga Gómez
* @since 4/02/2020
*/
public class ImageConverter {
private static final int COLOR_THRESHOLD = 500;
/**
* Changes the color of an image to a gray scale version of it. Given the file input path and an
* file output path.
*
* @param filePathInput The path to the image to change.
* @param filePathOutput The path to the gray scaled image.
* @author Luis Alejandro Quiroga Gómez
* @author MEMORYNOTFOUND (https://memorynotfound.com/convert-image-grayscale-java/)
*/
public final void convertToGrayScale(String filePathInput, String filePathOutput) {
File outputImage;
File inputImage = new File(filePathInput);
try {
BufferedImage image = ImageIO.read(inputImage);
BufferedImage result = new BufferedImage(
image.getWidth(),
image.getHeight(),
BufferedImage.TYPE_INT_RGB
);
this.convertImageRGBtoGrayScale(image, result);
outputImage = new File(filePathOutput);
ImageIO.write(result, "png", outputImage);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Changes the color of an image to a gray scale version of it. Given a certain
* {@link BufferedImage}.
*
* @param imageToConvert The image to convert to gray scale.
* @return The image converted to gray scale with a certain threshold.
* @author Luis Alejandro Quiroga Gómez
* @author MEMORYNOTFOUND (https://memorynotfound.com/convert-image-grayscale-java/)
*/
public final BufferedImage convertToGrayScale(BufferedImage imageToConvert) {
BufferedImage result = new BufferedImage(
imageToConvert.getWidth(),
imageToConvert.getHeight(),
BufferedImage.TYPE_INT_RGB
);
this.convertImageRGBtoGrayScale(imageToConvert, result);
return result;
}
/*====================================== PRIVATE METHODS =====================================*/
private void convertImageRGBtoGrayScale(BufferedImage image, BufferedImage result) {
Color color;
Color newColor;
int red;
int blue;
int green;
for (int i = 0; i < image.getWidth(); i++) {
for (int e = 0; e < image.getHeight(); e++) {
color = new Color(image.getRGB(i, e));
red = (int) (color.getRed() * 0.299);
blue = (int) (color.getBlue() * 0.587);
green = (int) (color.getGreen() * 0.114);
newColor = new Color(
red + blue + green,
red + blue + green,
red + blue + green
);
newColor = this.colorToBlackOrWhite(newColor);
result.setRGB(i, e, newColor.getRGB());
}
}
}
private Color colorToBlackOrWhite(Color color) {
int colorValue = color.getBlue() + color.getGreen() + color.getRed();
if (colorValue > ImageConverter.COLOR_THRESHOLD) {
return Color.WHITE;
} else {
return Color.BLACK;
}
}
}
|
package models.excel;
import lombok.Data;
import models.entity.TaskTables;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import util.ExcelUtil;
import util.FileTool;
import util.ImageUtil;
import util.LocalStoreTool;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
/**
* Created by shanmao on 15-12-16.
*/
@Data
public class ShopkeeperTaskBook {
private String taskBookUuid;
private String taskBookName;
private List<ShopkeeperTaskList> tasklist = new ArrayList<ShopkeeperTaskList>();
private Map<String,String> picMap = new HashMap<String,String>();
private Map<String,byte[]> picContentMap = new HashMap<String,byte[]>();
private Integer idIndex = 0;
private Map<String,Integer> allline = new HashMap<String,Integer>();
//前端打包有些bug,需要手动添加get函数
public List<ShopkeeperTaskList> getTasklist() {
return tasklist;
}
public String getTaskBookUuid() {
return taskBookUuid;
}
public int getTaskNum(){
int ret = 0;
for(ShopkeeperTaskList task:tasklist){
ret += task.getTaskNum();
}
return ret;
}
public double getTaskAllPriceSum(){
double ret = 0;
for(ShopkeeperTaskList task:tasklist){
ret += task.getTaskAllPriceSum();
}
return util.Misc.formatDoubleForMoney(ret);
}
/** 解析商家任务书excel */
public boolean parse(String dirPath) throws Exception {
//用于记录报错信息
String exceptionMessage = "";
//获取目录下的第一个.xls文件
List<String> list = FileTool.getFileListInDirectory(dirPath);
String excelFile = "";
for(String s:list){
if(s.endsWith(".xls")) {
excelFile = s;
break;
}
}
//随机生成一个uuid
taskBookUuid = UUID.randomUUID().toString();
//获取文件名
try {
String[] excelTmpStrings = excelFile.split(File.separator);
taskBookName = excelTmpStrings[excelTmpStrings.length - 1];
} catch(Exception e) {
throw new Exception("读取文件名异常,文件夹:" + dirPath);
}
//获取图片
try {
List<String> picList = FileTool.getFileListInDirectory(dirPath + File.separator + "图片");
for (String s : picList) {
if (!ImageUtil.allowPicType(s)) {
continue;
}
String[] tmp1 = s.split(File.separator);
String tmp2 = tmp1[tmp1.length - 1].split("\\.")[0];//.split(File.separator)[1].split("\\.");
picMap.put(tmp2, tmp1[tmp1.length - 1]);
try {
picContentMap.put(tmp1[tmp1.length - 1], FileTool.getFileContent(s));
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
throw new Exception("读取图片异常,文件夹:" + dirPath);
}
//解析excel表格
try {
POIFSFileSystem fs = new POIFSFileSystem(Files.newInputStream(Paths.get(excelFile)));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
List<Integer> taskListStart = new ArrayList<Integer>();
List<Integer> taskListEnd = new ArrayList<Integer>();
// 获取所有的表起始和结束
for(int i=0;i<(sheet.getLastRowNum()+1);i++){
if(!ExcelUtil.hasRow(sheet, i)){
continue;
}
String s = ExcelUtil.getCellString(sheet, i, 0);
if(s!=null && s.equals("商家姓名")){
taskListStart.add(i);
if(i>0){
taskListEnd.add(i-1);
}
}
}
taskListEnd.add(sheet.getLastRowNum());
//一份excel下会有多个商品
int tmpSubTaskBookId = 0;
for(int i=0;i<taskListEnd.size();i++){
ShopkeeperTaskList stl = new ShopkeeperTaskList();
try {
//解析任务
idIndex += stl.parse(sheet, taskListStart.get(i), taskListEnd.get(i), taskBookUuid, taskBookName, picMap, idIndex, tmpSubTaskBookId);
tasklist.add(stl);
} catch(Exception e) {
//e.printStackTrace();
//如果解析过程中有单元格解析失败,那么把报错信息添加到全局变量中
exceptionMessage = exceptionMessage + e.getMessage() + ";";
}
tmpSubTaskBookId++;
}
wb.close();
fs.close();
} catch(Exception ioe) {
ioe.printStackTrace();
return false;
}
//如果有解析失败的报错,那么直接抛出
if(!exceptionMessage.equals("")) {
throw new Exception(exceptionMessage);
}
return true;
}
public void generateExcel(String excelName){
allline.put("allline",0);
Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = ExcelUtil.getOrCreateSheet(wb, "sheet1");
int index = 0;
for(int i=1;i<tasklist.size();i++){
for(int j=i;j>0;j--){
if(tasklist.get(j).getTasklist().get(0).getId()<tasklist.get(j-1).getTasklist().get(0).getId()){
ShopkeeperTaskList a = tasklist.get(j);
ShopkeeperTaskList b = tasklist.get(j-1);
tasklist.set(j,b);
tasklist.set(j-1,a);
}
}
}
for(ShopkeeperTaskList stl:tasklist){
index +=stl.generateExcel(sheet,index,allline,picContentMap);
}
try {
Path p = Paths.get(excelName);
OutputStream fileOut = Files.newOutputStream(p);
wb.write(fileOut);
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void dodoer(){
for(int i=1;i<tasklist.size();i++){
for(int j=i;j>0;j--){
if(tasklist.get(j).getTasklist().get(0).getId()<tasklist.get(j-1).getTasklist().get(0).getId()){
ShopkeeperTaskList a = tasklist.get(j);
ShopkeeperTaskList b = tasklist.get(j-1);
tasklist.set(j,b);
tasklist.set(j-1,a);
}
}
}
}
public void addPic(String k,byte[] v){
picContentMap.put(k,v);
}
public void initByTask(ShopkeeperTaskList task){
taskBookUuid = task.getTasklist().get(0).getTaskBookUuid();
taskBookName = task.getTasklist().get(0).getTaskBookName();
String pic = task.getPic1();
if(pic!=null &&!pic.equals("")){
picContentMap.put(pic, LocalStoreTool.getImage(taskBookUuid + pic));
}
pic = task.getPic2();
if(pic!=null &&!pic.equals("")){
picContentMap.put(pic, LocalStoreTool.getImage(taskBookUuid + pic));
}
pic = task.getPic3();
if(pic!=null &&!pic.equals("")){
picContentMap.put(pic, LocalStoreTool.getImage(taskBookUuid + pic));
}
}
public void addShopkeeperTaskList(ShopkeeperTaskList stl){
tasklist.add(stl);
String pic = stl.getPic1();
if(pic!=null &&!pic.equals("")){
picContentMap.put(pic, LocalStoreTool.getImage(taskBookUuid + pic));
}
pic = stl.getPic2();
if(pic!=null &&!pic.equals("")){
picContentMap.put(pic, LocalStoreTool.getImage(taskBookUuid + pic));
}
pic = stl.getPic3();
if(pic!=null &&!pic.equals("")){
picContentMap.put(pic, LocalStoreTool.getImage(taskBookUuid + pic));
}
}
public static Map<String,ShopkeeperTaskBook> buildBookFromTask(List<TaskTables> ttlist){
Map<String,ShopkeeperTaskList> stbmap = new HashMap<String,ShopkeeperTaskList>();
for(TaskTables task:ttlist){
String uuid = task.getTaskBookUuid()+task.getSubTaskBookId();
ShopkeeperTask stk = new ShopkeeperTask();
stk.initByTables(task);
if(!stbmap.containsKey(uuid)){
ShopkeeperTaskList stl = new ShopkeeperTaskList();
stl.initByTask(stk);
stbmap.put(uuid,stl);
}
ShopkeeperTaskList stl = stbmap.get(uuid);
String pic = stk.getPic1();
if(pic!=null &&!pic.equals("")){
if(stl.getPic1() != null && !(stl.getPic1().equals(""))){
stl.setPic1(pic);
}
}
pic = stk.getPic2();
if(pic!=null &&!pic.equals("")){
if(stl.getPic2() != null && !(stl.getPic2().equals(""))){
stl.setPic2(pic);
}
}
pic = stk.getPic3();
if(pic!=null &&!pic.equals("")){
if(stl.getPic3() != null && !(stl.getPic3().equals(""))){
stl.setPic3(pic);
}
}
stl.addShopkeeperTask(stk);
}
Map<String,ShopkeeperTaskBook> bookMap = new HashMap<String,ShopkeeperTaskBook>();
for(Map.Entry<String,ShopkeeperTaskList> entry:stbmap.entrySet()){
String uuid = entry.getValue().getTasklist().get(0).getTaskBookUuid();
if(!bookMap.containsKey(uuid)){
ShopkeeperTaskBook stb = new ShopkeeperTaskBook();
stb.initByTask(entry.getValue());
bookMap.put(uuid,stb);
}
ShopkeeperTaskBook stb = bookMap.get(uuid);
stb.addShopkeeperTaskList(entry.getValue());
}
return bookMap;
}
}
|
package com.felipe.myportfolio.article;
import com.felipe.myportfolio.article.form.ArticleForm;
import com.felipe.myportfolio.model.Article;
import com.felipe.myportfolio.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/articles")
@CrossOrigin
public class ArticleController {
@Autowired private ArticleRepository articleRepository;
@GetMapping
public ResponseEntity<List<Article>> getArticles(){
return new ResponseEntity(articleRepository.findAll(), HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<Article> getArticleById(@PathVariable("id") String id){
final Optional<Article> article = articleRepository.findById(id);
if(article.isPresent()){
int views = article.get().getViews() + 1;
article.get().setViews(views);
articleRepository.save(article.get());
}
return new ResponseEntity<>(article.orElse(null), HttpStatus.OK);
}
@PostMapping
public ResponseEntity createArticle(@RequestBody ArticleForm form,
UriComponentsBuilder uriComponentsBuilder){
System.out.println("criando novo artigo");
Article article = new Article(form.getTitle(), form.getText());
articleRepository.save(article);
URI uri = uriComponentsBuilder
.path("/articles/{id}")
.buildAndExpand(article.getId())
.toUri();
return ResponseEntity.created(uri).body(article);
}
@DeleteMapping("/{id}")
public ResponseEntity deleteArticleById(@PathVariable("id") String id){
articleRepository.deleteById(id);
return new ResponseEntity(HttpStatus.OK);
}
@PutMapping("/{id}")
public ResponseEntity updateArticleById(
@PathVariable("id") String id,
@RequestBody ArticleForm form,
UriComponentsBuilder uriComponentsBuilder){
final Optional<Article> oldArticle = articleRepository.findById(id);
Article article = new Article();
URI uri = null;
System.out.println(form);
if(oldArticle.isPresent()){
article.setId(oldArticle.get().getId());
article.setTitle(form.getTitle());
article.setText(form.getText());
article.setViews(oldArticle.get().getViews());
article.setComments(oldArticle.get().getComments());
article.setLastEdition(LocalDate.now().toString());
articleRepository.save(article);
uri = uriComponentsBuilder
.path("/articles/{id}")
.buildAndExpand(article.getId())
.toUri();
}
return ResponseEntity.created(uri).body(article);
}
}
|
package com.tencent.mm.plugin.appbrand.appcache;
import com.tencent.mm.plugin.appbrand.appstorage.k;
import java.io.File;
public class h$b {
public static long aby() {
return k.w(new File(ah.abY()));
}
}
|
package ro.msg.cm.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import ro.msg.cm.types.CandidateCheck;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CandidateDto {
private Map<String, Object> changedAttributes = new HashMap<>();
private String firstName;
private String lastName;
private String phone;
private String email;
private String educationStatus;
private int originalStudyYear;
private String event;
private LocalDate dateOfAdding;
private CandidateCheck checkCandidate;
private int currentStudyYear;
public void setChangedAttributes(Map<String, Object> changedAttributes) {
this.changedAttributes = changedAttributes;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
changedAttributes.put("firstName", firstName);
}
public void setLastName(String lastName) {
this.lastName = lastName;
changedAttributes.put("lastName", lastName);
}
public void setPhone(String phone) {
this.phone = phone;
changedAttributes.put("phone", phone);
}
public void setEmail(String email) {
this.email = email;
changedAttributes.put("email", email);
}
public void setEducationStatus(String educationStatus) {
this.educationStatus = educationStatus;
changedAttributes.put("educationStatus", educationStatus);
}
public void setOriginalStudyYear(int originalStudyYear) {
this.originalStudyYear = originalStudyYear;
changedAttributes.put("originalStudyYear", originalStudyYear);
}
public void setEvent(String event) {
this.event = event;
changedAttributes.put("event", event);
}
public void setDateOfAdding(LocalDate dateOfAdding) {
this.dateOfAdding = dateOfAdding;
changedAttributes.put("dateOfAdding", dateOfAdding);
}
public void setCheckCandidate(CandidateCheck checkCandidate) {
this.checkCandidate = checkCandidate;
changedAttributes.put("checkCandidate", checkCandidate);
}
public void setCurrentStudyYear(int currentStudyYear) {
this.currentStudyYear = currentStudyYear;
changedAttributes.put("currentStudyYear", currentStudyYear);
}
public Map<String, Object> toMap() {
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("firstName", firstName);
resultMap.put("lastName", lastName);
resultMap.put("phone", phone);
resultMap.put("email", email);
resultMap.put("educationStatus", educationStatus);
resultMap.put("originalStudyYear", originalStudyYear);
resultMap.put("event", event);
resultMap.put("dateOfAdding", dateOfAdding);
resultMap.put("checkCandidate", checkCandidate);
resultMap.put("currentStudyYear", currentStudyYear);
return resultMap;
}
}
|
/*
* This file is part of SMG, a symbolic memory graph Java library
* Originally developed as part of CPAChecker, the configurable software verification platform
*
* Copyright (C) 2011-2015 Petr Muller
* Copyright (C) 2007-2014 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package cz.afri.smg.graphs;
import static org.mockito.Mockito.mock;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import cz.afri.smg.objects.SMGObject;
import cz.afri.smg.objects.SMGRegion;
import cz.afri.smg.types.CFunctionDeclaration;
import cz.afri.smg.types.CFunctionType;
import cz.afri.smg.types.CIdExpression;
import cz.afri.smg.types.CParameterDeclaration;
import cz.afri.smg.types.CType;
public class CLangSMGTest {
private static final CFunctionType FUNCTION_TYPE = CFunctionType.createSimpleFunctionType(CType.getIntType());
private static final ImmutableList<CParameterDeclaration> FUNCTION_PARAMS = ImmutableList.<CParameterDeclaration>of();
private static final CFunctionDeclaration FUNCTION_DECLARATION = new CFunctionDeclaration(FUNCTION_TYPE, "foo",
FUNCTION_PARAMS);
private CLangStackFrame sf;
private static final CIdExpression ID_EXPRESSION = new CIdExpression("label");
private static final int SIZE8 = 8;
private static final int SIZE16 = 16;
private static final int SIZE32 = 32;
private static final int OFFSET0 = 0;
private static final CType TYPE8 = CType.createTypeWithLength(SIZE8);
private static final CType TYPE16 = CType.createTypeWithLength(SIZE16);
private static final CType TYPE32 = CType.createTypeWithLength(SIZE32);
private static CLangSMG getNewCLangSMG64() {
return new CLangSMG();
}
@Before
public final void setUp() {
sf = new CLangStackFrame(FUNCTION_DECLARATION);
CLangSMG.setPerformChecks(true);
}
@Test
public final void cLangSMGConstructorTest() {
CLangSMG smg = getNewCLangSMG64();
Assert.assertEquals(0, smg.getStackFrames().size());
Assert.assertEquals(1, smg.getHeapObjects().size());
Assert.assertEquals(0, smg.getGlobalObjects().size());
SMGRegion obj1 = new SMGRegion(SIZE8, "obj1");
SMGRegion obj2 = smg.addGlobalVariable(TYPE8, "obj2");
Integer val1 = Integer.valueOf(1);
Integer val2 = Integer.valueOf(2);
SMGEdgePointsTo pt = new SMGEdgePointsTo(val1, obj1, 0);
SMGEdgeHasValue hv = new SMGEdgeHasValue(CType.getIntType(), 0, obj2, val2.intValue());
smg.addValue(val1);
smg.addValue(val2);
smg.addHeapObject(obj1);
smg.addPointsToEdge(pt);
smg.addHasValueEdge(hv);
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
// Copy constructor
CLangSMG smgCopy = new CLangSMG(smg);
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smgCopy));
Assert.assertEquals(0, smgCopy.getStackFrames().size());
Assert.assertEquals(2, smgCopy.getHeapObjects().size());
Assert.assertEquals(1, smgCopy.getGlobalObjects().size());
Assert.assertEquals(obj1, smgCopy.getObjectPointedBy(val1));
SMGEdgeHasValueFilter filter = SMGEdgeHasValueFilter.objectFilter(obj2);
Assert.assertEquals(hv, smgCopy.getUniqueHV(filter, true));
}
@Test
public final void cLangSMGaddHeapObjectTest() {
CLangSMG smg = getNewCLangSMG64();
SMGRegion obj1 = new SMGRegion(SIZE8, "label");
SMGRegion obj2 = new SMGRegion(SIZE8, "label");
smg.addHeapObject(obj1);
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
Set<SMGObject> heapObjs = smg.getHeapObjects();
Assert.assertTrue(heapObjs.contains(obj1));
Assert.assertFalse(heapObjs.contains(obj2));
Assert.assertTrue(heapObjs.size() == 2);
smg.addHeapObject(obj2);
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
heapObjs = smg.getHeapObjects();
Assert.assertTrue(heapObjs.contains(obj1));
Assert.assertTrue(heapObjs.contains(obj2));
final int expectedSize = 3;
Assert.assertEquals(heapObjs.size(), expectedSize);
}
@Test(expected = IllegalArgumentException.class)
public final void cLangSMGaddHeapObjectTwiceTest() {
CLangSMG smg = getNewCLangSMG64();
SMGRegion obj = new SMGRegion(SIZE8, "label");
smg.addHeapObject(obj);
smg.addHeapObject(obj);
}
@Test
public final void cLangSMGaddHeapObjectTwiceWithoutChecksTest() {
CLangSMG.setPerformChecks(false);
CLangSMG smg = getNewCLangSMG64();
SMGRegion obj = new SMGRegion(SIZE8, "label");
smg.addHeapObject(obj);
smg.addHeapObject(obj);
Assert.assertTrue("Asserting the test finished without exception", true);
}
@Test
public final void cLangSMGaddGlobalObjectTest() {
CLangSMG smg = getNewCLangSMG64();
SMGRegion obj1 = smg.addGlobalVariable(TYPE8, "label");
Map<String, SMGRegion> globalObjects = smg.getGlobalObjects();
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
Assert.assertEquals(globalObjects.size(), 1);
Assert.assertTrue(globalObjects.values().contains(obj1));
SMGRegion obj2 = smg.addGlobalVariable(TYPE8, "another_label");
globalObjects = smg.getGlobalObjects();
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
Assert.assertEquals(globalObjects.size(), 2);
Assert.assertTrue(globalObjects.values().contains(obj1));
Assert.assertTrue(globalObjects.values().contains(obj2));
}
@Test(expected = IllegalArgumentException.class)
public final void cLangSMGaddGlobalObjectTwiceTest() {
CLangSMG smg = getNewCLangSMG64();
smg.addGlobalVariable(TYPE8, "label");
smg.addGlobalVariable(TYPE8, "label");
}
@Test(expected = IllegalArgumentException.class)
public final void cLangSMGaddGlobalObjectWithSameLabelTest() {
CLangSMG smg = getNewCLangSMG64();
smg.addGlobalVariable(TYPE8, "label");
smg.addGlobalVariable(TYPE16, "label");
}
@Test
public final void cLangSMGaddStackObjectTest() {
CLangSMG smg = getNewCLangSMG64();
smg.addStackFrame(sf.getFunctionDeclaration());
SMGRegion obj1 = smg.addLocalVariable(TYPE8, "label");
CLangStackFrame currentFrame = smg.getStackFrames().peek();
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
Assert.assertEquals(currentFrame.getVariable("label"), obj1);
Assert.assertEquals(currentFrame.getVariables().size(), 1);
SMGRegion diffobj1 = smg.addLocalVariable(TYPE8, "difflabel");
currentFrame = smg.getStackFrames().peek();
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
Assert.assertEquals(currentFrame.getVariable("label"), obj1);
Assert.assertEquals(currentFrame.getVariable("difflabel"), diffobj1);
Assert.assertEquals(currentFrame.getVariables().size(), 2);
}
@Test(expected = IllegalArgumentException.class)
public final void cLangSMGaddStackObjectTwiceTest() {
CLangSMG smg = getNewCLangSMG64();
smg.addStackFrame(sf.getFunctionDeclaration());
smg.addLocalVariable(TYPE8, "label");
smg.addLocalVariable(TYPE8, "label");
}
@Test
public final void cLangSMGgetObjectForVisibleVariableTest() {
CLangSMG smg = getNewCLangSMG64();
SMGRegion obj3 = smg.addGlobalVariable(TYPE32, "label");
Assert.assertEquals(smg.getObjectForVisibleVariable(ID_EXPRESSION.getName()), obj3);
smg.addStackFrame(sf.getFunctionDeclaration());
SMGRegion obj1 = smg.addLocalVariable(TYPE8, "label");
Assert.assertEquals(smg.getObjectForVisibleVariable(ID_EXPRESSION.getName()), obj1);
smg.addStackFrame(sf.getFunctionDeclaration());
SMGRegion obj2 = smg.addLocalVariable(TYPE16, "label");
Assert.assertEquals(smg.getObjectForVisibleVariable(ID_EXPRESSION.getName()), obj2);
Assert.assertNotEquals(smg.getObjectForVisibleVariable(ID_EXPRESSION.getName()), obj1);
smg.addStackFrame(sf.getFunctionDeclaration());
Assert.assertEquals(smg.getObjectForVisibleVariable(ID_EXPRESSION.getName()), obj3);
Assert.assertNotEquals(smg.getObjectForVisibleVariable(ID_EXPRESSION.getName()), obj2);
}
@Test
public final void cLangSMGgetStackFramesTest() {
CLangSMG smg = getNewCLangSMG64();
Assert.assertEquals(smg.getStackFrames().size(), 0);
smg.addStackFrame(sf.getFunctionDeclaration());
smg.addLocalVariable(TYPE8, "frame1_1");
smg.addLocalVariable(TYPE8, "frame1_2");
smg.addLocalVariable(TYPE8, "frame1_3");
Assert.assertEquals(smg.getStackFrames().size(), 1);
final int expectedVariableCount = 3;
Assert.assertEquals(smg.getStackFrames().peek().getVariables().size(), expectedVariableCount);
smg.addStackFrame(sf.getFunctionDeclaration());
smg.addLocalVariable(TYPE8, "frame2_1");
smg.addLocalVariable(TYPE8, "frame2_2");
Assert.assertEquals(smg.getStackFrames().size(), 2);
Assert.assertEquals(smg.getStackFrames().peek().getVariables().size(), 2);
smg.addStackFrame(sf.getFunctionDeclaration());
smg.addLocalVariable(TYPE8, "frame3_1");
final int expectedStackSize = 3;
Assert.assertEquals(smg.getStackFrames().size(), expectedStackSize);
Assert.assertEquals(smg.getStackFrames().peek().getVariables().size(), 1);
smg.addStackFrame(sf.getFunctionDeclaration());
Assert.assertEquals(smg.getStackFrames().size(), expectedStackSize + 1);
Assert.assertEquals(smg.getStackFrames().peek().getVariables().size(), 0);
}
@Test
public final void cLangSMGgetHeapObjectsTest() {
CLangSMG smg = getNewCLangSMG64();
Assert.assertEquals(smg.getHeapObjects().size(), 1);
smg.addHeapObject(new SMGRegion(SIZE8, "heap1"));
Assert.assertEquals(smg.getHeapObjects().size(), 2);
smg.addHeapObject(new SMGRegion(SIZE8, "heap2"));
smg.addHeapObject(new SMGRegion(SIZE8, "heap3"));
final int expectedHeapSize = 4;
Assert.assertEquals(smg.getHeapObjects().size(), expectedHeapSize);
}
@Test
public final void cLangSMGgetGlobalObjectsTest() {
CLangSMG smg = getNewCLangSMG64();
Assert.assertEquals(smg.getGlobalObjects().size(), 0);
smg.addGlobalVariable(TYPE8, "heap1");
Assert.assertEquals(smg.getGlobalObjects().size(), 1);
smg.addGlobalVariable(TYPE8, "heap2");
smg.addGlobalVariable(TYPE8, "heap3");
final int expectedGlobalCount = 3;
Assert.assertEquals(smg.getGlobalObjects().size(), expectedGlobalCount);
}
@Test
public final void cLangSMGmemoryLeaksTest() {
CLangSMG smg = getNewCLangSMG64();
Assert.assertFalse(smg.hasMemoryLeaks());
smg.setMemoryLeak();
Assert.assertTrue(smg.hasMemoryLeaks());
}
@Test(expected = IllegalStateException.class)
public final void consistencyViolationDisjunctnessTest1() {
CLangSMG smg = getNewCLangSMG64();
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
SMGRegion obj = smg.addGlobalVariable(TYPE8, "label");
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
smg.addHeapObject(obj);
CLangSMGConsistencyVerifier.verifyCLangSMG(smg);
}
@Test(expected = IllegalStateException.class)
public final void consistencyViolationDisjunctnessTest2() {
CLangSMG smg = getNewCLangSMG64();
smg.addStackFrame(sf.getFunctionDeclaration());
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
SMGRegion obj = smg.addLocalVariable(TYPE8, "label");
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
smg.addHeapObject(obj);
CLangSMGConsistencyVerifier.verifyCLangSMG(smg);
}
@Test(expected = IllegalStateException.class)
public final void consistencyViolationUnionTest() {
CLangSMG smg = getNewCLangSMG64();
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
SMGRegion heapObj = new SMGRegion(SIZE8, "heap_object");
SMGRegion dummyObj = new SMGRegion(SIZE8, "dummy_object");
smg.addStackFrame(sf.getFunctionDeclaration());
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
smg.addLocalVariable(TYPE8, "stack_variable");
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
smg.addGlobalVariable(TYPE8, "global_variable");
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
smg.addHeapObject(heapObj);
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
smg.addObject(dummyObj);
CLangSMGConsistencyVerifier.verifyCLangSMG(smg);
}
@Test
public final void consistencyViolationNullTest() {
CLangSMG smg = getNewCLangSMG64();
smg = getNewCLangSMG64();
SMGObject nullObject = smg.getHeapObjects().iterator().next();
Integer value = SMGValueFactory.getNewValue();
SMGEdgeHasValue edge = new SMGEdgeHasValue(mock(CType.class), OFFSET0, nullObject, value);
smg.addValue(value);
smg.addHasValueEdge(edge);
Assert.assertFalse(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
}
/**
* Two objects with same label (variable name) in different frames are not inconsistent
*/
@Test
public final void consistencyViolationStackNamespaceTest2() {
CLangSMG smg = getNewCLangSMG64();
smg.addStackFrame(sf.getFunctionDeclaration());
smg.addLocalVariable(TYPE8, "label");
smg.addStackFrame(sf.getFunctionDeclaration());
smg.addLocalVariable(TYPE16, "label");
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
}
/**
* Two objects with same label (variable name) on stack and global namespace are not inconsistent
*/
@Test
public final void consistencyViolationStackNamespaceTest3() {
CLangSMG smg = getNewCLangSMG64();
smg.addGlobalVariable(TYPE8, "label");
smg.addStackFrame(sf.getFunctionDeclaration());
smg.addLocalVariable(TYPE16, "label");
Assert.assertTrue(CLangSMGConsistencyVerifier.verifyCLangSMG(smg));
}
}
|
package com.olal.caclulator.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Set;
@Entity
@Table(name = "recipes_categories")
public class RecipeCategory implements Serializable {
private Integer id;
private String title;
private String description;
private Set<Recipe> recipes;
public RecipeCategory(){
}
public RecipeCategory(String title, String description){
this.title = title;
this.description = description;
}
public RecipeCategory(String title, String description, Set<Recipe> recipes){
this.title = title;
this.description = description;
this.recipes = recipes;
}
@Id
@GeneratedValue
public Integer getId() {
return id;
}
@Column(nullable = false, length = 100)
public String getTitle() {
return title;
}
@Column(nullable = false, length = 100)
public String getDescription() {
return description;
}
@OneToMany(mappedBy = "recipes")
public Set<Recipe> getRecipes() {
return recipes;
}
public void setId(Integer id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
public void setRecipes(Set<Recipe> recipes) {
this.recipes = recipes;
}
}
|
package com.test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class StudentMain {
public static void main(String[] args) {
AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:Context.xml");
StudentInfo info = ctx.getBean("myStu", StudentInfo.class);
StudentInfo info2 = ctx.getBean("myStu2", StudentInfo.class);
info.printStundetInfo();
System.out.println("========================================");
info2.printStundetInfo();
}
}
|
package Tests;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class GetServiceTest extends Testable implements Runnable {
public GetServiceTest(int processNumber){
super(processNumber);
}
@Override
public void run() {
HttpClient httpClient = HttpClients.createDefault();
for(int i = 0 ; i < 10; i ++)
{
int random = i + (int)(Math.random() * 3*i);
HttpGet httpGet = new HttpGet("http://localhost:" + this.getHttpPort() + "/message?id=" + Integer.toString(random));
try
{
HttpResponse httpResponse = httpClient.execute(httpGet);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(httpResponse.getEntity().getContent())
);
String line = null;
System.out.print("Resposta GET: ");
while ((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
|
package com.itfdms.common.util;
import com.itfdms.common.util.exception.CheckedException;
import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
/**
* @author lxr
* @Title: Assert
* @ProjectName itfdms_blog
* @Description: 数据校验
* @date 2018-07-0721:06
*/
public class Assert {
private static Validator validator;
static {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
/**
* * @Description:校验对象
* * @param object 待校验对象
* * @param groups 待校验的组
* * @return ${return_type}
* * @throws
* * @author lxr
* * @date 2018-07-09 19:27
*
*/
public static void validatorEntity(Object object, Class<?>... groups) throws CheckedException {
Set<ConstraintViolation<Object>> constraintViolationSet = validator.validate(object, groups);
if (!constraintViolationSet.isEmpty()) {
StringBuilder msg = new StringBuilder();
for (ConstraintViolation<Object> constraint : constraintViolationSet) {
msg.append(constraint.getMessage()).append("<br>");
}
throw new CheckedException(msg.toString());
}
}
public static void isBlak(String str, String message) {
if (StringUtils.isBlank(str)) {
throw new CheckedException(message);
}
}
public static void isNull(Object object, String message) {
if (object == null) {
throw new CheckedException(message);
}
}
}
|
package com.puti.pachong.util;
import com.puti.pachong.entity.proxy.FreeProxy;
import org.junit.jupiter.api.Test;
class ProxyUtilTest {
@Test
void isAlive() {
FreeProxy freeProxy = new FreeProxy();
freeProxy.setIp("99.79.83.80");
freeProxy.setPort(80);
boolean alive = ProxyUtil.isAlive(freeProxy);
System.out.println("alive = " + alive);
}
} |
package models.SortingAlgorithms;
import java.util.ArrayList;
import java.util.Collections;
import javafx.animation.FillTransition;
import javafx.animation.ParallelTransition;
import javafx.animation.SequentialTransition;
import javafx.animation.TranslateTransition;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;
import models.Element;
public class NormalSort extends AbstractSort {
protected static ParallelTransition FillBeforeSwap(StackPane l1, StackPane l2,double speed) {
ParallelTransition pt = new ParallelTransition();
FillTransition ft1 = new FillTransition();
FillTransition ft2 = new FillTransition();
ft1.setShape((Element)l1.getChildren().get(0));
ft1.setDuration(Duration.millis(speed));
ft1.setToValue(Color.GRAY);
ft2.setDuration(Duration.millis(speed));
ft2.setShape((Element)l2.getChildren().get(0));
ft2.setToValue(Color.GRAY);
pt.getChildren().addAll(ft1,ft2);
return pt;
}
protected static ParallelTransition FillAfterSwap(StackPane l1, StackPane l2,double speed) {
ParallelTransition pt = new ParallelTransition();
FillTransition ft1 = new FillTransition();
FillTransition ft2 = new FillTransition();
ft1.setShape((Element)l1.getChildren().get(0));
ft1.setDuration(Duration.millis(speed));
ft1.setToValue(Color.valueOf("#ADD8E6"));
ft2.setDuration(Duration.millis(speed));
ft2.setShape((Element)l2.getChildren().get(0));
ft2.setToValue(Color.valueOf("#ADD8E6"));
pt.getChildren().addAll(ft1,ft2);
return pt;
}
protected static ParallelTransition swapMe(StackPane l1, StackPane l2, int a ,ArrayList<StackPane> list, double speed) {
TranslateTransition t1 = new TranslateTransition();
TranslateTransition t2 = new TranslateTransition();
t1.setDuration(Duration.millis(speed));
t2.setDuration(Duration.millis(speed));
ParallelTransition pl = new ParallelTransition();
t1.setNode(l1);
t2.setNode(l2);
t1.setByX(60*a);
t2.setByX(-60*a);
pl.getChildren().addAll(t1, t2);
Collections.swap(list, list.indexOf(l1), list.indexOf(l2));
return pl;
}
public NormalSort() {
// TODO Auto-generated constructor stub
}
}
|
package com.tencent.mm.plugin.ipcall.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
class IPCallShareCouponUI$7 implements OnClickListener {
final /* synthetic */ IPCallShareCouponUI kyP;
IPCallShareCouponUI$7(IPCallShareCouponUI iPCallShareCouponUI) {
this.kyP = iPCallShareCouponUI;
}
public final void onClick(DialogInterface dialogInterface, int i) {
this.kyP.finish();
}
}
|
package exerciciosAula18;
import java.util.HashSet;
import java.util.Set;
public class Prova {
public static void somaTotal(Set<Integer> conjuntoDeInteiros) {
int soma = 0;
for (Integer numero : conjuntoDeInteiros) {
System.out.print(numero+" ");
soma += numero;
}
System.out.println("\n a soma é: " + soma);
}
public static void main(String[] args) {
Set<Integer> conjunto = new HashSet<>();
conjunto.add(11);
conjunto.add(4);
conjunto.add(6);
conjunto.add(8);
conjunto.add(1);
somaTotal(conjunto);
}
} |
package com.epam.jmp.module.concurency.experiment;
import java.util.HashMap;
import java.util.concurrent.ConcurrentMap;
public class ExperimentSynchronizedConcurrentMap<K, V> extends HashMap<K, V> implements ConcurrentMap<K, V> {
@Override
public synchronized V putIfAbsent(K key, V value) {
return super.putIfAbsent(key, value);
}
@Override
public synchronized boolean remove(Object key, Object value) {
return super.remove(key, value);
}
@Override
public synchronized boolean replace(K key, V oldValue, V newValue) {
return super.replace(key, oldValue, newValue);
}
@Override
public synchronized V replace(K key, V value) {
return super.replace(key, value);
}
}
|
/*
* 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 figuras;
import javax.swing.JOptionPane;
/**
*
* @author ESTUDIANTE
*/
public class Figuras {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
String nombre;
float lado;
float base;
float altura;
int menu = Integer.parseInt(JOptionPane.showInputDialog("Menú\n1.Triángulo\n2.Cuadrado\n"
+ "3.rectángulo\n4.círculo\n5.Salir"));
if(menu == 5){
return ;
}
nombre = JOptionPane.showInputDialog(null, "Ingrese nombre figura");
switch(menu){
case 1:
base = Float.parseFloat(JOptionPane.showInputDialog("Ingrese base Triángulo"));
altura = Float.parseFloat(JOptionPane.showInputDialog("Ingrese altura Triángulo"));
lado = Float.parseFloat(JOptionPane.showInputDialog("Ingrese altura1 Triángulo"));
Triangulo triangulo = new Triangulo(nombre, base, altura, lado);
JOptionPane.showMessageDialog(null, triangulo.showData());
break;
case 2:
lado = Float.parseFloat(JOptionPane.showInputDialog("Ingrese lado Cuadrado"));
Cuadrado cuadrado = new Cuadrado(nombre, lado);
JOptionPane.showMessageDialog(null, cuadrado.showData());
break;
case 3:
base = Float.parseFloat(JOptionPane.showInputDialog("Ingrese base Triángulo"));
altura = Float.parseFloat(JOptionPane.showInputDialog("Ingrese altura Triángulo"));
Rectangulo rectangulo= new Rectangulo(nombre, base, altura);
JOptionPane.showMessageDialog(null, rectangulo.showData());
break;
case 4:
float radio = Float.parseFloat(JOptionPane.showInputDialog("Ingrese radio circulo"));
Circulo circulo= new Circulo(nombre, radio);
JOptionPane.showMessageDialog(null, circulo.showData());
break;
default:
JOptionPane.showMessageDialog(null,"Opción no valida");
break;
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
|
package com.nitgar.axonsample.command;
/**
* Created by anuraggupta on 28/03/17.
*/
public class AccountCreateCommand {
private final String accountNo;
public AccountCreateCommand(String accountNo) {
this.accountNo = accountNo;
}
public String getAccountNo() {
return accountNo;
}
}
|
package fi.lassemaatta.temporaljooq.config.jooq.converter;
public class TimeRangeUtil {
public static final TimeRange EMPTY = TimeRange.empty();
public static final TimeRange UNBOUNDED = TimeRange.unbounded();
}
|
package com.rex.demo.study.demo.sink;
import com.alibaba.fastjson.JSON;
import com.rex.demo.study.demo.entity.Student;
import com.rex.demo.study.demo.util.DruidConnectionPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeutils.base.VoidSerializer;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.typeutils.runtime.kryo.KryoSerializer;
import org.apache.flink.streaming.api.functions.sink.TwoPhaseCommitSinkFunction;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* mysql 两阶段提交sink,保证exactly once
* 通过ConnectionState将connection对象包装起来就没有报错(相较于{@link MySqlTwoPhaseCommitSink}.)
*
* @Author li zhiqang
* @create 2020/11/26
*/
@Slf4j
public class MySqlTwoPhaseCommitSinkDemo extends TwoPhaseCommitSinkFunction<Tuple2<String, Integer>,
MySqlTwoPhaseCommitSinkDemo.ConnectionState, Void> {
// 定义可用的构造函数
public MySqlTwoPhaseCommitSinkDemo() {
super(new KryoSerializer<>(ConnectionState.class, new ExecutionConfig()),
VoidSerializer.INSTANCE);
}
@Override
protected ConnectionState beginTransaction() throws Exception {
System.out.println("=====> beginTransaction... ");
//使用连接池,不使用单个连接
// Class.forName("com.mysql.jdbc.Driver");
// String url = "jdbc:mysql://172.26.55.109:3306/dc?characterEncoding=utf8&useSSL=false";
// Connection connection = DBConnectUtil.getConnection(url, "root", "t4*9&/y?c,h.e17!");
// 使用druid连接池
Connection connection = DruidConnectionPool.getConnection();
connection.setAutoCommit(false);//设定不自动提交
return new ConnectionState(connection);
}
@Override
protected void invoke(ConnectionState transaction, Tuple2<String, Integer> value, Context context) throws Exception {
Connection connection = transaction.connection;
/* wordcount demo */
// PreparedStatement pstm = connection.prepareStatement("INSERT INTO word_count (word, count) VALUES (?, ?) ON DUPLICATE KEY UPDATE count = ?");
// pstm.setString(1, value.f0);
// pstm.setInt(2, value.f1);
// pstm.setInt(3, value.f1);
// pstm.executeUpdate();
/* student demo */
String stu = value.f0;
Student student = JSON.parseObject(stu, Student.class);
String sql = "insert into student(id,name,password,age) values (?,?,?,?)";
PreparedStatement pstm = connection.prepareStatement(sql);
pstm.setInt(1, student.getId());
pstm.setString(2, student.getName());
pstm.setString(3, student.getPassword());
pstm.setInt(4, student.getAge());
pstm.execute();
pstm.close();
}
// 先不做处理
@Override
protected void preCommit(ConnectionState transaction) throws Exception {
System.out.println("=====> preCommit... " + transaction);
}
//提交事务
@Override
protected void commit(ConnectionState transaction) {
System.out.println("=====> commit... ");
Connection connection = transaction.connection;
try {
if(connection != null){
connection.commit();
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException("提交事物异常");
// log.error("提交事物异常", e);
}
}
//回滚事务
@Override
protected void abort(ConnectionState transaction) {
System.out.println("=====> abort... ");
Connection connection = transaction.connection;
try {
if(connection != null){
connection.rollback();
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException("回滚事物异常");
// log.error("回滚事物异常", e);
}
}
//定义建立数据库连接的方法
public static class ConnectionState {
private final transient Connection connection;
public ConnectionState(Connection connection) {
this.connection = connection;
}
}
}
|
package telcel.android.rick.com.rvisor.exceptions;
/**
* Created by PIN7025 on 18/01/2017.
*/
public class WebServiceConexionException extends RuntimeException {
public WebServiceConexionException(final String mensaje){
super(mensaje);
}
public WebServiceConexionException(String mensaje, Throwable excepcion){
super(mensaje,excepcion);
}
}
|
package org.bashemera.openfarm.controller;
import java.security.Principal;
import javax.validation.Valid;
import org.bashemera.openfarm.exception.AccountCreationException;
import org.bashemera.openfarm.form.AccountForm;
import org.bashemera.openfarm.model.Farm;
import org.bashemera.openfarm.model.User;
import org.bashemera.openfarm.service.AccountService;
import org.bashemera.openfarm.service.FarmService;
import org.bashemera.openfarm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class AccountController {
@Autowired
private UserService userService;
@Autowired
private FarmService farmService;
//@Autowired
//private RoleService roleService;
@Autowired
private AccountService accountService;
@RequestMapping(value = "/account/create", method = RequestMethod.GET)
public String createAccount(Model model) {
AccountForm account = new AccountForm();
model.addAttribute("title", "Create account");
model.addAttribute("account", account);
return "account/create";
}
@RequestMapping(value = "/account/create", method = RequestMethod.POST)
public String saveAccount(@Valid @ModelAttribute("account") AccountForm account, BindingResult bindingResult, Model model) {
model.addAttribute("title", "Account details");
System.out.println("Posting new account");
if (bindingResult.hasErrors()) {
model.addAttribute("title", "Account details");
return "account/create";
}
try {
accountService.createAccount(account);
return "account/create_result";
} catch (AccountCreationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "account/create_error";
}
@RequestMapping(value = "/account/view", method = RequestMethod.GET)
public String viewAccount(Principal principal, Model model) {
User currentLoggedInUser = userService.findByEmail(principal.getName());
Farm farm = farmService.findByEmployees(currentLoggedInUser.getId());
model.addAttribute("farm", farm);
model.addAttribute("title", "Account details");
return "account/view";
}
}
|
/**
*
*/
package test.layout;
import java.awt.Dimension;
import java.awt.Insets;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import site.com.google.anywaywrite.component.gui.BgAreaLabel;
import site.com.google.anywaywrite.component.layout.BgAreaLayout;
import site.com.google.anywaywrite.component.layout.BgLayoutBase;
import site.com.google.anywaywrite.component.layout.BgMultiPileLayout;
import site.com.google.anywaywrite.item.card.BgCardItem;
import site.com.google.anywaywrite.item.card.BgCardState.Direction;
import site.com.google.anywaywrite.item.card.BgCardState.Side;
import boardgame.cribagge.BgTrump;
/**
* @author y-kitajima
*
*/
public class TestMultiPile {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(250, 250));
BgAreaLabel area = BgAreaLabel.newInstance(createCards(),
createAreaLayout());
area.setAreaName("MultiPile");
// area.setPreferredSize(new Dimension(200, 200));
area.setBounds(10, 10, 130, 180);
f.add(area);
// f.setLayout(new BorderLayout());
// f.getContentPane().add(area, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
});
}
public static List<BgCardItem> createCards() {
java.util.List<BgCardItem> cards = new java.util.ArrayList<BgCardItem>();
for (int idx = 13; idx < 20; idx++) {
BgCardItem c = BgCardItem.newInstance(BgTrump.newInstance().getCards()
.get(idx));
c.setDirection(Direction.UP);
c.setSide(Side.DOWN);
cards.add(c);
}
return cards;
// List<BgCardInfo> cards = BgWeissSchwarzDeck.newInstance().getCards();
// ArrayList<BgCardItem> items = new ArrayList<BgCardItem>();
// for (BgCardInfo info : cards) {
// BgCardItem site.com.google.anywaywrite.item = BgCardItem.newInstance(info);
// site.com.google.anywaywrite.item.setDirection(Direction.UP);
// site.com.google.anywaywrite.item.setSide(Side.FACE);
// items.add(site.com.google.anywaywrite.item);
// }
//
// return items;
}
public static BgAreaLayout createAreaLayout() {
BgMultiPileLayout layout = BgMultiPileLayout.newInstance(BgLayoutBase.BOTH,
10, 10, 10);
layout.setMargin(new Insets(10, 20, 10, 20));
return layout;
}
}
|
package com.tencent.mm.plugin.wallet_payu.remittance.a;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.wallet_core.e.a.a;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
public final class f extends a {
public int bNI;
public int bWA;
public double hUL;
public String lNV;
private String myq;
public int myr;
public int pFV;
public int pFW;
public int status;
public f(String str, String str2, int i) {
this(str, str2, i, 0);
}
public f(String str, String str2, int i, int i2) {
this.myq = null;
this.myq = str;
this.bNI = 1;
this.bWA = i2;
Map hashMap = new HashMap();
hashMap.put("trans_id", str);
hashMap.put("receiver_name", str2);
hashMap.put("invalid_time", String.valueOf(i));
F(hashMap);
}
public final void a(int i, String str, JSONObject jSONObject) {
x.d("MicroMsg.NetScenePayURemittanceQuery", "errCode " + i + " errMsg: " + str);
if (i == 0) {
this.myr = jSONObject.optInt("pay_time");
this.hUL = jSONObject.optDouble("total_fee") / 100.0d;
this.lNV = jSONObject.optString("fee_type");
this.status = jSONObject.optInt("pay_status");
this.pFV = jSONObject.optInt("refund_time");
this.pFW = jSONObject.optInt("receive_time");
}
}
public final int bOo() {
return 25;
}
}
|
package api.longpoll.bots.methods.impl.messages;
import api.longpoll.bots.methods.AuthorizedVkApiMethod;
import api.longpoll.bots.methods.VkApiProperties;
import api.longpoll.bots.model.objects.basic.Chat;
import api.longpoll.bots.model.response.GenericResponse;
import com.google.gson.annotations.SerializedName;
/**
* Implements <b>messages.setChatPhoto</b> method.
* <p>
* Sets a previously-uploaded picture as the cover picture of a chat.
*
* @see <a href="https://vk.com/dev/messages.setChatPhoto">https://vk.com/dev/messages.setChatPhoto</a>
*/
public class SetChatPhoto extends AuthorizedVkApiMethod<SetChatPhoto.Response> {
public SetChatPhoto(String accessToken) {
super(accessToken);
}
@Override
protected String getUrl() {
return VkApiProperties.get("messages.setChatPhoto");
}
@Override
protected Class<Response> getResponseType() {
return Response.class;
}
public SetChatPhoto setFile(String file) {
return addParam("file", file);
}
@Override
public SetChatPhoto addParam(String key, Object value) {
return (SetChatPhoto) super.addParam(key, value);
}
/**
* Response to <b>messages.setChatPhoto</b> request.
*/
public static class Response extends GenericResponse<Response.ResponseObject> {
/**
* Response object.
*/
public static class ResponseObject {
@SerializedName("message_id")
private Integer messageId;
@SerializedName("chat")
private Chat chat;
public Integer getMessageId() {
return messageId;
}
public void setMessageId(Integer messageId) {
this.messageId = messageId;
}
public Chat getChat() {
return chat;
}
public void setChat(Chat chat) {
this.chat = chat;
}
@Override
public String toString() {
return "ResponseObject{" +
"messageId=" + messageId +
", chat=" + chat +
'}';
}
}
}
}
|
package com.ss.android.ugc.aweme.miniapp.c;
import com.ss.android.ugc.aweme.miniapp_api.services.a;
public final class a implements a {}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\ss\androi\\ugc\aweme\miniapp\c\a.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package classAndObject;
/**
* @author malf
* @description 懒汉式单例模式
* @project how2jStudy
* @since 2020/9/14
*/
public class GiantDragon2 {
// 私有化构造方法使得该类无法在外部通过new 进行实例化
private GiantDragon2() {
}
// 准备一个类属性,用于指向一个实例化对象,但是暂时指向null
private static GiantDragon2 instance;
// public static 方法,返回实例对象
public static GiantDragon2 getInstance() {
// 第一次访问的时候,发现instance没有指向任何对象,这时实例化一个对象
if (null == instance) {
instance = new GiantDragon2();
}
// 返回 instance指向的对象
return instance;
}
}
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.samplers;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.RcaController;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.framework.metrics.RcaRuntimeMetrics;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.stats.collectors.SampleAggregator;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.stats.emitters.ISampler;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.reader.ClusterDetailsEventProcessor;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.reader.ClusterDetailsEventProcessor.NodeDetails;
import com.google.common.annotations.VisibleForTesting;
public class RcaEnabledSampler implements ISampler {
@Override
public void sample(SampleAggregator sampleCollector) {
sampleCollector.updateStat(RcaRuntimeMetrics.RCA_ENABLED, "", isRcaEnabled() ? 1 : 0);
}
@VisibleForTesting
boolean isRcaEnabled() {
NodeDetails currentNode = ClusterDetailsEventProcessor.getCurrentNodeDetails();
if (currentNode != null && currentNode.getIsMasterNode()) {
return RcaController.isRcaEnabled();
}
return false;
}
}
|
package br.pe.joaopedro.page;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
public class DemoPage {
private WebDriver driver;
public void scrollAteFinalPagina() throws InterruptedException {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.clientHeight));");
Thread.sleep(3000);
js.executeScript("window.scrollTo(0, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.clientHeight));");
}
}
|
package com.alonemusk.medicalapp.ui.Login;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
public class SendOtpViewModel extends ViewModel {
public MutableLiveData<Boolean> codeSent = new MutableLiveData<>();
public MutableLiveData<PhoneAuthCredential> mCredential = new MutableLiveData<>();
public String mVerificationId;
public MutableLiveData<Boolean> progress = new MutableLiveData<>();
public void setCodeSent(String codeSent) {
mCredential.setValue(PhoneAuthProvider.getCredential(mVerificationId, codeSent));
}
}
|
package com.games.kripa.guessthemovie;
import java.util.ArrayList;
/**
* Created by Kripa on 7/2/2017.
*/
public class TmdbConfig {
private final String ImageBaseUrl;
private final ArrayList<String> posterSizes;
private TmdbConfig(ConfigBuilder builder){
ImageBaseUrl = builder.ImageBaseUrl;
posterSizes = builder.posterSizes;
}
public static class ConfigBuilder {
private String ImageBaseUrl;
private ArrayList<String> posterSizes;
public ConfigBuilder setImageBaseUrl(String imgUrl) {
this.ImageBaseUrl = imgUrl;
return this;
}
public ConfigBuilder setPosterSizes(ArrayList<String> sizes){
this.posterSizes = sizes;
return this;
}
public TmdbConfig build() {
return new TmdbConfig(this);
}
}
public static ConfigBuilder newBuilder() {
return new ConfigBuilder();
}
public String getImageBaseUrl(){
return this.ImageBaseUrl;
}
public ArrayList<String> getPosterSizes() {
return this.posterSizes;
}
}
|
package com.android.yinwear;
import android.app.Application;
import android.util.Log;
import com.android.yinwear.core.controller.CoreController;
import com.android.yinwear.core.db.AppDatabase;
import com.android.yinwear.core.db.DbClient;
import static com.android.yinwear.BuildConfig.DEBUG;
public class YINApplication extends Application {
private static final String TAG = "YINApplication";
private CoreController mCoreController;
private AppDatabase mAppDatabase;
@Override
public void onCreate() {
super.onCreate();
initDB();
initCoreController();
}
/**
* Initialize db
*/
private void initDB() {
mAppDatabase = DbClient.getInstance(getApplicationContext()).getAppDatabase();
}
/**
* To initialize application modules
*/
private void initCoreController() {
mCoreController = CoreController.getInstance();
if (!mCoreController.init(this)) {
if (DEBUG) Log.e(TAG, "Failed to initialize Core Controller");
}
}
public CoreController getCoreController() {
return mCoreController;
}
public AppDatabase getAppDatabase() {
return mAppDatabase;
}
}
|
package org.smxknife.airport.client.web.controller;
import lombok.extern.slf4j.Slf4j;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.Handler;
import org.apache.axis.SimpleChain;
import org.apache.axis.SimpleTargetedChain;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.configuration.SimpleProvider;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.transport.http.HTTPSender;
import org.apache.axis.transport.http.HTTPTransport;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.smxknife.airport.client.handler.AxisClientEnvelopeHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;
import java.rmi.RemoteException;
import static org.apache.axis.Constants.URI_DEFAULT_SCHEMA_XSD;
/**
* @author smxknife
* 2019/10/18
*/
@RestController
@RequestMapping("/gauge")
@Slf4j
public class GaugeController {
@RequestMapping
public String gauge() {
String namespace = "http://ws.travelsky.com/";
String endpoint = "http://localhost:7800/services/IGaugePort";
String method = "getGaugeData";
try {
Service service = new Service();
EngineConfiguration config = service.getEngine().getConfig();
SimpleProvider clientConfig = new SimpleProvider(config);
AxisClientEnvelopeHandler envelopeHandler = new AxisClientEnvelopeHandler(namespace);
SimpleChain reqHandler = new SimpleChain();
SimpleChain respHandler = new SimpleChain();
reqHandler.addHandler(envelopeHandler);
Handler pivot = new HTTPSender();
Handler transport = new SimpleTargetedChain(reqHandler, pivot, respHandler);
clientConfig.deployTransport(HTTPTransport.DEFAULT_TRANSPORT_NAME, transport);
service.setEngineConfiguration(clientConfig);
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(endpoint);
call.setEncodingStyle("utf-8");
call.setOperationName(new QName(endpoint, method));
// call.addParameter(new QName(endpoint, "arg0"), XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter(new QName(endpoint, "arg0"), new QName(URI_DEFAULT_SCHEMA_XSD, "string", "~CDATA"), ParameterMode.IN);
call.setReturnType(XMLType.XSD_STRING);
call.setTimeout(60000);
// call.getMessageContext().getAxisEngine().init();
// SOAPMessage message = call.getMessageContext().getMessage();
// CDATASection cdataSection = new CDATAImpl(buildXml());
// RPCParam param = new RPCParam("arg0", cdataSection);
// RPCElement element = new RPCElement(namespace, method, new Object[]{param});
// TypeMapping typeMapping = call.getTypeMapping();
// typeMapping.register(CDATAImpl.class, XMLType.SOAP_DOCUMENT,
// new CDATASerializerFactory(XMLType.SOAP_DOCUMENT, CDATAImpl.class),
// new CDATADeserializerFactory(XMLType.SOAP_DOCUMENT, CDATAImpl.class));
// element.getOwnerDocument().createCDATASection(buildXml());
// element.getDeserializationContext().startCDATA();
// element.getDeserializationContext().endCDATA();
// element.addParam(new RPCParam(XMLType.XSD_STRING, buildXml()));
// CDATASection cdataSection = XMLUtils.newDocument().createCDATASection(buildXml());
// Object invoke = call.invoke(new Object[] {cdataSection});
Object invoke = call.invoke(new Object[] {buildXml()});
// Object invoke = call.invoke(element);
log.info("receive message = {}", invoke.toString());
return invoke.toString();
} catch (ServiceException e) {
e.printStackTrace();
return e.getMessage();
} catch (RemoteException e) {
e.printStackTrace();
return e.getMessage();
}
}
private String buildXml() {
Element sems_rq = DocumentHelper.createElement("SEMS_RQ");
sems_rq.add(DocumentHelper.createElement("SEMS_TYPE").addText("DICTIONARY"));
sems_rq.add(DocumentHelper.createElement("SNDR").addText("POMS"));
sems_rq.add(DocumentHelper.createElement("SEQN").addText("123"));
sems_rq.add(DocumentHelper.createElement("SEMS_CONDITION"));
return sems_rq.asXML();
}
}
|
package engines;
import bots.Marcel;
import org.junit.Test;
import static org.junit.Assert.*;
public class TestTurn {
Turn turn;
Marcel marcel;
@Test
public void createTurn() {
turn = new Turn();
assertEquals(2, turn.getActionNb());
}
}
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.net.URLDecoder;
/**
* Created by Kevin Lau on 4/23/2016.
*/
public class WordHolder {
private HashMap<String, Number> wordCount;
private static final String TARGET_PATH = "txtfiles";
public WordHolder() {
wordCount = new HashMap<String, Number>();
}
public boolean loadData() throws IOException {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File folder;
try {
String path = classLoader.getResource(TARGET_PATH).getPath();
folder = new File(URLDecoder.decode(path, "UTF-8"));
} catch (NullPointerException e) {
throw new IOException("Folder load failed");
}
if (!folder.exists() || !folder.isDirectory()) {
throw new IOException("Folder could not be loaded");
}
File [] files = folder.listFiles();
for (File file : files) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
String [] words = line.split("[^A-Za-z]+");
for (String word : words) {
word = word.toLowerCase();
Number count = wordCount.get(word);
if (count != null) {
wordCount.put(word, count.intValue() + 1);
} else {
wordCount.put(word, 1);
}
}
}
} catch (Exception e) {
return false;
}
}
return true;
}
public int getCount(String word) {
Number count = wordCount.get(word.toLowerCase());
if (count == null) {
return 0;
} else {
return count.intValue();
}
}
}
|
package com.tis.retulix.mapper;
import com.tis.common.model.NotUserException;
import com.tis.retulix.domain.MemberVO;
public interface UserMapper {
int createUser(MemberVO user);
MemberVO findUserByEmail(String email);
MemberVO isLoginOk(String email, String pwd) throws NotUserException;
}
|
package com.spower.business.exam.controller;
import java.net.BindException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import com.spower.basesystem.common.Constants;
import com.spower.basesystem.common.Tools;
import com.spower.basesystem.common.controller.AutoBinderSimpleFormController;
import com.spower.basesystem.dictionary.service.DictionaryLoader;
import com.spower.basesystem.manage.service.IManageService;
import com.spower.basesystem.manage.service.dao.IManageDao;
import com.spower.basesystem.manage.valueobject.User;
import com.spower.basesystem.oplog.service.OperateLogHelper;
import com.spower.basesystem.oplog.valueobject.OperateLog;
import com.spower.business.exam.command.ExamEditInfo;
import com.spower.business.exam.service.IExamService;
import com.spower.business.exam.valueobject.ExamMain;
import com.spower.business.interview.valueobject.Interview;
import com.spower.business.person.service.IPersonService;
import com.spower.business.person.valueobject.Person;
/**
*
* @author huangwq
* 2014-11-28
*
*/
public class ExamEditController extends AutoBinderSimpleFormController{
private IPersonService personService;
public void setPersonService(IPersonService personService) {
this.personService = personService;
}
private IExamService examService;
private IManageService manageService;
private IManageDao manageDao;
public void setManageService(IManageService manageService) {
this.manageService = manageService;
}
public void setManageDao(IManageDao manageDao) {
this.manageDao = manageDao;
}
public void setExamService(IExamService examService) {
this.examService = examService;
}
protected Map referenceData(HttpServletRequest request) throws Exception {
Map model = new HashMap();
String examId = request.getParameter("examId");
String type = request.getParameter("type");
Person person=null;
ExamMain examMain=null;
// examMain.setExamDate(new Date());
List examDetail = null;
if (!Tools.isEmptyString(examId)) {
Long id = new Long(examId);
examMain=this.examService.selectExamMain(id);
person=this.examService.selectPeople(examMain.getPersonId());
examDetail = this.examService.selectExamDetailByExamId(id);
}
model.put("person",person );
model.put("type",type );
model.put("examMain", examMain);
model.put("examDetail", examDetail);
model.put("dicData", DictionaryLoader.getInstance().getAllDictionary());
model.put("token", request.getParameter("token"));
return model;
}
@Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command,
org.springframework.validation.BindException errors)
throws Exception {
ExamEditInfo info = (ExamEditInfo) command;
ModelAndView mav = new ModelAndView("common/ajaxDone");
User currentUser = (User) Constants.getCurrentLoginUser(request);
//执行放入回收站操作
if ( request.getParameter("type") != null && request.getParameter("type").equals("delete")) {
String[] ids = request.getParameter("examIds").split(",");
ExamMain examMain = null;
for (String id : ids) {
examMain = this.examService.selectExamMain(Long.valueOf(id));
examMain.setStatus("1");
this.examService.saveMain(examMain);
}
mav.addObject("statusCode", 200);
mav.addObject("message", "操作成功!");
mav.addObject("navTabId", "examQueryNav");
}
//执行从回收站恢复数据操作
else if (request.getParameter("type") != null && request.getParameter("type").equals("recycle")) {
String[] ids = request.getParameter("examIds2").split(",");
ExamMain examMain = null;
int n = 0;//统计恢复失败的
int m = 0;//统计恢复成功的
for (String id : ids) {
examMain = this.examService.selectExamMain(Long.valueOf(id));
Person person = personService.selectPerGroupById(examMain.getPersonId());
if("1".equals(person.getStatus())){
//如果这个人的个人信息还在回收站,则不给恢复
n++;
}else if("0".equals(person.getStatus())){
//如果这个人的个人信息不在回收站,则给恢复
m++;
examMain.setStatus("0");
this.examService.saveMain(examMain);
}
}
if(n>0&&m==0){
mav.addObject("statusCode", 300);
mav.addObject("navTabId", "examRecNav");
mav.addObject("message", n+"条数据恢复失败,"+m+"条数据恢复成功!" +"如果恢复,请先恢复其个人信息");
}
if(n>0&&m>0){
mav.addObject("statusCode", 200);
mav.addObject("message", n+"条数据恢复失败,"+m+"条数据恢复成功!" +"如果恢复,请先恢复其个人信息");
mav.addObject("navTabId", "examRecNav");
}
if(n==0&&m>0){
mav.addObject("statusCode", 200);
mav.addObject("message", n+"条数据恢复失败,"+m+"条数据恢复成功!" );
mav.addObject("navTabId", "examRecNav");
}
}
//执行添加和修改操作
else {
info.setUserId(currentUser.getId());
List<Person> list=personService.selectPeopleByIdNo(info.getIdNO());
if(info.getPersonId()==null&&list.size()>0){
mav.addObject("statusCode", 300);
mav.addObject("message", "该身份证的信息人已存在");
}else{
Long examid =this.examService.saveExam(info);
if (info.getExamId() != null) {
OperateLogHelper.getInstance().registLog(OperateLog.LOG_APPDATA,
"新增体检信息,编号:/" + examid + ",人名称:" + info.getPersonName(),
(User) Constants.getCurrentLoginUser(request));
}
mav.addObject("statusCode", 200);
mav.addObject("navTabId", "examQueryNav");
mav.addObject("callbackType", "closeCurrent");
mav.addObject("message", "操作成功!");
}
}
mav.addObject("title", "个人体检项目信息");
return mav;
}
}
|
package org.study.core.concurrency.thread;
/**
* Created by iovchynnikov on 7/29/2015.
*/
public class Synchronizations {
public void run() {
Counter counter = new Counter();
Thread thread1 = new Thread(new RunnableObject("test1", counter, new Boolean[]{true, false, true, true}));
Thread thread2 = new Thread(new RunnableObject("test2", counter, new Boolean[]{false, true, true, false}));
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(counter);
}
private class Counter {
private int counter = 0;
public int increment() {
counter++;
return counter;
}
public int decrement() {
counter--;
return counter;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Counter{");
sb.append("counter=").append(counter);
sb.append('}');
return sb.toString();
}
}
private class RunnableObject implements Runnable {
private final String title;
private final Counter counter;
private final Boolean[] operations;
private RunnableObject(String title, Counter counter, Boolean[] operations) {
this.title = title;
this.counter = counter;
this.operations = operations;
}
@Override
public void run() {
System.out.println(this);
for (Boolean operation : operations) {
System.out.println(this + " " + operation);
if (operation) {
counter.increment();
} else {
counter.decrement();
}
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("RunnableObject{");
sb.append("title='").append(title).append('\'');
sb.append('}');
return sb.toString();
}
}
public static void main(String[] args) {
new Synchronizations().run();
}
}
|
package com.tencent.mm.plugin.wallet_core.model;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
public class Orders$RemarksInfo implements Parcelable {
public static final Creator<Orders$RemarksInfo> CREATOR = new 1();
public String pqi;
public String pqj;
protected Orders$RemarksInfo(Parcel parcel) {
this.pqi = parcel.readString();
this.pqj = parcel.readString();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(this.pqi);
parcel.writeString(this.pqj);
}
}
|
package com.creativewidgetworks.goldparser.engine;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import com.creativewidgetworks.goldparser.engine.GroupList;
public class GroupListTest {
@Test
public void testConstructorDefault() {
GroupList groups = new GroupList();
assertEquals("wrong size", 0, groups.size());
}
/*----------------------------------------------------------------------------*/
@Test
public void testConstructorWithSizing() {
GroupList groups = new GroupList(5);
assertEquals("wrong number of placeholders", 5, groups.size());
for (int i = 0; i < groups.size(); i++) {
assertNull(groups.get(i));
}
}
}
|
package soumyavn.store.SalesTax;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import org.junit.Test;
import soumyavn.store.SalesTax.catalog.ImportedProduct;
import soumyavn.store.SalesTax.catalog.ImportedTaxableProduct;
import soumyavn.store.SalesTax.catalog.Product;
import soumyavn.store.SalesTax.catalog.TaxableProduct;
public class ShoppingCartTest {
@Test
public void testGetCartTotal() {
assertEquals(new BigDecimal("29.83"), fillBasket1().getCartTotal());
assertEquals(new BigDecimal("65.15"), fillBasket2().getCartTotal());
assertEquals(new BigDecimal("74.68"), fillBasket3().getCartTotal());
}
@Test
public void testGetCartSalesTaxTotal() {
assertEquals(new BigDecimal("1.50"), fillBasket1().getCartSalesTaxTotal());
assertEquals(new BigDecimal("7.65"), fillBasket2().getCartSalesTaxTotal());
assertEquals(new BigDecimal("6.70"), fillBasket3().getCartSalesTaxTotal());
}
ShoppingCart fillBasket1() {
ArrayList<Product> cartItems = new ArrayList<Product>();
Product product;
product = new Product("book", new BigDecimal("12.49"));
cartItems.add(product);
product = new TaxableProduct("music CD", new BigDecimal("14.99"));
cartItems.add(product);
product = new Product("Chocolate Bar", new BigDecimal("0.85"));
cartItems.add(product);
ShoppingCart cart = new ShoppingCart(cartItems);
return cart;
}
ShoppingCart fillBasket2() {
Product product;
ArrayList<Product> cartItems = new ArrayList<Product>();
product = new ImportedProduct("imported box of chocolates", new BigDecimal("10.00"));
cartItems.add(product);
product = new ImportedTaxableProduct("imported bottle of perfume", new BigDecimal("47.50"));
cartItems.add(product);
ShoppingCart cart = new ShoppingCart(cartItems);
return cart;
}
ShoppingCart fillBasket3() {
Product product;
ArrayList<Product> cartItems = new ArrayList<Product>();
product = new ImportedTaxableProduct("imported bottle of perfume ", new BigDecimal("27.99"));
cartItems.add(product);
product = new TaxableProduct("bottle of perfume", new BigDecimal("18.99"));
cartItems.add(product);
product = new Product("packet of headache pills", new BigDecimal("9.75"));
cartItems.add(product);
product = new ImportedProduct("imported box of chocolates", new BigDecimal("11.25"));
cartItems.add(product);
ShoppingCart cart = new ShoppingCart(cartItems);
return cart;
}
}
|
package com.uwiseone.notify.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class NotifyDao implements CommonDao {
private JdbcTemplate jdbcTemplate;
@Override
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Map<String, Object>> getIssueList() {
StringBuffer query = new StringBuffer();
query.append(" SELECT ");
query.append(" CONCAT('ISSUE[신규] ',SUBJECT,' ");
query.append("http://qa.dawins.net/issues/', ID) AS STR ");
query.append(" FROM ISSUES ");
query.append(" WHERE ASSIGNED_TO_ID = 100 ");
query.append(" AND STATUS_ID <> 5 ");
query.append(" AND CREATED_ON BETWEEN DATE_ADD(NOW(), INTERVAL -3 MINUTE) AND NOW() ");
List<Map<String, Object>> list = jdbcTemplate.query(
query.toString(),
new Object[]{},
new RowMapper<Map<String, Object>>() {
@Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
Map<String, Object> returnValue = new HashMap<String, Object>();
returnValue.put("STR", rs.getString("STR"));
return returnValue;
}
});
return list;
}
}
|
package net.minecraft.block;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.init.SoundEvents;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
public class BlockPressurePlateWeighted extends BlockBasePressurePlate {
public static final PropertyInteger POWER = PropertyInteger.create("power", 0, 15);
private final int maxWeight;
protected BlockPressurePlateWeighted(Material materialIn, int p_i46379_2_) {
this(materialIn, p_i46379_2_, materialIn.getMaterialMapColor());
}
protected BlockPressurePlateWeighted(Material materialIn, int p_i46380_2_, MapColor color) {
super(materialIn, color);
setDefaultState(this.blockState.getBaseState().withProperty((IProperty)POWER, Integer.valueOf(0)));
this.maxWeight = p_i46380_2_;
}
protected int computeRedstoneStrength(World worldIn, BlockPos pos) {
int i = Math.min(worldIn.getEntitiesWithinAABB(Entity.class, PRESSURE_AABB.offset(pos)).size(), this.maxWeight);
if (i > 0) {
float f = Math.min(this.maxWeight, i) / this.maxWeight;
return MathHelper.ceil(f * 15.0F);
}
return 0;
}
protected void playClickOnSound(World worldIn, BlockPos color) {
worldIn.playSound(null, color, SoundEvents.BLOCK_METAL_PRESSPLATE_CLICK_ON, SoundCategory.BLOCKS, 0.3F, 0.90000004F);
}
protected void playClickOffSound(World worldIn, BlockPos pos) {
worldIn.playSound(null, pos, SoundEvents.BLOCK_METAL_PRESSPLATE_CLICK_OFF, SoundCategory.BLOCKS, 0.3F, 0.75F);
}
protected int getRedstoneStrength(IBlockState state) {
return ((Integer)state.getValue((IProperty)POWER)).intValue();
}
protected IBlockState setRedstoneStrength(IBlockState state, int strength) {
return state.withProperty((IProperty)POWER, Integer.valueOf(strength));
}
public int tickRate(World worldIn) {
return 10;
}
public IBlockState getStateFromMeta(int meta) {
return getDefaultState().withProperty((IProperty)POWER, Integer.valueOf(meta));
}
public int getMetaFromState(IBlockState state) {
return ((Integer)state.getValue((IProperty)POWER)).intValue();
}
protected BlockStateContainer createBlockState() {
return new BlockStateContainer(this, new IProperty[] { (IProperty)POWER });
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\block\BlockPressurePlateWeighted.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
package servlets;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//importamos la libreria con la configuracion de la base de datos
import config.Acceso;
/**
* Servlet implementation class SERVLOGIN
*/
@WebServlet("/SERVLOGIN")
public class SERVLOGIN extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException {
//asignamos el tipo de respuesta
response.setContentType("text/html;charset=UTF-8");
String username ;
String password ;
//inicializamos un objeto con la clase Acceso
Acceso acc = new Acceso();// inicializamos el objeto de config.acceso
boolean status= false;
RequestDispatcher rd = null;
if(request.getParameter("btnLogin") != null) {
username = request.getParameter("user"); //optenemos el valor de user desde el POST
password = request.getParameter("pass"); //optenemos el valor de pass desde el POST
//validamos si las credenciales existen
status = acc.Validar(username, password); //llamamos a la funcion validad dentro de la clase Acceso
if(status == true) {
request.setAttribute("status", true);
} else {
//mensaje de error al no pasar las credenciales
request.setAttribute("mensaje", "Usuario o clave incorrectos");
//redireccionamos al login al con mensaje
}
request.setAttribute("user", username);
rd = request.getRequestDispatcher("index.jsp"); //redireccionar
}
rd.forward(request, response);
//}
}
/*Generado con Eclipse*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
processRequest(request, response);
} catch (ClassNotFoundException | ServletException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*Generado con Eclipse*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
processRequest(request, response);
} catch (ClassNotFoundException | ServletException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.knaptus.domainiser.clone;
import com.knaptus.domainiser.core.DomainDefinition;
import com.knaptus.domainiser.core.impl.DomainGraphDefinitionImpl;
import com.knaptus.domainiser.core.DomainResolver;
import com.knaptus.domainiser.example.Address;
import com.knaptus.domainiser.example.ExampleDomainResolver;
import com.knaptus.domainiser.example.Person;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static junit.framework.Assert.assertNotNull;
import static org.junit.Assert.*;
/**
* Unit test
*
* @author Aditya Bhardwaj
*/
public class CloningDomainWalkerTest {
public static final String FRIEND_1 = "Friend1";
public static final String FRIEND_2 = "Friend2";
private CloningDomainWalker cloningDomainWalker;
private Person grandDad;
@Before
public void setUp() throws Exception {
cloningDomainWalker = new CloningDomainWalker();
DomainResolver domainResolver = new ExampleDomainResolver();
cloningDomainWalker.setDomainResolver(domainResolver);
grandDad = new Person("Grand Dad", 80);
Person grandMom = new Person("Grand Mom", 79);
grandDad.setSpouse(grandMom);
Person dad = new Person("Dad", 50);
Person mom = new Person("Mom", 49);
dad.setSpouse(mom);
grandDad.addChild(dad);
grandMom.addChild(dad);
Person child1 = new Person("Child 1", 10);
dad.addChild(child1);
mom.addChild(child1);
Person child2 = new Person("Child 2", 15);
dad.addChild(child2);
mom.addChild(child2);
Person grandDadFriend1 = new Person(FRIEND_1, 80);
Person grandDadFriend2 = new Person(FRIEND_2, 80);
grandDad.addFriend(grandDadFriend1.getName(), grandDadFriend1);
grandDad.addFriend(grandDadFriend2.getName(), grandDadFriend2);
Address address1 = new Address();
address1.setLine1("address1");
grandDad.addAddress(address1);
Address address2 = new Address();
address2.setLine1("address2");
grandDad.addAddress(address2);
}
@Test
public void testWalkDefault() throws Exception {
Person person = cloningDomainWalker.walk(grandDad);
assertNotSame(grandDad, person);
assertEquals(grandDad.getName(), person.getName());
assertEquals(grandDad.getAge(), person.getAge());
assertNull(person.getSpouse());
assertNotNull(person.getChildren());
assertEquals(0, person.getChildren().size());
}
@Test
public void testWalkDefaultWithKeepReferences() throws Exception {
cloningDomainWalker.setKeepReferences(true);
Person person = cloningDomainWalker.walk(grandDad);
assertNotSame(grandDad, person);
assertEquals(grandDad.getName(), person.getName());
assertEquals(grandDad.getAge(), person.getAge());
assertNotNull(person.getSpouse());
assertSame(grandDad.getSpouse(), person.getSpouse());
assertEquals(1, person.getChildren().size());
assertSame("Dad object should be the same", grandDad.getChildren().get(0), person.getChildren().get(0));
assertEquals(2, person.getFriends().size());
assertSame("Friend1 object should be the same",
grandDad.getFriends().get(FRIEND_1),
person.getFriends().get(FRIEND_1));
assertEquals(2, person.getAddresses().size());
//one of the cloned address should not match any of the address from the original object.
boolean exactMatchFound = false;
Address clonedAddress = person.getAddresses().iterator().next();
for(Address address : grandDad.getAddresses()) {
if(address == clonedAddress) {
exactMatchFound = true;
}
}
assertTrue("Atleast one should match by reference", exactMatchFound);
}
@Test
public void testWalkCopySpouse() throws Exception {
DomainDefinition<Person> personDomainDefinition = DomainDefinition.getInstance(Person.class, cloningDomainWalker.getDomainResolver());
DomainGraphDefinitionImpl<Person> domainGraphDefinition = new DomainGraphDefinitionImpl<Person>(personDomainDefinition);
domainGraphDefinition.addChild("spouse", personDomainDefinition);
Person person = cloningDomainWalker.walk(grandDad, domainGraphDefinition);
assertNotSame(grandDad, person);
assertEquals(grandDad.getName(), person.getName());
assertEquals(grandDad.getAge(), person.getAge());
assertNotNull(person.getSpouse());
assertNotSame(grandDad.getSpouse(), person.getSpouse());
assertEquals(0, person.getChildren().size());
assertEquals(0, person.getFriends().size());
}
@Test
public void testWalkCopyChildren() throws Exception {
DomainDefinition<Person> personDomainDefinition = DomainDefinition.getInstance(Person.class, cloningDomainWalker.getDomainResolver());
DomainGraphDefinitionImpl<Person> domainGraphDefinition = new DomainGraphDefinitionImpl<Person>(personDomainDefinition);
domainGraphDefinition.addChild("children", personDomainDefinition);
Person person = cloningDomainWalker.walk(grandDad, domainGraphDefinition);
assertNotSame(grandDad, person);
assertEquals(grandDad.getName(), person.getName());
assertEquals(grandDad.getAge(), person.getAge());
assertNull(person.getSpouse());
assertNotNull(person.getChildren());
assertEquals(1, person.getChildren().size());
assertNotSame("Dad object should not be the same", grandDad.getChildren().get(0), person.getChildren().get(0));
assertEquals(0, person.getFriends().size());
}
@Test
public void testWalkCopyFriendsAndChildren() throws Exception {
DomainDefinition<Person> personDomainDefinition = DomainDefinition.getInstance(Person.class, cloningDomainWalker.getDomainResolver());
DomainGraphDefinitionImpl<Person> domainGraphDefinition = new DomainGraphDefinitionImpl<Person>(personDomainDefinition);
domainGraphDefinition.addChild("children", personDomainDefinition);
domainGraphDefinition.addChild("friends", personDomainDefinition);
Person person = cloningDomainWalker.walk(grandDad, domainGraphDefinition);
assertNotSame(grandDad, person);
assertEquals(grandDad.getName(), person.getName());
assertEquals(grandDad.getAge(), person.getAge());
assertNull(person.getSpouse());
assertEquals("Dad should be copied", 1, person.getChildren().size());
assertNotSame("Dad object should not be the same", grandDad.getChildren().get(0), person.getChildren().get(0));
assertEquals("Friends should be copied", 2, person.getFriends().size());
Assert.assertNotSame("Friend1 object should not be the same",
grandDad.getFriends().get(FRIEND_1),
person.getFriends().get(FRIEND_1));
}
@Test
public void testWalkCopyAddresses() throws Exception {
DomainDefinition<Person> personDomainDefinition = DomainDefinition.getInstance(Person.class, cloningDomainWalker.getDomainResolver());
DomainDefinition<Address> addressDomainDefinition = DomainDefinition.getInstance(Address.class, cloningDomainWalker.getDomainResolver());
DomainGraphDefinitionImpl<Person> domainGraphDefinition = new DomainGraphDefinitionImpl<Person>(personDomainDefinition);
domainGraphDefinition.addChild("addresses", addressDomainDefinition);
Person person = cloningDomainWalker.walk(grandDad, domainGraphDefinition);
assertNotSame(grandDad, person);
assertEquals(grandDad.getName(), person.getName());
assertEquals(grandDad.getAge(), person.getAge());
assertNull(person.getSpouse());
assertEquals("Dad shouldn't have been copied", 0, person.getChildren().size());
assertEquals("Friends should be empty", 0, person.getFriends().size());
Assert.assertEquals(2, person.getAddresses().size());
//one of the cloned address should not match any of the address from the original object.
Address clonedAddress = person.getAddresses().iterator().next();
for(Address address : grandDad.getAddresses()) {
Assert.assertNotSame(address, clonedAddress);
}
}
@Test
@Ignore
public void testWalkCopySpouseAndChildrenCrossRefCheck() throws Exception {
DomainDefinition<Person> personDomainDefinition = DomainDefinition.getInstance(Person.class, cloningDomainWalker.getDomainResolver());
DomainGraphDefinitionImpl<Person> domainGraphDefinition = new DomainGraphDefinitionImpl<Person>(personDomainDefinition);
domainGraphDefinition.addChild("children", personDomainDefinition);
domainGraphDefinition.addChild("spouse", personDomainDefinition);
Person person = cloningDomainWalker.walk(grandDad, domainGraphDefinition);
assertNotSame(grandDad, person);
assertEquals(grandDad.getName(), person.getName());
assertEquals(grandDad.getAge(), person.getAge());
assertNotNull(person.getSpouse());
assertEquals("Dad should be copied", 1, person.getChildren().size());
assertNotSame("Dad object should not be the same", grandDad.getChildren().get(0), person.getChildren().get(0));
assertNotNull(person.getSpouse().getChildren());
assertEquals("Dad should be copied to grandmom also", 1, person.getSpouse().getChildren().size());
}
}
|
package org.kt3k.straw.plugin;
import static org.kt3k.straw.plugin.HttpPlugin.*;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLSession;
import org.junit.Test;
import org.junit.Rule;
import org.junit.Before;
import org.kt3k.straw.StrawDrink;
import org.mockito.ArgumentCaptor;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import com.github.tomakehurst.wiremock.junit.*;
public class HttpPluginTest {
HttpParam param;
HttpPlugin plugin;
StrawDrink drink;
ArgumentCaptor<HttpResult> captor;
@Rule
public WireMockRule wireMockRule = new WireMockRule(8089, 8443);
@Before
public void setUp() {
this.param = new HttpParam();
this.plugin = new HttpPlugin();
this.drink = mock(StrawDrink.class);
this.captor = ArgumentCaptor.forClass(HttpResult.class);
}
@Test
public void testGetName() {
HttpPlugin plugin = new org.kt3k.straw.plugin.HttpPlugin();
assertEquals("http", plugin.getName());
}
@Test
public void testHttpParam() {
assertNotNull(new HttpParam());
}
@Test
public void testHttpResult() {
HttpResult httpResult = new HttpResult("abc");
assertNotNull(httpResult);
assertEquals(httpResult.content, "abc");
}
@Test
public void testGet() {
// stub http url
stubFor(get(urlEqualTo("/http/stub")).willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/plain").withBody("This is response text.")));
// prepare argument captor
ArgumentCaptor<HttpResult> captor = ArgumentCaptor.forClass(HttpResult.class);
this.param.url = "http://localhost:8089/http/stub";
// get request to stub server
this.plugin.get(this.param, this.drink);
// capture response
verify(this.drink).success(captor.capture());
// assert response text
assertEquals("This is response text.", captor.getValue().content);
}
@Test
public void testGetWithHttps() throws InterruptedException {
stubFor(get(urlEqualTo("/https/stub")).willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/plain").withBody("This is response text.")));
ArgumentCaptor<HttpResult> captor = ArgumentCaptor.forClass(HttpResult.class);
this.param.url = "https://localhost:8443/https/stub";
this.plugin.get(this.param, this.drink);
verify(this.drink).success(captor.capture());
assertEquals("This is response text.", captor.getValue().content);
}
@Test
public void testGetWithMalformedUrl() {
this.param.url = "zzzZZZ";
this.plugin.get(this.param, this.drink);
verify(this.drink).fail(URL_MALFORMED_ERROR, "URL format is wrong: zzzZZZ\n" +
"java.net.MalformedURLException: no protocol: zzzZZZ");
}
@Test
public void testGetWithIOErrorWhenConnect() {
this.param.url = "http://localhost:333/";
this.plugin.get(this.param, this.drink);
verify(this.drink).fail(CANNOT_READ_ERROR, "input stream cannot open: http://localhost:333/\n" +
"java.net.ConnectException: Connection refused");
}
@Test
public void testGetWithUrlNull() {
this.param.url = null;
this.plugin.get(this.param, this.drink);
verify(this.drink).fail(CANNOT_CONNECT_ERROR, "cannot connect to url: null\n" +
"java.io.IOException: url is null");
}
@Test
public void testGet404() {
stubFor(get(urlEqualTo("/404")).willReturn(aResponse().withStatus(404)));
this.param.url = "http://localhost:8089/404";
this.plugin.get(this.param, this.drink);
verify(this.drink).fail(CANNOT_READ_ERROR, "input stream cannot open: http://localhost:8089/404\n" +
"java.io.FileNotFoundException: http://localhost:8089/404");
}
@Test
public void testGetTimeout() {
stubFor(get(urlEqualTo("/http/stub")).willReturn(aResponse().withStatus(200).withFixedDelay(2000)));
this.param.url = "http://localhost:8089/http/stub";
this.param.timeout = 1000;
this.plugin.get(this.param, this.drink);
verify(this.drink).fail(TIMEOUT, "connection timed out: http://localhost:8089/http/stub\n" +
"java.net.SocketTimeoutException: Read timed out");
}
@Test
public void testGetNoTimeout() {
stubFor(get(urlEqualTo("/http/stub")).willReturn(aResponse().withStatus(200).withFixedDelay(2000)));
this.param.url = "http://localhost:8089/http/stub";
this.plugin.get(this.param, this.drink);
verify(this.drink).success(isA(HttpResult.class));
}
@Test
public void testGetInTimeout() {
stubFor(get(urlEqualTo("/http/stub")).willReturn(aResponse().withStatus(200).withFixedDelay(2000)));
this.param.url = "http://localhost:8089/http/stub";
this.param.timeout = 3000;
this.plugin.get(this.param, this.drink);
verify(this.drink).success(isA(HttpResult.class));
}
@Test
public void testGetWithCharset() throws UnsupportedEncodingException {
stubFor(get(urlEqualTo("/http/stub")).willReturn(aResponse().withStatus(200).withBody("あい".getBytes("UTF-8"))));
this.param.url = "http://localhost:8089/http/stub";
this.param.charset = "utf-8";
this.plugin.get(this.param, this.drink);
verify(this.drink).success(this.captor.capture());
assertEquals("あい", captor.getValue().content);
}
@Test
public void testTrustManger() throws CertificateException {
// test these things exist and run with no exception
TRUST_ALL.checkClientTrusted(new X509Certificate[]{}, "");
TRUST_ALL.checkServerTrusted(new X509Certificate[]{}, "");
TRUST_ALL.getAcceptedIssuers();
}
@Test
public void testHostnameVerifier() {
NO_VERIFIER.verify("", mock(SSLSession.class));
}
@Test
public void testNoKeepAlive() {
stubFor(get(urlEqualTo("/http/stub")).willReturn(aResponse().withStatus(200)));
this.param.url = "http://localhost:8089/http/stub";
this.plugin.get(this.param, this.drink);
assertEquals("false", System.getProperty("http.keepAlive"));
}
}
|
package org.hodroist.app;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
//Allow to play mp3 streaming from server
public class Player extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
String TAG = getClass().getSimpleName();
MediaPlayer mp = null;
Button play;
Button tracklist;
Button stop;
Button next;
Button prev;
String mediaServerIP;
String password;
Track selectedTrack;
int trackIndex;
String[] mp3Collection;
TextView playingText;
TextView loadedText;
TextView trackOrderText;
ImageView artwork;
ProgressBar seekBar;
Handler mHandler = new Handler();
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.player);
//Get variables from Intent of previous activity
Bundle bundle = this.getIntent().getExtras();
mediaServerIP = bundle.getString("ip");
password = bundle.getString("password");
selectedTrack = (Track) bundle.getSerializable("track");
trackIndex = bundle.getInt("trackIndex");
mp3Collection = bundle.getStringArray("collection");
//Obtain GUI layout items
play = (Button) findViewById(R.id.playButton);
stop = (Button) findViewById(R.id.stopButton);
next = (Button) findViewById(R.id.nextButton);
prev = (Button) findViewById(R.id.prevButton);
tracklist = (Button) findViewById(R.id.tracklistButton);
playingText = (TextView) findViewById(R.id.playingText);
loadedText = (TextView) findViewById(R.id.loadedText);
trackOrderText = (TextView) findViewById(R.id.trackOrderText);
artwork = (ImageView) findViewById(R.id.artworkImageView);
seekBar = (ProgressBar) findViewById(R.id.seekBar);
//Set configuration of GUI
resetProgressBar();
setArtwork();
setPlayingText();
setTrackOrderText();
// Set Buttons listeners
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
next();
}
});
tracklist.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Intent to open next Activity -> Tracklist.class
Intent i = new Intent(Player.this, Tracklist.class);
Bundle bundle = new Bundle();
bundle.putString("ip",mediaServerIP);
bundle.putString("password", password);
i.putExtras(bundle);
//Open Tracklist Activity
Player.this.startActivity(i);
}
});
prev.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
prev();
}
});
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
stop();
}
});
}
//Reset position of progress bar
void resetProgressBar(){
mHandler.post(new Runnable() {
public void run() {
seekBar.setProgress(0);
}
});
}
//Show information about playing track on GUI
void setPlayingText(){
// When clicked, show a toast with the track text
Toast.makeText(getApplicationContext(), "Loading: "+selectedTrack.artist+" - "+selectedTrack.title,Toast.LENGTH_SHORT).show();
playingText.setText(selectedTrack.artist+" - "+selectedTrack.title + " ("+selectedTrack.year+")"+" ["+selectedTrack.album+"]");
}
//Show order of playing track
void setTrackOrderText(){
trackOrderText.setText("Track "+(trackIndex+1)+" of "+mp3Collection.length);
}
//Show artwork image of playing track
void setArtwork(){
Bitmap bitmap = BitmapFactory.decodeByteArray(selectedTrack.artwork, 0, selectedTrack.artwork.length);
artwork.setImageBitmap(bitmap);
}
//Play a track
void play() {
//Change color of play and stop button
play.setBackgroundResource(R.drawable.greenplay);
stop.setBackgroundResource(R.drawable.bluestop);
Uri myUri = Uri.parse("http://"+mediaServerIP+":8088/"+Uri.encode(selectedTrack.filename));
Log.d(TAG, "Url -> "+myUri.toString());
//Starts a Media Player
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
//Overrided method
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}
//Stop playing a track
void stop() {
if(mp.isPlaying()){
//Change color of play and stop buttons
play.setBackgroundResource(R.drawable.blueplay);
stop.setBackgroundResource(R.drawable.greenstop);
mp.stop();
}
}
//Get a track object from server, set GUI parameters and call play() method
void loadAndPlayTrack(){
ServerConnection conn = new ServerConnection(mediaServerIP,password);
selectedTrack = (Track) conn.getTrack(trackIndex);
resetProgressBar();
setArtwork();
setPlayingText();
setTrackOrderText();
play();
}
//Play next track
void next() {
if(trackIndex<mp3Collection.length-1){
trackIndex++;
loadAndPlayTrack();
}else{
trackIndex=0;
loadAndPlayTrack();
}
}
//Play previous track
void prev(){
if(trackIndex>0){
trackIndex--;
loadAndPlayTrack();
}else{
trackIndex=mp3Collection.length-1;
loadAndPlayTrack();
}
}
@Override
public void onDestroy() {
super.onDestroy();
stop();
}
//Overrided method
public void onCompletion(MediaPlayer mp) {
stop();
}
//Overrided method
public boolean onError(MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(TAG, sb.toString());
return true;
}
//Overrided method
public void onBufferingUpdate(MediaPlayer mp, int percent) {
//Update seekbar & loadedTextView
seekBar.setSecondaryProgress(percent);
loadedText.setText("Loaded: "+percent+" %");
}
}
|
package org.webmaple.common.enums;
/**
* @author lyifee
* on 2021/2/2
*/
public enum SourceType {
SERVER('0'),
MYSQL('1'),
MONGODB('2'),
REDIS('3')
;
private char type;
SourceType(char type) {
this.type = type;
}
public char getType() {
return type;
}
public void setType(char type) {
this.type = type;
}
public static String getTypeStr(char type) throws Exception {
SourceType[] types = SourceType.values();
for (SourceType sourceType : types) {
if (sourceType.type == type) {
return sourceType.name().toLowerCase();
}
}
throw new Exception("invalid type : " + type);
}
}
|
package com.yeahbunny.stranger.server.utils;
import org.springframework.security.core.context.SecurityContextHolder;
import com.yeahbunny.stranger.server.security.CustomUserDetails;
public class AuthUtils {
public static String getAuthenticatedUserUsername() {
return ((CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
}
public static Long getAuthenticatedUserId() {
return ((CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUserId();
}
}
|
package Politech;
import java.util.ArrayList;
import java.util.Date;
public interface Service {
ArrayList list();
int num();
Date uD();
}
|
package com.example.todolist.Model.RemoteDataSource;
import com.example.todolist.Model.Entities.EntryResponse;
import com.example.todolist.Model.Entities.Groups;
import com.example.todolist.Model.Entities.Tasks;
import com.google.gson.JsonObject;
import java.util.List;
import io.reactivex.Single;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface Api_Interface {
@GET("get_groups.php")
Single<List<Groups>> get_GroupList();
@GET("get_tasks.php")
Single<List<Tasks>> get_TasksList();
@POST("add_group.php")
Single<String> add_Group(@Body JsonObject body);
@POST("add_task.php")
Single<String> add_Task(@Body JsonObject body);
@POST("entry.php")
Single<EntryResponse> entry(@Body JsonObject body);
}
|
package com.jianglei.zhaopin.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class CoordsConverter {
public static void main(String[] args) {
/*
* String convert = convert("125.321753,43.897727");
* System.out.println(convert);
*/
try {
convertAddtoCoords("长春");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据地址解析经纬度,如果没有解析出来,返回空字符串
*
* @param addr
* @return
* @throws Exception
*/
@SuppressWarnings("finally")
public static String convertAddtoCoords(String addr) {
String lonlat = "";
String result;
try {
String enAddr = URLEncoder.encode(addr, "UTF-8");
String url = "http://api.map.baidu.com/geocoder/v2/" + "?address=" + enAddr
+ "&output=json&ak=huWwdukpW9jeD86w0InyquPR630HxsSO";
result = getResult(url);
JSONObject json = JSONObject.fromObject(result);
Integer status = (Integer) json.get("status");
if (status == null || status != 0) {
return lonlat;
}
if (status == 0) {
JSONObject bresult = JSONObject.fromObject(json.get("result"));
JSONObject loc = JSONObject.fromObject(bresult.get("location"));
String lon = loc.get("lng") + "";
String lat = loc.get("lat") + "";
lonlat = lon + "," + lat;
}
System.out.println(lonlat);
} catch (Exception e) {
e.printStackTrace();
} finally {
return lonlat;
}
}
/**
* 单个经度转换 格式: 经度+,+纬度 125.xxxxxx,43.xxxxx 如果转换出问题会返回 空字符串”“
*
* @param LonLat
*/
public static String convert(String LonLat) {
String url = "http://api.map.baidu.com/geoconv/v1/?coords=" + LonLat
+ "&from=3&to=5&ak=huWwdukpW9jeD86w0InyquPR630HxsSO";
String lonlat = "";
try {
String content = getResult(url);
JSONObject jsonObject = JSONObject.fromObject(content);
Object result = jsonObject.get("result");
JSONObject xy = JSONObject.fromObject(JSONArray.fromObject(result).get(0));
lonlat = xy.getString("x") + "," + xy.getString("y");
/*
* System.out.println(xy.getString("x"));
* System.out.println(xy.getString("y"));
*/
} catch (IOException e) {
System.out.println("坐标转换出现问题:" + LonLat);
e.printStackTrace();
}
return lonlat;
}
/**
* @param url
* @return
* @throws MalformedURLException
* @throws IOException
*/
public static String getResult(String url) throws MalformedURLException, IOException {
URL urL = new URL(url);
URLConnection Connection = urL.openConnection();
InputStream inputStream = Connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
String content = "";
while ((line = reader.readLine()) != null) {
content = content + line;
}
return content;
}
}
|
package com.example.demo.Controller;
import com.example.demo.Config.JwtUtil;
import com.example.demo.Config.pwdEncoder;
import com.example.demo.Mappers.StudentMapper;
import com.example.demo.Mappers.TeacherMapper;
import com.example.demo.Mappers.UserMapper;
import com.example.demo.Status.Exception.NotFoundException;
import com.example.demo.Status.Exception.UnauthorizedException;
import com.example.demo.annotation.*;
import com.example.demo.domain.User;
import com.example.demo.Status.Result;
import com.example.springboot.demo.singleton.SingletonMybatis;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/index") //在类上使用RequestMapping,里面设置的value就是方法的父路径
public class UserController {
private static SqlSessionFactory sqlSessionFactory;
static {
sqlSessionFactory = SingletonMybatis.getSqlSessionFactory();
}
@RequestMapping //如果方法上的RequestMapping没有value,则此方法默认被父路径调用
public String index() {
return "hello spring boot";
}
//这里体现了restful风格的请求,按照请求的类型,来进行增删查改。
@RequestMapping(method = RequestMethod.GET, value = "/users")
public List<User> getUsers() {
List<User> listUsers;
//获取一个连接
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
//得到映射器
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//调用接口中的方法去执行xml文件中的SQL语句
listUsers = userMapper.getUsers();
//要提交后才会生效
sqlSession.commit();
} finally {
//最后记得关闭连接
sqlSession.close();
}
return listUsers;
}
//RequestBody这个注解可以接收json数据
//注册新用户
@RequestMapping(method = RequestMethod.POST, value = "/register")
public Object setUser(String userId, String password,String role) {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
StudentMapper studentMapper =sqlSession.getMapper(StudentMapper.class);
TeacherMapper teacherMapper =sqlSession.getMapper(TeacherMapper.class);
User user = userMapper.getByUserId(userId);
if (user != null) {
sqlSession.close();
return new Result("用户名已存在", Result.StatusCode.FAIL.getCode());
} else {
String pwdEncoded = pwdEncoder.getSaltMD5(password);
userMapper.insert(userId, pwdEncoded,role);
if(role.equals("student")){
System.out.println("aaa");
studentMapper.insert(userId);
}else if(role.equals("teacher")){
teacherMapper.insert(userId);
}
sqlSession.commit();
sqlSession.close();
return new Result("注册成功", Result.StatusCode.SUCCESS.getCode());
}
}
//登录
@LoginToken
@RequestMapping(method = RequestMethod.POST, value = "/login")
public Object login(String userId, String password) throws NotFoundException, UnauthorizedException {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getByUserId(userId);
sqlSession.close();
if (user == null) {
throw new NotFoundException("用户名不存在", Result.StatusCode.USER_NOT_FOUND.getCode());
} else {
String pwd = user.getPassword();
boolean isSuccess = pwdEncoder.getSaltverifyMD5(password, pwd);
if (isSuccess) {
String token = JwtUtil.createJWT(user);
JSONObject userInfo = new JSONObject();
userInfo.put("userId", user.getUserId());
userInfo.put("name", user.getName());
userInfo.put("role",user.getRole());
userInfo.put("token", token);
return new Result("登录成功", Result.StatusCode.SUCCESS.getCode(), userInfo,null);
} else {
throw new UnauthorizedException("密码错误", Result.StatusCode.Unauthorized.getCode());
}
}
}
@CheckToken
@RequestMapping(method = RequestMethod.POST, value = "/testToken")
public Object testToken(@CurrentUser User user) {
return user;
}
}
|
package de.zarncke.lib.err;
import java.io.Serializable;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;
import de.zarncke.lib.block.ABlock;
import de.zarncke.lib.block.Block;
import de.zarncke.lib.block.Running;
import de.zarncke.lib.log.Log;
/**
* Tracks exceptions and ensures their reporting.
* Use as follows:
*
* <pre>
* <code>
* // this outer layer ensures that no exception goes unreported
* Warden.guard(new Running() {
* @Override
* public void run() {
* doComplexProcessing();
* }
* private void doComplexProcessing() {
* // ...
* try {
* doDeeperProcessing();
* }
* catch(MyException e) {
* // solve issue
*
* // this will ensure that the exception will not be reported
* Warden.disregard(e);
* }
*
* doDeeperProcessing();
* // ...
* }
* private void doDeeperProcessing() {
* // ...
* // this will ensure that the exception is reported (by the Warden)
* throw Warden.spot(new MyException("explain"));
* // ...
* }
* });
* </code>
* </pre>
*
* Note that the Warden will handle chained exceptions (both ways) properly and report the most detailed one and only
* once.
*
* @author Gunnar Zarncke
*/
public class Warden {
static final class GuardedRunning extends Running implements Serializable {
private static final long serialVersionUID = 1L; // serializable if nested elements are
private Block<?> block;
private boolean strict;
@SuppressWarnings("unused" /* for serialization */)
private GuardedRunning() {
}
public GuardedRunning(final Block<?> block, final boolean strict) {
this.block = block;
this.strict = strict;
}
@Override
public void run() {
guard(this.strict ? ABlock.wrapInReportingBlock(this.block, null, new UncaughtExceptionHandler() {
@Override
public void uncaughtException(final Thread t, final Throwable e) {
Warden.report(e);
}
}) : this.block);
}
@Override
public String toString() {
return "guarding " + this.block + (this.strict ? " strictly" : "");
}
}
private static final ThreadLocal<Warden> THREAD_WARDEN = new ThreadLocal<Warden>();
private final Warden outerWarden;
private final Set<Throwable> trackedThrowables = new HashSet<Throwable>();
private List<Throwable> reportedThrowables = new LinkedList<Throwable>();
Warden(final Warden outerWarden) {
this.outerWarden = outerWarden;
}
/**
* Tell the Warden to disregard the {@link Throwable}, but take note of it.
* This means that this Throwable will not be reported later as "missing", but nonetheless as "occurred".
*
* @param throwableToIgnore this {@link Throwable} is "solved"
*/
public static void disregardAndReport(@Nonnull final Throwable throwableToIgnore) {
Warden currentWarden = currentWarden();
currentWarden.disregardThrowable(throwableToIgnore);
log(throwableToIgnore);
}
/**
* Tell the system that an Exception was handled and doesn't need to be reported.
* Note: This logs this incident with low priority.
* If are going to report it anyway, it is recommended to use {@link #disregardAndReport(Throwable)}.
*
* @param throwableToIgnore exception != null
*/
public static void disregard(@Nonnull final Throwable throwableToIgnore) {
logFromWithinLogging("disregarding " + throwableToIgnore);
currentWarden().disregardThrowable(throwableToIgnore);
}
/**
* Definitely report a problem but do not throw/forward it.
* Reporting it means:
* <ul>
* <li>It will be logged,</li>
* <li>it will be remembered by the Warden and</li>
* <li>it will be returned by the {@link #guard(Block) guard call}.</li>
* </ul>
*
* @param spottedThrowable != null
*/
public static void report(@Nonnull final Throwable spottedThrowable) {
currentWarden().logReport(spottedThrowable);
log(spottedThrowable);
}
public static void log(@Nonnull final Throwable spottedThrowable) {
if (spottedThrowable instanceof ShutdownPending) {
spottedThrowable.printStackTrace(System.err);
} else {
Log.LOG.get().report(spottedThrowable);
}
}
/**
* Reports problems within this logging package. <em>Important:</em> The name of this method is handled specially by
* logging! All other methods in this class and package occurring in stacktraces are ignored when determining
* callers except for this one.
*
* @param message to log as occurring explicitly from within logging
*/
public static void logFromWithinLogging(final String message) {
try {
Log.LOG.get().report(message);
} catch (ShutdownPending e) {
// ignore, this is not a problem during shutdown
}
}
private void logReport(@Nonnull final Throwable reportedThrowable) {
this.reportedThrowables.add(reportedThrowable);
}
/**
* Observe the occurrence of the exception just before it is thrown.
* The Warden will ensure that it is ultimately logged if it is not handled (by {@link #disregard(Throwable)}.
* This should be called before <strong>every</strong> throw.
* Best enforce by a CheckStyle rule which forbids <code>throw new</code>.
*
* @param <T> to return properly
* @param spottedThrowable != null
* @return same Throwable
*/
public static <T extends Throwable> T spot(@Nonnull final T spottedThrowable) {
return currentWarden().spotThrowable(spottedThrowable);
}
/**
* Record that an Exception was handled and doesn't need to be reported.
* Removes this exception and all of its causes from tracking.
*
* @param throwableToIgnore != null
*/
public void disregardThrowable(@Nonnull final Throwable throwableToIgnore) {
Throwable cause = throwableToIgnore;
int n = 0;
while (cause != null && n < ExceptionUtil.MAX_TESTED_EXCEPTION_NESTING) {
this.trackedThrowables.remove(cause);
cause = cause.getCause();
n++;
}
}
/**
* See {@link #spot(Throwable)}.
*
* @param <T> of spottedThrowable
* @param spottedThrowable != null
* @return spottedThrowable
*/
public <T extends Throwable> T spotThrowable(@Nonnull final T spottedThrowable) {
try {
// check if it is already known indirectly ->
for (Throwable t : this.trackedThrowables) {
if (t != spottedThrowable && ExceptionUtil.stacktraceContainsException(t, spottedThrowable)) {
report(new IllegalStateException("spotting <<" + spottedThrowable
+ ">>,\n which was already spotted as cause of <<" + t + ">> (below).\n"
+ "This is probably a problem", t));
return spottedThrowable;
}
}
Iterator<Throwable> it = this.trackedThrowables.iterator();
while (it.hasNext()) {
Throwable t = it.next();
if (ExceptionUtil.stacktraceContainsException(spottedThrowable, t)) {
it.remove();
}
}
this.trackedThrowables.add(spottedThrowable);
return spottedThrowable;
} catch (ConcurrentModificationException e) {
// can only happen if some other thread is reusing the Warden inappropriately
logFromWithinLogging("Invalid use of Warden. A Warden may only be used by the same Thread. -> " + e.getMessage());
return spottedThrowable;
} catch (Exception e) {
// this is a dangerous case and hopefully will not happen
logFromWithinLogging(e.getMessage());
return spottedThrowable;
}
}
/**
* Return the currently appointed Warden.
* If no warden is appointed it appoints one on the fly which immediatly reports anything.
*
* @return
*/
private static Warden currentWarden() {
Warden w = THREAD_WARDEN.get();
if (w == null) {
w = new Warden(null) {
@Override
public void disregardThrowable(final Throwable e) {
report(new IllegalStateException("disregarding is impossible without a surrounding guard (ignored)", e));
}
@Override
public <T extends Throwable> T spotThrowable(final T spottedThrowable) {
report(spottedThrowable);
return spottedThrowable;
};
};
THREAD_WARDEN.set(w);
}
return w;
}
/**
* Must always be called in a finally block after {@link #appointWarden()}.
* Restores the Warden on duty when this warden was appointed.
*
* @return List of reported Throwables during this period (which have already been reported)
*/
public List<Throwable> finish() {
if (!this.trackedThrowables.isEmpty()) {
for (Throwable t : this.trackedThrowables) {
encounter(t);
}
this.trackedThrowables.clear();
}
THREAD_WARDEN.set(this.outerWarden);
List<Throwable> reportedThrowablesCopy = this.reportedThrowables;
this.reportedThrowables = new LinkedList<Throwable>();
return reportedThrowablesCopy;
}
/**
* Reports the Throwable as unhandled.
* Derived classes may do more with it.
*
* @param t {@link Throwable} != null
*/
protected void encounter(@Nonnull final Throwable t) {
report(new UnhandledException(t));
}
/**
* Guard the execution of the {@link Runnable}.
* Reports any exceptions thrown but not handled.
* Exceptions thrown but not caught during execution (i.e. caught by this method) are only reported but not thrown
* further.
* If you want to propagate exceptions thru this construct you may use {@link TunnelException} which is forwarded.
* If you want to catch TunnelException also, then you need to wrap the Block with {@link ABlock#wrapInIgnoringBlock}.
* If you want to handle exceptions thrown by the block explicitly you could use {@link ABlock#wrapInReportingBlock} to
* handle these.
*
* @param runnable != null
* @return List of Exceptions reported (for reference only; they have already been reported).
*/
public static List<Throwable> guard(@Nonnull final Block<?> runnable) {
Warden w = appointWarden();
List<Throwable> unhandled;
try {
try {
runnable.execute();
} catch (TunnelException e) { // NOPMD special case
throw e;
} catch (Exception e) { // NOPMD generic code
Warden.spot(e);
Warden.report(e);
}
} finally {
unhandled = w.finish();
}
return unhandled;
}
/**
* Must always be called in conjunction with {@link #finish}.
* It is recommended to use {@link #guard(Block)}.
*
* @return a new Warden which remembers the current warden
*/
public static Warden appointWarden() {
Warden current = THREAD_WARDEN.get();
Warden inner = new Warden(current);
THREAD_WARDEN.set(inner);
return inner;
}
/**
* Wraps the given block so that its exceptions will be properly reported.
*
* @param block != null
* @return protected Block not throwing any exception
*/
public static Running guarded(@Nonnull final Block<?> block) {
return guarded(block, true);
}
/**
* Wraps the given block so that its exceptions will be properly reported.
*
* @param block != null
* @param strict false: only caught but unhandled exceptions will be reported exception declared by the block are
* reported; false: only
* @return protected Block not throwing any exception
*/
public static Running guarded(@Nonnull final Block<?> block, final boolean strict) {
return new GuardedRunning(block, strict);
}
/**
* Wraps the given block so that its exceptions will be reported.
*
* @param block != null
* @param uncaughtExceptionHandler to use on exceptions
* @return protected Block not throwing any exception
*/
public static Running guarded(@Nonnull final Block<?> block, final UncaughtExceptionHandler uncaughtExceptionHandler) {
return guarded(ABlock.wrapInReportingBlock(block, null, uncaughtExceptionHandler));
}
public static IllegalArgumentException illegal(final String string, final Object... args) {
return Warden.spot(new IllegalArgumentException(String.format(string, args)));
}
public static IllegalArgumentException illegal(final Throwable t, final String string, final Object... args) {
return Warden.spot(new IllegalArgumentException(String.format(string, args), t));
}
}
|
package com.tencent.mm.plugin.translate;
import android.os.Looper;
import com.tencent.mm.ab.e;
import com.tencent.mm.bt.h.d;
import com.tencent.mm.g.a.rt;
import com.tencent.mm.model.ar;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.translate.a.c;
import com.tencent.mm.plugin.translate.a.c$a;
import com.tencent.mm.plugin.translate.a.c.b;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.at;
import com.tencent.mm.sdk.platformtools.x;
import java.util.HashMap;
public final class a implements ar {
ag handler = new ag(Looper.getMainLooper());
c oEg = b.oEu;
at oEh = new at(5, "ProcessTranslatedMessage", 1, Looper.getMainLooper());
private c$a oEi = new 1(this);
private com.tencent.mm.sdk.b.c oEj = new com.tencent.mm.sdk.b.c<rt>() {
{
this.sFo = rt.class.getName().hashCode();
}
public final /* synthetic */ boolean a(com.tencent.mm.sdk.b.b bVar) {
rt rtVar = (rt) bVar;
x.d("MicroMsg.SubCoreTranslate", "recieve one translate request");
a.this.handler.post(new 1(this, rtVar));
return true;
}
};
private com.tencent.mm.sdk.b.c oEk = new 3(this);
public final HashMap<Integer, d> Ci() {
return null;
}
public final void gi(int i) {
}
public final void bn(boolean z) {
c cVar = this.oEg;
c$a c_a = this.oEi;
if (!(c_a == null || cVar.dlt.contains(c_a))) {
cVar.dlt.add(c_a);
}
com.tencent.mm.sdk.b.a.sFg.b(this.oEj);
com.tencent.mm.sdk.b.a.sFg.b(this.oEk);
}
public final void bo(boolean z) {
}
public final void onAccountRelease() {
com.tencent.mm.sdk.b.a.sFg.c(this.oEj);
com.tencent.mm.sdk.b.a.sFg.c(this.oEk);
c cVar = this.oEg;
c$a c_a = this.oEi;
if (c_a != null && cVar.dlt.contains(c_a)) {
cVar.dlt.remove(c_a);
}
c cVar2 = this.oEg;
if (cVar2.oEr != null) {
for (e eVar : cVar2.oEr) {
if (eVar != null) {
au.DF().b(631, eVar);
if (eVar.oEB != null) {
eVar.oED.SO();
au.DF().c(eVar.oEB);
}
eVar.bIS();
eVar.oEz = null;
}
}
}
cVar2.oEt.clear();
cVar2.oEs.clear();
cVar2.dlt.clear();
cVar2.htY = 0;
}
}
|
package com.upu.zenka.broadcasttest.util;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.util.Log;
import com.upu.zenka.broadcasttest.view.MyView;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* Created by ThinkPad on 2018/12/23.
*/
public class MusicUtil {
public static final String TAG="MusicUtil";
private MediaPlayer mediaPlayer;
private static MusicUtil mMusicManager;
MyView.MusicView musicView;
private String curmusicPath;
private int programIndex;
private int musicIndex;
private AudioManager audioManager;
private int volume;
public MusicUtil(AudioManager audioManager,MyView.MusicView musicView){
this.audioManager=audioManager;
this.musicView=musicView;
}
private boolean addSource(String path){
//mediaPlayer.reset();
try {
mediaPlayer.setDataSource(path);
curmusicPath=path;
}catch (IOException e){
e.printStackTrace();
return false;
}
return true;
}
public void play(int programIndex,int musicIndex,String path,int position,int volume){
File file=new File(path);
if (file==null){
musicView.playFaild("filenull");
return;
}
this.volume=volume;
this.programIndex=programIndex;
this.musicIndex=musicIndex;
mediaPlayer=new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,volume,0);
if(!addSource(path)){
musicView.playFaild("addSource");
return;
}
try{
play(position);
}catch (Exception e) {
new File(curmusicPath).delete();
musicView.playFaild("prePlay");
//musicView.completion(programIndex,musicIndex);
e.printStackTrace();
}
}
private boolean addSource(List<String> pathlist){
mediaPlayer.reset();
try {
for (int i = 0; i < pathlist.size(); i++) {
mediaPlayer.setDataSource(pathlist.get(i));
}
}catch (IOException e){
e.printStackTrace();
return false;
}
return true;
}
public void play(final int position){
Log.e(TAG,"mediaPlayer准备加载");
try {
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
try {
Log.e(TAG, "mediaPlayer加载完成,准备播放");
long ss=mediaPlayer.getDuration();
mediaPlayer.seekTo(position);
mediaPlayer.start();
musicView.play();
} catch (Exception e) {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
musicView.playFaild("PreparedListener");
}
e.printStackTrace();
}
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
musicView.completion(programIndex, musicIndex);
}
});
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
new File(curmusicPath).delete();
musicView.playFaild("error");
return true;
}
});
}catch (Exception e){
Log.e(TAG, "mediaPlayer加载异常");
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
musicView.playFaild("prepareAsync");
}
e.printStackTrace();
}
}
public void stop(){
if (mediaPlayer!=null&&mediaPlayer.isPlaying()){
mediaPlayer.stop();
musicView.stop();
mediaPlayer.release();
mediaPlayer=null;
}
}
public void pause(){
if (mediaPlayer!=null&&mediaPlayer.isPlaying()) {
mediaPlayer.pause();
musicView.pause();
}
}
public void keepup(){
if (mediaPlayer!=null){
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,volume,0);
mediaPlayer.start();
musicView.keepup();
}
}
public void release()
{
Log.e(TAG,"准备release mediaPlayer");
if (mediaPlayer!=null){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
musicView.playFaild("release");
}
}
}
|
package org.megaphone.rest;
import org.megaphone.util.walkers.AudiobookDirectoryWalker;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.io.File;
import java.util.ArrayList;
@RequestScoped
@Path("/directories")
public class DirectoryResource {
private final String location = "v:\\Ready";
@GET()
@Produces("application/json")
public ArrayList<File> getAllDirectories() {
ArrayList directories = new ArrayList();
AudiobookDirectoryWalker walker = new AudiobookDirectoryWalker();
try {
directories = walker.getDirectories(new File(location));
} catch (Exception e) {
e.printStackTrace();
}
return directories;
}
@GET
@Produces("application/json")
@Path("mp3")
public String getMP3() {
return "Hi from mp3";
}
}
|
package com.ese.cloud.client.controller.core;
import com.alibaba.fastjson.JSON;
import com.ese.cloud.client.entity.MetricsInfo;
import com.ese.cloud.client.util.ReturnData;
import org.apache.log4j.Logger;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
/**
* Created by wangchengcheng on 2017/11/6.
*/
@Controller
@RequestMapping("monitor")
public class MonitorController {
Logger logger = Logger.getLogger(MonitorController.class);
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "monitor/index";
}
/**
* 获取电子人实时肌电信号
*/
@RequestMapping(value = "/getCyborgEMG", method = RequestMethod.POST)
@ResponseBody
public String getCyborgEMG() {
final class EMGInfo {
long timestamp;
double value;
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
try {
List<EMGInfo> emgInfos = new ArrayList<>();
long timestamp = new Date().getTime();
for(int i = 0; i < 120; i++) {
double fakeEMG = Math.random() * 70;
EMGInfo emgInfo = new EMGInfo();
emgInfo.setTimestamp(timestamp);
emgInfo.setValue(fakeEMG);
emgInfos.add(emgInfo);
timestamp += 500;
}
return ReturnData.result(0, "获取申请统计数据成功", JSON.toJSONString(emgInfos));
} catch (Exception e) {
logger.error("获取申请统计数据失败:", e);
return ReturnData.result(-1, "获取申请统计数据失败", null);
}
}
}
|
package command;
import exceptions.IncorrectArgumentException;
import utility.Console;
import utility.Invoker;
import utility.Receiver;
import java.net.SocketAddress;
import java.nio.channels.DatagramChannel;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class CountLessThanStartDate extends CommandAbstract {
private final Receiver receiver;
public CountLessThanStartDate(DatagramChannel datagramChannel, SocketAddress socketAddress, Console console, Invoker invoker) {
super("Show amount of elements with field \"StartDate\" which is lower than indicated one");
this.receiver = new Receiver(datagramChannel, socketAddress, console, invoker);
}
@Override
public void exe(String arg) throws IncorrectArgumentException {
if (arg.length() == 0){
throw new IncorrectArgumentException("Command needs argument");
}else {
ZonedDateTime tempTime = null;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.uuuu H:mm:ss z");
try {
tempTime = ZonedDateTime.parse(arg, formatter);
} catch (DateTimeParseException exception) {
throw new IncorrectArgumentException("Incorrect argument. Follow format dd.mm.yyyy hh:mm:ss +/-hh:mm");
}
receiver.countLessThanStartDate(arg);
}
}
}
|
package algorithm.kakaoBlindTest._2018;
import java.util.*;
/*
* 1:30 시작 2:20 끝 50분소요
* 수학공식이 필요할땐 Math 클래스 라이브러리 쓰기
* 잘한 것 : 손으로 먼저 써보고 실행에 옮김. 하지만 이전에 풀어본 기억이 나서 빨리 푼 듯 싶음
* 고쳐야할 것 :
* 1. 손으로 써보고 코딩을 시작하긴했지만 완전히 쓰지않고 중간에 바로 코딩해서 마지막에 디버깅해야하는 일이 생김
* 2. 스택이어서 배열의 끝부터 push해야할때 for문이 배열의 끝부터 돌아야하는 것에 필요한 조건을 잘못쓰는 어이없는 실수는 하지 말자
*/
public class kakao_blind_2018_2 {
static int solution(String dartResult) {
int answer = 0;
char[] dR = dartResult.toCharArray();
int dSize = dR.length;
// num 리스트에 숫자 담기
ArrayList<Integer> numL = new ArrayList<>();
for (int i = 0; i < dSize; i++) {
if (dR[i] == 49 && dR[i + 1] == 48) {
numL.add(10);
i++;
} else if (dR[i] >= 48 && dR[i] <= 57) {
numL.add(Integer.parseInt(Character.toString(dR[i])));
}
}
System.out.println(numL);
// 스택초기화
Stack<Character> ds = new Stack<>();
for (int i = dSize - 1; i >= 0; i--) {
ds.push(dR[i]);
}
System.out.println(ds);
// * 42, # 35, 숫자48~57
int position = 0;
while (!ds.isEmpty()) {
char pop = ds.pop();
if (pop >= 48 && pop <= 57) {
continue;
}
if (pop == 'S') {
position++;
continue;
} else if (pop == 'D') {
numL.set(position, numL.get(position) * numL.get(position));
position++;
continue;
} else if (pop == 'T') {
numL.set(position, numL.get(position) * numL.get(position) * numL.get(position));
position++;
continue;
} else if (pop == '*') {
position--;
if (position == 0)
numL.set(position, numL.get(position) * 2);
else {
numL.set(position, numL.get(position) * 2);
numL.set(position - 1, numL.get(position - 1) * 2);
}
position++;
continue;
} else if (pop == '#') {
position--;
numL.set(position, numL.get(position) * -1);
position++;
continue;
}
}
for (int n : numL) {
answer += n;
}
return answer;
}
public static void main(String[] args) {
String dartResult = "1D2S3T*";
System.out.println(solution(dartResult));
}
}
|
import java.awt.*;
import java.awt.geom.Line2D;
import java.util.*;
import java.io.*;
public class EuropeanTrip {
public static void main(String[] args) throws IOException {
Scanner nya = new Scanner(System.in);
Point.Double a = new Point.Double(nya.nextDouble(),nya.nextDouble());
Point.Double b = new Point.Double(nya.nextDouble(),nya.nextDouble());
Point.Double c = new Point.Double(nya.nextDouble(),nya.nextDouble());
double c_ = a.distance(b);
double a_ = b.distance(c);
double b_ = c.distance(a);
double x = (a_*a.getX() + b_*b.getX() + c_*c.getX())/(a_+b_+c_);
double y = (a_*a.getY() + b_*b.getY() + c_*c.getY())/(a_+b_+c_);
Point.Double current = new Point.Double(x,y);
double test_dist = 2000;
double accuracy = .00000000001;
double min_dist = current.distance(a) + current.distance(b) +current.distance(c);
while(test_dist > accuracy){
boolean not_found = true;
Point.Double[] temp = new Point.Double[4];
temp[0] = new Point.Double(current.getX() + test_dist , current.getY());
temp[1] = new Point.Double(current.getX() - test_dist , current.getY());
temp[2] = new Point.Double(current.getX() , current.getY() + test_dist);
temp[3] = new Point.Double(current.getX() , current.getY() - test_dist);
for (int i = 0; i < 4; i++) {
double temp_dist = temp[i].distance(a) + temp[i].distance(b) + temp[i].distance(c);
if(temp_dist < min_dist) {
min_dist = temp_dist;
current = temp[i];
not_found = false;
break;
}
}
if(not_found)
test_dist /= 2;
}
System.out.printf("%f %f", current.getX(), current.getY());
}
}
|
package com.simpson.kisen.fanBoard.model.vo;
import java.sql.Date;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FbComment {
private int commentNo;
private int commentLevel;
private String writer;
private String content;
private int fbNo;
private int commentRef;
private Date regDate;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.