repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
pantelis60/L2Scripts_Underground | gameserver/src/main/java/l2s/gameserver/instancemanager/DailyQuestsManager.java | 1579 | package l2s.gameserver.instancemanager;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import l2s.commons.util.Rnd;
import l2s.gameserver.model.Player;
import l2s.gameserver.model.quest.Quest;
import l2s.gameserver.model.quest.QuestState;
public class DailyQuestsManager
{
private static final Logger _log = LoggerFactory.getLogger(DailyQuestsManager.class);
private static List<Integer> _disabledQuests = new ArrayList<Integer>();
public static void EngageSystem()
{
switch(Rnd.get(1, 3))
//60-64 1 quest per day
{
case 1:
_disabledQuests.add(470);
break;
case 2:
_disabledQuests.add(474);
break;
}
switch(Rnd.get(1, 2))
//75-79 2 quest per day
{
case 1:
_disabledQuests.add(488);
break;
case 2:
_disabledQuests.add(489);
break;
}
_log.info("Daily Quests Disable Managed: Loaded " + _disabledQuests.size() + " quests in total (4).");
}
//dunno if this is retail but as I understand if quest gone from the list it will be removed from the player as well.
public static void checkAndRemoveDisabledQuests(Player player)
{
if(player == null)
return;
for(int qId : _disabledQuests)
{
Quest q = QuestManager.getQuest(qId);
QuestState qs = player.getQuestState(q.getName());
if(qs == null)
continue;
if(q.checkMaxLevelCondition(player))
continue;
qs.exitCurrentQuest(true);
}
}
public static boolean isQuestDisabled(int questId)
{
if(_disabledQuests.contains(questId))
return true;
return false;
}
} | gpl-3.0 |
raymondbh/TFCraft | src/Common/com/bioxx/tfc/Render/Blocks/RenderLoom.java | 7580 | package com.bioxx.tfc.Render.Blocks;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.world.IBlockAccess;
import org.lwjgl.opengl.GL11;
import com.bioxx.tfc.TileEntities.TELoom;
import com.bioxx.tfc.api.TFCBlocks;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
public class RenderLoom implements ISimpleBlockRenderingHandler
{
static float minX = 0F;
static float maxX = 1F;
static float minY = 0F;
static float maxY = 1F;
static float minZ = 0F;
static float maxZ = 1F;
@Override
public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer)
{
TELoom te = (TELoom) world.getTileEntity(x, y, z);
Block materialBlock;
if(te.loomType < 16)
{
materialBlock = TFCBlocks.WoodSupportH;
}
else
{
materialBlock = TFCBlocks.WoodSupportH2;
}
renderer.renderAllFaces = true;
GL11.glPushMatrix();
//Arms
this.setRotatedRenderBounds(renderer, te.rotation, minX+0.1F, minY, minZ+0.75F, maxX-0.8F, maxY, maxZ-0.15F);
renderer.renderStandardBlock(materialBlock, x, y, z);
this.setRotatedRenderBounds(renderer, te.rotation, minX+0.8F, minY, minZ+0.75F, maxX-0.1F, maxY, maxZ-0.15F);
renderer.renderStandardBlock(materialBlock, x, y, z);
//Arm holding sections
//L
this.setRotatedRenderBounds(renderer, te.rotation, minX+0.1F, minY+0.25F, minZ+0.5F, maxX-0.8F, maxY-0.7F, maxZ-0.25F);
renderer.renderStandardBlock(materialBlock, x, y, z);
this.setRotatedRenderBounds(renderer, te.rotation, minX+0.1F, minY+0.05F, minZ+0.5F, maxX-0.8F, maxY-0.9F, maxZ-0.25F);
renderer.renderStandardBlock(materialBlock, x, y, z);
//R
this.setRotatedRenderBounds(renderer, te.rotation, minX+0.8F, minY+0.25F, minZ+0.5F, maxX-0.1F, maxY-0.7F, maxZ-0.25F);
renderer.renderStandardBlock(materialBlock, x, y, z);
this.setRotatedRenderBounds(renderer, te.rotation, minX+0.8F, minY+0.05F, minZ+0.5F, maxX-0.1F, maxY-0.9F, maxZ-0.25F);
renderer.renderStandardBlock(materialBlock, x, y, z);
//cross
this.setRotatedRenderBounds(renderer, te.rotation, maxX-0.8F, minY+0.8F, minZ+0.75F, minX+0.8F, maxY-0.1F, maxZ-0.15F);
renderer.renderStandardBlock(materialBlock, x, y, z);
this.setRotatedRenderBounds(renderer, te.rotation, maxX-0.8F, 0F, minZ+0.75F, minX+0.8F, minY+0.1F, maxZ-0.15F);
renderer.renderStandardBlock(materialBlock, x, y, z);
rotate(renderer, 0);
renderer.renderAllFaces = false;
GL11.glPopMatrix();
return true;
}
public void rotate(RenderBlocks renderer, int i)
{
renderer.uvRotateEast = i;
renderer.uvRotateWest = i;
renderer.uvRotateNorth = i;
renderer.uvRotateSouth = i;
}
private void setRotatedRenderBounds(RenderBlocks renderer, byte rotation , float x, float y, float z, float X, float Y, float Z){
switch(rotation){
case 0: renderer.setRenderBounds(x,y,z,X,Y,Z); break;
case 1: renderer.setRenderBounds(maxZ-Z,y,x,maxZ-z,Y,X); break;
case 2: renderer.setRenderBounds(x,y,maxZ-Z,X,Y,maxZ-z); break;
case 3: renderer.setRenderBounds(z,y,x,Z,Y,X); break;
default: break;
}
}
@Override
public void renderInventoryBlock(Block block, int meta, int modelID, RenderBlocks renderer)
{
Block materialBlock;
if(meta < 16)
{
materialBlock = TFCBlocks.WoodSupportH;
}
else
{
materialBlock = TFCBlocks.WoodSupportH2;
}
GL11.glPushMatrix();
GL11.glRotatef(180, 0, 1, 0);
//Arms
renderer.setRenderBounds(minX+0.1F, minY, minZ+0.75F, maxX-0.8F, maxY, maxZ-0.15F);
rotate(renderer, 1);
renderInvBlock(materialBlock, meta, renderer);
renderer.setRenderBounds(minX+0.8F, minY, minZ+0.75F, maxX-0.1F, maxY, maxZ-0.15F);
rotate(renderer, 1);
renderInvBlock(materialBlock, meta, renderer);
//Arm holding sections
//L
renderer.setRenderBounds(minX+0.1F, minY+0.35F, minZ+0.6F, maxX-0.8F, maxY-0.6F, maxZ-0.25F);
rotate(renderer, 1);
renderInvBlock(materialBlock, meta, renderer);
renderer.setRenderBounds(minX+0.1F, minY+0.15F, minZ+0.6F, maxX-0.8F, maxY-0.8F, maxZ-0.25F);
rotate(renderer, 1);
renderInvBlock(materialBlock, meta, renderer);
//R
renderer.setRenderBounds(minX+0.8F, minY+0.35F, minZ+0.6F, maxX-0.1F, maxY-0.6F, maxZ-0.25F);
rotate(renderer, 1);
renderInvBlock(materialBlock, meta, renderer);
renderer.setRenderBounds(minX+0.8F, minY+0.15F, minZ+0.6F, maxX-0.1F, maxY-0.8F, maxZ-0.25F);
rotate(renderer, 1);
renderInvBlock(materialBlock, meta, renderer);
//cross
renderer.setRenderBounds(maxX-0.8F, minY+0.8F, minZ+0.75F, minX+0.8F, maxY-0.1F, maxZ-0.15F);
rotate(renderer, 1);
renderInvBlock(materialBlock, meta, renderer);
renderer.setRenderBounds(maxX-0.8F, 0F, minZ+0.75F, minX+0.8F, minY+0.1F, maxZ-0.15F);
rotate(renderer, 1);
renderInvBlock(materialBlock, meta, renderer);
rotate(renderer, 0);
GL11.glPopMatrix();
}
@Override
public boolean shouldRender3DInInventory(int modelId)
{
return true;
}
@Override
public int getRenderId()
{
return 0;
}
public static void renderInvBlock(Block block, int m, RenderBlocks renderer)
{
Tessellator var14 = Tessellator.instance;
GL11.glTranslatef(-0.5F, -0.5F, -0.5F);
var14.startDrawingQuads();
var14.setNormal(0.0F, -1.0F, 0.0F);
renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(0, m));
var14.draw();
var14.startDrawingQuads();
var14.setNormal(0.0F, 1.0F, 0.0F);
renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(1, m));
var14.draw();
var14.startDrawingQuads();
var14.setNormal(0.0F, 0.0F, -1.0F);
renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(2, m));
var14.draw();
var14.startDrawingQuads();
var14.setNormal(0.0F, 0.0F, 1.0F);
renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(3, m));
var14.draw();
var14.startDrawingQuads();
var14.setNormal(-1.0F, 0.0F, 0.0F);
renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(4, m));
var14.draw();
var14.startDrawingQuads();
var14.setNormal(1.0F, 0.0F, 0.0F);
renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(5, m));
var14.draw();
GL11.glTranslatef(0.5F, 0.5F, 0.5F);
}
public static void renderInvBlockHoop(Block block, int m, RenderBlocks renderer)
{
Tessellator var14 = Tessellator.instance;
GL11.glTranslatef(-0.5F, -0.5F, -0.5F);
var14.startDrawingQuads();
var14.setNormal(0.0F, -1.0F, 0.0F);
renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(10, m));
var14.draw();
var14.startDrawingQuads();
var14.setNormal(0.0F, 1.0F, 0.0F);
renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(11, m));
var14.draw();
var14.startDrawingQuads();
var14.setNormal(0.0F, 0.0F, -1.0F);
renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(12, m));
var14.draw();
var14.startDrawingQuads();
var14.setNormal(0.0F, 0.0F, 1.0F);
renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(13, m));
var14.draw();
var14.startDrawingQuads();
var14.setNormal(-1.0F, 0.0F, 0.0F);
renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(14, m));
var14.draw();
var14.startDrawingQuads();
var14.setNormal(1.0F, 0.0F, 0.0F);
renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(15, m));
var14.draw();
GL11.glTranslatef(0.5F, 0.5F, 0.5F);
}
}
| gpl-3.0 |
zhaodongchao/dcproj | dcproj-model/src/main/java/org/dongchao/model/entity/User.java | 3180 | package org.dongchao.model.entity;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
* Created by zhaodongchao on 2017/5/3.
*/
@Table(name = "dc_user")
@Entity
public class User implements Serializable {
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Integer userId;
@NotEmpty
private String username;
private String password;
private String salt;
/*
存放用户拥有的角色的对象的集合
多对多关联fetch不能设置为懒加载
*/
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "dc_user_role",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "userId")},
inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "roleId")})
private Set<Role> role;
@Transient
private List<String> roles;
@Transient
private Set<String> permissions;
public User() {
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
public Set<Role> getRole() {
return role;
}
public void setRole(Set<Role> role) {
this.role = role;
}
public Set<String> getPermissions() {
return permissions;
}
public void setPermissions(Set<String> permissions) {
this.permissions = permissions;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(userId, user.userId) &&
Objects.equals(username, user.username) &&
Objects.equals(password, user.password) &&
Objects.equals(roles, user.roles);
}
@Override
public int hashCode() {
return Objects.hash(userId, username, password, roles);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("User{");
sb.append("userId=").append(userId);
sb.append(", username='").append(username).append('\'');
sb.append(", password='").append(password).append('\'');
sb.append(", salt='").append(salt).append('\'');
sb.append(", roles=").append(roles);
sb.append(", permissions=").append(permissions);
sb.append('}');
return sb.toString();
}
}
| gpl-3.0 |
kuros/random-jpa | src/test/java/com/github/kuros/random/jpa/testUtil/entity/EmployeeDepartment.java | 1656 | package com.github.kuros.random.jpa.testUtil.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "employee_department")
public class EmployeeDepartment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "employee_id")
private Long employeeId;
@Column(name = "shift_id")
private Integer shiftId;
@Column(name = "department_id")
private Integer departmentId;
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public Long getEmployeeId() {
return employeeId;
}
public void setEmployeeId(final Long employeeId) {
this.employeeId = employeeId;
}
public Integer getShiftId() {
return shiftId;
}
public void setShiftId(final Integer shiftId) {
this.shiftId = shiftId;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(final Integer departmentId) {
this.departmentId = departmentId;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final EmployeeDepartment that = (EmployeeDepartment) o;
return !(id != null ? !id.equals(that.id) : that.id != null);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
| gpl-3.0 |
Waikato/meka | src/test/java/meka/classifiers/multilabel/PMCCTest.java | 1617 | /*
* 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/>.
*/
/*
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*/
package meka.classifiers.multilabel;
import junit.framework.Test;
import junit.framework.TestSuite;
import weka.classifiers.Classifier;
/**
* Tests PMCC. Run from the command line with:<p/>
* java meka.classifiers.multilabel.PMCCTest
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision: 117 $
*/
public class PMCCTest
extends AbstractMultiLabelClassifierTest {
/**
* Initializes the test.
*
* @param name the name of the test
*/
public PMCCTest(String name) {
super(name);
}
/**
* Creates a default classifier.
*
* @return the classifier
*/
@Override
public Classifier getClassifier() {
return new PMCC();
}
public static Test suite() {
return new TestSuite(PMCCTest.class);
}
public static void main(String[] args){
junit.textui.TestRunner.run(suite());
}
}
| gpl-3.0 |
trol73/mucommander | src/main/com/mucommander/ui/main/DrivePopupButton.java | 26393 | /*
* This file is part of muCommander, http://www.mucommander.com
* Copyright (C) 2002-2012 Maxence Bernard
*
* muCommander 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.
*
* muCommander 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.mucommander.ui.main;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.net.MalformedURLException;
import java.util.*;
import java.util.List;
import java.util.regex.PatternSyntaxException;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import com.mucommander.adb.AndroidMenu;
import com.mucommander.adb.AdbUtils;
import com.mucommander.bonjour.BonjourDirectory;
import com.mucommander.utils.FileIconsCache;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mucommander.bonjour.BonjourMenu;
import com.mucommander.bonjour.BonjourService;
import com.mucommander.bookmark.Bookmark;
import com.mucommander.bookmark.BookmarkListener;
import com.mucommander.bookmark.BookmarkManager;
import com.mucommander.commons.conf.ConfigurationEvent;
import com.mucommander.commons.conf.ConfigurationListener;
import com.mucommander.commons.file.AbstractFile;
import com.mucommander.commons.file.FileFactory;
import com.mucommander.commons.file.FileProtocols;
import com.mucommander.commons.file.FileURL;
import com.mucommander.commons.file.filter.PathFilter;
import com.mucommander.commons.file.filter.RegexpPathFilter;
import com.mucommander.commons.file.impl.local.LocalFile;
import com.mucommander.commons.runtime.OsFamily;
import com.mucommander.conf.TcConfigurations;
import com.mucommander.conf.TcPreference;
import com.mucommander.conf.TcPreferences;
import com.mucommander.utils.text.Translator;
import com.mucommander.ui.action.TcAction;
import com.mucommander.ui.action.impl.OpenLocationAction;
import com.mucommander.ui.button.PopupButton;
import com.mucommander.ui.dialog.server.FTPPanel;
import com.mucommander.ui.dialog.server.HTTPPanel;
import com.mucommander.ui.dialog.server.NFSPanel;
import com.mucommander.ui.dialog.server.SFTPPanel;
import com.mucommander.ui.dialog.server.SMBPanel;
import com.mucommander.ui.dialog.server.ServerConnectDialog;
import com.mucommander.ui.dialog.server.ServerPanel;
import com.mucommander.ui.event.LocationEvent;
import com.mucommander.ui.event.LocationListener;
import com.mucommander.ui.helper.MnemonicHelper;
import com.mucommander.ui.icon.CustomFileIconProvider;
import com.mucommander.ui.icon.FileIcons;
import com.mucommander.ui.icon.IconManager;
import ru.trolsoft.ui.TMenuSeparator;
/**
* <code>DrivePopupButton</code> is a button which, when clicked, pops up a menu with a list of volumes items that be used
* to change the current folder.
*
* @author Maxence Bernard
*/
public class DrivePopupButton extends PopupButton implements BookmarkListener, ConfigurationListener, LocationListener {
private static Logger logger;
/** FolderPanel instance that contains this button */
private FolderPanel folderPanel;
/** Current volumes */
private static AbstractFile volumes[];
/** static FileSystemView instance, has a (non-null) value only under Windows */
private static FileSystemView fileSystemView;
/** Caches extended drive names, has a (non-null) value only under Windows */
private static Map<AbstractFile, String> extendedNameCache;
/** Caches drive icons */
private static Map<AbstractFile, Icon> iconCache = new HashMap<>();
/** Filters out volumes from the list based on the exclude regexp defined in the configuration, null if the regexp
* is not defined. */
private static PathFilter volumeFilter;
static {
if (OsFamily.WINDOWS.isCurrent()) {
fileSystemView = FileSystemView.getFileSystemView();
extendedNameCache = new HashMap<>();
}
try {
String excludeRegexp = TcConfigurations.getPreferences().getVariable(TcPreference.VOLUME_EXCLUDE_REGEXP);
if (excludeRegexp != null) {
volumeFilter = new RegexpPathFilter(excludeRegexp, true);
volumeFilter.setInverted(true);
}
} catch(PatternSyntaxException e) {
getLogger().info("Invalid regexp for conf variable " + TcPreferences.VOLUME_EXCLUDE_REGEXP, e);
}
// Initialize the volumes list
volumes = getDisplayableVolumes();
}
/**
* Creates a new <code>DrivePopupButton</code> which is to be added to the given FolderPanel.
*
* @param folderPanel the FolderPanel instance this button will be added to
*/
DrivePopupButton(FolderPanel folderPanel) {
this.folderPanel = folderPanel;
// Listen to location events to update the button when the current folder changes
folderPanel.getLocationManager().addLocationListener(this);
// Listen to bookmark changes to update the button if a bookmark corresponding to the current folder
// has been added/edited/removed
BookmarkManager.addBookmarkListener(this);
// Listen to configuration changes to update the button if the system file icons policy has changed
TcConfigurations.addPreferencesListener(this);
// Use new JButton decorations introduced in Mac OS X 10.5 (Leopard)
//if (OsFamily.MAC_OS_X.isCurrent() && OsVersion.MAC_OS_X_10_5.isCurrentOrHigher()) {
//setMargin(new Insets(6,8,6,8));
//putClientProperty("JComponent.sizeVariant", "small");
//putClientProperty("JComponent.sizeVariant", "large");
//putClientProperty("JButton.buttonType", "textured");
//}
}
/**
* Updates the button's label and icon to reflect the current folder and match one of the current volumes:
* <<ul>
* <li>If the specified folder corresponds to a bookmark, the bookmark's name will be displayed
* <li>If the specified folder corresponds to a local file, the enclosing volume's name will be displayed
* <li>If the specified folder corresponds to a remote file, the protocol's name will be displayed
* </ul>
* The button's icon will be the current folder's one.
*/
private void updateButton() {
AbstractFile currentFolder = folderPanel.getCurrentFolder();
setText(buildLabel(currentFolder));
// setToolTipText(newToolTip);
// Set the folder icon based on the current system icons policy
setIcon(FileIcons.getFileIcon(currentFolder));
}
private String buildLabel(AbstractFile currentFolder) {
String currentPath = currentFolder != null ? currentFolder.getAbsolutePath() : null;
FileURL currentURL = currentFolder != null ? currentFolder.getURL() : null;
// String newToolTip = null;
// First tries to find a bookmark matching the specified folder
List<Bookmark> bookmarks = BookmarkManager.getBookmarks();
String newLabel = null;
for (Bookmark b : bookmarks) {
if (currentPath != null && currentPath.equals(b.getLocation())) {
// Note: if several bookmarks match current folder, the first one will be used
newLabel = b.getName();
break;
}
}
if (newLabel != null) {
return newLabel;
}
// If no bookmark matched current folder
String protocol = currentURL != null ? currentURL.getScheme() : null;
if (!FileProtocols.FILE.equals(protocol)) {
// Remote file, use the protocol's name
return protocol != null ? protocol.toUpperCase() : "";
} else {
// Local file, use volume's name
// Patch for Windows UNC network paths (weakly characterized by having a host different from 'localhost'):
// display 'SMB' which is the underlying protocol
if (OsFamily.WINDOWS.isCurrent() && !FileURL.LOCALHOST.equals(currentURL.getHost())) {
return "SMB";
} else {
// getCanonicalPath() must be avoided under Windows for the following reasons:
// a) it is not necessary, Windows doesn't have symlinks
// b) it triggers the dreaded 'No disk in drive' error popup dialog.
// c) when network drives are present but not mounted (e.g. X:\ mapped onto an SMB share),
// getCanonicalPath which is I/O bound will take a looooong time to execute
int bestIndex = getBestIndex(getVolumePath(currentFolder));
return volumes[bestIndex].getName();
// Not used because the call to FileSystemView is slow
// if(fileSystemView!=null)
// newToolTip = getWindowsExtendedDriveName(volumes[bestIndex]);
}
}
}
private int getBestIndex(String currentPath) {
int bestLength = -1;
int bestIndex = 0;
for (int i = 0; i < volumes.length; i++) {
String volumePath = getVolumePath(volumes[i]).toLowerCase();
int len = volumePath.length();
if (currentPath.startsWith(volumePath) && len > bestLength) {
bestIndex = i;
bestLength = len;
}
}
return bestIndex;
}
@NotNull
private String getVolumePath(AbstractFile file) {
if (OsFamily.WINDOWS.isCurrent()) {
return file.getAbsolutePath(false);
} else {
return file.getCanonicalPath(false);
}
}
/**
* Returns the extended name of the given local file, e.g. "Local Disk (C:)" for C:\. The returned value is
* interesting only under Windows. This method is I/O bound and very slow so it should not be called from the main
* event thread.
*
* @param localFile the file for which to return the extended name
* @return the extended name of the given local file
*/
private static String getExtendedDriveName(AbstractFile localFile) {
// Note: fileSystemView.getSystemDisplayName(java.io.File) is unfortunately very very slow
String name = fileSystemView.getSystemDisplayName((java.io.File)localFile.getUnderlyingFileObject());
if (name == null || name.isEmpty()) { // This happens for CD/DVD drives when they don't contain any disc
return localFile.getName();
}
return name;
}
/**
* Returns the list of volumes to be displayed in the popup menu.
*
* <p>The raw list of volumes is fetched using {@link LocalFile#getVolumes()} and then
* filtered using the regexp defined in the {@link TcPreferences#VOLUME_EXCLUDE_REGEXP} configuration variable
* (if defined).
*
* @return the list of volumes to be displayed in the popup menu
*/
private static AbstractFile[] getDisplayableVolumes() {
AbstractFile[] volumes = LocalFile.getVolumes();
if (volumeFilter != null) {
return volumeFilter.filter(volumes);
}
return volumes;
}
////////////////////////////////
// PopupButton implementation //
////////////////////////////////
@Override
public JPopupMenu getPopupMenu() {
JPopupMenu popupMenu = new JPopupMenu();
// Update the list of volumes in case new ones were mounted
volumes = getDisplayableVolumes();
// Add volumes
final MainFrame mainFrame = folderPanel.getMainFrame();
MnemonicHelper mnemonicHelper = new MnemonicHelper(); // Provides mnemonics and ensures uniqueness
addVolumes(popupMenu, mainFrame, mnemonicHelper);
popupMenu.add(new TMenuSeparator());
addBookmarks(popupMenu, mainFrame, mnemonicHelper);
popupMenu.add(new TMenuSeparator());
// Add 'Network shares' shortcut
if (FileFactory.isRegisteredProtocol(FileProtocols.SMB)) {
TcAction action = new CustomOpenLocationAction(mainFrame, new Bookmark(Translator.get("drive_popup.network_shares"), "smb:///", null));
action.setIcon(IconManager.getIcon(IconManager.IconSet.FILE, CustomFileIconProvider.NETWORK_ICON_NAME));
setMnemonic(popupMenu.add(action), mnemonicHelper);
}
if (BonjourDirectory.isActive()) {
// Add Bonjour services menu
setMnemonic(popupMenu.add(new BonjourMenu() {
@Override
public TcAction getMenuItemAction(BonjourService bs) {
return new CustomOpenLocationAction(mainFrame, bs);
}
}), mnemonicHelper);
}
addAdbDevices(popupMenu, mainFrame, mnemonicHelper);
popupMenu.add(new TMenuSeparator());
// Add 'connect to server' shortcuts
setMnemonic(popupMenu.add(new ServerConnectAction("SMB...", SMBPanel.class)), mnemonicHelper);
setMnemonic(popupMenu.add(new ServerConnectAction("FTP...", FTPPanel.class)), mnemonicHelper);
setMnemonic(popupMenu.add(new ServerConnectAction("SFTP...", SFTPPanel.class)), mnemonicHelper);
setMnemonic(popupMenu.add(new ServerConnectAction("HTTP...", HTTPPanel.class)), mnemonicHelper);
setMnemonic(popupMenu.add(new ServerConnectAction("NFS...", NFSPanel.class)), mnemonicHelper);
return popupMenu;
}
private void addVolumes(JPopupMenu popupMenu, MainFrame mainFrame, MnemonicHelper mnemonicHelper) {
boolean useExtendedDriveNames = fileSystemView != null;
List<JMenuItem> itemsV = new ArrayList<>();
int nbVolumes = volumes.length;
for (int i = 0; i < nbVolumes; i++) {
TcAction action = new CustomOpenLocationAction(mainFrame, volumes[i]);
String volumeName = volumes[i].getName();
// If several volumes have the same filename, use the volume's path for the action's label instead of the
// volume's path, to disambiguate
for (int j = 0; j < nbVolumes; j++) {
if (j != i && volumes[j].getName().equalsIgnoreCase(volumeName)) {
action.setLabel(volumes[i].getAbsolutePath());
break;
}
}
JMenuItem item = popupMenu.add(action);
setMnemonic(item, mnemonicHelper);
// Set icon from cache
Icon icon = iconCache.get(volumes[i]);
if (icon != null) {
item.setIcon(icon);
}
if (useExtendedDriveNames) {
// Use the last known value (if any) while we update it in a separate thread
String previousExtendedName = extendedNameCache.get(volumes[i]);
if (previousExtendedName != null) {
item.setText(previousExtendedName);
}
}
itemsV.add(item); // JMenu offers no way to retrieve a particular JMenuItem, so we have to keep them
}
new RefreshDriveNamesAndIcons(popupMenu, itemsV).start();
}
private void addBookmarks(JPopupMenu popupMenu, MainFrame mainFrame, MnemonicHelper mnemonicHelper) {
// Add bookmarks
List<Bookmark> bookmarks = BookmarkManager.getBookmarks();
if (!bookmarks.isEmpty()) {
addBookmarksGroup(popupMenu, mainFrame, mnemonicHelper, bookmarks, null);
} else {
// No bookmark : add a disabled menu item saying there is no bookmark
popupMenu.add(Translator.get("bookmarks_menu.no_bookmark")).setEnabled(false);
}
}
private void addBookmarksGroup(JComponent parentMenu, MainFrame mainFrame, MnemonicHelper mnemonicHelper,
List<Bookmark> bookmarks, String parent) {
for (Bookmark b : bookmarks) {
if ((b.getParent() == null && parent == null) || (parent != null && parent.equals(b.getParent()))) {
if (b.getName().equals(BookmarkManager.BOOKMARKS_SEPARATOR) && b.getLocation().isEmpty()) {
parentMenu.add(new TMenuSeparator());
continue;
}
if (b.getLocation().isEmpty()) {
JMenu groupMenu = new JMenu(b.getName());
parentMenu.add(groupMenu);
addBookmarksGroup(groupMenu, mainFrame, mnemonicHelper, bookmarks, b.getName());
setMnemonic(groupMenu, mnemonicHelper);
} else {
JMenuItem item = createBookmarkMenuItem(parentMenu, mainFrame, b);
setMnemonic(item, mnemonicHelper);
}
}
}
}
private JMenuItem createBookmarkMenuItem(JComponent parentMenu, MainFrame mainFrame, Bookmark b) {
JMenuItem item;
if (parentMenu instanceof JPopupMenu) {
item = ((JPopupMenu)parentMenu).add(new CustomOpenLocationAction(mainFrame, b));
} else {
item = ((JMenu)parentMenu).add(new CustomOpenLocationAction(mainFrame, b));
}
//JMenuItem item = popupMenu.add(new CustomOpenLocationAction(mainFrame, b));
String location = b.getLocation();
if (!location.contains("://")) {
AbstractFile file = FileFactory.getFile(location);
if (file != null) {
Icon icon = FileIconsCache.getInstance().getIcon(file);
if (icon != null) {
item.setIcon(icon);
}
// Image image = FileIconsCache.getInstance().getImageIcon(file);
// if (image != null) {
// item.setIcon(new ImageIcon(image));
// }
}
} else if (location.startsWith("ftp://") || location.startsWith("sftp://") || location.startsWith("http://")) {
item.setIcon(IconManager.getIcon(IconManager.IconSet.FILE, CustomFileIconProvider.NETWORK_ICON_NAME));
} else if (location.startsWith("adb://")) {
item.setIcon(IconManager.getIcon(IconManager.IconSet.FILE, CustomFileIconProvider.ANDROID_ICON_NAME));
}
return item;
}
private void addAdbDevices(JPopupMenu popupMenu, MainFrame mainFrame, MnemonicHelper mnemonicHelper) {
if (AdbUtils.checkAdb()) {
setMnemonic(popupMenu.add(new AndroidMenu() {
@Override
public TcAction getMenuItemAction(String deviceSerial) {
FileURL url = getDeviceURL(deviceSerial);
return new CustomOpenLocationAction(mainFrame, url);
}
@Nullable
private FileURL getDeviceURL(String deviceSerial) {
try {
return FileURL.getFileURL("adb://" + deviceSerial);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}
}), mnemonicHelper);
}
}
/**
* Calls to getExtendedDriveName(String) are very slow, so they are performed in a separate thread so as
* to not lock the main even thread. The popup menu gets first displayed with the short drive names, and
* then refreshed with the extended names as they are retrieved.
*/
private class RefreshDriveNamesAndIcons extends Thread {
private JPopupMenu popupMenu;
private List<JMenuItem> items;
RefreshDriveNamesAndIcons(JPopupMenu popupMenu, List<JMenuItem> items) {
super("RefreshDriveNamesAndIcons");
this.popupMenu = popupMenu;
this.items = items;
}
@Override
public void run() {
final boolean useExtendedDriveNames = fileSystemView != null;
for (int i = 0; i < items.size(); i++) {
final JMenuItem item = items.get(i);
final String extendedName = getExtendedDriverName(useExtendedDriveNames, volumes[i]);
final Icon icon = getIcon(volumes[i]);
SwingUtilities.invokeLater(() -> {
if (useExtendedDriveNames) {
item.setText(extendedName);
}
if (icon != null) {
item.setIcon(icon);
}
});
}
// Re-calculate the popup menu's dimensions
SwingUtilities.invokeLater(() -> {
popupMenu.invalidate();
popupMenu.pack();
});
}
@Nullable
private Icon getIcon(AbstractFile file) {
// Set system icon for volumes, only if system icons are available on the current platform
final Icon icon = FileIcons.hasProperSystemIcons() ? FileIcons.getSystemFileIcon(file) : null;
if (icon != null) {
iconCache.put(file, icon);
}
return icon;
}
@Nullable
private String getExtendedDriverName(boolean useExtendedDriveNames, AbstractFile file) {
if (useExtendedDriveNames) {
// Under Windows, show the extended drive name (e.g. "Local Disk (C:)" instead of just "C:") but use
// the simple drive name for the mnemonic (i.e. 'C' instead of 'L').
String extendedName = getExtendedDriveName(file);
// Keep the extended name for later (see above)
extendedNameCache.put(file, extendedName);
return extendedName;
}
return null;
}
}
/**
* Convenience method that sets a mnemonic to the given JMenuItem, using the specified MnemonicHelper.
*
* @param menuItem the menu item for which to set a mnemonic
* @param mnemonicHelper the MnemonicHelper instance to be used to determine the mnemonic's character.
*/
private void setMnemonic(JMenuItem menuItem, MnemonicHelper mnemonicHelper) {
menuItem.setMnemonic(mnemonicHelper.getMnemonic(menuItem.getText()));
}
//////////////////////////////
// BookmarkListener methods //
//////////////////////////////
public void bookmarksChanged() {
// Refresh label in case a bookmark with the current location was changed
updateButton();
}
///////////////////////////////////
// ConfigurationListener methods //
///////////////////////////////////
/**
* Listens to certain configuration variables.
*/
public void configurationChanged(ConfigurationEvent event) {
String var = event.getVariable();
// Update the button's icon if the system file icons policy has changed
if (var.equals(TcPreferences.USE_SYSTEM_FILE_ICONS)) {
updateButton();
}
}
////////////////////////
// Overridden methods //
////////////////////////
@Override
public Dimension getPreferredSize() {
// Limit button's maximum width to something reasonable and leave enough space for location field,
// as bookmarks name can be as long as users want them to be.
// Note: would be better to use JButton.setMaximumSize() but it doesn't seem to work
Dimension d = super.getPreferredSize();
if (d.width > 160) {
d.width = 160;
}
return d;
}
///////////////////
// Inner classes //
///////////////////
/**
* This action pops up {@link com.mucommander.ui.dialog.server.ServerConnectDialog} for a specified
* protocol.
*/
private class ServerConnectAction extends AbstractAction {
private Class<? extends ServerPanel> serverPanelClass;
private ServerConnectAction(String label, Class<? extends ServerPanel> serverPanelClass) {
super(label);
this.serverPanelClass = serverPanelClass;
}
public void actionPerformed(ActionEvent actionEvent) {
new ServerConnectDialog(folderPanel, serverPanelClass).showDialog();
}
}
/**
* This modified {@link OpenLocationAction} changes the current folder on the {@link FolderPanel} that contains
* this button, instead of the currently active {@link FolderPanel}.
*/
private class CustomOpenLocationAction extends OpenLocationAction {
CustomOpenLocationAction(MainFrame mainFrame, Bookmark bookmark) {
super(mainFrame, new HashMap<>(), bookmark);
}
CustomOpenLocationAction(MainFrame mainFrame, AbstractFile file) {
super(mainFrame, new HashMap<>(), file);
}
CustomOpenLocationAction(MainFrame mainFrame, BonjourService bs) {
super(mainFrame, new HashMap<>(), bs);
}
CustomOpenLocationAction(MainFrame mainFrame, FileURL url) {
super(mainFrame, new HashMap<>(), url);
}
////////////////////////
// Overridden methods //
////////////////////////
@Override
protected FolderPanel getFolderPanel() {
return folderPanel;
}
}
/**********************************
* LocationListener Implementation
**********************************/
public void locationChanged(LocationEvent e) {
// Update the button's label to reflect the new current folder
updateButton();
}
public void locationChanging(LocationEvent locationEvent) { }
public void locationCancelled(LocationEvent locationEvent) { }
public void locationFailed(LocationEvent locationEvent) {}
private static Logger getLogger() {
if (logger == null) {
logger = LoggerFactory.getLogger(DrivePopupButton.class);
}
return logger;
}
}
| gpl-3.0 |
LeshiyGS/shikimori | library/src/main/java/org/shikimori/library/adapters/CommentsAdapter.java | 3387 | package org.shikimori.library.adapters;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import com.nostra13.universalimageloader.core.ImageLoader;
import org.shikimori.library.R;
import org.shikimori.library.adapters.base.BaseListAdapter;
import org.shikimori.library.adapters.holder.SettingsHolder;
import org.shikimori.library.objects.ActionQuote;
import org.shikimori.library.objects.one.ItemCommentsShiki;
import org.shikimori.library.tool.ProjectTool;
import org.shikimori.library.tool.hs;
import java.util.Date;
import java.util.List;
/**
* Created by LeshiyGS on 1.04.2015.
*/
public class CommentsAdapter extends BaseListAdapter<ItemCommentsShiki, SettingsHolder> implements View.OnClickListener {
private View.OnClickListener clickListener;
public CommentsAdapter(Context context, List<ItemCommentsShiki> list) {
super(context, list, R.layout.item_shiki_comments_list, SettingsHolder.class);
}
String formatDate(long date, String format) {
return hs.getStringDate(format, new Date(date));
}
@Override
public void setListeners(SettingsHolder holder) {
super.setListeners(holder);
if (clickListener != null)
holder.ivSettings.setOnClickListener(clickListener);
holder.ivPoster.setOnClickListener(this);
}
@Override
public SettingsHolder getViewHolder(View v) {
SettingsHolder hol = super.getViewHolder(v);
hol.ivSettings = find(v, R.id.icSettings);
return hol;
}
public void setOnSettingsListener(View.OnClickListener clickListener) {
this.clickListener = clickListener;
}
@Override
public void setValues(SettingsHolder holder, ItemCommentsShiki item, int position) {
holder.tvName.setText(item.nickname);
Date date = hs.getDateFromString("yyyy-MM-dd'T'HH:mm:ss.SSSZ", item.created_at);
String sdate = formatDate(date.getTime(), "dd MMMM yyyy HH:mm");
holder.tvDate.setText(sdate);
// HtmlText text = new HtmlText(getContext(), false);
// text.setText(item.html_body, holder.tvText);
holder.llBodyHtml.removeAllViews();
holder.llBodyHtml.setTag(R.id.icQuote, new ActionQuote(item.user_id, item.nickname, item.id));
// initDescription(item, holder.llBodyHtml);
if (item.parsedContent.getParent() != null)
((ViewGroup) item.parsedContent.getParent()).removeAllViews();
holder.llBodyHtml.addView(item.parsedContent);
holder.ivSettings.setTag(position);
// очищаем картинку перед загрузкой чтобы она при прокрутке не мигала
holder.ivPoster.setImageDrawable(null);
holder.ivPoster.setTag(position);
ImageLoader.getInstance().displayImage(item.image_x160, holder.ivPoster);
}
@Override
public void onClick(View v) {
// this is user
if (v.getId() == R.id.ivPoster) {
ItemCommentsShiki item = getItem((int) v.getTag());
ProjectTool.goToUser(getContext(), item.user_id);
}
}
public ItemCommentsShiki getItemById(String id){
for (int i = 0; i < getCount(); i++) {
ItemCommentsShiki item = getItem(i);
if(item.id.equals(id))
return item;
}
return null;
}
}
| gpl-3.0 |
MinedroidFTW/DualCraft | org/server/classic/cmd/impl/SummonCommand.java | 2455 | package dualcraft.org.server.classic.cmd.impl;
/*License
====================
Copyright (c) 2010-2012 Daniel Vidmar
We use a modified GNU gpl v 3 license for this.
GNU gpl v 3 is included in License.txt
The modified part of the license is some additions which state the following:
"Redistributions of this project in source or binary must give credit to UnXoft Interactive and DualCraft"
"Redistributions of this project in source or binary must modify at least 300 lines of code in order to release
an initial version. This will require documentation or proof of the 300 modified lines of code."
"Our developers reserve the right to add any additions made to a redistribution of DualCraft into the main
project"
"Our developers reserver the right if they suspect a closed source software using any code from our project
to request to overview the source code of the suspected software. If the owner of the suspected software refuses
to allow a devloper to overview the code then we shall/are granted the right to persue legal action against
him/her"*/
import dualcraft.org.server.classic.cmd.Command;
import dualcraft.org.server.classic.cmd.CommandParameters;
import dualcraft.org.server.classic.model.Player;
/**
* Official /summon command
*
*/
public class SummonCommand extends Command {
/**
* The instance of this command.
*/
private static final SummonCommand INSTANCE = new SummonCommand();
/**
* Gets the singleton instance of this command.
* @return The singleton instance of this command.
*/
public static SummonCommand getCommand() {
return INSTANCE;
}
public String name() {
return "summon";
}
/**
* Default private constructor.
*/
private SummonCommand() {
/* empty */
}
public void execute(Player player, CommandParameters params) {
// Player using command is OP?
if (params.getArgumentCount() == 1) {
for (Player other : player.getWorld().getPlayerList().getPlayers()) {
if (other.getName().toLowerCase().equals(params.getStringArgument(0).toLowerCase())) {
//TODO: Make the player face each other?
other.teleport(player.getPosition(), player.getRotation());
return;
}
}
// Player not found
player.getActionSender().sendChatMessage(params.getStringArgument(0) + " was not found");
return;
} else {
player.getActionSender().sendChatMessage("Wrong number of arguments");
}
player.getActionSender().sendChatMessage("/summon <name>");
}
}
| gpl-3.0 |
fga-gpp-mds/2016.2-CidadeDemocratica | app/src/test/java/com/mdsgpp/cidadedemocratica/requester/TagRequestResponseHandlerTest.java | 1856 | package com.mdsgpp.cidadedemocratica.requester;
import android.test.AndroidTestCase;
import com.mdsgpp.cidadedemocratica.model.Tag;
import org.json.JSONArray;
import org.json.JSONException;
import org.junit.Test;
import java.util.ArrayList;
/**
* Created by andreanmasiro on 04/11/16.
*/
public class TagRequestResponseHandlerTest extends AndroidTestCase implements RequestUpdateListener {
TagRequestResponseHandler handler = new TagRequestResponseHandler();
ArrayList<Tag> response = null;
Tag tag;
int id = 1;
String tagName = "internet";
String errorMessage = null;
@Override
protected void setUp() {
handler.setRequestUpdateListener(this);
}
@Override
protected void tearDown() throws Exception {
response = null;
errorMessage = null;
}
@Test
public void testOnSuccess() throws JSONException {
JSONArray jsonTag = new JSONArray("[{\"id\":" + id + ",\"name\":\"" + tagName + "\",\"relevancia\":982100}]");
handler.onSuccess(200, null, jsonTag);
assertEquals(id, tag.getId());
assertEquals(tagName, tag.getName());
}
@Test
public void testOnFailure() {
int errorCode = 500;
handler.onFailure(errorCode, null, null);
assertEquals(errorMessage, String.valueOf(errorCode));
}
@Test
public void testCompareTags() {
Tag t1 = new Tag(0, "", 0, 0);
Tag t2 = new Tag(0, "", 0, 0);
assertEquals(t1.compareTo(t2), handler.compare(t1, t2));
}
@Override
public void afterSuccess(RequestResponseHandler handler, Object response) {
ArrayList<Tag> tags = (ArrayList<Tag>) response;
tag = tags.get(0);
}
@Override
public void afterError(RequestResponseHandler handler, String message) {
errorMessage = message;
}
}
| gpl-3.0 |
manuel-freire/ac2 | clover/src/test/java/es/ucm/fdi/clover/model/SimpleRuleClustererTest.java | 13328 | /*
* AC - A source-code copy detector
*
* For more information please visit: http://github.com/manuel-freire/ac2
*
* ****************************************************************************
*
* This file is part of AC, version 2.x
*
* AC 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.
*
* AC 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 AC. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ucm.fdi.clover.model;
import es.ucm.fdi.clover.event.HierarchyChangeEvent;
import es.ucm.fdi.clover.event.StructureChangeEvent;
import java.util.ArrayList;
import junit.framework.*;
import es.ucm.fdi.clover.test.TestGraph;
import java.util.Collection;
/**
*
* @author mfreire
*/
public class SimpleRuleClustererTest extends TestCase {
private TestGraph tg;
private ClusterHierarchy ch;
private SimpleRuleClusterer src;
private Object v1 = null, v3 = null, v7 = null, v4 = null, v5 = null;
private Edge e34 = null;
private Cluster r1 = null;
public SimpleRuleClustererTest(String testName) {
super(testName);
}
protected void setUp() throws Exception {
tg = new TestGraph("([1, 2, 3, 4, 5, 6, 7, 8, 9], "
+ "[{1,2}, {1,3}, {3,4}, {4,5}, {4,6}, {3,7}, {7,9}, {7,8}])");
src = new SimpleRuleClusterer();
ch = new ClusterHierarchy(tg, "1", src);
for (Object v : tg.vertexSet()) {
if (v.toString().equals("3")) {
v3 = v;
for (Edge e : (Collection<Edge>) tg.outgoingEdgesOf(v3)) {
if (e.getTarget().toString().equals("4")) {
e34 = e;
v4 = e34.getTarget();
}
}
} else if (v.toString().equals("4"))
v4 = v;
else if (v.toString().equals("7"))
v7 = v;
else if (v.toString().equals("5"))
v5 = v;
else if (v.toString().equals("1"))
v1 = v;
}
r1 = ch.getRoot();
}
public static Test suite() {
TestSuite suite = new TestSuite(SimpleRuleClustererTest.class);
return suite;
}
public void test30NodeGraph() {
}
/**
* Test of createHierarchy method, of class eps.clover.model.SimpleRuleClusterer.
*/
public void testCreateHierarchy() {
BaseGraph base = tg;
Object rootVertex = v1;
SimpleRuleClusterer instance = new SimpleRuleClusterer();
Cluster result = instance.createHierarchy(base, rootVertex);
// expected output of simple clustering (only descendants of root)
String[] expected = new String[] { "{1}", "{2}", "{3}", "{4}", "{5}",
"{6}", "{7}", "{8}", "{9}", "{7.8.9}", "{4.5.6}",
"{3.4.5.6.7.8.9}" };
// check to see if they're equal
assertTrue(Utils.checkSameClusters(expected, result.getDescendants(),
tg));
}
// /**
// * Test of buildCluster method, of class eps.clover.model.SimpleRuleClusterer.
// */
// public void testBuildCluster() {
// System.out.println("buildCluster");
//
// SliceGraph graph = null;
// ArrayList vertices = null;
// Object rootVertex = null;
// SimpleRuleClusterer instance = new SimpleRuleClusterer();
//
// Cluster.Vertex expResult = null;
// Cluster.Vertex result = instance.buildCluster(graph, vertices, rootVertex);
// assertEquals(expResult, result);
//
// // TODO review the generated test code and remove the default call to fail.
// fail("The test case is a prototype.");
// }
/**
* Test of recreateHierarchy method, of class eps.clover.model.SimpleRuleClusterer.
*
* test change of an edge
*/
public void testRecreateHierarchy1() {
System.err.println("testRecreateHierarchy1");
// detach: avoid event-based notification, and go manual
tg.removeStructureChangeListener(ch);
StructureChangeEvent sce = new StructureChangeEvent(tg);
sce.getRemovedEdges().add(e34);
sce.getAddedEdges().add(new Edge(v7, v4));
tg.structureChangePerformed(sce);
BaseGraph base = tg;
Object rootVertex = v1;
Cluster oldRoot = r1;
HierarchyChangeEvent hce = new HierarchyChangeEvent(ch,
"empty test change");
SimpleRuleClusterer instance = new SimpleRuleClusterer();
Cluster c789 = r1.getLastClusterFor(v7).getParentCluster();
Cluster c3456789 = (Cluster) c789.getPath()[1];
// System.err.println("Old dump: "+ch.getRoot().dump());
Cluster result = instance.recreateHierarchy(base, rootVertex, sce, hce);
// System.err.println("New dump: "+result.dump());
System.err.println("hce: " + hce.getDescription());
assertEquals(5, hce.getMatchedClusters().size());
// expected output is "add {4.5.6.7.8.9} remove {7.8.9} {4.5.6} change
// {3.4.5.6.7.8.9}, {1.2.3.4.5.6.7.8.9}"
assertEquals(1, hce.getRemovedClusters().size());
assertEquals(2, hce.getRemovedClusters().values().iterator().next()
.size());
assertEquals(1, hce.getAddedClusters().size());
assertEquals("{4.5.6.7.8.9}", hce.getAddedClusters().values()
.iterator().next().get(0).getListing(tg));
assertEquals(2, hce.getChangedClusters().size());
assertTrue(hce.getChangedClusters().contains(r1));
assertTrue(hce.getChangedClusters().contains(c3456789));
assertEquals(1, hce.getRemovedEdges().size());
assertEquals(1, hce.getAddedEdges().size());
}
/**
* Test of recreateHierarchy method, of class eps.clover.model.SimpleRuleClusterer.
*
* test vertex addition
*/
public void testRecreateHierarchy2() {
System.err.println("testRecreateHierarchy2");
// detach: avoid event-based notification, and go manual
tg.removeStructureChangeListener(ch);
StructureChangeEvent sce = new StructureChangeEvent(tg);
Object v10 = "10";
sce.getAddedVertices().add(v10);
sce.getRemovedEdges().add(e34);
sce.getAddedEdges().add(new Edge(v7, v4));
sce.getAddedEdges().add(new Edge(v4, v10));
tg.structureChangePerformed(sce);
BaseGraph base = tg;
Object rootVertex = v1;
Cluster oldRoot = r1;
HierarchyChangeEvent hce = new HierarchyChangeEvent(ch,
"empty test change");
SimpleRuleClusterer instance = new SimpleRuleClusterer();
Cluster result = instance.recreateHierarchy(base, rootVertex, sce, hce);
System.err.println("hce2 = " + hce.getDescription());
// expected output is "add {4.5.6.7.8.9.10} remove {7.8.9} change {4.5.6.10}, ..."
assertEquals(1, hce.getRemovedClusters().size());
assertEquals(2, hce.getRemovedClusters().values().iterator().next()
.size());
assertEquals(2, hce.getAddedClusters().size());
// one should be {10.4.5.6.7.8.9}, the other {10}
assertEquals(1, hce.getRemovedEdges().size());
assertEquals(2, hce.getAddedEdges().size());
// would contain the '10' if it had already been added... not the case
String[] expected = new String[] { "{4.5.6}", "{1.2.3.4.5.6.7.8.9}",
"{3.4.5.6.7.8.9}" };
assertTrue(Utils.checkSameClusters(expected, hce.getChangedClusters(),
tg));
}
/**
* Test of recreateHierarchy method, of class eps.clover.model.SimpleRuleClusterer.
*
* test vertex addition
*/
public void testRecreateHierarchyRemoveV3() {
System.err.println("testRecreateHierarchyRemoveV3");
// detach: avoid event-based notification, and go manual
tg.removeStructureChangeListener(ch);
StructureChangeEvent sce = new StructureChangeEvent(tg);
sce.getRemovedVertices().add(Utils.getVertexForId("3", tg));
tg.structureChangePerformed(sce);
BaseGraph base = tg;
Object rootVertex = v1;
Cluster oldRoot = r1;
HierarchyChangeEvent hce = new HierarchyChangeEvent(ch,
"empty test change");
SimpleRuleClusterer instance = new SimpleRuleClusterer();
Cluster result = instance.recreateHierarchy(base, rootVertex, sce, hce);
System.err.println("hceRV3 = " + hce.getDescription());
// expected output is "add {1.2} {7.8.9} {4.5.6}
// remove {3.4.5.6.7.8.9} {1} {2} (because 1 and 2 go to {1,2})
// change {1.2.3.4.5.6.7.8.9}
assertEquals(1, hce.getRemovedClusters().size());
assertEquals(3, hce.getRemovedClusters().values().iterator().next()
.size());
assertEquals(1, hce.getAddedClusters().size());
assertEquals(3, hce.getAddedClusters().values().iterator().next()
.size());
assertEquals(0, hce.getRemovedEdges().size());
assertEquals(0, hce.getAddedEdges().size());
// would contain the '10' if it had already been added... not the case
String[] expected = new String[] { "{1.2.3.4.5.6.7.8.9}" };
assertTrue(Utils.checkSameClusters(expected, hce.getChangedClusters(),
tg));
}
/**
* Test of recreateHierarchy method, of class eps.clover.model.SimpleRuleClusterer.
*
* Test removal of a vertex
*/
public void testRecreateHierarchy3() {
System.err.println("testRecreateHierarchy3");
// detach: avoid event-based notification, and go manual
tg.removeStructureChangeListener(ch);
StructureChangeEvent sce = new StructureChangeEvent(tg);
sce.getRemovedVertices().add(v4);
tg.structureChangePerformed(sce);
BaseGraph base = tg;
Object rootVertex = v1;
Cluster oldRoot = r1;
HierarchyChangeEvent hce = new HierarchyChangeEvent(ch,
"empty test change");
SimpleRuleClusterer instance = new SimpleRuleClusterer();
Cluster c456 = r1.getLastClusterFor(v4).getParentCluster();
Cluster result = instance.recreateHierarchy(base, rootVertex, sce, hce);
System.err.println("hce3 = " + hce.getDescription());
// removes {3.4.5.6.7.8.9} ({4} and {4.5.6} are implicit)
assertEquals(1, hce.getRemovedClusters().size());
// adds {1.2.3.7.8.9}, only
assertEquals(1, hce.getAddedClusters().size());
assertEquals("{1.2.3.7.8.9}", hce.getAddedClusters().values()
.iterator().next().get(0).getListing(tg));
// there should be no removed edges
assertEquals(0, hce.getRemovedEdges().size());
// and remember that '4' won't dissapear until the change is performed
String[] expected = new String[] { "{1.2.3.4.5.6.7.8.9}" };
assertTrue(Utils.checkSameClusters(expected, hce.getChangedClusters(),
tg));
assertTrue(hce.getChangedClusters().contains(r1));
}
/**
* Test of recreateHierarchy method, of class eps.clover.model.SimpleRuleClusterer.
*
* Test removal of a vertex
*/
public void testRecreateHierarchy4() {
System.err.println("testRecreateHierarchy4");
// detach: avoid event-based notification, and go manual
tg.removeStructureChangeListener(ch);
StructureChangeEvent sce = new StructureChangeEvent(tg);
sce.getRemovedVertices().add(v5);
tg.structureChangePerformed(sce);
BaseGraph base = tg;
Object rootVertex = v1;
Cluster oldRoot = r1;
HierarchyChangeEvent hce = new HierarchyChangeEvent(ch,
"empty test change");
SimpleRuleClusterer instance = new SimpleRuleClusterer();
Cluster result = instance.recreateHierarchy(base, rootVertex, sce, hce);
System.err.println("hce4 = " + hce.getDescription());
// removes {5}
assertEquals(1, hce.getRemovedClusters().size());
assertEquals(oldRoot.getLastClusterFor(v5).getParentCluster(), hce
.getRemovedClusters().keySet().iterator().next());
assertEquals(0, hce.getAddedClusters().size());
assertEquals(0, hce.getRemovedEdges().size());
// remember, remember, the 5th of november stays there until changed
String[] expected = new String[] { "{1.2.3.4.5.6.7.8.9}",
"{3.4.5.6.7.8.9}", "{4.5.6}" };
assertTrue(Utils.checkSameClusters(expected, hce.getChangedClusters(),
tg));
for (ArrayList<Cluster> l : hce.getAddedClusters().values()) {
assertTrue(Utils.checkSameRoot(r1, l));
}
}
public void testRecreateHierarchy2_1() {
System.err.println("testRecreateHierarchy2_1");
tg = new TestGraph("([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], "
+ "[{0,1}, {1,2}, {2,3}, {3,4}, {4,5}, {6,7}, "
+ " {7,11}, {7,8}, {8,9}, {0,9}, {6,8}, {3,7}, {1,9}, {5,10}])");
ch = new ClusterHierarchy(tg, "0", src);
r1 = ch.getRoot();
Object v2 = null, v0 = null;
for (Object o : tg.vertexSet()) {
if (o.toString().equals("2"))
v2 = o;
if (o.toString().equals("0"))
v0 = o;
}
tg.removeStructureChangeListener(ch);
StructureChangeEvent sce = new StructureChangeEvent(tg);
sce.getRemovedVertices().add(v2);
tg.structureChangePerformed(sce);
System.err.println("sce2_1 = " + sce.getDescription());
BaseGraph base = tg;
Object rootVertex = v0;
Cluster oldRoot = r1;
HierarchyChangeEvent hce = new HierarchyChangeEvent(ch,
"empty test change");
SimpleRuleClusterer instance = new SimpleRuleClusterer();
Cluster result = instance.recreateHierarchy(base, rootVertex, sce, hce);
System.err.println("hce2_1 = " + hce.getDescription());
// removes {5}; but much bigger will disappear: {1.10.11.2.3.4.5.6.7.8.9}
assertEquals(1, hce.getRemovedClusters().size());
// adds another biggie: {0.1.10.11.2.3.4.5.6.7.8.9}
assertEquals(1, hce.getAddedClusters().size());
assertEquals(0, hce.getRemovedEdges().size());
String[] expected = new String[] { "{0.1.10.11.2.3.4.5.6.7.8.9}" };
assertTrue(Utils.checkSameClusters(expected, hce.getChangedClusters(),
tg));
}
}
| gpl-3.0 |
carlgreen/Lexicon-MPX-G2-Editor | mpxg2-cli/src/test/java/info/carlwithak/mpxg2/printing/RoutingPrinterTest.java | 20290 | /*
* Copyright (C) 2011 Carl Green
*
* 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 info.carlwithak.mpxg2.printing;
import info.carlwithak.mpxg2.model.Program;
import info.carlwithak.mpxg2.model.RoutingData;
import info.carlwithak.mpxg2.model.effects.algorithms.Ambience;
import info.carlwithak.mpxg2.model.effects.algorithms.AutoPan;
import info.carlwithak.mpxg2.model.effects.algorithms.Chamber;
import info.carlwithak.mpxg2.model.effects.algorithms.ChorusAlgorithm;
import info.carlwithak.mpxg2.model.effects.algorithms.ChorusPedalVol;
import info.carlwithak.mpxg2.model.effects.algorithms.DelayDual;
import info.carlwithak.mpxg2.model.effects.algorithms.DetuneDual;
import info.carlwithak.mpxg2.model.effects.algorithms.EchoDual;
import info.carlwithak.mpxg2.model.effects.algorithms.EqPedalVol;
import info.carlwithak.mpxg2.model.effects.algorithms.Overdrive;
import info.carlwithak.mpxg2.model.effects.algorithms.Panner;
import info.carlwithak.mpxg2.model.effects.algorithms.PedalWah1;
import info.carlwithak.mpxg2.model.effects.algorithms.Plate;
import info.carlwithak.mpxg2.model.effects.algorithms.Screamer;
import info.carlwithak.mpxg2.model.effects.algorithms.ShiftDual;
import info.carlwithak.mpxg2.model.effects.algorithms.Tone;
import info.carlwithak.mpxg2.model.effects.algorithms.UniVybe;
import info.carlwithak.mpxg2.model.effects.algorithms.VolumeDual;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Tests for RoutingPrinter.
*
* @author Carl Green
*/
public class RoutingPrinterTest {
/**
* Test printing a textual representation of the routing.
*
* G2 Blue is a simple all along the upper route routing.
*
* @throws PrintException if an error is encountered while printing
*/
@Test
public void testPrintG2Blue() throws PrintException {
Program program = new Program();
RoutingData routing = new RoutingData();
routing.setEffectId(8);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting0(routing);
routing = new RoutingData();
routing.setEffectId(0);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting1(routing);
routing = new RoutingData();
routing.setEffectId(1);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting2(routing);
routing = new RoutingData();
routing.setEffectId(6);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting3(routing);
routing = new RoutingData();
routing.setEffectId(2);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting4(routing);
routing = new RoutingData();
routing.setEffectId(3);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting5(routing);
routing = new RoutingData();
routing.setEffectId(4);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting6(routing);
routing = new RoutingData();
routing.setEffectId(5);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting7(routing);
routing = new RoutingData();
routing.setEffectId(7);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting8(routing);
program.setEffect1(new UniVybe());
program.setEffect2(new PedalWah1());
program.setChorus(new ChorusPedalVol());
program.setDelay(new EchoDual());
program.setReverb(new Ambience());
program.setGain(new Screamer());
String expected = "I=1=2=G=C=D=R=e=O";
assertEquals(expected, RoutingPrinter.print(program));
}
/**
* Test printing a textual representation of the routing.
*
* Guitar Solo splits into the lower route.
*
* @throws PrintException if an error is encountered while printing
*/
@Test
public void testPrintGuitarSolo() throws PrintException {
Program program = new Program();
RoutingData routing = new RoutingData();
routing.setEffectId(8);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting0(routing);
routing = new RoutingData();
routing.setEffectId(5);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting1(routing);
routing = new RoutingData();
routing.setEffectId(2);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting2(routing);
routing = new RoutingData();
routing.setEffectId(6);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting3(routing);
routing = new RoutingData();
routing.setEffectId(0);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(3);
routing.setPathType(0);
program.setRouting4(routing);
routing = new RoutingData();
routing.setEffectId(3);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(1);
routing.setPathType(1);
program.setRouting5(routing);
routing = new RoutingData();
routing.setEffectId(4);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(1);
program.setRouting6(routing);
routing = new RoutingData();
routing.setEffectId(1);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(2);
routing.setPathType(1);
program.setRouting7(routing);
routing = new RoutingData();
routing.setEffectId(7);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting8(routing);
program.setEffect1(new DetuneDual());
program.setEffect2(new Panner());
program.setDelay(new EchoDual());
program.setReverb(new Plate());
program.setGain(new Screamer());
String expected = "I=e=c=G=1===R=2=O\n" +
" |=D===|";
String actual = RoutingPrinter.print(program);
assertEquals(expected, actual);
}
/**
* Test printing a textual representation of the routing.
*
* Cordovox splits and has mono and stereo paths.
*
* @throws PrintException if an error is encountered while printing
*/
@Test
public void testPrintCordovox() throws PrintException {
Program program = new Program();
RoutingData routing = new RoutingData();
routing.setEffectId(8);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting0(routing);
routing = new RoutingData();
routing.setEffectId(5);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting1(routing);
routing = new RoutingData();
routing.setEffectId(6);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting2(routing);
routing = new RoutingData();
routing.setEffectId(2);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(3);
routing.setPathType(0);
program.setRouting3(routing);
routing = new RoutingData();
routing.setEffectId(0);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(4);
routing.setRouting(1);
routing.setPathType(1);
program.setRouting4(routing);
routing = new RoutingData();
routing.setEffectId(1);
routing.setUpperInputConnection(3);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(1);
program.setRouting5(routing);
routing = new RoutingData();
routing.setEffectId(3);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(1);
program.setRouting6(routing);
routing = new RoutingData();
routing.setEffectId(4);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(1);
program.setRouting7(routing);
routing = new RoutingData();
routing.setEffectId(7);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(2);
routing.setPathType(1);
program.setRouting8(routing);
program.setEffect1(new AutoPan());
program.setEffect2(new AutoPan());
program.setChorus(new ChorusAlgorithm());
program.setDelay(new EchoDual());
program.setReverb(new Chamber());
program.setEq(new EqPedalVol());
program.setGain(new Tone());
String expected = "I=E=G=C--\\2=D=R=O\n" +
" |/1=======|";
String actual = RoutingPrinter.print(program);
assertEquals(expected, actual);
}
/**
* Test printing a textual representation of the routing.
*
* PowerChords has "lower case numbers".
*
* @throws PrintException if an error is encountered while printing
*/
@Test
public void testPrintPowerChords() throws PrintException {
Program program = new Program();
RoutingData routing = new RoutingData();
routing.setEffectId(8);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting0(routing);
routing = new RoutingData();
routing.setEffectId(1);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting1(routing);
routing = new RoutingData();
routing.setEffectId(6);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting2(routing);
routing = new RoutingData();
routing.setEffectId(5);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting3(routing);
routing = new RoutingData();
routing.setEffectId(0);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting4(routing);
routing = new RoutingData();
routing.setEffectId(2);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting5(routing);
routing = new RoutingData();
routing.setEffectId(3);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting6(routing);
routing = new RoutingData();
routing.setEffectId(4);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting7(routing);
routing = new RoutingData();
routing.setEffectId(7);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting8(routing);
program.setEffect1(new ShiftDual());
program.setDelay(new DelayDual());
program.setReverb(new Chamber());
program.setGain(new Overdrive());
String expected = "I=₂=G=e=1=c=D=R=O";
assertEquals(expected, RoutingPrinter.print(program));
}
/**
* Test printing a textual representation of the routing.
*
* Pitch Cascade has inactive effects on the lower routing.
*
* @throws PrintException if an error is encountered while printing
*/
@Test
public void testPrintPitchCascase() throws PrintException {
Program program = new Program();
RoutingData routing = new RoutingData();
routing.setEffectId(8);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting0(routing);
routing = new RoutingData();
routing.setEffectId(6);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting1(routing);
routing = new RoutingData();
routing.setEffectId(1);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(3);
routing.setPathType(0);
program.setRouting2(routing);
routing = new RoutingData();
routing.setEffectId(5);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(1);
routing.setPathType(1);
program.setRouting3(routing);
routing = new RoutingData();
routing.setEffectId(3);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(1);
routing.setPathType(1);
program.setRouting4(routing);
routing = new RoutingData();
routing.setEffectId(0);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(1);
routing.setPathType(1);
program.setRouting5(routing);
routing = new RoutingData();
routing.setEffectId(2);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(1);
routing.setPathType(1);
program.setRouting6(routing);
routing = new RoutingData();
routing.setEffectId(4);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(2);
routing.setPathType(1);
program.setRouting7(routing);
routing = new RoutingData();
routing.setEffectId(7);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting8(routing);
program.setEffect1(new ShiftDual());
program.setEffect2(new VolumeDual());
program.setDelay(new DelayDual());
program.setReverb(new Ambience());
program.setEq(new EqPedalVol());
program.setGain(new Overdrive());
String expected = "I=G=2=========R=O\n" +
" |=E=D=1=c=|";
assertEquals(expected, RoutingPrinter.print(program));
}
/**
* Test printing an invalid routing where it splits into two routes but
* never combines again.
*
* @throws PrintException if an error is encountered while printing
*/
@Test(expected = PrintException.class)
public void testInvalidRouting() throws PrintException {
Program program = new Program();
RoutingData routing = new RoutingData();
routing.setEffectId(8);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting0(routing);
routing = new RoutingData();
routing.setEffectId(5);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting1(routing);
routing = new RoutingData();
routing.setEffectId(2);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting2(routing);
routing = new RoutingData();
routing.setEffectId(6);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(0);
routing.setPathType(0);
program.setRouting3(routing);
routing = new RoutingData();
routing.setEffectId(0);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(3);
routing.setPathType(0);
program.setRouting4(routing);
routing = new RoutingData();
routing.setEffectId(3);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(1);
routing.setPathType(1);
program.setRouting5(routing);
routing = new RoutingData();
routing.setEffectId(4);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(1);
routing.setPathType(1);
program.setRouting6(routing);
routing = new RoutingData();
routing.setEffectId(1);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(1);
routing.setPathType(1);
program.setRouting7(routing);
routing = new RoutingData();
routing.setEffectId(7);
routing.setUpperInputConnection(0);
routing.setLowerInputConnection(0);
routing.setRouting(1);
routing.setPathType(1);
program.setRouting8(routing);
RoutingPrinter.print(program);
}
}
| gpl-3.0 |
oitsjustjose/V-Tweaks | src/main/java/com/oitsjustjose/vtweaks/common/config/ItemTweakConfig.java | 2337 | package com.oitsjustjose.vtweaks.common.config;
import net.minecraftforge.common.ForgeConfigSpec;
public class ItemTweakConfig {
private static final String CATEGORY_ITEM_TWEAKS = "item tweaks";
public static ForgeConfigSpec.BooleanValue ENABLE_EGG_HATCHING;
public static ForgeConfigSpec.IntValue EGG_HATCING_CHANCE;
public static ForgeConfigSpec.BooleanValue ENABLE_SAPLING_SELF_PLANTING;
public static ForgeConfigSpec.BooleanValue ENABLE_DESPAWN_TIME_OVERRIDE;
public static ForgeConfigSpec.IntValue DESPAWN_TIME_OVERRIDE;
public static ForgeConfigSpec.BooleanValue ENABLE_CONCRETE_TWEAKS;
public static void init(ForgeConfigSpec.Builder COMMON_BUILDER) {
COMMON_BUILDER.comment("Item Tweaks").push(CATEGORY_ITEM_TWEAKS);
ENABLE_EGG_HATCHING = COMMON_BUILDER.comment("Allows egg items in the world to hatch instead of despawn")
.define("eggHatchingEnabled", true);
EGG_HATCING_CHANCE = COMMON_BUILDER
.comment("The chance (out of 100 - higher means more frequent) that the egg will turn into a chick\n"
+ "**DO NOT SET THIS TOO HIGH OR ELSE CHICKENS MAY INFINITELY LAG YOUR WORLD**")
.defineInRange("eggHatchingChance", 1, 1, 100);
ENABLE_SAPLING_SELF_PLANTING = COMMON_BUILDER
.comment("Instead of de-spawning, saplings will attempt to plant themselves")
.define("enableSaplingPlanting", true);
ENABLE_DESPAWN_TIME_OVERRIDE = COMMON_BUILDER.comment("Allow for modifications to item despawn timers")
.define("enableDespawnTimeAdjustments", false);
DESPAWN_TIME_OVERRIDE = COMMON_BUILDER.comment(
"Adjust Item Despawn Time (in ticks: 20 ticks in a second - default despawn delay is 6000 ticks)\n"
+ "-1 prevents items from despawning at all.\n"
+ "If other \"do x on despawn\" configs are enabled, then those items **will still despawn**")
.defineInRange("despawnTimeAdjustments", 6000, -1, Integer.MAX_VALUE);
ENABLE_CONCRETE_TWEAKS = COMMON_BUILDER
.comment("Convert Concrete Powder to Concrete when the item is thrown into water")
.define("enableConreteTweaks", true);
COMMON_BUILDER.pop();
}
} | gpl-3.0 |
optimizationBenchmarking/evaluator-base | src/main/java/org/optimizationBenchmarking/evaluator/data/spec/EAttributeType.java | 2775 | package org.optimizationBenchmarking.evaluator.data.spec;
import java.lang.ref.SoftReference;
/**
* The storage type of
* {@link org.optimizationBenchmarking.evaluator.data.spec.Attribute
* attribute}. Attributes can be {@link #PERMANENTLY_STORED permanently}
* stored, {@link #TEMPORARILY_STORED temporarily} stored as long as there
* is enough memory, or {@link #NEVER_STORED not stored} at all in internal
* caches. Whenever a attribute which may be stored in a cache is accessed,
* first it is checked whether the attribute resides in the cache. If so,
* the cached value is returned. Otherwise, it is computed.
*/
public enum EAttributeType {
/**
* This type is for attributes which must be permanently stored in the
* data set.
*/
PERMANENTLY_STORED(true),
/**
* Attributes of this type my be stored in the data sets but may also be
* purged in low-memory situations. Once purged, they will simply be
* re-computed. This is realized by internally referencing them with
* {@link java.lang.ref.SoftReference soft references} which will be
* garbage collected when the memory situation warrants it.
*/
TEMPORARILY_STORED(true) {
/** {@inheritDoc} */
@Override
@SuppressWarnings("unchecked")
final <T> T unpack(final Object o) {
return ((o != null) ? (((SoftReference<T>) (o)).get()) : null);
}
/** {@inheritDoc} */
@Override
final Object pack(final Object o) {
return new SoftReference<>(o);
}
},
/**
* Attributes of this type will never be stored. We would use this
* attribute type for attributes that either consume a lot of memory or
* are known to be rarely accessed twice. Storing them is either not
* feasible or makes no sense. Attributes of this type will always be
* re-computed when accessed.
*/
NEVER_STORED(false);
/** store the data */
final boolean m_store;
/**
* Create the attribute type
*
* @param store
* should the attribute data
*/
private EAttributeType(final boolean store) {
this.m_store = store;
}
/**
* Unpack an object: the method is internally used to unwrap objects by
* the cache in a data object.
*
* @param o
* the packed object
* @return the unpacked object
* @param <T>
* the goal type
*/
@SuppressWarnings("unchecked")
<T> T unpack(final Object o) {
return ((T) o);
}
/**
* pack an object: the method is internally used to wrap objects by the
* cache in a data object.
*
* @param o
* the unpacked object
* @return the packed object
*/
Object pack(final Object o) {
return o;
}
}
| gpl-3.0 |
GiGsolutions/Invoice_generator | src/model/beans/Invoice.java | 655 |
package model.beans;
import java.util.Date;
/**
*
* @author Gepardas
*/
public class Invoice {
private String buyerName;
private String buyerCode;
private String buyerAdress;
private String buyerCity;
private String buyerCountry;
private String buyerPhone;
private String buyerEmail;
private String buyerGetAlldata;
private Long id;
private Date date;
private double totalExcVat;
private int vat;
private int total;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
| gpl-3.0 |
sgsinclair/trombone | src/test/java/org/voyanttools/trombone/tool/build/CorpusCreatorTest.java | 3901 | package org.voyanttools.trombone.tool.build;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.Test;
import org.voyanttools.trombone.model.Corpus;
import org.voyanttools.trombone.storage.Storage;
import org.voyanttools.trombone.tool.build.RealCorpusCreator;
import org.voyanttools.trombone.util.FlexibleParameters;
import org.voyanttools.trombone.util.TestHelper;
import com.thoughtworks.xstream.XStream;
public class CorpusCreatorTest {
@Test
public void testSteps() throws IOException {
FlexibleParameters parameters = new FlexibleParameters(new String[]{"string=test","file="+TestHelper.getResource("formats/chars.rtf"),"steps=1"});
Storage storage = TestHelper.getDefaultTestStorage();
String nextStep;
// do a first pass one step at a time and make sure we get the right next steps
// store
RealCorpusCreator creator = new RealCorpusCreator(storage, parameters);
creator.run();
nextStep = creator.getNextCorpusCreatorStep();
assertEquals("expand", nextStep);
String storedStoredId = creator.getStoredId();
// expand
parameters.setParameter("nextCorpusCreatorStep", nextStep);
parameters.setParameter("storedId", storedStoredId);
creator.run();
nextStep = creator.getNextCorpusCreatorStep();
assertEquals("extract", nextStep);
String expandedStoredId = creator.getStoredId();
// extract
parameters.setParameter("nextCorpusCreatorStep", nextStep);
parameters.setParameter("storedId", expandedStoredId);
creator.run();
nextStep = creator.getNextCorpusCreatorStep();
assertEquals("index", nextStep);
String extractedStoredId = creator.getStoredId();
// index
parameters.setParameter("nextCorpusCreatorStep", nextStep);
parameters.setParameter("storedId", extractedStoredId);
creator.run();
nextStep = creator.getNextCorpusCreatorStep();
assertEquals("corpus", nextStep);
String indexedStoredId = creator.getStoredId();
// corpus
parameters.setParameter("nextCorpusCreatorStep", nextStep);
parameters.setParameter("storedId", extractedStoredId);
creator.run();
nextStep = creator.getNextCorpusCreatorStep();
assertEquals("done", nextStep);
String storedCorpusId = creator.getStoredId();
// do a second pass one step at a time and make sure we get the same IDs
String storedId;
parameters.removeParameter("nextCorpusCreatorStep");
// store
creator.run();
assertEquals(storedStoredId, creator.getStoredId());
parameters.setParameter("nextCorpusCreatorStep", creator.getNextCorpusCreatorStep());
parameters.setParameter("storedId", storedStoredId);
// expand
creator.run();
assertEquals(expandedStoredId, creator.getStoredId());
parameters.setParameter("nextCorpusCreatorStep", creator.getNextCorpusCreatorStep());
parameters.setParameter("storedId", expandedStoredId);
// extract
creator.run();
assertEquals(extractedStoredId, creator.getStoredId());
parameters.setParameter("nextCorpusCreatorStep", creator.getNextCorpusCreatorStep());
parameters.setParameter("storedId", extractedStoredId);
// index
creator.run();
assertEquals(indexedStoredId, creator.getStoredId());
parameters.setParameter("nextCorpusCreatorStep", creator.getNextCorpusCreatorStep());
parameters.setParameter("storedId", indexedStoredId);
// corpus
creator.run();
assertEquals(storedCorpusId, creator.getStoredId());
// now do a full pass with a new text
parameters = new FlexibleParameters(new String[]{"string=test","file="+TestHelper.getResource("formats/chars.rtf")});
creator = new RealCorpusCreator(storage, parameters);
creator.run();
assertEquals(storedCorpusId, creator.getStoredId());
// XStream xstream;
//
// // serialize to XML
// xstream = new XStream();
// xstream.autodetectAnnotations(true);
// String xml = xstream.toXML(creator);
// System.err.println(xml);
storage.destroy();
}
}
| gpl-3.0 |
BREAD5940/FRC-2016-BREAD-Codebase | FRC-2016-BREAD-Codebase/src/org/usfirst/frc/team5940/states/State.java | 1232 | package org.usfirst.frc.team5940.states;
import edu.wpi.first.wpilibj.RobotBase;
public abstract class State implements Runnable {
@SuppressWarnings("unused")
protected RobotBase robot;
//Update recall delay
private int delay = 25;
/**
* Constructor
* @param robot Saved in this class, allows states to determine information about the robot. This should be passed the subclass of RobotBase of your code.
*/
public State (RobotBase robot){
//Set the robot
this.robot = robot;
}
/**
* Overriden run method for Runnable superclass. Started with STATE_RUNNABLE_NAME.run(); or STATE_THREAD_NAME.start();
*/
@Override
public void run() {
//Initilize
this.init();
//Continue until interupdete
while (!Thread.interrupted()) {
//Update
update();
//try to sleep
try {
Thread.sleep(delay);
} catch (InterruptedException e) { /*Print the error*/e.printStackTrace(); }
}
}
/**
* Called once right after run() is called, even if the Thread is interrupted.
*/
protected abstract void init();
/**
* Called forever with a delay of delay (the var) while the Thread is not interrupted.
*/
protected abstract void update();
}
| gpl-3.0 |
yeSlin1/CBdParking | src/com/pms/bean/Contract.java | 2916 | package com.pms.bean;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
//合约实体类
public class Contract implements Serializable{
private int contractId;//合约ID
private String contractNo;//合约编号
private String contractPicture;//合约图片地址
private int contractType;//是否解约状态
private int contractDirection;//(合约类型<出租合约、租赁合约>)
private Date contractStart;//合约开始时间
private Date contractEnd;//合约结束时间
private Company company;//多对一关系,一个合约对应一个企业用户
private List<CBDParking> cbdparking;//多对多关系,
public List<CBDParking> getCbdParking() {
return cbdparking;
}
public void setCbdParking(List<CBDParking> cbdParking) {
this.cbdparking = cbdParking;
}
public int getContractId() {
return contractId;
}
public void setContractId(int contractId) {
this.contractId = contractId;
}
public String getContractNo() {
return contractNo;
}
public void setContractNo(String contractNo) {
this.contractNo = contractNo;
}
public String getContractPicture() {
return contractPicture;
}
public void setContractPicture(String contractPicture) {
this.contractPicture = contractPicture;
}
public int getContractType() {
return contractType;
}
public void setContractType(int contractType) {
this.contractType = contractType;
}
public int getContractDirection() {
return contractDirection;
}
public void setContractDirection(int contractDirection) {
this.contractDirection = contractDirection;
}
public Date getContractStart() {
return contractStart;
}
public void setContractStart(Date contractStart) {
this.contractStart = contractStart;
}
public Date getContractEnd() {
return contractEnd;
}
public void setContractEnd(Date contractEnd) {
this.contractEnd = contractEnd;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
@Override
public String toString() {
return "Contract [contractId=" + contractId + ", contractNo=" + contractNo + ", contractPicture="
+ contractPicture + ", contractType=" + contractType + ", contractDirection=" + contractDirection
+ ", contractStart=" + contractStart + ", contractEnd=" + contractEnd + ", company=" + company
+ ", cbdparking=" + cbdparking + ", getCbdParking()=" + getCbdParking() + ", getContractId()="
+ getContractId() + ", getContractNo()=" + getContractNo() + ", getContractPicture()="
+ getContractPicture() + ", getContractType()=" + getContractType() + ", getContractDirection()="
+ getContractDirection() + ", getContractStart()=" + getContractStart() + ", getContractEnd()="
+ getContractEnd() + ", getCompany()=" + getCompany() + ", getClass()=" + getClass() + ", hashCode()="
+ hashCode() + ", toString()=" + super.toString() + "]";
}
}
| gpl-3.0 |
isel-leic-mpd/mpd-2017-i41d | aula13-json/src/test/java/WeatherDomainTest.java | 3152 | /*
* Copyright (c) 2017, Miguel Gamboa
*
* 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/>.
*/
import org.junit.Test;
import util.Countify;
import util.FileRequest;
import util.ICounter;
import weather.WeatherService;
import weather.data.WeatherWebApi;
import weather.model.Location;
import weather.model.WeatherInfo;
import java.time.LocalDate;
import static java.lang.System.out;
import static java.time.LocalDate.of;
import static org.junit.Assert.assertEquals;
import static util.queries.LazyQueries.count;
import static util.queries.LazyQueries.distinct;
import static util.queries.LazyQueries.filter;
import static util.queries.LazyQueries.map;
import static util.queries.LazyQueries.skip;
/**
* @author Miguel Gamboa
* created on 29-03-2017
*/
public class WeatherDomainTest {
@Test
public void testWeatherService(){
/**
* Arrange WeatherService --> WeatherWebApi --> Countify --> FileRequest
*/
ICounter<String, Iterable<String>> req = Countify.of(new FileRequest()::getContent);
WeatherService api = new WeatherService(new WeatherWebApi(req::apply));
/**
* Act and Assert
* Counts 0 request while iterator() is not consumed
*/
Iterable<Location> locals = api.search("Porto");
assertEquals(0, req.getCount());
locals = filter(locals, l -> l.getLatitude() > 0 );
assertEquals(0, req.getCount());
/**
* Counts 1 request when iterate to get the first Location
*/
Location loc = locals.iterator().next();
assertEquals(1, req.getCount());
Iterable<WeatherInfo> infos = api.pastWeather(loc.getLatitude(), loc.getLongitude(), of(2017,02,01), of(2017,02,28));
assertEquals(1, req.getCount());
infos = filter(infos, info -> info.getDescription().toLowerCase().contains("sun"));
assertEquals(1, req.getCount());
Iterable<Integer> temps = map(infos, WeatherInfo::getTempC);
assertEquals(1, req.getCount());
temps = distinct(temps);
assertEquals(1, req.getCount());
/**
* When we iterate over the pastWeather then we make one more request
*/
assertEquals(5, count(temps)); // iterates all items
assertEquals(2, req.getCount());
assertEquals((long) 21, (long) skip(temps, 2).iterator().next()); // another iterator
assertEquals(3, req.getCount());
temps.forEach(System.out::println); // iterates all items
assertEquals(4, req.getCount());
}
}
| gpl-3.0 |
kootox/episodes-manager | episodesmanager-services/src/main/java/org/kootox/episodesmanager/services/importExport/XMLWriter.java | 7089 | /*
* #%L
* episodesmanager-services
*
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2009 - 2010 Jean Couteau
* %%
* 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/gpl-3.0.html>.
* #L%
*/
package org.kootox.episodesmanager.services.importExport;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.kootox.episodesmanager.entities.Episode;
import org.kootox.episodesmanager.entities.Season;
import org.kootox.episodesmanager.entities.Show;
import org.kootox.episodesmanager.services.EpisodesManagerService;
import org.kootox.episodesmanager.services.ServiceContext;
import org.kootox.episodesmanager.services.shows.EpisodesService;
import org.kootox.episodesmanager.services.shows.SeasonsService;
import org.kootox.episodesmanager.services.shows.ShowsService;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
/**
*
* Class that can export different elements of database into XML
*
* User: couteau
* Date: 12 mars 2010
*/
public class XMLWriter implements EpisodesManagerService {
private static Log log = LogFactory.getLog(XMLWriter.class);
protected ServiceContext serviceContext;
public XMLWriter(ServiceContext serviceContext) {
this.serviceContext = serviceContext;
}
public void setServiceContext(ServiceContext serviceContext) {
this.serviceContext = serviceContext;
}
/**
* Export an episode into XML
*
* @param episode the episode to export into XML
* @return the episode XML code
*/
private String exportEpisode(Episode episode) {
StringBuilder builder = new StringBuilder();
builder.append(" <episode>\n");
//title
builder.append(" <title>");
builder.append(escape(episode.getTitle()));
builder.append("</title>\n");
//airing date
builder.append(" <airdate>");
builder.append(episode.getAiringDate());
builder.append("</airdate>\n");
//acquired
builder.append(" <acquired>");
builder.append(episode.getAcquired());
builder.append("</acquired>\n");
//viewed
builder.append(" <watched>");
builder.append(episode.getViewed());
builder.append("</watched>\n");
//number
builder.append(" <number>");
builder.append(episode.getNumber());
builder.append("</number>\n");
//summary
builder.append(" <summary>");
builder.append(escape(episode.getSummary()));
builder.append("</summary>\n");
builder.append(" </episode>\n");
return builder.toString() ;
}
private String exportSeason(Season season){
EpisodesService episodesService = serviceContext.newService(EpisodesService.class);
StringBuilder builder = new StringBuilder();
builder.append(" <season>\n");
//number
builder.append(" <number>");
builder.append(season.getNumber());
builder.append("</number>\n");
builder.append(" <episodes>\n");
List<Episode> episodes = episodesService.getAllEpisodes(season);
for(Episode episode:episodes){
builder.append(exportEpisode(episode));
}
builder.append(" </episodes>\n");
builder.append(" </season>\n");
return builder.toString();
}
private String exportShow(Show show){
SeasonsService service = serviceContext.newService(SeasonsService.class);
StringBuilder builder = new StringBuilder();
builder.append("<show>\n");
//title
builder.append(" <name>");
builder.append(escape(show.getTitle()));
builder.append("</name>\n");
//tvrage id
builder.append(" <tvrageID>");
builder.append(show.getTvrageId());
builder.append("</tvrageID>\n");
//over
builder.append(" <status>");
builder.append(show.getOver());
builder.append("</status>\n");
//origin country
builder.append(" <origin_country>");
builder.append(escape(show.getOriginCountry()));
builder.append("</origin_country>\n");
//runtime
builder.append(" <runtime>");
builder.append(show.getRuntime());
builder.append("</runtime>\n");
//network
builder.append(" <network>");
builder.append(escape(show.getNetwork()));
builder.append("</network>\n");
//airtime
builder.append(" <airtime>");
builder.append(show.getAirtime());
builder.append("</airtime>\n");
//timezone
builder.append(" <timezone>");
builder.append(escape(show.getTimeZone()));
builder.append("</timezone>\n");
builder.append(" <seasons>\n");
List<Season> seasons = service.getAllSeasons(show);
for(Season season:seasons){
builder.append(exportSeason(season));
}
builder.append(" </seasons>\n");
builder.append("</show>\n");
return builder.toString();
}
public void exportToXML(File file) {
ShowsService service = serviceContext.newService(ShowsService.class);
OutputStreamWriter xmlFile = null;
try {
xmlFile = new FileWriter(file);
List<Show> shows = service.getAllShows();
StringBuilder builder = new StringBuilder();
builder.append("<?xml version=\"1.0\"?>\n<shows>\n");
for(Show show:shows) {
builder.append(exportShow(show));
}
builder.append("</shows>\n");
xmlFile.write(builder.toString());
xmlFile.close();
} catch (Exception ex) {
log.error("an error occurred", ex);
} finally {
try {
xmlFile.close();
} catch (IOException eee) {
log.error("Error trying to close file");
} catch (NullPointerException eee) {
log.debug("Stream was not existing");
}
}
}
private String escape(String toEscape){
return StringEscapeUtils.escapeXml(toEscape);
}
}
| gpl-3.0 |
wellingtondellamura/compilers-codes-samples | parsers/antlr/BasicIntAST/src/basicintast/util/ThrowingErrorListener.java | 1023 | /*
* 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 basicintast.util;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.misc.ParseCancellationException;
/**
*
* @author wellington
*/
public class ThrowingErrorListener extends BaseErrorListener {
public static final ThrowingErrorListener INSTANCE = new ThrowingErrorListener();
@Override
public void syntaxError(Recognizer<?, ?> recognizer,
Object offendingSymbol, int line,
int charPositionInLine, String msg,
RecognitionException e)
throws ParseCancellationException {
throw new ParseCancellationException("Error on line " + line + " character " + charPositionInLine + " " + msg);
}
}
| gpl-3.0 |
diecode/KillerMoney | src/net/diecode/killermoney/events/KMCCommandExecutionEvent.java | 1271 | package net.diecode.killermoney.events;
import net.diecode.killermoney.objects.CCommand;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class KMCCommandExecutionEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private CCommand cCommand;
private Player killer;
private LivingEntity victim;
private boolean cancelled;
public KMCCommandExecutionEvent(CCommand cCommand, Player killer, LivingEntity victim) {
this.cCommand = cCommand;
this.killer = killer;
this.victim = victim;
}
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
public CCommand getCCommand() {
return cCommand;
}
public Player getKiller() {
return killer;
}
public LivingEntity getVictim() {
return victim;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}
| gpl-3.0 |
gammalgris/jmul | Utilities/Persistence-Tests/src/test/jmul/persistence/FileManagerSmallDatapoolTest.java | 3258 | /*
* SPDX-License-Identifier: GPL-3.0
*
*
* (J)ava (M)iscellaneous (U)tilities (L)ibrary
*
* JMUL is a central repository for utilities which are used in my
* other public and private repositories.
*
* Copyright (C) 2013 Kristian Kutin
*
* 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/>.
*
* e-mail: kristian.kutin@arcor.de
*/
/*
* This section contains meta informations.
*
* $Id$
*/
package test.jmul.persistence;
import jmul.misc.id.IDGenerator;
import jmul.persistence.file.FileManager;
import static jmul.string.Constants.FILE_SEPARATOR;
import jmul.test.classification.ModuleTest;
import org.junit.After;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
/**
* This class contains tests to check file mangaers with existing files.
*
* @author Kristian Kutin
*/
@ModuleTest
public class FileManagerSmallDatapoolTest extends FileManagerTestBase {
/**
* A base directory for tests.
*/
private static final String BASEDIR = ROOT_DIRECTORY + "File-Manager3";
/**
* The file where the generated IDs are persisted.
*/
private static final String ID_FILE = BASEDIR + FILE_SEPARATOR + "idtest";
/**
* The number of files with which the file manager will be prepared before
* running the actual test.
*/
private static final int FILES_THRESHOLD = 10000;
/**
* A file manager.
*/
private FileManager fileManager;
/**
* An ID generator.
*/
private IDGenerator generator;
/**
* Preparations before a test.
*/
@Before
public void setUp() {
initBaseDirectory(BASEDIR);
fileManager = initFileManager(BASEDIR);
generator = initIDGenerator(ID_FILE);
createTestFiles(fileManager, generator, FILES_THRESHOLD);
}
/**
* Cleanup after a test.
*/
@After
public void tearDown() {
fileManager.shutdown();
fileManager = null;
generator = null;
}
/**
* Tests searching for a file within an existing data pool.
*/
@Test
public void testSmallDatapool() {
String[] identifiers = { "#z72_", "Hello World!" };
boolean[] expectedResults = { true, false };
assertEquals("Testdata is incorrect!", identifiers.length, expectedResults.length);
for (int a = 0; a < identifiers.length; a++) {
String identifier = identifiers[a];
boolean expectedResult = expectedResults[a];
boolean result = fileManager.existsFile(identifier);
checkExistence(identifier, expectedResult, result);
}
}
}
| gpl-3.0 |
benjaminaigner/AustrianPublicStream | app/src/main/java/systems/byteswap/publicstream/AppCompatPreferenceActivity.java | 3612 | /**
Copyright:
2015/2016 Benjamin Aigner
developer.google.com
This file is part of AustrianPublicStream.
AustrianPublicStream 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.
AustrianPublicStream 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 AustrianPublicStream. If not, see <http://www.gnu.org/licenses/>.
**/
package systems.byteswap.publicstream;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatDelegate;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A {@link android.preference.PreferenceActivity} which implements and proxies the necessary calls
* to be used with AppCompat.
*/
public abstract class AppCompatPreferenceActivity extends PreferenceActivity {
private AppCompatDelegate mDelegate;
@Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
@NonNull
@Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
@Override
public void setContentView(@LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
@Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
@Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
@Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
@Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
}
| gpl-3.0 |
mtomis/lemonjuice | src/com/codegremlins/lemonjuice/engine/EqualElement.java | 1485 | /*
* lemonjuice - Java Template Engine.
* Copyright (C) 2009-2012 Manuel Tomis manuel@codegremlins.com
*
* This library 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 library 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 library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codegremlins.lemonjuice.engine;
import com.codegremlins.lemonjuice.TemplateContext;
import com.codegremlins.lemonjuice.util.Functions;
class EqualElement extends Element {
private Element left;
private Element right;
private boolean condition;
public EqualElement(boolean condition, Element left, Element right) {
this.condition = condition;
this.left = left;
this.right = right;
}
@Override
public Object evaluate(TemplateContext model) throws Exception {
Object lvalue = left.evaluate(model);
Object rvalue = right.evaluate(model);
return condition == Functions.compareEqual(lvalue, rvalue);
}
} | gpl-3.0 |
siviotti/ubre | ubre-core/src/main/java/br/net/ubre/lang/keyword/binary/relational/EqualsOperator.java | 895 | package br.net.ubre.lang.keyword.binary.relational;
import br.net.ubre.data.container.DataContainer;
import br.net.ubre.lang.data.literal.FalseStatement;
import br.net.ubre.lang.data.literal.TrueStatement;
import br.net.ubre.lang.statement.Statement;
/**
* COmpara se os valores das partes (esquerda e direita) são iguais.
*
* @author Douglas Siviotti (073.116.317-69)
* @version 24/03/2015
*
*/
public class EqualsOperator extends RelationalKeyword {
public EqualsOperator(String token) {
super(token);
}
public Statement perform(DataContainer container) {
Object leftResult = left.result(container);
Object rightResult = right.result(container);
if (leftResult != null) {
return (leftResult.equals(rightResult)) ? TrueStatement.INSTANCE
: FalseStatement.INSTANCE;
}
return (rightResult == null) ? TrueStatement.INSTANCE
: FalseStatement.INSTANCE;
}
}
| gpl-3.0 |
silverweed/pokepon | move/Nap.java | 1192 | //: move/Nap.java
package pokepon.move;
import pokepon.enums.*;
import pokepon.pony.Pony;
import pokepon.battle.*;
/**
* Heal 50% of user's HP.
*
* @author silverweed
*/
public class Nap extends Move {
public Nap() {
super("Nap");
type = Type.NIGHT;
moveType = Move.MoveType.STATUS;
maxpp = pp = 10;
accuracy = -1;
priority = 0;
briefDesc = "User sleeps 2 turns to refill HP and cure status.";
healUser = 1f;
healUserStatus = 1f;
}
public Nap(Pony p) {
this();
pony = p;
}
@Override
public BattleEvent[] getBattleEvents() {
return new BattleEvent[] {
new BattleEvent(1, name) {
@Override
public void afterMoveUsage(final BattleEngine be) {
if(be.getAttacker() == pony && !pony.isFainted()) {
pony.setAsleep(true);
if(be.getBattleTask() != null) {
be.getBattleTask().sendB("|battle|"+pony.getNickname()+" takes a nap and becomes healthy!");
be.getBattleTask().sendB(be.getConnection(be.getSide(pony)),"|addstatus|ally|slp");
be.getBattleTask().sendB(be.getConnection(be.getOppositeSide(pony)),"|addstatus|opp|slp");
}
pony.sleepCounter = 3;
count = 0;
}
}
}
};
}
}
| gpl-3.0 |
pantelis60/L2Scripts_Underground | gameserver/src/main/java/l2s/gameserver/ai/SpecialTautiMonsters.java | 1320 | package l2s.gameserver.ai;
import l2s.gameserver.model.Creature;
import l2s.gameserver.model.instances.NpcInstance;
import l2s.gameserver.model.instances.MonsterInstance;
/**
* @author Bonux
**/
public class SpecialTautiMonsters extends Fighter
{
public SpecialTautiMonsters(NpcInstance actor)
{
super(actor);
}
@Override
protected void onEvtAttacked(Creature attacker, int damage)
{
NpcInstance actor = getActor();
if(!canAttack(actor.getNpcId(), attacker))
return;
super.onEvtAttacked(attacker, damage);
}
@Override
public boolean canAttackCharacter(Creature target)
{
NpcInstance actor = getActor();
return canAttack(actor.getNpcId(), target);
}
@Override
public int getMaxAttackTimeout()
{
return 0;
}
private boolean canAttack(int selfId, Creature target)
{
if(selfId == 33680 || selfId == 33679) //peace
{
if(target.isPlayable())
return false;
else
return target.isMonster();
}
else //not peace
{
if(target.isMonster())
{
MonsterInstance monster = (MonsterInstance) target;
if(monster.getNpcId() == 19262 || monster.getNpcId() == 19263 || monster.getNpcId() == 19264 || monster.getNpcId() == 19265 || monster.getNpcId() == 19266)
return false;
else
return true;
}
else
return !target.isNpc();
}
}
} | gpl-3.0 |
punyararj/his-interface-core | HISIF_CORE/src/com/healthcare/db/client/ItemmappingMapper.java | 1934 | package com.healthcare.db.client;
import com.healthcare.db.model.Itemmapping;
import com.healthcare.db.model.ItemmappingExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface ItemmappingMapper {
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table itemmapping
* @mbggenerated Mon Jul 27 06:41:29 ICT 2015
*/
int countByExample(ItemmappingExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table itemmapping
* @mbggenerated Mon Jul 27 06:41:29 ICT 2015
*/
int deleteByExample(ItemmappingExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table itemmapping
* @mbggenerated Mon Jul 27 06:41:29 ICT 2015
*/
int insert(Itemmapping record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table itemmapping
* @mbggenerated Mon Jul 27 06:41:29 ICT 2015
*/
int insertSelective(Itemmapping record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table itemmapping
* @mbggenerated Mon Jul 27 06:41:29 ICT 2015
*/
List<Itemmapping> selectByExample(ItemmappingExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table itemmapping
* @mbggenerated Mon Jul 27 06:41:29 ICT 2015
*/
int updateByExampleSelective(@Param("record") Itemmapping record,
@Param("example") ItemmappingExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table itemmapping
* @mbggenerated Mon Jul 27 06:41:29 ICT 2015
*/
int updateByExample(@Param("record") Itemmapping record,
@Param("example") ItemmappingExample example);
} | gpl-3.0 |
deric/clusteval-parent | clusteval-backend/src/main/java/de/clusteval/data/goldstandard/format/GoldStandardFormat.java | 821 | /*******************************************************************************
* Copyright (c) 2013 Christian Wiwie.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Christian Wiwie - initial API and implementation
******************************************************************************/
/**
*
*/
package de.clusteval.data.goldstandard.format;
// TODO: Auto-generated Javadoc
/**
* The Class GoldStandardFormat.
*
* @author Christian Wiwie
*/
public class GoldStandardFormat {
/**
* Instantiates a new gold standard format.
*
*/
public GoldStandardFormat() {
super();
}
}
| gpl-3.0 |
customertimes/easyrec-PoC | easyrec-client/src/main/java/easyrec/poc/client/entity/ResponseCode.java | 536 | package easyrec.poc.client.entity;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="success")
@XmlAccessorType(XmlAccessType.FIELD)
public class ResponseCode {
@XmlAttribute(name="code")
private Integer code;
@XmlAttribute(name="message")
private String message;
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
}
| gpl-3.0 |
donaldhwong/1Sheeld | oneSheeld/src/main/java/com/integreight/onesheeld/shields/controller/LcdShield.java | 9331 | package com.integreight.onesheeld.shields.controller;
import android.app.Activity;
import com.integreight.firmatabluetooth.ShieldFrame;
import com.integreight.onesheeld.enums.UIShield;
import com.integreight.onesheeld.shields.ControllerParent;
import com.integreight.onesheeld.utils.Log;
public class LcdShield extends ControllerParent<LcdShield> {
private LcdEventHandler eventHandler;
// private Activity activity;
public int rows = 2;
public int columns = 16;
public char[] chars;
public int currIndx = 0;
// Method ids
private static final byte PRINT = (byte) 0x11;
private static final byte BEGIN = (byte) 0x01;
private static final byte CLEAR = (byte) 0x02;
private static final byte HOME = (byte) 0x03;
// private static final byte NO_DISPLAY = (byte) 0x05;
// private static final byte DISPLAY = (byte) 0x06;
private static final byte NO_BLINK = (byte) 0x04;
private static final byte BLINK = (byte) 0x05;
private static final byte NO_CURSOR = (byte) 0x06;
private static final byte CURSOR = (byte) 0x07;
private static final byte SCROLL_DISPLAY_LEFT = (byte) 0x08;
private static final byte SCROLL_DISPLAY_RIGHT = (byte) 0x09;
private static final byte LEFT_TO_RIGHT = (byte) 0x0A;
private static final byte RIGHT_TO_LEFT = (byte) 0x0B;
// private static final byte CREATE_CHAR = (byte) 0x0F;
private static final byte SET_CURSOR = (byte) 0x0E;
private static final byte WRITE = (byte) 0x0F;
private static final byte AUTO_SCROLL = (byte) 0x0C;
private static final byte NO_AUTO_SCROLL = (byte) 0x0D;
public int lastScrollLeft = 0;
public boolean isBlinking = false, isCursoring = false;
private boolean isAutoScroll = false;
private boolean isLeftToRight = true;
public LcdShield() {
super();
}
public LcdShield(Activity activity, String tag) {
super(activity, tag);
setChars(new char[rows * columns]);
}
@Override
public ControllerParent<LcdShield> init(String tag) {
setChars(new char[columns * rows]);
return super.init(tag);
}
public void setLcdEventHandler(LcdEventHandler eventHandler) {
this.eventHandler = eventHandler;
}
public void write(char ch) {
if (currIndx > -1 && currIndx < chars.length) {
// if (isLeftToRight) {
if (!isAutoScroll) {
chars[currIndx] = ch;
changeCursor(isLeftToRight ? currIndx + 1 : currIndx - 1);
} else {
final char[] tmp = chars;
for (int i = 0; i < currIndx; i++) {
if (i + 1 < tmp.length && i + 1 > -1)
chars[i] = tmp[i + 1];
}
if (currIndx - 1 > -1 && currIndx - 1 < chars.length)
chars[currIndx - 1] = ch;
}
}
}
public void changeCursor(int indx) {
if (!isAutoScroll && indx > -1 && indx < rows * columns) {
if (eventHandler != null) {
eventHandler.noBlink();
eventHandler.noCursor();
}
currIndx = indx;
}
}
public synchronized void scrollDisplayLeft() {
lastScrollLeft = 1;
char[] tmp = new char[chars.length];
for (int i = 0; i < tmp.length; i++) {
if (i + lastScrollLeft > -1 && i + lastScrollLeft < chars.length) {
tmp[i] = chars[i + lastScrollLeft];
}
}
if (eventHandler != null)
eventHandler.noBlink();
changeCursor(currIndx - 1);
chars = tmp;
if (eventHandler != null) {
eventHandler.updateLCD(chars);
if (isBlinking)
eventHandler.blink();
}
Log.d("LCD", (">>>>>>> Left " + lastScrollLeft));
}
public synchronized void scrollDisplayRight() {
lastScrollLeft = -1;
char[] tmp = new char[chars.length];
for (int i = 0; i < tmp.length; i++) {
if (i + lastScrollLeft > -1 && i + lastScrollLeft < chars.length) {
tmp[i] = chars[i + lastScrollLeft];
}
}
if (eventHandler != null)
eventHandler.noBlink();
changeCursor(currIndx + 1);
chars = tmp;
if (eventHandler != null) {
eventHandler.updateLCD(chars);
if (isBlinking)
eventHandler.blink();
}
Log.d("LCD", (">>>>>>> Right " + lastScrollLeft));
}
public static interface LcdEventHandler {
public void updateLCD(char[] arrayToUpdate);
public void blink();
public void noBlink();
public void cursor();
public void noCursor();
}
private void processInput(ShieldFrame frame) {
switch (frame.getFunctionId()) {
case CLEAR:
if (eventHandler != null) {
eventHandler.noBlink();
eventHandler.noCursor();
}
lastScrollLeft = 0;
chars = new char[columns * rows];
if (eventHandler != null)
eventHandler.updateLCD(chars);
changeCursor(0);
if (isBlinking && eventHandler != null)
eventHandler.blink();
if (isCursoring && eventHandler != null)
eventHandler.cursor();
break;
case HOME:
if (eventHandler != null)
eventHandler.noBlink();
if (eventHandler != null)
eventHandler.noCursor();
changeCursor(0);
if (isBlinking && eventHandler != null)
eventHandler.blink();
if (isCursoring && eventHandler != null)
eventHandler.cursor();
break;
case BLINK:
if (eventHandler != null)
eventHandler.blink();
isBlinking = true;
break;
case NO_BLINK:
if (eventHandler != null)
eventHandler.noBlink();
isBlinking = false;
break;
case SCROLL_DISPLAY_LEFT:
scrollDisplayLeft();
break;
case SCROLL_DISPLAY_RIGHT:
scrollDisplayRight();
break;
case BEGIN:
break;
case SET_CURSOR:
if (eventHandler != null) {
eventHandler.noBlink();
eventHandler.noCursor();
}
int row = (int) frame.getArgument(0)[0];
int col = (int) frame.getArgument(1)[0];
changeCursor((row * columns) + col);
if (isBlinking && eventHandler != null)
eventHandler.blink();
if (isCursoring && eventHandler != null)
eventHandler.cursor();
break;
case WRITE:
write(frame.getArgumentAsString(0).charAt(0));
if (eventHandler != null) {
eventHandler.updateLCD(chars);
if (isBlinking)
eventHandler.blink();
if (isCursoring)
eventHandler.cursor();
}
break;
case PRINT:
lastScrollLeft = 0;
if (eventHandler != null) {
eventHandler.noBlink();
eventHandler.noCursor();
}
lastScrollLeft = 0;
String txt = frame.getArgumentAsString(0);
for (int i = 0; i < txt.length(); i++) {
write(txt.charAt(i));
}
if (eventHandler != null) {
eventHandler.updateLCD(chars);
if (isBlinking)
eventHandler.blink();
if (isCursoring)
eventHandler.cursor();
}
break;
case CURSOR:
if (eventHandler != null)
eventHandler.cursor();
isCursoring = true;
break;
case NO_CURSOR:
if (eventHandler != null)
eventHandler.noCursor();
isCursoring = false;
break;
case AUTO_SCROLL:
isAutoScroll = true;
break;
case NO_AUTO_SCROLL:
isAutoScroll = false;
break;
case LEFT_TO_RIGHT:
isLeftToRight = true;
break;
case RIGHT_TO_LEFT:
isLeftToRight = false;
break;
default:
break;
}
}
@Override
public void onNewShieldFrameReceived(ShieldFrame frame) {
if (frame.getShieldId() == UIShield.LCD_SHIELD.getId())
processInput(frame);
}
@Override
public void reset() {
// TODO Auto-generated method stub
}
public void setChars(char[] chars) {
this.chars = chars;
}
}
| gpl-3.0 |
drdrej/android-drafts-app | app/src/main/java/com/touchableheroes/drafts/app/sensors/ISensorListener.java | 127 | package com.touchableheroes.drafts.app.sensors;
/**
* Created by asiebert on 06.12.14.
*/
public class ISensorListener {
}
| gpl-3.0 |
CMPUT301F15T06/GraceHoppers | app/src/androidTest/java/com/gracehoppers/jlovas/bookwrm/ViewTradeActivityTest.java | 2048 | package com.gracehoppers.jlovas.bookwrm;
import android.app.Activity;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.Button;
import android.widget.TextView;
import junit.framework.TestCase;
import java.util.ArrayList;
/**
* Created by ljuarezr on 11/24/15.
*/
public class ViewTradeActivityTest extends TestCase {
/*
Testing ViewTradeActivity. (No UI test yet).
Create a mock trade manually, then test that it is displayed correctly
*/
private TextView borrowerUsername, borrowerBook, ownerUsername, ownerBook, comments;
private Button complete;
public void testViewTrade(){
//First create two accounts
Account A = new Account();
Account B = new Account();
try{
A.setUsername("A");
A.setEmail("abc@gmail.com");
A.setCity("YEG");
B.setUsername("B");
B.setEmail("xyz@gmail.com");
B.setCity("YEG");
} catch (NoSpacesException e){
} catch (TooLongException e){
} catch (IllegalEmailException e ) {
}
//Create two books to make the trade with
Book bookA = new Book();
bookA.setTitle("BookA");
bookA.setAuthor("AuthorA");
Book bookB = new Book();
bookB.setTitle("BookB");
bookB.setAuthor("AuthorB");
ArrayList<Book> borrowerBookList = new ArrayList<>();
borrowerBookList.add(bookB);
//Set up the trade
Trade trade = new Trade();
trade.setOwner(A);
trade.setBorrower(B);
trade.setBorrowerBook(borrowerBookList);
trade.setOwnerBook(bookA);
trade.setOwnerComment("Test Trade");
//Reset the application to a known state
A.getTradeHistory().clear();
A.getTradeHistory().addTrade(trade);
//confirm that book was added to the TradeHistory
assertTrue(A.getTradeHistory().getSize() == 1);
}
public void testComplete(){
}
} | gpl-3.0 |
Sriee/epi | Interview/src/company/StringChains.java | 1592 | package company;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
public class StringChains {
private int longestChain(String[] words) {
if (words == null || words.length == 0)
return 0;
int chainLength = 0;
Arrays.sort(words, new Comparator<String>() {
public int compare(String first, String second) {
return first.length() - second.length();
}
});
Map<String, Integer> wordMap = new HashMap<>();
for (int i = 0; i < words.length; i++) {
if (wordMap.containsKey(words[i]))
continue;
wordMap.put(words[i], 1);
for (int j = 0; j < words[i].length(); j++) {
String temp = words[i].substring(0, j) + words[i].substring(j + 1);
if (wordMap.containsKey(temp) && wordMap.get(temp) + 1 > wordMap.get(words[i])) {
wordMap.put(words[i], wordMap.get(temp) + 1);
}
}
if (wordMap.get(words[i]) > chainLength)
chainLength = wordMap.get(words[i]);
}
return chainLength;
}
public static void main(String[] args) {
StringChains sc = new StringChains();
System.out.println(sc.longestChain(new String[] { "a", "b", "ba", "bca", "bda", "bdca" }));
System.out.println(sc.longestChain(new String[] {}));
System.out.println(sc.longestChain(null));
System.out.println(sc.longestChain(new String[] { "bc", "abc" }));
}
}
| gpl-3.0 |
avdata99/SIAT | siat-1.0-SOURCE/src/view/src/WEB-INF/src/ar/gov/rosario/siat/rec/view/struts/AdministrarNovedadRSDAction.java | 9557 | //Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda.
//This file is part of SIAT. SIAT is licensed under the terms
//of the GNU General Public License, version 3.
//See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt>
package ar.gov.rosario.siat.rec.view.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import ar.gov.rosario.siat.base.view.struts.BaseDispatchAction;
import ar.gov.rosario.siat.base.view.util.BaseConstants;
import ar.gov.rosario.siat.base.view.util.UserSession;
import ar.gov.rosario.siat.gde.iface.model.NovedadRSAdapter;
import ar.gov.rosario.siat.rec.iface.model.NovedadRSVO;
import ar.gov.rosario.siat.rec.iface.service.RecServiceLocator;
import ar.gov.rosario.siat.rec.iface.util.RecError;
import ar.gov.rosario.siat.rec.iface.util.RecSecurityConstants;
import ar.gov.rosario.siat.rec.view.util.RecConstants;
import coop.tecso.demoda.iface.helper.DemodaUtil;
import coop.tecso.demoda.iface.model.CommonKey;
import coop.tecso.demoda.iface.model.NavModel;
public final class AdministrarNovedadRSDAction extends BaseDispatchAction {
private Log log = LogFactory.getLog(AdministrarNovedadRSDAction.class);
public ActionForward inicializar(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String funcName = DemodaUtil.currentMethodName();
String act = getCurrentAct(request);
if (log.isDebugEnabled()) log.debug("entrando en " + funcName);
UserSession userSession = canAccess(request, mapping, RecSecurityConstants.ABM_NOVEDADRS, act);
if (userSession == null) return forwardErrorSession(request);
NavModel navModel = userSession.getNavModel();
NovedadRSAdapter novedadRSAdapterVO = null;
String stringServicio = "";
ActionForward actionForward = null;
try {
CommonKey commonKey = new CommonKey(navModel.getSelectedId());
if (navModel.getAct().equals(BaseConstants.ACT_VER)) {
stringServicio = "getNovedadRSAdapterForView(userSession, commonKey)";
novedadRSAdapterVO = RecServiceLocator.getDreiService().getNovedadRSAdapterForView(userSession, commonKey);
actionForward = mapping.findForward(RecConstants.FWD_NOVEDADRS_VIEW_ADAPTER);
}
if (navModel.getAct().equals(BaseConstants.ACT_APLICAR)) {
stringServicio = "getNovedadRSAdapterForUpdate(userSession, commonKey)";
novedadRSAdapterVO = RecServiceLocator.getDreiService().getNovedadRSAdapterForSimular(userSession, commonKey);
novedadRSAdapterVO.addMessage(RecError.NOVEDADRS_MSG_APLICAR);
actionForward = mapping.findForward(RecConstants.FWD_NOVEDADRS_EDIT_ADAPTER);
}
if (navModel.getAct().equals(RecConstants.ACT_APLICAR_MASIVO_NOVEDADRS)) {
stringServicio = "getNovedadRSAdapterForMasivo(userSession)";
novedadRSAdapterVO = RecServiceLocator.getDreiService().getNovedadRSAdapterForMasivo(userSession);
novedadRSAdapterVO.addMessage(RecError.NOVEDADRS_MSG_APLICAR_MASIVO);
actionForward = mapping.findForward(RecConstants.FWD_NOVEDADRS_VIEW_ADAPTER);
}
if (log.isDebugEnabled()) log.debug(funcName + " salimos de servicio: " + stringServicio );
// Nunca Tiene errores recuperables
// Tiene errores no recuperables
if (novedadRSAdapterVO.hasErrorNonRecoverable()) {
log.error("error en: " + funcName + ": servicio: " +
stringServicio + ": " + novedadRSAdapterVO.errorString());
return forwardErrorNonRecoverable(mapping, request, funcName, NovedadRSAdapter.NAME, novedadRSAdapterVO);
}
// Seteo los valores de navegacion en el adapter
novedadRSAdapterVO.setValuesFromNavModel(navModel);
if (log.isDebugEnabled()) log.debug(funcName + ": " +
NovedadRSAdapter.NAME + ": " + novedadRSAdapterVO.infoString());
// Envio el VO al request
request.setAttribute(NovedadRSAdapter.NAME, novedadRSAdapterVO);
// Subo el apdater al userSession
userSession.put(NovedadRSAdapter.NAME, novedadRSAdapterVO);
saveDemodaMessages(request, novedadRSAdapterVO);
return actionForward;
} catch (Exception exception) {
return baseException(mapping, request, funcName, exception, NovedadRSAdapter.NAME);
}
}
public ActionForward aplicar(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String funcName = DemodaUtil.currentMethodName();
if (log.isDebugEnabled()) log.debug("entrando en " + funcName);
UserSession userSession = canAccess(request, mapping,
RecSecurityConstants.ABM_NOVEDADRS, RecSecurityConstants.MTD_APLICAR);
if (userSession==null) return forwardErrorSession(request);
try {
// Bajo el adapter del userSession
NovedadRSAdapter novedadRSAdapterVO = (NovedadRSAdapter) userSession.get(NovedadRSAdapter.NAME);
// Si es nulo no se puede continuar
if (novedadRSAdapterVO == null) {
log.error("error en: " + funcName + ": " + NovedadRSAdapter.NAME + " IS NULL. No se pudo obtener de la sesion");
return forwardErrorSessionNullObject(mapping, request, funcName, NovedadRSAdapter.NAME);
}
// llamada al servicio
NovedadRSVO novedadRSVO = RecServiceLocator.getDreiService().aplicarNovedadRS(userSession, novedadRSAdapterVO.getNovedadRS());
// Tiene errores recuperables
if (novedadRSVO.hasErrorRecoverable()) {
log.error("recoverable error en: " + funcName + ": " + novedadRSAdapterVO.infoString());
saveDemodaErrors(request, novedadRSVO);
return forwardErrorRecoverable(mapping, request, userSession, NovedadRSAdapter.NAME, novedadRSAdapterVO);
}
// Tiene errores no recuperables
if (novedadRSVO.hasErrorNonRecoverable()) {
log.error("error en: " + funcName + ": " + novedadRSAdapterVO.errorString());
return forwardErrorNonRecoverable(mapping, request, funcName, NovedadRSAdapter.NAME, novedadRSAdapterVO);
}
// Fue Exitoso
return forwardConfirmarOk(mapping, request, funcName, NovedadRSAdapter.NAME);
} catch (Exception exception) {
return baseException(mapping, request, funcName, exception, NovedadRSAdapter.NAME);
}
}
public ActionForward aplicarMasivo(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String funcName = DemodaUtil.currentMethodName();
if (log.isDebugEnabled()) log.debug("entrando en " + funcName);
UserSession userSession = canAccess(request, mapping,
RecSecurityConstants.ABM_NOVEDADRS, RecSecurityConstants.MTD_APLICARMASIVO);
if (userSession==null) return forwardErrorSession(request);
try {
// Bajo el adapter del userSession
NovedadRSAdapter novedadRSAdapterVO = (NovedadRSAdapter) userSession.get(NovedadRSAdapter.NAME);
// Si es nulo no se puede continuar
if (novedadRSAdapterVO == null) {
log.error("error en: " + funcName + ": " + NovedadRSAdapter.NAME + " IS NULL. No se pudo obtener de la sesion");
return forwardErrorSessionNullObject(mapping, request, funcName, NovedadRSAdapter.NAME);
}
// Recuperamos datos del form en el vo
DemodaUtil.populateVO(novedadRSAdapterVO, request);
// Tiene errores recuperables
if (novedadRSAdapterVO.hasErrorRecoverable()) {
log.error("recoverable error en: " + funcName + ": " + novedadRSAdapterVO.infoString());
saveDemodaErrors(request, novedadRSAdapterVO);
return forwardErrorRecoverable(mapping, request, userSession, NovedadRSAdapter.NAME, novedadRSAdapterVO);
}
// llamada al servicio
novedadRSAdapterVO = RecServiceLocator.getDreiService().aplicarMasivoNovedadRS(userSession,novedadRSAdapterVO);
// Tiene errores recuperables
if (novedadRSAdapterVO.hasErrorRecoverable()) {
log.error("recoverable error en: " + funcName + ": " + novedadRSAdapterVO.infoString());
saveDemodaErrors(request, novedadRSAdapterVO);
return forwardErrorRecoverable(mapping, request, userSession, NovedadRSAdapter.NAME, novedadRSAdapterVO, RecConstants.FWD_NOVEDADRS_VIEW_ADAPTER);
}
// Tiene errores no recuperables
if (novedadRSAdapterVO.hasErrorNonRecoverable()) {
log.error("error en: " + funcName + ": " + novedadRSAdapterVO.errorString());
return forwardErrorNonRecoverable(mapping, request, funcName, NovedadRSAdapter.NAME, novedadRSAdapterVO);
}
// Fue Exitoso
return forwardConfirmarOk(mapping, request, funcName, NovedadRSAdapter.NAME);
} catch (Exception exception) {
return baseException(mapping, request, funcName, exception, NovedadRSAdapter.NAME);
}
}
public ActionForward volver(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return baseVolver(mapping, form, request, response, NovedadRSAdapter.NAME);
}
public ActionForward refill(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String funcName = DemodaUtil.currentMethodName();
return baseRefill(mapping, form, request, response, funcName, NovedadRSAdapter.NAME);
}
}
| gpl-3.0 |
optimizationBenchmarking/evaluator-attributes | src/test/java/test/junit/org/optimizationBenchmarking/evaluator/attributes/functions/aggregation2D/package-info.java | 162 | /**
* Tests of our statistical diagram computing attributes.
*/
package test.junit.org.optimizationBenchmarking.evaluator.attributes.functions.aggregation2D; | gpl-3.0 |
chvink/kilomek | megamek/src/megamek/common/weapons/WeaponHandler.java | 56885 | /**
* MegaMek - Copyright (C) 2004,2005 Ben Mazur (bmazur@sev.org)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
package megamek.common.weapons;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Vector;
import megamek.common.Aero;
import megamek.common.AmmoType;
import megamek.common.BattleArmor;
import megamek.common.Building;
import megamek.common.Compute;
import megamek.common.Coords;
import megamek.common.Entity;
import megamek.common.EquipmentMode;
import megamek.common.EquipmentType;
import megamek.common.HitData;
import megamek.common.IAimingModes;
import megamek.common.IGame;
import megamek.common.ITerrain;
import megamek.common.Infantry;
import megamek.common.LosEffects;
import megamek.common.Mech;
import megamek.common.Mounted;
import megamek.common.RangeType;
import megamek.common.Report;
import megamek.common.TagInfo;
import megamek.common.TargetRoll;
import megamek.common.Targetable;
import megamek.common.Terrains;
import megamek.common.ToHitData;
import megamek.common.WeaponType;
import megamek.common.actions.WeaponAttackAction;
import megamek.common.options.OptionsConstants;
import megamek.server.Server;
import megamek.server.Server.DamageType;
import megamek.server.SmokeCloud;
/**
* @author Andrew Hunter A basic, simple attack handler. May or may not work for
* any particular weapon; must be overloaded to support special rules.
*/
public class WeaponHandler implements AttackHandler, Serializable {
private static final long serialVersionUID = 7137408139594693559L;
public ToHitData toHit;
protected HitData hit;
public WeaponAttackAction waa;
public int roll;
protected boolean isJammed = false;
protected IGame game;
protected transient Server server; // must not save the server
protected boolean bMissed;
protected boolean bSalvo = false;
protected boolean bGlancing = false;
protected boolean bDirect = false;
protected boolean nukeS2S = false;
protected WeaponType wtype;
protected String typeName;
protected Mounted weapon;
protected Entity ae;
protected Targetable target;
protected int subjectId;
protected int nRange;
protected int nDamPerHit;
protected int attackValue;
protected boolean throughFront;
protected boolean underWater;
protected boolean announcedEntityFiring = false;
protected boolean missed = false;
protected DamageType damageType;
protected int generalDamageType = HitData.DAMAGE_NONE;
protected Vector<Integer> insertedAttacks = new Vector<Integer>();
protected int nweapons; // for capital fighters/fighter squadrons
protected int nweaponsHit; // for capital fighters/fighter squadrons
protected boolean secondShot = false;
protected int numRapidFireHits;
protected String sSalvoType = " shot(s) ";
protected int nSalvoBonus = 0;
/**
* Keeps track of whether we are processing the first hit in a series of
* hits (like for cluster weapons)
*/
protected boolean firstHit = true;
/**
* Boolean flag that determines whether or not this attack is part of a
* strafing run.
*/
protected boolean isStrafing = false;
/**
* Boolean flag that determiens if this shot was the first one by a
* particular weapon in a strafing run. Used to ensure that heat is only
* added once.
*/
protected boolean isStrafingFirstShot = false;
/**
* return the <code>int</code> Id of the attacking <code>Entity</code>
*/
public int getAttackerId() {
return ae.getId();
}
/**
* Do we care about the specified phase?
*/
public boolean cares(IGame.Phase phase) {
if (phase == IGame.Phase.PHASE_FIRING) {
return true;
}
return false;
}
/**
* @param vPhaseReport
* - A <code>Vector</code> containing the phasereport.
* @return a <code>boolean</code> value indicating wether or not the attack
* misses because of a failed check.
*/
protected boolean doChecks(Vector<Report> vPhaseReport) {
return false;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
server = Server.getServerInstance();
}
/**
* @return a <code>boolean</code> value indicating wether or not this attack
* needs further calculating, like a missed shot hitting a building,
* or an AMS only shooting down some missiles.
*/
protected boolean handleSpecialMiss(Entity entityTarget,
boolean targetInBuilding, Building bldg, Vector<Report> vPhaseReport) {
// Shots that miss an entity can set fires.
// Buildings can't be accidentally ignited,
// and some weapons can't ignite fires.
if ((entityTarget != null)
&& ((bldg == null) && (wtype.getFireTN() != TargetRoll.IMPOSSIBLE))) {
server.tryIgniteHex(target.getPosition(), subjectId, false, false,
new TargetRoll(wtype.getFireTN(), wtype.getName()), 3,
vPhaseReport);
}
// shots that miss an entity can also potential cause explosions in a
// heavy industrial hex
server.checkExplodeIndustrialZone(target.getPosition(), vPhaseReport);
// BMRr, pg. 51: "All shots that were aimed at a target inside
// a building and miss do full damage to the building instead."
if (!targetInBuilding
|| (toHit.getValue() == TargetRoll.AUTOMATIC_FAIL)) {
return false;
}
return true;
}
/**
* Calculate the number of hits
*
* @param vPhaseReport
* - the <code>Vector</code> containing the phase report.
* @return an <code>int</code> containing the number of hits.
*/
protected int calcHits(Vector<Report> vPhaseReport) {
// normal BA attacks (non-swarm, non single-trooper weapons)
// do more than 1 hit
if ((ae instanceof BattleArmor)
&& (weapon.getLocation() == BattleArmor.LOC_SQUAD)
&& !(weapon.isSquadSupportWeapon())
&& !(ae.getSwarmTargetId() == target.getTargetId())) {
bSalvo = true;
int toReturn = allShotsHit() ? ((BattleArmor) ae)
.getShootingStrength() : Compute
.missilesHit(((BattleArmor) ae).getShootingStrength());
Report r = new Report(3325);
r.newlines = 0;
r.subject = subjectId;
r.add(toReturn);
r.add(" troopers ");
r.add(toHit.getTableDesc());
vPhaseReport.add(r);
return toReturn;
}
return 1;
}
/**
* Calculate the clustering of the hits
*
* @return a <code>int</code> value saying how much hits are in each cluster
* of damage.
*/
protected int calcnCluster() {
return 1;
}
protected int calcnClusterAero(Entity entityTarget) {
if (usesClusterTable() && !ae.isCapitalFighter()
&& (entityTarget != null) && !entityTarget.isCapitalScale()) {
return 5;
} else {
return 1;
}
}
protected int[] calcAeroDamage(Entity entityTarget,
Vector<Report> vPhaseReport) {
// Now I need to adjust this for attacks on aeros because they use
// attack values and different rules
// this will work differently for cluster and non-cluster
// weapons, and differently for capital fighter/fighter
// squadrons
if (game.getOptions().booleanOption("aero_sanity")) {
// everything will use the normal hits and clusters for hits weapon
// unless
// we have a squadron or capital scale entity
int reportSize = vPhaseReport.size();
int hits = calcHits(vPhaseReport);
int nCluster = calcnCluster();
if (ae.isCapitalFighter()) {
Vector<Report> throwAwayReport = new Vector<Report>();
// for capital scale fighters, each non-cluster weapon hits a
// different location
bSalvo = true;
hits = 1;
if (nweapons > 1) {
if (allShotsHit()) {
nweaponsHit = nweapons;
} else {
nweaponsHit = Compute.missilesHit(nweapons,
((Aero) ae).getClusterMods());
}
if (usesClusterTable()) {
// remove the last reports because they showed the
// number of shots that hit
while (vPhaseReport.size() > reportSize) {
vPhaseReport.remove(vPhaseReport.size() - 1);
}
// nDamPerHit = 1;
hits = 0;
for (int i = 0; i < nweaponsHit; i++) {
hits += calcHits(throwAwayReport);
}
Report r = new Report(3325);
r.subject = subjectId;
r.add(hits);
r.add(sSalvoType);
r.add(toHit.getTableDesc());
r.newlines = 0;
vPhaseReport.add(r);
} else {
nCluster = 1;
Report r = new Report(3325);
r.subject = subjectId;
r.add(nweaponsHit);
r.add(" weapon(s) ");
r.add(" ");
r.newlines = 0;
hits = nweaponsHit;
vPhaseReport.add(r);
}
}
}
int[] results = new int[2];
results[0] = hits;
results[1] = nCluster;
return results;
} else {
int hits = 1;
int nCluster = calcnClusterAero(entityTarget);
if (ae.isCapitalFighter()) {
bSalvo = false;
if (nweapons > 1) {
nweaponsHit = Compute.missilesHit(nweapons,
((Aero) ae).getClusterMods());
Report r = new Report(3325);
r.subject = subjectId;
r.add(nweaponsHit);
r.add(" weapon(s) ");
r.add(" ");
r.newlines = 0;
vPhaseReport.add(r);
}
nDamPerHit = attackValue * nweaponsHit;
hits = 1;
nCluster = 1;
} else if (nCluster > 1) {
bSalvo = true;
nDamPerHit = 1;
hits = attackValue;
} else {
bSalvo = false;
nDamPerHit = attackValue;
hits = 1;
nCluster = 1;
}
int[] results = new int[2];
results[0] = hits;
results[1] = nCluster;
return results;
}
}
/**
* handle this weapons firing
*
* @return a <code>boolean</code> value indicating whether this should be
* kept or not
*/
public boolean handle(IGame.Phase phase, Vector<Report> vPhaseReport) {
if (!cares(phase)) {
return true;
}
boolean heatAdded = false;
int numAttacks = 1;
if (game.getOptions().booleanOption("uac_tworolls")
&& ((wtype.getAmmoType() == AmmoType.T_AC_ULTRA) || (wtype
.getAmmoType() == AmmoType.T_AC_ULTRA_THB))
&& !weapon.curMode().equals("Single")) {
numAttacks = 2;
}
insertAttacks(phase, vPhaseReport);
Entity entityTarget = (target.getTargetType() == Targetable.TYPE_ENTITY) ? (Entity) target
: null;
final boolean targetInBuilding = Compute.isInBuilding(game,
entityTarget);
if (entityTarget != null) {
ae.setLastTarget(entityTarget.getId());
ae.setLastTargetDisplayName(entityTarget.getDisplayName());
}
// Which building takes the damage?
Building bldg = game.getBoard().getBuildingAt(target.getPosition());
String number = nweapons > 1 ? " (" + nweapons + ")" : "";
for (int i = numAttacks; i > 0; i--) {
// Report weapon attack and its to-hit value.
Report r = new Report(3115);
r.indent();
r.newlines = 0;
r.subject = subjectId;
r.add(wtype.getName() + number);
if (entityTarget != null) {
if ((wtype.getAmmoType() != AmmoType.T_NA)
&& (weapon.getLinked() != null)
&& (weapon.getLinked().getType() instanceof AmmoType)) {
AmmoType atype = (AmmoType) weapon.getLinked().getType();
if (atype.getMunitionType() != AmmoType.M_STANDARD) {
r.messageId = 3116;
r.add(atype.getSubMunitionName());
}
}
r.addDesc(entityTarget);
} else {
r.messageId = 3120;
r.add(target.getDisplayName(), true);
}
vPhaseReport.addElement(r);
if (toHit.getValue() == TargetRoll.IMPOSSIBLE) {
r = new Report(3135);
r.subject = subjectId;
r.add(toHit.getDesc());
vPhaseReport.addElement(r);
return false;
} else if (toHit.getValue() == TargetRoll.AUTOMATIC_FAIL) {
r = new Report(3140);
r.newlines = 0;
r.subject = subjectId;
r.add(toHit.getDesc());
vPhaseReport.addElement(r);
} else if (toHit.getValue() == TargetRoll.AUTOMATIC_SUCCESS) {
r = new Report(3145);
r.newlines = 0;
r.subject = subjectId;
r.add(toHit.getDesc());
vPhaseReport.addElement(r);
} else {
// roll to hit
r = new Report(3150);
r.newlines = 0;
r.subject = subjectId;
r.add(toHit.getValue());
vPhaseReport.addElement(r);
}
// dice have been rolled, thanks
r = new Report(3155);
r.newlines = 0;
r.subject = subjectId;
r.add(roll);
vPhaseReport.addElement(r);
// do we hit?
bMissed = roll < toHit.getValue();
// are we a glancing hit?
if (game.getOptions().booleanOption("tacops_glancing_blows")) {
if (roll == toHit.getValue()) {
bGlancing = true;
r = new Report(3186);
r.subject = ae.getId();
r.newlines = 0;
vPhaseReport.addElement(r);
} else {
bGlancing = false;
}
} else {
bGlancing = false;
}
// Set Margin of Success/Failure.
toHit.setMoS(roll - Math.max(2, toHit.getValue()));
bDirect = game.getOptions().booleanOption("tacops_direct_blow")
&& ((toHit.getMoS() / 3) >= 1) && (entityTarget != null);
if (bDirect) {
r = new Report(3189);
r.subject = ae.getId();
r.newlines = 0;
vPhaseReport.addElement(r);
}
// Do this stuff first, because some weapon's miss report reference
// the
// amount of shots fired and stuff.
nDamPerHit = calcDamagePerHit();
if (!heatAdded) {
addHeat();
heatAdded = true;
}
attackValue = calcAttackValue();
// Any necessary PSRs, jam checks, etc.
// If this boolean is true, don't report
// the miss later, as we already reported
// it in doChecks
boolean missReported = doChecks(vPhaseReport);
if (missReported) {
bMissed = true;
}
// Do we need some sort of special resolution (minefields,
// artillery,
if (specialResolution(vPhaseReport, entityTarget) && (i < 2)) {
return false;
}
if (bMissed && !missReported) {
if (game.getOptions().booleanOption("uac_tworolls")
&& ((wtype.getAmmoType() == AmmoType.T_AC_ULTRA) || (wtype
.getAmmoType() == AmmoType.T_AC_ULTRA_THB))
&& (i == 2)) {
reportMiss(vPhaseReport, true);
} else {
reportMiss(vPhaseReport);
}
// Works out fire setting, AMS shots, and whether continuation
// is
// necessary.
if (!handleSpecialMiss(entityTarget, targetInBuilding, bldg,
vPhaseReport) && (i < 2)) {
return false;
}
}
// yeech. handle damage. . different weapons do this in very
// different
// ways
int nCluster = calcnCluster();
int id = vPhaseReport.size();
int hits = calcHits(vPhaseReport);
if (target.isAirborne() || game.getBoard().inSpace()) {
// if we added a line to the phase report for calc hits, remove
// it now
while (vPhaseReport.size() > id) {
vPhaseReport.removeElementAt(vPhaseReport.size() - 1);
}
int[] aeroResults = calcAeroDamage(entityTarget, vPhaseReport);
hits = aeroResults[0];
nCluster = aeroResults[1];
}
// We have to adjust the reports on a miss, so they line up
if (bMissed && id != vPhaseReport.size()) {
vPhaseReport.get(id - 1).newlines--;
vPhaseReport.get(id).indent(2);
vPhaseReport.get(vPhaseReport.size() - 1).newlines++;
}
if (!bMissed) {
// The building shields all units from a certain amount of
// damage.
// The amount is based upon the building's CF at the phase's
// start.
int bldgAbsorbs = 0;
if (targetInBuilding && (bldg != null)) {
bldgAbsorbs = bldg.getAbsorbtion(target.getPosition());
}
// Make sure the player knows when his attack causes no damage.
if (hits == 0) {
r = new Report(3365);
r.subject = subjectId;
vPhaseReport.addElement(r);
}
// for each cluster of hits, do a chunk of damage
while (hits > 0) {
int nDamage;
if ((target.getTargetType() == Targetable.TYPE_HEX_TAG)
|| (target.getTargetType() == Targetable.TYPE_BLDG_TAG)) {
int priority = 1;
EquipmentMode mode = (weapon.curMode());
if (mode != null) {
if (mode.getName() == "1-shot") {
priority = 1;
} else if (mode.getName() == "2-shot") {
priority = 2;
} else if (mode.getName() == "3-shot") {
priority = 3;
} else if (mode.getName() == "4-shot") {
priority = 4;
}
}
TagInfo info = new TagInfo(ae.getId(),
target.getTargetType(), target, priority, false);
game.addTagInfo(info);
r = new Report(3390);
r.subject = subjectId;
vPhaseReport.addElement(r);
hits = 0;
}
// targeting a hex for igniting
if ((target.getTargetType() == Targetable.TYPE_HEX_IGNITE)
|| (target.getTargetType() == Targetable.TYPE_BLDG_IGNITE)) {
handleIgnitionDamage(vPhaseReport, bldg, hits);
hits = 0;
}
// targeting a hex for clearing
if (target.getTargetType() == Targetable.TYPE_HEX_CLEAR) {
nDamage = nDamPerHit * hits;
handleClearDamage(vPhaseReport, bldg, nDamage);
hits = 0;
}
// Targeting a building.
if (target.getTargetType() == Targetable.TYPE_BUILDING) {
// The building takes the full brunt of the attack.
nDamage = nDamPerHit * hits;
handleBuildingDamage(vPhaseReport, bldg, nDamage,
target.getPosition());
hits = 0;
}
if (entityTarget != null) {
handleEntityDamage(entityTarget, vPhaseReport, bldg,
hits, nCluster, bldgAbsorbs);
server.creditKill(entityTarget, ae);
hits -= nCluster;
firstHit = false;
}
} // Handle the next cluster.
} else { // We missed, but need to handle special miss cases
// When shooting at a non-infantry unit in a building and the
// shot misses, the building is damaged instead, TW pg 171
int dist = ae.getPosition().distance(target.getPosition());
if (targetInBuilding && !(entityTarget instanceof Infantry)
&& dist == 1) {
r = new Report(6429);
r.indent(2);
r.subject = ae.getId();
r.newlines--;
vPhaseReport.add(r);
int nDamage = nDamPerHit * hits;
// We want to set bSalvo to true to prevent
// handleBuildingDamage from reporting a hit
boolean savedSalvo = bSalvo;
bSalvo = true;
handleBuildingDamage(vPhaseReport, bldg, nDamage,
target.getPosition());
bSalvo = savedSalvo;
hits = 0;
}
}
if (game.getOptions().booleanOption("uac_tworolls")
&& ((wtype.getAmmoType() == AmmoType.T_AC_ULTRA) || (wtype
.getAmmoType() == AmmoType.T_AC_ULTRA_THB))
&& (i == 2)) {
// Jammed weapon doesn't get 2nd shot...
if (isJammed) {
r = new Report(9905);
r.indent();
r.subject = ae.getId();
vPhaseReport.addElement(r);
i--;
} else { // If not jammed, it gets the second shot...
r = new Report(9900);
r.indent();
r.subject = ae.getId();
vPhaseReport.addElement(r);
if (null != ae.getCrew()) {
roll = ae.getCrew().rollGunnerySkill();
} else {
roll = Compute.d6(2);
}
}
}
}
Report.addNewline(vPhaseReport);
return false;
}
/**
* Calculate the damage per hit.
*
* @return an <code>int</code> representing the damage dealt per hit.
*/
protected int calcDamagePerHit() {
double toReturn = wtype.getDamage(nRange);
// Check for BA vs BA weapon effectiveness, if option is on
if (game.getOptions().booleanOption("tacops_ba_vs_ba")
&& (target instanceof BattleArmor)) {
// We don't check to make sure the attacker is BA, as most weapons
// will return their normal damage.
toReturn = Compute.directBlowBADamage(toReturn,
wtype.getBADamageClass(), (BattleArmor) target);
}
// we default to direct fire weapons for anti-infantry damage
if ((target instanceof Infantry) && !(target instanceof BattleArmor)) {
toReturn = Compute.directBlowInfantryDamage(toReturn,
bDirect ? toHit.getMoS() / 3 : 0,
wtype.getInfantryDamageClass(),
((Infantry) target).isMechanized());
} else if (bDirect) {
toReturn = Math.min(toReturn + (toHit.getMoS() / 3), toReturn * 2);
}
if (bGlancing) {
// Round up glancing blows against conventional infantry
if ((target instanceof Infantry)
&& !(target instanceof BattleArmor)) {
toReturn = (int) Math.ceil(toReturn / 2.0);
} else {
toReturn = (int) Math.floor(toReturn / 2.0);
}
}
if (game.getOptions().booleanOption(OptionsConstants.AC_TAC_OPS_RANGE)
&& (nRange > wtype.getRanges(weapon)[RangeType.RANGE_LONG])) {
toReturn = (int) Math.floor(toReturn * .75);
}
if (game.getOptions().booleanOption(
OptionsConstants.AC_TAC_OPS_LOS_RANGE)
&& (nRange > wtype.getRanges(weapon)[RangeType.RANGE_EXTREME])) {
toReturn = (int) Math.floor(toReturn * .5);
}
return (int) toReturn;
}
/**
* Calculate the attack value based on range
*
* @return an <code>int</code> representing the attack value at that range.
*/
protected int calcAttackValue() {
int av = 0;
// if we have a ground firing unit, then AV should not be determined by
// aero range brackets
if (!ae.isAirborne() || game.getOptions().booleanOption("uac_tworolls")) {
if (usesClusterTable()) {
// for cluster weapons just use the short range AV
av = wtype.getRoundShortAV();
} else {
// otherwise just use the full weapon damage by range
av = wtype.getDamage(nRange);
}
} else {
// we have an airborne attacker, so we need to use aero range
// brackets
int range = RangeType.rangeBracket(nRange, wtype.getATRanges(),
true, false);
if (range == WeaponType.RANGE_SHORT) {
av = wtype.getRoundShortAV();
} else if (range == WeaponType.RANGE_MED) {
av = wtype.getRoundMedAV();
} else if (range == WeaponType.RANGE_LONG) {
av = wtype.getRoundLongAV();
} else if (range == WeaponType.RANGE_EXT) {
av = wtype.getRoundExtAV();
}
}
if (bDirect) {
av = Math.min(av + (toHit.getMoS() / 3), av * 2);
}
if (bGlancing) {
av = (int) Math.floor(av / 2.0);
}
av = (int) Math.floor(getBracketingMultiplier() * av);
return av;
}
/**
* * adjustment factor on attack value for fighter squadrons
*/
protected double getBracketingMultiplier() {
double mult = 1.0;
if (wtype.hasModes() && weapon.curMode().equals("Bracket 80%")) {
mult = 0.8;
}
if (wtype.hasModes() && weapon.curMode().equals("Bracket 60%")) {
mult = 0.6;
}
if (wtype.hasModes() && weapon.curMode().equals("Bracket 40%")) {
mult = 0.4;
}
return mult;
}
/*
* Return the capital missile target for criticals. Zero if not a capital
* missile
*/
protected int getCapMisMod() {
return 0;
}
/**
* Handles potential damage to partial cover that absorbs a shot. The
* <code>ToHitData</code> is checked to what if there is any damagable cover
* to be hit, and if so which cover gets hit (there are two possibilities in
* some cases, such as 75% partial cover). The method then takes care of
* assigning damage to the cover. Buildings are damaged directly, while
* dropships call the <code>handleEntityDamage</code> method.
*
* @param entityTarget
* The target Entity
* @param vPhaseReport
* @param pcHit
* @param bldg
* @param hits
* @param nCluster
* @param bldgAbsorbs
*/
protected void handlePartialCoverHit(Entity entityTarget,
Vector<Report> vPhaseReport, HitData pcHit, Building bldg,
int hits, int nCluster, int bldgAbsorbs) {
// Report the hit and table description, if this isn't part of a salvo
Report r;
if (!bSalvo) {
r = new Report(3405);
r.subject = subjectId;
r.add(toHit.getTableDesc());
r.add(entityTarget.getLocationAbbr(pcHit));
vPhaseReport.addElement(r);
if (weapon.isRapidfire()) {
r.newlines = 0;
r = new Report(3225);
r.subject = subjectId;
r.add(numRapidFireHits * 3);
vPhaseReport.add(r);
}
} else {
// Keep spacing consistent
Report.addNewline(vPhaseReport);
}
r = new Report(3460);
r.subject = subjectId;
r.add(entityTarget.getShortName());
r.add(entityTarget.getLocationAbbr(pcHit));
r.indent(2);
vPhaseReport.addElement(r);
int damagableCoverType = LosEffects.DAMAGABLE_COVER_NONE;
Building coverBuilding = null;
Entity coverDropship = null;
Coords coverLoc = null;
// Determine if there is primary and secondary cover,
// and then determine which one gets hit
if ((toHit.getCover() == LosEffects.COVER_75RIGHT || toHit.getCover() == LosEffects.COVER_75LEFT)
||
// 75% cover has a primary and secondary
(toHit.getCover() == LosEffects.COVER_HORIZONTAL && toHit
.getDamagableCoverTypeSecondary() != LosEffects.DAMAGABLE_COVER_NONE)) {
// Horiztonal cover provided by two 25%'s, so primary and secondary
int hitLoc = pcHit.getLocation();
// Primary stores the left side, from the perspective of the
// attacker
if (hitLoc == Mech.LOC_RLEG || hitLoc == Mech.LOC_RT
|| hitLoc == Mech.LOC_RARM) {
// Left side is primary
damagableCoverType = toHit.getDamagableCoverTypePrimary();
coverBuilding = toHit.getCoverBuildingPrimary();
coverDropship = toHit.getCoverDropshipPrimary();
coverLoc = toHit.getCoverLocPrimary();
} else {
// If not left side, then right side, which is secondary
damagableCoverType = toHit.getDamagableCoverTypeSecondary();
coverBuilding = toHit.getCoverBuildingSecondary();
coverDropship = toHit.getCoverDropshipSecondary();
coverLoc = toHit.getCoverLocSecondary();
}
} else { // Only primary cover exists
damagableCoverType = toHit.getDamagableCoverTypePrimary();
coverBuilding = toHit.getCoverBuildingPrimary();
coverDropship = toHit.getCoverDropshipPrimary();
coverLoc = toHit.getCoverLocPrimary();
}
// Check if we need to damage the cover that absorbed the hit.
if (damagableCoverType == LosEffects.DAMAGABLE_COVER_DROPSHIP) {
// We need to adjust some state and then restore it later
// This allows us to make a call to handleEntityDamage
ToHitData savedToHit = toHit;
int savedAimingMode = waa.getAimingMode();
waa.setAimingMode(IAimingModes.AIM_MODE_NONE);
int savedAimedLocation = waa.getAimedLocation();
waa.setAimedLocation(Entity.LOC_NONE);
boolean savedSalvo = bSalvo;
bSalvo = true;
// Create new toHitData
toHit = new ToHitData(0, "", ToHitData.HIT_NORMAL,
Compute.targetSideTable(ae, coverDropship));
// Report cover was damaged
int sizeBefore = vPhaseReport.size();
r = new Report(3465);
r.subject = subjectId;
r.add(coverDropship.getShortName());
vPhaseReport.add(r);
// Damage the dropship
handleEntityDamage(coverDropship, vPhaseReport, bldg, hits,
nCluster, bldgAbsorbs);
// Remove a blank line in the report list
if (vPhaseReport.elementAt(sizeBefore).newlines > 0)
vPhaseReport.elementAt(sizeBefore).newlines--;
// Indent reports related to the damage absorption
while (sizeBefore < vPhaseReport.size()) {
vPhaseReport.elementAt(sizeBefore).indent(3);
sizeBefore++;
}
// Restore state
toHit = savedToHit;
waa.setAimingMode(savedAimingMode);
waa.setAimedLocation(savedAimedLocation);
bSalvo = savedSalvo;
// Damage a building that blocked a shot
} else if (damagableCoverType == LosEffects.DAMAGABLE_COVER_BUILDING) {
// Normal damage
int nDamage = nDamPerHit * Math.min(nCluster, hits);
Vector<Report> buildingReport = server.damageBuilding(
coverBuilding, nDamage, " blocks the shot and takes ",
coverLoc);
for (Report report : buildingReport) {
report.subject = subjectId;
report.indent();
}
vPhaseReport.addAll(buildingReport);
// Damage any infantry in the building.
Vector<Report> infantryReport = server.damageInfantryIn(
coverBuilding, nDamage, coverLoc,
wtype.getInfantryDamageClass());
for (Report report : infantryReport) {
report.indent(2);
}
vPhaseReport.addAll(infantryReport);
}
missed = true;
}
/**
* Handle damage against an entity, called once per hit by default.
*
* @param entityTarget
* @param vPhaseReport
* @param bldg
* @param hits
* @param nCluster
* @param bldgAbsorbs
*/
protected void handleEntityDamage(Entity entityTarget,
Vector<Report> vPhaseReport, Building bldg, int hits, int nCluster,
int bldgAbsorbs) {
int nDamage;
missed = false;
hit = entityTarget.rollHitLocation(toHit.getHitTable(),
toHit.getSideTable(), waa.getAimedLocation(),
waa.getAimingMode(), toHit.getCover());
hit.setGeneralDamageType(generalDamageType);
hit.setCapital(wtype.isCapital());
hit.setBoxCars(roll == 12);
hit.setCapMisCritMod(getCapMisMod());
hit.setFirstHit(firstHit);
hit.setAttackerId(getAttackerId());
if (weapon.isWeaponGroup()) {
hit.setSingleAV(attackValue);
}
boolean isIndirect = wtype.hasModes()
&& weapon.curMode().equals("Indirect");
if (!isIndirect
&& entityTarget.removePartialCoverHits(hit.getLocation(), toHit
.getCover(), Compute.targetSideTable(ae, entityTarget,
weapon.getCalledShot().getCall()))) {
// Weapon strikes Partial Cover.
handlePartialCoverHit(entityTarget, vPhaseReport, hit, bldg, hits,
nCluster, bldgAbsorbs);
return;
}
if (!bSalvo) {
// Each hit in the salvo get's its own hit location.
Report r = new Report(3405);
r.subject = subjectId;
r.add(toHit.getTableDesc());
r.add(entityTarget.getLocationAbbr(hit));
vPhaseReport.addElement(r);
if (weapon.isRapidfire()) {
r.newlines = 0;
r = new Report(3225);
r.subject = subjectId;
r.add(numRapidFireHits * 3);
vPhaseReport.add(r);
}
} else {
Report.addNewline(vPhaseReport);
}
// for non-salvo shots, report that the aimed shot was successfull
// before applying damage
if (hit.hitAimedLocation() && !bSalvo) {
Report r = new Report(3410);
r.subject = subjectId;
vPhaseReport.lastElement().newlines = 0;
vPhaseReport.addElement(r);
}
// Resolve damage normally.
nDamage = nDamPerHit * Math.min(nCluster, hits);
if (bDirect) {
hit.makeDirectBlow(toHit.getMoS() / 3);
}
// A building may be damaged, even if the squad is not.
if (bldgAbsorbs > 0) {
int toBldg = Math.min(bldgAbsorbs, nDamage);
nDamage -= toBldg;
Report.addNewline(vPhaseReport);
Vector<Report> buildingReport = server.damageBuilding(bldg, toBldg,
entityTarget.getPosition());
for (Report report : buildingReport) {
report.subject = subjectId;
}
vPhaseReport.addAll(buildingReport);
}
nDamage = checkTerrain(nDamage, entityTarget, vPhaseReport);
nDamage = checkLI(nDamage, entityTarget, vPhaseReport);
// some buildings scale remaining damage that is not absorbed
// TODO: this isn't quite right for castles brian
if (null != bldg) {
nDamage = (int) Math.floor(bldg.getDamageToScale() * nDamage);
}
// A building may absorb the entire shot.
if (nDamage == 0) {
Report r = new Report(3415);
r.subject = subjectId;
r.indent(2);
r.addDesc(entityTarget);
vPhaseReport.addElement(r);
missed = true;
} else {
if (bGlancing) {
hit.makeGlancingBlow();
}
vPhaseReport
.addAll(server.damageEntity(entityTarget, hit, nDamage,
false, ae.getSwarmTargetId() == entityTarget
.getId() ? DamageType.IGNORE_PASSENGER
: damageType, false, false, throughFront,
underWater, nukeS2S));
// for salvo shots, report that the aimed location was hit after
// applying damage, because the location is first reported when
// dealing the damage
if (hit.hitAimedLocation() && bSalvo) {
Report r = new Report(3410);
r.subject = subjectId;
vPhaseReport.lastElement().newlines = 0;
vPhaseReport.addElement(r);
}
}
// If a BA squad is shooting at infantry, damage may be random and need
// to be rerolled for the next hit (if any) from the same attack.
if ((ae instanceof BattleArmor) && (target instanceof Infantry)) {
nDamPerHit = calcDamagePerHit();
}
}
protected void handleIgnitionDamage(Vector<Report> vPhaseReport,
Building bldg, int hits) {
if (!bSalvo) {
// hits!
Report r = new Report(2270);
r.subject = subjectId;
r.newlines = 0;
vPhaseReport.addElement(r);
}
TargetRoll tn = new TargetRoll(wtype.getFireTN(), wtype.getName());
if (tn.getValue() != TargetRoll.IMPOSSIBLE) {
Report.addNewline(vPhaseReport);
server.tryIgniteHex(target.getPosition(), subjectId, false, false,
tn, true, -1, vPhaseReport);
}
}
protected void handleClearDamage(Vector<Report> vPhaseReport,
Building bldg, int nDamage) {
handleClearDamage(vPhaseReport, bldg, nDamage, true);
}
protected void handleClearDamage(Vector<Report> vPhaseReport,
Building bldg, int nDamage, boolean hitReport) {
if (!bSalvo && hitReport) {
// hits!
Report r = new Report(2270);
r.subject = subjectId;
vPhaseReport.addElement(r);
}
// report that damage was "applied" to terrain
Report r = new Report(3385);
r.indent(2);
r.subject = subjectId;
r.add(nDamage);
vPhaseReport.addElement(r);
// Any clear attempt can result in accidental ignition, even
// weapons that can't normally start fires. that's weird.
// Buildings can't be accidentally ignited.
// TODO: change this for TacOps - now you roll another 2d6 first and on
// a 5 or less
// you do a normal ignition as though for intentional fires
if ((bldg != null)
&& server.tryIgniteHex(target.getPosition(), subjectId, false,
false,
new TargetRoll(wtype.getFireTN(), wtype.getName()), 5,
vPhaseReport)) {
return;
}
Vector<Report> clearReports = server.tryClearHex(target.getPosition(),
nDamage, subjectId);
if (clearReports.size() > 0) {
vPhaseReport.lastElement().newlines = 0;
}
vPhaseReport.addAll(clearReports);
return;
}
protected void handleBuildingDamage(Vector<Report> vPhaseReport,
Building bldg, int nDamage, Coords coords) {
if (!bSalvo) {
// hits!
Report r = new Report(3390);
r.subject = subjectId;
vPhaseReport.addElement(r);
}
Report.addNewline(vPhaseReport);
Vector<Report> buildingReport = server.damageBuilding(bldg, nDamage,
coords);
for (Report report : buildingReport) {
report.subject = subjectId;
}
vPhaseReport.addAll(buildingReport);
// Damage any infantry in the hex.
vPhaseReport.addAll(server.damageInfantryIn(bldg, nDamage, coords,
wtype.getInfantryDamageClass()));
}
protected boolean allShotsHit() {
if ((((target.getTargetType() == Targetable.TYPE_BLDG_IGNITE) || (target
.getTargetType() == Targetable.TYPE_BUILDING)) && (nRange <= 1))
|| (target.getTargetType() == Targetable.TYPE_HEX_CLEAR)) {
return true;
}
if (game.getOptions().booleanOption("aero_sanity")
&& target.getTargetType() == Targetable.TYPE_ENTITY
&& ((Entity) target).isCapitalScale()
&& !((Entity) target).isCapitalFighter()) {
return true;
}
return false;
}
protected void reportMiss(Vector<Report> vPhaseReport) {
reportMiss(vPhaseReport, false);
}
protected void reportMiss(Vector<Report> vPhaseReport, boolean singleNewline) {
// Report the miss.
Report r = new Report(3220);
r.subject = subjectId;
if (singleNewline) {
r.newlines = 1;
} else {
r.newlines = 2;
}
vPhaseReport.addElement(r);
}
protected WeaponHandler() {
// deserialization only
}
// Among other things, basically a refactored Server#preTreatWeaponAttack
public WeaponHandler(ToHitData t, WeaponAttackAction w, IGame g, Server s) {
damageType = DamageType.NONE;
toHit = t;
waa = w;
game = g;
ae = game.getEntity(waa.getEntityId());
weapon = ae.getEquipment(waa.getWeaponId());
wtype = (WeaponType) weapon.getType();
typeName = wtype.getInternalName();
target = game.getTarget(waa.getTargetType(), waa.getTargetId());
server = s;
subjectId = getAttackerId();
nRange = Compute.effectiveDistance(game, ae, target);
if (target instanceof Mech) {
throughFront = Compute.isThroughFrontHex(game, ae.getPosition(),
(Entity) target);
} else {
throughFront = true;
}
// is this an underwater attack on a surface naval vessel?
underWater = toHit.getHitTable() == ToHitData.HIT_UNDERWATER;
if (null != ae.getCrew()) {
roll = ae.getCrew().rollGunnerySkill();
} else {
roll = Compute.d6(2);
}
nweapons = getNumberWeapons();
nweaponsHit = 1;
// use ammo when creating this, so it works when shooting the last shot
// a unit has and we fire multiple weapons of the same type
// TODO: need to adjust this for cases where not all the ammo is
// available
for (int i = 0; i < nweapons; i++) {
useAmmo();
}
if (target instanceof Entity) {
((Entity) target).addAttackedByThisTurn(w.getEntityId());
}
}
protected void useAmmo() {
if (wtype.hasFlag(WeaponType.F_ONESHOT)) {
weapon.setFired(true);
}
setDone();
}
protected void setDone() {
weapon.setUsedThisRound(true);
}
protected void addHeat() {
if (!(toHit.getValue() == TargetRoll.IMPOSSIBLE)) {
if (ae.usesWeaponBays() && !game.getOptions().booleanOption("heat_by_bay")) {
int loc = weapon.getLocation();
boolean rearMount = weapon.isRearMounted();
if (!ae.hasArcFired(loc, rearMount)) {
ae.heatBuildup += ae.getHeatInArc(loc, rearMount);
ae.setArcFired(loc, rearMount);
}
} else {
if (!isStrafing() || isStrafingFirstShot()) {
ae.heatBuildup += (weapon.getCurrentHeat());
}
}
}
}
/**
* Does this attack use the cluster hit table? necessary to determine how
* Aero damage should be applied
*/
protected boolean usesClusterTable() {
return false;
}
/**
* special resolution, like minefields and arty
*
* @param vPhaseReport - a <code>Vector</code> containing the phase report
* @param entityTarget - the <code>Entity</code> targeted, or <code>null</code>, if
* no Entity targeted
* @return true when done with processing, false when not
*/
protected boolean specialResolution(Vector<Report> vPhaseReport,
Entity entityTarget) {
return false;
}
public boolean announcedEntityFiring() {
return announcedEntityFiring;
}
public void setAnnouncedEntityFiring(boolean announcedEntityFiring) {
this.announcedEntityFiring = announcedEntityFiring;
}
public WeaponAttackAction getWaa() {
return waa;
}
public int checkTerrain(int nDamage, Entity entityTarget,
Vector<Report> vPhaseReport) {
boolean isAboveWoods = ((entityTarget != null) && ((entityTarget
.relHeight() >= 2) || (entityTarget.isAirborne())));
if (game.getOptions().booleanOption("tacops_woods_cover")
&& !isAboveWoods
&& (game.getBoard().getHex(entityTarget.getPosition())
.containsTerrain(Terrains.WOODS) || game.getBoard()
.getHex(entityTarget.getPosition())
.containsTerrain(Terrains.JUNGLE))
&& !(entityTarget.getSwarmAttackerId() == ae.getId())) {
ITerrain woodHex = game.getBoard()
.getHex(entityTarget.getPosition())
.getTerrain(Terrains.WOODS);
ITerrain jungleHex = game.getBoard()
.getHex(entityTarget.getPosition())
.getTerrain(Terrains.JUNGLE);
int treeAbsorbs = 0;
String hexType = "";
if (woodHex != null) {
treeAbsorbs = woodHex.getLevel() * 2;
hexType = "wooded";
} else if (jungleHex != null) {
treeAbsorbs = jungleHex.getLevel() * 2;
hexType = "jungle";
}
// Do not absorb more damage than the weapon can do.
treeAbsorbs = Math.min(nDamage, treeAbsorbs);
nDamage = Math.max(0, nDamage - treeAbsorbs);
server.tryClearHex(entityTarget.getPosition(), treeAbsorbs,
ae.getId());
Report.addNewline(vPhaseReport);
Report terrainReport = new Report(6427);
terrainReport.subject = entityTarget.getId();
terrainReport.add(hexType);
terrainReport.add(treeAbsorbs);
terrainReport.indent(2);
terrainReport.newlines = 0;
vPhaseReport.add(terrainReport);
}
return nDamage;
}
/**
* Check for Laser Inhibiting smoke clouds
*/
public int checkLI(int nDamage, Entity entityTarget,
Vector<Report> vPhaseReport) {
weapon = ae.getEquipment(waa.getWeaponId());
wtype = (WeaponType) weapon.getType();
ArrayList<Coords> coords = Coords.intervening(ae.getPosition(),
entityTarget.getPosition());
int refrac = 0;
double travel = 0;
double range = ae.getPosition().distance(target.getPosition());
double atkLev = ae.relHeight();
double tarLev = entityTarget.relHeight();
double levDif = Math.abs(atkLev - tarLev);
String hexType = "LASER inhibiting smoke";
// loop through all intervening coords.
// If you could move this to compute.java, then remove - import
// java.util.ArrayList;
for (Coords curr : coords) {
// skip hexes not actually on the board
if (!game.getBoard().contains(curr)) {
continue;
}
ITerrain smokeHex = game.getBoard().getHex(curr)
.getTerrain(Terrains.SMOKE);
if (game.getBoard().getHex(curr).containsTerrain(Terrains.SMOKE)
&& wtype.hasFlag(WeaponType.F_ENERGY)
&& ((smokeHex.getLevel() == SmokeCloud.SMOKE_LI_LIGHT) || (smokeHex
.getLevel() == SmokeCloud.SMOKE_LI_HEAVY))) {
int levit = ((game.getBoard().getHex(curr).getLevel()) + 2);
// does the hex contain LASER inhibiting smoke?
if ((tarLev > atkLev)
&& (levit >= ((travel * (levDif / range)) + atkLev))) {
refrac++;
} else if ((atkLev > tarLev)
&& (levit >= (((range - travel) * (levDif / range)) + tarLev))) {
refrac++;
} else if ((atkLev == tarLev) && (levit >= 0)) {
refrac++;
}
travel++;
}
}
if (refrac != 0) {
// Damage reduced by 2 for each interviening smoke.
refrac = (refrac * 2);
// Do not absorb more damage than the weapon can do. (Are both of
// these really necessary?)
refrac = Math.min(nDamage, refrac);
nDamage = Math.max(0, (nDamage - refrac));
Report.addNewline(vPhaseReport);
Report fogReport = new Report(6427);
fogReport.subject = entityTarget.getId();
fogReport.add(hexType);
fogReport.add(refrac);
fogReport.indent(2);
fogReport.newlines = 0;
vPhaseReport.add(fogReport);
}
return nDamage;
}
protected boolean canDoDirectBlowDamage() {
return true;
}
/**
* Insert any additionaly attacks that should occur before this attack
*/
protected void insertAttacks(IGame.Phase phase, Vector<Report> vPhaseReport) {
return;
}
/**
* @return the number of weapons of this type firing (for squadron weapon
* groups)
*/
protected int getNumberWeapons() {
return weapon.getNWeapons();
}
/**
* Restores the equipment from the name
*/
public void restore() {
if (typeName == null) {
typeName = wtype.getName();
} else {
wtype = (WeaponType) EquipmentType.get(typeName);
}
if (wtype == null) {
System.err
.println("WeaponHandler.restore: could not restore equipment type \""
+ typeName + "\"");
}
}
protected int getClusterModifiers(boolean clusterRangePenalty) {
int nMissilesModifier = nSalvoBonus;
int[] ranges = wtype.getRanges(weapon);
if (clusterRangePenalty && game.getOptions().booleanOption("tacops_clusterhitpen")) {
if (nRange <= 1) {
nMissilesModifier += 1;
} else if (nRange <= ranges[RangeType.RANGE_MEDIUM]) {
nMissilesModifier += 0;
} else {
nMissilesModifier -= 1;
}
}
if (game.getOptions().booleanOption(OptionsConstants.AC_TAC_OPS_RANGE)
&& (nRange > ranges[RangeType.RANGE_LONG])) {
nMissilesModifier -= 2;
}
if (game.getOptions().booleanOption(OptionsConstants.AC_TAC_OPS_LOS_RANGE)
&& (nRange > ranges[RangeType.RANGE_EXTREME])) {
nMissilesModifier -= 3;
}
if (bGlancing) {
nMissilesModifier -= 4;
}
if (bDirect) {
nMissilesModifier += (toHit.getMoS() / 3) * 2;
}
if (game.getPlanetaryConditions().hasEMI()) {
nMissilesModifier -= 2;
}
if (null != ae.getCrew()) {
if (ae.getCrew().getOptions().booleanOption("sandblaster")
&& ae.getCrew().getOptions().stringOption("weapon_specialist")
.equals(wtype.getName())) {
if (nRange > ranges[RangeType.RANGE_MEDIUM]) {
nMissilesModifier += 2;
} else if (nRange > ranges[RangeType.RANGE_SHORT]) {
nMissilesModifier += 3;
} else {
nMissilesModifier += 4;
}
} else if (ae.getCrew().getOptions().booleanOption("cluster_master")) {
nMissilesModifier += 2;
} else if (ae.getCrew().getOptions().booleanOption("cluster_hitter")) {
nMissilesModifier += 1;
}
}
return nMissilesModifier;
}
public boolean isStrafing() {
return isStrafing;
}
public void setStrafing(boolean isStrafing) {
this.isStrafing = isStrafing;
}
public boolean isStrafingFirstShot() {
return isStrafingFirstShot;
}
public void setStrafingFirstShot(boolean isStrafingFirstShot) {
this.isStrafingFirstShot = isStrafingFirstShot;
}
}
| gpl-3.0 |
foobnix/LirbiReader | app/src/main/java/org/ebookdroid/core/HScrollController.java | 3996 | package org.ebookdroid.core;
import android.graphics.Rect;
import android.graphics.RectF;
import com.foobnix.model.AppBook;
import org.ebookdroid.common.settings.SettingsManager;
import org.ebookdroid.common.settings.types.DocumentViewMode;
import org.ebookdroid.common.settings.types.PageAlign;
import org.ebookdroid.ui.viewer.IActivityController;
public class HScrollController extends AbstractScrollController {
public HScrollController(final IActivityController base) {
super(base, DocumentViewMode.HORIZONTAL_SCROLL);
}
/**
* {@inheritDoc}
*
* @see org.ebookdroid.ui.viewer.IViewController#calculateCurrentPage(org.ebookdroid.core.ViewState)
*/
@Override
public final int calculateCurrentPage(final ViewState viewState, final int firstVisible, final int lastVisible) {
int result = 0;
long bestDistance = Long.MAX_VALUE;
final int viewX = Math.round(viewState.viewRect.centerX());
final Iterable<Page> pages = firstVisible != -1 ? viewState.model.getPages(firstVisible, lastVisible + 1)
: viewState.model.getPages(0);
for (final Page page : pages) {
final RectF bounds = viewState.getBounds(page);
final int pageX = Math.round(bounds.centerX());
final long dist = Math.abs(pageX - viewX);
if (dist < bestDistance) {
bestDistance = dist;
result = page.index.viewIndex;
}
}
return result;
}
@Override
public int getBottomScrollLimit() {
return 0;
}
/**
* {@inheritDoc}
*
* @see org.ebookdroid.ui.viewer.IViewController#getScrollLimits()
*/
@Override
public final Rect getScrollLimits() {
final int width = getWidth();
final int height = getHeight();
final Page lpo = model.getLastPageObject();
final float zoom = getBase().getZoomModel().getZoom();
final int right = lpo != null ? (int) lpo.getBounds(zoom).right - width : 0;
final int bottom = (int) (height * zoom) - height;
return new Rect(0, -height/2, right, bottom+height/2);
}
/**
* {@inheritDoc}
*
* @see org.ebookdroid.ui.viewer.IViewController#invalidatePageSizes(org.ebookdroid.ui.viewer.IViewController.InvalidateSizeReason,
* org.ebookdroid.core.Page)
*/
@Override
public synchronized final void invalidatePageSizes(final InvalidateSizeReason reason, final Page changedPage) {
if (!isInitialized) {
return;
}
if (reason == InvalidateSizeReason.PAGE_ALIGN) {
return;
}
final int height = getHeight();
final int width = getWidth();
final AppBook bookSettings = SettingsManager.getBookSettings();
final PageAlign pageAlign = DocumentViewMode.getPageAlign(bookSettings);
if (changedPage == null) {
float widthAccum = 0;
for (final Page page : model.getPages()) {
final RectF pageBounds = calcPageBounds(pageAlign, page.getAspectRatio(), width, height);
pageBounds.offset(widthAccum, 0);
page.setBounds(pageBounds);
widthAccum += pageBounds.width() + 3;
}
} else {
float widthAccum = changedPage.getBounds(1.0f).left;
for (final Page page : model.getPages(changedPage.index.viewIndex)) {
final RectF pageBounds = calcPageBounds(pageAlign, page.getAspectRatio(), width, height);
pageBounds.offset(widthAccum, 0);
page.setBounds(pageBounds);
widthAccum += pageBounds.width() + 3;
}
}
}
@Override
public RectF calcPageBounds(final PageAlign pageAlign, final float pageAspectRatio, final int width,
final int height) {
return new RectF(0, 0, height * pageAspectRatio, height);
}
}
| gpl-3.0 |
otting/NebenkostenAssistent | src/gui/WorkFrame.java | 4016 | package gui;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class WorkFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = -7783509968212805832L;
private final JFrame parent;
public static int width, height;
private static final File saveFile = new File("config" + File.separator + "windowResolutions");
/**
* used to save the resolution for specific panes
*/
private String name;
/**
*
* @param parent
* @param pane
* the content pane
* @param paneName
* required to save the panes resolution, should be unique
*/
public WorkFrame(JFrame parent, JComponent pane, String paneName) {
super();
setBounds(100, 100, WorkFrame.width, height);
setContentPane(pane);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
this.parent = parent;
name = paneName;
// must be called after the name is set!
Dimension dim = loadResolution();
if (dim != null)
setSize(dim);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
saveResolution(getSize());
WorkFrame.this.parent.setEnabled(true);
WorkFrame.this.parent.setVisible(true);
}
});
parent.setEnabled(false);
parent.setVisible(false);
setVisible(true);
}
public void saveResolution(Dimension d) {
if (name == null) {
ErrorHandle.popUp("Name for this Window is not set");
}
try {
boolean found = false;
StringBuilder text = new StringBuilder();
NumberFormat formatter = new DecimalFormat("#0.00");
if (saveFile.exists()) {
BufferedReader read = new BufferedReader(new FileReader(saveFile));
String line;
while ((line = read.readLine()) != null) {
if (line.contains(name)) {
found = true;
line = name + ":" + formatter.format(d.getHeight()) + ":" + formatter.format(d.getWidth());
System.out.println(line);
}
text.append(line + System.lineSeparator());
}
read.close();
} else {
if (!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
}
}
if (!saveFile.exists() || !found) {
text.append(name + ":" + formatter.format(d.getHeight()) + ":" + formatter.format(d.getWidth())
+ System.lineSeparator());
System.out.println(text.toString());
}
FileOutputStream fileOut = new FileOutputStream(saveFile);
fileOut.write(text.toString().getBytes());
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @return saved Dimension if available
*/
public Dimension loadResolution() {
if (name == null) {
ErrorHandle.popUp("Name for this Window is not set");
}
Dimension d = null;
NumberFormat format = NumberFormat.getNumberInstance(Locale.GERMAN);
format.setMaximumFractionDigits(2);
if (!saveFile.exists())
return d;
try {
BufferedReader read = new BufferedReader(new FileReader(saveFile));
String line;
while ((line = read.readLine()) != null) {
if (line.contains(name)) {
String[] str = line.split(":", 3);
d = new Dimension();
d.setSize(format.parse(str[2]).doubleValue(), format.parse(str[1]).doubleValue());
read.close();
return d;
}
}
read.close();
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return d;
}
}
| gpl-3.0 |
yhqmcq/infox | src/main/java/com/infox/sysmgr/entity/base/BaseField.java | 1767 | package com.infox.sysmgr.entity.base;
import java.io.Serializable;
public class BaseField implements Serializable {
private static final long serialVersionUID = 1L;
private int hashCode = Integer.MIN_VALUE;
// fields
private java.lang.String name;
private java.lang.String fieldType;
private java.lang.String fieldDefault;
private java.lang.String fieldProperty;
private java.lang.String comment;
private java.lang.String nullable;
private java.lang.String extra;
public int getHashCode() {
return hashCode;
}
public void setHashCode(int hashCode) {
this.hashCode = hashCode;
}
public java.lang.String getName() {
return name;
}
public void setName(java.lang.String name) {
this.name = name;
}
public java.lang.String getFieldType() {
return fieldType;
}
public void setFieldType(java.lang.String fieldType) {
this.fieldType = fieldType;
}
public java.lang.String getFieldDefault() {
return fieldDefault;
}
public void setFieldDefault(java.lang.String fieldDefault) {
this.fieldDefault = fieldDefault;
}
public java.lang.String getFieldProperty() {
return fieldProperty;
}
public void setFieldProperty(java.lang.String fieldProperty) {
this.fieldProperty = fieldProperty;
}
public java.lang.String getComment() {
return comment;
}
public void setComment(java.lang.String comment) {
this.comment = comment;
}
public java.lang.String getNullable() {
return nullable;
}
public void setNullable(java.lang.String nullable) {
this.nullable = nullable;
}
public java.lang.String getExtra() {
return extra;
}
public void setExtra(java.lang.String extra) {
this.extra = extra;
}
} | gpl-3.0 |
drugis/mtc | mtc-gui/src/main/java/org/drugis/mtc/presentation/results/NetworkVarianceTableModel.java | 3491 | /*
* This file is part of the GeMTC software for MTC model generation and
* analysis. GeMTC is distributed from http://drugis.org/gemtc.
* Copyright (C) 2009-2012 Gert van Valkenhoef.
*
* 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.drugis.mtc.presentation.results;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.table.AbstractTableModel;
import org.drugis.mtc.Parameter;
import org.drugis.mtc.presentation.InconsistencyWrapper;
import org.drugis.mtc.presentation.MTCModelWrapper;
import org.drugis.mtc.summary.QuantileSummary;
@SuppressWarnings("serial")
public class NetworkVarianceTableModel extends AbstractTableModel {
private static final int RANDOM_EFFECTS = 0;
private final MTCModelWrapper<?> d_mtc;
private final PropertyChangeListener d_listener;
public NetworkVarianceTableModel(final MTCModelWrapper<?> mtc) {
d_mtc = mtc;
d_listener = new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
fireTableDataChanged();
}
};
if (isInconsistency()) {
attachListener(((InconsistencyWrapper<?>) d_mtc).getInconsistencyVariance());
}
attachListener(mtc.getRandomEffectsStandardDeviation());
}
private void attachListener(final Parameter p) {
final QuantileSummary quantileSummary = d_mtc.getQuantileSummary(p);
if(quantileSummary != null) {
quantileSummary.addPropertyChangeListener(d_listener);
}
}
@Override
public Class<?> getColumnClass(final int columnIndex) {
if (columnIndex == 0) {
return String.class;
} else {
return QuantileSummary.class;
}
}
@Override
public String getColumnName(final int column) {
return column == 0 ? "Parameter" : "Median (95% CrI)";
}
@Override
public int getRowCount() {
return isInconsistency() ? 2 : 1;
}
private boolean isInconsistency() {
return (d_mtc instanceof InconsistencyWrapper);
}
@Override
public Object getValueAt(final int row, final int col) {
if (col == 0) {
return getRowDescription(row);
} else {
return getEstimate(row);
}
}
private QuantileSummary getEstimate(final int row) {
return row == RANDOM_EFFECTS ? getRandomEffectsSummary() : getInconsistencySummary();
}
private QuantileSummary getInconsistencySummary() {
if (isInconsistency()) {
final Parameter p = ((InconsistencyWrapper<?>) d_mtc).getInconsistencyVariance();
return d_mtc.getQuantileSummary(p);
}
return null;
}
private QuantileSummary getRandomEffectsSummary() {
final Parameter p = d_mtc.getRandomEffectsStandardDeviation();
return d_mtc.getQuantileSummary(p);
}
private String getRowDescription(final int row) {
if (row == RANDOM_EFFECTS) {
return "Random Effects Standard Deviation";
} else {
return "Inconsistency Standard Deviation";
}
}
@Override
public int getColumnCount() {
return 2;
}
}
| gpl-3.0 |
adam-roughton/CrowdHammer | src/main/java/com/adamroughton/crowdhammer/master/state/MasterStateType.java | 932 | /*
* Copyright 2012 Adam Roughton.
*
* This file is part of CrowdHammer.
*
* CrowdHammer 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.
*
* CrowdHammer 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 CrowdHammer. If not, see <http://www.gnu.org/licenses/>.
*/
package com.adamroughton.crowdhammer.master.state;
public enum MasterStateType {
START,
SCENARIO_RUN_START,
SET_UP_PHASE,
TEST_PHASE_PREP,
TEST_PHASE_EXEC,
SHUT_DOWN,
ERROR
}
| gpl-3.0 |
Better-Aether/Better-Aether | src/main/java/com/gildedgames/aether/client/renderer/tile_entities/TileEntityPresentRenderer.java | 2920 | package com.gildedgames.aether.client.renderer.tile_entities;
import com.gildedgames.aether.client.models.entities.tile.ModelPresent;
import com.gildedgames.aether.common.items.blocks.ItemBlockPresent;
import com.gildedgames.aether.common.tiles.TileEntityPresent;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.util.ResourceLocation;
import java.util.Random;
public class TileEntityPresentRenderer extends TileEntitySpecialRenderer<TileEntityPresent>
{
public static final ResourceLocation[] boxTextures = new ResourceLocation[16];
public static final ResourceLocation[] bowTextures = new ResourceLocation[16];
public static final String[] colors = new String[] { "black", "red", "green", "brown", "blue", "purple", "cyan", "silver", "gray", "pink", "lime", "yellow", "light_blue", "magenta", "orange", "white" };
static
{
for (int i = 0; i < 16; i++)
{
boxTextures[i] = new ResourceLocation("aether", "textures/tile_entities/present/present_box_" + colors[i] + ".png");
bowTextures[i] = new ResourceLocation("aether", "textures/tile_entities/present/present_ribbon_" + colors[i] + ".png");
}
}
private final ModelPresent model = new ModelPresent();
private final Random random = new Random();
@Override
public void renderTileEntityAt(TileEntityPresent present, double x, double y, double z, float partialTicks, int destroyStage)
{
GlStateManager.pushMatrix();
ItemBlockPresent.PresentData data = null;
if (present != null)
{
data = present.getPresentData();
}
byte boxColor = data == null ? 15 : data.getDye().getBoxColor();
byte bowColor = data == null ? 1 : data.getDye().getBowColor();
// Sanitize dye colors to prevent rogue presents!
boxColor = (boxColor >= 15 ? 15 : (boxColor < 0 ? 0 : boxColor));
bowColor = (bowColor >= 15 ? 15 : (bowColor < 0 ? 0 : bowColor));
GlStateManager.enableRescaleNormal();
GlStateManager.translate((float) x + 0.5f, (float) y, (float) z + 0.5f);
if (present != null)
{
this.random.setSeed((long) (present.getPos().getX() + present.getPos().getY() + present.getPos().getZ()) * 5L);
float offset = this.random.nextFloat() * 0.1f;
float scale = 1f + ((this.random.nextFloat() * 0.1f) - 0.1f);
float rotate = this.random.nextFloat() * 180f;
GlStateManager.translate(offset, 0, offset);
GlStateManager.rotate(180f, 1f, 0f, 1f);
GlStateManager.rotate(rotate, 0f, 1f, 0f);
GlStateManager.scale(scale, scale, scale);
}
else
{
GlStateManager.rotate(180f, 1.0f, 0f, 0.4f);
GlStateManager.scale(1.5F, 1.5F, 1.5F);
}
this.bindTexture(boxTextures[boxColor]);
this.model.renderBox(0.0625F);
this.bindTexture(bowTextures[bowColor]);
this.model.renderBow(0.0625F);
this.model.renderBox(0.0625F);
GlStateManager.disableRescaleNormal();
GlStateManager.popMatrix();
}
}
| gpl-3.0 |
censlin/cilib-old | library/src/main/java/net/sourceforge/cilib/problem/boundaryconstraint/PreviousPosition.java | 1495 | /** __ __
* _____ _/ /_/ /_ Computational Intelligence Library (CIlib)
* / ___/ / / / __ \ (c) CIRG @ UP
* / /__/ / / / /_/ / http://cilib.net
* \___/_/_/_/_.___/
*/
package net.sourceforge.cilib.problem.boundaryconstraint;
import net.sourceforge.cilib.entity.Entity;
import net.sourceforge.cilib.entity.Property;
import net.sourceforge.cilib.type.types.Numeric;
import net.sourceforge.cilib.type.types.Types;
import net.sourceforge.cilib.type.types.container.Vector;
/**
* Once the entity has over shot the search space boundaries, re-initialise
* the Entity once again to be within the search space of the problem at a
* random position.
*
* @see Types#isInsideBounds(net.sourceforge.cilib.type.types.Type)
*/
public class PreviousPosition implements BoundaryConstraint {
private double bound = 1.0e290;
/**
* {@inheritDoc}
*/
@Override
public PreviousPosition getClone() {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public void enforce(Entity entity) {
double total = 0;
for (Numeric curElement : (Vector) entity.getPosition()) {
total += Math.abs(curElement.doubleValue() * 2);
}
if (total > bound || Double.isNaN(total) || total == Double.POSITIVE_INFINITY) {
entity.setPosition(entity.get(Property.PREVIOUS_SOLUTION));
}
}
public void setBound(double bound) {
this.bound = bound;
}
}
| gpl-3.0 |
Monstercraft/MonsterIRC | src/main/java/org/monstercraft/irc/ircplugin/event/events/PluginDisconnectEvent.java | 758 | package org.monstercraft.irc.ircplugin.event.events;
import java.util.EventListener;
import org.monstercraft.irc.ircplugin.event.EventMulticaster;
import org.monstercraft.irc.ircplugin.event.listeners.IRCListener;
import org.monstercraft.irc.plugin.wrappers.IRCServer;
public class PluginDisconnectEvent extends IRCEvent {
private static final long serialVersionUID = 8708860642802706979L;
private final IRCServer server;
public PluginDisconnectEvent(final IRCServer server) {
this.server = server;
}
@Override
public void dispatch(final EventListener el) {
((IRCListener) el).onDisconnect(server);
}
@Override
public long getMask() {
return EventMulticaster.IRC_DISCONNECT_EVENT;
}
}
| gpl-3.0 |
cooked/NDT | sc.ndt.editor.fast.fst/src-gen/sc/ndt/editor/fast/fastfst/nTEC_Sres.java | 2191 | /**
*/
package sc.ndt.editor.fast.fastfst;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>nTEC Sres</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link sc.ndt.editor.fast.fastfst.nTEC_Sres#getValue <em>Value</em>}</li>
* <li>{@link sc.ndt.editor.fast.fastfst.nTEC_Sres#getName <em>Name</em>}</li>
* </ul>
* </p>
*
* @see sc.ndt.editor.fast.fastfst.FastfstPackage#getnTEC_Sres()
* @model
* @generated
*/
public interface nTEC_Sres extends EObject
{
/**
* Returns the value of the '<em><b>Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Value</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Value</em>' attribute.
* @see #setValue(float)
* @see sc.ndt.editor.fast.fastfst.FastfstPackage#getnTEC_Sres_Value()
* @model
* @generated
*/
float getValue();
/**
* Sets the value of the '{@link sc.ndt.editor.fast.fastfst.nTEC_Sres#getValue <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Value</em>' attribute.
* @see #getValue()
* @generated
*/
void setValue(float 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 sc.ndt.editor.fast.fastfst.FastfstPackage#getnTEC_Sres_Name()
* @model
* @generated
*/
String getName();
/**
* Sets the value of the '{@link sc.ndt.editor.fast.fastfst.nTEC_Sres#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);
} // nTEC_Sres
| gpl-3.0 |
241180/Oryx | oryx-client/client-core/src/main/java/com/oryx/core/converter/XMLGregorianCalendarStringConverter.java | 2519 | package com.oryx.core.converter;
import com.vaadin.data.util.converter.Converter;
import org.apache.log4j.Logger;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
/**
* Created by 241180 on 14/03/2017.
*/
public class XMLGregorianCalendarStringConverter implements Converter<String, XMLGregorianCalendar> {
final static Logger logger = Logger.getLogger(XMLGregorianCalendarStringConverter.class);
@Override
public XMLGregorianCalendar convertToModel(String date, Class<? extends XMLGregorianCalendar> aClass, Locale locale) throws ConversionException {
if (date == null)
return null;
try {
return stringToXMLGregorianCalendar(date);
} catch (DatatypeConfigurationException e) {
//e.printStackTrace();
logger.warn("DatatypeConfigurationException date to XMLGregorianCalendar");
} catch (ParseException e) {
logger.warn("ParseException date to XMLGregorianCalendar");
//e.printStackTrace();
}
return null;
}
@Override
public String convertToPresentation(XMLGregorianCalendar xmlGregorianCalendar, Class<? extends String> aClass, Locale locale) throws ConversionException {
if (xmlGregorianCalendar != null)
return xmlGregorianCalendar.toGregorianCalendar().getTime().toString();
else
return null;
}
public Class<XMLGregorianCalendar> getModelType() {
return XMLGregorianCalendar.class;
}
public Class<String> getPresentationType() {
return String.class;
}
public XMLGregorianCalendar stringToXMLGregorianCalendar(String s)
throws ParseException,
DatatypeConfigurationException {
XMLGregorianCalendar result = null;
Date date;
SimpleDateFormat simpleDateFormat;
GregorianCalendar gregorianCalendar;
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
date = simpleDateFormat.parse(s);
gregorianCalendar =
(GregorianCalendar) GregorianCalendar.getInstance();
gregorianCalendar.setTime(date);
result = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
return result;
}
}
| gpl-3.0 |
automenta/adams-core | src/main/java/adams/gui/goe/AbstractIntegralNumberEditor.java | 3227 | /*
* 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/>.
*/
/**
* AbstractIntegralNumberEditor.java
* Copyright (C) 2009 University of Waikato, Hamilton, New Zealand
*/
package adams.gui.goe;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JPopupMenu;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import adams.gui.core.MouseUtils;
/**
* An abstract ancestor for custom editors for integral numbers, like bytes,
* shorts, integers and longs.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision: 4943 $
*/
public abstract class AbstractIntegralNumberEditor
extends AbstractNumberEditor {
/**
* Creates the spinner model to use.
*
* @return the model
*/
protected SpinnerNumberModel createModel() {
SpinnerNumberModel result;
result = new SpinnerNumberModel();
updateBounds(result);
return result;
}
/**
* Updates the bounds of the spinner model.
*
* @param model the model to update
*/
protected abstract void updateBounds(SpinnerNumberModel model);
/**
* Updates the bounds.
*/
protected void updateBounds() {
SpinnerNumberModel model;
if (m_CustomEditor != null) {
model = (SpinnerNumberModel) ((JSpinner) m_CustomEditor).getModel();
updateBounds(model);
}
}
/**
* Creates the custom editor to use.
*
* @return the custom editor
*/
protected JComponent createCustomEditor() {
JSpinner result;
result = new JSpinner(createModel());
result.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JSpinner spinner = (JSpinner) e.getSource();
if (!spinner.getValue().equals(getValue()))
setValue(spinner.getValue());
}
});
// workaround for mouselistener problem:
// http://bugs.sun.com/view_bug.do?bug_id=4760088
((JSpinner.DefaultEditor) result.getEditor()).getTextField().addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JPopupMenu popup = createPopup();
if (MouseUtils.isRightClick(e) && (popup != null))
popup.show(m_CustomEditor, e.getX(), e.getY());
else
super.mouseClicked(e);
}
});
return result;
}
/**
* Initializes the display of the value.
*/
protected void initForDisplay() {
resetChosenOption();
if (!((JSpinner) m_CustomEditor).getValue().equals(getValue()))
((JSpinner) m_CustomEditor).setValue(getValue());
}
}
| gpl-3.0 |
leafsoftinfo/pyramus | persistence/src/main/java/fi/pyramus/dao/users/PasswordResetRequestDAO.java | 2326 | package fi.pyramus.dao.users;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import fi.pyramus.dao.PyramusEntityDAO;
import fi.pyramus.domainmodel.base.Person;
import fi.pyramus.domainmodel.users.PasswordResetRequest;
import fi.pyramus.domainmodel.users.PasswordResetRequest_;
@Stateless
public class PasswordResetRequestDAO extends PyramusEntityDAO<PasswordResetRequest> {
public PasswordResetRequest create(Person person, String secret, Date date) {
EntityManager entityManager = getEntityManager();
PasswordResetRequest passwordResetRequest = new PasswordResetRequest();
passwordResetRequest.setPerson(person);
passwordResetRequest.setSecret(secret);
passwordResetRequest.setDate(date);
entityManager.persist(passwordResetRequest);
return passwordResetRequest;
}
public PasswordResetRequest findBySecret(String secret) {
EntityManager entityManager = getEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<PasswordResetRequest> criteria = criteriaBuilder.createQuery(PasswordResetRequest.class);
Root<PasswordResetRequest> root = criteria.from(PasswordResetRequest.class);
criteria.select(root);
criteria.where(
criteriaBuilder.equal(root.get(PasswordResetRequest_.secret), secret)
);
return getSingleResult(entityManager.createQuery(criteria));
}
public List<PasswordResetRequest> listByPerson(Person person) {
EntityManager entityManager = getEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<PasswordResetRequest> criteria = criteriaBuilder.createQuery(PasswordResetRequest.class);
Root<PasswordResetRequest> root = criteria.from(PasswordResetRequest.class);
criteria.select(root);
criteria.where(
criteriaBuilder.equal(root.get(PasswordResetRequest_.person), person)
);
return entityManager.createQuery(criteria).getResultList();
}
@Override
public void delete(PasswordResetRequest request) {
super.delete(request);
}
}
| gpl-3.0 |
shitongtong/libraryManage | stt-util/src/main/java/com/stt/util2/UUIDUtil.java | 603 | package com.stt.util2;
import java.util.UUID;
/**
* @Author shitongtong
* <p>
* Created by shitongtong on 2017/3/24.
*/
public class UUIDUtil {
/**
* 带"-"分割的
* @return
*/
public static String randomUUID(){
return UUID.randomUUID().toString();
}
/**
* 不带"-"分割的
* @return
*/
public static String randomUUID2(){
return noSplit(randomUUID());
}
/**
* 去"-"分割
* @param uuid
* @return
*/
public static String noSplit(String uuid){
return uuid.replaceAll("-","");
}
}
| gpl-3.0 |
Neutrinet/ISP-ng | src/main/java/be/neutrinet/ispng/security/SessionToken.java | 1487 | package be.neutrinet.ispng.security;
import be.neutrinet.ispng.vpn.Users;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import org.apache.log4j.Logger;
import java.sql.SQLException;
import java.util.UUID;
/**
* Created by wannes on 12/20/14.
*/
@DatabaseTable(tableName = "session_tokens")
public class SessionToken {
@DatabaseField(canBeNull = false)
private UUID user;
@DatabaseField(canBeNull = false)
private String address;
@DatabaseField(canBeNull = false)
private long creationTime;
@DatabaseField(id = true)
private UUID token;
private SessionToken() {
}
public SessionToken(UUID user, String address) {
this.user = user;
this.address = address;
this.creationTime = System.currentTimeMillis();
this.token = UUID.randomUUID();
try {
SessionTokens.dao.create(this);
} catch (SQLException ex) {
Logger.getLogger(getClass()).error("Failed to create session token", ex);
}
}
public UUID getToken() {
return token;
}
public UUID getUser() {
return user;
}
public String getAddress() {
return address;
}
public long getCreationTime() {
return creationTime;
}
public boolean valid() {
if (Users.isRelatedService(this.user)) return true;
return System.currentTimeMillis() - this.creationTime <= 3600 * 1000;
}
}
| gpl-3.0 |
rogerxu/design-patterns | src/main/java/demo/designpatterns/simplefactory/MobileFactory.java | 456 | package demo.designpatterns.simplefactory;
/**
* Created by Roger Xu on 2017/6/24.
*/
public class MobileFactory {
public Mobile getMobile(String title) throws Exception {
if (title.equalsIgnoreCase("nokia")) {
return new Nokia();
} else if (title.equalsIgnoreCase("motorola")) {
return new Motorola();
} else {
throw new Exception("no such " + title + " mobile found");
}
}
}
| gpl-3.0 |
qt-haiku/LibreOffice | qadevOOo/tests/java/ifc/style/_ParagraphPropertiesComplex.java | 1768 | /*
* 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 ifc.style;
import lib.MultiPropertyTest;
/**
* Testing <code>com.sun.star.style.ParagraphPropertiesComplex</code>
*
* Properties testing is automated by <code>lib.MultiPropertyTest</code>.
* @see com.sun.star.style.ParagraphPropertiesComplex
*/
public class _ParagraphPropertiesComplex extends MultiPropertyTest {
protected PropertyTester WritingModeTester = new PropertyTester() {
protected Object getNewValue(String propName, Object oldValue) {
if ((oldValue != null) && (oldValue.equals(new Short(com.sun.star.text.WritingMode2.LR_TB))))
return new Short(com.sun.star.text.WritingMode2.PAGE); else
return new Short(com.sun.star.text.WritingMode2.LR_TB);
}
} ;
public void _WritingMode() {
log.println("Testing with custom Property tester") ;
testProperty("WritingMode", WritingModeTester) ;
}
} // finish class _ParagraphPropertiesComplex
| gpl-3.0 |
OmicronProject/BakeoutController-Basic | src/main/java/kernel/modbus/package-info.java | 114 | /**
* Contains methods for working with device using the MODBUS protocol over
* RS232
*/
package kernel.modbus; | gpl-3.0 |
takisd123/executequery | src/org/executequery/gui/prefs/PropertiesToolBar.java | 13636 | /*
* PropertiesToolBar.java
*
* Copyright (C) 2002-2017 Takis Diakoumis
*
* 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 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.executequery.gui.prefs;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.util.Collections;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.executequery.Constants;
import org.executequery.GUIUtilities;
import org.underworldlabs.swing.actions.ActionUtilities;
import org.underworldlabs.swing.actions.ReflectiveAction;
import org.underworldlabs.swing.toolbar.ButtonComparator;
import org.underworldlabs.swing.toolbar.ToolBarButton;
import org.underworldlabs.swing.toolbar.ToolBarProperties;
import org.underworldlabs.swing.toolbar.ToolBarWrapper;
/**
*
* @author Takis Diakoumis
*/
public class PropertiesToolBar extends AbstractPropertiesBasePanel {
private Vector selections;
private JTable table;
private ToolBarButtonModel toolButtonModel;
private static IconCellRenderer iconRenderer;
private static NameCellRenderer nameRenderer;
private JButton moveUpButton;
private JButton moveDownButton;
private JButton addSeparatorButton;
private JButton removeSeparatorButton;
/** The tool bar name */
private String toolBarName;
/** The tool bar wrapper */
private ToolBarWrapper toolBar;
public PropertiesToolBar(String toolBarName) {
this.toolBarName = toolBarName;
try {
jbInit();
}
catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() {
ReflectiveAction action = new ReflectiveAction(this);
moveUpButton = ActionUtilities.createButton(
action,
GUIUtilities.loadIcon("Up16.png", true),
null,
"moveUp");
moveDownButton = ActionUtilities.createButton(
action,
GUIUtilities.loadIcon("Down16.png", true),
null,
"moveDown");
moveUpButton.setMargin(Constants.EMPTY_INSETS);
moveDownButton.setMargin(Constants.EMPTY_INSETS);
addSeparatorButton = ActionUtilities.createButton(
action,
"Add Separator",
"addSeparator");
addSeparatorButton.setToolTipText("Adds a separator above the selection");
removeSeparatorButton = ActionUtilities.createButton(
action,
"Remove Separator",
"removeSeparator");
removeSeparatorButton.setToolTipText("Removes the selected separator");
ToolBarWrapper _toolBar = ToolBarProperties.getToolBar(toolBarName);
toolBar = (ToolBarWrapper)_toolBar.clone();
selections = toolBar.getButtonsVector();
setInitialValues();
iconRenderer = new IconCellRenderer();
nameRenderer = new NameCellRenderer();
toolButtonModel = new ToolBarButtonModel();
table = new JTable(toolButtonModel);
setTableProperties();
JScrollPane scroller = new JScrollPane(table);
scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroller.getViewport().setBackground(table.getBackground());
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
gbc.gridx = 0;
gbc.weightx = 1.0;
gbc.insets.bottom = 5;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.NORTHWEST;
panel.add(new JLabel(toolBarName + " - Buttons"), gbc);
gbc.gridy++;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
panel.add(scroller, gbc);
gbc.gridy++;
gbc.weighty = 0;
gbc.insets.bottom = 10;
gbc.insets.right = 10;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(addSeparatorButton, gbc);
gbc.gridx++;
gbc.insets.right = 0;
panel.add(removeSeparatorButton, gbc);
JPanel movePanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.gridy = 0;
gbc2.insets.bottom = 10;
gbc2.anchor = GridBagConstraints.CENTER;
movePanel.add(moveUpButton, gbc2);
gbc2.gridy++;
gbc2.insets.bottom = 5;
gbc2.insets.top = 5;
movePanel.add(new JLabel("Move"), gbc2);
gbc2.gridy++;
gbc2.insets.bottom = 10;
movePanel.add(moveDownButton, gbc2);
gbc.gridx++;
gbc.gridy = 0;
gbc.weighty = 1.0;
gbc.weightx = 0;
gbc.insets.left = 5;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridheight = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.NONE;
panel.add(movePanel, gbc);
addContent(panel);
}
private void setTableProperties() {
table.setTableHeader(null);
table.setColumnSelectionAllowed(false);
table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setIntercellSpacing(new Dimension(0,0));
table.setShowGrid(false);
table.setRowHeight(28);
table.doLayout();
TableColumnModel tcm = table.getColumnModel();
tcm.getColumn(0).setPreferredWidth(30);
TableColumn col = tcm.getColumn(1);
col.setPreferredWidth(40);
col.setCellRenderer(iconRenderer);
col = tcm.getColumn(2);
col.setPreferredWidth(251);
col.setCellRenderer(nameRenderer);
}
private void setInitialValues() {
Collections.sort(selections, new ButtonComparator());
}
public void restoreDefaults() {
ToolBarWrapper _toolBar = ToolBarProperties.getDefaultToolBar(toolBarName);
toolBar = (ToolBarWrapper)_toolBar.clone();
selections = toolBar.getButtonsVector();
Collections.sort(selections, new ButtonComparator());
toolButtonModel.fireTableRowsUpdated(0, selections.size()-1);
}
public void save() {
int size = selections.size();
Vector buttons = new Vector(selections.size());
// update the buttons
for (int i = 0; i < size; i++) {
ToolBarButton tb = (ToolBarButton)selections.elementAt(i);
if (tb.isVisible())
tb.setOrder(i);
else
tb.setOrder(1000);
buttons.add(tb);
}
toolBar.setButtonsVector(buttons);
ToolBarProperties.resetToolBar(toolBarName, toolBar);
}
public void addSeparator(ActionEvent e) {
int selection = table.getSelectedRow();
if (selection == -1) {
return;
}
ToolBarButton tb = new ToolBarButton(ToolBarButton.SEPARATOR_ID);
tb.setOrder(selection);
tb.setVisible(true);
selections.insertElementAt(tb, selection);
toolButtonModel.fireTableRowsInserted(selection == 0 ? 0 : selection - 1,
selection == 0 ? 1 : selection);
}
public void removeSeparator(ActionEvent e) {
int selection = table.getSelectedRow();
if (selection == -1) {
return;
}
ToolBarButton remove = (ToolBarButton)selections.elementAt(selection);
if (!remove.isSeparator()) {
return;
}
selections.removeElementAt(selection);
toolButtonModel.fireTableRowsDeleted(selection, selection);
}
public void moveUp(ActionEvent e) {
int selection = table.getSelectedRow();
if (selection <= 0) {
return;
}
int newPostn = selection - 1;
ToolBarButton move = (ToolBarButton)selections.elementAt(selection);
selections.removeElementAt(selection);
selections.add(newPostn, move);
table.setRowSelectionInterval(newPostn, newPostn);
toolButtonModel.fireTableRowsUpdated(newPostn, selection);
}
public void moveDown(ActionEvent e) {
int selection = table.getSelectedRow();
if (selection == -1 || selection == selections.size() - 1) {
return;
}
int newPostn = selection + 1;
ToolBarButton move = (ToolBarButton)selections.elementAt(selection);
selections.removeElementAt(selection);
selections.add(newPostn, move);
table.setRowSelectionInterval(newPostn, newPostn);
toolButtonModel.fireTableRowsUpdated(selection, newPostn);
}
private class ToolBarButtonModel extends AbstractTableModel {
public ToolBarButtonModel() {}
public int getColumnCount() {
return 3;
}
public int getRowCount() {
return selections.size();
}
public Object getValueAt(int row, int col) {
ToolBarButton tbb = (ToolBarButton)selections.elementAt(row);
switch(col) {
case 0:
return new Boolean(tbb.isVisible());
case 1:
return tbb.getIcon();
case 2:
return tbb.getName();
default:
return null;
}
}
public void setValueAt(Object value, int row, int col) {
ToolBarButton tbb = (ToolBarButton)selections.elementAt(row);
if (col == 0)
tbb.setVisible(((Boolean)value).booleanValue());
fireTableRowsUpdated(row, row);
}
public boolean isCellEditable(int row, int col) {
if (col == 0)
return true;
else
return false;
}
public Class getColumnClass(int col) {
if (col == 0)
return Boolean.class;
else
return String.class;
}
public void addNewRow() {
}
} // CreateTableModel
public class NameCellRenderer extends JLabel
implements TableCellRenderer {
public NameCellRenderer() {
//setFont(panelFont);
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
setBackground(isSelected ? table.getSelectionBackground() :
table.getBackground());
setForeground(isSelected ? table.getSelectionForeground() :
table.getForeground());
setText(value.toString());
setBorder(null);
return this;
}
} // class NameCellRenderer
public class IconCellRenderer extends JLabel
implements TableCellRenderer {
public IconCellRenderer() {
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
setBackground(isSelected ? table.getSelectionBackground() :
table.getBackground());
setForeground(isSelected ? table.getSelectionForeground() :
table.getForeground());
setHorizontalAlignment(JLabel.CENTER);
setIcon((ImageIcon)value);
return this;
}
} // class IconCellRenderer
}
| gpl-3.0 |
compwiz1548/ElementalTemples | src/main/java/com/compwiz1548/elementaltemples/item/ItemForestRelic.java | 235 | package com.compwiz1548.elementaltemples.item;
public class ItemForestRelic extends ItemET
{
public ItemForestRelic()
{
super();
this.setUnlocalizedName("forestRelic");
this.setMaxStackSize(1);
}
}
| gpl-3.0 |
zqad/zmask | src/org/zkt/zmask/masks/VerticalGlass.java | 2138 | /*
* VerticalGlass.java
* Copyright (C) 2010-2011 Jonas Eriksson
*
* 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.zkt.zmask.masks;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import org.zkt.zmask.Image;
import org.zkt.zmask.GeneralProperties;
import org.zkt.zmask.utils.PropertyDescription;
import org.zkt.zmask.utils.PropertyException;
import org.zkt.zmask.utils.PropertyHandler;
/**
* The vertical glass mask
*
* @author zqad
*/
public class VerticalGlass implements Mask {
public String getDescription() {
return "Vertical Glass";
}
public boolean needClone() {
return false;
}
public boolean needWhole() {
return false;
}
public boolean runBare() {
return false;
}
public BufferedImage runMask(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
BufferedImage bi = new BufferedImage(width, height,
image.getType());
Graphics2D g = (Graphics2D)bi.getGraphics();
g.scale(-1.0, 1.0);
int bs = GeneralProperties.getInstance().getBlockSize().width;
for (int i = 0; i <= width - bs; i += bs)
g.drawImage(image.getSubimage(i, 0, bs, height), -1 * i - bs, 0, null);
int remainder = width % bs;
if (remainder != 0)
g.drawImage(image.getSubimage(width - remainder, 0, remainder, height),
width - remainder, 0, null);
return bi;
}
public void runMask(Image image) {
throw new UnsupportedOperationException("Not supported.");
}
public PropertyDescription[] getProperties() {
return null;
}
}
| gpl-3.0 |
priiduneemre/bitplexus | src/main/java/com/neemre/bitplexus/backend/model/AddressType.java | 4237 | package com.neemre.bitplexus.backend.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedStoredProcedureQueries;
import javax.persistence.NamedStoredProcedureQuery;
import javax.persistence.ParameterMode;
import javax.persistence.SequenceGenerator;
import javax.persistence.StoredProcedureParameter;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;
import com.google.common.base.Function;
import com.google.common.collect.Ordering;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = false)
@Entity
@Table(name = "address_type", schema = "public")
@SequenceGenerator(name = "seq_address_type_id", sequenceName = "seq_address_type_address_type_id",
allocationSize = 1)
@NamedStoredProcedureQueries(value = {
@NamedStoredProcedureQuery(name = "findIdByAddressAndChainCode",
procedureName = "f_get_address_type_id", parameters = {
@StoredProcedureParameter(mode = ParameterMode.IN, name = "in_address", type = String.class),
@StoredProcedureParameter(mode = ParameterMode.IN, name = "in_chain_code", type = String.class)})
})
public class AddressType extends BaseEntity {
public static final Ordering<AddressType> LEADING_SYMBOL_ORDERING = Ordering.natural().nullsLast()
.onResultOf(new LeadingSymbolExtractor());
public static final Ordering<AddressType> NAME_ORDERING = Ordering.natural().nullsLast()
.onResultOf(new NameExtractor());
public static final Ordering<AddressType> NATURAL_ORDERING = NAME_ORDERING
.compound(LEADING_SYMBOL_ORDERING);
private static final long serialVersionUID = 1L;
@NotNull
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_address_type_id")
@Column(name = "address_type_id", insertable = false, updatable = false)
private Short addressTypeId;
@NotNull
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "chain_id", updatable = false)
private Chain chain;
@NotNull
@Size(max = 30)
@Column(name = "code")
private String code;
@NotNull
@Size(max = 60)
@Column(name = "name")
private String name;
@NotNull
@Size(min = 1, max = 1)
@Pattern(regexp = "^[1-9a-km-zA-HJ-NP-Z]*$")
@Column(name = "leading_symbol", updatable = false)
private String leadingSymbol;
@Past
@Generated(GenerationTime.INSERT)
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at", insertable = false, updatable = false)
private Date createdAt;
@NotNull
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "created_by", updatable = false)
private Employee createdBy;
@Past
@Generated(GenerationTime.ALWAYS)
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at", insertable = false, updatable = false)
private Date updatedAt;
@ManyToOne(fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "updated_by", insertable = false)
private Employee updatedBy;
public void setChain(Chain chain) {
if (this.chain != chain) {
if (this.chain != null) {
this.chain.removeAddressType(this);
}
this.chain = chain;
if (chain != null) {
chain.addAddressType(this);
}
}
}
private static class LeadingSymbolExtractor implements Function<AddressType, String> {
@Override
public String apply(AddressType addressType) {
return addressType.getLeadingSymbol();
}
}
private static class NameExtractor implements Function<AddressType, String> {
@Override
public String apply(AddressType addressType) {
return addressType.getName();
}
}
} | gpl-3.0 |
ggonzales/ksl | src/com/dotmarketing/portlets/dashboard/model/DashboardSummaryPeriod.java | 1302 | package com.dotmarketing.portlets.dashboard.model;
import java.io.Serializable;
import java.util.Date;
public class DashboardSummaryPeriod implements Serializable {
private static final long serialVersionUID = 1L;
private long id;
private Date fullDate;
private int day;
private String dayName;
private int week;
private int month;
private String monthName;
private String year;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getFullDate() {
return fullDate;
}
public void setFullDate(Date fullDate) {
this.fullDate = fullDate;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public String getDayName() {
return dayName;
}
public void setDayName(String dayName) {
this.dayName = dayName;
}
public int getWeek() {
return week;
}
public void setWeek(int week) {
this.week = week;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public String getMonthName() {
return monthName;
}
public void setMonthName(String monthName) {
this.monthName = monthName;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
| gpl-3.0 |
ltf/lab | jlab/namerank/src/main/java/ltf/namerank/dao/fs/DictItemDaoImpl.java | 1864 | package ltf.namerank.dao.fs;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import ltf.namerank.dao.DictItemDao;
import ltf.namerank.entity.DictItem;
import ltf.namerank.entity.DictItem_Bm8;
import ltf.namerank.utils.PathUtils;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static ltf.namerank.utils.FileUtils.file2Str;
import static ltf.namerank.utils.FileUtils.str2File;
/**
* @author ltf
* @since 6/11/16, 5:17 PM
*/
@Component
public class DictItemDaoImpl implements DictItemDao {
@Override
public void saveDictItem(DictItem dictItem) {
File f = new File(PathUtils.getJsonHome() + "/dict", dictItem.getZi());
Map<String, DictItem> items = new HashMap<>();
if (f.exists()) {
try {
items = JSON.parseObject(file2Str(f), items.getClass());
} catch (IOException e) {
e.printStackTrace();
}
}
items.put(dictItem.getItemType(), dictItem);
try {
str2File(JSON.toJSONString(items, true), f);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public DictItem loadItemsByZi(String zi) {
File f = new File(PathUtils.getJsonHome() + "/dict", zi);
if (!f.exists()) return null;
List<DictItem> list = new ArrayList<>(2);
Map<String, DictItem_Bm8> items = new HashMap<>();
try {
items = JSON.parseObject(file2Str(f), new TypeReference<Map<String, DictItem_Bm8>>() {
});
return items.get("DictItem_Bm8");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| gpl-3.0 |
DMXControl/DMXControl-for-Android | DMXControl/src/de/dmxcontrol/model/ModelManager.java | 3722 | /*
* ModelManager.java
*
* DMXControl for Android
*
* Copyright (c) 2012 DMXControl-For-Android. All rights reserved.
*
* This software 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, june 2007 of the License, or (at your option) any later version.
*
* 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 (gpl.txt) along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* For further information, please contact info [(at)] dmxcontrol.de
*
*
*/
package de.dmxcontrol.model;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
import de.dmxcontrol.device.EntitySelection;
import de.dmxcontrol.model.BaseModel.OnModelListener;
public class ModelManager {
private final static String TAG = "modelmanager";
public enum Type {
Color,
Gobo,
Position,
Dimmer,
Strobe,
Shutter,
Zoom,
Focus,
Iris,
Frost,
Effect
}
private Map<Type, BaseModel> mModels = new HashMap<Type, BaseModel>();
private static Map<Type, Class<? extends BaseModel>> mTypeLookup = new HashMap<Type, Class<? extends BaseModel>>();
private Map<OnModelListener, Boolean> mDefaultModelListeners = new HashMap<OnModelListener, Boolean>();
private EntitySelection mEntitySelection;
public ModelManager(EntitySelection es) {
addDefaultModelListener(es);
mEntitySelection = es;
}
public EntitySelection getEntitySelection() {
return mEntitySelection;
}
public void addDefaultModelListener(OnModelListener listener) {
mDefaultModelListeners.put(listener, true);
}
@SuppressWarnings("unchecked")
public <T extends BaseModel> T getModel(Type type) {
if(mModels.containsKey(type)) {
return (T) mModels.get(type);
}
else {
T model;
model = create(type);
mModels.put(type, (BaseModel) model);
return model;
}
}
@SuppressWarnings("unchecked")
private <T extends BaseModel> T create(Type type) {
Class<? extends BaseModel> clazz = mTypeLookup.get(type);
T model;
try {
model = (T) clazz.getDeclaredConstructors()[0].newInstance(this);
}
catch(Exception e) {
Log.e(TAG, "error creation of model with class " + clazz.getName());
Log.e(TAG, "exception: ", e);
return null;
}
model.addDefaultListener(mDefaultModelListeners);
return model;
}
static {
mTypeLookup.put(Type.Color, ColorModel.class);
mTypeLookup.put(Type.Gobo, GoboModel.class);
mTypeLookup.put(Type.Position, PositionModel.class);
mTypeLookup.put(Type.Dimmer, DimmerModel.class);
mTypeLookup.put(Type.Strobe, StrobeModel.class);
mTypeLookup.put(Type.Shutter, ShutterModel.class);
mTypeLookup.put(Type.Zoom, ZoomModel.class);
mTypeLookup.put(Type.Focus, FocusModel.class);
mTypeLookup.put(Type.Iris, IrisModel.class);
mTypeLookup.put(Type.Frost, FrostModel.class);
mTypeLookup.put(Type.Effect, EffectModel.class);
}
} | gpl-3.0 |
MrMid/gio-seminare | rozvrhovac/src/cz/devaty/projects/gio/Main.java | 2895 | package cz.devaty.projects.gio;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class Main {
/**
* předmět a -> 3., 7.O
* předmět b -> 4., 8.O
* předmět c -> 3., 7.O, 4., 8.O
*/
private static String FILE = "a.csv";
private static char[] groups = {'A', 'B',}; //'C', 'D', 'E'};
private static ArrayList<Student> students;
private static ArrayList<Seminar> seminars;
public static void main(String[] args) {
try {
loadData();
seminars = seminars.stream().distinct().collect(Collectors.toCollection(ArrayList::new));
computeGroups();
} catch (FileNotFoundException e) {
System.out.println("Error loading data");
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
private static void computeGroups() throws CloneNotSupportedException {
//variace s opakováním
for (int i = 0; i < 12; i++) {
seminars.remove(0);
}
ArrayList<ArrayList<Seminar>> variations = new ArrayList<>();
brute(variations, 0);
}
private static void brute(ArrayList<ArrayList<Seminar>> variations, int count) throws CloneNotSupportedException {
if (count < seminars.size()) {
for (int i = 0; i < groups.length; i++) {
seminars.get(count).setGroup(groups[i]);
brute(variations, count + 1);
}
} else {
//defensive copy
ArrayList<Seminar> sem = new ArrayList<>();
for (int i = 0; i < seminars.size(); i++) {
sem.add(seminars.get(i).clone());
}
variations.add(sem);
}
}
private static double countConflicts(int lastIndex) {
double result = 0;
for (int i = 0; i < lastIndex; i++) {
result += Student.conflictsPerStudent(students.get(i));
}
return result;
}
private static void loadData() throws FileNotFoundException {
seminars = new ArrayList<>();
students = new ArrayList<>();
BufferedReader in = new BufferedReader(new FileReader(FILE));
while (true) {
try {
String s = in.readLine();
if (s == null) return;
String[] line = s.split(";");
ArrayList<Seminar> sem = new ArrayList<>();
for (int i = 2; i < line.length; i++) {
sem.add(new Seminar(line[i]));
seminars.add(new Seminar(line[i]));
}
students.add(new Student(line[1], line[2], sem));
} catch (IOException e) {
return;
}
}
}
}
| gpl-3.0 |
idega/platform2 | src/is/idega/idegaweb/campus/business/ContractRenewalServiceHomeImpl.java | 430 | package is.idega.idegaweb.campus.business;
import javax.ejb.CreateException;
import com.idega.business.IBOHomeImpl;
public class ContractRenewalServiceHomeImpl extends IBOHomeImpl implements
ContractRenewalServiceHome {
public Class getBeanInterfaceClass() {
return ContractRenewalService.class;
}
public ContractRenewalService create() throws CreateException {
return (ContractRenewalService) super.createIBO();
}
} | gpl-3.0 |
ReunionDev/reunion | jreunion/src/main/java/org/reunionemu/jreunion/model/quests/restrictions/RaceRestriction.java | 294 | package org.reunionemu.jreunion.model.quests.restrictions;
import org.reunionemu.jreunion.model.quests.Restriction;
/**
* @author Aidamina
* @license http://reunion.googlecode.com/svn/trunk/license.txt
*/
public interface RaceRestriction extends Restriction {
public Integer getId();
}
| gpl-3.0 |
otavanopisto/pyramus | persistence/src/main/java/fi/otavanopisto/pyramus/domainmodel/clientapplications/ClientApplicationAccessToken.java | 2460 | package fi.otavanopisto.pyramus.domainmodel.clientapplications;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.TableGenerator;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
public class ClientApplicationAccessToken {
public Long getId() {
return id;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public Long getExpires() {
return expires;
}
public void setExpires(Long expires) {
this.expires = expires;
}
public ClientApplication getClientApplication() {
return clientApplication;
}
public void setClientApplication(ClientApplication clientApplication) {
this.clientApplication = clientApplication;
}
public ClientApplicationAuthorizationCode getClientApplicationAuthorizationCode() {
return clientApplicationAuthorizationCode;
}
public void setClientApplicationAuthorizationCode(ClientApplicationAuthorizationCode clientApplicationAuthorizationCode) {
this.clientApplicationAuthorizationCode = clientApplicationAuthorizationCode;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "ClientApplicationAccessToken")
@TableGenerator(name = "ClientApplicationAccessToken", allocationSize = 1, table = "hibernate_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_next_hi_value")
private Long id;
@NotNull
@NotEmpty
@Column(nullable = false, unique=true)
private String accessToken;
@NotEmpty
@Column(nullable = false)
private String refreshToken;
@NotNull
@Column(nullable = false)
private Long expires;
@NotNull
@ManyToOne
@JoinColumn(name = "app_id", nullable = false)
private ClientApplication clientApplication;
@NotNull
@OneToOne
@JoinColumn(name = "clientApplicationAuthorizationCode", unique = true, nullable = false)
private ClientApplicationAuthorizationCode clientApplicationAuthorizationCode;
}
| gpl-3.0 |
amasiero/algoritmos_estrutura_dados | aula_04/beamer/src/sequencial.java | 193 |
vetor[10] = {31, 16, 45, 87, 37, 99, 21, 43, 10, 48}
valorProcurado = 87
indice = -1
for (i = 0; i < vetor.length - 1; i++) {
if (vetor[i] == valorProcurado) {
indice = i
}
}
| gpl-3.0 |
fluoxa/Iris | src/main/java/de/baleipzig/iris/ui/playground/RonnyView.java | 681 | package de.baleipzig.iris.ui.playground;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.spring.annotation.UIScope;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
import javax.annotation.PostConstruct;
@UIScope
@SpringView(name = RonnyView.VIEW_NAME)
public class RonnyView extends VerticalLayout implements View {
public static final String VIEW_NAME = "ronny";
@PostConstruct
void init() {
this.addComponent(new Label("Ronnys Spielwiese"));
}
@Override
public void enter(ViewChangeListener.ViewChangeEvent event) {
}
}
| gpl-3.0 |
ckaestne/CIDE | CIDE_Language_XML_concrete/src/tmp/generated_xhtml/Content_var_Choice110.java | 783 | package tmp.generated_xhtml;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public class Content_var_Choice110 extends Content_var_Choice1 {
public Content_var_Choice110(Element_i element_i, Token firstToken, Token lastToken) {
super(new Property[] {
new PropertyOne<Element_i>("element_i", element_i)
}, firstToken, lastToken);
}
public Content_var_Choice110(Property[] properties, IToken firstToken, IToken lastToken) {
super(properties,firstToken,lastToken);
}
public ASTNode deepCopy() {
return new Content_var_Choice110(cloneProperties(),firstToken,lastToken);
}
public Element_i getElement_i() {
return ((PropertyOne<Element_i>)getProperty("element_i")).getValue();
}
}
| gpl-3.0 |
raiben/made | madetools/core/src/main/java/com/velonuboso/made/core/abm/api/IBehaviourTreeBlackboard.java | 878 | /*
* Copyright (C) 2015 Rubén Héctor García (raiben@gmail.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.velonuboso.made.core.abm.api;
/**
*
* @author Rubén Héctor García (raiben@gmail.com)
*/
public interface IBehaviourTreeBlackboard {
}
| gpl-3.0 |
nict-isp/ETL-flow-editor | backend/DynamicFlink/csv1POJO1446411691328.java | 499 | package DynamicFlink;
public class csv1POJO1446411691328{
String latitude;
public void setLatitude(String latitude) { this.latitude = latitude; }
public String getLatitude() { return this.latitude; }
String longitude;
public void setLongitude(String longitude) { this.longitude = longitude; }
public String getLongitude() { return this.longitude; }
String city_name;
public void setCity_name(String city_name) { this.city_name = city_name; }
public String getCity_name() { return this.city_name; }
} | gpl-3.0 |
jschang/jSchangLib | investing/src/main/java/com/jonschang/investing/valuesource/TrueRangeValueSource.java | 2142 | /*
###############################
# Copyright (C) 2012 Jon Schang
#
# This file is part of jSchangLib, released under the LGPLv3
#
# jSchangLib 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.
#
# jSchangLib 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 jSchangLib. If not, see <http://www.gnu.org/licenses/>.
###############################
*/
package com.jonschang.investing.valuesource;
import com.jonschang.investing.model.*;
/**
* determine the Average True Range of the stock period
* @author schang
*/
@SuppressWarnings(value={"unchecked"})
public class TrueRangeValueSource<Q extends Quote<I>,I extends Quotable>
extends AbstractQuoteValueSource<Q,I> {
/**
* the average true range of a stock requires only the last two quotes
*/
public int getPeriods() {
return 2;
}
/**
* get the average true range of the current quote
*/
public double getValue() throws TooFewQuotesException
{
if( this.quotes.size()<2 )
throw new TooFewQuotesException("there were too few quotes: "+this.quotes.size()+" available, 2 quotes needed.");
Quote today = this.quotes.get( this.quotes.size()-1 );
Quote yesterday = this.quotes.get( this.quotes.size()-2 );
double diffCurHighCurLow = today.getPriceHigh() - today.getPriceLow();
double diffCurHighPrevClose = today.getPriceHigh() - yesterday.getPriceClose();
double diffCurLowPrevClose = today.getPriceLow() - yesterday.getPriceClose();
double atr = 0;
atr = diffCurHighCurLow > atr ? diffCurHighCurLow : atr;
atr = diffCurHighPrevClose > atr ? diffCurHighPrevClose : atr;
atr = diffCurLowPrevClose > atr ? diffCurLowPrevClose : atr;
return atr;
}
}
| gpl-3.0 |
iTitus/MyMod | src/main/java/io/github/ititus/mymod/util/ICyclable.java | 221 | package io.github.ititus.mymod.util;
public interface ICyclable<T> {
T next(int i);
T prev(int i);
default T next() {
return next(1);
}
default T prev() {
return prev(1);
}
}
| gpl-3.0 |
Thomas-Gr/exaBilan | src/main/java/com/exabilan/interfaces/ResultAssociator.java | 529 | package com.exabilan.interfaces;
import java.util.List;
import com.exabilan.types.exalang.Answer;
import com.exabilan.types.exalang.ExaLang;
import com.exabilan.types.exalang.Question;
public interface ResultAssociator {
/**
* Finds the question corresponding to a question number for a given version of Exalang
*/
Question getQuestion(ExaLang exalang, int questionNumber);
/**
* Parses the answers written in Exalang specific storage files
*/
List<Answer> parseAnswer(String result);
}
| gpl-3.0 |
gama-platform/gama | ummisco.gama.ui.shared/src/ummisco/gama/ui/commands/OpenGamaWebsiteHandler.java | 1076 | /*********************************************************************************************
*
* 'OpenGamaWebsiteHandler.java, in plugin ummisco.gama.ui.shared, is part of the source code of the
* GAMA modeling and simulation platform.
* (v. 1.8.1)
*
* (c) 2007-2020 UMI 209 UMMISCO IRD/UPMC & Partners
*
* Visit https://github.com/gama-platform/gama for license information and developers contact.
*
*
**********************************************************************************************/
package ummisco.gama.ui.commands;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import msi.gama.runtime.GAMA;
public class OpenGamaWebsiteHandler extends AbstractHandler {
/**
* Method execute()
*
* @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
*/
@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
GAMA.getGui().openWelcomePage(false);
return null;
}
}
| gpl-3.0 |
pajato/game-chat-android | app/src/main/java/com/pajato/android/gamechat/MainActivity.java | 8746 | package com.pajato.android.gamechat;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.identitytoolkit.GitkitClient;
import com.google.identitytoolkit.GitkitUser;
import com.google.identitytoolkit.IdToken;
import com.pajato.android.gamechat.chat.ChatManager;
import com.pajato.android.gamechat.chat.ChatManagerImpl;
import com.pajato.android.gamechat.game.GameManager;
import com.pajato.android.gamechat.game.GameManagerImpl;
import com.pajato.android.gamechat.account.AccountManager;
import com.pajato.android.gamechat.account.AccountManagerImpl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
/**
* The main activity ... <tbd>
*/
public class MainActivity extends AppCompatActivity implements GitkitClient.SignInCallbacks {
// Public class constants
// Private class constants
/** The logcat tag constant. */
private static final String TAG = MainActivity.class.getSimpleName();
/** The preferences file name. */
private static final String PREFS = "GameChatPrefs";
// Private instance variables
/** The account manager handles all things related to accounts: signing in, switching accounts, setup, aliases, etc. */
private AccountManager mAccountManager;
/** The chat manager handles all things chat: accessing rooms, history, settings, etc. */
private ChatManager mChatManager;
/** The game manager handles all game related activities: mode, players, game selection, etc. */
private GameManager mGameManager;
/** The top level container. */
private DrawerLayout mDrawerLayout;
// Public instance methods
/**
* Override to implement a successful login by ensuring that the account is registered and up to date..
*/
@Override public void onSignIn(IdToken idToken, GitkitUser user) {
// Create a session for the given user by saving the token in the account.
Log.d(TAG, String.format("Processing a successful signin: idToken/user {%s/%s}.", idToken, user));
Toast.makeText(this, "You are successfully signed in to GameChat", Toast.LENGTH_LONG).show();
mAccountManager.handleSigninSuccess(user.getUserProfile(), idToken, getSharedPreferences(PREFS, 0));
}
/** Override to implement a failed signin by posting a message to the User. */
@Override public void onSignInFailed() {
// Post a message and head back to the main screen.
Log.d(TAG, "Processing a failed signin attempt.");
Toast.makeText(this, "Sign in failed", Toast.LENGTH_LONG).show();
mAccountManager.handleSigninFailed();
}
// Protected instance methods
/**
* Handle the signin activity result value by passing it back to the account manager.
*
* @param requestCode ...
* @param resultCode ...
* @param intent ...
*/
@Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Pass the event off to the account manager for processing.
Log.d(TAG, String.format("Processing a signin result: requestCode/resultCode/intent {%d/%d/%s}.", requestCode, resultCode, intent));
if (!mAccountManager.handleSigninResult(requestCode, resultCode, intent)) {
Log.d(TAG, "Signin result was not processed by the GIT.");
super.onActivityResult(requestCode, resultCode, intent);
}
}
/**
* Set up the app per the characteristics of the running device.
*
* @see android.app.Activity#onCreate(Bundle)
*/
@Override protected void onCreate(Bundle savedInstanceState) {
// Initialize the app state as necessary.
super.onCreate(savedInstanceState);
mAccountManager = new AccountManagerImpl(savedInstanceState, getSharedPreferences(PREFS, 0));
mGameManager = new GameManagerImpl(savedInstanceState);
mChatManager = new ChatManagerImpl(savedInstanceState);
// Start the app. Setup the top level views: toolbar, action bar and drawer layout.
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
actionBar.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Setup the navigation view and the main app pager.
//
// Todo: extend this to work with specific device classes based on size to provide optimal layouts.
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationHandler());
GameChatPagerAdapter adapter = new GameChatPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
// Determine if an account needs to be set up.
if (!mAccountManager.hasAccount()) {
// There is no account yet. Give the User a chance to sign in even though it is not strictly necessary, for
// example when playing games with the computer.
mAccountManager.signin(this);
}
}
/**
* Override to implement by passing a given intent to the account manager to see if it is consuming the intent.
*
* @param intent The given Intent object.
*/
@Override protected void onNewIntent(final Intent intent) {
// Give the account manager a chance to consume the intent.
if (!mAccountManager.handleIntent(intent)) {
Log.d(TAG, "Signin intent was not processed by the GIT.");
super.onNewIntent(intent);
}
}
// Private instance methods
// Private classes
/**
* Provide a class to handle the view pager setup.
*/
private class GameChatPagerAdapter extends FragmentStatePagerAdapter {
/**
* A list of panels ordered left to right.
*/
private List<Panel> panelList = new ArrayList<>();
/**
* Build an adapter to handle the panels.
*
* @param fm The fragment manager.
*/
public GameChatPagerAdapter(final FragmentManager fm) {
super(fm);
panelList.add(Panel.ROOMS);
panelList.add(Panel.CHAT);
panelList.add(Panel.MEMBERS);
panelList.add(Panel.GAME);
}
@Override
public Fragment getItem(int position) {
return panelList.get(position).getFragment();
}
@Override
public int getCount() {
return panelList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return MainActivity.this.getString(panelList.get(position).getTitleId());
}
}
/**
* Provide a handler for navigation panel selections.
*/
private class NavigationHandler implements NavigationView.OnNavigationItemSelectedListener {
@Override
public boolean onNavigationItemSelected(final MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
Toast.makeText(MainActivity.this, menuItem.getTitle(), Toast.LENGTH_LONG).show();
return true;
}
}
}
| gpl-3.0 |
superman-t/LetUsGo | src/com/superman/letusgo/base/BaseTaskPool.java | 3152 | package com.superman.letusgo.base;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.content.Context;
import android.widget.Toast;
import com.superman.letusgo.util.AppClient;
import com.superman.letusgo.util.HttpUtil;
public class BaseTaskPool {
// task thread pool
static private ExecutorService taskPool;
// for HttpUtil.getNetType
private Context context;
public BaseTaskPool (BaseUi ui) {
this.context = ui.getContext();
taskPool = Executors.newCachedThreadPool();
}
// http post task with params
public void addTask (int taskId, String taskUrl, HashMap<String, String> taskArgs, BaseTask baseTask, int delayTime) {
baseTask.setId(taskId);
try {
taskPool.execute(new TaskThread(context, taskUrl, taskArgs, baseTask, delayTime));
} catch (Exception e) {
taskPool.shutdown();
}
}
// http post task without params
public void addTask (int taskId, String taskUrl, BaseTask baseTask, int delayTime) {
baseTask.setId(taskId);
try {
Toast.makeText(context, "11111111111", Toast.LENGTH_SHORT);
taskPool.execute(new TaskThread(context, taskUrl, null, baseTask, delayTime));
} catch (Exception e) {
taskPool.shutdown();
}
}
// custom task
public void addTask (int taskId, BaseTask baseTask, int delayTime) {
baseTask.setId(taskId);
try {
taskPool.execute(new TaskThread(context, null, null, baseTask, delayTime));
} catch (Exception e) {
taskPool.shutdown();
}
}
// task thread logic
private class TaskThread implements Runnable {
private Context context;
private String taskUrl;
private HashMap<String, String> taskArgs;
private BaseTask baseTask;
private int delayTime = 0;
public TaskThread(Context context, String taskUrl, HashMap<String, String> taskArgs, BaseTask baseTask, int delayTime) {
this.context = context;
this.taskUrl = taskUrl;
this.taskArgs = taskArgs;
this.baseTask = baseTask;
this.delayTime = delayTime;
}
@Override
public void run() {
try {
baseTask.onStart();
String httpResult = null;
// set delay time
if (this.delayTime > 0) {
Thread.sleep(this.delayTime);
}
try {
// remote task
if (this.taskUrl != null) {
// init app client
AppClient client = new AppClient(this.taskUrl);
if (HttpUtil.WAP_INT == HttpUtil.getNetType(context)) {
client.useWap();
}
// http get
if (taskArgs == null) {
httpResult = client.get();
// http post
} else {
httpResult = client.post(this.taskArgs);
}
}
// remote task
if (httpResult != null) {
baseTask.onComplete(httpResult);
// local task
} else {
baseTask.onComplete();
}
} catch (Exception e) {
baseTask.onError(e.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
baseTask.onStop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} | gpl-3.0 |
simonpatrick/stepbystep-java | spring-demo/docs/learningMVC/common/src/main/java/com/common/tuple/MutableTriple.java | 2978 | package com.springdemo.learningMVC.common.src.main.java.com.common.tuple;
/**
* A mutable triple consisting of three {@code Object} elements.
* <p>
* Not #ThreadSafe#
*
* @param <L> the left element type
* @param <M> the middle element type
* @param <R> the right element type
* @version $Id: MutableTriple.java 290 2014-10-27 08:48:18Z $
*/
public class MutableTriple<L, M, R> extends Triple<L, M, R> {
/**
* Serialization version
*/
private static final long serialVersionUID = 1L;
/**
* Left object
*/
public L left;
/**
* Middle object
*/
public M middle;
/**
* Right object
*/
public R right;
/**
* Obtains an mutable triple of three objects inferring the generic types.
* <p>
* This factory allows the triple to be created using inference to
* obtain the generic types.
*
* @param <L> the left element type
* @param <M> the middle element type
* @param <R> the right element type
* @param left the left element, may be null
* @param middle the middle element, may be null
* @param right the right element, may be null
* @return a triple formed from the three parameters, not null
*/
public static <L, M, R> MutableTriple<L, M, R> of(
final L left, final M middle, final R right) {
return new MutableTriple<>(left, middle, right);
}
/**
* Create a new triple instance of three nulls.
*/
public MutableTriple() {
super();
}
/**
* Create a new triple instance.
*
* @param left the left value, may be null
* @param middle the middle value, may be null
* @param right the right value, may be null
*/
public MutableTriple(final L left, final M middle, final R right) {
super();
this.left = left;
this.middle = middle;
this.right = right;
}
//-----------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public L getLeft() {
return left;
}
/**
* Sets the left element of the triple.
*
* @param left the new value of the left element, may be null
*/
public void setLeft(final L left) {
this.left = left;
}
/**
* {@inheritDoc}
*/
@Override
public M getMiddle() {
return middle;
}
/**
* Sets the middle element of the triple.
*
* @param middle the new value of the middle element, may be null
*/
public void setMiddle(final M middle) {
this.middle = middle;
}
/**
* {@inheritDoc}
*/
@Override
public R getRight() {
return right;
}
/**
* Sets the right element of the triple.
*
* @param right the new value of the right element, may be null
*/
public void setRight(final R right) {
this.right = right;
}
} | gpl-3.0 |
SirBlobman/DragonFire | src/main/java/com/DragonFire/recipe/RecipePotionCookie.java | 2236 | package com.DragonFire.recipe;
import com.DragonFire.item.DFItems;
import net.minecraft.init.Items;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.potion.PotionUtils;
import net.minecraft.util.NonNullList;
import net.minecraft.world.World;
import net.minecraftforge.registries.IForgeRegistryEntry.Impl;
public class RecipePotionCookie extends Impl<IRecipe> implements IRecipe {
public RecipePotionCookie() {setRegistryName("potion_cookie");}
@Override
public boolean matches(InventoryCrafting inv, World worldIn) {
if (inv.getWidth() == 3 && inv.getHeight() == 3) {
for (int i = 0; i < inv.getWidth(); ++i) {
for (int j = 0; j < inv.getHeight(); ++j) {
ItemStack itemstack = inv.getStackInRowAndColumn(i, j);
if (itemstack.isEmpty()) return false;
Item item = itemstack.getItem();
if (i == 1 && j == 1) {
if (item != Items.LINGERING_POTION) return false;
} else if (item != Items.COOKIE) return false;
}
}
return true;
} else return false;
}
@Override
public ItemStack getCraftingResult(InventoryCrafting inv) {
ItemStack itemstack = inv.getStackInRowAndColumn(1, 1);
if (itemstack.getItem() != Items.LINGERING_POTION) return ItemStack.EMPTY;
else {
ItemStack itemstack1 = new ItemStack(DFItems.POTION_COOKIE, 8);
PotionUtils.addPotionToItemStack(itemstack1, PotionUtils.getPotionFromItem(itemstack));
PotionUtils.appendEffects(itemstack1, PotionUtils.getFullEffectsFromItem(itemstack));
return itemstack1;
}
}
public ItemStack getRecipeOutput() {return ItemStack.EMPTY;}
public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) {return NonNullList.<ItemStack>withSize(inv.getSizeInventory(), ItemStack.EMPTY);}
public boolean isHidden() {return true;}
public boolean canFit(int width, int height) {return width == 3 && height == 3;}
} | gpl-3.0 |
agicquel/dut | M3104/JAVA/tomcat-etud/work/Catalina/localhost/gpsapp/org/apache/jsp/index_jsp.java | 3368 | /*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/8.0.15
* Generated at: 2017-09-18 08:01:06 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final java.lang.String _jspx_method = request.getMethod();
if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");
return;
}
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
if (true) {
_jspx_page_context.forward("index");
return;
}
out.write('\n');
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| gpl-3.0 |
Aptoide/aptoide-client-v8 | app/src/vanilla/java/cm/aptoide/pt/util/MarketResourceFormatter.java | 346 | package cm.aptoide.pt.util;
import android.content.Context;
public class MarketResourceFormatter {
private String marketName;
public MarketResourceFormatter(String marketName) {
this.marketName = marketName;
}
public String formatString(Context context, int id, String... optParamaters) {
return context.getString(id);
}
}
| gpl-3.0 |
omerjerk/RemoteDroid | app/src/main/java/com/koushikdutta/async/http/server/AsyncHttpServer.java | 20350 | package com.koushikdutta.async.http.server;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Build;
import android.text.TextUtils;
import com.koushikdutta.async.AsyncSSLSocket;
import com.koushikdutta.async.AsyncSSLSocketWrapper;
import com.koushikdutta.async.AsyncServer;
import com.koushikdutta.async.AsyncServerSocket;
import com.koushikdutta.async.AsyncSocket;
import com.koushikdutta.async.ByteBufferList;
import com.koushikdutta.async.DataEmitter;
import com.koushikdutta.async.Util;
import com.koushikdutta.async.callback.CompletedCallback;
import com.koushikdutta.async.callback.ListenCallback;
import com.koushikdutta.async.http.AsyncHttpGet;
import com.koushikdutta.async.http.AsyncHttpHead;
import com.koushikdutta.async.http.AsyncHttpPost;
import com.koushikdutta.async.http.Headers;
import com.koushikdutta.async.http.HttpUtil;
import com.koushikdutta.async.http.Multimap;
import com.koushikdutta.async.http.Protocol;
import com.koushikdutta.async.http.WebSocket;
import com.koushikdutta.async.http.WebSocketImpl;
import com.koushikdutta.async.http.body.AsyncHttpRequestBody;
import com.koushikdutta.async.util.StreamUtility;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLContext;
@TargetApi(Build.VERSION_CODES.ECLAIR)
public class AsyncHttpServer {
ArrayList<AsyncServerSocket> mListeners = new ArrayList<AsyncServerSocket>();
public void stop() {
if (mListeners != null) {
for (AsyncServerSocket listener: mListeners) {
listener.stop();
}
}
}
protected boolean onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
return false;
}
protected void onRequest(HttpServerRequestCallback callback, AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
if (callback != null)
callback.onRequest(request, response);
}
protected AsyncHttpRequestBody onUnknownBody(Headers headers) {
return new UnknownRequestBody(headers.get("Content-Type"));
}
ListenCallback mListenCallback = new ListenCallback() {
@Override
public void onAccepted(final AsyncSocket socket) {
AsyncHttpServerRequestImpl req = new AsyncHttpServerRequestImpl() {
HttpServerRequestCallback match;
String fullPath;
String path;
boolean responseComplete;
boolean requestComplete;
AsyncHttpServerResponseImpl res;
boolean hasContinued;
@Override
protected AsyncHttpRequestBody onUnknownBody(Headers headers) {
return AsyncHttpServer.this.onUnknownBody(headers);
}
@Override
protected void onHeadersReceived() {
Headers headers = getHeaders();
// should the negotiation of 100 continue be here, or in the request impl?
// probably here, so AsyncResponse can negotiate a 100 continue.
if (!hasContinued && "100-continue".equals(headers.get("Expect"))) {
pause();
// System.out.println("continuing...");
Util.writeAll(mSocket, "HTTP/1.1 100 Continue\r\n\r\n".getBytes(), new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
resume();
if (ex != null) {
report(ex);
return;
}
hasContinued = true;
onHeadersReceived();
}
});
return;
}
// System.out.println(headers.toHeaderString());
String statusLine = getStatusLine();
String[] parts = statusLine.split(" ");
fullPath = parts[1];
path = fullPath.split("\\?")[0];
method = parts[0];
synchronized (mActions) {
ArrayList<Pair> pairs = mActions.get(method);
if (pairs != null) {
for (Pair p: pairs) {
Matcher m = p.regex.matcher(path);
if (m.matches()) {
mMatcher = m;
match = p.callback;
break;
}
}
}
}
res = new AsyncHttpServerResponseImpl(socket, this) {
@Override
protected void report(Exception e) {
super.report(e);
if (e != null) {
socket.setDataCallback(new NullDataCallback());
socket.setEndCallback(new NullCompletedCallback());
socket.close();
}
}
@Override
protected void onEnd() {
super.onEnd();
mSocket.setEndCallback(null);
responseComplete = true;
// reuse the socket for a subsequent request.
handleOnCompleted();
}
};
boolean handled = onRequest(this, res);
if (match == null && !handled) {
res.code(404);
res.end();
return;
}
if (!getBody().readFullyOnRequest()) {
onRequest(match, this, res);
}
else if (requestComplete) {
onRequest(match, this, res);
}
}
@Override
public void onCompleted(Exception e) {
// if the protocol was switched off http, ignore this request/response.
if (res.code() == 101)
return;
requestComplete = true;
super.onCompleted(e);
// no http pipelining, gc trashing if the socket dies
// while the request is being sent and is paused or something
mSocket.setDataCallback(new NullDataCallback() {
@Override
public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
super.onDataAvailable(emitter, bb);
mSocket.close();
}
});
handleOnCompleted();
if (getBody().readFullyOnRequest()) {
onRequest(match, this, res);
}
}
private void handleOnCompleted() {
if (requestComplete && responseComplete) {
if (HttpUtil.isKeepAlive(Protocol.HTTP_1_1, getHeaders())) {
onAccepted(socket);
}
else {
socket.close();
}
}
}
@Override
public String getPath() {
return path;
}
@Override
public Multimap getQuery() {
String[] parts = fullPath.split("\\?", 2);
if (parts.length < 2)
return new Multimap();
return Multimap.parseQuery(parts[1]);
}
};
req.setSocket(socket);
socket.resume();
}
@Override
public void onCompleted(Exception error) {
report(error);
}
@Override
public void onListening(AsyncServerSocket socket) {
mListeners.add(socket);
}
};
public AsyncServerSocket listen(AsyncServer server, int port) {
return server.listen(null, port, mListenCallback);
}
private void report(Exception ex) {
if (mCompletedCallback != null)
mCompletedCallback.onCompleted(ex);
}
public AsyncServerSocket listen(int port) {
return listen(AsyncServer.getDefault(), port);
}
public void listenSecure(final int port, final SSLContext sslContext) {
AsyncServer.getDefault().listen(null, port, new ListenCallback() {
@Override
public void onAccepted(AsyncSocket socket) {
AsyncSSLSocketWrapper.handshake(socket, null, port, sslContext.createSSLEngine(), null, null, false,
new AsyncSSLSocketWrapper.HandshakeCallback() {
@Override
public void onHandshakeCompleted(Exception e, AsyncSSLSocket socket) {
if (socket != null)
mListenCallback.onAccepted(socket);
}
});
}
@Override
public void onListening(AsyncServerSocket socket) {
mListenCallback.onListening(socket);
}
@Override
public void onCompleted(Exception ex) {
mListenCallback.onCompleted(ex);
}
});
}
public ListenCallback getListenCallback() {
return mListenCallback;
}
CompletedCallback mCompletedCallback;
public void setErrorCallback(CompletedCallback callback) {
mCompletedCallback = callback;
}
public CompletedCallback getErrorCallback() {
return mCompletedCallback;
}
private static class Pair {
Pattern regex;
HttpServerRequestCallback callback;
}
final Hashtable<String, ArrayList<Pair>> mActions = new Hashtable<String, ArrayList<Pair>>();
public void removeAction(String action, String regex) {
synchronized (mActions) {
ArrayList<Pair> pairs = mActions.get(action);
if (pairs == null)
return;
for (int i = 0; i < pairs.size(); i++) {
Pair p = pairs.get(i);
if (regex.equals(p.regex.toString())) {
pairs.remove(i);
return;
}
}
}
}
public void addAction(String action, String regex, HttpServerRequestCallback callback) {
Pair p = new Pair();
p.regex = Pattern.compile("^" + regex);
p.callback = callback;
synchronized (mActions) {
ArrayList<Pair> pairs = mActions.get(action);
if (pairs == null) {
pairs = new ArrayList<AsyncHttpServer.Pair>();
mActions.put(action, pairs);
}
pairs.add(p);
}
}
public static interface WebSocketRequestCallback {
public void onConnected(WebSocket webSocket, AsyncHttpServerRequest request);
}
public void websocket(String regex, final WebSocketRequestCallback callback) {
websocket(regex, null, callback);
}
public void websocket(String regex, final String protocol, final WebSocketRequestCallback callback) {
get(regex, new HttpServerRequestCallback() {
@Override
public void onRequest(final AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
boolean hasUpgrade = false;
String connection = request.getHeaders().get("Connection");
if (connection != null) {
String[] connections = connection.split(",");
for (String c: connections) {
if ("Upgrade".equalsIgnoreCase(c.trim())) {
hasUpgrade = true;
break;
}
}
}
if (!"websocket".equalsIgnoreCase(request.getHeaders().get("Upgrade")) || !hasUpgrade) {
response.code(404);
response.end();
return;
}
String peerProtocol = request.getHeaders().get("Sec-WebSocket-Protocol");
if (!TextUtils.equals(protocol, peerProtocol)) {
response.code(404);
response.end();
return;
}
callback.onConnected(new WebSocketImpl(request, response), request);
}
});
}
public void get(String regex, HttpServerRequestCallback callback) {
addAction(AsyncHttpGet.METHOD, regex, callback);
}
public void post(String regex, HttpServerRequestCallback callback) {
addAction(AsyncHttpPost.METHOD, regex, callback);
}
public static android.util.Pair<Integer, InputStream> getAssetStream(final Context context, String asset) {
AssetManager am = context.getAssets();
try {
InputStream is = am.open(asset);
return new android.util.Pair<Integer, InputStream>(is.available(), is);
}
catch (IOException e) {
return null;
}
}
static Hashtable<String, String> mContentTypes = new Hashtable<String, String>();
{
mContentTypes.put("js", "application/javascript");
mContentTypes.put("json", "application/json");
mContentTypes.put("png", "image/png");
mContentTypes.put("jpg", "image/jpeg");
mContentTypes.put("html", "text/html");
mContentTypes.put("css", "text/css");
mContentTypes.put("mp4", "video/mp4");
mContentTypes.put("mov", "video/quicktime");
mContentTypes.put("wmv", "video/x-ms-wmv");
}
public static String getContentType(String path) {
String type = tryGetContentType(path);
if (type != null)
return type;
return "text/plain";
}
public static String tryGetContentType(String path) {
int index = path.lastIndexOf(".");
if (index != -1) {
String e = path.substring(index + 1);
String ct = mContentTypes.get(e);
if (ct != null)
return ct;
}
return null;
}
public void directory(Context context, String regex, final String assetPath) {
final Context _context = context.getApplicationContext();
addAction(AsyncHttpGet.METHOD, regex, new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
String path = request.getMatcher().replaceAll("");
android.util.Pair<Integer, InputStream> pair = getAssetStream(_context, assetPath + path);
if (pair == null || pair.second == null) {
response.code(404);
response.end();
return;
}
final InputStream is = pair.second;
response.getHeaders().set("Content-Length", String.valueOf(pair.first));
response.code(200);
response.getHeaders().add("Content-Type", getContentType(assetPath + path));
Util.pump(is, response, new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
response.end();
StreamUtility.closeQuietly(is);
}
});
}
});
addAction(AsyncHttpHead.METHOD, regex, new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
String path = request.getMatcher().replaceAll("");
android.util.Pair<Integer, InputStream> pair = getAssetStream(_context, assetPath + path);
if (pair == null || pair.second == null) {
response.code(404);
response.end();
return;
}
final InputStream is = pair.second;
StreamUtility.closeQuietly(is);
response.getHeaders().set("Content-Length", String.valueOf(pair.first));
response.code(200);
response.getHeaders().add("Content-Type", getContentType(assetPath + path));
response.writeHead();
response.end();
}
});
}
public void directory(String regex, final File directory) {
directory(regex, directory, false);
}
public void directory(String regex, final File directory, final boolean list) {
assert directory.isDirectory();
addAction("GET", regex, new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
String path = request.getMatcher().replaceAll("");
File file = new File(directory, path);
if (file.isDirectory() && list) {
ArrayList<File> dirs = new ArrayList<File>();
ArrayList<File> files = new ArrayList<File>();
for (File f: file.listFiles()) {
if (f.isDirectory())
dirs.add(f);
else
files.add(f);
}
Comparator<File> c = new Comparator<File>() {
@Override
public int compare(File lhs, File rhs) {
return lhs.getName().compareTo(rhs.getName());
}
};
Collections.sort(dirs, c);
Collections.sort(files, c);
files.addAll(0, dirs);
return;
}
if (!file.isFile()) {
response.code(404);
response.end();
return;
}
try {
FileInputStream is = new FileInputStream(file);
response.code(200);
Util.pump(is, response, new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
response.end();
}
});
}
catch (FileNotFoundException ex) {
response.code(404);
response.end();
}
}
});
}
private static Hashtable<Integer, String> mCodes = new Hashtable<Integer, String>();
static {
mCodes.put(200, "OK");
mCodes.put(206, "Partial Content");
mCodes.put(101, "Switching Protocols");
mCodes.put(301, "Moved Permanently");
mCodes.put(302, "Found");
mCodes.put(404, "Not Found");
}
public static String getResponseCodeDescription(int code) {
String d = mCodes.get(code);
if (d == null)
return "Unknown";
return d;
}
}
| gpl-3.0 |
phamhathanh/ImageAuthentication | client/app/src/main/java/com/authpro/imageauthentication/InputFragment.java | 8323 | package com.authpro.imageauthentication;
import android.app.Fragment;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Base64;
import android.util.Pair;
import android.view.DragEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import static junit.framework.Assert.*;
public class InputFragment extends Fragment implements ICallbackable<HttpResult>
{
private final int imageCount = 30;
private int rowCount, columnCount;
private ArrayList<Pair<Integer, Integer>> input = new ArrayList<>();
private TextView textView;
private View initialButton = null;
private ImageButton[][] imageButtons;
private String[] imageHashes;
private Bitmap[] images;
private ArrayList<Integer> permutation;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_input, container, true);
this.textView = (EditText)view.findViewById(R.id.textView);
getDimensions();
setupButtons(view);
fetchImages();
return view;
}
private void getDimensions()
{
Resources resources = getResources();
int columnCountResID = R.integer.gridColumnCount,
rowCountResID = R.integer.gridRowCount;
this.columnCount = resources.getInteger(columnCountResID);
this.rowCount = resources.getInteger(rowCountResID);
assertEquals(rowCount * columnCount, imageCount);
}
private void setupButtons(View view)
{
final ViewGroup gridLayout = (ViewGroup)view.findViewById(R.id.rows);
final int realRowCount = gridLayout.getChildCount();
assertEquals(realRowCount, rowCount);
this.imageButtons = new ImageButton[rowCount][columnCount];
for (int i = 0; i < rowCount; i++)
{
final View child = gridLayout.getChildAt(i);
assertTrue(child instanceof LinearLayout);
LinearLayout row = (LinearLayout) child;
final int realColumnCount = row.getChildCount();
assertEquals(realColumnCount, columnCount);
for (int j = 0; j < columnCount; j++)
{
final View cell = ((ViewGroup)row.getChildAt(j)).getChildAt(0);
assertTrue(cell instanceof ImageButton);
final ImageButton imageButton = (ImageButton)cell;
final int index = i * columnCount + j;
imageButton.setTag(index);
imageButtons[i][j] = imageButton;
setupForDragEvent(cell);
}
}
}
private void setupForDragEvent(View view)
{
view.setOnTouchListener(new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
assertTrue(v instanceof ImageButton);
int action = event.getAction() & MotionEvent.ACTION_MASK;
switch (action)
{
case MotionEvent.ACTION_DOWN:
assertNull(initialButton);
// TODO: Fix the bug when this is not null sometimes.
initialButton = v;
View.DragShadowBuilder shadow = new View.DragShadowBuilder();
v.startDrag(null, shadow, null, 0);
v.setPressed(true);
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
break;
}
return true;
}
});
view.setOnDragListener(new View.OnDragListener()
{
@Override
public boolean onDrag(View v, DragEvent event)
{
int action = event.getAction();
switch (action)
{
case DragEvent.ACTION_DRAG_ENTERED:
if (v != initialButton)
v.setPressed(true);
break;
case DragEvent.ACTION_DRAG_EXITED:
if (v != initialButton)
v.setPressed(false);
break;
case DragEvent.ACTION_DROP:
assertNotNull(initialButton);
int firstIndex = (int)initialButton.getTag(),
secondIndex = (int)v.getTag();
addInput(firstIndex, secondIndex);
v.setPressed(false);
v.playSoundEffect(SoundEffectConstants.CLICK);
break;
case DragEvent.ACTION_DRAG_ENDED:
if (v == initialButton)
{
initialButton.setPressed(false);
initialButton = null;
}
break;
}
return true;
}
});
}
private void addInput(int firstIndex, int secondIndex)
{
input.add(new Pair<>(permutation.get(firstIndex), permutation.get(secondIndex)));
textView.append("*");
assertEquals(textView.length(), input.size());
}
private void fetchImages()
{
HttpMethod method = HttpMethod.GET;
String url = Config.API_URL + "api/images";
HttpTask task = new HttpTask(this, method, url);
task.execute();
}
public void callback(HttpResult result)
{
HttpStatus status = result.getStatus();
switch (status)
{
case OK:
String data = result.getContent();
setImages(data);
break;
default:
// Silently fail.
}
}
private void setImages(String data)
{
images = new Bitmap[imageCount];
imageHashes = new String[imageCount];
permutation = new ArrayList<>(imageCount);
String[] base64Strings = data.split("\n");
for (int i = 0; i < rowCount; i++)
for (int j = 0; j < columnCount; j++)
{
int index = i * columnCount + j;
permutation.add(index);
String base64 = base64Strings[index];
images[index] = fromBase64(base64);
imageHashes[index] = Utils.computeHash(base64);
}
shuffle();
}
public void shuffle()
{
Collections.shuffle(permutation);
for (int i = 0; i < rowCount; i++)
for (int j = 0; j < columnCount; j++)
{
ImageButton imageButton = imageButtons[i][j];
int index = i * columnCount + j;
Bitmap image = images[permutation.get(index)];
imageButton.setImageBitmap(image);
}
}
private Bitmap fromBase64(String base64)
{
byte[] bytes = Base64.decode(base64, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
public void clear()
{
input = new ArrayList<>();
textView.setText("");
}
public String getInputString()
// Should use char[] instead, for security reasons.
{
StringBuilder output = new StringBuilder();
for (Pair<Integer, Integer> pair : this.input)
{
if (pair.first.equals(pair.second))
output.append(imageHashes[pair.first]).append("_");
else
output.append(imageHashes[pair.first]).append("+").append(imageHashes[pair.second]).append("_");
}
return output.toString();
}
}
| gpl-3.0 |
septadev/SEPTA-Android | app/src/main/java/org/septa/android/app/services/apiinterfaces/FavoritesSharedPrefsUtilsImpl.java | 15568 | package org.septa.android.app.services.apiinterfaces;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import org.septa.android.app.favorites.FavoriteState;
import org.septa.android.app.services.apiinterfaces.model.Favorite;
import org.septa.android.app.services.apiinterfaces.model.NextArrivalFavorite;
import org.septa.android.app.services.apiinterfaces.model.TransitViewFavorite;
import org.septa.android.app.transitview.TransitViewUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FavoritesSharedPrefsUtilsImpl implements FavoritesSharedPrefsUtils {
public static final String TAG = FavoritesSharedPrefsUtilsImpl.class.getSimpleName();
private static final String KEY_FAVORITES_NTA = "favorite_json";
private static final String KEY_FAVORITES_TRANSITVIEW = "favorite_transitview_json";
private static final String KEY_FAVORITES_STATE = "favorite_state_json";
// using commit() instead of apply() so that the values are immediately written to memory
/**
* fixing some corrupt favorites
*
* @param context
* @return list of valid favorites
*/
@Override
public Map<String, NextArrivalFavorite> getNTAFavorites(Context context) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
Map<String, NextArrivalFavorite> favorites = getNTAFavorites(sharedPreferences);
for (Map.Entry<String, NextArrivalFavorite> entry : favorites.entrySet()) {
// delete any invalid NTA favorites
if (entry.getValue().getStart() == null) {
deleteAllFavorites(context);
return new HashMap<>();
}
}
return favorites;
}
/**
* fixing some corrupt favorites
*
* @param context
* @return list of valid favorites
*/
@Override
public Map<String, TransitViewFavorite> getTransitViewFavorites(Context context) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
Map<String, TransitViewFavorite> favorites = getTransitViewFavorites(sharedPreferences);
for (Map.Entry<String, TransitViewFavorite> entry : favorites.entrySet()) {
// TODO: delete / fix any invalid TransitView favorites
if (entry.getValue().getSecondRoute() == null && entry.getValue().getThirdRoute() != null) {
deleteAllFavorites(context);
return new HashMap<>();
}
}
return favorites;
}
@Override
public List<FavoriteState> getFavoriteStates(Context context) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
String preferencesJson = sharedPreferences.getString(KEY_FAVORITES_STATE, null);
if (preferencesJson == null) {
return new ArrayList<>();
}
Gson gson = new Gson();
try {
return gson.fromJson(preferencesJson, new TypeToken<List<FavoriteState>>() {
}.getType());
} catch (JsonSyntaxException e) {
Log.e(TAG, e.toString());
sharedPreferences.edit().remove(KEY_FAVORITES_STATE).commit();
return new ArrayList<>();
}
}
@Override
public void addFavorites(Context context, Favorite favorite) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
if (favorite instanceof NextArrivalFavorite) {
Map<String, NextArrivalFavorite> favorites = getNTAFavorites(sharedPreferences);
favorites.put(favorite.getKey(), (NextArrivalFavorite) favorite);
addFavoriteState(context, new FavoriteState(favorite.getKey()));
storeNTAFavorites(sharedPreferences, favorites);
} else if (favorite instanceof TransitViewFavorite) {
Map<String, TransitViewFavorite> favorites = getTransitViewFavorites(sharedPreferences);
favorites.put(favorite.getKey(), (TransitViewFavorite) favorite);
addFavoriteState(context, new FavoriteState(favorite.getKey()));
storeTransitViewFavorites(sharedPreferences, favorites);
} else {
Log.e(TAG, "Invalid class type -- could not create a new Favorite for " + favorite.getKey());
}
}
@Override
public void addFavoriteState(Context context, FavoriteState favoriteState) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
List<FavoriteState> favoritesState = getFavoriteStates(context);
if (!favoritesState.contains(favoriteState)) {
favoritesState.add(favoriteState);
storeFavoritesState(sharedPreferences, favoritesState);
} else {
Log.d(TAG, "Already have a favorite state for " + favoriteState.getFavoriteKey());
}
}
@Override
public void setFavoriteStates(Context context, List<FavoriteState> favoriteStateList) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
storeFavoritesState(sharedPreferences, favoriteStateList);
}
@Override
public void modifyFavoriteState(Context context, int index, boolean expanded) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
List<FavoriteState> favoriteStateList = getFavoriteStates(context);
favoriteStateList.get(index).setExpanded(expanded);
storeFavoritesState(sharedPreferences, favoriteStateList);
}
@Override
public void renameFavorite(Context context, Favorite favorite) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
if (favorite instanceof NextArrivalFavorite) {
Map<String, NextArrivalFavorite> favorites = getNTAFavorites(sharedPreferences);
if (favorites.containsKey(favorite.getKey())) {
favorites.put(favorite.getKey(), (NextArrivalFavorite) favorite);
storeNTAFavorites(sharedPreferences, favorites);
} else {
Log.d(TAG, "NTA Favorite could not be renamed because it did not exist!");
addFavorites(context, favorite);
}
} else if (favorite instanceof TransitViewFavorite) {
Map<String, TransitViewFavorite> favorites = getTransitViewFavorites(sharedPreferences);
if (favorites.containsKey(favorite.getKey())) {
favorites.put(favorite.getKey(), (TransitViewFavorite) favorite);
storeTransitViewFavorites(sharedPreferences, favorites);
} else {
Log.d(TAG, "TransitView Favorite could not be renamed because it did not exist!");
addFavorites(context, favorite);
}
} else {
Log.e(TAG, "Invalid class type -- could not rename Favorite " + favorite.getKey());
}
}
@Override
public void deleteFavorite(Context context, String favoriteKey) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
// attempt to delete NTA favorite
Map<String, NextArrivalFavorite> ntaFavorites = getNTAFavorites(sharedPreferences);
if (ntaFavorites.remove(favoriteKey) != null) {
storeNTAFavorites(sharedPreferences, ntaFavorites);
} else {
// attempt to delete TransitView favorite
Map<String, TransitViewFavorite> transitViewFavorites = getTransitViewFavorites(sharedPreferences);
if (transitViewFavorites.remove(favoriteKey) != null) {
storeTransitViewFavorites(sharedPreferences, transitViewFavorites);
} else {
Log.e(TAG, "Could not delete Favorite with key " + favoriteKey);
}
}
deleteFavoriteState(context, favoriteKey);
}
private void deleteFavoriteState(Context context, String favoriteKey) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
List<FavoriteState> favoriteStates = getFavoriteStates(context);
int indexToRemove = -1;
for (int i = 0; i < favoriteStates.size(); i++) {
if (favoriteKey.equals(favoriteStates.get(i).getFavoriteKey())) {
indexToRemove = i;
break;
}
}
if (indexToRemove != -1) {
favoriteStates.remove(indexToRemove);
} else {
Log.e(TAG, "Could not delete favorite state with key " + favoriteKey);
}
storeFavoritesState(sharedPreferences, favoriteStates);
}
@Override
public void deleteAllFavorites(Context context) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
sharedPreferences.edit().remove(KEY_FAVORITES_NTA).commit();
sharedPreferences.edit().remove(KEY_FAVORITES_TRANSITVIEW).commit();
deleteAllFavoriteStates(context);
}
@Override
public void deleteAllFavoriteStates(Context context) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
sharedPreferences.edit().remove(KEY_FAVORITES_STATE).commit();
}
@Override
public Favorite getFavoriteByKey(Context context, String key) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
Favorite favorite = getNTAFavorites(sharedPreferences).get(key);
if (favorite == null) {
favorite = getTransitViewFavorites(sharedPreferences).get(key);
}
return favorite;
}
@Override
public void moveFavoriteStateToIndex(Context context, int fromPosition, int toPosition) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
List<FavoriteState> favoriteStateList = getFavoriteStates(context);
FavoriteState favoriteStateToMove = favoriteStateList.get(fromPosition);
// remove favorite state
favoriteStateList.remove(fromPosition);
// re-add at index which shifts everything else back one
favoriteStateList.add(toPosition, favoriteStateToMove);
storeFavoritesState(sharedPreferences, favoriteStateList);
}
@Override
public void resyncFavoritesMap(Context context) {
SharedPreferences sharedPreferences = getSharedPreferences(context);
List<FavoriteState> favoriteStateList = getFavoriteStates(context);
Map<String, NextArrivalFavorite> ntaFavorites = getNTAFavorites(context);
Map<String, TransitViewFavorite> transitViewFavorites = getTransitViewFavorites(context);
if (favoriteStateList.isEmpty() && (!ntaFavorites.isEmpty() || !transitViewFavorites.isEmpty())) {
// initialize favorite state list
Log.d(TAG, "Initializing favorite states now...");
for (NextArrivalFavorite entry : ntaFavorites.values()) {
FavoriteState favoriteState = new FavoriteState(entry.getKey());
favoriteStateList.add(favoriteState);
}
for (TransitViewFavorite entry : transitViewFavorites.values()) {
FavoriteState favoriteState = new FavoriteState(entry.getKey());
favoriteStateList.add(favoriteState);
}
setFavoriteStates(context, favoriteStateList);
} else if (favoriteStateList.size() != (ntaFavorites.size() + transitViewFavorites.size())) {
// resync because state list does not map 1-to-1
Log.d(TAG, "Resyncing favorite states now...");
deleteAllFavorites(context);
Map<String, NextArrivalFavorite> newNTAFavorites = new HashMap<>();
Map<String, TransitViewFavorite> newTransitViewFavorites = new HashMap<>();
for (FavoriteState favoriteState : favoriteStateList) {
String favoriteKey = favoriteState.getFavoriteKey();
// copy over favorite
if (TransitViewUtils.isATransitViewFavorite(favoriteKey)) {
newTransitViewFavorites.put(favoriteKey, transitViewFavorites.get(favoriteKey));
} else {
newNTAFavorites.put(favoriteKey, ntaFavorites.get(favoriteKey));
}
// create new favorite state for it
if (getFavoriteByKey(context, favoriteKey) == null) {
addFavoriteState(context, new FavoriteState(favoriteKey));
} else {
Log.d(TAG, "Favorite state already exists for favorite with key: " + favoriteKey);
}
}
storeNTAFavorites(sharedPreferences, newNTAFavorites);
storeTransitViewFavorites(sharedPreferences, newTransitViewFavorites);
} else {
Log.d(TAG, "Resync of favorites map did not occur. State list size: " + favoriteStateList.size() +
" NTA Map size: " + ntaFavorites.size() + " TransitView map size: " + transitViewFavorites.size());
}
}
private SharedPreferences getSharedPreferences(Context context) {
return context.getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE);
}
private Map<String, NextArrivalFavorite> getNTAFavorites(SharedPreferences sharedPreferences) {
String preferencesJson = sharedPreferences.getString(KEY_FAVORITES_NTA, null);
if (preferencesJson == null) {
return new HashMap<>();
}
Gson gson = new Gson();
try {
return gson.fromJson(preferencesJson, new TypeToken<Map<String, NextArrivalFavorite>>() {
}.getType());
} catch (JsonSyntaxException e) {
Log.e(TAG, e.toString());
sharedPreferences.edit().remove(KEY_FAVORITES_NTA).commit();
return new HashMap<>();
}
}
private Map<String, TransitViewFavorite> getTransitViewFavorites(SharedPreferences sharedPreferences) {
String preferencesJson = sharedPreferences.getString(KEY_FAVORITES_TRANSITVIEW, null);
if (preferencesJson == null) {
return new HashMap<>();
}
Gson gson = new Gson();
try {
return gson.fromJson(preferencesJson, new TypeToken<Map<String, TransitViewFavorite>>() {
}.getType());
} catch (JsonSyntaxException e) {
Log.e(TAG, e.toString());
sharedPreferences.edit().remove(KEY_FAVORITES_TRANSITVIEW).commit();
return new HashMap<>();
}
}
private void storeNTAFavorites(SharedPreferences sharedPreferences, Map<String, NextArrivalFavorite> favorites) {
Gson gson = new Gson();
String favoritesJson = gson.toJson(favorites);
sharedPreferences.edit().putString(KEY_FAVORITES_NTA, favoritesJson).commit();
}
private void storeTransitViewFavorites(SharedPreferences sharedPreferences, Map<String, TransitViewFavorite> favorites) {
Gson gson = new Gson();
String favoritesJson = gson.toJson(favorites);
sharedPreferences.edit().putString(KEY_FAVORITES_TRANSITVIEW, favoritesJson).commit();
}
private void storeFavoritesState(SharedPreferences sharedPreferences, List<FavoriteState> favoriteStateList) {
Gson gson = new Gson();
String favoritesStatesJson = gson.toJson(favoriteStateList);
sharedPreferences.edit().putString(KEY_FAVORITES_STATE, favoritesStatesJson).commit();
}
}
| gpl-3.0 |
pajato/java-examples | apps/misc/smerge/src/main/java/Main.java | 2552 | /**
* Problem 10.1 CTCI Sorted Merge
*
* You are given two sorted arrays, a and b, where a has a large enough buffer at the end to hold
* b. Write a method to merge b into a in sorted order.
*
* Examples:
*
* a: 2, 7, 22, 44, 56, 88, 456, 5589
* b: 1, 4, 9, 23, 99, 1200
*
* Result:
*
* result: 1, 2, 4, 7, 9, 22, 23, 44, 56, 88, 99, 456, 1200, 5589
*
* Analysis:
*
* The merge is probably most effective if the values are inserted into the buffer starting with
* the end of the input arrays.
*
* a == a0, a1, a2, ..., ai, ... an i.e. i is range 0..n
* b == b0, b1, b2, ..., bj, ... bm i.e. j is range 0..m
*
* Algorithm:
*
* 1) Starting at the end of the arrays, compare (a, b) each descending element and place the larger
* at the end of the result array (a). If the values are identical, put both elements into the
* result.
*
* 2) Decrement the running index for each array contributing to the result on this iteration.
*
* 3) Repeat until the b running index (j) is 0 (all of b have been added to a).
*
* i = n;
* j = m;
* while j >= 0 do
* if i < 0
* then
* a[j] = b[j]
* else if a[i] > b[j]
* then
* a[i+j+1] = a[i--]
* else if b[j] > a[i]
* a[i+j] = b[j--]
* else
* a[i+j] = b[j--]
* a[i+j] = a[i--]
*/
import java.util.Arrays;
import java.util.Locale;
public class Main {
/** Run the program using the command line arguments. */
public static void main(String[] args) {
// Define a and b.
int[] a = new int[]{2, 7, 22, 44, 56, 88, 456, 5589};
int[] b = new int[]{1, 4, 9, 23, 99, 1200};
int[] result = smerge(a, b);
String format = "Result: %s";
System.out.println(String.format(Locale.US, format, Arrays.toString(result)));
}
/** Return the given value in the given base. */
private static int[] smerge(final int[] a, final int[] b) {
final int N = a.length;
final int M = b.length;
int [] result = new int[N + M];
System.arraycopy(a, 0, result, 0, N);
int i = N - 1;
int j = M - 1;
while (j >= 0) {
if (i < 0)
result[j] = b[j--];
else if (a[i] > b[j])
result[i + j + 1] = a[i--];
else if (b[j] > a[i])
result[i + j + 1] = b[j--];
else {
result[i + j + 1] = a[i--];
result[i + j + 1] = b[j--];
}
}
return result;
}
}
| gpl-3.0 |
Ophidia/eubrazilcc-uc3-gateway | src/it/cmcc/ophidiaweb/utils/deserialization/Nodelink.java | 2185 | /**
Eubrazil Scientific Gateway
Copyright (C) 2015 CMCC
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.cmcc.ophidiaweb.utils.deserialization;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"node",
"description"
})
public class Nodelink {
@JsonProperty("node")
private String node;
@JsonProperty("description")
private String description;
@JsonProperty("node")
public String getNode() {
return node;
}
@JsonProperty("node")
public void setNode(String node) {
this.node = node;
}
@JsonProperty("description")
public String getDescription() {
return description;
}
@JsonProperty("description")
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(Object other) {
return EqualsBuilder.reflectionEquals(this, other);
}
}
| gpl-3.0 |
fisty256/PackGame | src/net/fisty/packgame/client/graphics/particle/Particle.java | 402 | package net.fisty.packgame.client.graphics.particle;
import java.awt.Graphics;
import java.awt.image.ImageObserver;
public abstract class Particle {
public int index = 0;
public abstract void render(Graphics g, ImageObserver obs);
public abstract void update();
public abstract void server();
public abstract String serializeParticle();
public abstract void unserializeParticle(String s);
} | gpl-3.0 |
potty-dzmeia/db4o | src/db4oj.tests/src/com/db4o/db4ounit/common/soda/ordered/OrderedOrConstraintTestCase.java | 1737 | /* 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.db4ounit.common.soda.ordered;
import com.db4o.*;
import com.db4o.query.*;
import db4ounit.*;
import db4ounit.extensions.*;
/**
* COR-1062
*/
public class OrderedOrConstraintTestCase extends AbstractDb4oTestCase{
public static class Item{
public Item(int int_, boolean boolean_) {
_int = int_;
_boolean = boolean_;
}
public int _int;
public boolean _boolean;
}
@Override
protected void store() throws Exception {
store(new Item(10, false));
store(new Item(4, true));
super.store();
}
public void test(){
Query query = newQuery(Item.class);
Constraint c1 = query.descend("_int").constrain(9).greater();
Constraint c2 = query.descend("_boolean").constrain(true);
c1.or(c2);
query.descend("_int").orderAscending();
ObjectSet<Item> objectSet = query.execute();
Assert.areEqual(2, objectSet.size());
Item item = objectSet.next();
Assert.areEqual(4, item._int);
item = objectSet.next();
Assert.areEqual(10, item._int);
}
}
| gpl-3.0 |
fastlorenzo/mvfa | src/be/bernardi/mvforandroid/data/DatabaseHelper.java | 12330 | /*
Copyright (C) 2011 Lorenzo Bernardi (fastlorenzo@gmail.com)
2010 Ben Van Daele (vandaeleben@gmail.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 be.bernardi.mvforandroid.data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mvforandroid.db";
private static final int SCHEMA_VERSION = 3;
public final Usage usage;
public final Credit credit;
public final Topups topups;
public final Msisdns msisdns;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
this.usage = new Usage();
this.credit = new Credit();
this.topups = new Topups();
this.msisdns = new Msisdns();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + Usage.TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "timestamp INTEGER NOT NULL, "
+ "duration INTEGER, " + "type INTEGER, " + "incoming INTEGER, " + "contact TEXT, " + "cost REAL);");
db.execSQL("CREATE TABLE IF NOT EXISTS " + Topups.TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "amount REAL NOT NULL, "
+ "method TEXT NOT NULL, " + "executed_on INTEGER NOT NULL, " + "received_on INTEGER, " + "status TEXT NOT NULL);");
db.execSQL("CREATE TABLE IF NOT EXISTS " + Credit.TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "valid_until INTEGER NULL, "
+ "expired INTEGER NOT NULL, " + "sms INTEGER NOT NULL, " + "data INTEGER NOT NULL, " + "credits REAL NOT NULL, "
+ "price_plan TEXT NOT NULL, " + "sms_son INTEGER NOT NULL);");
db.execSQL("CREATE TABLE IF NOT EXISTS " + Msisdns.TABLE_NAME + " (msisdn TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion) {
case 1:
if(newVersion < 2) {
return;
}
case 2: {
db.execSQL("DROP TABLE " + Topups.TABLE_NAME + ";");
db.execSQL("CREATE TABLE IF NOT EXISTS " + Topups.TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "amount REAL NOT NULL, "
+ "method TEXT NOT NULL, " + "executed_on INTEGER NOT NULL, " + "received_on INTEGER, " + "status TEXT NOT NULL);");
break;
}
}
}
private static SimpleDateFormat apiFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static Date getDateFromAPI(String dateString) {
try {
return apiFormat.parse(dateString);
}
catch(ParseException e) {
return null;
}
}
public class Credit {
private static final String TABLE_NAME = "credit";
public void update(JSONObject json, boolean data_only) throws JSONException, NumberFormatException {
Cursor query = getWritableDatabase().query(TABLE_NAME, new String[] { "_id" }, null, null, null, null, null, null);
ContentValues values = new ContentValues();
values.put("valid_until", getDateFromAPI(json.getString("valid_until")).getTime());
values.put("expired", (Boolean.parseBoolean(json.getString("is_expired")) ? 1 : 0));
if(Boolean.parseBoolean(json.getString("is_expired")) == true) {
values.put("data", 0);
values.put("credits", 0);
}
else {
values.put("data", Long.parseLong(json.getString("data")));
}
values.put("price_plan", json.getString("price_plan"));
if(!data_only) {
values.put("credits", Double.parseDouble(json.getString("credits")));
values.put("sms", Integer.parseInt(json.getString("sms")));
values.put("sms_son", Integer.parseInt(json.getString("sms_super_on_net")));
}
else {
values.put("credits", 0);
values.put("sms", 0);
values.put("sms_son", 0);
}
if(query.getCount() == 0) {
// No credit info stored yet, insert a row
getWritableDatabase().insert(TABLE_NAME, "valid_until", values);
}
else {
// Credit info present already, so update it
getWritableDatabase().update(TABLE_NAME, values, null, null);
}
query.close();
}
public long getValidUntil() {
Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null);
long result;
if(c.moveToFirst())
result = c.getLong(1);
else
result = 0;
c.close();
return result;
}
public boolean isExpired() {
Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null);
boolean result;
if(c.moveToFirst())
result = c.getLong(2) == 1;
else
result = true;
c.close();
return result;
}
public int getRemainingSms() {
Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null);
int result;
if(c.moveToFirst())
result = c.getInt(3);
else
result = 0;
c.close();
return result;
}
public long getRemainingData() {
Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null);
long result;
if(c.moveToFirst())
result = c.getLong(4);
else
result = 0;
c.close();
return result;
}
public double getRemainingCredit() {
Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null);
double result;
if(c.moveToFirst())
result = c.getDouble(5);
else
result = 0;
c.close();
return result;
}
public int getPricePlan() {
Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null);
int result;
if(c.moveToFirst())
result = c.getInt(6);
else
result = 0;
c.close();
return result;
}
public int getRemainingSmsSuperOnNet() {
Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null);
int result;
if(c.moveToFirst())
result = c.getInt(7);
else
result = 0;
c.close();
return result;
}
}
public class Usage {
private static final String TABLE_NAME = "usage";
public static final int TYPE_DATA = 0;
public static final int TYPE_SMS = 1;
public static final int TYPE_VOICE = 2;
public static final int TYPE_MMS = 3;
public static final int ORDER_BY_DATE = 1;
public void update(JSONArray jsonArray) throws JSONException {
getWritableDatabase().delete(TABLE_NAME, null, null);
getWritableDatabase().beginTransaction();
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
insert(json);
}
getWritableDatabase().setTransactionSuccessful();
getWritableDatabase().endTransaction();
}
public void insert(JSONObject json) throws JSONException {
// "timestamp INTEGER NOT NULL, " +
// "duration INTEGER NOT NULL, " +
// "type INTEGER NOT NULL, " +
// "incoming INTEGER NOT NULL, " +
// "contact TEXT NOT NULL, " +
// "cost REAL NOT NULL);");
ContentValues values = new ContentValues();
values.put("timestamp", getDateFromAPI(json.getString("start_timestamp")).getTime());
values.put("duration", json.getLong("duration_connection"));
if(Boolean.parseBoolean(json.getString("is_data")))
values.put("type", TYPE_DATA);
if(Boolean.parseBoolean(json.getString("is_sms")))
values.put("type", TYPE_SMS);
if(Boolean.parseBoolean(json.getString("is_voice")))
values.put("type", TYPE_VOICE);
if(Boolean.parseBoolean(json.getString("is_mms")))
values.put("type", TYPE_MMS);
values.put("incoming", (Boolean.parseBoolean(json.getString("is_incoming")) ? 1 : 0));
values.put("contact", json.getString("to"));
values.put("cost", Double.parseDouble(json.getString("price")));
getWritableDatabase().insert(TABLE_NAME, "timestamp", values);
}
public Cursor get(long id) {
return getReadableDatabase().query(TABLE_NAME, null, "_id=" + id, null, null, null, null);
}
/**
* Returns a cursor over the Usage table.
*
* @param isSearch
* Whether to include usage records obtained by a search, or
* (xor) those obtained through auto-updating.
* @param order
* The constant representing the field to order the cursor
* by.
* @param ascending
* Whether the order should be ascending or descending.
*/
public Cursor get(int order, boolean ascending) {
String orderBy = null;
switch(order) {
case ORDER_BY_DATE:
orderBy = "timestamp " + (ascending ? "asc" : "desc");
}
return getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, orderBy);
}
public long getTimestamp(Cursor c) {
return c.getLong(1);
}
public long getduration(Cursor c) {
return c.getLong(2);
}
public int getType(Cursor c) {
return c.getInt(3);
}
public boolean isIncoming(Cursor c) {
return c.getInt(4) == 1;
}
public String getContact(Cursor c) {
return c.getString(5);
}
public double getCost(Cursor c) {
return c.getDouble(6);
}
}
public class Topups {
private static final String TABLE_NAME = "topups";
public void update(JSONArray jsonArray, boolean b) throws JSONException {
getWritableDatabase().delete(TABLE_NAME, null, null);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
insert(json);
}
}
private void insert(JSONObject json) throws JSONException {
ContentValues values = new ContentValues();
values.put("amount", Double.parseDouble(json.getString("amount")));
values.put("method", json.getString("method"));
values.put("executed_on", getDateFromAPI(json.getString("executed_on")).getTime());
Log.d("MVFA", json.getString("payment_received_on"));
if(!json.getString("payment_received_on").equals("null"))
values.put("received_on", getDateFromAPI(json.getString("payment_received_on")).getTime());
values.put("status", json.getString("status"));
getWritableDatabase().insert(TABLE_NAME, "timestamp", values);
}
public Cursor getAll() {
return getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null);
}
public double getAmount(Cursor c) {
return c.getDouble(1);
}
public String getMethod(Cursor c) {
return c.getString(2);
}
public long getExecutedOn(Cursor c) {
return c.getLong(3);
}
public long getReceivedOn(Cursor c) {
return c.getLong(4);
}
public String getStatus(Cursor c) {
return c.getString(5);
}
}
public class Msisdns {
private static final String TABLE_NAME = "msisdns";
public void update(JSONArray jsonArray) throws JSONException {
getWritableDatabase().delete(TABLE_NAME, null, null);
for(int i = 0; i < jsonArray.length(); i++) {
String msisdn = jsonArray.getString(i);
insert(msisdn);
}
}
private void insert(String msisdn) throws JSONException {
ContentValues values = new ContentValues();
values.put("msisdn", msisdn);
getWritableDatabase().insert(TABLE_NAME, "msisdn", values);
}
public Cursor getAll() {
return getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null);
}
public String[] getMsisdnList() {
Cursor c = getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null);
String[] result = null;
int i = 0;
if(c.moveToFirst()) {
do {
i++;
}
while(c.moveToNext());
result = new String[i];
c.moveToFirst();
i = 0;
do {
if(c.getString(0) != null) {
result[i] = c.getString(0);
i++;
}
}
while(c.moveToNext());
}
c.close();
return result;
}
}
}
| gpl-3.0 |
CaronLe/chanhthings2 | src/omr/gui/Menu.java | 6822 | package omr.gui;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
/**
* Menu bar of the main window.
*/
public class Menu extends JMenuBar implements ActionListener {
private static final long serialVersionUID = 1L;
private Gui gui;
private JMenuItem newProject;
private JMenuItem openProject;
private JMenuItem saveProject;
private JMenuItem saveProjectAs;
private JMenuItem importSheets;
private JMenuItem exportAnswers;
private JMenuItem exportResults;
private JMenuItem mailFeedback;
public Menu(Gui gui) {
this.gui = gui;
UndoSupport undoSupport = gui.getUndoSupport();
// File menu
JMenu fileMenu = new JMenu("Bộ Bài Thi");
fileMenu.setMnemonic(KeyEvent.VK_F);
fileMenu.setForeground(new Color(48,47,95));
fileMenu.setFont(new Font("Century Gothic", Font.BOLD, 14));
add(fileMenu);
// New project
newProject = new JMenuItem("Tạo Bộ Bài Thi Mới", KeyEvent.VK_N);
newProject.addActionListener(this);
fileMenu.add(newProject);
// Open project
openProject = new JMenuItem("Mở Bộ Bài Thi", KeyEvent.VK_O);
openProject.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
openProject.addActionListener(this);
fileMenu.add(openProject);
// Save project
saveProject = new JMenuItem("Lưu Bộ Bài Thi", KeyEvent.VK_A);
saveProject.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
saveProject.addActionListener(this);
fileMenu.add(saveProject);
// Save project as
saveProjectAs = new JMenuItem("Lưu Bộ Bài Thi Tại .....", KeyEvent.VK_S);
//saveProjectAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
saveProjectAs.addActionListener(this);
fileMenu.add(saveProjectAs);
// Sheets management
JMenu sheetsMenu = new JMenu("Bài Thi");
sheetsMenu.setMnemonic(KeyEvent.VK_F);
sheetsMenu.setForeground(new Color(48,47,95));
sheetsMenu.setFont(new Font("Century Gothic", Font.BOLD, 14));
//menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items");
add(sheetsMenu);
importSheets = new JMenuItem("Nhập Bài Thi", KeyEvent.VK_I);
importSheets.getAccessibleContext().setAccessibleDescription("Nhập hình ảnh bài thi vào bộ bài thi");
importSheets.addActionListener(this);
sheetsMenu.add(importSheets);
// Export answers
exportAnswers = new JMenuItem("Xuất Câu Trả Lời", KeyEvent.VK_C);
exportAnswers.getAccessibleContext().setAccessibleDescription("Xuất Toàn Bộ Câu Trả Lời Ra Một Tệp Tin");
exportAnswers.addActionListener(this);
sheetsMenu.add(exportAnswers);
// Export results
exportResults = new JMenuItem("Xuất Kết Quả", KeyEvent.VK_R);
exportResults.getAccessibleContext().setAccessibleDescription("Xuất Toàn Bộ Kết Quả Ra Một Tệp Tin");
exportResults.addActionListener(this);
sheetsMenu.add(exportResults);
// Edit menu
JMenu editMenu = new JMenu("Tuỳ Chỉnh");
editMenu.setMnemonic(KeyEvent.VK_E);
editMenu.setForeground(new Color(48,47,95));
editMenu.setFont(new Font("Century Gothic", Font.BOLD, 14));
add(editMenu);
// Undo
JMenuItem undo = new JMenuItem("Undo", KeyEvent.VK_U);
undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
undo.addActionListener(undoSupport.getUndoAction());
editMenu.add(undo);
// Redo
JMenuItem redo = new JMenuItem("Redo", KeyEvent.VK_R);
redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
redo.addActionListener(undoSupport.getRedoAction());
editMenu.add(redo);
// Cut
JMenuItem cut = new JMenuItem("Cắt", KeyEvent.VK_T);
cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
//cut.addActionListener(new CutAction(undoManager));
//editMenu.add(cut);
// Copy
JMenuItem copy = new JMenuItem("Sao chép", KeyEvent.VK_C);
copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
//copy.addActionListener(new CopyAction(undoManager));
//editMenu.add(copy);
// Paste
JMenuItem paste = new JMenuItem("Dán", KeyEvent.VK_P);
paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
//paste.addActionListener(new PasteAction(undoManager));
//editMenu.add(paste);
// Delete
JMenuItem delete = new JMenuItem("Xoá", KeyEvent.VK_D);
delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
//delete.addActionListener(new DeleteAction(undoManager));
editMenu.add(delete);
// // Mail feedback
// JMenu mailMenu = new JMenu("Gửi Mail");
// mailMenu.setMnemonic(KeyEvent.VK_F);
// //menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items");
// add(mailMenu);
//
// mailFeedback = new JMenuItem("Gửi Mail Kết Quả Cho Thí Sinh", KeyEvent.VK_M);
// mailFeedback.getAccessibleContext().setAccessibleDescription("Gửi Mail Kết Quả Cho Thí Sinh");
// mailFeedback.addActionListener(this);
// mailMenu.add(mailFeedback);
}
/**
* Menu event listener.
*/
public void actionPerformed(ActionEvent event) {
JMenuItem source = (JMenuItem)(event.getSource());
if (source == newProject) {
gui.newProject();
} else if (source == openProject) {
gui.openProject();
} else if (source == saveProject) {
gui.saveProject();
} else if (source == saveProjectAs) {
gui.saveProjectAs();
} else if (source == importSheets) {
gui.importSheets();
} else if (source == exportAnswers) {
gui.exportAnswers();
} else if (source == exportResults) {
gui.exportResults();
} else if (source == mailFeedback) {
gui.mailFeedback();
}
}
}
| gpl-3.0 |
neblina-software/balerocms-v2 | src/main/java/com/neblina/balero/util/AntiXSS.java | 854 | /**
* Balero CMS Project: Proyecto 100% Mexicano de código libre.
* Página Oficial: http://www.balerocms.com
*
* @author Anibal Gomez <anibalgomez@icloud.com>
* @copyright Copyright (C) 2015 Neblina Software. Derechos reservados.
* @license Licencia BSD; vea LICENSE.txt
*/
package com.neblina.balero.util;
import org.owasp.html.Sanitizers;
public class AntiXSS {
/**
* Sanitize common elements b, p, etc. img and a.
* @author Anibal Gomez
* @param input Unsafe Input
* @return Safe Output
*/
public String blind(String input) {
org.owasp.html.PolicyFactory policy = Sanitizers.STYLES
.and(Sanitizers.FORMATTING)
.and(Sanitizers.IMAGES)
.and(Sanitizers.LINKS);
String output = policy.sanitize(input);
return output;
}
}
| gpl-3.0 |
Link184/Respiration | respiration-compiler/src/main/java/com/link184/respiration/LocalRepositoryClassGenerator.java | 3600 | package com.link184.respiration;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.util.Map;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
/**
* Created by eugeniu on 3/22/18.
*/
public class LocalRepositoryClassGenerator {
JavaFile generateRepositories(Map<Element, String> repositoriesWithPackages) {
for (Map.Entry<Element, String> entry : repositoriesWithPackages.entrySet()) {
if (entry.getKey().getAnnotation(LocalRepository.class) != null) {
return generateRepository(entry.getKey(), entry.getValue());
}
}
return null;
}
private JavaFile generateRepository(Element element, String packageName) {
Name simpleName = element.getSimpleName();
String capitalizedRepoName = simpleName.toString().substring(0, 1).toUpperCase()
+ simpleName.toString().substring(1);
LocalRepository annotation = element.getAnnotation(LocalRepository.class);
TypeName modelType = GenerationUtils.extractTypeName(annotation);
ParameterizedTypeName superClass = ParameterizedTypeName.get(ClassName.bestGuess(element.asType().toString()), modelType);
TypeSpec.Builder repositoryClass = TypeSpec.classBuilder(capitalizedRepoName)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(generateRepositoryAnnotation(element))
.superclass(superClass)
.addMethod(generateRepositoryConstructor(element));
return JavaFile.builder(packageName, repositoryClass.build())
.build();
}
private AnnotationSpec generateRepositoryAnnotation(Element element) {
LocalRepository annotation = element.getAnnotation(LocalRepository.class);
AnnotationSpec.Builder annotationBuilder = AnnotationSpec.builder(annotation.annotationType());
annotationBuilder
.addMember("dataSnapshotType", "$T.class", GenerationUtils.extractTypeName(annotation))
.addMember("dataBaseAssetPath", "$S", annotation.dataBaseAssetPath());
if (annotation.children().length > 0 && !annotation.children()[0].isEmpty()) {
annotationBuilder.addMember("children", "$L", GenerationUtils.generateChildrenArrayForAnnotations(annotation));
}
if (!annotation.dataBaseName().isEmpty()) {
annotationBuilder.addMember("dataBaseName", "$S", annotation.dataBaseName());
}
return annotationBuilder.build();
}
private MethodSpec generateRepositoryConstructor(Element element) {
final ClassName configurationClass = ClassName.get("com.link184.respiration.repository.local", "LocalConfiguration");
final String configurationParameterName = "configuration";
TypeName modelType = GenerationUtils.extractTypeName(element.getAnnotation(LocalRepository.class));
ParameterizedTypeName parametrizedConfigurationClass = ParameterizedTypeName.get(configurationClass, modelType);
return MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC)
.addParameter(parametrizedConfigurationClass, configurationParameterName)
.addStatement("super($N)", configurationParameterName)
.build();
}
}
| gpl-3.0 |
guiguilechat/EveOnline | model/sde/SDE-Types/src/generated/java/fr/guiguilechat/jcelechat/model/sde/attributes/MiningDurationRoleBonus.java | 830 | package fr.guiguilechat.jcelechat.model.sde.attributes;
import fr.guiguilechat.jcelechat.model.sde.IntAttribute;
/**
*
*/
public class MiningDurationRoleBonus
extends IntAttribute
{
public static final MiningDurationRoleBonus INSTANCE = new MiningDurationRoleBonus();
@Override
public int getId() {
return 2458;
}
@Override
public int getCatId() {
return 7;
}
@Override
public boolean getHighIsGood() {
return false;
}
@Override
public double getDefaultValue() {
return 0.0;
}
@Override
public boolean getPublished() {
return true;
}
@Override
public boolean getStackable() {
return true;
}
@Override
public String toString() {
return "MiningDurationRoleBonus";
}
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/javaxval/src/test/java/org/baeldung/ContainerValidationIntegrationTest.java | 3005 | package org.baeldung;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.OptionalInt;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.baeldung.valueextractors.ProfileValueExtractor;
import org.junit.Before;
import org.junit.Test;
public class ContainerValidationIntegrationTest {
private Validator validator;
@Before
public void setup() {
ValidatorFactory factory = Validation.byDefaultProvider().configure()
.addValueExtractor(new ProfileValueExtractor()).buildValidatorFactory();
validator = factory.getValidator();
}
@Test
public void whenEmptyAddress_thenValidationFails() {
Customer customer = new Customer();
customer.setName("John");
customer.setAddresses(Collections.singletonList(" "));
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(1, violations.size());
assertEquals("Address must not be blank", violations.iterator()
.next()
.getMessage());
}
@Test
public void whenInvalidEmail_thenValidationFails() {
CustomerMap map = new CustomerMap();
map.setCustomers(Collections.singletonMap("john", new Customer()));
Set<ConstraintViolation<CustomerMap>> violations = validator.validate(map);
assertEquals(1, violations.size());
assertEquals("Must be a valid email", violations.iterator()
.next()
.getMessage());
}
@Test
public void whenAgeTooLow_thenValidationFails() {
Customer customer = new Customer();
customer.setName("John");
customer.setAge(15);
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(1, violations.size());
}
@Test
public void whenAgeNull_thenValidationSucceeds() {
Customer customer = new Customer();
customer.setName("John");
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(0, violations.size());
}
@Test
public void whenNumberOrdersValid_thenValidationSucceeds() {
Customer customer = new Customer();
customer.setName("John");
customer.setNumberOfOrders(OptionalInt.of(1));
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(0, violations.size());
}
//@Test
public void whenProfileCompanyNameBlank_thenValidationFails() {
Customer customer = new Customer();
customer.setName("John");
Profile profile = new Profile();
profile.setCompanyName(" ");
customer.setProfile(profile);
Set<ConstraintViolation<Customer>> violations = validator.validate(customer);
assertEquals(1, violations.size());
}
}
| gpl-3.0 |
zanghongtu2006/blog | src/main/java/com/zanghongtu/blog/util/SummaryParser.java | 2801 | package com.zanghongtu.blog.util;
/**
* 摘要
*/
public class SummaryParser {
private static final int SUMMARY_LENGTH = 256;
/**
* 去除info里content 所有html字符
* 截取字符串长度256
* @param sourceStr 源字符串
* @return 截取后的字符串
*/
public static String getSummary(String sourceStr) {
if(StringUtils.isBlank(sourceStr)){
return "";
}
sourceStr= removeHTML(sourceStr);
sourceStr = sourceStr.trim().replaceAll("\t", " ").replaceAll("\n", " ")
.replaceAll("\r", " ").replaceAll(" ", " ")
.replaceAll("\\s+", " ");
if(sourceStr.length() > SUMMARY_LENGTH) {
sourceStr = sourceStr.substring(0, SUMMARY_LENGTH);
}
return sourceStr;
}
/**
* 除去所有html tag
*
* @param source 源字符串
* @return 去除HTMLisBlank标签后的字符串
*/
private static String removeHTML(String source) {
if (source == null || source.length() == 0)
return "";
StringBuilder sb = new StringBuilder();
Character IN = '<', OUT = '>';
Character currentState = OUT;
int currentIndex = 0, nextIndex = -1;
for (Character c : source.toCharArray()) {
currentIndex++;
if (currentIndex >= nextIndex)
nextIndex = -1;
if (currentState == OUT && c != OUT && c != IN && c != '\"') {
if (c == '&') {
nextIndex = checkInHTMLCode(source, currentIndex);
if (nextIndex > -1)
nextIndex = currentIndex + nextIndex;
}
if (nextIndex == -1)
sb.append(c);
}
if (c == OUT)
currentState = OUT;
if (c == IN)
currentState = IN;
}
return sb.toString();
}
/**
* RemoveHTML的辅助方法,用于检测是否遇到HTML转义符,如:
*
* @param source 源字符串
* @param start 扫描开始的位置
* @return 第一个出现转义字符的位置
*/
private static int checkInHTMLCode(String source, int start) {
int MAX_HTMLCODE_LEN = 10;
int index = 0;
String substr;
if ((source.length() - start - 1) < MAX_HTMLCODE_LEN)
substr = source.substring(start);
else {
substr = source.substring(start, start + MAX_HTMLCODE_LEN);
}
for (Character c : substr.toCharArray()) {
index++;
if (index > 1 && c == ';')
return index + 1;
if (c > 'z' || c < 'a')
return -1;
}
return -1;
}
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java | 2768 | package org.baeldung.persistence.model;
import io.katharsis.resource.annotations.JsonApiId;
import io.katharsis.resource.annotations.JsonApiRelation;
import io.katharsis.resource.annotations.JsonApiResource;
import io.katharsis.resource.annotations.SerializeType;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
@Entity
@JsonApiResource(type = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonApiId
private Long id;
private String username;
private String email;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
@JsonApiRelation(serialize=SerializeType.EAGER)
private Set<Role> roles;
public User() {
super();
}
public User(String username, String email) {
super();
this.username = username;
this.email = email;
}
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (email == null ? 0 : email.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final User user = (User) obj;
if (!email.equals(user.email)) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("User [id=").append(id).append(", username=").append(username).append(", email=").append(email).append(", roles=").append(roles).append("]");
return builder.toString();
}
} | gpl-3.0 |
carlosb1/labdoo-api | tests/ClientTest.java | 3807 | /*
* Labdoo API
Copyright (C) 2012 Labdoo team
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/>.
*
*/
import java.util.Date;
import junit.framework.Assert;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import api.APIException;
import api.LabdooClient;
import api.resources.Laptop;
//TODO Implements wrong cases
public class ClientTest {
LabdooClient client = null;
final Log log = LogFactory.getLog(ClientTest.class);
@Before
public void setUp() throws Exception {
client = new LabdooClient("http://dummy.test","asddadadasd999887");
}
@After
public void tearDown() throws Exception {
client = null;
}
@Test
public void testSayHello() throws APIException {
client.sayHello();
}
@Test
public void testAddRemoveLaptop() throws APIException {
Laptop laptop = new Laptop();
laptop.setStatus(Laptop.TAGGED_S0);
laptop.setA501c3Recip("");
laptop.setCpu(1);
laptop.setCpuType(Laptop.CPU_FIVE);
laptop.setCurrentManager("carlos.baez");
laptop.setCurrentOS("");
String nid = client.addLaptop(laptop);
// log.info("Response test: "+nid);
boolean result = client.deleteLaptop(nid);
Assert.assertTrue(result);
// log.info("It was deleted: "+result);
}
@Test
public void testGetLaptop() throws APIException {
String nid = "464";
Laptop newLaptop = client.getLaptop(nid);
Assert.assertEquals(null,newLaptop);
// log.info(newLaptop.getId());
// log.info(newLaptop.toString());
}
@Test
public void testDatesLaptop() throws APIException {
Laptop laptop = new Laptop();
laptop.setStatus(Laptop.TAGGED_S0);
Date dateDelivered = new Date();
dateDelivered.setHours(12);
dateDelivered.setMinutes(45);
dateDelivered.setSeconds(10);
dateDelivered.setMonth(3);
dateDelivered.setYear(2012);
laptop.setDateDelivered(dateDelivered);
Date dateReceived = new Date();
dateReceived.setHours(1);
dateReceived.setMinutes(41);
dateReceived.setSeconds(10);
dateReceived.setMonth(5);
dateReceived.setYear(2012);
laptop.setDateReceived(dateReceived);
Date dateRecycled = new Date();
dateRecycled.setHours(1);
dateRecycled.setMinutes(35);
dateRecycled.setSeconds(10);
dateRecycled.setMonth(4);
dateRecycled.setYear(2012);
laptop.setDateRecycled(dateRecycled);
String nid = client.addLaptop(laptop);
//Check date laptop
// Laptop laptop = client.getLaptop(nid);
// log.info(laptop);
// log.info("Response test: "+nid);
boolean result = client.deleteLaptop(nid);
// log.info("It was deleted: "+result);
Assert.assertTrue(result);
}
@Test
public void testUpdateLaptop() throws APIException {
Laptop laptop = new Laptop();
laptop.setStatus(Laptop.TAGGED_S0);
String nid = client.addLaptop(laptop);
boolean updated = client.updateLaptop(laptop);
Assert.assertTrue(updated);
//Check date laptop
// Laptop Laptop = client.getLaptop(nid);
// log.info(laptop);
// log.info("Response test: "+nid);
boolean result = client.deleteLaptop(nid);
// log.info("It was deleted: "+result);
Assert.assertTrue(result);
}
}
| gpl-3.0 |
wandora-team/wandora | src/org/wandora/application/tools/extractors/europeana/EuropeanaExtractor.java | 2752 | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2016 Wandora Team
*
* 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.wandora.application.tools.extractors.europeana;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
/**
*
* @author nlaitinen
*/
public class EuropeanaExtractor extends AbstractEuropeanaExtractor {
private EuropeanaExtractorUI ui = null;
@Override
public void execute(Wandora wandora, Context context) {
try {
if(ui == null) {
ui = new EuropeanaExtractorUI();
}
ui.open(wandora, context);
if(ui.wasAccepted()) {
WandoraTool[] extrs = null;
try{
extrs = ui.getExtractors(this);
} catch(Exception e) {
log(e.getMessage());
return;
}
if(extrs != null && extrs.length > 0) {
setDefaultLogger();
int c = 0;
log("Performing Europeana API query...");
for(int i=0; i<extrs.length && !forceStop(); i++) {
try {
WandoraTool e = extrs[i];
e.setToolLogger(getDefaultLogger());
e.execute(wandora);
setState(EXECUTE);
c++;
}
catch(Exception e) {
log(e);
}
}
log("Ready.");
}
else {
log("Couldn't find a suitable subextractor to perform or there was an error with an extractor.");
}
}
}
catch(Exception e) {
singleLog(e);
}
if(ui != null && ui.wasAccepted()) setState(WAIT);
else setState(CLOSE);
}
}
| gpl-3.0 |
openflexo-team/gina | gina-api/src/main/java/org/openflexo/gina/model/bindings/FIBVariablePathElement.java | 6703 | /**
*
* Copyright (c) 2014, Openflexo
*
* This file is part of Gina, a component of the software infrastructure
* developed at Openflexo.
*
*
* Openflexo is dual-licensed under the European Union Public License (EUPL, either
* version 1.1 of the License, or any later version ), which is available at
* https://joinup.ec.europa.eu/software/page/eupl/licence-eupl
* and the GNU General Public License (GPL, either version 3 of the License, or any
* later version), which is available at http://www.gnu.org/licenses/gpl.html .
*
* You can redistribute it and/or modify under the terms of either of these licenses
*
* If you choose to redistribute it and/or modify under the terms of the GNU GPL, you
* must include the following additional permission.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with software containing parts covered by the terms
* of EPL 1.0, the licensors of this Program grant you additional permission
* to convey the resulting work. *
*
* 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 http://www.openflexo.org/license.html for details.
*
*
* Please contact Openflexo (openflexo-contacts@openflexo.org)
* or visit www.openflexo.org if you need additional information.
*
*/
package org.openflexo.gina.model.bindings;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.Type;
import java.util.logging.Logger;
import org.openflexo.connie.BindingEvaluationContext;
import org.openflexo.connie.BindingModel;
import org.openflexo.connie.binding.IBindingPathElement;
import org.openflexo.connie.binding.SimplePathElement;
import org.openflexo.connie.exception.NullReferenceException;
import org.openflexo.connie.exception.TypeMismatchException;
import org.openflexo.connie.type.TypeUtils;
import org.openflexo.gina.model.FIBVariable;
import org.openflexo.gina.view.FIBView;
public class FIBVariablePathElement extends SimplePathElement implements PropertyChangeListener {
private static final Logger logger = Logger.getLogger(FIBVariablePathElement.class.getPackage().getName());
private Type lastKnownType = null;
private final FIBVariable<?> fibVariable;
public FIBVariablePathElement(IBindingPathElement parent, FIBVariable<?> fibVariable) {
super(parent, fibVariable.getName(), fibVariable.getType());
this.fibVariable = fibVariable;
lastKnownType = fibVariable.getType();
}
@Override
public void activate() {
super.activate();
if (fibVariable != null && fibVariable.getPropertyChangeSupport() != null) {
fibVariable.getPropertyChangeSupport().addPropertyChangeListener(this);
}
}
@Override
public void desactivate() {
if (fibVariable != null && fibVariable.getPropertyChangeSupport() != null) {
fibVariable.getPropertyChangeSupport().removePropertyChangeListener(this);
}
super.desactivate();
}
public FIBVariable<?> getFIBVariable() {
return fibVariable;
}
@Override
public String getLabel() {
return getPropertyName();
}
@Override
public String getTooltipText(Type resultingType) {
return fibVariable.getDescription();
}
@Override
public Type getType() {
return getFIBVariable().getType();
}
@Override
public Object getBindingValue(Object target, BindingEvaluationContext context) throws TypeMismatchException, NullReferenceException {
// System.out.println("j'evalue " + fibVariable + " pour " + target);
// System.out.println("il s'agit de " + fibVariable.getValue());
if (target instanceof FIBView) {
Object returned = ((FIBView<?, ?>) target).getVariableValue(fibVariable);
// System.out.println("returned=" + returned);
if (returned == null || TypeUtils.isOfType(returned, getType())) {
// System.out.println("Et je retourne");
return returned;
}
else {
// System.out.println("Ouhlala, on me demande " + getType() + " mais j'ai " + returned.getClass());
// System.out.println("On s'arrete");
return null;
}
// System.out.println("je retourne " + ((FIBView)
// target).getVariableValue(fibVariable));
// return ((FIBView) target).getVariableValue(fibVariable);
}
logger.warning("Please implement me, target=" + target + " context=" + context);
return null;
}
@Override
public void setBindingValue(Object value, Object target, BindingEvaluationContext context)
throws TypeMismatchException, NullReferenceException {
if (target instanceof FIBView) {
((FIBView) target).setVariableValue(fibVariable, value);
return;
}
logger.warning("Please implement me, target=" + target + " context=" + context);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getSource() == getFIBVariable()) {
if (evt.getPropertyName().equals(FIBVariable.NAME_KEY)) {
// System.out.println("Notify name changing for " +
// getFlexoProperty() + " new=" + getVariableName());
getPropertyChangeSupport().firePropertyChange(NAME_PROPERTY, evt.getOldValue(), getLabel());
fibVariable.getOwner().getBindingModel().getPropertyChangeSupport()
.firePropertyChange(BindingModel.BINDING_PATH_ELEMENT_NAME_CHANGED, evt.getOldValue(), getLabel());
}
if (evt.getPropertyName().equals(FIBVariable.TYPE_KEY)) {
Type newType = getFIBVariable().getType();
if (lastKnownType == null || !lastKnownType.equals(newType)) {
getPropertyChangeSupport().firePropertyChange(TYPE_PROPERTY, lastKnownType, newType);
fibVariable.getOwner().getBindingModel().getPropertyChangeSupport()
.firePropertyChange(BindingModel.BINDING_PATH_ELEMENT_TYPE_CHANGED, lastKnownType, newType);
lastKnownType = newType;
}
}
if (lastKnownType != getType()) {
// We might arrive here only in the case of a FIBVariable does
// not correctely notify
// its type change. We warn it to 'tell' the developper that
// such notification should be done
// in FlexoProperty (see IndividualProperty for example)
logger.warning("Detecting un-notified type changing for FIBVariable " + fibVariable + " from " + lastKnownType + " to "
+ getType() + ". Trying to handle case.");
getPropertyChangeSupport().firePropertyChange(TYPE_PROPERTY, lastKnownType, getType());
fibVariable.getOwner().getBindingModel().getPropertyChangeSupport()
.firePropertyChange(BindingModel.BINDING_PATH_ELEMENT_TYPE_CHANGED, lastKnownType, getType());
lastKnownType = getType();
}
}
}
}
| gpl-3.0 |
QuarterCode/QuarterBukkit | plugin/src/main/java/com/quartercode/quarterbukkit/util/QuarterBukkitExceptionListener.java | 2265 | /*
* This file is part of QuarterBukkit-Plugin.
* Copyright (c) 2012 QuarterCode <http://www.quartercode.com/>
*
* QuarterBukkit-Plugin 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.
*
* QuarterBukkit-Plugin 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 QuarterBukkit-Plugin. If not, see <http://www.gnu.org/licenses/>.
*/
package com.quartercode.quarterbukkit.util;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import com.quartercode.quarterbukkit.api.exception.InstallException;
import com.quartercode.quarterbukkit.api.exception.InternalException;
public class QuarterBukkitExceptionListener implements Listener {
private final Plugin plugin;
public QuarterBukkitExceptionListener(Plugin plugin) {
this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void installException(InstallException exception) {
if (exception.getCauser() != null) {
exception.getCauser().sendMessage(ChatColor.RED + "Can't update " + plugin.getName() + ": " + exception.getMessage());
if (exception.getCause() != null) {
exception.getCauser().sendMessage(ChatColor.RED + "Reason: " + exception.getCause().toString());
}
} else {
plugin.getLogger().warning("Can't update " + plugin.getName() + ": " + exception.getMessage());
if (exception.getCause() != null) {
plugin.getLogger().warning("Reason: " + exception.getCause().toString());
}
}
}
@EventHandler
public void internalException(InternalException exception) {
exception.getCause().printStackTrace();
}
}
| gpl-3.0 |
Dominik-Licari/schoolwork | src/Schuler.java | 758 | public class Schuler
{
private String name;
private int test1;
private int test2;
private int test3;
public Schuler()
{
name = "";
test1 = 0;
test2 = 0;
test3 = 0;
}
public void setName(String nm)
{
name = nm;
}
public String getName()
{
return name;
}
public void setPunkte(int i, int punkte)
{
if (i==1) test1=punkte;
if (i==2) test2=punkte;
if (i==3) test3=punkte;
}
public int getPunkte(int i)
{
if (i==1) return test1;
if (i==2) return test2;
if (i==3) return test3;
return -1;
}
public int getAverage()
{
return (int)Math.round((test1+test2+test3)/3.0);
}
public String toString()
{
return "Name: "+name+"\nTest 1: "+test1+"\nTest 2: "+test2+"\nTest 3: "+test3+"\nAverage: " +getAverage();
}
}
| gpl-3.0 |