repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
SPACEDAC7/TrabajoFinalGrado
uploads/34f7f021ecaf167f6e9669e45c4483ec/java_source/com/buzzfeed/toolkit/content/AuthorContent.java
211
/* * Decompiled with CFR 0_115. */ package com.buzzfeed.toolkit.content; public interface AuthorContent { public String getAvatar(); public String getDisplayName(); public String getTitle(); }
gpl-3.0
haozhi-ly/haozhi
newhaozhiwang/src/main/java/com/haozhi/service/impl/CourseAssessServiceImpl.java
1527
package com.haozhi.service.impl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.haozhi.entity.CourseAssess; import com.haozhi.mapper.CourseAssessMapper; import com.haozhi.service.CourseAssessService; @Service("courseAssessService") public class CourseAssessServiceImpl implements CourseAssessService { @Autowired private CourseAssessMapper courseAssessMapper; @Override public List<CourseAssess> getAssessbypageDescTime(Map<String, Object> hashmap) { return courseAssessMapper.getAssessbypageDescTime(hashmap); } @Override public List<CourseAssess> CMcountbycourseid(String courseid) { return courseAssessMapper.CMcountbycourseid(Integer.parseInt(courseid)); } @Override public List<CourseAssess> getAssesstopfour(int courseid) { return courseAssessMapper.getAssesstopfour(courseid); } public List<CourseAssess> getAssessByCmidByPage(Map<String,Object> hashmap) { return courseAssessMapper.getAssessByCmidByPage(hashmap); } @Override public List<CourseAssess> getAssessCountByCmid(Integer cmid) { return courseAssessMapper.getAssessCountByCmid(cmid); } @Override public int addAssess(Integer userid, Integer cmid, String content) { return courseAssessMapper.addAssess(userid, cmid, content); } @Override public int delcourseAssess(Integer csid) { return courseAssessMapper.delcourseAssess(csid); } }
gpl-3.0
pearisgreen/JavaServerClient
src/com/pearisgreen/server/Server.java
3011
package com.pearisgreen.server; import java.io.IOException; import java.io.Serializable; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class Server implements Runnable, Serializable { private int port; private String ipAdress; private Thread thread; private boolean listening = false; private ServerSocket serverSocket; private HashMap<Long, SClient> clients = new HashMap<Long, SClient>(); public Server(int port) { this.port = port; try { this.serverSocket = new ServerSocket(port); } catch (IOException e) { System.out.println("couldnt host server on port: " + port); e.printStackTrace(); } } public void startListening() { System.out.println("starting to listen on port: " + port); thread = new Thread(this); thread.start(); } @Override public void run() { listening = true; long clientCount = 0; while(listening) { ClientGroup clientGroup = new ClientGroup(); SClient client = new SClient(this,clientGroup, clientCount); clientGroup.addClient(client); if(client.bindClient()) { System.out.println("client connected"); client.start(); clients.put(clientCount, client); clientCount++; } } } private void stop() { listening = false; for(Map.Entry<Long, SClient> entry : clients.entrySet()) { entry.getValue().stop(); } try { thread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addClients(long acceptor, long donor) { clients.get(acceptor).getClientGroup().addClient(clients.get(donor)); } public void removeClient(long id) { clients.get(id).stop(); clients.remove(id); } public Socket acceptClientSocket() { try { return serverSocket.accept(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public ArrayList<SClient> getClients(SClient.State state) { ArrayList<SClient> tempArrayList = new ArrayList<SClient>(); for(Map.Entry<Long, SClient> entry : clients.entrySet()) { if(entry.getValue().getState() == state) tempArrayList.add(entry.getValue()); } return tempArrayList; } public String getClientsString(SClient.State state) { String tempStr = ""; ArrayList<SClient> tempArrayList = getClients(state); for(SClient cl : tempArrayList) { tempStr = tempStr + cl.getName() + " - "; } return tempStr; } public void connectWithRandom(SClient cl) { for(Map.Entry<Long, SClient> entry : clients.entrySet()) { if(entry.getValue().getState() == SClient.State.LFM && entry.getValue() != cl) { entry.getValue().getClientGroup().addClient(cl); } } } }
gpl-3.0
avasquez614/commons
utilities/src/main/java/org/craftercms/commons/i10n/AbstractI10nRuntimeException.java
1896
/* * Copyright (C) 2007-2019 Crafter Software Corporation. All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.craftercms.commons.i10n; import java.util.ResourceBundle; import org.apache.commons.lang3.StringUtils; /** * Root runtime exception for any {@link Exception} that wants to be localized. * * @author avasquez */ public abstract class AbstractI10nRuntimeException extends RuntimeException { private static final long serialVersionUID = -2438526910810755060L; protected String key; protected Object[] args; public AbstractI10nRuntimeException() { } public AbstractI10nRuntimeException(String key, Object... args) { this.key = key; this.args = args; } public AbstractI10nRuntimeException(String key, Throwable cause, Object... args) { super(cause); this.key = key; this.args = args; } public AbstractI10nRuntimeException(Throwable cause) { super(cause); } @Override public String getMessage() { if (StringUtils.isNotEmpty(key)) { return I10nUtils.getLocalizedMessage(getResourceBundle(), key, args); } else { return null; } } protected abstract ResourceBundle getResourceBundle(); }
gpl-3.0
trejkaz/haqua
demo/src/org/trypticon/haqua/demo/problems/ComboBoxPaintingTest.java
2311
/* * Haqua - a collection of hacks to work around issues in the Aqua look and feel * Copyright (C) 2014 Trejkaz, Haqua Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.trypticon.haqua.demo.problems; import javax.swing.*; import java.awt.*; public class ComboBoxPaintingTest implements Runnable { public static void main(String[] args) { SwingUtilities.invokeLater(new ComboBoxPaintingTest()); } @Override public void run() { JLabel textFieldLabel = new JLabel("Text field:"); JTextField textField = new JTextField(8); JLabel editableLabel = new JLabel("Editable:"); // Notice that the button positioning is incorrect and that the highlighting does // not go all the way around the combo box. JComboBox<String> editableComboBox = new JComboBox<>(new String[] { "Item 1", "Item 2", "Item 3" }); editableComboBox.setEditable(true); JLabel nonEditableLabel = new JLabel("Non-editable:"); JComboBox<String> nonEditableComboBox = new JComboBox<>(new String[] { "Item 1", "Item 2", "Item 3" }); FlowLayout layout = new FlowLayout(FlowLayout.LEADING); layout.setAlignOnBaseline(true); JPanel panel = new JPanel(layout); panel.add(textFieldLabel); panel.add(textField); panel.add(editableLabel); panel.add(editableComboBox); panel.add(nonEditableLabel); panel.add(nonEditableComboBox); JFrame frame = new JFrame(); frame.setContentPane(panel); frame.pack(); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); } }
gpl-3.0
jmalmellones/alfred
src/test/java/me/eightball/alfred/TelegramTest.java
1741
package me.eightball.alfred; import java.util.List; import java.util.function.Consumer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.BeforeClass; import org.junit.Test; import me.eightball.exceptions.ConfigurationException; import me.eightball.telegram.TelegramApi; import me.eightball.telegram.beans.Update; import me.eightball.telegram.exceptions.TelegramException; import me.eightball.telegram.params.GetUpdatesParams; import me.eightball.telegram.params.SendMessageParams; public class TelegramTest { private static Logger logger; private static TelegramApi telegramApi; private static ConfigurationService configService; @BeforeClass public static void beforeClass() throws TelegramException, ConfigurationException { logger = LogManager.getLogger(TelegramTest.class); telegramApi = TelegramApi.getInstance(); configService = ConfigurationService.getInstance(); } @Test public void testSendMessage() throws Exception { for (int x = 1; x <= 2; x++) { SendMessageParams params = new SendMessageParams(); params.setChat_id(configService.getTelegramChatId()); params.setText("hola " + x); logger.info(String.format("%s", telegramApi.sendMessage(params))); } } @Test public void testGetUpdates() throws Exception { GetUpdatesParams gup = new GetUpdatesParams(); gup.setTimeout(5); // 5 segundos logger.debug("buscando updates"); List<Update> updates = telegramApi.getUpdates(gup); updates.forEach(new Consumer<Update>() { @Override public void accept(Update update) { System.out.println(update); } }); } @Test public void testGetMe() throws Exception { logger.info(telegramApi.getMe().toString()); } }
gpl-3.0
tinyivc/java-demo
src/test/java/com/tinyivc/lib/img4java/TestMagick.java
1839
package com.tinyivc.lib.img4java; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import org.im4java.core.ConvertCmd; import org.im4java.core.IMOperation; import org.im4java.process.Pipe; import org.junit.Test; /** * Created by tinyivc on 16/12/21. */ public class TestMagick { // create command private static final ConvertCmd CONVERT_CMD = new ConvertCmd(true); /** * 根据poi头图URL生成中部banner字节数组 */ @Test public void resize() throws Exception { // create the operation, add images and operators/options IMOperation op = new IMOperation(); op.addImage("/Users/tinyivc/t/poi.jpg"); op.resize(508, 380); op.addImage("/Users/tinyivc/t/poi_larger.jpg"); // execute the operation CONVERT_CMD.run(op); } /** * 根据poi头图URL生成中部banner字节数组 */ @Test public void pip() throws Exception { // create the operation, add images and operators/options IMOperation op = new IMOperation(); op.addImage("-"); op.addImage("jpg:-"); InputStream inputStream = new URL("http://p0.meituan.net/xianfu/wm_bg_image.jpg").openStream(); Pipe pipeIn = new Pipe(inputStream, null); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Pipe pipeOut = new Pipe(null, outputStream); ConvertCmd convert = new ConvertCmd(); convert.setInputProvider(pipeIn); convert.setOutputConsumer(pipeOut); convert.run(op); inputStream.close(); byte[] imageBytes = outputStream.toByteArray(); outputStream.close(); Files.write(Paths.get("/Users/tinyivc/t/111.jpg"), imageBytes); } }
gpl-3.0
Zerrens/Chain-Reaction
src/main/java/com/zerren/chainreaction/block/BlockCR.java
9093
package com.zerren.chainreaction.block; import buildcraft.api.tools.IToolWrench; import chainreaction.api.block.IInventoryCR; import chainreaction.api.item.IScanner; import com.zerren.chainreaction.ChainReaction; import com.zerren.chainreaction.tile.TEHeatHandlerBase; import com.zerren.chainreaction.tile.TEMultiBlockBase; import com.zerren.chainreaction.tile.TileEntityCRBase; import com.zerren.chainreaction.reference.Reference; import com.zerren.chainreaction.tile.plumbing.TEHeatExchanger; import com.zerren.chainreaction.utility.CoreUtility; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import java.util.List; import java.util.Random; /** * Created by Zerren on 2/19/2015. */ public class BlockCR extends Block { @SideOnly(Side.CLIENT) protected IIcon[] icon; protected String[] subtypes; protected String folder; public BlockCR(String name, String[] subtypes, Material material, float hardness, float resistance, Block.SoundType sound, String folder) { super(material); this.setBlockName(name); this.subtypes = subtypes; this.setHardness(hardness); this.setResistance(resistance); this.setStepSound(sound); this.folder = folder; } public BlockCR(String name, String[] subtypes, Material material, float hardness, float resistance, Block.SoundType sound, String folder, CreativeTabs tab) { this(name, subtypes, material, hardness, resistance, sound, folder); this.setCreativeTab(tab); } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int meta, float sideX, float sideY, float sideZ) { ItemStack held = player.getHeldItem(); if (held != null && held.getItem() instanceof IToolWrench) { IToolWrench wrench = (IToolWrench)held.getItem(); if (wrench.canWrench(player, x, y, z)) { TileEntity tile = CoreUtility.getTileEntity(world, x, y, z); if (tile != null && tile instanceof TileEntityCRBase) { if (tile instanceof TEMultiBlockBase && ((TEMultiBlockBase) tile).hasValidMaster()) return false; //cant face up or down and the clicked face was one of those return false if (!((TileEntityCRBase) tile).canFaceUpDown() && (CoreUtility.getClickedFaceDirection(sideX, sideY, sideZ) == ForgeDirection.UP || CoreUtility.getClickedFaceDirection(sideX, sideY, sideZ) == ForgeDirection.DOWN)) { return false; } if (player.isSneaking()) ((TileEntityCRBase) tile).setOrientation(CoreUtility.getClickedFaceDirection(sideX, sideY, sideZ).getOpposite()); else ((TileEntityCRBase) tile).setOrientation(CoreUtility.getClickedFaceDirection(sideX, sideY, sideZ)); wrench.wrenchUsed(player, x, y, z); return true; } } } return false; } @Override public Item getItemDropped(int meta, Random random, int p2) { switch (meta) { default: return Item.getItemFromBlock(this); } } @Override public int damageDropped(int meta) { return meta; } @Override public String getUnlocalizedName() { return String.format("tile.%s%s", Reference.ModInfo.CR_RESOURCE_PREFIX, unwrapName(super.getUnlocalizedName())); } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister iconRegister) { this.icon = new IIcon[subtypes.length]; for (int i = 0; i < subtypes.length; i++) { icon[i] = iconRegister.registerIcon(Reference.ModInfo.CR_RESOURCE_PREFIX + folder + subtypes[i]); } } protected String unwrapName(String unlocalizedName) { return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1); } @Override @SideOnly(Side.CLIENT) public void getSubBlocks(Item item, CreativeTabs creativeTabs, List list) { for (int meta = 0; meta < subtypes.length; meta++) { list.add(new ItemStack(item, 1, meta)); } } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int metaData) { metaData = MathHelper.clamp_int(metaData, 0, subtypes.length - 1); return icon[metaData]; } @Override public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entity, ItemStack itemStack) { if (world.getTileEntity(x, y, z) instanceof TileEntityCRBase) { TileEntityCRBase tile = (TileEntityCRBase)world.getTileEntity(x, y, z); if (itemStack.hasDisplayName()) { tile.setCustomName(itemStack.getDisplayName()); } tile.setOrientation(CoreUtility.getLookingDirection(entity, tile.canFaceUpDown()).getOpposite()); tile.setOwnerUUID(entity.getPersistentID()); } } @Override public void breakBlock(World world, int x, int y, int z, Block block, int meta) { TileEntityCRBase tile = CoreUtility.get(world, x, y, z, TileEntityCRBase.class); if (tile != null && tile instanceof TEMultiBlockBase && (((TEMultiBlockBase)tile).hasValidMaster() || ((TEMultiBlockBase)tile).isMaster())) { if (((TEMultiBlockBase) tile).getCommandingController() instanceof IInventoryCR) { dropInventoryProxy(world, x, y, z, ((IInventoryCR)((TEMultiBlockBase) tile).getCommandingController())); } ((TEMultiBlockBase)tile).getCommandingController().invalidateMultiblock(); } dropInventory(world, x, y, z); super.breakBlock(world, x, y, z, block, meta); } protected void dropInventoryProxy(World world, int x, int y, int z, IInventoryCR inv) { for (int i = 0; i < inv.getSizeInventory(); i++) { ItemStack itemStack = inv.getStackInSlot(i); if (itemStack != null && itemStack.stackSize > 0) { Random rand = new Random(); float dX = rand.nextFloat() * 0.8F + 0.1F; float dY = rand.nextFloat() * 0.8F + 0.1F; float dZ = rand.nextFloat() * 0.8F + 0.1F; EntityItem entityItem = new EntityItem(world, x + dX, y + dY, z + dZ, itemStack.copy()); if (itemStack.hasTagCompound()) { entityItem.getEntityItem().setTagCompound((NBTTagCompound) itemStack.getTagCompound().copy()); } float factor = 0.05F; entityItem.motionX = rand.nextGaussian() * factor; entityItem.motionY = rand.nextGaussian() * factor + 0.2F; entityItem.motionZ = rand.nextGaussian() * factor; world.spawnEntityInWorld(entityItem); itemStack.stackSize = 0; } } inv.clearInventory(); } protected void dropInventory(World world, int x, int y, int z) { TileEntity tileEntity = world.getTileEntity(x, y, z); if (!(tileEntity instanceof IInventory)) { return; } IInventory inventory = (IInventory) tileEntity; for (int i = 0; i < inventory.getSizeInventory(); i++) { ItemStack itemStack = inventory.getStackInSlot(i); if (itemStack != null && itemStack.stackSize > 0) { Random rand = new Random(); float dX = rand.nextFloat() * 0.8F + 0.1F; float dY = rand.nextFloat() * 0.8F + 0.1F; float dZ = rand.nextFloat() * 0.8F + 0.1F; EntityItem entityItem = new EntityItem(world, x + dX, y + dY, z + dZ, itemStack.copy()); if (itemStack.hasTagCompound()) { entityItem.getEntityItem().setTagCompound((NBTTagCompound) itemStack.getTagCompound().copy()); } float factor = 0.05F; entityItem.motionX = rand.nextGaussian() * factor; entityItem.motionY = rand.nextGaussian() * factor + 0.2F; entityItem.motionZ = rand.nextGaussian() * factor; world.spawnEntityInWorld(entityItem); itemStack.stackSize = 0; } } } }
gpl-3.0
ATG-PoliMi/Sharon
src/it/polimi/deib/atg/sharon/configs/NeedsDrift.java
6483
/* * * SHARON - Human Activities Simulator * Author: ATG Group (http://atg.deib.polimi.it/) * * Copyright (C) 2015, Politecnico di Milano * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package it.polimi.deib.atg.sharon.configs; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.nio.file.NotDirectoryException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; /** * This class represents a drift in the value of a needs growth rate, so every instance of this class represent a specific drift. * <p> * It has 4 members: * <ul> * <li> The id of the need. * <li> The mode of the drift. * <li> The time when the drift appears. * <li> The new value of the need growth rate. * </ul> * All those members can be reached and modified with those methods: @see {@link NeedsDrift#getId()}, @see {@link NeedsDrift#setId()}, * @see {@link NeedsDrift#getMode()}, @see {@link NeedsDrift#setMode(ModeOfDrift)}, @see {@link NeedsDrift#getNewValue()}, * @see {@link NeedsDrift#setNewValue(double)}, @see {@link NeedsDrift#getTime()} and @see {@link NeedsDrift#setTime(long)}. * <p> * The drifts of the needs are loaded for config files with the method @see {@link NeedsDrift#loadNeedDrift()} in the class @see Main and stored in the singolet * class @see Parameters, for the next elaboration. * <p> * @author alessandro */ public class NeedsDrift { public enum ModeOfDrift { STEP }; private int id = 0; private ModeOfDrift mode = ModeOfDrift.valueOf("STEP"); private long time; private double newValue; /** * This constructor is called in method @see {@link NeedsDrift#loadNeedDrift()}. * @param id The id of the need to drift, is represent as an integer. * @param mode The mode in which the drift has to be applied, is represent as an enumerative type(that has the implementation only for the mode "STEP"). * @param time The time of the simulation when the drift has to appear, is represent as a long. * @param newValue The new value of the needs growth rate, is represent as a double. */ public NeedsDrift(int id, ModeOfDrift mode,long time, double newValue){ super(); this.id= id; this.mode= mode; this.time= time; this.newValue= newValue; } /** * Loads the drifts of needs from the configuration files. It would ignore template files. * @return An ArrayList of instances of NeedsDrift * @throws NotDirectoryException If the folder "config" doesn't exist */ public static synchronized ArrayList<NeedsDrift> loadNeedDrift() throws NotDirectoryException{ File folder = new File("config"); if(!folder.exists()){ throw new NotDirectoryException(null); } ArrayList<NeedsDrift> DriftInstances = new ArrayList<NeedsDrift>(); ArrayList<Integer> IdNeed = new ArrayList<Integer>(); ArrayList<ModeOfDrift> Mode = new ArrayList<ModeOfDrift>(); ArrayList<Long> Time = new ArrayList<Long>(); ArrayList<Double> NewValue = new ArrayList<Double>(); BufferedReader reader = null; ArrayList<String> distribution = new ArrayList <String>(); FilenameFilter NeedDriftFilter = new FilenameFilter(){ @Override public boolean accept(File dir, String name) { if(name.equals("need.drift")){ return true; } return false; } }; try{ ArrayList<File> fileList = new ArrayList<File>(Arrays.asList(folder.listFiles(NeedDriftFilter))); reader = new BufferedReader(new FileReader(fileList.get(0))); String line = null; while ((line = reader.readLine()) != null) { distribution.add(line); } }catch(NullPointerException e){ e.printStackTrace(); }catch (Exception e) {e.printStackTrace();} finally { try {reader.close();} catch (IOException e) {e.printStackTrace();} } Iterator<String> itr = distribution.iterator(); while(itr.hasNext()){ String[] need = itr.next().split(","); if(Arrays.asList(need).size() == 4){ IdNeed.add(Integer.parseInt(need[0])); Mode.add(ModeOfDrift.valueOf(need[1])); Time.add(Long.parseLong(need[2])); NewValue.add(Double.parseDouble(need[3])); } else{ //throw new } } Integer[] id = IdNeed.toArray(new Integer[IdNeed.size()]); ModeOfDrift[] mode = Mode.toArray(new ModeOfDrift[Mode.size()]); Long[] time = Time.toArray(new Long[Time.size()]); Double[] newValue = NewValue.toArray(new Double[NewValue.size()]); for(int i = 0; i < id.length; i++){ int tempId = id[i]; long tempTime = time[i]; double tempValue = newValue[i]; DriftInstances.add(new NeedsDrift(tempId, mode[i], tempTime, tempValue)); } return DriftInstances; } /** * Returns @see {@link #id} * @return the id of the need of the specified drift. */ public int getId() { return id; } /** * Set @see {@link #id} to a new value. * @param id the new value of id */ public void setId(int id) { this.id = id; } /** * Returns @see {@link #mode}. * @return the mode of the specified drift */ public ModeOfDrift getMode() { return mode; } /** * Sets the @see {@link #mode} to a new value. * @param mode the new value of mode. */ public void setMode(ModeOfDrift mode) { this.mode = mode; } /** * Returns @see {@link #time} * @return the time of the specified drift */ public long getTime() { return time; } /** * Sets @see {@link #time} to a new value * @param time the new value of time */ public void setTime(long time) { this.time = time; } /** * Returns @see {@link #newValue} * @return the new value of the grown rate of the specified drift */ public double getNewValue() { return newValue; } /** * Sets @see {@link #newValue} to a new value. * @param newValue the new value of the grown rate. */ public void setNewValue(double newValue) { this.newValue = newValue; } }
gpl-3.0
Mazdallier/Applied-Energistics-2
src/main/java/appeng/client/render/blocks/RenderBlockController.java
4743
package appeng.client.render.blocks; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; import appeng.block.AEBaseBlock; import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; import appeng.tile.networking.TileController; public class RenderBlockController extends BaseBlockRender { public RenderBlockController() { super( false, 20 ); } @Override public boolean renderInWorld(AEBaseBlock blk, IBlockAccess world, int x, int y, int z, RenderBlocks renderer) { boolean xx = getTileEntity( world, x - 1, y, z ) instanceof TileController && getTileEntity( world, x + 1, y, z ) instanceof TileController; boolean yy = getTileEntity( world, x, y - 1, z ) instanceof TileController && getTileEntity( world, x, y + 1, z ) instanceof TileController; boolean zz = getTileEntity( world, x, y, z - 1 ) instanceof TileController && getTileEntity( world, x, y, z + 1 ) instanceof TileController; int meta = world.getBlockMetadata( x, y, z ); boolean hasPower = meta > 0; boolean isConflict = meta == 2; ExtraBlockTextures lights = null; if ( xx && !yy && !zz ) { if ( hasPower ) { blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumnPowered.getIcon() ); if ( isConflict ) lights = ExtraBlockTextures.BlockControllerColumnConflict; else lights = ExtraBlockTextures.BlockControllerColumnLights; } else blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumn.getIcon() ); renderer.uvRotateEast = 1; renderer.uvRotateWest = 1; renderer.uvRotateTop = 1; renderer.uvRotateBottom = 1; } else if ( !xx && yy && !zz ) { if ( hasPower ) { blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumnPowered.getIcon() ); if ( isConflict ) lights = ExtraBlockTextures.BlockControllerColumnConflict; else lights = ExtraBlockTextures.BlockControllerColumnLights; } else blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumn.getIcon() ); renderer.uvRotateEast = 0; renderer.uvRotateNorth = 0; } else if ( !xx && !yy && zz ) { if ( hasPower ) { blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumnPowered.getIcon() ); if ( isConflict ) lights = ExtraBlockTextures.BlockControllerColumnConflict; else lights = ExtraBlockTextures.BlockControllerColumnLights; } else blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumn.getIcon() ); renderer.uvRotateNorth = 1; renderer.uvRotateSouth = 1; renderer.uvRotateTop = 0; } else if ( (xx ? 1 : 0) + (yy ? 1 : 0) + (zz ? 1 : 0) >= 2 ) { int v = (Math.abs( x ) + Math.abs( y ) + Math.abs( z )) % 2; renderer.uvRotateEast = renderer.uvRotateBottom = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; if ( v == 0 ) blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerInsideA.getIcon() ); else blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerInsideB.getIcon() ); } else { if ( hasPower ) { blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerPowered.getIcon() ); if ( isConflict ) lights = ExtraBlockTextures.BlockControllerConflict; else lights = ExtraBlockTextures.BlockControllerLights; } else blk.getRendererInstance().setTemporaryRenderIcon( null ); } boolean out = renderer.renderStandardBlock( blk, x, y, z ); if ( lights != null ) { Tessellator.instance.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); Tessellator.instance.setBrightness( 14 << 20 | 14 << 4 ); renderer.renderFaceXNeg( blk, x, y, z, lights.getIcon() ); renderer.renderFaceXPos( blk, x, y, z, lights.getIcon() ); renderer.renderFaceYNeg( blk, x, y, z, lights.getIcon() ); renderer.renderFaceYPos( blk, x, y, z, lights.getIcon() ); renderer.renderFaceZNeg( blk, x, y, z, lights.getIcon() ); renderer.renderFaceZPos( blk, x, y, z, lights.getIcon() ); } blk.getRendererInstance().setTemporaryRenderIcon( null ); renderer.uvRotateEast = renderer.uvRotateBottom = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; return out; } private TileEntity getTileEntity(IBlockAccess world, int x, int y, int z) { if ( y >= 0 ) return world.getTileEntity( x, y, z ); return null; } }
gpl-3.0
SCI2SUGR/KEEL
src/keel/Algorithms/Fuzzy_Rule_Learning/Genetic/Thrift/Difuso.java
1767
/*********************************************************************** This file is part of KEEL-software, the Data Mining tool for regression, classification, clustering, pattern mining and so on. Copyright (C) 2004-2010 F. Herrera (herrera@decsai.ugr.es) L. Sánchez (luciano@uniovi.es) J. Alcalá-Fdez (jalcala@decsai.ugr.es) S. García (sglopez@ujaen.es) A. Fernández (alberto.fernandez@ujaen.es) J. Luengo (julianlm@decsai.ugr.es) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ **********************************************************************/ package keel.Algorithms.Fuzzy_Rule_Learning.Genetic.Thrift; class Difuso { /* This class allows trapezium or triangular-shaped fuzzy set */ public double x0, x1 ,x2 ,x3, y; public String Nombre, Etiqueta; public Difuso copia(){ Difuso copy = new Difuso(); copy.x0 = this.x0; copy.x1 = this.x1; copy.x2 = this.x2; copy.x3 = this.x3; copy.y = this.y; copy.Nombre = this.Nombre; copy.Etiqueta = this.Etiqueta; return copy; } }
gpl-3.0
routeKIT/routeKIT
src/routeKIT.java
241
import edu.kit.pse.ws2013.routekit.controllers.MainController; /** * Shortcut to allow the shorter command line {@code java routeKIT}. */ public class routeKIT { public static void main(String[] args) { MainController.main(args); } }
gpl-3.0
ggonzales/ksl
src/com/liferay/portlet/admin/ejb/AdminConfigUtil.java
10246
/** * Copyright (c) 2000-2005 Liferay, LLC. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.liferay.portlet.admin.ejb; import com.dotmarketing.util.Logger; import com.liferay.portal.model.ModelListener; import com.liferay.portal.util.PropsUtil; import com.liferay.util.GetterUtil; import com.liferay.util.InstancePool; import com.liferay.util.Validator; /** * <a href="AdminConfigUtil.java.html"><b><i>View Source</i></b></a> * * @author Brian Wing Shun Chan * @version $Revision: 1.81 $ * */ public class AdminConfigUtil { public static String PERSISTENCE = GetterUtil.get(PropsUtil.get( "value.object.persistence.com.liferay.portlet.admin.model.AdminConfig"), "com.liferay.portlet.admin.ejb.AdminConfigPersistence"); public static String LISTENER = GetterUtil.getString(PropsUtil.get( "value.object.listener.com.liferay.portlet.admin.model.AdminConfig")); protected static com.liferay.portlet.admin.model.AdminConfig create( java.lang.String configId) { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.create(configId); } protected static com.liferay.portlet.admin.model.AdminConfig remove( java.lang.String configId) throws com.liferay.portlet.admin.NoSuchConfigException, com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); ModelListener listener = null; if (Validator.isNotNull(LISTENER)) { try { listener = (ModelListener)Class.forName(LISTENER).newInstance(); } catch (Exception e) { Logger.error(AdminConfigUtil.class,e.getMessage(),e); } } if (listener != null) { listener.onBeforeRemove(findByPrimaryKey(configId)); } com.liferay.portlet.admin.model.AdminConfig adminConfig = persistence.remove(configId); if (listener != null) { listener.onAfterRemove(adminConfig); } return adminConfig; } protected static com.liferay.portlet.admin.model.AdminConfig update( com.liferay.portlet.admin.model.AdminConfig adminConfig) throws com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); ModelListener listener = null; if (Validator.isNotNull(LISTENER)) { try { listener = (ModelListener)Class.forName(LISTENER).newInstance(); } catch (Exception e) { Logger.error(AdminConfigUtil.class,e.getMessage(),e); } } boolean isNew = adminConfig.isNew(); if (listener != null) { if (isNew) { listener.onBeforeCreate(adminConfig); } else { listener.onBeforeUpdate(adminConfig); } } adminConfig = persistence.update(adminConfig); if (listener != null) { if (isNew) { listener.onAfterCreate(adminConfig); } else { listener.onAfterUpdate(adminConfig); } } return adminConfig; } protected static com.liferay.portlet.admin.model.AdminConfig findByPrimaryKey( java.lang.String configId) throws com.liferay.portlet.admin.NoSuchConfigException, com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.findByPrimaryKey(configId); } protected static java.util.List findByCompanyId(java.lang.String companyId) throws com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.findByCompanyId(companyId); } protected static java.util.List findByCompanyId( java.lang.String companyId, int begin, int end) throws com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.findByCompanyId(companyId, begin, end); } protected static java.util.List findByCompanyId( java.lang.String companyId, int begin, int end, com.liferay.util.dao.hibernate.OrderByComparator obc) throws com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.findByCompanyId(companyId, begin, end, obc); } protected static com.liferay.portlet.admin.model.AdminConfig findByCompanyId_First( java.lang.String companyId, com.liferay.util.dao.hibernate.OrderByComparator obc) throws com.liferay.portlet.admin.NoSuchConfigException, com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.findByCompanyId_First(companyId, obc); } protected static com.liferay.portlet.admin.model.AdminConfig findByCompanyId_Last( java.lang.String companyId, com.liferay.util.dao.hibernate.OrderByComparator obc) throws com.liferay.portlet.admin.NoSuchConfigException, com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.findByCompanyId_Last(companyId, obc); } protected static com.liferay.portlet.admin.model.AdminConfig[] findByCompanyId_PrevAndNext( java.lang.String configId, java.lang.String companyId, com.liferay.util.dao.hibernate.OrderByComparator obc) throws com.liferay.portlet.admin.NoSuchConfigException, com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.findByCompanyId_PrevAndNext(configId, companyId, obc); } protected static java.util.List findByC_T(java.lang.String companyId, java.lang.String type) throws com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.findByC_T(companyId, type); } protected static java.util.List findByC_T(java.lang.String companyId, java.lang.String type, int begin, int end) throws com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.findByC_T(companyId, type, begin, end); } protected static java.util.List findByC_T(java.lang.String companyId, java.lang.String type, int begin, int end, com.liferay.util.dao.hibernate.OrderByComparator obc) throws com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.findByC_T(companyId, type, begin, end, obc); } protected static com.liferay.portlet.admin.model.AdminConfig findByC_T_First( java.lang.String companyId, java.lang.String type, com.liferay.util.dao.hibernate.OrderByComparator obc) throws com.liferay.portlet.admin.NoSuchConfigException, com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.findByC_T_First(companyId, type, obc); } protected static com.liferay.portlet.admin.model.AdminConfig findByC_T_Last( java.lang.String companyId, java.lang.String type, com.liferay.util.dao.hibernate.OrderByComparator obc) throws com.liferay.portlet.admin.NoSuchConfigException, com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.findByC_T_Last(companyId, type, obc); } protected static com.liferay.portlet.admin.model.AdminConfig[] findByC_T_PrevAndNext( java.lang.String configId, java.lang.String companyId, java.lang.String type, com.liferay.util.dao.hibernate.OrderByComparator obc) throws com.liferay.portlet.admin.NoSuchConfigException, com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.findByC_T_PrevAndNext(configId, companyId, type, obc); } protected static java.util.List findAll() throws com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.findAll(); } protected static void removeByCompanyId(java.lang.String companyId) throws com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); persistence.removeByCompanyId(companyId); } protected static void removeByC_T(java.lang.String companyId, java.lang.String type) throws com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); persistence.removeByC_T(companyId, type); } protected static int countByCompanyId(java.lang.String companyId) throws com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.countByCompanyId(companyId); } protected static int countByC_T(java.lang.String companyId, java.lang.String type) throws com.liferay.portal.SystemException { AdminConfigPersistence persistence = (AdminConfigPersistence)InstancePool.get(PERSISTENCE); return persistence.countByC_T(companyId, type); } }
gpl-3.0
potty-dzmeia/db4o
src/db4oj.tests/src/com/db4o/test/performance/FileSeekBenchmark.java
1747
/* This file is part of the db4o object database http://www.db4o.com Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com db4o is free software; you can redistribute it and/or modify it under the terms of version 3 of the GNU General Public License as published by the Free Software Foundation. db4o is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ package com.db4o.test.performance; import java.io.*; public class FileSeekBenchmark { private static String FILE = "FileSeekBenchmark.file"; private static final int COUNT = 100000; private static final int SIZE = 100000; public static void main(String[] args) throws IOException { new File(FILE).delete(); RandomAccessFile raf = new RandomAccessFile(FILE, "rw"); for (int i = 0; i < SIZE; i++) { raf.write(1); } raf.close(); raf = new RandomAccessFile(FILE, "rw"); long start = System.currentTimeMillis(); for (int i = 0; i < COUNT; i++) { raf.seek(1); raf.read(); raf.seek(SIZE - 2); raf.read(); } long stop = System.currentTimeMillis(); long duration = stop - start; raf.close(); new File(FILE).delete(); System.out.println("Time for " + COUNT + " seeks in a " + SIZE + " bytes sized file:\n" + duration + "ms"); } }
gpl-3.0
kozzeluc/dmlj
Eclipse CA IDMS Schema Diagram Editor/bundles/org.lh.dmlj.schema.editor.model/src/org/lh/dmlj/schema/IndexElement.java
4383
/** * Copyright (C) 2013 Luc Hermans * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If * not, see <http://www.gnu.org/licenses/>. * * Contact information: kozzeluc@gmail.com. */ package org.lh.dmlj.schema; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Index Element</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.lh.dmlj.schema.IndexElement#getBaseName <em>Base Name</em>}</li> * <li>{@link org.lh.dmlj.schema.IndexElement#getName <em>Name</em>}</li> * <li>{@link org.lh.dmlj.schema.IndexElement#getOccursSpecification <em>Occurs Specification</em>}</li> * </ul> * </p> * * @see org.lh.dmlj.schema.SchemaPackage#getIndexElement() * @model * @generated */ public interface IndexElement extends EObject { /** * Returns the value of the '<em><b>Base Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Base Name</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Base Name</em>' attribute. * @see #setBaseName(String) * @see org.lh.dmlj.schema.SchemaPackage#getIndexElement_BaseName() * @model * @generated */ String getBaseName(); /** * Sets the value of the '{@link org.lh.dmlj.schema.IndexElement#getBaseName <em>Base Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Base Name</em>' attribute. * @see #getBaseName() * @generated */ void setBaseName(String value); /** * Returns the value of the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Name</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Name</em>' attribute. * @see #setName(String) * @see org.lh.dmlj.schema.SchemaPackage#getIndexElement_Name() * @model * @generated */ String getName(); /** * Sets the value of the '{@link org.lh.dmlj.schema.IndexElement#getName <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Name</em>' attribute. * @see #getName() * @generated */ void setName(String value); /** * Returns the value of the '<em><b>Occurs Specification</b></em>' container reference. * It is bidirectional and its opposite is '{@link org.lh.dmlj.schema.OccursSpecification#getIndexElements <em>Index Elements</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Occurs Specification</em>' container reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Occurs Specification</em>' container reference. * @see #setOccursSpecification(OccursSpecification) * @see org.lh.dmlj.schema.SchemaPackage#getIndexElement_OccursSpecification() * @see org.lh.dmlj.schema.OccursSpecification#getIndexElements * @model opposite="indexElements" required="true" transient="false" * @generated */ OccursSpecification getOccursSpecification(); /** * Sets the value of the '{@link org.lh.dmlj.schema.IndexElement#getOccursSpecification <em>Occurs Specification</em>}' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Occurs Specification</em>' container reference. * @see #getOccursSpecification() * @generated */ void setOccursSpecification(OccursSpecification value); } // IndexElement
gpl-3.0
SanderMertens/opensplice
src/api/dcps/java/saj/code/DDS/GuardConditionInterfaceOperations.java
450
/* * OpenSplice DDS * * This software and documentation are Copyright 2006 to 2013 PrismTech * Limited and its licensees. All rights reserved. See file: * * $OSPL_HOME/LICENSE * * for full copyright notice and license terms. * */ package DDS; public interface GuardConditionInterfaceOperations extends DDS.ConditionOperations { /* operations */ int set_trigger_value(boolean value); }
gpl-3.0
xframium/xframium-java
framework/src/org/xframium/content/provider/ContentProvider.java
1318
/******************************************************************************* * xFramium * * Copyright 2016 by Moreland Labs, Ltd. (http://www.morelandlabs.com) * * Some open source application is free software: you can redistribute * it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * * Some open source application is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with xFramium. If not, see <http://www.gnu.org/licenses/>. * * @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+> *******************************************************************************/ package org.xframium.content.provider; // TODO: Auto-generated Javadoc /** * The Interface PageDataProvider. */ public interface ContentProvider { /** * Read page data. */ public void readContent(); public String getxFID(); public void setxFID( String xFID ); }
gpl-3.0
Omegapoint/opmarketplace
apigateway/src/main/java/se/omegapoint/academy/opmarketplace/apigateway/infrastructure/json_representations/DTO.java
206
package se.omegapoint.academy.opmarketplace.apigateway.infrastructure.json_representations; // Classes implementing this interface should // be annotated for Jackson serialization. public interface DTO {}
gpl-3.0
gaich/quickapps
app/src/main/java/com/yoavst/quickapps/clock/StopwatchManager.java
2272
package com.yoavst.quickapps.clock; import java.util.Timer; import java.util.TimerTask; /** * Created by Yoav. */ public class StopwatchManager { private static Runnable sRunnable; private static Stopwatch sStopwatch; private static long sMilliseconds = 0; private static long sPeriod = 0; private StopwatchManager() { } public static void startTimer(final long period, Runnable callback) { sRunnable = callback; sPeriod = period; initStopwatch(); startTimer(); } private static void startTimer() { new Timer().schedule(sStopwatch, 10, sPeriod); } private static void initStopwatch() { sStopwatch = new Stopwatch() { @Override protected void runCode() { sMilliseconds += sPeriod; if (sRunnable != null) sRunnable.run(); } }; } /** * Make the timer to run on background, with no callback */ public static void runOnBackground() { sRunnable = null; // If the stopwatch is paused, it will just save its data, and will not run. if (!(sStopwatch == null || sStopwatch.isRunning())) { sStopwatch.cancel(); sStopwatch = null; } } public static void runOnUi(Runnable callback) { sRunnable = callback; if (hasOldData() && sStopwatch == null) { initStopwatch(); startTimer(); sStopwatch.isRunning(false); if (sRunnable != null) sRunnable.run(); } } public static void stopTimer() { sRunnable = null; sStopwatch.cancel(); sStopwatch = null; sMilliseconds = 0; sPeriod = 0; } public static void PauseTimer() { if (sStopwatch != null) sStopwatch.isRunning(false); } public static void ResumeTimer() { if (sStopwatch != null) sStopwatch.isRunning(true); } public static long getMillis() { return sMilliseconds; } public static boolean isRunning() { return sStopwatch != null && sStopwatch.isRunning(); } public static boolean hasOldData() { return sMilliseconds != 0 && sPeriod != 0; } public static abstract class Stopwatch extends TimerTask { private boolean isRunning = true; public synchronized void isRunning(boolean running) { this.isRunning = running; } public synchronized boolean isRunning() { return isRunning; } @Override public void run() { if (isRunning) runCode(); } protected abstract void runCode(); } }
gpl-3.0
pdepaepe/graylog2-server
graylog2-server/src/main/java/org/graylog2/shared/initializers/JerseyService.java
17473
/** * This file is part of Graylog. * * Graylog is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Graylog is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog2.shared.initializers; import com.codahale.metrics.InstrumentedExecutorService; import com.codahale.metrics.MetricRegistry; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; import com.google.common.base.Strings; import com.google.common.util.concurrent.AbstractIdleService; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.grizzly.http.server.NetworkListener; import org.glassfish.grizzly.ssl.SSLContextConfigurator; import org.glassfish.grizzly.ssl.SSLEngineConfigurator; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.message.GZipEncoder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.ServerProperties; import org.glassfish.jersey.server.filter.EncodingFilter; import org.glassfish.jersey.server.model.Resource; import org.graylog2.Configuration; import org.graylog2.audit.PluginAuditEventTypes; import org.graylog2.audit.jersey.AuditEventModelProcessor; import org.graylog2.jersey.PrefixAddingModelProcessor; import org.graylog2.plugin.rest.PluginRestResource; import org.graylog2.rest.filter.WebAppNotFoundResponseFilter; import org.graylog2.shared.rest.CORSFilter; import org.graylog2.shared.rest.NodeIdResponseFilter; import org.graylog2.shared.rest.NotAuthorizedResponseFilter; import org.graylog2.shared.rest.PrintModelProcessor; import org.graylog2.shared.rest.RestAccessLogFilter; import org.graylog2.shared.rest.XHRFilter; import org.graylog2.shared.rest.exceptionmappers.AnyExceptionClassMapper; import org.graylog2.shared.rest.exceptionmappers.BadRequestExceptionMapper; import org.graylog2.shared.rest.exceptionmappers.JacksonPropertyExceptionMapper; import org.graylog2.shared.rest.exceptionmappers.JsonProcessingExceptionMapper; import org.graylog2.shared.rest.exceptionmappers.WebApplicationExceptionMapper; import org.graylog2.shared.security.tls.KeyStoreUtils; import org.graylog2.shared.security.tls.PemKeyStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Named; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.container.DynamicFeature; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.ExceptionMapper; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.KeyStore; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.stream.Collectors; import static com.codahale.metrics.MetricRegistry.name; import static com.google.common.base.MoreObjects.firstNonNull; public class JerseyService extends AbstractIdleService { public static final String PLUGIN_PREFIX = "/plugins"; private static final Logger LOG = LoggerFactory.getLogger(JerseyService.class); private static final String RESOURCE_PACKAGE_WEB = "org.graylog2.web.resources"; private final Configuration configuration; private final Map<String, Set<Class<? extends PluginRestResource>>> pluginRestResources; private final String[] restControllerPackages; private final Set<Class<? extends DynamicFeature>> dynamicFeatures; private final Set<Class<? extends ContainerResponseFilter>> containerResponseFilters; private final Set<Class<? extends ExceptionMapper>> exceptionMappers; private final Set<Class> additionalComponents; private final Set<PluginAuditEventTypes> pluginAuditEventTypes; private final ObjectMapper objectMapper; private final MetricRegistry metricRegistry; private HttpServer apiHttpServer = null; private HttpServer webHttpServer = null; @Inject public JerseyService(final Configuration configuration, Set<Class<? extends DynamicFeature>> dynamicFeatures, Set<Class<? extends ContainerResponseFilter>> containerResponseFilters, Set<Class<? extends ExceptionMapper>> exceptionMappers, @Named("additionalJerseyComponents") final Set<Class> additionalComponents, final Map<String, Set<Class<? extends PluginRestResource>>> pluginRestResources, @Named("RestControllerPackages") final String[] restControllerPackages, Set<PluginAuditEventTypes> pluginAuditEventTypes, ObjectMapper objectMapper, MetricRegistry metricRegistry) { this.configuration = configuration; this.dynamicFeatures = dynamicFeatures; this.containerResponseFilters = containerResponseFilters; this.exceptionMappers = exceptionMappers; this.additionalComponents = additionalComponents; this.pluginRestResources = pluginRestResources; this.restControllerPackages = restControllerPackages; this.pluginAuditEventTypes = pluginAuditEventTypes; this.objectMapper = objectMapper; this.metricRegistry = metricRegistry; } @Override protected void startUp() throws Exception { startUpApi(); if (configuration.isWebEnable() && !configuration.isRestAndWebOnSamePort()) { startUpWeb(); } } private void startUpWeb() throws Exception { final String[] resources = new String[]{RESOURCE_PACKAGE_WEB}; final SSLEngineConfigurator sslEngineConfigurator = configuration.isWebEnableTls() ? buildSslEngineConfigurator( configuration.getWebTlsCertFile(), configuration.getWebTlsKeyFile(), configuration.getWebTlsKeyPassword()) : null; final URI webListenUri = configuration.getWebListenUri(); final URI listenUri = new URI( webListenUri.getScheme(), webListenUri.getUserInfo(), webListenUri.getHost(), webListenUri.getPort(), null, null, null ); webHttpServer = setUp("web", listenUri, sslEngineConfigurator, configuration.getWebThreadPoolSize(), configuration.getWebMaxInitialLineLength(), configuration.getWebMaxHeaderSize(), configuration.isWebEnableGzip(), configuration.isWebEnableCors(), Collections.emptySet(), resources); webHttpServer.start(); LOG.info("Started Web Interface at <{}>", configuration.getWebListenUri()); } @Override protected void shutDown() throws Exception { shutdownHttpServer(apiHttpServer, configuration.getRestListenUri()); shutdownHttpServer(webHttpServer, configuration.getWebListenUri()); } private void shutdownHttpServer(HttpServer httpServer, URI listenUri) { if (httpServer != null && httpServer.isStarted()) { LOG.info("Shutting down HTTP listener at <{}>", listenUri); httpServer.shutdownNow(); } } private void startUpApi() throws Exception { final boolean startWebInterface = configuration.isWebEnable() && configuration.isRestAndWebOnSamePort(); final List<String> resourcePackages = new ArrayList<>(Arrays.asList(restControllerPackages)); if (startWebInterface) { resourcePackages.add(RESOURCE_PACKAGE_WEB); } final Set<Resource> pluginResources = prefixPluginResources(PLUGIN_PREFIX, pluginRestResources); final SSLEngineConfigurator sslEngineConfigurator = configuration.isRestEnableTls() ? buildSslEngineConfigurator( configuration.getRestTlsCertFile(), configuration.getRestTlsKeyFile(), configuration.getRestTlsKeyPassword()) : null; final URI restListenUri = configuration.getRestListenUri(); final URI listenUri = new URI( restListenUri.getScheme(), restListenUri.getUserInfo(), restListenUri.getHost(), restListenUri.getPort(), null, null, null ); apiHttpServer = setUp("rest", listenUri, sslEngineConfigurator, configuration.getRestThreadPoolSize(), configuration.getRestMaxInitialLineLength(), configuration.getRestMaxHeaderSize(), configuration.isRestEnableGzip(), configuration.isRestEnableCors(), pluginResources, resourcePackages.toArray(new String[0])); apiHttpServer.start(); LOG.info("Started REST API at <{}>", configuration.getRestListenUri()); if (startWebInterface) { LOG.info("Started Web Interface at <{}>", configuration.getWebListenUri()); } } private Set<Resource> prefixPluginResources(String pluginPrefix, Map<String, Set<Class<? extends PluginRestResource>>> pluginResourceMap) { return pluginResourceMap.entrySet().stream() .map(entry -> prefixResources(pluginPrefix + "/" + entry.getKey(), entry.getValue())) .flatMap(Collection::stream) .collect(Collectors.toSet()); } private <T> Set<Resource> prefixResources(String prefix, Set<Class<? extends T>> resources) { final String pathPrefix = prefix.endsWith("/") ? prefix.substring(0, prefix.length() - 1) : prefix; return resources .stream() .map(resource -> { final javax.ws.rs.Path pathAnnotation = Resource.getPath(resource); final String resourcePathSuffix = Strings.nullToEmpty(pathAnnotation.value()); final String resourcePath = resourcePathSuffix.startsWith("/") ? pathPrefix + resourcePathSuffix : pathPrefix + "/" + resourcePathSuffix; return Resource .builder(resource) .path(resourcePath) .build(); }) .collect(Collectors.toSet()); } private ResourceConfig buildResourceConfig(final boolean enableGzip, final boolean enableCors, final Set<Resource> additionalResources, final String[] controllerPackages) { final Map<String, String> packagePrefixes = new HashMap<>(); for (String resourcePackage : controllerPackages) { packagePrefixes.put(resourcePackage, configuration.getRestListenUri().getPath()); } packagePrefixes.put(RESOURCE_PACKAGE_WEB, configuration.getWebListenUri().getPath()); packagePrefixes.put("", configuration.getRestListenUri().getPath()); final ResourceConfig rc = new ResourceConfig() .property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true) .property(ServerProperties.WADL_FEATURE_DISABLE, true) .register(new PrefixAddingModelProcessor(packagePrefixes)) .register(new AuditEventModelProcessor(pluginAuditEventTypes)) .registerClasses( JacksonJaxbJsonProvider.class, JsonProcessingExceptionMapper.class, JacksonPropertyExceptionMapper.class, AnyExceptionClassMapper.class, WebApplicationExceptionMapper.class, BadRequestExceptionMapper.class, RestAccessLogFilter.class, NodeIdResponseFilter.class, XHRFilter.class, NotAuthorizedResponseFilter.class, WebAppNotFoundResponseFilter.class) .register(new ContextResolver<ObjectMapper>() { @Override public ObjectMapper getContext(Class<?> type) { return objectMapper; } }) .packages(true, controllerPackages) .registerResources(additionalResources); exceptionMappers.forEach(rc::registerClasses); dynamicFeatures.forEach(rc::registerClasses); containerResponseFilters.forEach(rc::registerClasses); additionalComponents.forEach(rc::registerClasses); if (enableGzip) { EncodingFilter.enableFor(rc, GZipEncoder.class); } if (enableCors) { LOG.info("Enabling CORS for HTTP endpoint"); rc.registerClasses(CORSFilter.class); } if (LOG.isDebugEnabled()) { rc.registerClasses(PrintModelProcessor.class); } return rc; } private HttpServer setUp(String namePrefix, URI listenUri, SSLEngineConfigurator sslEngineConfigurator, int threadPoolSize, int maxInitialLineLength, int maxHeaderSize, boolean enableGzip, boolean enableCors, Set<Resource> additionalResources, String[] controllerPackages) throws GeneralSecurityException, IOException { final ResourceConfig resourceConfig = buildResourceConfig( enableGzip, enableCors, additionalResources, controllerPackages ); final HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer( listenUri, resourceConfig, sslEngineConfigurator != null, sslEngineConfigurator); final NetworkListener listener = httpServer.getListener("grizzly"); listener.setMaxHttpHeaderSize(maxInitialLineLength); listener.setMaxRequestHeaders(maxHeaderSize); final ExecutorService workerThreadPoolExecutor = instrumentedExecutor( namePrefix + "-worker-executor", namePrefix + "-worker-%d", threadPoolSize); listener.getTransport().setWorkerThreadPool(workerThreadPoolExecutor); return httpServer; } private SSLEngineConfigurator buildSslEngineConfigurator(Path certFile, Path keyFile, String keyPassword) throws GeneralSecurityException, IOException { if (keyFile == null || !Files.isRegularFile(keyFile) || !Files.isReadable(keyFile)) { throw new InvalidKeyException("Unreadable or missing private key: " + keyFile); } if (certFile == null || !Files.isRegularFile(certFile) || !Files.isReadable(certFile)) { throw new CertificateException("Unreadable or missing X.509 certificate: " + certFile); } final SSLContextConfigurator sslContext = new SSLContextConfigurator(); final char[] password = firstNonNull(keyPassword, "").toCharArray(); final KeyStore keyStore = PemKeyStore.buildKeyStore(certFile, keyFile, password); sslContext.setKeyStorePass(password); sslContext.setKeyStoreBytes(KeyStoreUtils.getBytes(keyStore, password)); if (!sslContext.validateConfiguration(true)) { throw new IllegalStateException("Couldn't initialize SSL context for HTTP server"); } return new SSLEngineConfigurator(sslContext.createSSLContext(), false, false, false); } private ExecutorService instrumentedExecutor(final String executorName, final String threadNameFormat, int poolSize) { final ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat(threadNameFormat) .setDaemon(true) .build(); return new InstrumentedExecutorService( Executors.newFixedThreadPool(poolSize, threadFactory), metricRegistry, name(JerseyService.class, executorName)); } }
gpl-3.0
jorkKit/mantoQSAR
gui/src/org/mantoQSAR/gui/ProcessGroup.java
1191
/* This file is part of mantoQSAR. mantoQSAR - Quantitative structure-activity relationship descriptor calculation and modeling for biomolecules. Copyright (C) 2016 Jörg Kittelmann mantoQSAR is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. mantoQSAR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with mantoQSAR. If not, see <http://www.gnu.org/licenses/>. */ package org.mantoQSAR.gui; import java.util.List; public final class ProcessGroup { private static ProcessGroup instance = null; public static ProcessGroup getInstance(){ if(instance == null){ instance = new ProcessGroup(); } return instance; } protected ProcessGroup(){ } }
gpl-3.0
Severed-Infinity/technium
build/tmp/recompileMc/sources/net/minecraft/client/renderer/block/statemap/StateMap.java
3920
package net.minecraft.client.renderer.block.statemap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.util.Collections; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class StateMap extends StateMapperBase { private final IProperty<?> name; private final String suffix; private final List < IProperty<? >> ignored; private StateMap(@Nullable IProperty<?> name, @Nullable String suffix, List < IProperty<? >> ignored) { this.name = name; this.suffix = suffix; this.ignored = ignored; } protected ModelResourceLocation getModelResourceLocation(IBlockState state) { Map < IProperty<?>, Comparable<? >> map = Maps. < IProperty<?>, Comparable<? >> newLinkedHashMap(state.getProperties()); String s; if (this.name == null) { s = ((ResourceLocation)Block.REGISTRY.getNameForObject(state.getBlock())).toString(); } else { s = String.format("%s:%s", Block.REGISTRY.getNameForObject(state.getBlock()).getResourceDomain(), this.removeName(this.name, map)); } if (this.suffix != null) { s = s + this.suffix; } for (IProperty<?> iproperty : this.ignored) { map.remove(iproperty); } return new ModelResourceLocation(s, this.getPropertyString(map)); } private <T extends Comparable<T>> String removeName(IProperty<T> property, Map < IProperty<?>, Comparable<? >> values) { return property.getName((T)values.remove(this.name)); } @SideOnly(Side.CLIENT) public static class Builder { private IProperty<?> name; private String suffix; private final List < IProperty<? >> ignored = Lists. < IProperty<? >> newArrayList(); public StateMap.Builder withName(IProperty<?> builderPropertyIn) { this.name = builderPropertyIn; return this; } public StateMap.Builder withSuffix(String builderSuffixIn) { this.suffix = builderSuffixIn; return this; } /** * Ignore the listed {@code IProperty}s when building the variant string for the final {@code * ModelResourceLocation}. It is valid to pass a {@code Block} that does not have one of these {@code * IProperty}s to the built {@code StateMap}. * @return {@code this}, for convenience in chaining * * @param ignores the {@code IProperty}s to ignore when building a variant string */ public StateMap.Builder ignore(IProperty<?>... ignores) { Collections.addAll(this.ignored, ignores); return this; } /** * Build a new {@code StateMap} with the settings contained in this {@code StateMap.Builder}. The {@code * StateMap} will work with any {@code Block} that has the required {@code IProperty}s. * @return a new {@code StateMap} with the settings contained in this {@code StateMap.Builder} * @see #ignore(IProperty...) * @see #withName(IProperty) * @see #withSuffix(String) */ public StateMap build() { return new StateMap(this.name, this.suffix, this.ignored); } } }
gpl-3.0
kinztechcom/League-File-Manager
src/com/kinztech/league/raf/utilities/io/IOBuffer.java
3881
package com.kinztech.league.raf.utilities.io; /** * Created by Allen Kinzalow on 7/2/2015. */ public class IOBuffer { byte[] buffer; int position; /** * Construct an IOBuffer with a given byte array * @param buffer */ public IOBuffer(byte[] buffer) { this.buffer = buffer; } /** * Read Little Endian Unsigned Integer * 0, 8, 16, 24 * @return */ public int readUnsignedLEInt() { this.position += 4; return (this.buffer[this.position - 4] & 255) + ((this.buffer[this.position - 3] & 255) << 8) + ((this.buffer[this.position - 2] & 255) << 16) + ((this.buffer[this.position - 1] & 255) << 24); } /** * Read Unsigned Integer * 24 16 8 0 * @return */ public int readUnsignedInt() { this.position += 4; return (this.buffer[this.position - 1] & 255) + ((this.buffer[this.position - 2] & 255) << 8) + ((this.buffer[this.position - 3] & 255) << 16) + ((this.buffer[this.position - 4] & 255) << 24); } /** * Read Little Endian Unsigned Medium * 0, 8, 16 * @return */ public int readUnsignedLEMedium() { this.position += 3; return (this.buffer[this.position - 3] & 255) + ((this.buffer[this.position - 2] & 255) << 8) + ((this.buffer[this.position - 1] & 255) << 16); } /** * Read Unsigned Medium * 16 8 0 * @return */ public int readUnsignedMedium() { this.position += 3; return (this.buffer[this.position - 1] & 255) + ((this.buffer[this.position - 2] & 255) << 8) + ((this.buffer[this.position - 3] & 255) << 16); } /** * Read Little Endian Unsigned Short * 0, 8, 16 * @return */ public int readUnsignedLEShort() { this.position += 2; return (this.buffer[this.position - 2] & 255) + ((this.buffer[this.position - 1] & 255) << 8); } /** * Read Unsigned Short * 16 8 0 * @return */ public int readUnsignedShort() { this.position += 2; return (this.buffer[this.position - 1] & 255) + ((this.buffer[this.position - 2] & 255) << 8); } public Float readLEFloat() { return Float.intBitsToFloat(this.readUnsignedLEInt()); } public Float readFloat() { return Float.intBitsToFloat(this.readUnsignedInt()); } /** * Read an unsigned byte. * @return */ public int readUnsignedByte() { this.position += 1; return this.buffer[this.position - 1] & 255; } /** * Read a signed byte. * @return */ public int readByte() { this.position += 1; return this.buffer[this.position - 1]; } /** * Set the buffer's position. * @param position */ public void setPosition(int position) { this.position = position; } /** * Return the buffer's position. * @return */ public int getPosition() { return position; } /** * Read bytes from the buffer to a byte array with a given length. * -Starts from the current position! * @param ai * @param length */ public void readBytes(byte[] ai, int length) { for(int pos = 0; pos < length; pos++) ai[pos] = buffer[position + pos]; } /** * Read a string with a null terminating 0x00 * @return */ public String readString() { int start = position; while (readByte() != 0); int len = position - start; byte[] str = new byte[len]; position = start; readBytes(str, len - 1); return new String(str, 0, len - 1); } public String readString(int size) { byte[] str = new byte[size]; readBytes(str, size - 1); position += size; return new String(str, 0 , size - 1); } }
gpl-3.0
fauu/NotPetStore
nps-core/src/main/java/com/github/fauu/notpetstore/common/Page.java
961
package com.github.fauu.notpetstore.common; import lombok.Data; import lombok.NonNull; import java.util.List; public @Data class Page<T> { private @NonNull int no; private @NonNull List<T> items; private @NonNull int maxSize; private @NonNull int totalItemCount; public int getNumPagesTotal() { return totalItemCount == 0 ? 1 : (int) Math.ceil((double) totalItemCount / (double) maxSize); } public boolean isMoreAvailable() { return getNumPagesTotal() > 1; } public boolean isPreviousAvailable() { return no > 1; } public boolean isNextAvailable() { return no < getNumPagesTotal(); } public int getFirstNo() { return 1; } public int getPreviousNo() { return isPreviousAvailable() ? no - 1 : -1; } public int getNextNo() { return isNextAvailable() ? no + 1 : -1; } public int getLastNo() { return getNumPagesTotal(); } }
gpl-3.0
marvisan/HadesFIX
Model/src/test/java/net/hades/fix/message/impl/v43/data/NewOrderCrossMsg43TestData.java
9293
/* * Copyright (c) 2006-2016 Marvisan Pty. Ltd. All rights reserved. * Use is subject to license terms. */ /* * NewOrderCrossMsg43TestData.java * * $Id: NewOrderCrossMsg43TestData.java,v 1.3 2011-10-29 09:42:28 vrotaru Exp $ */ package net.hades.fix.message.impl.v43.data; import java.io.UnsupportedEncodingException; import java.util.Calendar; import static org.junit.Assert.*; import net.hades.fix.TestUtils; import net.hades.fix.message.MsgTest; import net.hades.fix.message.NewOrderCrossMsg; import net.hades.fix.message.comp.impl.v43.Instrument43TestData; import net.hades.fix.message.comp.impl.v43.SpreadOrBenchmarkCurveData43TestData; import net.hades.fix.message.comp.impl.v43.Stipulations43TestData; import net.hades.fix.message.group.impl.v43.SideCrossOrdModGroup43TestData; import net.hades.fix.message.group.impl.v43.YieldData43TestData; import net.hades.fix.message.group.impl.v43.TradingSessionGroup43TestData; import net.hades.fix.message.type.CancellationRights; import net.hades.fix.message.type.CrossPrioritization; import net.hades.fix.message.type.CrossType; import net.hades.fix.message.type.Currency; import net.hades.fix.message.type.DiscretionInst; import net.hades.fix.message.type.ExecInst; import net.hades.fix.message.type.GTBookingInst; import net.hades.fix.message.type.HandlInst; import net.hades.fix.message.type.MoneyLaunderingStatus; import net.hades.fix.message.type.OrdType; import net.hades.fix.message.type.PriceType; import net.hades.fix.message.type.ProcessCode; import net.hades.fix.message.type.SettlType; import net.hades.fix.message.type.TimeInForce; /** * Test utility for NewOrderCrossMsg43 message class. * * @author <a href="mailto:support@marvisan.com">Support Team</a> * @version $Revision: 1.3 $ * @created 12/05/2011, 12:08:30 PM */ public class NewOrderCrossMsg43TestData extends MsgTest { private static final NewOrderCrossMsg43TestData INSTANCE; static { INSTANCE = new NewOrderCrossMsg43TestData(); } public static NewOrderCrossMsg43TestData getInstance() { return INSTANCE; } public void populate(NewOrderCrossMsg msg) throws UnsupportedEncodingException { TestUtils.populate43HeaderAll(msg); Calendar cal = Calendar.getInstance(); msg.setCrossID("AAA564567"); msg.setCrossType(CrossType.CrossAON); msg.setCrossPrioritization(CrossPrioritization.BuySidePrioritized); msg.setNoSides(2); SideCrossOrdModGroup43TestData.getInstance().populate1(msg.getSideCrossOrdModGroups()[0]); SideCrossOrdModGroup43TestData.getInstance().populate2(msg.getSideCrossOrdModGroups()[1]); msg.setInstrument(); Instrument43TestData.getInstance().populate(msg.getInstrument()); msg.setSettlType(SettlType.Cash.getValue()); cal.set(2010, 3, 14, 12, 15, 33); msg.setSettlDate(cal.getTime()); msg.setHandlInst(HandlInst.ManualOrder); msg.setExecInst(ExecInst.CallFirst.getValue()); msg.setMinQty(12.44d); msg.setMaxFloor(33.66d); msg.setExDestination("exchange"); msg.setNoTradingSessions(new Integer(2)); TradingSessionGroup43TestData.getInstance().populate1(msg.getTradingSessionGroups()[0]); TradingSessionGroup43TestData.getInstance().populate2(msg.getTradingSessionGroups()[1]); msg.setProcessCode(ProcessCode.Regular); msg.setPrevClosePx(29.45d); msg.setLocateReqd(Boolean.TRUE); cal.set(2010, 3, 14, 15, 18, 32); msg.setTransactTime(cal.getTime()); cal.set(2010, 3, 15, 15, 22, 32); msg.setTransBkdTime(cal.getTime()); msg.setStipulations(); Stipulations43TestData.getInstance().populate(msg.getStipulations()); msg.setOrdType(OrdType.Limit); msg.setPriceType(PriceType.FixedAmount); msg.setPrice(50.67d); msg.setStopPx(51.67d); msg.setSpreadOrBenchmarkCurveData(); SpreadOrBenchmarkCurveData43TestData.getInstance().populate(msg.getSpreadOrBenchmarkCurveData()); msg.setYieldData(); YieldData43TestData.getInstance().populate(msg.getYieldData()); msg.setCurrency(Currency.UnitedStatesDollar); msg.setComplianceID("compl ID"); msg.setIOIID("X25388405"); msg.setQuoteID("G93847464"); msg.setTimeInForce(TimeInForce.Opening); cal.set(2010, 3, 14, 22, 22, 22); msg.setEffectiveTime(cal.getTime()); cal.set(2010, 3, 16, 22, 22, 22); msg.setExpireDate(cal.getTime()); cal.set(2010, 3, 14, 12, 30, 44); msg.setExpireTime(cal.getTime()); msg.setGTBookingInst(GTBookingInst.BookOutAllTrades); msg.setMaxShow(15.35d); msg.setPegOffsetValue(0.65d); msg.setDiscretionInst(DiscretionInst.RelatedToMarketPrice); msg.setDiscretionOffsetValue(24.66d); msg.setCancellationRights(CancellationRights.No_ExecutionOnly); msg.setMoneyLaunderingStatus(MoneyLaunderingStatus.Exempt_BelowLimit); msg.setRegistID("67628248247"); msg.setDesignation("test"); msg.setAccruedInterestRate(2.5d); msg.setAccruedInterestAmt(233.5d); msg.setNetMoney(222.35d); } public void check(NewOrderCrossMsg expected, NewOrderCrossMsg actual) throws Exception { assertEquals(expected.getCrossID(), actual.getCrossID()); assertEquals(expected.getCrossType(), actual.getCrossType()); assertEquals(expected.getCrossPrioritization(), actual.getCrossPrioritization()); assertEquals(expected.getNoSides(), actual.getNoSides()); SideCrossOrdModGroup43TestData.getInstance().check(expected.getSideCrossOrdModGroups()[0], actual.getSideCrossOrdModGroups()[0]); SideCrossOrdModGroup43TestData.getInstance().check(expected.getSideCrossOrdModGroups()[1], actual.getSideCrossOrdModGroups()[1]); Instrument43TestData.getInstance().check(expected.getInstrument(), actual.getInstrument()); assertEquals(expected.getSettlType(), actual.getSettlType()); assertDateEquals(expected.getSettlDate(), actual.getSettlDate()); assertEquals(expected.getHandlInst(), actual.getHandlInst()); assertEquals(expected.getExecInst(), actual.getExecInst()); assertEquals(expected.getMinQty(), actual.getMinQty()); assertEquals(expected.getMaxFloor(), actual.getMaxFloor()); assertEquals(expected.getExDestination(), actual.getExDestination()); assertEquals(expected.getNoTradingSessions().intValue(), actual.getNoTradingSessions().intValue()); TradingSessionGroup43TestData.getInstance().check(expected.getTradingSessionGroups()[0], actual.getTradingSessionGroups()[0]); TradingSessionGroup43TestData.getInstance().check(expected.getTradingSessionGroups()[1], actual.getTradingSessionGroups()[1]); assertEquals(expected.getProcessCode(), actual.getProcessCode()); assertEquals(expected.getLocateReqd(), actual.getLocateReqd()); assertUTCTimestampEquals(expected.getTransactTime(), actual.getTransactTime(), false); Stipulations43TestData.getInstance().check(expected.getStipulations(), actual.getStipulations()); assertEquals(expected.getOrdType(), actual.getOrdType()); assertEquals(expected.getPriceType(), actual.getPriceType()); assertEquals(expected.getPrice(), actual.getPrice()); assertEquals(expected.getStopPx(), actual.getStopPx()); SpreadOrBenchmarkCurveData43TestData.getInstance().check(expected.getSpreadOrBenchmarkCurveData(), actual.getSpreadOrBenchmarkCurveData()); YieldData43TestData.getInstance().check(expected.getYieldData(), actual.getYieldData()); assertEquals(expected.getCurrency(), actual.getCurrency()); assertEquals(expected.getComplianceID(), actual.getComplianceID()); assertEquals(expected.getIOIID(), actual.getIOIID()); assertEquals(expected.getQuoteID(), actual.getQuoteID()); assertEquals(expected.getTimeInForce(), actual.getTimeInForce()); assertUTCTimestampEquals(expected.getEffectiveTime(), actual.getEffectiveTime(), false); assertDateEquals(expected.getExpireDate(), actual.getExpireDate()); assertUTCTimestampEquals(expected.getExpireTime(), actual.getExpireTime(), false); assertEquals(expected.getGTBookingInst(), actual.getGTBookingInst()); assertEquals(expected.getMaxShow(), actual.getMaxShow()); assertEquals(expected.getPegOffsetValue(), actual.getPegOffsetValue()); assertEquals(expected.getDiscretionInst(), actual.getDiscretionInst()); assertEquals(expected.getDiscretionOffsetValue(), actual.getDiscretionOffsetValue()); assertEquals(expected.getCancellationRights(), actual.getCancellationRights()); assertEquals(expected.getMoneyLaunderingStatus(), actual.getMoneyLaunderingStatus()); assertEquals(expected.getRegistID(), actual.getRegistID()); assertEquals(expected.getDesignation(), actual.getDesignation()); assertEquals(expected.getAccruedInterestRate(), actual.getAccruedInterestRate()); assertEquals(expected.getAccruedInterestAmt(), actual.getAccruedInterestAmt()); } }
gpl-3.0
shem-sergey/veraPDF-pdflib
src/main/java/org/verapdf/pd/form/PDAcroForm.java
1850
/** * This file is part of veraPDF Parser, a module of the veraPDF project. * Copyright (c) 2015, veraPDF Consortium <info@verapdf.org> * All rights reserved. * * veraPDF Parser is free software: you can redistribute it and/or modify * it under the terms of either: * * The GNU General public license GPLv3+. * You should have received a copy of the GNU General Public License * along with veraPDF Parser as the LICENSE.GPL file in the root of the source * tree. If not, see http://www.gnu.org/licenses/ or * https://www.gnu.org/licenses/gpl-3.0.en.html. * * The Mozilla Public License MPLv2+. * You should have received a copy of the Mozilla Public License along with * veraPDF Parser as the LICENSE.MPL file in the root of the source tree. * If a copy of the MPL was not distributed with this file, you can obtain one at * http://mozilla.org/MPL/2.0/. */ package org.verapdf.pd.form; import org.verapdf.as.ASAtom; import org.verapdf.cos.COSArray; import org.verapdf.cos.COSObjType; import org.verapdf.cos.COSObject; import org.verapdf.pd.PDObject; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author Maksim Bezrukov */ public class PDAcroForm extends PDObject { public PDAcroForm(COSObject obj) { super(obj); } public Boolean getNeedAppearances() { return getBooleanKey(ASAtom.NEED_APPEARANCES); } public List<PDFormField> getFields() { COSObject fields = getKey(ASAtom.FIELDS); if (fields != null && fields.getType() == COSObjType.COS_ARRAY) { List<PDFormField> res = new ArrayList<>(); for (COSObject obj : (COSArray) fields.getDirectBase()) { if (obj != null && obj.getType().isDictionaryBased()) { res.add(PDFormField.createTypedFormField(obj)); } } return Collections.unmodifiableList(res); } return Collections.emptyList(); } }
gpl-3.0
daemon/elemental-backend
src/main/net/rocketeer/elemental/geometry/Scene.java
2231
package net.rocketeer.elemental.geometry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Scene { private final int width; private final int height; private final int depth; private final HeatData heatData; private final FluidField fluidField; private float[] buffer; private boolean[] wallBlocks; private final Vector<Integer> origin; public Scene(int size) { this(size, new Vector<>(0, 0, 0)); } public Scene(int size, Vector<Integer> origin) { this(size, size, size, origin); } public Scene(int width, int height, int depth, Vector<Integer> origin) { this.buffer = new float[width * height * depth]; this.wallBlocks = new boolean[width * height * depth]; this.heatData = new HeatData(width, height, depth); this.fluidField = new FluidField(); this.origin = origin; this.width = width; this.height = height; this.depth = depth; } public float[] buffer() { return this.buffer; } public HeatData heatData() { return this.heatData; } public FluidField fluidField() { return this.fluidField; } public int width() { return this.width; } public int volume() { return this.width * this.height * this.depth; } public class FluidField { public float[] velocitiesX = new float[0]; public float[] velocitiesY = new float[0]; public float[] velocitiesZ = new float[0]; public float[] positionsX = new float[0]; public float[] positionsY = new float[0]; public float[] positionsZ = new float[0]; } public class HeatData { float[] heatPoints; float[] heatCoeffs; public HeatData(int width, int height, int depth) { this.heatPoints = new float[width * height * depth]; this.heatCoeffs = new float[width * height * depth]; } public float[] heatPoints() { return this.heatPoints; } public float heat(int x, int y, int z) { return this.heatPoints[width * height * x + height * y + z]; } public void setHeat(int x, int y, int z, float heat) { this.heatPoints[width * height * x + height * y + z] = heat; } public float[] heatCoeffs() { return this.heatCoeffs; } } }
gpl-3.0
joney000/Java-Competitive-Programming
Algorithms/BinarySearch.java
8619
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; /** * Author : joney_000[developer.jaswant@gmail.com] * Algorithm : Binary Search * Time : O(long n) Space : O(1) * Platform : Codeforces * Ref : N/A */ public class A{ private InputStream inputStream ; private OutputStream outputStream ; private FastReader in ; private PrintWriter out ; private final int BUFFER = 100005; private final long mod = 1000000000+7; private final int INF = Integer.MAX_VALUE; private final long INF_L = Long.MAX_VALUE / 10; public A(){} public A(boolean stdIO)throws FileNotFoundException{ // stdIO = false; // for file io, set from main driver if(stdIO){ inputStream = System.in; outputStream = System.out; }else{ inputStream = new FileInputStream("input.txt"); outputStream = new FileOutputStream("output.txt"); } in = new FastReader(inputStream); out = new PrintWriter(outputStream); } void run()throws Exception{ int n = i(); int m = i(); long ans = 0; out.write(""+ans+"\n"); } long binarySearch(int A[], int n, int key){ int m = 0; int l = 1; int r = n; while(l <= r){ m = l + (r-l)/2; if(A[m] == key){ // first comparison return m; }else if( A[m] < key ){ // second comparison l = m + 1; }else{ r = m - 1; } } return -1; } void clear(){ } long gcd(long a, long b){ if(b == 0)return a; return gcd(b, a % b); } long lcm(long a, long b){ if(a == 0 || b == 0)return 0; return (a * b)/gcd(a, b); } long mulMod(long a, long b, long mod){ if(a == 0 || b == 0)return 0; if(b == 1)return a; long ans = mulMod(a, b/2, mod); ans = (ans * 2) % mod; if(b % 2 == 1)ans = (a + ans)% mod; return ans; } long pow(long a, long b, long mod){ if(b == 0)return 1; if(b == 1)return a; long ans = pow(a, b/2, mod); ans = mulMod(ans, ans, mod); if(ans >= mod)ans %= mod; if(b % 2 == 1)ans = mulMod(a, ans, mod); if(ans >= mod)ans %= mod; return ans; } // 20*20 nCr Pascal Table long[][] ncrTable(){ long ncr[][] = new long[21][21]; for(int i = 0; i <= 20; i++){ ncr[i][0] = ncr[i][i] = 1L; } for(int j = 0; j <= 20; j++){ for(int i = j + 1; i <= 20; i++){ ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; } } return ncr; } int i()throws Exception{ return in.nextInt(); } long l()throws Exception{ return in.nextLong(); } double d()throws Exception{ return in.nextDouble(); } char c()throws Exception{ return in.nextCharacter(); } String s()throws Exception{ return in.nextLine(); } BigInteger bi()throws Exception{ return in.nextBigInteger(); } private void closeResources(){ out.flush(); out.close(); return; } // IMP: roundoff upto 2 digits // double roundOff = Math.round(a * 100.0) / 100.0; // or // System.out.printf("%.2f", val); // print upto 2 digits after decimal // val = ((long)(val * 100.0))/100.0; public static void main(String[] args) throws java.lang.Exception{ A driver = new A(true); driver.run(); driver.closeResources(); } } class FastReader{ private boolean finished = false; private InputStream stream; private byte[] buf = new byte[4 * 1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastReader(InputStream stream){ this.stream = stream; } public int read(){ if (numChars == -1){ throw new InputMismatchException (); } if (curChar >= numChars){ curChar = 0; try{ numChars = stream.read (buf); } catch (IOException e){ throw new InputMismatchException (); } if (numChars <= 0){ return -1; } } return buf[curChar++]; } public int peek(){ if (numChars == -1){ return -1; } if (curChar >= numChars){ curChar = 0; try{ numChars = stream.read (buf); } catch (IOException e){ return -1; } if (numChars <= 0){ return -1; } } return buf[curChar]; } public int nextInt(){ int c = read (); while (isSpaceChar (c)) c = read (); int sgn = 1; if (c == '-'){ sgn = -1; c = read (); } int res = 0; do{ if(c==','){ c = read(); } if (c < '0' || c > '9'){ throw new InputMismatchException (); } res *= 10; res += c - '0'; c = read (); } while (!isSpaceChar (c)); return res * sgn; } public long nextLong(){ int c = read (); while (isSpaceChar (c)) c = read (); int sgn = 1; if (c == '-'){ sgn = -1; c = read (); } long res = 0; do{ if (c < '0' || c > '9'){ throw new InputMismatchException (); } res *= 10; res += c - '0'; c = read (); } while (!isSpaceChar (c)); return res * sgn; } public String nextString(){ int c = read (); while (isSpaceChar (c)) c = read (); StringBuilder res = new StringBuilder (); do{ res.appendCodePoint (c); c = read (); } while (!isSpaceChar (c)); return res.toString (); } public boolean isSpaceChar(int c){ if (filter != null){ return filter.isSpaceChar (c); } return isWhitespace (c); } public static boolean isWhitespace(int c){ return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0(){ StringBuilder buf = new StringBuilder (); int c = read (); while (c != '\n' && c != -1){ if (c != '\r'){ buf.appendCodePoint (c); } c = read (); } return buf.toString (); } public String nextLine(){ String s = readLine0 (); while (s.trim ().length () == 0) s = readLine0 (); return s; } public String nextLine(boolean ignoreEmptyLines){ if (ignoreEmptyLines){ return nextLine (); }else{ return readLine0 (); } } public BigInteger nextBigInteger(){ try{ return new BigInteger (nextString ()); } catch (NumberFormatException e){ throw new InputMismatchException (); } } public char nextCharacter(){ int c = read (); while (isSpaceChar (c)) c = read (); return (char) c; } public double nextDouble(){ int c = read (); while (isSpaceChar (c)) c = read (); int sgn = 1; if (c == '-'){ sgn = -1; c = read (); } double res = 0; while (!isSpaceChar (c) && c != '.'){ if (c == 'e' || c == 'E'){ return res * Math.pow (10, nextInt ()); } if (c < '0' || c > '9'){ throw new InputMismatchException (); } res *= 10; res += c - '0'; c = read (); } if (c == '.'){ c = read (); double m = 1; while (!isSpaceChar (c)){ if (c == 'e' || c == 'E'){ return res * Math.pow (10, nextInt ()); } if (c < '0' || c > '9'){ throw new InputMismatchException (); } m /= 10; res += (c - '0') * m; c = read (); } } return res * sgn; } public boolean isExhausted(){ int value; while (isSpaceChar (value = peek ()) && value != -1) read (); return value == -1; } public String next(){ return nextString (); } public SpaceCharFilter getFilter(){ return filter; } public void setFilter(SpaceCharFilter filter){ this.filter = filter; } public interface SpaceCharFilter{ public boolean isSpaceChar(int ch); } } class Pair implements Comparable<Pair>{ public int a; public int b; public Pair(){ this.a = 0; this.b = 0; } public Pair(int a,int b){ this.a = a; this.b = b; } public int compareTo(Pair p){ if(this.a == p.a){ return this.b - p.b; } return this.a - p.a; } @Override public String toString(){ return "a = " + this.a + " b = " + this.b; } }
gpl-3.0
jagornet/dhcp
Jagornet-DHCP/dhcp-server/src/main/java/com/jagornet/dhcp/server/rest/api/ObjectMapperContextResolver.java
619
package com.jagornet.dhcp.server.rest.api; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import com.fasterxml.jackson.databind.ObjectMapper; @Provider public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> { private final ObjectMapper mapper; public ObjectMapperContextResolver() { this.mapper = createObjectMapper(); } @Override public ObjectMapper getContext(Class<?> type) { return mapper; } private ObjectMapper createObjectMapper() { return new JacksonObjectMapper().getJsonObjectMapper(); } }
gpl-3.0
chrisvdweth/onespace
android-application/app/src/main/java/com/sesame/onespace/network/CornerMarkerLoader.java
13688
package com.sesame.onespace.network; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.ListView; import com.google.android.gms.maps.model.LatLngBounds; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import com.sesame.onespace.R; import com.sesame.onespace.managers.chat.ChatHistoryManager; import com.sesame.onespace.models.chat.Chat; import com.sesame.onespace.models.map.Corner; import com.sesame.onespace.models.map.FilterMarkerNode; import com.sesame.onespace.service.MessageService; import com.sesame.onespace.service.xmpp.Tools; import com.sesame.onespace.utils.Log; import com.sesame.onespace.views.adapters.CornerListAdapter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import retrofit.Call; import retrofit.Callback; import retrofit.GsonConverterFactory; import retrofit.Response; import retrofit.RxJavaCallAdapterFactory; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; /** * Created by chongos on 11/16/15 AD. */ public class CornerMarkerLoader extends MapMarkerLoader implements CornerListAdapter.OnCornerListInteractionListener { private Call callOtherCorners; private Call callMyCorners; private Multimap<String, String> mapFilterAndID; private List<String> listVisibleCategories; private RecyclerView recyclerView; private CornerListAdapter listAdapter; private LatLngBounds lastBounds; private int lastLimit; private String userID; public CornerMarkerLoader(Context context, OneSpaceApi.Service api, com.squareup.otto.Bus bus) { super(context, api, bus); mapFilterAndID = ArrayListMultimap.create(); listVisibleCategories = new ArrayList<>(); } public void setRecyclerView(RecyclerView recyclerView) { this.recyclerView = recyclerView; LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); listAdapter = new CornerListAdapter(context); listAdapter.setOnCornerListInteractionListener(this); this.recyclerView.setOverScrollMode(ListView.OVER_SCROLL_NEVER); this.recyclerView.setLayoutManager(linearLayoutManager); this.recyclerView.setAdapter(listAdapter); notifyMyCornerChanged(); } public void setUserID(String userID) { this.userID = userID; } public void notifyMyCornerChanged() { fetchMyCorner(); } public void delete(final Corner corner) { new AlertDialog.Builder(context) .setTitle("Delete Corner") .setMessage(context.getString(R.string.alert_confirm_delete_corner)) .setPositiveButton(context.getString(R.string.confirm_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteCorner(corner); } }) .setNegativeButton(context.getString(R.string.confirm_no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } private void deleteCorner(final Corner corner) { if(listAdapter != null) listAdapter.deleteCorner(corner); deleteCornerFromServer(corner); deleteCornerFromMap(corner); new AsyncTask<Void, Void, Chat>() { @Override protected Chat doInBackground(Void... params) { Chat chat = null; try{ chat = ChatHistoryManager.getInstance(context).getChat(corner.getRoomJid()); } catch (NullPointerException e) { } return chat; } @Override protected void onPostExecute(Chat chat) { super.onPostExecute(chat); if(chat != null) Tools.sendToService(context, MessageService.ACTION_XMPP_GROUP_LEAVE, chat); } }.execute(); } private void deleteCornerFromServer(final Corner corner) { Observable<String> observable = new OneSpaceApi.Builder(context) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build() .deleteCorner(corner.getCreatorId(), corner.getRoomJid()); observable.observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<String>() { @Override public void onCompleted() { Log.i("Delete completed."); } @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onNext(String s) { Log.i("Delete corner : " + s); } }); } public void deleteCornerFromMap(final Corner corner) { new AsyncTask<Void, Void, ArrayList<Object>>() { @Override protected ArrayList<Object> doInBackground(Void... params) { markerHashMap.remove(String.valueOf(corner.getId())); mapFilterAndID.remove(corner.isMine() ? context.getString(R.string.display_corners_my) : context.getString(R.string.display_corners_other) , corner.getId()); ArrayList<Object> corners = new ArrayList<>(); corners.add(corner); return corners; } @Override protected void onPostExecute(ArrayList<Object> objects) { super.onPostExecute(objects); publishRemoveResult(objects); } }.execute(); } @Override public void setFilter(FilterMarkerNode filter) { super.setFilter(filter); for(int i=0; i<filter.getSubCategorySize(); i++) { FilterMarkerNode sub = filter.getSubCategory(i); if (sub.isSelected()) { listVisibleCategories.add(sub.getName()); } } } @Override public void fetch(LatLngBounds bounds, int limit) { this.lastBounds = bounds; this.lastLimit = limit; if(!filter.isSelected()) return; if(listVisibleCategories.contains(context.getString(R.string.display_corners_other))) fetchOtherCorner(bounds, limit); if(userID != null && listVisibleCategories.contains(context.getString(R.string.display_corners_my))) fetchMyCorner(); } @Override public void onFilterChange(final FilterMarkerNode filterMarkerNode) { if(filterMarkerNode.equals(filter)) { if(filterMarkerNode.isSelected()) { new AsyncTask<Void, Void, ArrayList<Object>>() { @Override protected ArrayList<Object> doInBackground(Void... params) { ArrayList<Object> corners = new ArrayList<>(); for(String visibleCategory : listVisibleCategories) { Collection<String> addCorners = mapFilterAndID.get(visibleCategory); for (String addCornerID : addCorners) { Object aCorner = markerHashMap.get(addCornerID); corners.add(aCorner); } } return corners; } @Override protected void onPostExecute(ArrayList<Object> objects) { super.onPostExecute(objects); publishAddResult(objects); } }.execute(); } else { super.onFilterChange(filterMarkerNode); } } else { new AsyncTask<Void, Void, ArrayList<Object>>() { @Override protected ArrayList<Object> doInBackground(Void... params) { ArrayList<Object> corners = new ArrayList<>(); Collection<String> addCorners = mapFilterAndID.get(filterMarkerNode.getName()); for (String addCornerID : addCorners) { Object aPlace = markerHashMap.get(addCornerID); corners.add(aPlace); } return corners; } @Override protected void onPostExecute(ArrayList<Object> objects) { super.onPostExecute(objects); if (filterMarkerNode.isSelected()) { listVisibleCategories.add(filterMarkerNode.getName()); publishAddResult(objects); if(lastBounds != null) fetch(lastBounds, lastLimit); } else { listVisibleCategories.remove(filterMarkerNode.getName()); publishRemoveResult(objects); } } }.execute(); } } private void fetchMyCorner() { if(callMyCorners != null) callMyCorners.cancel(); callMyCorners = api.getCorners(userID); callMyCorners.enqueue(getCallback(context.getString(R.string.display_corners_my))); } private void fetchOtherCorner(LatLngBounds bounds, int limit) { if(callOtherCorners != null) callOtherCorners.cancel(); callOtherCorners = api.getCorners(bounds.northeast.latitude, bounds.northeast.longitude, bounds.southwest.latitude, bounds.southwest.longitude, limit); callOtherCorners.enqueue(getCallback(context.getString(R.string.display_corners_other))); } private Callback getCallback(final String filterName) { return new Callback<ArrayList<Corner>>() { @Override public void onResponse(final Response<ArrayList<Corner>> response) { if (response.isSuccess()) { new AsyncTask<Void, Void, ArrayList<Object>>() { @Override protected ArrayList<Object> doInBackground(Void... params) { ArrayList<Object> corners = new ArrayList<>(); for (Corner corner : response.body()) { String creatorID = corner.getCreatorId(); String id = String.valueOf(corner.getId()); corner.setIsMine(filterName.equals(context.getString(R.string.display_corners_my))); if ((filterName.equals(context.getString(R.string.display_corners_other)) && !creatorID.equals(userID)) || filterName.equals(context.getString(R.string.display_corners_my))) { if (!markerHashMap.containsKey(id)) { markerHashMap.put(id, corner); mapFilterAndID.put(filterName, id); corners.add(corner); } } } return corners; } @Override protected void onPostExecute(ArrayList<Object> objects) { super.onPostExecute(objects); if(filter.isSelected() && listVisibleCategories.contains(filterName)) publishAddResult(objects); if(listAdapter != null && filterName.equals(context.getString(R.string.display_corners_my))) { for(Object obj : objects) listAdapter.addCorner((Corner) obj); } } }.execute(); } } @Override public void onFailure(Throwable t) { android.util.Log.e("GetMyCorners", t.toString()); } }; } @Override public void onOpenChat(Corner corner) { String roomId = corner.getRoomJid().split("@")[0]; String roomName = corner.getName(); Intent i = new Intent(MessageService.ACTION_XMPP_GROUP_JOIN, null, context, MessageService.class); i.putExtra(MessageService.KEY_BUNDLE_GROUP_ROOM_JID, roomId); i.putExtra(MessageService.KEY_BUNDLE_GROUP_NAME, roomName); MessageService.sendToServiceHandler(i); } @Override public void onDelete(Corner corner) { delete(corner); } }
gpl-3.0
ckaestne/LEADT
workspace/argouml_diagrams/argouml-app/src/org/argouml/uml/ui/UMLDerivedCheckBox.java
2072
// $Id: UMLDerivedCheckBox.java 13702 2007-11-04 00:11:25Z tfmorris $ // Copyright (c) 2003-2007 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.uml.ui; import org.argouml.model.Facade; /** * Class to represent a checkbox for the derived tagged value. * * @author tfmorris */ public class UMLDerivedCheckBox extends UMLTaggedValueCheckBox { /** * The constructor. * */ public UMLDerivedCheckBox() { // TODO: This is a tagged value name which will never trigger an event super(Facade.DERIVED_TAG); } }
gpl-3.0
Nauja/Minecraft-NaujaModManager
org/minecraftnauja/manager/version/Version.java
4421
package org.minecraftnauja.manager.version; /** * A version is identified by a compatibility version, a major version and a * minor version. The compatibility version is used to determine which API * version id compatible. */ public final class Version implements Comparable<Version> { /** * All versions. */ public static final Version ALL = new Version(0, 0, 0, Modifier.Release); /** * Parses the specified input to returns corresponding version. * * @param s * the input to parse. * @return corresponding version. * @throws VersionFormatException * the input has an invalid format. */ public static Version parse(String s) throws VersionFormatException { if (s == null) { throw new NullPointerException(s); } else if (s.equals("*")) { return ALL; } else { try { Modifier m = Modifier.Release; final int i = s.indexOf('-'); if (i > 0) { m = Modifier.parse(s.substring(i + 1)); s = s.substring(0, i); } final String[] parts = s.split("[.]"); final int revision = parts.length == 3 ? Integer .parseInt(parts[2]) : 0; return new Version(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), revision, m); } catch (final Exception e) { throw VersionFormatException.forInputString(s); } } } /** * The major version. */ private final int major; /** * The minor version. */ private final int minor; /** * The revision version. */ private final int revision; /** * The modifier. */ private final Modifier modifier; /** * Initialising constructor. * * @param major * the major version. * @param minor * the minor version. * @param revision * the revision version. * @param modifier * the modifier. */ public Version(final int major, final int minor, final int revision, final Modifier modifier) { super(); this.major = major; this.minor = minor; this.revision = revision; this.modifier = modifier; } /** * Gets the major version. * * @return the major version. */ public int getMajor() { return major; } /** * Gets the minor version. * * @return the minor version. */ public int getMinor() { return minor; } /** * Gets the revision version. * * @return the revision version. */ public int getRevision() { return revision; } /** * Gets the modifier. * * @return the modifier. */ public Modifier getModifier() { return modifier; } /** * {@inheritDoc} */ @Override public int compareTo(final Version other) { if (this == ALL || other == ALL) { return 0; } int c = modifier.compareTo(other.modifier); if (c != 0) { return c; } c = major - other.major; if (c != 0) { return c; } c = minor - other.minor; if (c != 0) { return c; } return revision - other.revision; } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + major; result = prime * result + minor; result = prime * result + ((modifier == null) ? 0 : modifier.hashCode()); result = prime * result + revision; return result; } /** * {@inheritDoc} */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Version other = (Version) obj; if (this == ALL || other == ALL) { return true; } if (major != other.major) { return false; } if (minor != other.minor) { return false; } if (modifier != other.modifier) { return false; } if (revision != other.revision) { return false; } return true; } /** * {@inheritDoc} */ @Override public String toString() { if (this == ALL) { return "*"; } else { final StringBuilder sb = new StringBuilder(); sb.append(Integer.toString(major)); sb.append('.'); sb.append(Integer.toString(minor)); sb.append('.'); sb.append(revision); if (modifier != Modifier.Release) { sb.append('-'); sb.append(modifier); } return sb.toString(); } } }
gpl-3.0
JujuYuki/AdeptCraft
src/main/java/fr/jujuyuki/adeptcraft/init/Recipes.java
401
package fr.jujuyuki.adeptcraft.init; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.oredict.ShapedOreRecipe; public class Recipes { public static void init() { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModBlocks.psyStone), "sss", "sss", "sss", 's', new ItemStack(ModItems.psyCrystal))); } }
gpl-3.0
4Space/4Space-5
src/main/java/micdoodle8/mods/galacticraft/core/items/ItemPickaxeGC.java
954
package micdoodle8.mods.galacticraft.core.items; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import micdoodle8.mods.galacticraft.core.GalacticraftCore; import micdoodle8.mods.galacticraft.core.proxy.ClientProxyCore; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.EnumRarity; import net.minecraft.item.ItemPickaxe; import net.minecraft.item.ItemStack; public class ItemPickaxeGC extends ItemPickaxe { public ItemPickaxeGC(String assetName) { super(GCItems.TOOL_STEEL); this.setUnlocalizedName(assetName); this.setTextureName(GalacticraftCore.TEXTURE_PREFIX + assetName); } @Override public CreativeTabs getCreativeTab() { return GalacticraftCore.galacticraftItemsTab; } @Override @SideOnly(Side.CLIENT) public EnumRarity getRarity(ItemStack par1ItemStack) { return ClientProxyCore.galacticraftItem; } }
gpl-3.0
afollestad/polar-dashboard
app/src/main/java/com/afollestad/polar/util/WallpaperUtils.java
15421
package com.afollestad.polar.util; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.preference.PreferenceManager; import android.support.annotation.ColorInt; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.v4.content.FileProvider; import android.util.Log; import android.widget.Toast; import com.afollestad.ason.AsonIgnore; import com.afollestad.assent.Assent; import com.afollestad.bridge.Bridge; import com.afollestad.bridge.BridgeException; import com.afollestad.bridge.Callback; import com.afollestad.bridge.Request; import com.afollestad.bridge.Response; import com.afollestad.bridge.annotations.ContentType; import com.afollestad.inquiry.Inquiry; import com.afollestad.inquiry.annotations.Column; import com.afollestad.inquiry.annotations.Table; import com.afollestad.materialdialogs.MaterialDialog; import com.afollestad.polar.BuildConfig; import com.afollestad.polar.R; import com.afollestad.polar.fragments.WallpapersFragment; import java.io.File; import java.io.Serializable; import java.util.Locale; /** @author Aidan Follestad (afollestad) */ public class WallpaperUtils { private static final String DATABASE_NAME = "data_cache"; private static final int DATABASE_VERSION = 1; public interface WallpapersCallback { void onRetrievedWallpapers(WallpapersHolder wallpapers, Exception error, boolean cancelled); } @ContentType("application/json") public static class WallpapersHolder implements Serializable { public Wallpaper get(int index) { return wallpapers[index]; } public int length() { return wallpapers != null ? wallpapers.length : 0; } public Wallpaper[] wallpapers; @SuppressWarnings("unused") public WallpapersHolder() {} WallpapersHolder(Wallpaper[] wallpapers) { this.wallpapers = wallpapers; } } @Table(name = "polar_wallpapers") @ContentType("application/json") public static class Wallpaper implements Serializable { public Wallpaper() {} @SuppressWarnings("unused") @AsonIgnore @Column(primaryKey = true, notNull = true, autoIncrement = true) public long _id; @Column public String author; @Column public String url; @Column public String name; @Column public String thumbnail; public String getListingImageUrl() { return thumbnail != null ? thumbnail : url; } @Column private int paletteNameColor; @Column private int paletteAuthorColor; @Column private int paletteBgColor; public void setPaletteNameColor(@ColorInt int color) { this.paletteNameColor = color; } @ColorInt public int getPaletteNameColor() { return paletteNameColor; } public void setPaletteAuthorColor(@ColorInt int color) { this.paletteAuthorColor = color; } @ColorInt public int getPaletteAuthorColor() { return paletteAuthorColor; } public void setPaletteBgColor(@ColorInt int color) { this.paletteBgColor = color; } @ColorInt public int getPaletteBgColor() { return paletteBgColor; } public boolean isPaletteComplete() { return paletteNameColor != 0 && paletteAuthorColor != 0 && paletteBgColor != 0; } } @SuppressLint({"CommitPrefEdits", "ApplySharedPref"}) public static boolean didExpire(Context context) { final long NOW = System.currentTimeMillis(); final String UPDATE_TIME_KEY = "wallpaper_last_update_time"; final String LAST_UPDATE_VERSION_KEY = "wallpaper_last_update_version"; final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final long LAST_UPDATE = prefs.getLong(UPDATE_TIME_KEY, -1); final long INTERVAL = 24 * 60 * 60 * 1000; // every 24 hours if (LAST_UPDATE == -1 || NOW >= (LAST_UPDATE + INTERVAL)) { Log.d( "WallpaperUtils", "Cache invalid: never updated, or it's been 24 hours since last update."); // Never updated before, or it's been at least 24 hours prefs.edit().putLong(UPDATE_TIME_KEY, NOW).commit(); return true; } else if (prefs.getInt(LAST_UPDATE_VERSION_KEY, -1) != BuildConfig.VERSION_CODE) { Log.d("WallpaperUtils", "App was updated, wallpapers cache is invalid."); prefs.edit().putInt(LAST_UPDATE_VERSION_KEY, BuildConfig.VERSION_CODE).commit(); return true; } Log.d("WallpaperUtils", "Cache is still valid."); return false; } public static WallpapersHolder getAll(final Context context, boolean allowCached) throws Exception { final String iname = "get_walldb_instance"; Inquiry.newInstance(context, DATABASE_NAME) .databaseVersion(DATABASE_VERSION) .instanceName(iname) .build(); try { if (allowCached) { Wallpaper[] cache = Inquiry.get(iname).select(Wallpaper.class).all(); if (cache != null && cache.length > 0) { Log.d("WallpaperUtils", String.format("Loaded %d wallpapers from cache.", cache.length)); return new WallpapersHolder(cache); } } else { Inquiry.get(iname).delete(Wallpaper.class).run(); } } catch (Throwable t) { t.printStackTrace(); return null; } try { WallpapersHolder holder = Bridge.get(context.getString(R.string.wallpapers_json_url)) .tag(WallpapersFragment.class.getName()) .asClass(WallpapersHolder.class); if (holder == null) { throw new Exception("No wallpapers returned."); } Log.d("WallpaperUtils", String.format("Loaded %d wallpapers from web.", holder.length())); if (holder.length() > 0) { try { Inquiry.get(iname).insert(Wallpaper.class).values(holder.wallpapers).run(); } catch (Throwable t) { t.printStackTrace(); } } return holder; } catch (Exception e1) { Log.d("WallpaperUtils", String.format("Failed to load wallpapers... %s", e1.getMessage())); throw e1; } finally { Inquiry.destroy(iname); } } public static void saveDb( @Nullable final Context context, @Nullable final WallpapersHolder holder) { if (context == null || holder == null || holder.length() == 0) { return; } final String iname = "save_walldb_instance"; Inquiry.newInstance(context, DATABASE_NAME) .databaseVersion(DATABASE_VERSION) .instanceName(iname) .build(); try { Inquiry.get(iname).delete(Wallpaper.class).run(); Inquiry.get(iname) .insert(Wallpaper.class) .values(holder.wallpapers) .run(changed -> Inquiry.destroy(iname)); } catch (Throwable t) { t.printStackTrace(); } } public static void getAll( final Context context, boolean allowCached, final WallpapersCallback callback) { final String iname = "save_walldb_instance2"; Inquiry.newInstance(context, DATABASE_NAME) .databaseVersion(DATABASE_VERSION) .instanceName(iname) .build(); try { if (allowCached) { Wallpaper[] cache = Inquiry.get(iname).select(Wallpaper.class).all(); if (cache != null && cache.length > 0) { Log.d("WallpaperUtils", String.format("Loaded %d wallpapers from cache.", cache.length)); callback.onRetrievedWallpapers(new WallpapersHolder(cache), null, false); return; } } else { Inquiry.get(iname).delete(Wallpaper.class).run(); } } catch (Throwable t) { t.printStackTrace(); } Bridge.get(context.getString(R.string.wallpapers_json_url)) .tag(WallpapersFragment.class.getName()) .asClass( WallpapersHolder.class, (response, holder, e) -> { if (e != null) { callback.onRetrievedWallpapers( null, e, e.reason() == BridgeException.REASON_REQUEST_CANCELLED); } else { if (holder == null) { callback.onRetrievedWallpapers( null, new Exception("No wallpapers returned."), false); return; } try { for (Wallpaper wallpaper : holder.wallpapers) { if (wallpaper.name == null) { wallpaper.name = ""; } if (wallpaper.author == null) { wallpaper.author = ""; } } Log.d( "WallpaperUtils", String.format("Loaded %d wallpapers from web.", holder.length())); if (holder.length() > 0) { try { Inquiry.get(iname).insert(Wallpaper.class).values(holder.wallpapers).run(); } catch (Throwable t) { t.printStackTrace(); } } callback.onRetrievedWallpapers(holder, null, false); } catch (Throwable e1) { Log.d( "WallpaperUtils", String.format("Failed to load wallpapers... %s", e1.getMessage())); if (e1 instanceof Exception) { callback.onRetrievedWallpapers(null, (Exception) e1, false); } } finally { Inquiry.destroy(iname); } } }); } @SuppressLint("StaticFieldLeak") private static Activity contextCache; private static Wallpaper wallpaperCache; private static boolean applyCache; private static File fileCache; private static Toast toast; private static void showToast(Context context, @StringRes int msg) { showToast(context, context.getString(msg)); } private static void showToast(Context context, String msg) { if (toast != null) { toast.cancel(); } toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT); toast.show(); } public static void download( final Activity context, final Wallpaper wallpaper, final boolean apply) { contextCache = context; wallpaperCache = wallpaper; applyCache = apply; if (!Assent.isPermissionGranted(Assent.WRITE_EXTERNAL_STORAGE) && !apply) { Assent.requestPermissions( permissionResultSet -> { if (permissionResultSet.isGranted(Assent.WRITE_EXTERNAL_STORAGE)) { download(contextCache, wallpaperCache, applyCache); } else { Toast.makeText(context, R.string.write_storage_permission_denied, Toast.LENGTH_LONG) .show(); } }, 69, Assent.WRITE_EXTERNAL_STORAGE); return; } File saveFolder; final String name; final String extension = wallpaper.url.toLowerCase(Locale.getDefault()).endsWith(".png") ? "png" : "jpg"; if (apply) { // Crop/Apply saveFolder = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? context.getCacheDir() : context.getExternalCacheDir(); name = String.format( "%s_%s_wallpaper.%s", wallpaper.name.replace(" ", "_"), wallpaper.author.replace(" ", "_"), extension); } else { // Save saveFolder = new File(Environment.getExternalStorageDirectory(), context.getString(R.string.app_name)); name = String.format( "%s_%s.%s", wallpaper.name.replace(" ", "_"), wallpaper.author.replace(" ", "_"), extension); } //noinspection ResultOfMethodCallIgnored saveFolder.mkdirs(); fileCache = new File(saveFolder, name); if (!fileCache.exists()) { final MaterialDialog dialog = new MaterialDialog.Builder(context) .content(R.string.downloading_wallpaper) .progress(true, -1) .cancelable(true) .cancelListener( dialogInterface -> { if (contextCache != null && !contextCache.isFinishing()) { showToast(contextCache, R.string.download_cancelled); } Bridge.cancelAll().tag(WallpaperUtils.class.getName()).commit(); }) .show(); Bridge.get(wallpaper.url) .tag(WallpaperUtils.class.getName()) .request( new Callback() { @Override public void response(Request request, Response response, BridgeException e) { if (e != null) { dialog.dismiss(); if (e.reason() == BridgeException.REASON_REQUEST_CANCELLED) { return; } Utils.showError(context, e); } else { try { response.asFile(fileCache); finishOption(contextCache, apply, dialog); } catch (BridgeException e1) { dialog.dismiss(); Utils.showError(context, e1); } } } }); } else { finishOption(context, apply, null); } } private static void finishOption( final Activity context, boolean apply, @Nullable final MaterialDialog dialog) { if (!apply) { MediaScannerConnection.scanFile( context, new String[] {fileCache.getAbsolutePath()}, null, (path, uri) -> { Log.i("WallpaperScan", "Scanned " + path + ":"); Log.i("WallpaperScan", "-> uri = " + uri); }); } if (apply) { // Apply if (dialog != null) { dialog.dismiss(); } Uri uri; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { uri = FileProvider.getUriForFile( context, BuildConfig.APPLICATION_ID + ".fileProvider", fileCache); } else { uri = Uri.fromFile(fileCache); } final Intent intent = new Intent(Intent.ACTION_ATTACH_DATA) .setDataAndType(uri, "image/*") .putExtra("mimeType", "image/*") .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); context.startActivity( Intent.createChooser(intent, context.getString(R.string.set_wallpaper_using))); } else { // Save if (dialog != null) { dialog.dismiss(); } showToast(context, context.getString(R.string.saved_to_x, fileCache.getAbsolutePath())); resetOptionCache(false); } } @SuppressWarnings("ResultOfMethodCallIgnored") public static void resetOptionCache(boolean delete) { contextCache = null; wallpaperCache = null; applyCache = false; if (delete && fileCache != null) { fileCache.delete(); final File[] contents = fileCache.getParentFile().listFiles(); if (contents != null && contents.length > 0) { fileCache.getParentFile().delete(); } } } private WallpaperUtils() {} }
gpl-3.0
danielhuson/dendroscope3
src/dendroscope/commands/SetMagDisplacementCommand.java
3434
/* * SetMagDisplacementCommand.java Copyright (C) 2020 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dendroscope.commands; import dendroscope.window.TreeViewer; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Iterator; /** * Daniel Huson, 4.2011 */ public class SetMagDisplacementCommand extends CommandBaseMultiViewer implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Set Magnification Displacement..."; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the displacement of the magnifier"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it * * @param np * @throws java.io.IOException */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set magdisplacement="); double value = np.getDouble(0.50000, 1); if (value <= 0.5) value = 0.50000001; if (value > 1) value = 0.99999999; np.matchIgnoreCase(";"); for (Iterator<TreeViewer> it = multiViewer.getTreeGrid().getSelectedOrAllIterator(); it.hasNext(); ) { TreeViewer viewer = it.next(); viewer.trans.getMagnifier().setDisplacement(value); viewer.repaint(); } } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set magdisplacement=<float>;"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } /** * action to be performed * * @param ev */ @Override public void actionPerformed(ActionEvent ev) { System.err.println("Please enter on command-line"); } }
gpl-3.0
ENGYS/HELYX-OS
src/eu/engys/gui/casesetup/boundaryconditions/panels/GeneralTensorTable.java
7515
/******************************************************************************* * | o | * | o o | HELYX-OS: The Open Source GUI for OpenFOAM | * | o O o | Copyright (C) 2012-2016 ENGYS | * | o o | http://www.engys.com | * | o | | * |---------------------------------------------------------------------------| * | License | * | This file is part of HELYX-OS. | * | | * | HELYX-OS is free software; you can redistribute it and/or modify it | * | under the terms of the GNU General Public License as published by the | * | Free Software Foundation; either version 2 of the License, or (at your | * | option) any later version. | * | | * | HELYX-OS is distributed in the hope that it will be useful, but WITHOUT | * | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | * | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License | * | for more details. | * | | * | You should have received a copy of the GNU General Public License | * | along with HELYX-OS; if not, write to the Free Software Foundation, | * | Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA | *******************************************************************************/ package eu.engys.gui.casesetup.boundaryconditions.panels; import static eu.engys.util.RegexpUtils.ATMOSPHERIC_PATTERN; import static eu.engys.util.RegexpUtils.DOUBLE; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import org.apache.commons.lang.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import eu.engys.core.dictionary.Dictionary; import eu.engys.core.dictionary.parser.ListField2; import eu.engys.core.modules.AbstractChart; import eu.engys.core.project.system.monitoringfunctionobjects.TimeBlocks; import eu.engys.gui.casesetup.DictionaryTableAndChartPanel; public class GeneralTensorTable extends DictionaryTableAndChartPanel { private static final Logger logger = LoggerFactory.getLogger(GeneralTensorTable.class); public static final String DISTANCE_M_LABEL = "Distance [m]"; public static final String VALUE_VAR = "Value"; public static final String TITLE = "General Table"; private String[] columnNames; private String key; public GeneralTensorTable(String key, String label, String[] columnNames) { super(label, label, DISTANCE_M_LABEL, "", true, columnNames); this.key = key; this.columnNames = columnNames; } @Override protected AbstractChart createChart(String domainAxisLabel, String rangeAxisLabel) { return null; } public void load(Dictionary dictionary) { if (dictionary.found(key)) { if (dictionary.isList2(key)) { // // Fix for alpha1 which is read with DictionaryReader2 this.data = toObject(ListField2.convertToString(dictionary.getList2(key))); } else { this.data = toObject(dictionary.lookup(key).trim()); } } loadTableAndChart(); } @Override protected Object[] getEmptyRowData() { return new Object[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; } @Override protected TableModel createTableModel() { DefaultTableModel tableModel = new DefaultTableModel(data, ArrayUtils.add(columnNames, 0, DISTANCE_M_LABEL)) { @Override public Class<?> getColumnClass(int columnIndex) { return Double.class; } @Override public boolean isCellEditable(int row, int column) { return true; } }; return tableModel; } @Override protected TimeBlocks convertTableDataToTimeBlocks() { TimeBlocks tbs = new TimeBlocks(); return tbs; } @Override public void saveOnDialogClose() { TableModel tableModel = table.getModel(); Double[][] data = new Double[tableModel.getRowCount()][tableModel.getColumnCount()]; for (int row = 0; row < tableModel.getRowCount(); row++) { for (int col = 0; col < tableModel.getColumnCount(); col++) { // use table here because it is ordered data[row][col] = (Double) table.getValueAt(row, col); } } this.data = data; } public void save(Dictionary dictionary) { String value = toPrimitive(); dictionary.add(key, value); } @Override protected String toPrimitive() { StringBuilder sb = new StringBuilder(); sb.append("( "); if(data != null){ for (int i = 0; i < data.length; i++) { Double[] row = data[i]; Double time = row[0].doubleValue(); Double xx = row[1].doubleValue(); Double xy = row[2].doubleValue(); Double xz = row[3].doubleValue(); Double yy = row[4].doubleValue(); Double yz = row[5].doubleValue(); Double zz = row[6].doubleValue(); sb.append("( " + time + " ( " + xx + " " + xy + " " + xz + " " + yy + " " + yz + " " + zz + " ) ) "); } } sb.append(")"); return sb.toString(); } @Override protected Double[][] toObject(String tableData) { List<Double[]> rows = new ArrayList<>(); if (tableData.startsWith("(") && tableData.endsWith(")")) { tableData = tableData.substring(1, tableData.length() - 1).trim(); try { Pattern regex = Pattern.compile(ATMOSPHERIC_PATTERN); Matcher regexMatcher = regex.matcher(tableData); while (regexMatcher.find()) { rows.add(parseRows(regexMatcher.group(0))); } } catch (PatternSyntaxException ex) { logger.error("Parsing error: {}", ex.getMessage()); } } return rows.toArray(new Double[0][0]); } private Double[] parseRows(String row) { Pattern innerRegex = Pattern.compile(DOUBLE); Matcher innerRegexMatcher = innerRegex.matcher(row); Double[] values = new Double[7]; int internalCount = 0; while (innerRegexMatcher.find()) { values[internalCount++] = Double.parseDouble(innerRegexMatcher.group(0)); } return values; } }
gpl-3.0
desces/Essentials
EssentialsUpdate/src/org/jibble/pircbot/InputThread.java
6156
/* Copyright Paul James Mutton, 2001-2009, http://www.jibble.org/ This file is part of PircBot. This software is dual-licensed, allowing you to choose between the GNU General Public License (GPL) and the www.jibble.org Commercial License. Since the GPL may be too restrictive for use in a proprietary application, a commercial license is also provided. Full license information can be found at http://www.jibble.org/licenses/ */ package org.jibble.pircbot; import java.io.*; import java.net.Socket; import java.util.StringTokenizer; /** * A Thread which reads lines from the IRC server. It then * passes these lines to the PircBot without changing them. * This running Thread also detects disconnection from the server * and is thus used by the OutputThread to send lines to the server. * * @author Paul James Mutton, * <a href="http://www.jibble.org/">http://www.jibble.org/</a> * @version 1.5.0 (Build time: Mon Dec 14 20:07:17 2009) */ public class InputThread extends Thread { /** * The InputThread reads lines from the IRC server and allows the * PircBot to handle them. * * @param bot An instance of the underlying PircBot. * @param breader The BufferedReader that reads lines from the server. * @param bwriter The BufferedWriter that sends lines to the server. */ InputThread(PircBot bot, Socket socket, BufferedReader breader, BufferedWriter bwriter) { _bot = bot; _socket = socket; _breader = breader; _bwriter = bwriter; this.setName(this.getClass() + "-Thread"); } /** * Sends a raw line to the IRC server as soon as possible, bypassing the * outgoing message queue. * * @param line The raw line to send to the IRC server. */ void sendRawLine(String line) { OutputThread.sendRawLine(_bot, _bwriter, line); } /** * Returns true if this InputThread is connected to an IRC server. * The result of this method should only act as a rough guide, * as the result may not be valid by the time you act upon it. * * @return True if still connected. */ boolean isConnected() { return _isConnected; } /** * Called to start this Thread reading lines from the IRC server. * When a line is read, this method calls the handleLine method * in the PircBot, which may subsequently call an 'onXxx' method * in the PircBot subclass. If any subclass of Throwable (i.e. * any Exception or Error) is thrown by your method, then this * method will print the stack trace to the standard output. It * is probable that the PircBot may still be functioning normally * after such a problem, but the existance of any uncaught exceptions * in your code is something you should really fix. */ public void run() { try { boolean running = true; while (running) { try { String line = null; while ((line = _breader.readLine()) != null) { try { _bot.handleLine(line); } catch (Throwable t) { // Stick the whole stack trace into a String so we can output it nicely. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); StringTokenizer tokenizer = new StringTokenizer(sw.toString(), "\r\n"); synchronized (_bot) { _bot.log("### Your implementation of PircBot is faulty and you have"); _bot.log("### allowed an uncaught Exception or Error to propagate in your"); _bot.log("### code. It may be possible for PircBot to continue operating"); _bot.log("### normally. Here is the stack trace that was produced: -"); _bot.log("### "); while (tokenizer.hasMoreTokens()) { _bot.log("### " + tokenizer.nextToken()); } } } } if (line == null) { // The server must have disconnected us. running = false; } } catch (InterruptedIOException iioe) { // This will happen if we haven't received anything from the server for a while. // So we shall send it a ping to check that we are still connected. this.sendRawLine("PING " + (System.currentTimeMillis() / 1000)); // Now we go back to listening for stuff from the server... } } } catch (Exception e) { // Do nothing. } // If we reach this point, then we must have disconnected. try { _socket.close(); } catch (Exception e) { // Just assume the socket was already closed. } if (!_disposed) { _bot.log("*** Disconnected."); _isConnected = false; _bot.onDisconnect(); } } /** * Closes the socket without onDisconnect being called subsequently. */ public void dispose () { try { _disposed = true; _socket.close(); } catch (Exception e) { // Do nothing. } } private PircBot _bot = null; private Socket _socket = null; private BufferedReader _breader = null; private BufferedWriter _bwriter = null; private boolean _isConnected = true; private boolean _disposed = false; public static final int MAX_LINE_LENGTH = 512; }
gpl-3.0
sapia-oss/corus
modules/server/src/main/java/org/sapia/corus/os/NativeProcessFactory.java
444
package org.sapia.corus.os; import org.sapia.corus.util.OsUtil; /** * A factory of {@link NativeProcess} instance. * * @author Yanick Duchesne */ public class NativeProcessFactory { /** * @return a NativeProcess instance corresponding to the OS. */ public static NativeProcess newNativeProcess() { if (OsUtil.isWindowsFamily()) { return new WindowsProcess(); } else { return new UnixProcess(); } } }
gpl-3.0
zeminlu/comitaco
tests/icse/binomialheap/set5/BinomialHeapExtractMin1Bug1D.java
13793
package icse.binomialheap.set5; import icse.binomialheap.BinomialHeapNode; public class BinomialHeapExtractMin1Bug1D { /*@ @ invariant (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, sibling + child).has(n); n.parent != null ==> n.key >= n.parent.key ); @ invariant (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, sibling + child).has(n); n.sibling != null ==> \reach(n.sibling, BinomialHeapNode, sibling + child).has(n) == false ); @ invariant (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, sibling + child).has(n); n.child != null ==> \reach(n.child, BinomialHeapNode, sibling + child).has(n) == false ); @ invariant (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, sibling + child).has(n); ( n.child != null && n.sibling != null ) ==> @ (\forall BinomialHeapNode m; \reach(n.child, BinomialHeapNode, child + sibling).has(m); \reach(n.sibling, BinomialHeapNode, child + sibling).has(m) == false) ); @ invariant (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, sibling + child).has(n); ( n.child != null && n.sibling != null ) ==> @ (\forall BinomialHeapNode m; \reach(n.sibling, BinomialHeapNode, child + sibling).has(m); \reach(n.child, BinomialHeapNode, child + sibling).has(m) == false) ); @ invariant (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, sibling + child).has(n); n.degree >= 0 ); @ invariant (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, sibling + child).has(n); n.child == null ==> n.degree == 0 ); @ invariant (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, sibling + child).has(n); n.child != null ==> n.degree == \reach(n.child, BinomialHeapNode, sibling).int_size() ); @ invariant (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, sibling + child).has(n); n.child != null ==> \reach(n.child.child, BinomialHeapNode, child + sibling).int_size() == \reach(n.child.sibling, BinomialHeapNode, child + sibling).int_size() ); @ invariant (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, sibling + child).has(n); n.child != null ==> @ ( \forall BinomialHeapNode m; \reach(n.child, BinomialHeapNode, sibling).has(m); m.parent == n ) ); @ invariant (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, sibling + child).has(n); ( n.sibling != null && n.parent != null ) ==> n.degree > n.sibling.degree ); @ @ invariant this.size == \reach(Nodes, BinomialHeapNode, sibling + child).int_size(); @ @ invariant ( \forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, sibling).has(n); (n.sibling != null ==> n.degree < n.sibling.degree) && (n.parent == null) ); @ @ invariant ( \forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, sibling).has(n); n.key >= 0 ); @ @*/ public /*@ nullable @*/icse.binomialheap.BinomialHeapNode Nodes; public int size; public BinomialHeapExtractMin1Bug1D() { } /*@ @ requires true; @ ensures (\forall BinomialHeapNode n; \old(\reach(Nodes, BinomialHeapNode, child + sibling)).has(n); \reach(Nodes, BinomialHeapNode, child + sibling).has(n) && \old(n.key) == n.key); @ ensures value > 0 ==> (\exists BinomialHeapNode n; !\old(\reach(Nodes, BinomialHeapNode, child + sibling)).has(n); \reach(Nodes, BinomialHeapNode, child + sibling).has(n) && n.key == value); @ ensures value > 0 ==> size == \old(size) + 1; @ signals (Exception e) false; @ @*/ public void insert( int value ) { if (value > 0) { icse.binomialheap.BinomialHeapNode insertTemp = new icse.binomialheap.BinomialHeapNode(); insertTemp.key = value; if (Nodes == null) { Nodes = insertTemp; size = 1; } else { icse.binomialheap.BinomialHeapNode temp1 = Nodes; icse.binomialheap.BinomialHeapNode temp2 = insertTemp; //@decreasing \reach(temp2, BinomialHeapNode, sibling).int_size(); while (temp1 != null && temp2 != null) { if (temp1.degree == temp2.degree) { icse.binomialheap.BinomialHeapNode tmp = temp2; temp2 = temp2.sibling; tmp.sibling = temp1.sibling; temp1.sibling = tmp; temp1 = tmp.sibling; } else { if (temp1.degree < temp2.degree) { if (temp1.sibling == null || temp1.sibling.degree > temp2.degree) { icse.binomialheap.BinomialHeapNode tmp = temp2; temp2 = temp2.sibling; tmp.sibling = temp1.sibling; temp1.sibling = tmp; temp1 = tmp.sibling; } else { temp1 = temp1.sibling; } } else { icse.binomialheap.BinomialHeapNode tmp = temp1; temp1 = temp2; temp2 = temp2.sibling; temp1.sibling = tmp; if (tmp == Nodes) { Nodes = temp1; } } } } if (temp1 == null) { temp1 = Nodes; //@decreasing \reach(temp1, BinomialHeapNode, sibling).int_size(); while (temp1.sibling != null) { temp1 = temp1.sibling; } temp1.sibling = temp2; } icse.binomialheap.BinomialHeapNode prevTemp = null; icse.binomialheap.BinomialHeapNode temp = Nodes; icse.binomialheap.BinomialHeapNode nextTemp = Nodes.sibling; //@decreasing \reach(temp, BinomialHeapNode, sibling).int_size(); while (nextTemp != null) { if (temp.degree != nextTemp.degree || nextTemp.sibling != null && nextTemp.sibling.degree == temp.degree) { prevTemp = temp; temp = nextTemp; } else { if (temp.key <= nextTemp.key) { temp.sibling = nextTemp.sibling; nextTemp.parent = temp; nextTemp.sibling = temp.child; temp.child = nextTemp; temp.degree++; } else { if (prevTemp == null) { Nodes = nextTemp; } else { prevTemp.sibling = nextTemp; } temp.parent = nextTemp; temp.sibling = nextTemp.child; nextTemp.child = temp; nextTemp.degree++; temp = nextTemp; } } nextTemp = temp.sibling; } size++; } } } /*@ requires true; @ ensures \old(Nodes) != null ==> \old(\reach(Nodes, BinomialHeapNode, child + sibling)).has(\result); @ ensures (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, child + sibling).has(n); \result.key <= n.key); @ ensures (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, child + sibling).has(n); \old(n.key) == n.key); @*/ public /* @ nullable @ */icse.binomialheap.BinomialHeapNode extractMin() { if (Nodes.child == this.Nodes) { //mutGenLimit 0 return null; } icse.binomialheap.BinomialHeapNode temp = Nodes; icse.binomialheap.BinomialHeapNode prevTemp = null; icse.binomialheap.BinomialHeapNode minNode = null; minNode = Nodes.findMinNode(); //@decreasing \reach(temp, BinomialHeapNode, sibling).int_size(); while (temp.key != minNode.key) { prevTemp = temp; temp = temp.sibling; } if (prevTemp == null) { Nodes = temp.sibling; } else { prevTemp.sibling = temp.sibling; } temp = temp.child; icse.binomialheap.BinomialHeapNode fakeNode = temp; //@decreasing \reach(temp, BinomialHeapNode, sibling).int_size(); while (temp != null) { temp.parent = null; temp = temp.sibling; } if (Nodes == null && fakeNode == null) { size = 0; } else { if (Nodes == null && fakeNode != null) { Nodes = fakeNode.reverse( null ); size--; } else { if (Nodes != null && fakeNode == null) { size--; } else { unionNodes( fakeNode.reverse( null ) ); size--; } } } return minNode; } // 3. Unite two binomial heaps // helper procedure private void merge( /* @ nullable @ */icse.binomialheap.BinomialHeapNode binHeap ) { icse.binomialheap.BinomialHeapNode temp1 = Nodes; icse.binomialheap.BinomialHeapNode temp2 = binHeap; while (temp1 != null && temp2 != null) { if (temp1.degree == temp2.degree) { icse.binomialheap.BinomialHeapNode tmp = temp2; temp2 = temp2.sibling; tmp.sibling = temp1.sibling; temp1.sibling = tmp; temp1 = tmp.sibling; } else { if (temp1.degree < temp2.degree) { if (temp1.sibling == null || temp1.sibling.degree > temp2.degree) { icse.binomialheap.BinomialHeapNode tmp = temp2; temp2 = temp2.sibling; tmp.sibling = temp1.sibling; temp1.sibling = tmp; temp1 = tmp.sibling; } else { temp1 = temp1.sibling; } } else { icse.binomialheap.BinomialHeapNode tmp = temp1; temp1 = temp2; temp2 = temp2.sibling; temp1.sibling = tmp; if (tmp == Nodes) { Nodes = temp1; } } } } if (temp1 == null) { temp1 = Nodes; while (temp1.sibling != null) { temp1 = temp1.sibling; } temp1.sibling = temp2; } } // another helper procedure private void unionNodes( /* @ nullable @ */icse.binomialheap.BinomialHeapNode binHeap ) { merge( binHeap ); icse.binomialheap.BinomialHeapNode prevTemp = null; icse.binomialheap.BinomialHeapNode temp = Nodes; icse.binomialheap.BinomialHeapNode nextTemp = Nodes.sibling; while (nextTemp != null) { if (temp.degree != nextTemp.degree || nextTemp.sibling != null && nextTemp.sibling.degree == temp.degree) { prevTemp = temp; temp = nextTemp; } else { if (temp.key <= nextTemp.key) { temp.sibling = nextTemp.sibling; nextTemp.parent = temp; nextTemp.sibling = temp.child; temp.child = nextTemp; temp.degree++; } else { if (prevTemp == null) { Nodes = nextTemp; } else { prevTemp.sibling = nextTemp; } temp.parent = nextTemp; temp.sibling = nextTemp.child; nextTemp.child = temp; nextTemp.degree++; temp = nextTemp; } } nextTemp = temp.sibling; } } /*@ requires Nodes != null; @ ensures (\exists BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, child + sibling).has(n); n.key == \result); @ ensures (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, child + sibling).has(n); \result <= n.key); @ ensures (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, child + sibling).has(n); \old(n.key) == n.key); @ ensures (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, child + sibling).has(n); \old(n.degree) == n.degree); @ ensures (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, child + sibling).has(n); \old(n.parent) == n.parent); @ ensures (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, child + sibling).has(n); \old(n.sibling) == n.sibling); @ ensures (\forall BinomialHeapNode n; \reach(Nodes, BinomialHeapNode, child + sibling).has(n); \old(n.child) == n.child); @ signals (Exception e) false; @*/ public int findMinimum() { icse.binomialheap.BinomialHeapNode x = Nodes; icse.binomialheap.BinomialHeapNode y = Nodes; int min = x.key; //@decreasing \reach(x, BinomialHeapNode, sibling).int_size(); while (x != null) { if (x.key < min) { y = x; min = x.key; } x = x.sibling; } return y.key; } }
gpl-3.0
wogua/LJAndroidStudy
app/src/main/java/com/lijun/androidstudy/launcher/LJLauncher.java
19056
package com.lijun.androidstudy.launcher; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu; import com.lijun.androidstudy.R; import com.lijun.androidstudy.plugin.PluginLocalManager; import com.lijun.androidstudy.util.PhotoUtils; import com.lijun.androidstudy.util.Utilities; import com.lijun.viewexplosion.ExplosionField; import com.lijun.viewexplosion.factory.ParticleFactory; import android.Manifest; import android.content.BroadcastReceiver; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.util.AttributeSet; import android.util.Log; import android.util.Xml; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.graphics.BitmapFactory; import android.widget.Toast; public class LJLauncher extends Activity implements View.OnClickListener { private static String TAG = "LJMain"; public static String[] sAllPermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.BLUETOOTH}; public static final int REQUEST_PERMISSION_ALL = 0;//add for checkAllPermission public static boolean sExpolosionMode = false; private LayoutInflater mInflater; private String TAG_WORKSPACE = "cells"; View mLauncherView = null; LJWorkSpace mWorkspace = null; ArrayList<LJCellInfo> mCellInfos = null; static final int ROWS = 4;//行数 static final int COLUMNS = 4;//列数 int screenWidth = 0; private int cellSize = 0; private int screens = 0; private View slideMenuView; private ListView slideMenuLlistView; int[] mSlideStyles; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.launcher); checkPermission(); mLauncherView = (View) findViewById(R.id.launcher); mWorkspace = (LJWorkSpace) findViewById(R.id.workspace); mInflater = getLayoutInflater(); initSlidingMenu(); bindWorkspace(); registerBroadcastReceiver(); } public void registerBroadcastReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction("com.lijun.androidstudy.EXPLOSION_CHANGED"); registerReceiver(mBroadcastReceiver, filter); } private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals("com.lijun.androidstudy.EXPLOSION_CHANGED")) { boolean isOpened = intent.getBooleanExtra("opened",false); onExpolosionChanged(isOpened); } } }; private void onExpolosionChanged(boolean isOpened) { Log.d("PluginLocalManager","currentThread 3 : " + Thread.currentThread()); if (isOpened) { Toast.makeText(getApplicationContext(), "Explosion Mode Opened", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Explosion Mode Closed", Toast.LENGTH_LONG).show(); } sExpolosionMode = isOpened; if (mWorkspace != null && mWorkspace.getChildCount() > 0) { for (int i = 0; i < mWorkspace.getChildCount(); i++) { LJCellLayout ljCellLayout = (LJCellLayout) mWorkspace.getChildAt(i); for (int j = 0; j < ljCellLayout.getChildCount(); j++) { LJCellView cellView = (LJCellView) ljCellLayout.getChildAt(j); LJCellInfo cellInfo = cellView.getmCellInfo(); if (isOpened&&!"com.lijun.viewexplosion.test.TestViewExplosionActivity".equals(cellInfo.className)) { ExplosionField explosionField = new ExplosionField(this, ParticleFactory.getRandomParticle(j)/*new FallingParticleFactory()*/); explosionField.addListener(cellView); } else { cellView.setOnClickListener(this); } } } } } @Override public void onClick(View v) { // TODO Auto-generated method stub if (v instanceof LJCellView) { LJCellView cv = (LJCellView) v; LJCellInfo cellInfo = cv.getmCellInfo(); Log.i(TAG, "onClick v : " + cv.getTitle()); if(cellInfo.isPlugin){ PluginLocalManager.startPluginActivity(this,cv); }else if (cv.intent != null) { startActivitySafety(cv.intent); } } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mBroadcastReceiver); } @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub menu.add(0, 1, 0, R.string.scroll_style_classics_title); menu.add(0, 2, 0, R.string.scroll_style_cube_title); menu.add(0, 3, 0, R.string.scroll_style_columnar_title); menu.add(0, 4, 0, R.string.scroll_style_sphere_title); menu.add(0, 5, 0, R.string.scroll_style_3drota_title); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub int style = 1; switch (item.getItemId()) { case 1: style = LJWorkSpace.SCROLL_STYLE_CLASSICS; break; case 2: style = LJWorkSpace.SCROLL_STYLE_CUBE; break; case 3: style = LJWorkSpace.SCROLL_STYLE_COLUMNAR; break; case 4: style = LJWorkSpace.SCROLL_STYLE_SPHERE; break; case 5: style = LJWorkSpace.SCROLL_STYLE_3DROTA; break; } setScrollStyle(style); return true; } private void bindWorkspace() { Log.e(TAG, "bindWorkspace"); mCellInfos = (ArrayList<LJCellInfo>) loadCellsFromXml(R.xml.workspace); if (mCellInfos == null || mCellInfos.size() == 0) { Log.e(TAG, "no cell"); return; } cellSize = mCellInfos.size(); screens = (cellSize % (ROWS * COLUMNS) == 0) ? cellSize / (ROWS * COLUMNS) : (cellSize / (ROWS * COLUMNS) + 1); for (int i = 0; i < screens; i++) { LJCellLayout cellLaout = new LJCellLayout(this); int start = i * ROWS * COLUMNS; int end = (i + 1) * ROWS * COLUMNS - 1; end = end > (cellSize - 1) ? (cellSize - 1) : end; for (int j = start; j <= end; j++) { LJCellView cellView = createLJCellView(cellLaout, mCellInfos.get(j)); ///for view explosion example cellLaout.addView(cellView); } mWorkspace.addView(cellLaout); } mWorkspace.invalidate(); } private List<LJCellInfo> loadCellsFromXml(int resourceId) { List<LJCellInfo> cells = new ArrayList<LJCellInfo>(); Resources res = getResources(); try { XmlResourceParser parser = getResources().getXml(resourceId); AttributeSet attrs = Xml.asAttributeSet(parser); beginDocument(parser, TAG_WORKSPACE); final int depth = parser.getDepth(); Bitmap maskBitmap = BitmapFactory.decodeResource(res, R.drawable.ic_mask); Bitmap bgBitmap = BitmapFactory.decodeResource(res, R.drawable.ic_bg); Bitmap zoomTemp = BitmapFactory.decodeResource(res, R.drawable.ic_zoom_template); int tempW = zoomTemp.getWidth(); int tempH = zoomTemp.getHeight(); int type; while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } LJCellInfo cell = new LJCellInfo(); TypedArray a = obtainStyledAttributes(attrs, R.styleable.Cell); final String name = parser.getName(); Log.d(TAG, "cell name : " + name); cell.name = a.getString(R.styleable.Cell_name); cell.className = a.getString(R.styleable.Cell_className); cell.packageName = a.getString(R.styleable.Cell_packageName); cell.isPlugin = a.getBoolean(R.styleable.Cell_isPlugin,false); // cell.icon = PhotoUtils.zoom(BitmapFactory.decodeResource(res, a.getResourceId(R.styleable.Cell_icon, 0)), tempW, tempH); cell.icon = PhotoUtils.compositeByBitmap(BitmapFactory.decodeResource(res, a.getResourceId(R.styleable.Cell_icon, 0)),maskBitmap,bgBitmap,zoomTemp,false); // cell.icon = BitmapFactory.decodeResource(res, a.getResourceId(R.styleable.Cell_icon, 0)); cells.add(cell); a.recycle(); } } catch (XmlPullParserException e) { // TODO Auto-generated catch block Log.w(TAG, "Got exception parsing cells.", e); } catch (IOException e) { // TODO Auto-generated catch block Log.w(TAG, "Got exception parsing cells.", e); } catch (RuntimeException e) { Log.w(TAG, "Got exception parsing cells.", e); } return cells; } private static final void beginDocument(XmlPullParser parser, String firstElementName) throws XmlPullParserException, IOException { int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { ; } if (type != XmlPullParser.START_TAG) { throw new XmlPullParserException("No start tag found"); } if (!parser.getName().equals(firstElementName)) { throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() + ", expected " + firstElementName); } } private LJCellView createLJCellView(ViewGroup parent, LJCellInfo cellInfo) { LJCellView cellView = (LJCellView) mInflater.inflate(R.layout.cell_layout, parent, false); cellView.setmCellInfo(cellInfo); cellView.setOnClickListener(this); return cellView; } private boolean startActivitySafety(Intent intent) { try { startActivity(intent); return true; } catch (ActivityNotFoundException ex) { android.util.Log.d(TAG, "ActivityNotFoundException"); return false; } } public int getScrollStyle() { if (mWorkspace != null) { return mWorkspace.mScrollStyle; } else { return LJWorkSpace.SCROLL_STYLE_CLASSICS; } } public void setScrollStyle(int style) { switch (style) { case LJWorkSpace.SCROLL_STYLE_CLASSICS: case LJWorkSpace.SCROLL_STYLE_CUBE: case LJWorkSpace.SCROLL_STYLE_3DROTA: break; case LJWorkSpace.SCROLL_STYLE_COLUMNAR: break; case LJWorkSpace.SCROLL_STYLE_SPHERE: break; default: break; } mWorkspace.scrollStyleChanged(style); SharedPreferences sp = getSharedPreferences("LJLauncher", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putInt(LJWorkSpace.SCROLL_STYLE_KEY, style); editor.commit(); } class SlideMenuListAdapter extends BaseAdapter { private List<Map<String, Object>> data; private LayoutInflater layoutInflater; private Context context; public SlideMenuListAdapter(Context context, List<Map<String, Object>> data) { this.context = context; this.data = data; this.layoutInflater = LayoutInflater.from(context); } final class SlideMenuItem { ImageView slideMenuItemIconView; TextView slideMenuItemTextView; int slideStyle; } @Override public int getCount() { // TODO Auto-generated method stub return data.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return data.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub SlideMenuItem itemLayout = null; if (convertView == null) { itemLayout = new SlideMenuItem(); convertView = mInflater.inflate(R.layout.slide_menu_list_item, null); itemLayout.slideMenuItemIconView = (ImageView) convertView.findViewById(R.id.slide_menu_icon); itemLayout.slideMenuItemTextView = (TextView) convertView.findViewById(R.id.slide_menu_title); itemLayout.slideStyle = mSlideStyles[position]; convertView.setTag(itemLayout); convertView.setOnClickListener(mSlidingMenuItemClick); } else { itemLayout = (SlideMenuItem) convertView.getTag(); } itemLayout.slideMenuItemIconView.setImageResource((Integer) data.get(position).get("icon")); itemLayout.slideMenuItemTextView.setText((String) data.get(position).get("title")); return convertView; } } public List<Map<String, Object>> getData() { int[] icons = Utilities.getIds(this.getResources(), R.array.slide_menu_icons); String[] titles = this.getResources().getStringArray( R.array.slide_menu_titles); mSlideStyles = this.getResources().getIntArray(R.array.slide_menu_values); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (int i = 0; i < icons.length; i++) { Map<String, Object> map = new HashMap<String, Object>(); map.put("icon", icons[i]); map.put("title", titles[i]); list.add(map); } return list; } private View.OnClickListener mSlidingMenuItemClick = new View.OnClickListener() { @Override public void onClick(View v) { SlideMenuListAdapter.SlideMenuItem itemLayout = (SlideMenuListAdapter.SlideMenuItem) v.getTag(); setScrollStyle(itemLayout.slideStyle); } }; public void initSlidingMenu() { LayoutInflater inflater = LayoutInflater.from(this); slideMenuView = inflater.inflate(R.layout.slide_menu, (ViewGroup) mLauncherView, false); slideMenuLlistView = (ListView) slideMenuView.findViewById(R.id.slide_menu_list); List<Map<String, Object>> data = getData(); slideMenuLlistView.setAdapter(new SlideMenuListAdapter(this, data)); SlidingMenu localSlidingMenu = new SlidingMenu(this); localSlidingMenu.setMode(SlidingMenu.LEFT);//设置左右滑菜单 localSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);//设置要使菜单滑动,触碰屏幕的范围 //localSlidingMenu.setTouchModeBehind(SlidingMenu.RIGHT); localSlidingMenu.setShadowWidthRes(R.dimen.sliding_menu_shadow_width);//设置阴影图片的宽度 localSlidingMenu.setShadowDrawable(R.drawable.shadow);//设置阴影图片 localSlidingMenu.setBehindOffsetRes(R.dimen.sliding_menu_behind_offset);//设置划出时主页面显示的剩余宽度 localSlidingMenu.setFadeEnabled(true);//设置滑动时菜单的是否渐变 localSlidingMenu.setFadeDegree(0.35F);//设置滑动时的渐变程度 localSlidingMenu.attachToActivity(this, SlidingMenu.RIGHT);//使SlidingMenu附加在Activity右边 // localSlidingMenu.setBehindWidthRes(R.dimen.left_drawer_avatar_size);//设置SlidingMenu菜单的宽度 localSlidingMenu.setMenu(slideMenuView);//设置menu的布局文件 // localSlidingMenu.toggle();//动态判断自动关闭或开启SlidingMenu localSlidingMenu.setOnOpenedListener(new SlidingMenu.OnOpenedListener() { public void onOpened() { } }); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if(requestCode == REQUEST_PERMISSION_ALL){//lijun add for checkAllPermission if (grantResults.length > 0) { } } } private void checkPermission() { List<String> noOkPermissions = new ArrayList<>(); for (String permission : sAllPermissions) { if (ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_DENIED) { noOkPermissions.add(permission); } } if (noOkPermissions.size() <= 0) return; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(noOkPermissions.toArray(new String[noOkPermissions.size()]), REQUEST_PERMISSION_ALL); } } }
gpl-3.0
MyPictures/NoCheatPlus
NCPCore/src/main/java/fr/neatmonster/nocheatplus/command/CommandUtil.java
4187
package fr.neatmonster.nocheatplus.command; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandMap; import org.bukkit.command.SimpleCommandMap; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import fr.neatmonster.nocheatplus.NCPAPIProvider; import fr.neatmonster.nocheatplus.checks.CheckType; import fr.neatmonster.nocheatplus.logging.LogUtil; public class CommandUtil { /** * Return plugin + server commands [Subject to change]. * @return Returns null if not CraftBukkit or CommandMap not available. */ public static CommandMap getCommandMap() { try { return NCPAPIProvider.getNoCheatPlusAPI().getMCAccess().getCommandMap(); } catch (Throwable t) { LogUtil.logSevere(t); return null; } } /** * Get all Command instances, that NCP can get hold of. Attempt to get a SimpleCommandMap instance from the server to get the actually registered commands, but also get commands from JavaPlugin instances. * @return */ public static Collection<Command> getCommands() { final Collection<Command> commands = new LinkedHashSet<Command>(500); // All (?) commands from the SimpleCommandMap of the server, if available. final CommandMap commandMap = getCommandMap(); if (commandMap != null && commandMap instanceof SimpleCommandMap) { commands.addAll(((SimpleCommandMap) commandMap).getCommands()); } // TODO: Fall-back for Vanilla / CB commands? [Fall-back should be altering permission defaults, though negating permissions is the right way.] // Fall-back: plugin commands. for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { if (plugin instanceof JavaPlugin) { final JavaPlugin javaPlugin = (JavaPlugin) plugin; final Map<String, Map<String, Object>> map = javaPlugin.getDescription().getCommands(); if (map != null) { for (String label : map.keySet()) { Command command = javaPlugin.getCommand(label); if (command != null) { commands.add(command); } } } } } return commands; } /** * Get the command label (trim + lower case), include server commands [subject to change]. * @param alias * @param strict If to return null if no command is found. * @return The command label, if possible to find, or the alias itself (+ trim + lower-case). */ public static String getCommandLabel(final String alias, final boolean strict) { final Command command = getCommand(alias); if (command == null) { return strict ? null : alias.trim().toLowerCase(); } else { return command.getLabel().trim().toLowerCase(); } } /** * Get a command, include server commands [subject to change]. * @param alias * @return */ public static Command getCommand(final String alias) { final String lcAlias = alias.trim().toLowerCase(); final CommandMap map = getCommandMap(); if (map != null) { return map.getCommand(lcAlias); } else { // TODO: maybe match versus plugin commands. return null; } } /** * Match for CheckType, some smart method, to also match after first "_" for convenience of input. * @param input * @return */ public static List<String> getCheckTypeTabMatches(final String input) { final String ref = input.toUpperCase().replace('-', '_').replace('.', '_'); final List<String> res = new ArrayList<String>(); for (final CheckType checkType : CheckType.values()) { final String name = checkType.name(); if (name.startsWith(ref)) { res.add(name); } } if (ref.indexOf('_') == -1) { for (final CheckType checkType : CheckType.values()) { final String name = checkType.name(); final String[] split = name.split("_", 2); if (split.length > 1 && split[1].startsWith(ref)) { res.add(name); } } } if (!res.isEmpty()) { Collections.sort(res); return res; } return null; } }
gpl-3.0
asgarth/swiftle
src/org/swiftle/ui/util/IconUtils.java
851
package org.swiftle.ui.util; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.program.Program; import org.snow.util.cache.ImageCache; import org.swiftle.network.Entry; import org.swiftle.util.FileUtils; public class IconUtils { /** Utility class, prevent instantiation */ private IconUtils() { } public static Image getIcon( final Entry entry ) { if( entry.isDirectory() ) return getDirectoryIcon(); final Program program = Program.findProgram( FileUtils.getFilenameExtension( entry.getName() ) ); if( program == null || program.getImageData() == null ) return ImageCache.getInstance().getImage( "./resources/themes/unknown.png" ); return ImageCache.getInstance().getIcon( program ); } public static Image getDirectoryIcon() { return ImageCache.getInstance().getImage( "./resources/themes/folder.png" ); } }
gpl-3.0
guiguilechat/EveOnline
model/sde/SDE-Types/src/generated/java/fr/guiguilechat/jcelechat/model/sde/attributes/RoleBonus.java
774
package fr.guiguilechat.jcelechat.model.sde.attributes; import fr.guiguilechat.jcelechat.model.sde.IntAttribute; /** * */ public class RoleBonus extends IntAttribute { public static final RoleBonus INSTANCE = new RoleBonus(); @Override public int getId() { return 2091; } @Override public int getCatId() { return 9; } @Override public boolean getHighIsGood() { return true; } @Override public double getDefaultValue() { return 0.0; } @Override public boolean getPublished() { return false; } @Override public boolean getStackable() { return true; } @Override public String toString() { return "RoleBonus"; } }
gpl-3.0
daftano/dl-learner
components-core/src/main/java/org/dllearner/kb/extraction/ObjectPropertyNode.java
7248
/** * Copyright (C) 2007-2011, Jens Lehmann * * This file is part of DL-Learner. * * DL-Learner is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * DL-Learner is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.dllearner.kb.extraction; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.dllearner.kb.aquisitors.RDFBlankNode; import org.dllearner.kb.aquisitors.TupleAquisitor; import org.dllearner.kb.manipulator.Manipulator; import org.dllearner.utilities.datastructures.RDFNodeTuple; import org.dllearner.utilities.owl.OWLVocabulary; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAnnotation; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassExpression; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLObjectProperty; /** * Property node, has connection to a and b part * * @author Sebastian Hellmann * */ public class ObjectPropertyNode extends PropertyNode { // specialtypes like owl:symmetricproperty private SortedSet<String> specialTypes = new TreeSet<String>(); private SortedSet<RDFNodeTuple> propertyInformation = new TreeSet<RDFNodeTuple>(); private List<BlankNode> blankNodes = new ArrayList<BlankNode>(); public ObjectPropertyNode(String propertyURI, Node a, Node b) { super(propertyURI, a, b); } // Property Nodes are normally not expanded, // this function is never called @Override public List<Node> expand(TupleAquisitor tupelAquisitor, Manipulator manipulator) { return null; } // gets the types for properties recursively @Override public List<BlankNode> expandProperties(TupleAquisitor tupelAquisitor, Manipulator manipulator, boolean dissolveBlankNodes) { List<BlankNode> ret = new ArrayList<BlankNode>(); ret.addAll(b.expandProperties(tupelAquisitor, manipulator, dissolveBlankNodes)); SortedSet<RDFNodeTuple> newTypes = tupelAquisitor.getTupelForResource(uri); for (RDFNodeTuple tuple : newTypes) { try { if (tuple.a.toString().equals(OWLVocabulary.RDF_TYPE)) { if(!tuple.b.toString().equals(OWLVocabulary.OWL_OBJECTPROPERTY)){ specialTypes.add(tuple.b.toString()); } }else if(tuple.b.isAnon()){ if(dissolveBlankNodes){ RDFBlankNode n = (RDFBlankNode) tuple.b; BlankNode tmp = new BlankNode( n, tuple.a.toString()); //add it to the graph blankNodes.add(tmp); ret.add( tmp); } }else{ propertyInformation.add(tuple); } } catch (Exception e) { tail("expand properties: with tuple: "+ tuple); e.printStackTrace(); } } return ret; } @Override public SortedSet<String> toNTriple() { SortedSet<String> s = new TreeSet<String>(); s.add(getNTripleForm()+"<" + OWLVocabulary.RDF_TYPE + "><" + OWLVocabulary.OWL_OBJECTPROPERTY + ">."); for (String one : specialTypes) { s.add(getNTripleForm()+"<" + OWLVocabulary.RDF_TYPE + "><" + one + ">."); } for (RDFNodeTuple one : propertyInformation) { s.add(one.getNTriple(uri)); } return s; } @Override public void toOWLOntology( OWLAPIOntologyCollector owlAPIOntologyCollector){ //FIXME Property information OWLDataFactory factory = owlAPIOntologyCollector.getFactory(); OWLObjectProperty me =factory.getOWLObjectProperty(getIRI()); for (RDFNodeTuple one : propertyInformation) { if(one.aPartContains(OWLVocabulary.RDFS_range)){ OWLClass c = factory.getOWLClass(IRI.create(one.b.toString())); owlAPIOntologyCollector.addAxiom(factory.getOWLObjectPropertyRangeAxiom(me, c)); }else if(one.aPartContains(OWLVocabulary.RDFS_domain)){ OWLClass c = factory.getOWLClass(IRI.create(one.b.toString())); owlAPIOntologyCollector.addAxiom(factory.getOWLObjectPropertyDomainAxiom(me, c)); }else if(one.aPartContains(OWLVocabulary.RDFS_SUB_PROPERTY_OF)){ OWLObjectProperty p = factory.getOWLObjectProperty(IRI.create(one.b.toString())); owlAPIOntologyCollector.addAxiom(factory.getOWLSubObjectPropertyOfAxiom(me, p)); }else if(one.aPartContains(OWLVocabulary.OWL_inverseOf)){ OWLObjectProperty p = factory.getOWLObjectProperty(IRI.create(one.b.toString())); owlAPIOntologyCollector.addAxiom(factory.getOWLInverseObjectPropertiesAxiom(me, p)); }else if(one.aPartContains(OWLVocabulary.OWL_equivalentProperty)){ OWLObjectProperty p = factory.getOWLObjectProperty(IRI.create(one.b.toString())); Set<OWLObjectProperty> tmp = new HashSet<OWLObjectProperty>(); tmp.add(me);tmp.add(p); owlAPIOntologyCollector.addAxiom(factory.getOWLEquivalentObjectPropertiesAxiom(tmp)); }else if(one.a.toString().equals(OWLVocabulary.RDFS_LABEL)){ OWLAnnotation annoLabel = factory.getOWLAnnotation(factory.getRDFSLabel(), factory.getOWLStringLiteral(one.b.toString())); OWLAxiom ax = factory.getOWLAnnotationAssertionAxiom(me.getIRI(), annoLabel); owlAPIOntologyCollector.addAxiom(ax); }else if(one.b.isLiteral()){ // XXX comments } else { tail("conversion to ontology: property information: " + one); } } for (String one : specialTypes) { if(one.equals(OWLVocabulary.OWL_FunctionalProperty)){ owlAPIOntologyCollector.addAxiom(factory.getOWLFunctionalObjectPropertyAxiom(me)); }else if(one.equals(OWLVocabulary.OWL_InverseFunctionalProperty)){ owlAPIOntologyCollector.addAxiom(factory.getOWLInverseFunctionalObjectPropertyAxiom(me)); }else if(one.equals(OWLVocabulary.OWL_TransitiveProperty)){ owlAPIOntologyCollector.addAxiom(factory.getOWLTransitiveObjectPropertyAxiom(me)); }else if(one.equals(OWLVocabulary.OWL_SymmetricProperty)){ owlAPIOntologyCollector.addAxiom(factory.getOWLSymmetricObjectPropertyAxiom(me)); }else{ tail("conversion to ontology: special types: " + one); } } for (BlankNode bn : blankNodes) { OWLClassExpression target = bn.getAnonymousClass(owlAPIOntologyCollector); if(bn.getInBoundEdge().equals(OWLVocabulary.RDFS_range)){ owlAPIOntologyCollector.addAxiom(factory.getOWLObjectPropertyRangeAxiom(me, target)); }else if(bn.getInBoundEdge().equals(OWLVocabulary.RDFS_domain)){ owlAPIOntologyCollector.addAxiom(factory.getOWLObjectPropertyDomainAxiom(me, target)); } //System.out.println(bn.getAnonymousClass(owlAPIOntologyCollector).toString()); } } }
gpl-3.0
aleatorio12/ProVentasConnector
jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/components/map/type/MapTypeEnum.java
1775
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.components.map.type; import net.sf.jasperreports.engine.type.EnumUtil; import net.sf.jasperreports.engine.type.NamedEnum; /** * @author sanda zaharia (shertage@users.sourceforge.net) */ public enum MapTypeEnum implements NamedEnum { /** * The roadmap type */ ROADMAP("roadmap"), /** * The satellite map type */ SATELLITE("satellite"), /** * The terrain map type */ TERRAIN("terrain"), /** * The hybrid type */ HYBRID("hybrid"); /** * */ private final transient String name; private MapTypeEnum(String name) { this.name = name; } /** * */ public String getName() { return name; } /** * */ public static MapTypeEnum getByName(String name) { return EnumUtil.getEnumByName(values(), name); } }
gpl-3.0
adityayadav76/internet_of_things_simulator
AutoSIM-UDP/src/com/automatski/autosim/udp/UDPConnectionFactory.java
1570
/* * AutoSIM - Internet of Things Simulator * Copyright (C) 2014, Aditya Yadav <aditya@automatski.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.automatski.autosim.udp; import com.automatski.autosim.environments.IConnection; import com.automatski.autosim.environments.IConnectionFactory; import com.automatski.autosim.udp.config.AutoSIMConnectionConfig; public class UDPConnectionFactory implements IConnectionFactory{ private AutoSIMConnectionConfig connectionConfig = null; public UDPConnectionFactory(AutoSIMConnectionConfig connectionConfig){ this.connectionConfig = connectionConfig; } @Override public IConnection getConnection() { IConnection connection = null; try { connection = (IConnection) Class.forName(connectionConfig.connectorClassName).newInstance(); connection.setConfig(connectionConfig); } catch (Exception e){ System.out.println(e.getMessage()); } return connection; } }
gpl-3.0
WorldBank-Transport/DRIVER-Android
app/src/main/java/org/worldbank/transport/driver/annotations/ConstantFieldType.java
396
package org.worldbank.transport.driver.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by kat on 1/10/16. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ConstantFieldType { public ConstantFieldTypes value(); }
gpl-3.0
zeatul/poc
e-commerce/e-commerce-ecom-pay-service/src/main/java/com/alipay/api/domain/ReduceToDiscountDstCampPrizeModel.java
1379
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 减至指定折扣奖品模型 * * @author auto create * @since 1.0, 2017-03-03 16:47:49 */ public class ReduceToDiscountDstCampPrizeModel extends AlipayObject { private static final long serialVersionUID = 5683199518175575693L; /** * 折扣预算ID */ @ApiField("budget_id") private String budgetId; /** * 奖品id */ @ApiField("id") private String id; /** * 单次优惠上限(元) */ @ApiField("max_discount_amt") private String maxDiscountAmt; /** * 折扣幅度减至必须为0.3到1之间的小数(保留小数点后2位) */ @ApiField("reduce_to_discount_rate") private String reduceToDiscountRate; public String getBudgetId() { return this.budgetId; } public void setBudgetId(String budgetId) { this.budgetId = budgetId; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getMaxDiscountAmt() { return this.maxDiscountAmt; } public void setMaxDiscountAmt(String maxDiscountAmt) { this.maxDiscountAmt = maxDiscountAmt; } public String getReduceToDiscountRate() { return this.reduceToDiscountRate; } public void setReduceToDiscountRate(String reduceToDiscountRate) { this.reduceToDiscountRate = reduceToDiscountRate; } }
gpl-3.0
bergerkiller/SpigotSource
src/main/java/net/minecraft/server/WorldGenTaiga1.java
4016
package net.minecraft.server; import java.util.Random; public class WorldGenTaiga1 extends WorldGenTreeAbstract { private static final IBlockData a = Blocks.LOG.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.SPRUCE); private static final IBlockData b = Blocks.LEAVES.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.SPRUCE).set(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false)); public WorldGenTaiga1() { super(false); } public boolean generate(World world, Random random, BlockPosition blockposition) { int i = random.nextInt(5) + 7; int j = i - random.nextInt(2) - 3; int k = i - j; int l = 1 + random.nextInt(k + 1); boolean flag = true; if (blockposition.getY() >= 1 && blockposition.getY() + i + 1 <= 256) { int i1; int j1; int k1; for (int l1 = blockposition.getY(); l1 <= blockposition.getY() + 1 + i && flag; ++l1) { boolean flag1 = true; if (l1 - blockposition.getY() < j) { k1 = 0; } else { k1 = l; } BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); for (i1 = blockposition.getX() - k1; i1 <= blockposition.getX() + k1 && flag; ++i1) { for (j1 = blockposition.getZ() - k1; j1 <= blockposition.getZ() + k1 && flag; ++j1) { if (l1 >= 0 && l1 < 256) { if (!this.a(world.getType(blockposition_mutableblockposition.c(i1, l1, j1)).getBlock())) { flag = false; } } else { flag = false; } } } } if (!flag) { return false; } else { Block block = world.getType(blockposition.down()).getBlock(); if ((block == Blocks.GRASS || block == Blocks.DIRT) && blockposition.getY() < 256 - i - 1) { this.a(world, blockposition.down()); k1 = 0; int i2; for (i2 = blockposition.getY() + i; i2 >= blockposition.getY() + j; --i2) { for (i1 = blockposition.getX() - k1; i1 <= blockposition.getX() + k1; ++i1) { j1 = i1 - blockposition.getX(); for (int j2 = blockposition.getZ() - k1; j2 <= blockposition.getZ() + k1; ++j2) { int k2 = j2 - blockposition.getZ(); if (Math.abs(j1) != k1 || Math.abs(k2) != k1 || k1 <= 0) { BlockPosition blockposition1 = new BlockPosition(i1, i2, j2); if (!world.getType(blockposition1).b()) { this.a(world, blockposition1, WorldGenTaiga1.b); } } } } if (k1 >= 1 && i2 == blockposition.getY() + j + 1) { --k1; } else if (k1 < l) { ++k1; } } for (i2 = 0; i2 < i - 1; ++i2) { Material material = world.getType(blockposition.up(i2)).getMaterial(); if (material == Material.AIR || material == Material.LEAVES) { this.a(world, blockposition.up(i2), WorldGenTaiga1.a); } } return true; } else { return false; } } } else { return false; } } }
gpl-3.0
MongoLink/mongolink
mongolink/src/test/java/org/mongolink/domain/mapper/TestsClassMapper.java
2567
/* * MongoLink, Object Document Mapper for Java and MongoDB * * Copyright (c) 2012, Arpinum or third-party contributors as * indicated by the @author tags * * MongoLink is free software: you can redistribute it and/or modify * it under the terms of the Lesser GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MongoLink is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Lesser GNU General Public License for more details. * * You should have received a copy of the Lesser GNU General Public License * along with MongoLink. If not, see <http://www.gnu.org/licenses/>. * */ package org.mongolink.domain.mapper; import org.bson.Document; import org.junit.*; import org.mongolink.test.entity.*; import org.mongolink.test.simpleMapping.*; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class TestsClassMapper { @Before public void before() { FakeAggregateMapping fakeEntityMapping = new FakeAggregateMapping(); CommentMapping commentMapping = new CommentMapping(); context = new MapperContext(); fakeEntityMapping.buildMapper(context); commentMapping.buildMapper(context); } @Test public void canSaveComponent() { FakeAggregate entity = new FakeAggregate("ok"); entity.setComment(new Comment("valeur")); final Document dbObject = entityMapper().toDBObject(entity); assertThat(dbObject.get("comment"), notNullValue()); } @Test public void canConvertFromDBValue() { final Object value = entityMapper().toDbValue(new FakeAggregate("ok")); assertThat(value, instanceOf(Document.class)); } @Test public void canCreateInstanceFromDBValue() { final Document value = new Document(); value.put("value", "test"); final Object instance = entityMapper().fromDbValue(value); assertThat(instance, instanceOf(FakeAggregate.class)); assertThat(((FakeAggregate) instance).getValue(), is("test")); } @Test public void isNotCappedByDefault() { assertThat(entityMapper().isCapped(), is(false)); } private AggregateMapper<FakeAggregate> entityMapper() { return (AggregateMapper<FakeAggregate>) context.mapperFor(FakeAggregate.class); } private MapperContext context; }
gpl-3.0
Boukefalos/jlibredis
src/main/java/redis/clients/jedis/BinaryJedisCommands.java
6538
package redis.clients.jedis; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; /** * Common interface for sharded and non-sharded BinaryJedis */ public interface BinaryJedisCommands { String set(byte[] key, byte[] value); byte[] get(byte[] key); Boolean exists(byte[] key); Long persist(byte[] key); String type(byte[] key); Long expire(byte[] key, int seconds); Long expireAt(byte[] key, long unixTime); Long ttl(byte[] key); Boolean setbit(byte[] key, long offset, boolean value); Boolean setbit(byte[] key, long offset, byte[] value); Boolean getbit(byte[] key, long offset); Long setrange(byte[] key, long offset, byte[] value); byte[] getrange(byte[] key, long startOffset, long endOffset); byte[] getSet(byte[] key, byte[] value); Long setnx(byte[] key, byte[] value); String setex(byte[] key, int seconds, byte[] value); Long decrBy(byte[] key, long integer); Long decr(byte[] key); Long incrBy(byte[] key, long integer); Double incrByFloat(byte[] key, double value); Long incr(byte[] key); Long append(byte[] key, byte[] value); byte[] substr(byte[] key, int start, int end); Long hset(byte[] key, byte[] field, byte[] value); byte[] hget(byte[] key, byte[] field); Long hsetnx(byte[] key, byte[] field, byte[] value); String hmset(byte[] key, Map<byte[], byte[]> hash); List<byte[]> hmget(byte[] key, byte[]... fields); Long hincrBy(byte[] key, byte[] field, long value); Double hincrByFloat(byte[] key, byte[] field, double value); Boolean hexists(byte[] key, byte[] field); Long hdel(byte[] key, byte[]... field); Long hlen(byte[] key); Set<byte[]> hkeys(byte[] key); Collection<byte[]> hvals(byte[] key); Map<byte[], byte[]> hgetAll(byte[] key); Long rpush(byte[] key, byte[]... args); Long lpush(byte[] key, byte[]... args); Long llen(byte[] key); List<byte[]> lrange(byte[] key, long start, long end); String ltrim(byte[] key, long start, long end); byte[] lindex(byte[] key, long index); String lset(byte[] key, long index, byte[] value); Long lrem(byte[] key, long count, byte[] value); byte[] lpop(byte[] key); byte[] rpop(byte[] key); Long sadd(byte[] key, byte[]... member); Set<byte[]> smembers(byte[] key); Long srem(byte[] key, byte[]... member); byte[] spop(byte[] key); Long scard(byte[] key); Boolean sismember(byte[] key, byte[] member); byte[] srandmember(byte[] key); List<byte[]> srandmember(final byte[] key, final int count); Long strlen(byte[] key); Long zadd(byte[] key, double score, byte[] member); Long zadd(byte[] key, Map<byte[], Double> scoreMembers); Set<byte[]> zrange(byte[] key, long start, long end); Long zrem(byte[] key, byte[]... member); Double zincrby(byte[] key, double score, byte[] member); Long zrank(byte[] key, byte[] member); Long zrevrank(byte[] key, byte[] member); Set<byte[]> zrevrange(byte[] key, long start, long end); Set<Tuple> zrangeWithScores(byte[] key, long start, long end); Set<Tuple> zrevrangeWithScores(byte[] key, long start, long end); Long zcard(byte[] key); Double zscore(byte[] key, byte[] member); List<byte[]> sort(byte[] key); List<byte[]> sort(byte[] key, SortingParams sortingParameters); Long zcount(byte[] key, double min, double max); Long zcount(byte[] key, byte[] min, byte[] max); Set<byte[]> zrangeByScore(byte[] key, double min, double max); Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max); Set<byte[]> zrevrangeByScore(byte[] key, double max, double min); Set<byte[]> zrangeByScore(byte[] key, double min, double max, int offset, int count); Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min); Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, int count); Set<byte[]> zrevrangeByScore(byte[] key, double max, double min, int offset, int count); Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max); Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, double min); Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max, int offset, int count); Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min, int offset, int count); Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max); Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min); Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, int offset, int count); Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, double min, int offset, int count); Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, int offset, int count); Long zremrangeByRank(byte[] key, long start, long end); Long zremrangeByScore(byte[] key, double start, double end); Long zremrangeByScore(byte[] key, byte[] start, byte[] end); Long zlexcount(final byte[] key, final byte[] min, final byte[] max); Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max); Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max, int offset, int count); Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min); Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min, int offset, int count); Long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max); Long linsert(byte[] key, Client.LIST_POSITION where, byte[] pivot, byte[] value); Long lpushx(byte[] key, byte[]... arg); Long rpushx(byte[] key, byte[]... arg); /** * @deprecated unusable command, this command will be removed in 3.0.0. */ @Deprecated List<byte[]> blpop(byte[] arg); /** * @deprecated unusable command, this command will be removed in 3.0.0. */ @Deprecated List<byte[]> brpop(byte[] arg); Long del(byte[] key); byte[] echo(byte[] arg); Long move(byte[] key, int dbIndex); Long bitcount(final byte[] key); Long bitcount(final byte[] key, long start, long end); Long pfadd(final byte[] key, final byte[]... elements); long pfcount(final byte[] key); }
gpl-3.0
IntecsSPA/buddata-ebxml-registry
Installer/distribution/bundled-tomcat/apache-tomcat-5.5.28/webapps/servlets-examples/WEB-INF/classes/RequestHeaderExample.java
3190
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /* $Id: RequestHeaderExample.java 466607 2006-10-21 23:09:50Z markt $ * */ import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import util.HTMLFilter; /** * Example servlet showing request headers * * @author James Duncan Davidson <duncan@eng.sun.com> */ public class RequestHeaderExample extends HttpServlet { ResourceBundle rb = ResourceBundle.getBundle("LocalStrings"); public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body bgcolor=\"white\">"); out.println("<head>"); String title = rb.getString("requestheader.title"); out.println("<title>" + title + "</title>"); out.println("</head>"); out.println("<body>"); // all links relative // XXX // making these absolute till we work out the // addition of a PathInfo issue out.println("<a href=\"../reqheaders.html\">"); out.println("<img src=\"../images/code.gif\" height=24 " + "width=24 align=right border=0 alt=\"view code\"></a>"); out.println("<a href=\"../index.html\">"); out.println("<img src=\"../images/return.gif\" height=24 " + "width=24 align=right border=0 alt=\"return\"></a>"); out.println("<h3>" + title + "</h3>"); out.println("<table border=0>"); Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String headerName = (String)e.nextElement(); String headerValue = request.getHeader(headerName); out.println("<tr><td bgcolor=\"#CCCCCC\">"); out.println(HTMLFilter.filter(headerName)); out.println("</td><td>"); out.println(HTMLFilter.filter(headerValue)); out.println("</td></tr>"); } out.println("</table>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } }
gpl-3.0
isnuryusuf/ingress-indonesia-dev
apk/classes-ekstartk/com/nianticproject/ingress/gameentity/components/SimpleLocked.java
270
package com.nianticproject.ingress.gameentity.components; public class SimpleLocked implements Locked { } /* Location: classes_dex2jar.jar * Qualified Name: com.nianticproject.ingress.gameentity.components.SimpleLocked * JD-Core Version: 0.6.2 */
gpl-3.0
ChampionsDev/Champions
library/src/main/java/com/github/championsdev/champions/library/weapon/WeaponRestricted.java
1003
/******************************************************************************* * This file is part of Champions. * * Champions is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Champions is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Champions. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.github.championsdev.champions.library.weapon; /** * @author B2OJustin */ public interface WeaponRestricted { }
gpl-3.0
TeamLocker/Java-GUI-Client
src/main/java/me/camerongray/teamlocker/core/LockerSimpleException.java
409
/* * 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 me.camerongray.teamlocker.core; /** * * @author camerong */ public class LockerSimpleException extends LockerNonFatalException { public LockerSimpleException(String message) { super(message); } }
gpl-3.0
alefq/asistente-eventos
src/main/java/py/gov/senatics/asistente/view/PermisoListMB.java
1403
package py.gov.senatics.asistente.view; import java.util.Iterator; import java.util.List; import javax.inject.Inject; import org.primefaces.model.LazyDataModel; import org.ticpy.tekoporu.annotation.NextView; import org.ticpy.tekoporu.annotation.PreviousView; import org.ticpy.tekoporu.stereotype.ViewController; import org.ticpy.tekoporu.template.AbstractListPageBean; import org.ticpy.tekoporu.transaction.Transactional; import py.gov.senatics.asistente.business.PermisoBC; import py.gov.senatics.asistente.domain.Permiso; @ViewController @NextView("./permiso_edit.jsf") @PreviousView("./permiso_list.jsf") public class PermisoListMB extends AbstractListPageBean<Permiso, Long> { private static final long serialVersionUID = 1L; @Inject private PermisoBC permisoBC; private LazyDataModel<Permiso> model; private int pageSize = 5; // default page size @Override protected List<Permiso> handleResultList() { return this.permisoBC.findAll(); } @Transactional public String deleteSelection() { boolean delete; for (Iterator<Long> iter = getSelection().keySet().iterator(); iter .hasNext();) { Long id = iter.next(); delete = getSelection().get(id); if (delete) { permisoBC.delete(id); iter.remove(); } } return getPreviousView(); } public LazyDataModel<Permiso> getModel() { return model; } public int getPageSize() { return pageSize; } }
gpl-3.0
Letractively/fxlgui
co.fxl.gui.form/src/main/java/co/fxl/gui/toolbar/impl/ScalingToolbarImpl.java
2396
/** * This file is part of FXL GUI API. * * FXL GUI API is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FXL GUI API is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FXL GUI API. If not, see <http://www.gnu.org/licenses/>. * * Copyright (c) 2010-2015 Dangelmayr IT GmbH. All rights reserved. */ package co.fxl.gui.toolbar.impl; import co.fxl.gui.api.IComboBox; import co.fxl.gui.api.IContainer; import co.fxl.gui.api.IFlowPanel; import co.fxl.gui.api.IImage; import co.fxl.gui.api.ILabel; import co.fxl.gui.api.ITextField; import co.fxl.gui.impl.Heights; import co.fxl.gui.toolbar.api.IScalingToolbar; class ScalingToolbarImpl implements IScalingToolbar { private IFlowPanel panel; private String thumbnail; ScalingToolbarImpl(IContainer container) { this(container.panel().flow().spacing(4)); } ScalingToolbarImpl(IFlowPanel panel) { this.panel = panel; } @Override public ICommandButton addButton() { return new ICommandButton() { @Override public IImage image(String resource) { return addImage().resource(resource); } @Override public ILabel text(String text) { return addLabel().text(text); } }; } @Override public IScalingToolbar thumbnail(String imageResource) { thumbnail = imageResource; return this; } @Override public IImage addImage() { return panel.add().image(); } @Override public ILabel addLabel() { return panel.add().label(); } @Override public IScalingToolbar addComposite() { return new ScalingToolbarImpl(panel); } @Override public IComboBox addComboBox() { IComboBox comboBox = panel.add().comboBox(); Heights.INSTANCE.decorate(comboBox); return comboBox; } @Override public ITextField addTextField() { ITextField textField = panel.add().textField(); Heights.INSTANCE.decorate(textField); return textField; } }
gpl-3.0
rubenswagner/L2J-Global
java/com/l2jglobal/gameserver/model/actor/request/SayuneRequest.java
4273
/* * This file is part of the L2J Global project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.l2jglobal.gameserver.model.actor.request; import java.util.Arrays; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Objects; import com.l2jglobal.gameserver.data.xml.impl.SayuneData; import com.l2jglobal.gameserver.enums.SayuneType; import com.l2jglobal.gameserver.model.SayuneEntry; import com.l2jglobal.gameserver.model.actor.instance.L2PcInstance; import com.l2jglobal.gameserver.network.serverpackets.sayune.ExFlyMove; import com.l2jglobal.gameserver.network.serverpackets.sayune.ExFlyMoveBroadcast; import com.l2jglobal.gameserver.util.Broadcast; /** * @author UnAfraid */ public class SayuneRequest extends AbstractRequest { private final int _mapId; private boolean _isSelecting; private final Deque<SayuneEntry> _possibleEntries = new LinkedList<>(); public SayuneRequest(L2PcInstance player, int mapId) { super(player); _mapId = mapId; final SayuneEntry map = SayuneData.getInstance().getMap(_mapId); Objects.requireNonNull(map); _possibleEntries.addAll(map.getInnerEntries()); } @Override public boolean isUsing(int objectId) { return false; } private SayuneEntry findEntry(int pos) { if (_possibleEntries.isEmpty()) { return null; } else if (_isSelecting) { return _possibleEntries.stream().filter(loc -> loc.getId() == pos).findAny().orElse(null); } return _possibleEntries.removeFirst(); } public synchronized void move(L2PcInstance activeChar, int pos) { final SayuneEntry map = SayuneData.getInstance().getMap(_mapId); if ((map == null) || map.getInnerEntries().isEmpty()) { activeChar.sendMessage("MapId: " + _mapId + " was not found in the map!"); return; } final SayuneEntry nextEntry = findEntry(pos); if (nextEntry == null) { activeChar.removeRequest(getClass()); return; } // If player was selecting unset and set his possible path if (_isSelecting) { _isSelecting = false; // Set next possible path if (!nextEntry.isSelector()) { _possibleEntries.clear(); _possibleEntries.addAll(nextEntry.getInnerEntries()); } } final SayuneType type = (pos == 0) && nextEntry.isSelector() ? SayuneType.START_LOC : nextEntry.isSelector() ? SayuneType.MULTI_WAY_LOC : SayuneType.ONE_WAY_LOC; final List<SayuneEntry> locations = nextEntry.isSelector() ? nextEntry.getInnerEntries() : Arrays.asList(nextEntry); if (nextEntry.isSelector()) { _possibleEntries.clear(); _possibleEntries.addAll(locations); _isSelecting = true; } activeChar.sendPacket(new ExFlyMove(activeChar, type, _mapId, locations)); final SayuneEntry activeEntry = locations.get(0); Broadcast.toKnownPlayersInRadius(activeChar, new ExFlyMoveBroadcast(activeChar, type, map.getId(), activeEntry), 1000); activeChar.setXYZ(activeEntry); } public void onLogout() { final SayuneEntry map = SayuneData.getInstance().getMap(_mapId); if ((map != null) && !map.getInnerEntries().isEmpty()) { final SayuneEntry nextEntry = findEntry(0); if (_isSelecting || ((nextEntry != null) && nextEntry.isSelector())) { // If player is on selector or next entry is selector go back to first entry getActiveChar().setXYZ(map); } else { // Try to find last entry to set player, if not set him to first entry final SayuneEntry lastEntry = map.getInnerEntries().get(map.getInnerEntries().size() - 1); if (lastEntry != null) { getActiveChar().setXYZ(lastEntry); } else { getActiveChar().setXYZ(map); } } } } }
gpl-3.0
jinsedeyuzhou/NewsClient
doraemonkit/src/main/java/com/ebrightmoon/doraemonkit/kit/network/httpurlconnection/interceptor/HttpChainFacade.java
1330
package com.ebrightmoon.doraemonkit.kit.network.httpurlconnection.interceptor; import java.io.IOException; import java.util.List; /** * @date: 2019/3/14 * @desc: 对几个处理链的包装 */ public class HttpChainFacade { private final HttpRequestChain mHttpRequestChain; private final HttpResponseChain mHttpResponseChain; private final HttpRequestStreamChain mHttpRequestStreamChain; private final HttpResponseStreamChain mHttpResponseStreamChain; public HttpChainFacade(List<DKInterceptor> interceptors) { mHttpRequestChain = new HttpRequestChain(interceptors); mHttpResponseChain = new HttpResponseChain(interceptors); mHttpRequestStreamChain = new HttpRequestStreamChain(interceptors); mHttpResponseStreamChain = new HttpResponseStreamChain(interceptors); } public void process(HttpRequest request) throws IOException { mHttpRequestChain.process(request); } public void process(HttpResponse response) throws IOException { mHttpResponseChain.process(response); } public void processStream(HttpRequest request) throws IOException { mHttpRequestStreamChain.process(request); } public void processStream(HttpResponse response) throws IOException { mHttpResponseStreamChain.process(response); } }
gpl-3.0
h4h13/RetroMusicPlayer
app/src/main/java/code/name/monkey/retromusic/interfaces/LoaderIds.java
111
package code.name.monkey.retromusic.interfaces; public interface LoaderIds { int FOLDERS_FRAGMENT = 5; }
gpl-3.0
TGAC/miso-lims
miso-dto/src/main/java/uk/ac/bbsrc/tgac/miso/dto/SpreadsheetRequest.java
533
package uk.ac.bbsrc.tgac.miso.dto; import java.util.List; public class SpreadsheetRequest { private String format; private List<Long> ids; private String sheet; public String getFormat() { return format; } public List<Long> getIds() { return ids; } public String getSheet() { return sheet; } public void setFormat(String format) { this.format = format; } public void setIds(List<Long> ids) { this.ids = ids; } public void setSheet(String sheet) { this.sheet = sheet; } }
gpl-3.0
repoxIST/repoxEuropeana
repox-core/src/main/java/pt/utl/ist/repox/metadataTransformation/TransformationFile.java
2662
package pt.utl.ist.repox.metadataTransformation; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Namespace; import org.dom4j.Node; import org.dom4j.io.SAXReader; import javax.xml.transform.Templates; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Created to project REPOX. * User: Edmundo * Date: 03/09/12 * Time: 13:28 */ public class TransformationFile { private List<TransformationSubFile> transformationSubFiles; private File stylesheet; private Templates template; private Long timestamp; public TransformationFile(File stylesheet, Templates template, Long timestamp) { this.stylesheet = stylesheet; this.template = template; this.timestamp = timestamp; transformationSubFiles = new ArrayList<TransformationSubFile>(); addSubFiles(); } public void addSubFiles(){ // todo: process imports inside of imports try { SAXReader reader = new SAXReader(); Document document = reader.read(stylesheet); document.getRootElement().add(new Namespace("xsl","http://www.w3.org/1999/XSL/Transform")); List<Node> list = document.getRootElement().selectNodes("xsl:import"); for(Node node: list) { String fileName = node.valueOf("@href"); File xslFile = new File(stylesheet.getParent(),fileName); transformationSubFiles.add(new TransformationSubFile(xslFile.lastModified(),xslFile.getName())); } } catch (DocumentException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } public boolean isOutdated(Long currentStylesheetDate) { return !currentStylesheetDate.equals(getTimestamp()); } public boolean subFilesUpToDate() { for(TransformationSubFile subFile : transformationSubFiles){ File currentFile = new File(stylesheet.getParent(),subFile.getFileName()); if(subFile.getTimestamp() != currentFile.lastModified()){ // System.out.println("Sub Files OUTDATED"); return false; } } // System.out.println("Sub Files Up to Date"); return true; } public Templates getTemplate() { return template; } public void setTemplate(Templates template) { this.template = template; } public List<TransformationSubFile> getTransformationSubFiles() { return transformationSubFiles; } public Long getTimestamp() { return timestamp; } }
gpl-3.0
marvisan/HadesFIX
Model/src/test/java/net/hades/fix/message/impl/v44/data/ExecutionReportMsg44TestData.java
24619
/* * Copyright (c) 2006-2009 Marvisan Pty. Ltd. All rights reserved. * Use is subject to license terms. */ /* * ExecutionReportMsg44TestData.java * * $Id: ExecutionReportMsg44TestData.java,v 1.4 2011-10-29 09:42:17 vrotaru Exp $ */ package net.hades.fix.message.impl.v44.data; import java.io.UnsupportedEncodingException; import java.util.Calendar; import static org.junit.Assert.*; import net.hades.fix.TestUtils; import net.hades.fix.message.ExecutionReportMsg; import net.hades.fix.message.MsgTest; import net.hades.fix.message.comp.impl.v43.CommissionData43TestData; import net.hades.fix.message.comp.impl.v44.DiscretionInstructions44TestData; import net.hades.fix.message.comp.impl.v44.FinancingDetails44TestData; import net.hades.fix.message.comp.impl.v44.Instrument44TestData; import net.hades.fix.message.comp.impl.v44.OrderQtyData44TestData; import net.hades.fix.message.comp.impl.v44.Parties44TestData; import net.hades.fix.message.comp.impl.v44.PegInstructions44TestData; import net.hades.fix.message.comp.impl.v44.SpreadOrBenchmarkCurveData44TestData; import net.hades.fix.message.comp.impl.v44.Stipulations44TestData; import net.hades.fix.message.comp.impl.v44.UnderlyingInstrument44TestData; import net.hades.fix.message.comp.impl.v44.YieldData44TestData; import net.hades.fix.message.group.impl.v43.ContAmtGroup43TestData; import net.hades.fix.message.group.impl.v43.ContraBrokerGroup43TestData; import net.hades.fix.message.group.impl.v44.InstrmtLegExecGroup44TestData; import net.hades.fix.message.group.impl.v44.MiscFeeGroup44TestData; import net.hades.fix.message.type.AccountType; import net.hades.fix.message.type.AcctIDSource; import net.hades.fix.message.type.BookingType; import net.hades.fix.message.type.BookingUnit; import net.hades.fix.message.type.CancellationRights; import net.hades.fix.message.type.CashMargin; import net.hades.fix.message.type.ClearingFeeIndicator; import net.hades.fix.message.type.CrossType; import net.hades.fix.message.type.Currency; import net.hades.fix.message.type.CustOrderCapacity; import net.hades.fix.message.type.DayBookingInst; import net.hades.fix.message.type.ExecInst; import net.hades.fix.message.type.ExecPriceType; import net.hades.fix.message.type.ExecRestatementReason; import net.hades.fix.message.type.ExecType; import net.hades.fix.message.type.GTBookingInst; import net.hades.fix.message.type.HandlInst; import net.hades.fix.message.type.LastCapacity; import net.hades.fix.message.type.LastLiquidityInd; import net.hades.fix.message.type.MoneyLaunderingStatus; import net.hades.fix.message.type.MultiLegReportingType; import net.hades.fix.message.type.OrdRejReason; import net.hades.fix.message.type.OrdStatus; import net.hades.fix.message.type.OrdType; import net.hades.fix.message.type.OrderCapacity; import net.hades.fix.message.type.OrderRestrictions; import net.hades.fix.message.type.PositionEffect; import net.hades.fix.message.type.PreallocMethod; import net.hades.fix.message.type.PriceType; import net.hades.fix.message.type.PriorityIndicator; import net.hades.fix.message.type.QtyType; import net.hades.fix.message.type.SettlCurrFxRateCalc; import net.hades.fix.message.type.SettlType; import net.hades.fix.message.type.Side; import net.hades.fix.message.type.TargetStrategy; import net.hades.fix.message.type.TimeInForce; import net.hades.fix.message.type.TradingSessionID; import net.hades.fix.message.type.TradingSessionSubID; /** * Test utility for ExecutionReportMsg44 message class. * * @author <a href="mailto:support@marvisan.com">Support Team</a> * @version $Revision: 1.4 $ * @created 11/05/2009, 12:08:30 PM */ public class ExecutionReportMsg44TestData extends MsgTest { private static final ExecutionReportMsg44TestData INSTANCE; static { INSTANCE = new ExecutionReportMsg44TestData(); } public static ExecutionReportMsg44TestData getInstance() { return INSTANCE; } public void populate(ExecutionReportMsg msg) throws UnsupportedEncodingException { TestUtils.populate44HeaderAll(msg); msg.setOrderID("XXX9374994"); msg.setSecondaryOrderID("SSS778877"); msg.setSecondaryClOrdID("SEC7364883"); msg.setSecondaryExecID("SECEXEC2142343"); msg.setClOrdID("AAA564567"); msg.setOrigClOrdID("COD003883"); msg.setClOrdLinkID("ORDLINK213131"); msg.setQuoteRespID("QUOTE784844"); msg.setOrdStatusReqID("STS223942943"); msg.setMassStatusReqID("MASS92363"); msg.setTotNumReports(3); msg.setLastRptRequested(Boolean.TRUE); msg.setParties(); Parties44TestData.getInstance().populate(msg.getParties()); Calendar cal = Calendar.getInstance(); cal.set(2010, 4, 15, 11, 12, 13); msg.setTradeOriginationDate(cal.getTime()); msg.setNoContraBrokers(2); ContraBrokerGroup43TestData.getInstance().populate1(msg.getContraBrokers()[0]); ContraBrokerGroup43TestData.getInstance().populate2(msg.getContraBrokers()[1]); msg.setListID("LST44555"); msg.setCrossID("CROSS534333"); msg.setOrigCrossID("ORIGCROSS2424234"); msg.setCrossType(CrossType.CrossOneSide); msg.setExecID("EXEC273663"); msg.setExecRefID("EXEC836684"); msg.setExecType(ExecType.New); msg.setOrdStatus(OrdStatus.New); msg.setWorkingIndicator(Boolean.TRUE); msg.setOrdRejReason(OrdRejReason.DuplicateOrder); msg.setExecRestatementReason(ExecRestatementReason.BrokerOption); msg.setAccount("12735534784"); msg.setAcctIDSource(AcctIDSource.SID); msg.setAccountType(AccountType.FloorTrader); msg.setDayBookingInst(DayBookingInst.Accumulate); msg.setBookingUnit(BookingUnit.EachExecutionBookableUnit); msg.setPreallocMethod(PreallocMethod.ProRata); msg.setSettlType(SettlType.Cash.getValue()); cal.set(2010, 3, 14, 12, 15, 33); msg.setSettlDate(cal.getTime()); msg.setCashMargin(CashMargin.Cash); msg.setClearingFeeIndicator(ClearingFeeIndicator.CBOEMember); msg.setInstrument(); Instrument44TestData.getInstance().populate(msg.getInstrument()); msg.setFinancingDetails(); FinancingDetails44TestData.getInstance().populate(msg.getFinancingDetails()); msg.setNoUnderlyings(2); UnderlyingInstrument44TestData.getInstance().populate1(msg.getUnderlyingInstruments()[0]); UnderlyingInstrument44TestData.getInstance().populate2(msg.getUnderlyingInstruments()[1]); msg.setSide(Side.Buy); msg.setStipulations(); Stipulations44TestData.getInstance().populate(msg.getStipulations()); msg.setQtyType(QtyType.Units); msg.setOrderQtyData(); OrderQtyData44TestData.getInstance().populate(msg.getOrderQtyData()); msg.setOrdType(OrdType.Limit); msg.setPriceType(PriceType.Percentage); msg.setPrice(50.67d); msg.setStopPx(51.67d); msg.setPegInstructions(); PegInstructions44TestData.getInstance().populate(msg.getPegInstructions()); msg.setDiscretionInstructions(); DiscretionInstructions44TestData.getInstance().populate(msg.getDiscretionInstructions()); msg.setPeggedPrice(33.33d); msg.setDiscretionPrice(45.44d); msg.setTargetStrategy(TargetStrategy.Participate.getValue()); msg.setTargetStrategyParameters("24234235325"); msg.setParticipationRate(23.30d); msg.setTargetStrategyParameters("T8243423235"); msg.setCurrency(Currency.UnitedStatesDollar); msg.setComplianceID("COMP_ID"); msg.setSolicitedFlag(Boolean.TRUE); msg.setTimeInForce(TimeInForce.Opening); cal.set(2010, 3, 14, 11, 11, 11); msg.setEffectiveTime(cal.getTime()); cal.set(2010, 3, 15, 12, 12, 12); msg.setExpireDate(cal.getTime()); cal.set(2010, 3, 14, 12, 30, 44); msg.setExpireTime(cal.getTime()); msg.setExecInst(ExecInst.CallFirst.getValue()); msg.setOrderCapacity(OrderCapacity.Proprietary); msg.setOrderRestrictions(OrderRestrictions.ProgramTrade.getValue()); msg.setCustOrderCapacity(CustOrderCapacity.AllOther); msg.setLastQty(23.44d); msg.setUnderlyingLastQty(33.88d); msg.setLastPx(33.33d); msg.setUnderlyingLastPx(33.77d); msg.setLastParPx(43.55d); msg.setLastSpotRate(13.12d); msg.setLastForwardPoints(2.22d); msg.setLastMkt("ASX"); msg.setTradingSessionID(TradingSessionID.Day.getValue()); msg.setTradingSessionSubID(TradingSessionSubID.Opening.getValue()); msg.setLastCapacity(LastCapacity.Principal); msg.setLeavesQty(23.66d); msg.setCumQty(39.44d); msg.setAvgPx(33.44d); msg.setDayOrderQty(22.34d); msg.setDayCumQty(123.45d); msg.setDayAvgPx(23.35d); msg.setGTBookingInst(GTBookingInst.BookOutAllTrades); cal.set(2010, 3, 14, 12, 55, 55); msg.setTradeDate(cal.getTime()); cal.set(2010, 3, 14, 12, 56, 56); msg.setTransactTime(cal.getTime()); msg.setReportToExch(Boolean.TRUE); msg.setCommissionData(); CommissionData43TestData.getInstance().populate(msg.getCommissionData()); msg.setSpreadOrBenchmarkCurveData(); SpreadOrBenchmarkCurveData44TestData.getInstance().populate(msg.getSpreadOrBenchmarkCurveData()); msg.setYieldData(); YieldData44TestData.getInstance().populate(msg.getYieldData()); msg.setGrossTradeAmt(35.44d); msg.setNumDaysInterest(3); cal.set(2010, 3, 7, 3, 4, 5); msg.setExDate(cal.getTime()); msg.setAccruedInterestRate(4.55d); msg.setAccruedInterestAmt(24.67d); msg.setInterestAtMaturity(54.33d); msg.setEndAccruedInterestAmt(65.33d); msg.setStartCash(33.12d); msg.setEndCash(35.66d); msg.setTradedFlatSwitch(Boolean.FALSE); cal.set(2010, 3, 8, 9, 10, 11); msg.setBasisFeatureDate(cal.getTime()); msg.setConcession(2.56d); msg.setTotalTakedown(13.55d); msg.setNetMoney(44.45d); msg.setSettlCurrAmt(22.34d); msg.setSettlCurrency(Currency.AustralianDollar); msg.setSettlCurrFxRate(23.33d); msg.setSettlCurrFxRateCalc(SettlCurrFxRateCalc.Multiply); msg.setHandlInst(HandlInst.ManualOrder); msg.setMinQty(23.50d); msg.setMaxFloor(24.5d); msg.setPositionEffect(PositionEffect.Close); msg.setMaxShow(25.60d); msg.setBookingType(BookingType.RegularBooking); msg.setText("some text here"); msg.setEncodedTextLen(new Integer(8)); byte[] encodedText = new byte[] {(byte) 18, (byte) 32, (byte) 43, (byte) 95, (byte) 177, (byte) 198, (byte) 224, (byte) 253}; msg.setEncodedText(encodedText); cal.set(2010, 3, 24, 11, 22, 33); msg.setSettlDate2(cal.getTime()); msg.setOrderQty2(33.78d); msg.setMultilegReportingType(MultiLegReportingType.MultiLegSecurity); msg.setCancellationRights(CancellationRights.No_ExecutionOnly); msg.setMoneyLaunderingStatus(MoneyLaunderingStatus.Exempt_BelowLimit); msg.setRegistID("REG8633444"); msg.setDesignation("DES8474638"); cal.set(2010, 3, 14, 16, 27, 38); msg.setTransBkdTime(cal.getTime()); cal.set(2010, 3, 8, 9, 10, 11); msg.setExecValuationPoint(cal.getTime()); msg.setExecPriceType(ExecPriceType.BidPrice); msg.setExecPriceAdjustment(22.56d); msg.setPriorityIndicator(PriorityIndicator.PriorityUnchanged); msg.setPriceImprovement(16.77d); msg.setLastLiquidityInd(LastLiquidityInd.AddedLiquidity); msg.setNoContAmts(2); ContAmtGroup43TestData.getInstance().populate1(msg.getContAmtGroups()[0]); ContAmtGroup43TestData.getInstance().populate2(msg.getContAmtGroups()[1]); msg.setNoLegs(2); InstrmtLegExecGroup44TestData.getInstance().populate1(msg.getInstrmtLegExecGroups()[0]); InstrmtLegExecGroup44TestData.getInstance().populate2(msg.getInstrmtLegExecGroups()[1]); msg.setCopyMsgIndicator(Boolean.TRUE); msg.setNoMiscFees(2); MiscFeeGroup44TestData.getInstance().populate1(msg.getMiscFeeGroups()[0]); MiscFeeGroup44TestData.getInstance().populate1(msg.getMiscFeeGroups()[1]); } public void check(ExecutionReportMsg expected, ExecutionReportMsg actual) throws Exception { assertEquals(expected.getOrderID(), actual.getOrderID()); assertEquals(expected.getSecondaryOrderID(), actual.getSecondaryOrderID()); assertEquals(expected.getSecondaryClOrdID(), actual.getSecondaryClOrdID()); assertEquals(expected.getSecondaryExecID(), actual.getSecondaryExecID()); assertEquals(expected.getClOrdID(), actual.getClOrdID()); assertEquals(expected.getOrigClOrdID(), actual.getOrigClOrdID()); assertEquals(expected.getClOrdLinkID(), actual.getClOrdLinkID()); assertEquals(expected.getQuoteRespID(), actual.getQuoteRespID()); assertEquals(expected.getOrdStatusReqID(), actual.getOrdStatusReqID()); assertEquals(expected.getMassStatusReqID(), actual.getMassStatusReqID()); assertEquals(expected.getTotNumReports(), actual.getTotNumReports()); assertEquals(expected.getLastRptRequested(), actual.getLastRptRequested()); Parties44TestData.getInstance().check(expected.getParties(), actual.getParties()); assertEquals(expected.getNoMiscFees(), actual.getNoMiscFees()); ContraBrokerGroup43TestData.getInstance().check(expected.getContraBrokers()[0], actual.getContraBrokers()[0]); ContraBrokerGroup43TestData.getInstance().check(expected.getContraBrokers()[1], actual.getContraBrokers()[1]); assertEquals(expected.getListID(), actual.getListID()); assertEquals(expected.getCrossID(), actual.getCrossID()); assertEquals(expected.getOrigCrossID(), actual.getOrigCrossID()); assertEquals(expected.getCrossType(), actual.getCrossType()); assertEquals(expected.getExecID(), actual.getExecID()); assertEquals(expected.getExecRefID(), actual.getExecRefID()); assertEquals(expected.getExecType(), actual.getExecType()); assertEquals(expected.getOrdStatus(), actual.getOrdStatus()); assertEquals(expected.getWorkingIndicator(), actual.getWorkingIndicator()); assertEquals(expected.getOrdRejReason(), actual.getOrdRejReason()); assertEquals(expected.getExecRestatementReason(), actual.getExecRestatementReason()); assertEquals(expected.getAccount(), actual.getAccount()); assertEquals(expected.getAcctIDSource(), actual.getAcctIDSource()); assertEquals(expected.getAccountType(), actual.getAccountType()); assertEquals(expected.getDayBookingInst(), actual.getDayBookingInst()); assertEquals(expected.getBookingUnit(), actual.getBookingUnit()); assertEquals(expected.getPreallocMethod(), actual.getPreallocMethod()); assertEquals(expected.getSettlType(), actual.getSettlType()); assertDateEquals(expected.getSettlDate(), actual.getSettlDate()); assertEquals(expected.getCashMargin(), actual.getCashMargin()); assertEquals(expected.getClearingFeeIndicator(), actual.getClearingFeeIndicator()); Instrument44TestData.getInstance().check(expected.getInstrument(), actual.getInstrument()); FinancingDetails44TestData.getInstance().check(expected.getFinancingDetails(), actual.getFinancingDetails()); assertEquals(expected.getNoUnderlyings(), actual.getNoUnderlyings()); UnderlyingInstrument44TestData.getInstance().check(expected.getUnderlyingInstruments()[0], actual.getUnderlyingInstruments()[0]); UnderlyingInstrument44TestData.getInstance().check(expected.getUnderlyingInstruments()[1], actual.getUnderlyingInstruments()[1]); assertEquals(expected.getSide(), actual.getSide()); Stipulations44TestData.getInstance().check(expected.getStipulations(), actual.getStipulations()); assertEquals(expected.getQuantityType(), actual.getQuantityType()); OrderQtyData44TestData.getInstance().check(expected.getOrderQtyData(), actual.getOrderQtyData()); assertEquals(expected.getOrdType(), actual.getOrdType()); assertEquals(expected.getPriceType(), actual.getPriceType()); assertEquals(expected.getPrice(), actual.getPrice()); assertEquals(expected.getStopPx(), actual.getStopPx()); PegInstructions44TestData.getInstance().check(expected.getPegInstructions(), actual.getPegInstructions()); DiscretionInstructions44TestData.getInstance().check(expected.getDiscretionInstructions(), actual.getDiscretionInstructions()); assertEquals(expected.getPeggedPrice(), actual.getPeggedPrice()); assertEquals(expected.getDiscretionPrice(), actual.getDiscretionPrice()); assertEquals(expected.getTargetStrategy(), actual.getTargetStrategy()); assertEquals(expected.getTargetStrategyParameters(), actual.getTargetStrategyParameters()); assertEquals(expected.getParticipationRate(), actual.getParticipationRate()); assertEquals(expected.getTargetStrategyParameters(), actual.getTargetStrategyParameters()); assertEquals(expected.getCurrency(), actual.getCurrency()); assertEquals(expected.getComplianceID(), actual.getComplianceID()); assertEquals(expected.getSolicitedFlag(), actual.getSolicitedFlag()); assertEquals(expected.getTimeInForce(), actual.getTimeInForce()); assertUTCTimestampEquals(expected.getEffectiveTime(), actual.getEffectiveTime(), false); assertDateEquals(expected.getExpireDate(), actual.getExpireDate()); assertUTCTimestampEquals(expected.getExpireTime(), actual.getExpireTime(), false); assertEquals(expected.getExecInst(), actual.getExecInst()); assertEquals(expected.getOrderCapacity(), actual.getOrderCapacity()); assertEquals(expected.getOrderRestrictions(), actual.getOrderRestrictions()); assertEquals(expected.getCustOrderCapacity(), actual.getCustOrderCapacity()); assertEquals(expected.getLastQty(), actual.getLastQty()); assertEquals(expected.getUnderlyingLastQty(), actual.getUnderlyingLastQty()); assertEquals(expected.getLastPx(), actual.getLastPx()); assertEquals(expected.getUnderlyingLastPx(), actual.getUnderlyingLastPx()); assertEquals(expected.getLastParPx(), actual.getLastParPx()); assertEquals(expected.getLastSpotRate(), actual.getLastSpotRate()); assertEquals(expected.getLastForwardPoints(), actual.getLastForwardPoints()); assertEquals(expected.getLastMkt(), actual.getLastMkt()); assertEquals(expected.getTradingSessionID(), actual.getTradingSessionID()); assertEquals(expected.getTradingSessionSubID(), actual.getTradingSessionSubID()); assertEquals(expected.getLastCapacity(), actual.getLastCapacity()); assertEquals(expected.getLeavesQty(), actual.getLeavesQty()); assertEquals(expected.getCumQty(), actual.getCumQty()); assertEquals(expected.getAvgPx(), actual.getAvgPx()); assertEquals(expected.getDayOrderQty(), actual.getDayOrderQty()); assertEquals(expected.getDayCumQty(), actual.getDayCumQty()); assertEquals(expected.getDayAvgPx(), actual.getDayAvgPx()); assertEquals(expected.getGTBookingInst(), actual.getGTBookingInst()); assertDateEquals(expected.getTradeDate(), actual.getTradeDate()); assertUTCTimestampEquals(expected.getTransactTime(), actual.getTransactTime(), false); assertEquals(expected.getReportToExch(), actual.getReportToExch()); CommissionData43TestData.getInstance().check(expected.getCommissionData(), actual.getCommissionData()); SpreadOrBenchmarkCurveData44TestData.getInstance().check(expected.getSpreadOrBenchmarkCurveData(), actual.getSpreadOrBenchmarkCurveData()); YieldData44TestData.getInstance().check(expected.getYieldData(), actual.getYieldData()); assertEquals(expected.getGrossTradeAmt(), actual.getGrossTradeAmt()); assertEquals(expected.getNumDaysInterest(), actual.getNumDaysInterest()); assertDateEquals(expected.getExDate(), actual.getExDate()); assertEquals(expected.getAccruedInterestRate(), actual.getAccruedInterestRate()); assertEquals(expected.getAccruedInterestAmt(), actual.getAccruedInterestAmt()); assertEquals(expected.getInterestAtMaturity(), actual.getInterestAtMaturity()); assertEquals(expected.getEndAccruedInterestAmt(), actual.getEndAccruedInterestAmt()); assertEquals(expected.getStartCash(), actual.getStartCash()); assertEquals(expected.getEndCash(), actual.getEndCash()); assertEquals(expected.getTradedFlatSwitch(), actual.getTradedFlatSwitch()); assertDateEquals(expected.getBasisFeatureDate(), actual.getBasisFeatureDate()); assertEquals(expected.getConcession(), actual.getConcession()); assertEquals(expected.getTotalTakedown(), actual.getTotalTakedown()); assertEquals(expected.getNetMoney(), actual.getNetMoney()); assertEquals(expected.getSettlCurrAmt(), actual.getSettlCurrAmt()); assertEquals(expected.getSettlCurrency(), actual.getSettlCurrency()); assertEquals(expected.getSettlCurrFxRate(), actual.getSettlCurrFxRate()); assertEquals(expected.getSettlCurrFxRateCalc(), actual.getSettlCurrFxRateCalc()); assertEquals(expected.getHandlInst(), actual.getHandlInst()); assertEquals(expected.getMinQty(), actual.getMinQty()); assertEquals(expected.getMaxFloor(), actual.getMaxFloor()); assertEquals(expected.getPositionEffect(), actual.getPositionEffect()); assertEquals(expected.getMaxShow(), actual.getMaxShow()); assertEquals(expected.getBookingType(), actual.getBookingType()); assertEquals(expected.getText(), actual.getText()); assertEquals(expected.getEncodedTextLen().intValue(), actual.getEncodedTextLen().intValue()); assertArrayEquals(expected.getEncodedText(), actual.getEncodedText()); assertDateEquals(expected.getSettlDate2(), actual.getSettlDate2()); assertEquals(expected.getOrderQty2(), actual.getOrderQty2()); assertEquals(expected.getMultilegReportingType(), actual.getMultilegReportingType()); assertEquals(expected.getCancellationRights(), actual.getCancellationRights()); assertEquals(expected.getMoneyLaunderingStatus(), actual.getMoneyLaunderingStatus()); assertEquals(expected.getRegistID(), actual.getRegistID()); assertEquals(expected.getDesignation(), actual.getDesignation()); assertUTCTimestampEquals(expected.getTransBkdTime(), actual.getTransBkdTime(), false); assertUTCTimestampEquals(expected.getExecValuationPoint(), actual.getExecValuationPoint(), false); assertEquals(expected.getExecPriceType(), actual.getExecPriceType()); assertEquals(expected.getExecPriceAdjustment(), actual.getExecPriceAdjustment()); assertEquals(expected.getPriorityIndicator(), actual.getPriorityIndicator()); assertEquals(expected.getPriceImprovement(), actual.getPriceImprovement()); assertEquals(expected.getLastLiquidityInd(), actual.getLastLiquidityInd()); assertEquals(expected.getNoContAmts(), actual.getNoContAmts()); ContAmtGroup43TestData.getInstance().check(expected.getContAmtGroups()[0], actual.getContAmtGroups()[0]); ContAmtGroup43TestData.getInstance().check(expected.getContAmtGroups()[1], actual.getContAmtGroups()[1]); assertEquals(expected.getNoLegs(), actual.getNoLegs()); InstrmtLegExecGroup44TestData.getInstance().check(expected.getInstrmtLegExecGroups()[0], actual.getInstrmtLegExecGroups()[0]); InstrmtLegExecGroup44TestData.getInstance().check(expected.getInstrmtLegExecGroups()[1], actual.getInstrmtLegExecGroups()[1]); assertEquals(expected.getCopyMsgIndicator(), actual.getCopyMsgIndicator()); assertEquals(expected.getNoMiscFees(), actual.getNoMiscFees()); MiscFeeGroup44TestData.getInstance().check(expected.getMiscFeeGroups()[0], actual.getMiscFeeGroups()[0]); MiscFeeGroup44TestData.getInstance().check(expected.getMiscFeeGroups()[1], actual.getMiscFeeGroups()[1]); } }
gpl-3.0
NovaStory/AeroStory
src/server/movement/ChairMovement.java
1707
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package server.movement; import java.awt.Point; import tools.data.output.LittleEndianWriter; public class ChairMovement extends AbstractLifeMovement { private int unk; public ChairMovement(byte type, Point position, int duration, byte newstate) { super(type, position, duration, newstate); } public int getUnk() { return unk; } public void setUnk(int unk) { this.unk = unk; } @Override public void serialize(LittleEndianWriter lew) { lew.write(getType()); lew.writeShort(getPosition().x); lew.writeShort(getPosition().y); lew.writeShort(unk); lew.write(getNewstate()); lew.writeShort(getDuration()); } }
gpl-3.0
deska123/Java-Data-Structures
Linked List/DoublyLinkedList.java
6465
/** * This class implements a Doubly Linked List Data Structure and Its Supporting Methods * A Linked List only contains header node as its first controller * * @author Dennis Pratama Kamah * @version 2017.09.03 * @param <T> **/ public class DoublyLinkedList<T> { private DynamicNode headerNode; /** * Default Constructor Doubly LinkedList * Initial header node is null **/ public DoublyLinkedList() { this.headerNode = null; } /** * Return the condition whether linked list is empty (or not) * @return true or false **/ public boolean isEmpty() { return this.headerNode == null; } /** * Make linked list to be emptied **/ public void makeEmpty() { this.headerNode = null; } /** * Method to print Data of Header Node * @throws NullPointerException if linked list is empty **/ public void printHeaderNode() { if(!this.isEmpty()) { System.out.println(this.headerNode.getData()); } else { throw new NullPointerException("There is no header node to be printed in this linked list"); } } /** * Method to print all data in each node in linked list * starting from header node * @throws NullPointerException if linked list is empty **/ public void forwardPrintAll() { if(!this.isEmpty()) { DynamicNode current = this.headerNode; while(current != null) { System.out.println(current.getData()); current = current.getNextNode(); } } else { throw new NullPointerException("No such element nodes to be printed in this linked list"); } } /** * Method to print all data in each node in linked list * starting from tail node * @throws NullPointerException if linked list is empty **/ public void backwardPrintAll() { if(!this.isEmpty()) { DynamicNode current = this.headerNode; while(current.getNextNode() != null) { current = current.getNextNode(); } while(current != null) { System.out.println(current.getData()); current = current.getPreviousNode(); } } else { throw new NullPointerException("No such element nodes to be printed in this linked list"); } } /** * Method to insert new header node * @param data a generic-typed data **/ public void headerInsert(T data) { DynamicNode newNode = new DynamicNode(data); DynamicNode oldNode = this.headerNode; newNode.setNextNode(oldNode); if(oldNode != null) { oldNode.setPreviousNode(newNode); } this.headerNode = newNode; } /** * Method to insert new node as tail * @param data a generic-typed data **/ public void insert(T data) { DynamicNode current = this.headerNode; DynamicNode newNode = new DynamicNode(data); if(current == null) { this.headerNode = newNode; } else { while(current.getNextNode() != null) { current = current.getNextNode(); } current.setNextNode(newNode); newNode.setPreviousNode(current); } } /** * Method to delete header node * @throws NullPointerException if linked list is empty **/ public void headerDelete() { if(this.isEmpty()) { throw new NullPointerException("No such header node to be deleted in this linked list"); } else { if(this.headerNode.getNextNode() == null) { this.headerNode = null; } else { this.headerNode = this.headerNode.getNextNode(); this.headerNode.setPreviousNode(null); } } } /** * Method to delete tail node * @throws NullPointerException if linked list is empty **/ public void delete() { DynamicNode current = this.headerNode; if(this.isEmpty()) { throw new NullPointerException("No such element nodes to be deleted in this linked list"); } else if(current.getNextNode() == null) { this.headerNode = null; } else { while(current != null) { if(current.getNextNode().getNextNode() == null) { break; } current = current.getNextNode(); } current.setNextNode(null); } } /** * Method to delete specific data node in linked list * @param data data to be deleted * @throws NullPointerException if there is no specific data or linked list is empty **/ public void deleteNode(T data) { if(this.isEmpty()) { throw new NullPointerException("linked list is empty"); } else if(this.headerNode.getData() == data) { this.headerNode.getNextNode().setPreviousNode(null); this.headerNode = this.headerNode.getNextNode(); } else { if(this.headerNode.getNextNode() == null) { throw new NullPointerException("There is no element node containing " + data); } else { DynamicNode current = this.headerNode; while(current != null) { if(current.getNextNode() == null || current.getNextNode().getData() == data) { break; } current = current.getNextNode(); } if(current.getNextNode() == null) { throw new NullPointerException("There is no element node containing " + data); } else { if(current.getNextNode().getNextNode() == null) { current.setNextNode(null); } else { current.setNextNode(current.getNextNode().getNextNode()); current.getNextNode().setPreviousNode(current); } } } } } }
gpl-3.0
OpenSourcePhysics/STP
src/org/opensourcephysics/stp/randomwalk/saw/FlatApp.java
6961
/* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.randomwalk.saw; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuItem; import org.opensourcephysics.controls.*; import org.opensourcephysics.display.DatasetManager; import org.opensourcephysics.display.DrawingPanel; import org.opensourcephysics.display.GUIUtils; import org.opensourcephysics.display.OSPFrame; import org.opensourcephysics.display.OSPRuntime; import org.opensourcephysics.frames.*; /** * Simulates random walkers in one dimension * * @author Jan Tobochnik, Wolfgang Christian, Harvey Gould * @version 1.0 revised 04/21/05 */ public class FlatApp extends AbstractSimulation { Flat walkers = new Flat(); PlotFrame xyFrame = new PlotFrame("time", "", "<x>,<y>"); PlotFrame x2y2Frame = new PlotFrame("ln time", "x^2, y^2", "ln <x^2>,ln <y^2>"); PlotFrame r2Frame = new PlotFrame("ln time", "r^2", "ln <r^2>"); DatasetManager datasets; DrawingPanel drawingPanel; int step, nstep, maxStep; // time step /** * Sets column names for data table */ public FlatApp() { xyFrame.setXYColumnNames(0, "t", "<x>"); xyFrame.setXYColumnNames(1, "t", "<y>"); x2y2Frame.setXYColumnNames(0, "ln t", "ln <x^2>"); x2y2Frame.setXYColumnNames(1, "ln t", "ln <y^2>"); x2y2Frame.setAutoscaleX(true); x2y2Frame.setAutoscaleY(true); x2y2Frame.limitAutoscaleX(0, 10); x2y2Frame.limitAutoscaleY(0, 10); xyFrame.setAutoscaleX(true); xyFrame.setAutoscaleY(true); xyFrame.limitAutoscaleX(0, 10); xyFrame.limitAutoscaleY(0, 10); datasets=r2Frame.getDatasetManager(); datasets.setXYColumnNames(0, "ln t", "ln <r^2>"); drawingPanel=r2Frame.getDrawingPanel(); drawingPanel.setAutoscaleX(true); drawingPanel.setAutoscaleY(true); drawingPanel.limitAutoscaleX(0, 10); drawingPanel.limitAutoscaleY(0, 10); } /** * Gets parameters and initializes model */ public void initialize() { walkers.numberOfWalkers = control.getInt("number of initial walkers"); maxStep = control.getInt("number of steps"); OneWalker.s0 = (short) (maxStep/2); //walkers.L = control.getInt("Half lattice Size"); walkers.initialize(); step = 0; nstep = 2; drawingPanel.setMessage("time = "+step); } /** * Does one walker at a time */ public void doStep() { if(nstep<=maxStep) { int step0 = step; for(int i = step0; i<nstep; i++) { walkers.step(); step++; } nstep *= 2; double norm = walkers.norm; double xbar = walkers.xAccum/norm; double x2bar = walkers.xSquaredAccum/norm; double ybar = walkers.yAccum/norm; double y2bar = walkers.ySquaredAccum/norm; xyFrame.append(0, step, xbar); xyFrame.append(1, step, ybar); x2y2Frame.append(0, Math.log(step), Math.log(x2bar-xbar*xbar)); x2y2Frame.append(1, Math.log(step), Math.log(y2bar-ybar*ybar)); datasets.append(0, Math.log(step), Math.log(x2bar-xbar*xbar+y2bar-ybar*ybar)); xyFrame.setMessage("# walkers = "+walkers.numberOfWalkers); drawingPanel.setMessage("time = "+step); } } /** * Resets to default values */ public void reset() { control.setValue("number of initial walkers", 100); control.setValue("number of steps", 1024); //control.setAdjustableValue("steps per display", 100); //control.setValue("Half lattice Size", 100); //enableStepsPerDisplay(true); xyFrame.clearData(); datasets.clear(); x2y2Frame.clearData(); } /** * Switch to the WRApp user interface. */ public void switchGUI() { stopSimulation(); Runnable runner = new Runnable() { public synchronized void run() { OSPRuntime.disableAllDrawing = true; OSPFrame mainFrame = getMainFrame(); XMLControlElement xml = new XMLControlElement(getOSPApp()); WindowListener[] listeners = mainFrame.getWindowListeners(); int closeOperation = mainFrame.getDefaultCloseOperation(); mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); mainFrame.setKeepHidden(true); mainFrame.dispose(); FlatWRApp app = new FlatWRApp(); FlatAppControl c = new FlatAppControl(app, app.r2Frame, null); c.getMainFrame().setDefaultCloseOperation(closeOperation); for(int i = 0, n = listeners.length; i<n; i++) { if(listeners[i].getClass().getName().equals("org.opensourcephysics.tools.Launcher$FrameCloser")) { c.getMainFrame().addWindowListener(listeners[i]); } } c.loadXML(xml, true); app.customize(); c.resetSimulation(); System.gc(); OSPRuntime.disableAllDrawing = false; GUIUtils.showDrawingAndTableFrames(); } }; Thread t = new Thread(runner); t.start(); } void customize() { OSPFrame f = getMainFrame(); if((f==null)||!f.isDisplayable()) { return; } JMenu menu = f.getMenu("Display"); JMenuItem item = new JMenuItem("Switch GUI"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { switchGUI(); } }); menu.add(item); addChildFrame(xyFrame); addChildFrame(x2y2Frame); addChildFrame(r2Frame); } /** * Starts the Java application. * @param args command line parameters */ public static void main(String[] args) { FlatApp app=new FlatApp(); SimulationControl.createApp(app); app.customize(); } } /* * Open Source Physics software is free software; you can redistribute * it and/or modify it under the terms of the GNU General Public License (GPL) as * published by the Free Software Foundation; either version 2 of the License, * or(at your option) any later version. * Code that uses any portion of the code in the org.opensourcephysics package * or any subpackage (subdirectory) of this package must must also be be released * under the GNU GPL license. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston MA 02111-1307 USA * or view the license online at http://www.gnu.org/copyleft/gpl.html * * Copyright (c) 2007 The Open Source Physics project * http://www.opensourcephysics.org */
gpl-3.0
qt-haiku/LibreOffice
qadevOOo/tests/java/mod/_sw/PageStyle.java
7807
/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ package mod._sw; import com.sun.star.beans.Property; import com.sun.star.beans.PropertyAttribute; import com.sun.star.beans.XPropertySet; import com.sun.star.container.XIndexAccess; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNameContainer; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.style.XStyle; import com.sun.star.style.XStyleFamiliesSupplier; import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import java.io.PrintWriter; import lib.StatusException; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import util.DesktopTools; import util.SOfficeFactory; import util.utils; /** * Test for object which is represented by service * <code>com.sun.star.style.PageStyle</code>. <p> * @see com.sun.star.style.PageStyle */ public class PageStyle extends TestCase { XTextDocument xTextDoc; SOfficeFactory SOF = null; /** * Creates text document. */ protected void initialize( TestParameters tParam, PrintWriter log ) { SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)tParam.getMSF() ); try { log.println( "creating a textdocument" ); xTextDoc = SOF.createTextDoc( null ); } catch ( com.sun.star.uno.Exception e ) { e.printStackTrace( log ); throw new StatusException( "Couldn't create document", e ); } } /** * Disposes text document. */ protected void cleanup( TestParameters tParam, PrintWriter log ) { log.println( " disposing xTextDoc " ); DesktopTools.closeDoc(xTextDoc); } protected TestEnvironment createTestEnvironment(TestParameters tParam, PrintWriter log) { TestEnvironment tEnv = null; XNameAccess oSFNA = null; XStyle oStyle = null; XStyle oMyStyle = null; log.println("creating a test environment"); try { log.println("getting style"); XStyleFamiliesSupplier oSFS = UnoRuntime.queryInterface(XStyleFamiliesSupplier.class, xTextDoc); XNameAccess oSF = oSFS.getStyleFamilies(); oSFNA = UnoRuntime.queryInterface( XNameAccess.class,oSF.getByName("PageStyles")); // get the page style XIndexAccess oSFIA = UnoRuntime.queryInterface(XIndexAccess.class, oSFNA); oStyle = UnoRuntime.queryInterface( XStyle.class,oSFIA.getByIndex(0)); log.println("Chosen pool style: "+oStyle.getName()); } catch ( com.sun.star.lang.WrappedTargetException e ) { log.println("Error: exception occurred."); e.printStackTrace(log); throw new StatusException( "Couldn't create environment ", e ); } catch ( com.sun.star.lang.IndexOutOfBoundsException e ) { log.println("Error: exception occurred."); e.printStackTrace(log); throw new StatusException( "Couldn't create environment ", e ); } catch ( com.sun.star.container.NoSuchElementException e ) { log.println("Error: exception occurred."); e.printStackTrace(log); throw new StatusException( "Couldn't create environment ", e ); } try { log.print("Creating a user-defined style... "); XMultiServiceFactory oMSF = UnoRuntime.queryInterface(XMultiServiceFactory.class, xTextDoc); XInterface oInt = (XInterface) oMSF.createInstance("com.sun.star.style.PageStyle"); // oMSF.createInstanceWithArguments("com.sun.star.style.PageStyle",new Object[]{oStyle}); oMyStyle = UnoRuntime.queryInterface(XStyle.class, oInt); } catch ( com.sun.star.uno.Exception e ) { log.println("Error: exception occurred."); e.printStackTrace(log); throw new StatusException( "Couldn't create environment ", e ); } if (oMyStyle == null) log.println("FAILED"); else log.println("OK"); XNameContainer oSFNC = UnoRuntime.queryInterface(XNameContainer.class, oSFNA); try { if ( oSFNC.hasByName("My Style") ) oSFNC.removeByName("My Style"); oSFNC.insertByName("My Style", oMyStyle); } catch ( com.sun.star.lang.WrappedTargetException e ) { e.printStackTrace(log); throw new StatusException( "Couldn't create environment ", e ); } catch ( com.sun.star.lang.IllegalArgumentException e ) { e.printStackTrace(log); throw new StatusException( "Couldn't create environment ", e ); } catch ( com.sun.star.container.NoSuchElementException e ) { e.printStackTrace(log); throw new StatusException( "Couldn't create environment ", e ); } catch ( com.sun.star.container.ElementExistException e ) { e.printStackTrace(log); throw new StatusException( "Couldn't create environment ", e ); } XText oText = xTextDoc.getText(); XTextCursor oCursor = oText.createTextCursor(); XPropertySet xProp = UnoRuntime.queryInterface(XPropertySet.class, oCursor); Property[] props = xProp.getPropertySetInfo().getProperties(); for (int i=0; i<props.length; i++) System.out.println("# Property: " + props[i].Name + " val: " + props[i].Type.toString() + " attr: " + props[i].Attributes); try { xProp.setPropertyValue("PageDescName", oMyStyle.getName()); } catch ( com.sun.star.lang.WrappedTargetException e ) { e.printStackTrace( log ); throw new StatusException( "Couldn't create environment ", e ); } catch ( com.sun.star.lang.IllegalArgumentException e ) { e.printStackTrace( log ); throw new StatusException( "Couldn't create environment ", e ); } catch ( com.sun.star.beans.PropertyVetoException e ) { e.printStackTrace( log ); throw new StatusException( "Couldn't create environment ", e ); } catch ( com.sun.star.beans.UnknownPropertyException e ) { e.printStackTrace( log ); throw new StatusException( "Couldn't create environment ", e ); } // oMyStyle = oStyle; log.println("creating a new environment for object"); tEnv = new TestEnvironment(oMyStyle); tEnv.addObjRelation("PoolStyle", oStyle); tEnv.addObjRelation("FollowStyle", "Envelope"); XPropertySet xStyleProp = UnoRuntime.queryInterface(XPropertySet.class, oMyStyle); short exclude = PropertyAttribute.READONLY; String[] names = utils.getFilteredPropertyNames(xStyleProp, (short)0, exclude); tEnv.addObjRelation("PropertyNames", names); return tEnv; } }
gpl-3.0
jatecs/jatecs
src/example/java/apps/output/DumpFeatureRelevance.java
4054
/* * This file is part of JaTeCS. * * JaTeCS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JaTeCS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JaTeCS. If not, see <http://www.gnu.org/licenses/>. * * The software has been mainly developed by (in alphabetical order): * - Andrea Esuli (andrea.esuli@isti.cnr.it) * - Tiziano Fagni (tiziano.fagni@isti.cnr.it) * - Alejandro Moreo Fernández (alejandro.moreo@isti.cnr.it) * Other past contributors were: * - Giacomo Berardi (giacomo.berardi@isti.cnr.it) */ package apps.output; import it.cnr.jatecs.indexes.DB.interfaces.IIndex; import it.cnr.jatecs.indexes.DB.troveCompact.TroveClassificationDBType; import it.cnr.jatecs.indexes.DB.troveCompact.TroveContentDBType; import it.cnr.jatecs.indexes.DB.troveCompact.TroveReadWriteHelper; import it.cnr.jatecs.indexing.tsr.InformationGain; import it.cnr.jatecs.io.FileSystemStorageManager; import it.cnr.jatecs.utils.Os; import it.cnr.jatecs.utils.iterators.interfaces.IIntIterator; import it.cnr.jatecs.utils.iterators.interfaces.IShortIterator; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Arrays; import java.util.Comparator; public class DumpFeatureRelevance { public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Usage: DumpFeatureRelevance <indexDirectory>"); return; } File file = new File(args[0]); String indexName = file.getName(); String dataPath = file.getParent(); FileSystemStorageManager storageManager = new FileSystemStorageManager( dataPath, false); storageManager.open(); IIndex index = TroveReadWriteHelper.readIndex(storageManager, indexName, TroveContentDBType.Full, TroveClassificationDBType.Full); storageManager.close(); InformationGain ig = new InformationGain(); if (indexName.endsWith(".idx")) { indexName = indexName.substring(0, indexName.length() - 4); } IShortIterator cats = index.getCategoryDB().getCategories(); while (cats.hasNext()) { short cat = cats.next(); String catName = index.getCategoryDB().getCategoryName(cat); Object[][] objects = new Object[index.getFeatureDB() .getFeaturesCount()][3]; IIntIterator feats = index.getFeatureDB().getFeatures(); int counter = 0; while (feats.hasNext()) { int feat = feats.next(); String featName = index.getFeatureDB().getFeatureName(feat); double value = ig.compute(cat, feat, index); objects[counter][0] = value; objects[counter][1] = feat; objects[counter][2] = featName; ++counter; } Arrays.sort(objects, new Comparator<Object[]>() { @SuppressWarnings({"rawtypes", "unchecked"}) public int compare(Object[] o1, Object[] o2) { return ((Comparable) o2[0]).compareTo(o1[0]); } }); BufferedWriter writer = new BufferedWriter( new FileWriter(dataPath + Os.pathSeparator() + indexName + "_rank-" + catName, true)); for (Object[] tuple : objects) { writer.write(tuple[0] + "\t" + tuple[1] + "\t" + tuple[2] + "\n"); } writer.close(); } } }
gpl-3.0
libdeos/deos-rsksmart
lib/rskj/rskj-core/src/main/java/co/rsk/net/handler/txvalidator/TxFilterAccumCostFilter.java
2121
/* * This file is part of RskJ * Copyright (C) 2017 RSK Labs Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.rsk.net.handler.txvalidator; import co.rsk.net.handler.TxsPerAccount; import org.ethereum.core.AccountState; import org.ethereum.core.Transaction; import java.math.BigInteger; import java.util.LinkedList; import java.util.List; /** * Checks if the sum cost of all transactions of a given account considering * gaslimit, gasprice and value can be covered by the account balance in nonce * order */ public class TxFilterAccumCostFilter implements TxFilter { @Override public List<Transaction> filter(AccountState state, TxsPerAccount tpa) { BigInteger accumTxCost = BigInteger.valueOf(0); tpa.getTransactions().sort((t1, t2) -> { BigInteger n1 = new BigInteger(1, t1.getNonce()); BigInteger n2 = new BigInteger(1, t2.getNonce()); return n1.compareTo(n2); }); List<Transaction> newTxs = new LinkedList<>(); for (Transaction t : tpa.getTransactions()) { BigInteger gasCost = new BigInteger(1, t.getGasLimit()).multiply(new BigInteger(1, t.getGasPrice())); if (accumTxCost.add(gasCost).compareTo(state.getBalance()) > 0) { break; } accumTxCost = accumTxCost.add(gasCost); accumTxCost = accumTxCost.add(new BigInteger(1, t.getValue())); newTxs.add(t); } return newTxs; } }
gpl-3.0
NYRDS/pixel-dungeon-remix
RemixedDungeon/src/main/java/com/watabou/pixeldungeon/windows/WndInfoMob.java
4230
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.pixeldungeon.windows; import com.nyrds.pixeldungeon.windows.HBox; import com.nyrds.pixeldungeon.windows.VHBox; import com.nyrds.platform.util.StringsManager; import com.nyrds.util.GuiProperties; import com.watabou.noosa.ColorBlock; import com.watabou.noosa.Text; import com.watabou.noosa.ui.Component; import com.watabou.pixeldungeon.actors.Char; import com.watabou.pixeldungeon.actors.CharUtils; import com.watabou.pixeldungeon.actors.mobs.Mob; import com.watabou.pixeldungeon.scenes.PixelScene; import com.watabou.pixeldungeon.sprites.CharSprite; import com.watabou.pixeldungeon.ui.BuffIndicator; import com.watabou.pixeldungeon.ui.RedButton; import com.watabou.pixeldungeon.utils.Utils; import org.jetbrains.annotations.NotNull; import lombok.Getter; public class WndInfoMob extends WndTitledMessage { private static final float BUTTON_WIDTH = 36; @Getter private Char target; public WndInfoMob(Char mob, @NotNull Char selector ) { super( new MobTitle( mob ), desc( mob, true ) ); target = mob; VHBox actions = new VHBox(width - 2* GAP); actions.setAlign(HBox.Align.Width); actions.setGap(GAP); if (selector.isAlive()) { for (final String action: CharUtils.actions(target, selector )) { RedButton btn = new RedButton(StringsManager.maybeId(action)) { @Override protected void onClick() { CharUtils.execute(mob, selector, action); hide(); } }; btn.setSize( Math.max( BUTTON_WIDTH, btn.reqWidth() ), BUTTON_HEIGHT ); actions.add(btn); } } add(actions); actions.setPos(GAP, height+2*GAP); resize( width, (int) (actions.bottom() + GAP)); } public WndInfoMob( Mob mob, int knowledge) { super( new MobTitle( mob ), desc( mob, false) ); } private static String desc(Char mob, boolean withStatus ) { if(withStatus) { return mob.getDescription() + "\n\n" + Utils.capitalize(mob.getState().status(mob)) + "."; } else { return mob.getDescription(); } } private static class MobTitle extends Component { private static final int COLOR_BG = 0xFFCC0000; private static final int COLOR_LVL = 0xFF00EE00; private static final int BAR_HEIGHT = 2; private CharSprite image; private Text name; private ColorBlock hpBg; private ColorBlock hpLvl; private BuffIndicator buffs; private float hp; public MobTitle(@NotNull Char mob ) { hp = (float)mob.hp() / mob.ht(); name = PixelScene.createText( Utils.capitalize( mob.getName() ), GuiProperties.titleFontSize()); name.hardlight( TITLE_COLOR ); add( name ); image = mob.newSprite(); add( image ); hpBg = new ColorBlock( 1, 1, COLOR_BG ); add( hpBg ); hpLvl = new ColorBlock( 1, 1, COLOR_LVL ); add( hpLvl ); buffs = new BuffIndicator( mob ); add( buffs ); } @Override protected void layout() { image.x = 0 - image.visualOffsetX(); image.y = Math.max( 0, name.height() + GAP + BAR_HEIGHT - image.visualHeight()) - image.visualOffsetY(); name.x = image.visualWidth() + GAP; name.y = image.visualHeight() - BAR_HEIGHT - GAP - name.baseLine(); float w = width - image.visualWidth() - GAP; hpBg.size( w, BAR_HEIGHT ); hpLvl.size( w * hp, BAR_HEIGHT ); hpBg.x = hpLvl.x = image.visualWidth() + GAP; hpBg.y = hpLvl.y = image.visualHeight() - BAR_HEIGHT; buffs.setPos( name.x + name.width() + GAP, name.y + name.baseLine() - BuffIndicator.ICON_SIZE ); height = hpBg.y + hpBg.height(); } } }
gpl-3.0
ratrecommends/dice-heroes
main/src/com/vlaaad/dice/game/tutorial/tasks/ForceDragAbilityOnFreeSlot.java
2169
/* * Dice heroes is a turn based rpg-strategy game where characters are dice. * Copyright (C) 2016 Vladislav Protsenko * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.vlaaad.dice.game.tutorial.tasks; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.scenes.scene2d.Actor; import com.vlaaad.common.tutorial.tasks.ForceDragActor; import com.vlaaad.dice.Config; import com.vlaaad.dice.game.config.abilities.Ability; import com.vlaaad.dice.game.user.Die; import com.vlaaad.dice.game.user.UserData; import com.vlaaad.dice.states.GameMapState; /** * Created 14.11.13 by vlaaad */ public class ForceDragAbilityOnFreeSlot extends ForceDragActor { private final String dieName; private final String abilityName; public ForceDragAbilityOnFreeSlot(String dieName, String abilityName) { super(); this.dieName = dieName; this.abilityName = abilityName; } @Override protected Actor getActor() { Ability ability = Config.abilities.get(abilityName); UserData userData = resources.get("userData"); Die die = userData.findDieByName(dieName); GameMapState mapState = resources.get("map"); return mapState.diceWindow.getPane(die).inventory.getInventoryIcon(ability); } @Override protected Rectangle[] getTargets() { UserData userData = resources.get("userData"); Die die = userData.findDieByName(dieName); GameMapState mapState = resources.get("map"); return mapState.diceWindow.getPane(die).net.getEmptyPlaces(); } }
gpl-3.0
erickok/RateBeer-Mobile
src/dk/moerks/ratebeermobile/adapters/SearchAdapter.java
3567
/* * Copyright 2010, Jesper Fussing Mørk * * This file is part of Ratebeer Mobile for Android. * * Ratebeer Mobile is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Ratebeer Mobile is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Ratebeer Mobile. If not, see <http://www.gnu.org/licenses/>. */ package dk.moerks.ratebeermobile.adapters; import java.util.List; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import dk.moerks.ratebeermobile.R; import dk.moerks.ratebeermobile.util.StringUtils; import dk.moerks.ratebeermobile.vo.SearchResult; public class SearchAdapter extends ArrayAdapter<SearchResult> { Activity context; List<SearchResult> results; public SearchAdapter(Activity context, List<SearchResult> results){ super(context, R.layout.search_row, results); this.context = context; this.results = results; } @Override public View getView(int position, View convertView, ViewGroup parent){ View row = convertView; try { if (row == null) { LayoutInflater inflater = LayoutInflater.from(this.context); row = inflater.inflate(R.layout.search_row, null); } ImageView icon = (ImageView) row.findViewById(R.id.search_row_icon); if(results.get(position).isRated()){ icon.setImageResource(R.drawable.israted); } else { icon.setImageResource(R.drawable.isnotrated); } TextView name = (TextView)row.findViewById(R.id.search_row_name); name.setText(StringUtils.cleanHtml(results.get(position).getBeerName())); TextView percentile = (TextView)row.findViewById(R.id.search_row_percentile); if(results.get(position).getBeerPercentile().equalsIgnoreCase("")){ percentile.setText(context.getText(R.string.view_score) + "\n" + context.getText(R.string.view_scorena)); } else { percentile.setText(context.getText(R.string.view_score) + "\n" + results.get(position).getBeerPercentile()); } TextView ratings = (TextView)row.findViewById(R.id.search_row_ratings); ratings.setText(context.getText(R.string.view_ratings) + "\n" + results.get(position).getBeerRatings()); TextView additional = (TextView)row.findViewById(R.id.search_row_additional); boolean isRetired = results.get(position).isRetired(); boolean isAlias = results.get(position).isAlias(); additional.setVisibility((!isRetired && !isAlias)? View.GONE: View.VISIBLE); if (isRetired && isAlias) { additional.setText(context.getText(R.string.view_information) + "\n" + context.getText(R.string.view_retalias)); } else if (isAlias) { additional.setText(context.getText(R.string.view_information) + "\n" + context.getText(R.string.view_alias)); } else if(isRetired) { additional.setText(context.getText(R.string.view_information) + "\n" + context.getText(R.string.view_retired)); } /*} else { additional.setText("Information\nAvailable"); }*/ } catch (Exception e) { e.printStackTrace(); } return row; } }
gpl-3.0
innovad/4mila
backend/src/main/java/com/_4mila/backend/service/course/iof2/xml/Time.java
2131
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2011.07.09 at 05:12:48 PM MESZ // package com._4mila.backend.service.course.iof2.xml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @XmlRootElement(name = "Time") public class Time { @XmlAttribute @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String timeFormat; @XmlValue protected String value; /** * Gets the value of the timeFormat property. * * @return * possible object is * {@link String } * */ public String getTimeFormat() { if (timeFormat == null) { return "MM:SS"; } else { return timeFormat; } } /** * Sets the value of the timeFormat property. * * @param value * allowed object is * {@link String } * */ public void setTimeFormat(String value) { this.timeFormat = value; } /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getvalue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setvalue(String value) { this.value = value; } }
gpl-3.0
TUD-IfC/WebGen-WPS
src/ch/unizh/geo/webgen/service/LineSmoothing.java
8375
package ch.unizh.geo.webgen.service; import java.util.ArrayList; import java.util.Iterator; import ch.unizh.geo.algorithms.snakes.SnakesSmoothingLineNew; import ch.unizh.geo.geomutilities.InterpolateLinePoints; import ch.unizh.geo.measures.TAFandCurvature; import ch.unizh.geo.webgen.registry.AttributeDescription; import ch.unizh.geo.webgen.registry.InterfaceDescription; import ch.unizh.geo.webgen.server.AWebGenAlgorithm; import ch.unizh.geo.webgen.server.IWebGenAlgorithm; import ch.unizh.geo.webgen.server.WebGenRequest; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.feature.FeatureCollection; import com.vividsolutions.jump.feature.FeatureDataset; /** * @descrption: * smoothes lines and polygons with a snakes algorithm * needed parameters: * FeatureCollection => Feature => Geometry : LineString or Polygon * tolerance : maximum displacement * segmentate : should the line be segmentated * further params initilized in this file: * start params Snakes: alpha und beta (init = 1) * segmentation value: curvature (init = Pi/3) * * @author sstein * * */ public class LineSmoothing extends AWebGenAlgorithm implements IWebGenAlgorithm { private double segmentCurvThreshold = Math.PI/3; double alpha = 1; double beta = 1; double minPoints = 6; public void run(WebGenRequest wgreq) { FeatureCollection fc = wgreq.getFeatureCollection("geom"); double tolerance = wgreq.getParameterDouble("tolerance"); boolean segmentate = wgreq.getParameterBoolean("segmentation"); try { FeatureCollection fcnew = smoothFC(fc, tolerance, segmentate); wgreq.addResult("result", fcnew); } catch(Exception e) {} } public FeatureCollection smoothFC(FeatureCollection fc, double tolerance, boolean doSegmentation) throws Exception { System.gc(); //flush garbage collector FeatureCollection fcnew = new FeatureDataset(fc.getFeatureSchema()); for (Iterator i = fc.iterator(); i.hasNext();) { Geometry newgeo; Feature f = (Feature)((Feature)i.next()).clone(); newgeo = this.smoothSingle(f.getGeometry(),tolerance, doSegmentation); f.setGeometry(newgeo); fcnew.add(f); } return fcnew; } private Geometry smoothSingle(Geometry geom, double maxDisp, boolean segmentate) throws Exception{ Geometry resultgeom = null; int geomType = 0; int polyRing = 0; LineString line = null; Polygon poly = null; if(geom instanceof LineString){ line = (LineString)geom; geomType = 1; } else if(geom instanceof Polygon){ poly = (Polygon)geom; line = poly.getExteriorRing(); geomType = 2; polyRing = 0; } else{ geomType = 0; } /****************************************/ if (geomType > 0){ if(line.getNumPoints() <= this.minPoints){ line = InterpolateLinePoints.addMiddlePoints(line); System.out.println("LineSmoothSimpleVersion.smooth1: to short " + "line found with" + line.getNumPoints() + "points. Points added"); } int[] pointidx = null; if(segmentate==true){ System.out.println("segmentation = true"); System.out.println("angle criteria in rad: " + this.segmentCurvThreshold); pointidx = this.calcSegments(line, this.segmentCurvThreshold); } else{ System.out.println("segmentation = false"); } //-- smoothing SnakesSmoothingLineNew ssmooth = new SnakesSmoothingLineNew(line, maxDisp, this.alpha, this.beta, segmentate, pointidx); LineString result = ssmooth.getSmoothedLine(); //-- update geometry -------- if (geomType == 1){ //linestring Coordinate[] coords =line.getCoordinates(); for (int j=0; j < coords.length; j++){ coords[j] = result.getCoordinateN(j); } resultgeom = line; } else if (geomType == 2){ //polygon LineString extring = poly.getExteriorRing(); Coordinate[] coords =extring.getCoordinates(); for (int j=0; j < coords.length; j++){ coords[j] = result.getCoordinateN(j); } //-- smooth innner rings if exists, and update as well if (poly.getNumInteriorRing() > 0){ for(int j=0; j < poly.getNumInteriorRing(); j++){ line = poly.getInteriorRingN(j); if(line.getNumPoints() <= this.minPoints){ line = InterpolateLinePoints.addMiddlePoints(line); System.out.println("LineSmoothSimpleVersion.smooth1: to short " + "line found with" + line.getNumPoints() + "points. Points added"); } pointidx = null; if(segmentate==true){ //System.out.println("segmentation = true"); pointidx = this.calcSegments(line, this.segmentCurvThreshold); } else{ //System.out.println("segmentation = false"); } //-- smoothing ssmooth = new SnakesSmoothingLineNew(line, maxDisp, this.alpha, this.beta, segmentate, pointidx); result = ssmooth.getSmoothedLine(); coords =line.getCoordinates(); for (int u=0; u < coords.length; u++){ coords[u] = result.getCoordinateN(u); } } } resultgeom = poly; } String mytext = "item : smoothing finalized"; if (ssmooth.isCouldNotSmooth() == true){mytext = "item: not smoothed since to small threshold!!!";} //context.getWorkbenchFrame().setStatusMessage(mytext); //System.out.println(mytext); }//end if : polygon or linestring return resultgeom; } private int[] calcSegments(LineString line, double segmentationValue){ TAFandCurvature myTafCalc = new TAFandCurvature(line); double[] curv = myTafCalc.getCurvature(); ArrayList myPoints = new ArrayList(); System.out.println("curvature values:"); for(int j=0; j < curv.length; j++){ System.out.print(curv[j] + ", "); if ( Math.abs(curv[j]) > segmentationValue){ if ((j > 0) && (j < curv.length-1)){ myPoints.add(new Integer(j)); } } } System.out.println(" "); System.out.println("no. of segmentation points: " + myPoints.size()); int[] pointIdxList= new int[myPoints.size()]; int j=0; for (Iterator iter = myPoints.iterator(); iter.hasNext();) { Integer element = (Integer) iter.next(); pointIdxList[j] = element.intValue(); System.out.print(element.intValue() + " "); j=j+1; } System.out.println(" "); return pointIdxList; } public InterfaceDescription getInterfaceDescription() { InterfaceDescription id = new InterfaceDescription("LineSmoothing", "sstein", "operator", "", "LineSmoothing", "Line Smoothing", "1.0", new String[] {"ica.genops.cartogen.Enhancement"}); id.visible = true; //add input parameters String[] allowed = {"LineString"}; id.addInputParameter("geom", "FeatureCollection", new AttributeDescription("GEOMETRY", "GEOMETRY", allowed), "layer with geometries"); id.addInputParameter("tolerance", "DOUBLE", "10.0", "tolerance"); id.addInputParameter("segmentation", "BOOLEAN", "false", "segmentation"); //add output parameters id.addOutputParameter("result", "FeatureCollection", new AttributeDescription("GEOMETRY", "GEOMETRY", allowed), "smoothed lines"); return id; } }
gpl-3.0
matttbe/bouboule
Bouboule/src/be/ac/ucl/lfsab1509/bouboule/game/menu/GdxMenus.java
2807
package be.ac.ucl.lfsab1509.bouboule.game.menu; import com.badlogic.gdx.Gdx; import be.ac.ucl.lfsab1509.bouboule.game.gameManager.GlobalSettings; import be.ac.ucl.lfsab1509.bouboule.game.screen.GameOverScreen; import be.ac.ucl.lfsab1509.bouboule.game.screen.LooseScreen; import be.ac.ucl.lfsab1509.bouboule.game.screen.MenuScreen; import be.ac.ucl.lfsab1509.bouboule.game.screen.WinScreen; /* * This file is part of Bouboule. * * Copyright 2013 UCLouvain * * Authors: * * Group 7 - Course: http://www.uclouvain.be/en-cours-2013-lfsab1509.html * Matthieu Baerts <matthieu.baerts@student.uclouvain.be> * Baptiste Remy <baptiste.remy@student.uclouvain.be> * Nicolas Van Wallendael <nicolas.vanwallendael@student.uclouvain.be> * Helene Verhaeghe <helene.verhaeghe@student.uclouvain.be> * * Bouboule is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ public class GdxMenus implements Menus { @Override public void launchInitMenu() { Gdx.app.log ("Matth", "GdxMenus: InitMenu: " + GlobalSettings.GAME_EXIT); GlobalSettings.GAME.setScreen(new MenuScreen()); } @Override public void launchEndGameMenu() { Gdx.app.log ("Matth", "GdxMenus: EndGameMenu: " + GlobalSettings.GAME_EXIT); // we need a pause to call the same methods that when using Android menus GlobalSettings.GAME.setScreenGamePause(); switch (GlobalSettings.GAME_EXIT) { case NONE : return; case WIN : GlobalSettings.GAME.winSound(); GlobalSettings.GAME.setScreen(new WinScreen()); break; case LOOSE : GlobalSettings.GAME.looseSound(); GlobalSettings.GAME.setScreen(new LooseScreen()); break; case GAMEOVER_LOOSE : GlobalSettings.GAME.looseSound(); GlobalSettings.GAME.setScreen(new GameOverScreen(false)); break; case GAMEOVER_END : GlobalSettings.GAME.winSound(); GlobalSettings.GAME.setScreen(new GameOverScreen(true)); break; } } @Override public void launchPauseMenu() { Gdx.app.log ("Matth", "GdxMenus: PauseMenu: " + GlobalSettings.GAME_EXIT); if (GlobalSettings.GAME.isGameScreen()) { GlobalSettings.GAME.toogleGeneralPause(); if (GlobalSettings.GAME.isGeneralPause()) GlobalSettings.GAME.getScreen().pause(); } } }
gpl-3.0
zeatul/poc
e-commerce/e-commerce-ecom-pay-service/src/main/java/com/alipay/api/domain/AlipayEcoCplifeBasicserviceInitializeModel.java
3887
package com.alipay.api.domain; import java.util.Date; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 初始化小区物业基础服务 * * @author auto create * @since 1.0, 2017-03-24 11:43:21 */ public class AlipayEcoCplifeBasicserviceInitializeModel extends AlipayObject { private static final long serialVersionUID = 5445964798791234924L; /** * 若服务类型为物业缴费账单模式,每个小区默认的收款帐号为授权物业的支付宝账号,默认不用传该参数。 但为满足部分物业公司财务要求,允许开发者为每个小区服务传入一个指定的物业收款帐号。根据不同账号类型(account_type),开发者需要向物业或支付宝商务支持接口人获取具体的收款帐号。 */ @ApiField("account") private String account; /** * 若服务类型为物业缴费账单模式,每个小区默认的收款账号为授权物业的支付宝账号,默认不用传该参数。用户完成缴费后实时入账至该支付宝账号,后续由物业财务系统根据缴费异步通知和支付宝对账文件进行资金清分。 但为了满足部分物业公司的财务清结算需求,允许在授权物业账号下已设置支付宝收款子账号限制集的前提下,由开发者为指定小区服务传入一个物业公司的支付宝收款子帐号,支持通过以下任一种形式传递该账号: ALIPAY_LOGON_ID - 支付宝登陆账号。 ALIPAY_PARTNER_ID - 支付宝登陆账号对应的用户ID,2088开头的16位纯数字用户号。 注意:若传递的收款子账号事先未在支付宝配置,开发者在上线前的支付验证环节会提示不支持收款到该账户,请联系物业公司完成配置事宜。 */ @ApiField("account_type") private String accountType; /** * 支付宝社区小区统一编号,必须在物业账号名下存在。 */ @ApiField("community_id") private String communityId; /** * 由开发者系统提供的,支付宝根据基础服务类型在特定业务环节调用的外部系统服务地址,开发者需要确保外部地址的准确性。在线上环境需要使用HTTPS协议,会检查ssl证书,要求证书为正规的证书机构签发,不支持自签名证书。 对于PROPERTY_PAY_BILL_MODE服务类型,该地址表示用户缴费支付完成后开发者系统接受支付结果通知的回调地址。 */ @ApiField("external_invoke_address") private String externalInvokeAddress; /** * 若本服务有预期的过期时间(如在物业服务合同中约定),开发者按标准时间格式:yyyy-MM-dd HH:mm:ss传入。 */ @ApiField("service_expires") private Date serviceExpires; /** * 基础服务类型,目前支持的类型值为: PROPERTY_PAY_BILL_MODE - 物业缴费账单上传模式 */ @ApiField("service_type") private String serviceType; public String getAccount() { return this.account; } public void setAccount(String account) { this.account = account; } public String getAccountType() { return this.accountType; } public void setAccountType(String accountType) { this.accountType = accountType; } public String getCommunityId() { return this.communityId; } public void setCommunityId(String communityId) { this.communityId = communityId; } public String getExternalInvokeAddress() { return this.externalInvokeAddress; } public void setExternalInvokeAddress(String externalInvokeAddress) { this.externalInvokeAddress = externalInvokeAddress; } public Date getServiceExpires() { return this.serviceExpires; } public void setServiceExpires(Date serviceExpires) { this.serviceExpires = serviceExpires; } public String getServiceType() { return this.serviceType; } public void setServiceType(String serviceType) { this.serviceType = serviceType; } }
gpl-3.0
Echtzeitsysteme/mindroid
impl/androidApp/app/src/main/java/org/mindroid/android/app/programs/dev/demo/Domino.java
1785
package org.mindroid.android.app.programs.dev.demo; import org.mindroid.api.ImperativeWorkshopAPI; import org.mindroid.common.messages.server.MindroidMessage; import org.mindroid.impl.brick.Button; import java.util.Arrays; public class Domino extends ImperativeWorkshopAPI { private final String WALL_MSG = "Wall found!"; private final String LEADER_MSG = "I am the leader!"; public Domino(){ super("Domino", 3); } @Override public void run() { boolean leader = false; while(!isInterrupted()) { if (isButtonClicked(Button.ENTER)) { sendBroadcastMessage(LEADER_MSG); leader = true; break; }else if (hasMessage()) { MindroidMessage msg = getNextMessage(); sendLogMessage("I received a message: " + msg.getSource().getValue() + ": \"" + msg.getContent() + "\""); if (msg.getContent().equals(LEADER_MSG)) { //Colleague is the leader sendLogMessage("I am NOT the leader!"); break; } } delay(10); } if(!leader){ waitForMessage(); turnLeft(180); } setMotorSpeed(200); forward(); while(!isInterrupted() && getDistance() > 20){ delay(10); } stop(); sendBroadcastMessage(WALL_MSG); while(!isInterrupted()) delay(50); } private void waitForMessage(){ boolean waitOver = false; while (!isInterrupted() && !waitOver) { delay(10); if (hasMessage()) { MindroidMessage msg = getNextMessage(); if (msg.getContent().equals(WALL_MSG)) { sendLogMessage("I received: " + msg.getContent()); if (getDistance() < 30){ waitOver = true; sendLogMessage("I am the chosen one"); } } } } } }
gpl-3.0
josanuz/Inge_UNA_20
src/Modelo/Beans/Articulo_Proveedor.java
1883
/* * 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 Modelo.Beans; import javafx.beans.property.DoubleProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleIntegerProperty; /** * * @author Juan */ public class Articulo_Proveedor { public Articulo_Proveedor(Integer codigo_articulo,Integer codigo_proveedor,Double precio_compra){ this.codigo_articulo = new SimpleIntegerProperty(codigo_articulo); this.codigo_proveedor = new SimpleIntegerProperty(codigo_proveedor); this.precio_compra = new SimpleDoubleProperty(precio_compra); } public IntegerProperty codigo_articuloProperty(){ return this.codigo_articulo; } public IntegerProperty codigo_proveedorProperty(){ return this.codigo_proveedor; } public DoubleProperty precioCompraProperty(){ return this.precio_compra; } public Integer getCodigo_articulo() { return codigo_articulo.get(); } public void setCodigo_articulo(Integer codigo_articulo) { this.codigo_articulo.set(codigo_articulo); } public Integer getCodigo_proveedor() { return codigo_proveedor.get(); } public void setCodigo_proveedor(Integer codigo_proveedor) { this.codigo_proveedor.set(codigo_proveedor); } public Double getPrecio_compra() { return precio_compra.get(); } public void setPrecio_compra(Double precio_compra) { this.precio_compra.set(precio_compra); } private IntegerProperty codigo_articulo; private IntegerProperty codigo_proveedor; private DoubleProperty precio_compra; }
gpl-3.0
apruden/agate
agate-core/src/test/java/org/obiba/agate/assertj/Assertions.java
103
package org.obiba.agate.assertj; public class Assertions extends org.assertj.core.api.Assertions { }
gpl-3.0
jasmeet17/sbc-qsystem
QSkyApi/src/java/ru/apertum/qsky/web/PieChartVM.java
4263
/* * 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 ru.apertum.qsky.web; import org.zkoss.bind.annotation.BindingParam; import org.zkoss.bind.annotation.GlobalCommand; import org.zkoss.bind.annotation.NotifyChange; import org.zkoss.zul.PieModel; import java.awt.Color; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import org.apache.commons.lang.StringUtils; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.DefaultDrawingSupplier; import org.jfree.chart.plot.PiePlot; import org.zkoss.util.resource.Labels; import org.zkoss.zkex.zul.impl.JFreeChartEngine; import org.zkoss.zul.Chart; import org.zkoss.zul.SimplePieModel; public class PieChartVM { public static String l(String resName) { return Labels.getLabel(resName); } private final PieChartEngine engine; PieModel model; public PieChartVM() { // prepare chart data engine = new PieChartEngine(); model = PieChartData.getModel(); } public PieChartEngine getEngine() { return engine; } public PieModel getModel() { return model; } public void setModel(PieModel model) { this.model = model; } @GlobalCommand("dataChanged") @NotifyChange("model") public void onDataChanged(@BindingParam("category") String category, @BindingParam("num") Number num) { model.setValue(category, num); } public static class PieChartEngine extends JFreeChartEngine { private boolean explode = true; @Override public boolean prepareJFreeChart(JFreeChart jfchart, Chart chart) { jfchart.setBackgroundPaint(Color.white); final PiePlot piePlot = (PiePlot) jfchart.getPlot(); piePlot.setLabelBackgroundPaint(ChartColors.COLOR_4); //override some default colors final Paint[] colors = new Paint[]{ChartColors.COLOR_1, ChartColors.COLOR_2, ChartColors.COLOR_3, ChartColors.COLOR_4, ChartColors.COLOR_5, ChartColors.COLOR_6, ChartColors.COLOR_7, ChartColors.COLOR_8, ChartColors.COLOR_9, ChartColors.COLOR_10}; DefaultDrawingSupplier defaults = new DefaultDrawingSupplier(); piePlot.setDrawingSupplier(new DefaultDrawingSupplier(colors, new Paint[]{defaults.getNextFillPaint()}, new Paint[]{defaults.getNextOutlinePaint()}, new Stroke[]{defaults.getNextStroke()}, new Stroke[]{defaults.getNextOutlineStroke()}, new Shape[]{defaults.getNextShape()})); piePlot.setShadowPaint(new Color(0xE5E5E5)); piePlot.setSectionOutlinesVisible(false); piePlot.setExplodePercent(l("refresh_data"), explode ? 0.2 : 0); return false; } public void setExplode(boolean explode) { this.explode = explode; } } private static class PieChartData { public static PieModel getModel() { PieModel model = new SimplePieModel(); model.setValue(l("refresh_data"), 100); return model; } } private static class ChartColors { //main colors public static Color COLOR_1 = new Color(0x96FFE6); public static Color COLOR_2 = new Color(0x1C85FF); public static Color COLOR_3 = new Color(0xFF1692); public static Color COLOR_4 = new Color(0xFFFA0A); public static Color COLOR_5 = new Color(0x0FFFFF); //additional colors public static Color COLOR_6 = new Color(0xFF0CFF); public static Color COLOR_7 = new Color(0x1CFF85); public static Color COLOR_8 = new Color(0x780AFF); public static Color COLOR_9 = new Color(0xFF530F); public static Color COLOR_10 = new Color(0x1CFF36); public static String toHtmlColor(Color color) { return "#" + toHexColor(color); } public static String toHexColor(Color color) { return StringUtils.leftPad(Integer.toHexString(color.getRGB() & 0xFFFFFF), 6, '0'); } } }
gpl-3.0
dougmencken/bytecodemaker
source/plugins/attributes/Class$SourceFile.java
1114
/* * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. */ package douglas.mencken.bm.plugins.attr; import java.awt.Component; import java.io.*; import douglas.mencken.tools.AttributeSupport; /** * <code>Class$SourceFile</code> * * @version 1.0d * @since Bytecode Maker 0.6.0 */ public class Class$SourceFile extends Object implements AttributeSupport { private int attributeLength; public Class$SourceFile() { super(); } public int getAttributeLength() { return this.attributeLength; } public String getAttributeName() { return "SourceFile"; } public int getAttributeLevel() { return AttributeSupport.ATTRIBUTE_LEVEL_CLASS; } public void readAttribute(ObjectInput in) throws IOException { // ... } public void writeAttribute(ObjectOutput in) throws IOException { // ... } public Component getAttributeEditor() { return null; } public void plugin() {} }
gpl-3.0
BlenderViking/NewPipe
app/src/main/java/org/schabi/newpipe/info_list/SimpleItemTouchHelperCallback.java
1320
package org.schabi.newpipe.info_list; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback { private final ItemTouchHelperAdapter mAdapter; public SimpleItemTouchHelperCallback(ItemTouchHelperAdapter adapter) { mAdapter = adapter; } @Override public boolean isLongPressDragEnabled() { return true; } @Override public boolean isItemViewSwipeEnabled() { return true; } @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN; int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END; return makeMovementFlags(dragFlags, swipeFlags); } @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { mAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition()); return true; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { mAdapter.onItemDismiss(viewHolder.getAdapterPosition()); } }
gpl-3.0
dotCMS/core
dotCMS/src/main/java/com/dotcms/rendering/velocity/viewtools/cache/XSLTransformationCache.java
3446
package com.dotcms.rendering.velocity.viewtools.cache; import java.util.Date; import com.dotmarketing.beans.Identifier; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.CacheLocator; import com.dotmarketing.business.DotCacheAdministrator; import com.dotmarketing.business.DotCacheException; import com.dotmarketing.business.UserAPI; import com.dotmarketing.business.VersionableAPI; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.util.Logger; import com.dotcms.rendering.velocity.viewtools.bean.XSLTranformationDoc; /** * This class manage the XSLTransformation plugin cache * @author Oswaldo */ public class XSLTransformationCache { private static final UserAPI userAPI = APILocator.getUserAPI(); private static final VersionableAPI versionableAPI = APILocator.getVersionableAPI(); /** * Add into the cache the XSL transformation Doc * @param doc XSLTranformationDoc */ public static void addXSLTranformationDoc(XSLTranformationDoc doc){ DotCacheAdministrator cache = CacheLocator.getCacheAdministrator(); // we use the identifier uri for our mappings. String xmlPath = doc.getXmlPath(); String xslPath = doc.getXslPath(); cache.put(getPrimaryGroup() + xmlPath+"_"+xslPath, doc, getPrimaryGroup()); } /** * Get the XSLTranformationDoc by the xml path * @param XMLPath XML path * @param XSLPath XSL path * @return XSLTranformationDoc */ public static XSLTranformationDoc getXSLTranformationDocByXMLPath(String XMLPath,String XSLPath) { DotCacheAdministrator cache = CacheLocator.getCacheAdministrator(); XSLTranformationDoc doc = null; try{ doc = (XSLTranformationDoc) cache.get(getPrimaryGroup() + XMLPath+"_"+XSLPath, getPrimaryGroup()); }catch (DotCacheException e) { Logger.debug(XSLTransformationCache.class,"Cache Entry not found", e); } if (doc != null) { try{ /*validate if xsl file change*/ Identifier xslIdentifier = APILocator.getIdentifierAPI().find(doc.getIdentifier()); Contentlet xslFile = APILocator.getContentletAPI().findContentletByIdentifier(doc.getIdentifier(), false, APILocator.getLanguageAPI().getDefaultLanguage().getId(), userAPI.getSystemUser(), false); /*validate time to live*/ long ttl = doc.getTtl() - new Date().getTime(); if(ttl <= 0 || doc.getInode() != xslFile.getInode()){ removeXSLTranformationDoc(doc); doc =null; } }catch (Exception e) { Logger.debug(XSLTransformationCache.class,"Cache xsl identifier not found", e); } } return doc; } /** * Remove from chache the specified XSLTranformationDoc * @param xmlDoc */ public static void removeXSLTranformationDoc(XSLTranformationDoc doc){ DotCacheAdministrator cache = CacheLocator.getCacheAdministrator(); String xmlPath = doc.getXmlPath(); String xslPath = doc.getXslPath(); cache.remove(getPrimaryGroup() + xmlPath+"_"+xslPath, getPrimaryGroup()); } /** * Flush al the cache * */ public static void clearCache(){ DotCacheAdministrator cache = CacheLocator.getCacheAdministrator(); //clear the cache cache.flushGroup(getPrimaryGroup()); } public static String[] getGroups() { String[] groups = {getPrimaryGroup()}; return groups; } public static String getPrimaryGroup() { return "XSLTransformationCache"; } }
gpl-3.0
SecUSo/privacy-friendly-pedometer
app/src/main/java/org/secuso/privacyfriendlyactivitytracker/persistence/TrainingPersistenceHelper.java
4669
/* Privacy Friendly Pedometer is licensed under the GPLv3. Copyright (C) 2017 Tobias Neidig This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.secuso.privacyfriendlyactivitytracker.persistence; import android.content.Context; import org.secuso.privacyfriendlyactivitytracker.models.Training; import java.util.List; /** * Helper to save and restore training sessions from database. * * @author Tobias Neidig * @version 20170810 */ public class TrainingPersistenceHelper { public static final String LOG_CLASS = TrainingPersistenceHelper.class.getName(); /** * @deprecated Use {@link TrainingDbHelper#getAllTrainings()} instead. * * Gets all training sessions from database * * @param context The application context * @return a list of training sessions */ public static List<Training> getAllItems(Context context) { return new TrainingDbHelper(context).getAllTrainings(); } /** * @deprecated Use {@link TrainingDbHelper#getTraining(int)} instead. * * Gets the specific training session * * @param id the id of the training session * @param context The application context * @return the requested training session or null */ public static Training getItem(long id, Context context) { return new TrainingDbHelper(context).getTraining((int) id); } /** * @deprecated Use {@link TrainingDbHelper#getActiveTraining()} instead. * * Gets the active training session * * @param context The application context * @return the requested training session or null */ public static Training getActiveItem(Context context) { return new TrainingDbHelper(context).getActiveTraining(); } /** * Stores the given training session to database. * If id is set, the training session will be updated else it will be created * * @param item the training session to store * @param context The application context * @return the saved training session (with correct id) */ public static Training save(Training item, Context context) { if (item == null) { return null; } if (item.getId() <= 0) { long insertedId = insert(item, context); if (insertedId == -1) { return null; } else { item.setId(insertedId); return item; } } else { int affectedRows = update(item, context); if (affectedRows == 0) { return null; } else { return item; } } } /** * @deprecated Use {@link TrainingDbHelper#deleteTraining(Training)} instead. * * Deletes the given training session from database * * @param item the item to delete * @param context The application context * @return true if deletion was successful else false */ public static boolean delete(Training item, Context context) { new TrainingDbHelper(context).deleteTraining(item); return true; } /** * @deprecated Use {@link TrainingDbHelper#addTraining(Training)} instead. * * Inserts the given training session as new entry. * * @param item The training session which should be stored * @param context The application context * @return the inserted id */ protected static long insert(Training item, Context context) { return new TrainingDbHelper(context).addTraining(item); } /** * @deprecated Use {@link TrainingDbHelper#updateTraining(Training)} instead. * * Updates the given training session in database * * @param item The training session to update * @param context The application context * @return the number of rows affected */ protected static int update(Training item, Context context) { return new TrainingDbHelper(context).updateTraining(item); } }
gpl-3.0
FritzSolms/org.urdad.contractMock
src/main/java/org/urdad/services/validation/package-info.java
554
@XmlSchema(namespace = "http://www.urdad.org/services/validation/beanvalidation", elementFormDefault = XmlNsForm .QUALIFIED) /** * This domain of responsibility is associated with services and other constructs that are related to a * services-oriented approach to defining system functionality. More specifically this sub-domain contains artifacts * that are responsible for service request and response validation. */ package org.urdad.services.validation; import javax.xml.bind.annotation.XmlNsForm; import javax.xml.bind.annotation.XmlSchema;
gpl-3.0
Cbsoftware/PressureNet
src/ca/cumulonimbus/barometernetwork/PlayServicesLegalActivity.java
1136
package ca.cumulonimbus.barometernetwork; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import ca.cumulonimbus.barometernetwork.PressureNetApplication.TrackerName; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import com.google.android.gms.common.GooglePlayServicesUtil; public class PlayServicesLegalActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.legal); TextView legalText = (TextView) findViewById(R.id.textLegal); legalText.setText( GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(getApplicationContext())); } @Override protected void onStart() {// Get tracker. Tracker t = ((PressureNetApplication) getApplication()).getTracker( TrackerName.APP_TRACKER); // Set screen name. t.setScreenName("Play Services Legal"); // Send a screen view. t.send(new HitBuilders.ScreenViewBuilder().build()); super.onStart(); } @Override protected void onStop() { super.onStop(); } }
gpl-3.0
kinztechcom/OS-Cache-Suite
src/com/osrs/suite/ui/LabeledIdentifer.java
694
package com.osrs.suite.ui; import javafx.scene.control.Label; import javafx.scene.layout.HBox; /** * Created by Allen Kinzalow on 3/21/2015. */ public class LabeledIdentifer { private Label identifer; private Label value; public LabeledIdentifer(String id, String val) { this.identifer = new Label(id); this.value = new Label(val); } public Label getIdentifer() { return identifer; } public Label getValue() { return value; } public HBox getContainer() { HBox container = new HBox(); container.setSpacing(7); container.getChildren().addAll(identifer,value); return container; } }
gpl-3.0
zeatul/poc
e-commerce/e-commerce-ecom-pay-service/src/main/java/com/alipay/api/response/MonitorHeartbeatSynResponse.java
548
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.AlipayResponse; /** * ALIPAY API: monitor.heartbeat.syn response. * * @author auto create * @since 1.0, 2016-06-06 22:21:41 */ public class MonitorHeartbeatSynResponse extends AlipayResponse { private static final long serialVersionUID = 5529472753922257774L; /** * 商户pid */ @ApiField("pid") private String pid; public void setPid(String pid) { this.pid = pid; } public String getPid( ) { return this.pid; } }
gpl-3.0
starlis/EMC-CraftBukkit
src/main/java/net/minecraft/server/PacketPlayOutBlockChange.java
2104
package net.minecraft.server; public class PacketPlayOutBlockChange extends Packet { private int a; private int b; private int c; public Block block; // CraftBukkit - public public int data; // CraftBukkit - public public PacketPlayOutBlockChange() {} public PacketPlayOutBlockChange(int i, int j, int k, World world) { this.a = i; this.b = j; this.c = k; this.block = world.getType(i, j, k); this.data = world.getData(i, j, k); } public void a(PacketDataSerializer packetdataserializer) { this.a = packetdataserializer.readInt(); this.b = packetdataserializer.readUnsignedByte(); this.c = packetdataserializer.readInt(); this.block = Block.getById(packetdataserializer.a()); this.data = packetdataserializer.readUnsignedByte(); } public void b(PacketDataSerializer packetdataserializer) { // Spigot start - protocol patch if ( packetdataserializer.version < 25 ) { packetdataserializer.writeInt( this.a ); packetdataserializer.writeByte( this.b ); packetdataserializer.writeInt( this.c ); packetdataserializer.b( Block.getId( this.block ) ); packetdataserializer.writeByte(this.data); } else { packetdataserializer.writePosition( a, b, c ); int id = Block.getId( this.block ); data = org.spigotmc.SpigotDebreakifier.getCorrectedData( id, data ); packetdataserializer.b( (id << 4) | this.data ); } // Spigot end } public void a(PacketPlayOutListener packetplayoutlistener) { packetplayoutlistener.a(this); } public String b() { return String.format("type=%d, data=%d, x=%d, y=%d, z=%d", new Object[] { Integer.valueOf(Block.getId(this.block)), Integer.valueOf(this.data), Integer.valueOf(this.a), Integer.valueOf(this.b), Integer.valueOf(this.c)}); } public void handle(PacketListener packetlistener) { this.a((PacketPlayOutListener) packetlistener); } }
gpl-3.0
vpac-innovations/rsa
src/rsaworkers/src/main/java/org/vpac/worker/WorkExecutor.java
9589
package org.vpac.worker; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.UUID; import java.util.regex.Pattern; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.vpac.ndg.AppContext; import org.vpac.ndg.configuration.NdgConfigManager; import org.vpac.ndg.query.Query; import org.vpac.ndg.query.QueryDefinition; import org.vpac.ndg.query.QueryDefinition.DatasetInputDefinition; import org.vpac.ndg.query.QueryException; import org.vpac.ndg.query.filter.Foldable; import org.vpac.worker.Job.Work; import scala.concurrent.duration.Duration; import ucar.nc2.NetcdfFileWriter; import ucar.nc2.NetcdfFileWriter.Version; import akka.actor.Cancellable; import akka.actor.UntypedActor; import akka.event.Logging; import akka.event.LoggingAdapter; public class WorkExecutor extends UntypedActor { /** * The application context should only be initialised once EVER - otherwise * you get resource leaks (e.g. extra open sockets) when using something * like Nailgun. The use of the enum here ensures this. The context acquired * here is passed automatically to {@link AppContext} in the Storage Manager * for use by other parts of the RSA. */ private static enum AppContextSingleton { INSTANCE; public ApplicationContext appContext; private AppContextSingleton() { appContext = new ClassPathXmlApplicationContext(new String[] { "spring/config/BeanLocations.xml" }); } } public WorkExecutor() { ApplicationContext appContext = AppContextSingleton.INSTANCE.appContext; ndgConfigManager = (NdgConfigManager) appContext.getBean("ndgConfigManager"); } private NdgConfigManager ndgConfigManager; private LoggingAdapter log = Logging.getLogger(getContext().system(), this); @Override public void onReceive(Object message) { if (message instanceof Work) { Work work = (Work) message; WorkProgress wp = new WorkProgress(work.workId); Collection<Path> tempFiles = new ArrayList<>(); // heart beat to master to check progress. Cancellable cancel = getContext() .system() .scheduler() .schedule( Duration.create(1, "seconds"), Duration.create(1, "seconds"), getSender(), new MasterWorkerProtocol.ProgressCheckPoint( work.workId, wp), getContext().system().dispatcher(), null); Map<String, Foldable<?>> output = null; Path queryPath = null; try { QueryDefinition qd = preprocessQueryDef(work, tempFiles); queryPath = getOutputFile(work); Files.deleteIfExists(queryPath); output = executeQuery(qd, wp, queryPath, work.netcdfVersion); } catch (Exception e) { wp.setErrorMessage(e.getMessage()); log.error(e, "Task {} exited abnormally", work.workId); getSender().tell(new Job.Error(work, e), getSelf()); // Error handling has been delegated to `sender`, so just // return. return; } finally { // Query is no longer running, so no more progress updates are // required. cancel.cancel(); for (Path path : tempFiles) { try { Files.delete(path); } catch (IOException e) { log.error(e, "Failed to delete temp file {}", path); } } } HashMap<String, Foldable<?>> result = new java.util.HashMap<>(); for (Entry<String, Foldable<?>> v : output.entrySet()) { if (!Serializable.class.isAssignableFrom(v.getValue() .getClass())) continue; log.info("key : {}, value: {}", v.getKey(), v.getValue()); result.put(v.getKey(), v.getValue()); } String fileId = SerializeResult(work, result); getSender().tell(new Job.WorkComplete(fileId), getSelf()); } } private String SerializeResult(Work work, HashMap<String, Foldable<?>> result) { String fileName = UUID.randomUUID().toString(); Path outputDir = Paths.get(ndgConfigManager.getConfig() .getDefaultPickupLocation() + "/" + work.jobProgressId + "/temp"); try { if (!Files.exists(outputDir)) try { Files.createDirectories(outputDir); } catch (IOException e1) { log.error("directory creation error:", e1); e1.printStackTrace(); throw e1; } FileOutputStream fileOut = new FileOutputStream(outputDir + "/" + fileName); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(result); out.close(); fileOut.close(); } catch(IOException i) { i.printStackTrace(); } return fileName; } private QueryDefinition preprocessQueryDef(Work work, Collection<Path> tempFiles) throws IOException { final QueryDefinition qd = QueryDefinition .fromString(work.queryDefinitionString); qd.output.grid.bounds = String.format("%f %f %f %f", work.bound .getMin().getX(), work.bound.getMin().getY(), work.bound .getMax().getX(), work.bound.getMax().getY()); // Fetch external data and store in local files before executing query. // This is required because the query engine needs to know some metadata // early in the query configuration process, before the files are // opened. for (DatasetInputDefinition di : qd.inputs) { if (di.href.startsWith("epiphany")) { Path epiphanyTempFile = fetchEpiphanyData(di, work); tempFiles.add(epiphanyTempFile); di.href = epiphanyTempFile.toString(); } } return qd; } private Path getOutputPath(Work work) throws IOException { Path outputDir = Paths.get(ndgConfigManager.getConfig() .getDefaultPickupLocation() + "/" + work.jobProgressId); if (!Files.exists(outputDir)) try { Files.createDirectories(outputDir); } catch (IOException e1) { log.error("directory creation error:", e1); e1.printStackTrace(); throw e1; } return outputDir; } private Path getOutputFile(Work work) throws IOException { Path outputDir = getOutputPath(work); return outputDir.resolve(work.workId + "_out.nc"); } private Map<String, Foldable<?>> executeQuery(QueryDefinition qd, WorkProgress wp, Path outputPath, Version netcdfVersion) throws IOException, QueryException { /* * NetcdfFileWriter outputDataset = NetcdfFileWriter.createNew( * netcdfVersion, outputPath.toString()); */ NetcdfFileWriter outputDataset = NetcdfFileWriter.createNew( netcdfVersion, outputPath.toString()); Map<String, Foldable<?>> output = null; try { Query q = new Query(outputDataset); q.setNumThreads(1); q.setMemento(qd, new File(".").getAbsolutePath()); try { q.setProgress(wp); // Memory leak point - Jin : when I comment out this there not much memory is used // We should have a look inside of this method. q.run(); output = q.getAccumulatedOutput(); } finally { q.close(); } } catch(Exception e) { throw e; } finally { try { outputDataset.close(); } catch (Exception e) { log.error("Failed to close output file", e); } } return output; } // Dataset identifier looks like "epiphany:id?query" private static final Pattern EP_PATTERN = Pattern.compile( "epiphany:([^?]+)(?:\\?(.*))?"); private Path fetchEpiphanyData(DatasetInputDefinition di, Work w) throws IOException { String epiphanyHost = ndgConfigManager.getConfig().getEpiphanyHost(); String epiphanyPort = ndgConfigManager.getConfig().getEpiphanyPort(); Matcher matcher = EP_PATTERN.matcher(di.href); if (!matcher.matches()) { throw new IOException(String.format( "Invalid format for dataset reference: %s", di.href)); } String datasetId = matcher.group(1); String query = matcher.group(2); // http://172.31.25.104:8000/map/wcs/1060?VIEWMETHOD=none // &FORMAT=application/x-netcdf&SERVICE=WCS&VERSION=1.1.1&REQUEST=GetMap // &SRS=EPSG%3A3111 // &BBOX=2125506.0544,2250071.3640,2960417.7309,2824982.3383 // &WIDTH=1452&HEIGHT=1000 // &LAYERS=1060&YEAR=2011 // &AGELOWER=15&AGEUPPER=25 String url = "http://" + epiphanyHost; if (epiphanyPort != null) url += ":" + epiphanyPort; url += "/map/wcs/" + datasetId + "?FORMAT=application/x-netcdf&SERVICE=WCS&VERSION=1.1.1&REQUEST=GetMap" + "&SRS=EPSG:3111&BBOX=" + w.bound.getMin().getX() + "," + w.bound.getMin().getY() + "," + w.bound.getMax().getX() + "," + w.bound.getMax().getY() + "&WIDTH=5000&HEIGHT=5000" + "&LAYERS=" + datasetId; if (query != null) url += "&" + query; System.out.println("Fetching: " + url); URL connectionUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) connectionUrl .openConnection(); connection.setRequestMethod("GET"); Path path = Files.createTempFile("epiphany_" + w.workId, ".nc"); // TODO : file doesn't need to be stored. -JP // It's probably good practice to store it, though: otherwise we might // fill our RAM. rsaquery will only read a small amount at a time. -AF try (InputStream in = connection.getInputStream(); OutputStream out = new FileOutputStream(path.toFile());) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } return path; } }
gpl-3.0
richrr/scripts
bash/bbtools/bbmap/current/fun/Calc.java
5296
package fun; import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; import dna.Parser; import fileIO.ByteFile; import fileIO.FileFormat; import fileIO.ReadWrite; import shared.ReadStats; import shared.Shared; import shared.Timer; import shared.Tools; import stream.ConcurrentReadInputStream; import stream.ConcurrentReadOutputStream; import stream.FASTQ; import stream.FastaReadInputStream; import stream.Read; import structures.ListNum; public class Calc { /*--------------------------------------------------------------*/ /*---------------- Initialization ----------------*/ /*--------------------------------------------------------------*/ /** * Code entrance from the command line. * @param args Command line arguments */ public static void main(String[] args){ Timer t=new Timer(); Calc as=new Calc(args); as.process(t); } /** * Constructor. * @param args Command line arguments */ public Calc(String[] args){ //Process any config files args=Parser.parseConfig(args); //Detect whether the uses needs help if(Parser.parseHelp(args, true)){ printOptions(); System.exit(0); } //Print the program name and arguments outstream.println("Executing "+getClass().getName()+" "+Arrays.toString(args)+"\n"); //Create a parser object Parser parser=new Parser(); //Parse each argument for(int i=0; i<args.length; i++){ String arg=args[i]; //Break arguments into their constituent parts, in the form of "a=b" String[] split=arg.split("="); String a=split[0].toLowerCase(); String b=split.length>1 ? split[1] : null; if(b==null || b.equalsIgnoreCase("null")){b=null;} while(a.startsWith("-")){a=a.substring(1);} //Strip leading hyphens if(a.equals("verbose")){ verbose=Tools.parseBoolean(b); }else if(a.equals("parse_flag_goes_here")){ long fake_variable=Tools.parseKMG(b); //Set a variable here }else if(a.equals("num") || a.equals("numstats")){ numStats=Integer.parseInt(b); }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser //do nothing }else{ outstream.println("Unknown parameter "+args[i]); assert(false) : "Unknown parameter "+args[i]; } } {//Process parser fields overwrite=ReadStats.overwrite=parser.overwrite; append=ReadStats.append=parser.append; out1=parser.out1; } } /*--------------------------------------------------------------*/ /*---------------- Outer Methods ----------------*/ /*--------------------------------------------------------------*/ /** Create read streams and process all data */ void process(Timer t){ //Process the read stream processInner(numStats); if(verbose){outstream.println("Finished; closing streams.");} //Report timing and results { t.stop(); outstream.println("Time: \t"+t); } //Throw an exception of there was an error in a thread if(errorState){ throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt."); } } /** Iterate through the reads */ void processInner(int numStats){ int bits=numStats*5; final int iters=1<<bits; final int buckets=1+31*numStats; int[] counts=new int[buckets]; for(int i=0; i<iters; i++){ counts[sum(i)]++; } int[] cumulative=new int[buckets]; cumulative[0]=counts[0]; for(int i=1; i<buckets; i++){ cumulative[i]=cumulative[i-1]+counts[i]; } //StringBuilder sb=new StringBuilder(); final double mult=100.0/iters; for(int i=0; i<buckets; i++){ String s=(String.format(Locale.ROOT, "%d\t%.4f%%\n", i, cumulative[i]*mult)); System.out.print(s); } } int sum(int stats){ int sum=0; while(stats>0){ sum+=(stats&0x1F); stats>>>=5; } return sum; } /*--------------------------------------------------------------*/ /*---------------- Inner Methods ----------------*/ /*--------------------------------------------------------------*/ /** This is called if the program runs with no parameters */ private void printOptions(){ throw new RuntimeException("TODO"); } /*--------------------------------------------------------------*/ /*---------------- Fields ----------------*/ /*--------------------------------------------------------------*/ /** Primary output file path */ private String out1="stdout.txt"; private int numStats=6; /*--------------------------------------------------------------*/ /*---------------- Common Fields ----------------*/ /*--------------------------------------------------------------*/ /** Print status messages to this output stream */ private PrintStream outstream=System.err; /** Print verbose messages */ public static boolean verbose=false; /** True if an error was encountered */ public boolean errorState=false; /** Overwrite existing output files */ private boolean overwrite=false; /** Append to existing output files */ private boolean append=false; }
gpl-3.0
zamojski/TowerCollector
app/src/main/java/info/zamojski/soft/towercollector/model/MapMeasurement.java
2162
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package info.zamojski.soft.towercollector.model; import android.content.Context; import android.text.TextUtils; import org.jetbrains.annotations.NotNull; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import info.zamojski.soft.towercollector.enums.NetworkGroup; import info.zamojski.soft.towercollector.utils.NetworkTypeUtils; public class MapMeasurement extends MeasurementBase implements Serializable { private static final long serialVersionUID = -1561704184666574202L; /** * Associated cells. */ private List<MapCell> cells = new ArrayList<>(); public List<MapCell> getCells() { return cells; } public void addCell(MapCell cell) { this.cells.add(cell); } public List<MapCell> getMainCells() { List<MapCell> mainCells = new ArrayList<>(); for (MapCell cell : cells) { if (!cell.isNeighboring()) mainCells.add(cell); } if (mainCells.isEmpty()) mainCells.add(cells.get(0)); // should never happen return mainCells; } public String getDescription(Context context) { return super.getDescription(context, getMainCells(), "<br/>"); } public static MapMeasurement fromMeasurement(Measurement m) { MapMeasurement mm = new MapMeasurement(); mm.setLatitude(m.getLatitude()); mm.setLongitude(m.getLongitude()); mm.setMeasuredAt(m.getMeasuredAt()); List<MapCell> cc = mm.getCells(); for (Cell c : m.getCells()) { cc.add(MapCell.fromCell(c)); } return mm; } @NotNull @Override public String toString() { return "MapMeasurement{" + "latitude=" + latitude + ", longitude=" + longitude + ", measuredAt=" + measuredAt + ", cells=[" + TextUtils.join(", ", cells) + "]" + '}'; } }
mpl-2.0
deanhiller/databus
webapp/play1.3.x/framework/src/play/db/jpa/JPAConfig.java
5530
package play.db.jpa; import java.lang.reflect.Modifier; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.hibernate.ejb.Ejb3Configuration; import play.Invoker; import play.Play; import play.classloading.ApplicationClasses; import play.exceptions.JPAException; /** * JPA Support for a specific JPA/DB configuration * * dbConfigName corresponds to properties-names in application.conf. * * The default DBConfig is the one configured using 'db.' in application.conf * * dbConfigName = 'other' is configured like this: * * db_other = mem * db_other.user = batman * * * A particular JPAConfig-instance uses the DBConfig with the same configName */ public class JPAConfig { private final String configName; private EntityManagerFactory entityManagerFactory = null; private ThreadLocal<JPAContext> local = new ThreadLocal<JPAContext>(); public final JPQL jpql; protected JPAConfig(Ejb3Configuration cfg, String configName) { this.configName = configName; invokeJPAConfigurationExtensions(cfg, configName); entityManagerFactory = cfg.buildEntityManagerFactory(); jpql = new JPQL(this); } public String getConfigName() { return configName; } protected void close() { if (isEnabled()) { try { entityManagerFactory.close(); } catch (Exception e) { // ignore it - we don't care if it failed.. } entityManagerFactory = null; } } /** * @return true if an entityManagerFactory has started */ public boolean isEnabled() { return entityManagerFactory != null; } /* * Build a new entityManager. * (In most case you want to use the local entityManager with em) */ public EntityManager newEntityManager() { return entityManagerFactory.createEntityManager(); } /** * gets the active or create new * @return the active JPAContext bound to current thread */ public JPAContext getJPAContext() { return getJPAContext(null); } /** * gets the active or create new. manualReadOnly is only used if we're create new context * @param manualReadOnly is not null, this value is used instead of value from @Transactional.readOnly * @return the active JPAContext bound to current thread */ protected JPAContext getJPAContext(Boolean manualReadOnly) { JPAContext context = local.get(); if ( context == null) { // throw new JPAException("The JPAContext is not initialized. JPA Entity Manager automatically start when one or more classes annotated with the @javax.persistence.Entity annotation are found in the application."); // This is the first time someone tries to use JPA in this thread. // we must initialize it if(Invoker.InvocationContext.current().getAnnotation(NoTransaction.class) != null ) { //Called method or class is annotated with @NoTransaction telling us that //we should not start a transaction throw new JPAException("Cannot create JPAContext due to @NoTransaction"); } boolean readOnly = false; if (manualReadOnly!=null) { readOnly = manualReadOnly; } else { Transactional tx = Invoker.InvocationContext.current().getAnnotation(Transactional.class); if (tx != null) { readOnly = tx.readOnly(); } } context = new JPAContext(this, readOnly, JPAPlugin.autoTxs); local.set(context); } return context; } protected void clearJPAContext() { JPAContext context = local.get(); if (context != null) { try { context.close(); } catch(Exception e) { // Let's it fail } local.remove(); } } /** * @return true if JPA is enabled in current thread */ public boolean threadHasJPAContext() { return local.get() != null; } public boolean isInsideTransaction() { if (!threadHasJPAContext()) { return false; } return getJPAContext().isInsideTransaction(); } /** * Looks up all {@link JPAConfigurationExtension} implementations and applies them to the JPA configuration. * * @param cfg the {@link} Ejb3Configuration for this {@link JPAConfig} * @param configName the name of the db configuration */ protected void invokeJPAConfigurationExtensions(Ejb3Configuration cfg, String configName) { for(ApplicationClasses.ApplicationClass c : Play.classes.getAssignableClasses(JPAConfigurationExtension.class)) { if(!Modifier.isAbstract(c.getClass().getModifiers())) { JPAConfigurationExtension extension = null; try { extension = (JPAConfigurationExtension) c.javaClass.newInstance(); } catch (Throwable t) { throw new JPAException(String.format("Could not instantiate JPAConfigurationExtension '%s'", c.javaClass.getName()), t); } if(extension.getConfigurationName() == null || extension.getConfigurationName().equals(configName)) { extension.configure(cfg); } } } } }
mpl-2.0
therajanmaurya/self-service-app
app/src/main/java/org/mifos/mobilebanking/models/accounts/loan/DaysInMonthType.java
1765
package org.mifos.mobilebanking.models.accounts.loan; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; /** * Created by Rajan Maurya on 04/03/17. */ public class DaysInMonthType implements Parcelable { @SerializedName("id") Integer id; @SerializedName("code") String code; @SerializedName("value") String value; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeValue(this.id); dest.writeString(this.code); dest.writeString(this.value); } public DaysInMonthType() { } protected DaysInMonthType(Parcel in) { this.id = (Integer) in.readValue(Integer.class.getClassLoader()); this.code = in.readString(); this.value = in.readString(); } public static final Parcelable.Creator<DaysInMonthType> CREATOR = new Parcelable.Creator<DaysInMonthType>() { @Override public DaysInMonthType createFromParcel(Parcel source) { return new DaysInMonthType(source); } @Override public DaysInMonthType[] newArray(int size) { return new DaysInMonthType[size]; } }; }
mpl-2.0
bgroenks96/2DX-GL
snap2d/src/test/java/com/snap2d/testing/physics/PropertyFormatException.java
882
/* * Copyright (C) 2011-2014 Brian Groenke * All rights reserved. * * This file is part of the 2DX Graphics Library. * * This Source Code Form is subject to the terms of the * Mozilla Public License, v. 2.0. If a copy of the MPL * was not distributed with this file, You can obtain one at * http://mozilla.org/MPL/2.0/. */ package com.snap2d.testing.physics; /** * @author Brian Groenke * */ public class PropertyFormatException extends Exception { /** * */ private static final long serialVersionUID = -6601101818940971328L; /** * @param message */ public PropertyFormatException(final String message) { super(message); } /** * @param message * @param cause */ public PropertyFormatException(final String message, final Throwable cause) { super(message, cause); } }
mpl-2.0
renatocoelho/vencimetro
src/test/java/app/controllers/UserControllerTest.java
248
package app.controllers; import static org.junit.Assert.assertNotNull; import org.junit.Test; public class UserControllerTest { @Test public void fakeTest() { assertNotNull("put something real.", new UserController(null, null, null)); } }
mpl-2.0
sensiasoft/lib-swe-common
swe-common-core/src/main/java/org/vast/data/CategoryImpl.java
4983
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved. ******************************* END LICENSE BLOCK ***************************/ package org.vast.data; import java.util.List; import net.opengis.OgcProperty; import net.opengis.OgcPropertyImpl; import net.opengis.swe.v20.AllowedTokens; import net.opengis.swe.v20.Category; import net.opengis.swe.v20.DataComponentVisitor; import net.opengis.swe.v20.DataType; import net.opengis.swe.v20.ValidationException; /** * <p> * Extended SWE Category implementation adapted to old VAST framework * </p> * * @author Alex Robin * @since Aug 30, 2014 */ public class CategoryImpl extends DataValue implements Category { private static final long serialVersionUID = -8819399062433113779L; protected String codeSpace; protected OgcProperty<AllowedTokens> constraint; public CategoryImpl() { this.dataType = DataType.UTF_STRING; } @Override public CategoryImpl copy() { CategoryImpl newObj = new CategoryImpl(); super.copyTo(newObj); if (codeSpace != null) newObj.codeSpace = codeSpace; else newObj.codeSpace = null; if (constraint != null) newObj.constraint = constraint.copy(); else newObj.constraint = null; return newObj; } /** * Gets the codeSpace property */ @Override public String getCodeSpace() { return codeSpace; } /** * Checks if codeSpace is set */ @Override public boolean isSetCodeSpace() { return (codeSpace != null); } /** * Sets the codeSpace property */ @Override public void setCodeSpace(String codeSpace) { this.codeSpace = codeSpace; } /** * Gets the constraint property */ @Override public AllowedTokens getConstraint() { if (constraint == null) return null; return constraint.getValue(); } /** * Gets extra info (name, xlink, etc.) carried by the constraint property */ @Override public OgcProperty<AllowedTokens> getConstraintProperty() { if (constraint == null) constraint = new OgcPropertyImpl<AllowedTokens>(); return constraint; } /** * Checks if constraint is set */ @Override public boolean isSetConstraint() { return (constraint != null && (constraint.hasValue() || constraint.hasHref())); } /** * Sets the constraint property */ @Override public void setConstraint(AllowedTokens constraint) { if (this.constraint == null) this.constraint = new OgcPropertyImpl<AllowedTokens>(); this.constraint.setValue(constraint); } /** * Gets the value property */ @Override public String getValue() { if (dataBlock == null) return null; return dataBlock.getStringValue(); } /** * Sets the value property */ @Override public void setValue(String value) { if (dataBlock == null) assignNewDataBlock(); dataBlock.setStringValue(value); } @Override public boolean hasConstraints() { return isSetConstraint(); } @Override public void validateData(List<ValidationException> errorList) { if (isSetConstraint() && isSetValue()) { AllowedTokensImpl constraint = (AllowedTokensImpl)getConstraint(); if (!constraint.isValid(getValue())) { errorList.add(new ValidationException(getName(), "Value '" + dataBlock.getStringValue() + "' is not valid for component '" + getName() + "': " + constraint.getAssertionMessage())); } } } @Override public String toString(String indent) { StringBuffer text = new StringBuffer(); text.append("Category"); if (dataBlock != null) { text.append(" = "); text.append(dataBlock.getStringValue()); } return text.toString(); } @Override public void accept(DataComponentVisitor visitor) { visitor.visit(this); } }
mpl-2.0
zyxakarene/LearningOpenGl
MainGame/src/zyx/game/components/world/furniture/Stove.java
587
package zyx.game.components.world.furniture; import zyx.game.components.SimpleMesh; import zyx.game.components.world.items.GameItem; public class Stove extends NpcFurniture<SimpleMesh> { public Stove() { super(false); } @Override protected void onGotItem(GameItem item) { view.addChildAsAttachment(item, "Stove_plate"); } @Override protected void onLostItem(GameItem item) { view.removeChildAsAttachment(item); item.setPosition(true, 0, 0, 0); item.setRotation(0, 0, 0); } @Override protected String getResource() { return "mesh.furniture.stove"; } }
mpl-2.0
seedstack/seed
core/src/test/java/org/seedstack/seed/core/CommandIT.java
2013
/* * Copyright © 2013-2021, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.seed.core; import static org.assertj.core.api.Assertions.assertThat; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import java.util.List; import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import org.seedstack.seed.command.Argument; import org.seedstack.seed.command.Command; import org.seedstack.seed.command.CommandRegistry; import org.seedstack.seed.command.Option; import org.seedstack.seed.core.fixtures.TestCommand; import org.seedstack.seed.testing.junit4.SeedITRunner; @RunWith(SeedITRunner.class) public class CommandIT { @Inject private CommandRegistry commandRegistry; @Test public void commandRegistryIsInjectable() { assertThat(commandRegistry).isNotNull(); } @Test public void testCommandInstantiation() throws Exception { Command command = commandRegistry.createCommand("core", "test", Lists.newArrayList("arg1"), ImmutableMap.of("o1", "o2=toto")); assertThat(command).isInstanceOf(TestCommand.class); assertThat(command.execute(null)).isNotNull(); } @Test public void testArgumentInfo() { List<Argument> argumentsInfo = commandRegistry.getArgumentsInfo("core", "test"); assertThat(argumentsInfo).hasSize(1); assertThat(argumentsInfo.get(0).name()).isEqualTo("arg1"); } @Test public void testOptionsInfo() { List<Option> optionsInfo = commandRegistry.getOptionsInfo("core", "test"); assertThat(optionsInfo).hasSize(2); assertThat(optionsInfo.get(0).longName()).isEqualTo("option1"); assertThat(optionsInfo.get(1).longName()).isEqualTo("option2"); } }
mpl-2.0