repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
ViolentMod/ViolentCoreOld
src/main/java/violentninjad/violentcoreold/item/ModItems.java
498
package violentninjad.violentcoreold.item; import cpw.mods.fml.common.registry.GameRegistry; import violentninjad.violentcoreold.reference.ItemIds; import violentninjad.violentcoreold.reference.ItemNames; public class ModItems { public static ItemViolentMods tabPicture; public static void init() { //Item Initialisation tabPicture = new ItemTabPicture(ItemIds.TAB_PICTURE); //Registering Items GameRegistry.registerItem(tabPicture, "items." + ItemNames.TAB_PICTURE_NAME); } }
gpl-3.0
adam-roughton/CrowdHammer
src/main/java/com/adamroughton/crowdhammer/worker/user/User.java
4493
/* * 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.worker.user; import java.util.Map; import java.util.Objects; import com.adamroughton.crowdhammer.Client; import com.adamroughton.crowdhammer.ScenarioClock; import com.adamroughton.crowdhammer.TestException; import com.adamroughton.crowdhammer.UserContext; import com.adamroughton.crowdhammer.UserScenarioInstance; import com.adamroughton.crowdhammer.common.CrowdHammerException; import com.adamroughton.crowdhammer.common.TimeService; import com.adamroughton.crowdhammer.util.event.UnsupportedEventException; import com.adamroughton.crowdhammer.util.event.statemachine.StateException; import com.adamroughton.crowdhammer.worker.TestEntryHelper; import com.lmax.disruptor.EventHandler; public class User<C extends Client> implements EventHandler<UserEvent> { private final TestEntryHelper<C> _testEntryHelper; private final UserContext _userContext; private final C _client; private final TimeService _timeService; /** * We don't want all users active for all tests as we attempt * to simulate some fixed user load - each worker is instructed * to simulate n users, and the remaining will have this flag set * to false */ private boolean _isActive = false; private UserScenarioInstance _userScenarioInstance; public User( final TestEntryHelper<C> testEntryHelper, final UserContext context, final TimeService timeService) throws TestException { _testEntryHelper = Objects.requireNonNull(testEntryHelper); _userContext = Objects.requireNonNull(context); _timeService = Objects.requireNonNull(timeService); _client = testEntryHelper.createClient(context.getGlobalUserIndex()); } @Override public void onEvent(final UserEvent event, long sequence, boolean isEndOfBatch) throws Exception { try { switch (event.getEventType()) { case START_SCENARIO: startScenario(event.getScenarioName(), event.getReqWorkerSimCount(), event.getScenarioContext()); break; case EXEC_SET_UP_PHASE: executeSetUpPhase(event.getSetUpPhaseIndex()); break; case PREPARE_TEST_PHASE: prepareTestPhase(); break; case EXEC_TEST_PHASE: executeTestPhase(event.getStartTime()); break; default: throw new UnsupportedEventException(String.format("Unknown user event '%1s'", event.getEventType().name())); } } catch (CrowdHammerException e) { // put the exception on the event for the user monitor event.setException(e); } } private void startScenario(final String scenarioName, final int reqWorkerSimCount, final Map<String, String> scenarioContext) throws Exception { if (_userScenarioInstance != null) throw new StateException("A scenario is already active."); // only simulate the required number of users on this worker _isActive = _userContext.getLocalUserIndex() < reqWorkerSimCount; _userScenarioInstance = _testEntryHelper.createScenarioInstance( scenarioName, _client, _userContext, scenarioContext); } private void executeSetUpPhase(final int phaseIndex) throws Exception { ensureActiveScenario(); if (_isActive) { _userScenarioInstance.executeSetUpPhase(phaseIndex); } } private void prepareTestPhase() throws Exception { ensureActiveScenario(); if (_isActive) { _userScenarioInstance.prepareTest(); } } private void executeTestPhase(long startTime) throws Exception { ensureActiveScenario(); if (_isActive) { ScenarioClock scenarioClock = _timeService.createScenarioClock(startTime); _userScenarioInstance.executeTest(scenarioClock); } _userScenarioInstance = null; } private void ensureActiveScenario() throws StateException { if (_userScenarioInstance == null) throw new StateException("A scenario is not active."); } }
gpl-3.0
Ineedajob/RSBot
src/org/rsbot/event/events/TextPaintEvent.java
1739
package org.rsbot.event.events; import org.rsbot.event.EventMulticaster; import org.rsbot.event.listeners.TextPaintListener; import java.awt.*; import java.awt.geom.AffineTransform; import java.util.EventListener; /** * An event that specifies a line index and graphics * object on which a TextPaintListener should paint a * line of text. */ public class TextPaintEvent extends RSEvent { private static final long serialVersionUID = 6634362568916377937L; public Graphics graphics; public int idx; @Override public void dispatch(final EventListener el) { final Graphics2D g2d = (Graphics2D) graphics; // Backup settings // Which is needed, otherwise if some script does a transform without // cleaning // every other graphics call will use the same transformations. final Color s_background = g2d.getBackground(); final Shape s_clip = g2d.getClip(); final Color s_color = g2d.getColor(); final Composite s_composite = g2d.getComposite(); final Font s_font = g2d.getFont(); final Paint s_paint = g2d.getPaint(); final RenderingHints s_renderingHints = g2d.getRenderingHints(); final Stroke s_stroke = g2d.getStroke(); final AffineTransform s_transform = g2d.getTransform(); // Dispatch the event idx = ((TextPaintListener) el).drawLine(graphics, idx); // Restore settings g2d.setBackground(s_background); g2d.setClip(s_clip); g2d.setColor(s_color); g2d.setComposite(s_composite); g2d.setFont(s_font); g2d.setPaint(s_paint); g2d.setRenderingHints(s_renderingHints); g2d.setStroke(s_stroke); g2d.setTransform(s_transform); } @Override public long getMask() { return EventMulticaster.TEXT_PAINT_EVENT; } }
gpl-3.0
michoo/kubeek
kubeek-core/src/main/java/com/kubeek/message/factory/MailMessageFactory.java
442
package com.kubeek.message.factory; import com.kubeek.message.mail.MailMessageSimple; import com.kubeek.sdk.message.factory.KMailMessageFactory; import com.kubeek.sdk.message.mail.KMailMessage; public class MailMessageFactory implements KMailMessageFactory { @Override public KMailMessage getSimpleMessage(String recipient, String subject, String message) { return new MailMessageSimple(recipient,subject,message); } }
gpl-3.0
nivertius/repositable
src/main/java/org/perfectable/repositable/EntryLister.java
155
package org.perfectable.repositable; public interface EntryLister { interface Consumer { void entry(String name); } void list(Consumer consumer); }
gpl-3.0
gg-net/dwoss
ui/receipt/src/test/java/eu/ggnet/dwoss/receipt/ui/tryout/ReceiptTryout.java
6583
/* * Copyright (C) 2021 GG-Net GmbH * * 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 eu.ggnet.dwoss.receipt.ui.tryout; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.time.LocalDateTime; import java.time.Month; import java.util.ArrayList; import java.util.List; import javax.enterprise.inject.Instance; import javax.enterprise.inject.se.SeContainer; import javax.enterprise.inject.se.SeContainerInitializer; import javax.swing.*; import eu.ggnet.dwoss.core.system.util.Utils; import eu.ggnet.dwoss.core.widget.Dl; import eu.ggnet.dwoss.core.widget.auth.Guardian; import eu.ggnet.dwoss.core.widget.cdi.WidgetProducers; import eu.ggnet.dwoss.core.widget.dl.RemoteDl; import eu.ggnet.dwoss.core.widget.dl.RemoteLookup; import eu.ggnet.dwoss.mandator.api.Mandators; import eu.ggnet.dwoss.mandator.spi.CachedMandators; import eu.ggnet.dwoss.receipt.ee.*; import eu.ggnet.dwoss.receipt.ui.ProductUiBuilder; import eu.ggnet.dwoss.receipt.ui.cap.*; import eu.ggnet.dwoss.receipt.ui.product.SimpleView.CreateOrEdit; import eu.ggnet.dwoss.receipt.ui.shipment.ShipmentEditView; import eu.ggnet.dwoss.receipt.ui.tryout.stub.ProductProcessorStub.EditProduct; import eu.ggnet.dwoss.receipt.ui.tryout.stub.*; import eu.ggnet.dwoss.spec.ee.SpecAgent; import eu.ggnet.dwoss.stock.ee.StockAgent; import eu.ggnet.dwoss.stock.spi.ActiveStock; import eu.ggnet.dwoss.uniqueunit.ee.UniqueUnitAgent; import eu.ggnet.dwoss.uniqueunit.ee.entity.Product; import eu.ggnet.dwoss.uniqueunit.ee.entity.UniqueUnit; import eu.ggnet.saft.core.*; import eu.ggnet.saft.core.impl.Swing; /** * * @author oliver.guenther */ public class ReceiptTryout { public static void main(String[] args) throws Exception { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SeContainerInitializer ci = SeContainerInitializer.newInstance(); ci.addPackages(ReceiptTryout.class); ci.addPackages(WidgetProducers.class); ci.addPackages(true, ProductUiBuilder.class); // receipt.ui ci.disableDiscovery(); SeContainer container = ci.initialize(); Instance<Object> instance = container.getBeanManager().createInstance(); Saft saft = instance.select(Saft.class).get(); saft.addOnShutdown(() -> container.close()); UiCore.initGlobal(saft); // Transition. RemoteDl remote = instance.select(RemoteDl.class).get(); ProductProcessorStub pp = new ProductProcessorStub(); remote.add(ProductProcessor.class, pp); remote.add(SpecAgent.class, pp.specAgent()); remote.add(StockAgent.class, pp.stockAgent()); remote.add(Mandators.class, pp.cachedMandators()); remote.add(UnitProcessor.class, pp.unitProcessor()); remote.add(UnitSupporter.class, pp.unitSupporter()); remote.add(UniqueUnitAgent.class, pp.uniqueUnitAgent()); Dl.local().add(CachedMandators.class, pp.cachedMandators()); Dl.local().add(RemoteLookup.class, new RemoteLookupStub()); Dl.local().add(Guardian.class, new GuardianStub()); StockSpiStub su = new StockSpiStub(); su.setActiveStock(pp.stocks.get(1).toPicoStock()); // Hint: pp.editAbleRefurbishId is allways on stock.id=0 Dl.local().add(ActiveStock.class, su); JFrame mainFrame = UiUtil.startup(() -> { JMenuBar menubar = new JMenuBar(); JMenu receipt = new JMenu("Aufnahme"); receipt.add(instance.select(OpenCpuListAction.class).get()); receipt.add(instance.select(OpenGpuListAction.class).get()); receipt.add(instance.select(OpenSpecListAction.class).get()); receipt.add(instance.select(OpenShipmentListAction.class).get()); receipt.add(instance.select(EditUnitAction.class).get()); menubar.add(receipt); JButton openShipmentUpdateView = new JButton("Open ShipmentUpdateView"); openShipmentUpdateView.addActionListener(a -> saft.build().fx().eval(ShipmentEditView.class).cf().thenAccept(System.out::println)); JButton editOneUnit = new JButton("Eine SopoNr bearbeiten"); editOneUnit.addActionListener(e -> instance.select(EditUnitAction.class).get().editUnit(pp.editAbleRefurbishId).handle(saft.handler())); JMenu editProduct = new JMenu("Artikel direkt bearbeiten"); for (EditProduct ep : pp.editProducts) { JMenuItem m = new JMenuItem(ep.description()); m.addActionListener(e -> { instance.select(ProductUiBuilder.class).get() .createOrEditPart(() -> new CreateOrEdit(ep.manufacturer(), ep.partNo())) .handle(saft.handler()); }); editProduct.add(m); } menubar.add(editProduct); JPanel buttonPanel = new JPanel(new FlowLayout()); buttonPanel.add(openShipmentUpdateView); buttonPanel.add(editOneUnit); DefaultListModel<String> model = new DefaultListModel<>(); model.addAll(prepareHelper(pp.uniqueUnitAgent())); JList<String> list = new JList<>(model); JPanel main = new JPanel(new BorderLayout()); main.add(menubar, BorderLayout.NORTH); main.add(new JScrollPane(list), BorderLayout.CENTER); main.add(buttonPanel, BorderLayout.SOUTH); return main; }); saft.core(Swing.class).initMain(mainFrame); System.out.println("DAte:" + Utils.toDate(LocalDateTime.of(2000, Month.JANUARY, 1, 0, 0))); } public static List<String> prepareHelper(UniqueUnitAgent agent) { List<String> info = new ArrayList<>(); agent.findAll(Product.class).forEach(p -> info.add(p.getPartNo() + " - " + p.getName())); agent.findAll(UniqueUnit.class).forEach(uu -> info.add(uu.getRefurbishId() + "|" + uu.getSerial())); return info; } }
gpl-3.0
zeminlu/comitaco
tests/icse/bintree/set3/BinTreeInsert4Bug4Ix5Dx16Dx20D.java
7037
package icse.bintree.set3; import icse.bintree.BinTreeNode; public class BinTreeInsert4Bug4Ix5Dx16Dx20D { /*@ @ invariant (\forall BinTreeNode n; @ \reach(root, BinTreeNode, left + right).has(n) == true; @ \reach(n.right, BinTreeNode, right + left).has(n) == false && @ \reach(n.left, BinTreeNode, left + right).has(n) == false); @ @ invariant (\forall BinTreeNode n; @ \reach(root, BinTreeNode, left + right).has(n) == true; @ (\forall BinTreeNode m; @ \reach(n.left, BinTreeNode, left + right).has(m) == true; @ m.key <= n.key) && @ (\forall BinTreeNode m; @ \reach(n.right, BinTreeNode, left + right).has(m) == true; @ m.key > n.key)); @ @ invariant size == \reach(root, BinTreeNode, left + right).int_size(); @ @ invariant (\forall BinTreeNode n; @ \reach(root, BinTreeNode, left + right).has(n) == true; @ (n.left != null ==> n.left.parent == n) && (n.right != null ==> n.right.parent == n)); @ @ invariant root != null ==> root.parent == null; @*/ public /*@nullable@*/icse.bintree.BinTreeNode root; public int size; public BinTreeInsert4Bug4Ix5Dx16Dx20D() { } /*@ @ requires true; @ @ ensures (\result == true) <==> (\exists BinTreeNode n; @ \reach(root, BinTreeNode, left+right).has(n) == true; @ n.key == k); @ @ ensures (\forall BinTreeNode n; @ \reach(root, BinTreeNode, left+right).has(n); @ \old(\reach(root, BinTreeNode, left+right)).has(n)); @ @ ensures (\forall BinTreeNode n; @ \old(\reach(root, BinTreeNode, left+right)).has(n); @ \reach(root, BinTreeNode, left+right).has(n)); @ @ signals (RuntimeException e) false; @*/ public boolean contains( int k ) { icse.bintree.BinTreeNode current = root; //mutGenLimit 0 //@decreasing \reach(current, BinTreeNode, left+right).int_size(); while (current != null) { //mutGenLimit 0 if (k < current.key) { //mutGenLimit 0 current = current.left; //mutGenLimit 0 } else { if (k > current.key) { //mutGenLimit 0 current = current.right; //mutGenLimit 0 } else { return true; //mutGenLimit 0 } } } return false; //mutGenLimit 0 } /*@ @ requires newBinTreeNode != null; @ requires newBinTreeNode.key == k; @ requires newBinTreeNode.left == null; @ requires newBinTreeNode.right == null; @ requires \reach(root, BinTreeNode, left+right).has(newBinTreeNode) == false; @ @ ensures (\exists BinTreeNode n; @ \old(\reach(root, BinTreeNode, left + right)).has(n) == true; @ n.key == k) ==> size == \old(size); @ @ ensures (\forall BinTreeNode n; @ \old(\reach(root, BinTreeNode, left + right)).has(n) == true; @ n.key != k) ==> size == \old(size) + 1; @ @ ensures (\exists BinTreeNode n; @ \reach(root, BinTreeNode, left + right).has(n) == true; @ n.key == k); @ @ signals (RuntimeException e) false; @*/ public boolean insert( int k, BinTreeNode newBinTreeNode ) { icse.bintree.BinTreeNode y = null; //mutGenLimit 0 icse.bintree.BinTreeNode x = root; //mutGenLimit 0 //@decreasing \reach(x, BinTreeNode, left+right).int_size(); while (x != null) { //mutGenLimit 0 y.right = x; //mutGenLimit 1 if (k < x.parent.key) { //mutGenLimit 1 x = x.left; //mutGenLimit 0 } else { if (k > x.key) { //mutGenLimit 0 x = x.right; //mutGenLimit 0 } else { return false; //mutGenLimit 0 } } } x = newBinTreeNode; //mutGenLimit 0 x.key = -k; //mutGenLimit 1 if (y == null) { //mutGenLimit 0 root = x; //mutGenLimit 0 } else { if (k < ++y.key) { //mutGenLimit 1 y.left = x; //mutGenLimit 0 } else { y.right = x; //mutGenLimit 0 } } x.parent = y; //mutGenLimit 0 size += 1; //mutGenLimit 0 return true; //mutGenLimit 0 } /*@ @ requires (\forall BinTreeNode n1; @ \reach(root, BinTreeNode, left+right).has(n1); @ (\forall BinTreeNode m1; @ \reach(root, BinTreeNode, left+right).has(m1); n1 != m1 ==> n1.key != m1.key)); @ @ ensures (\exists BinTreeNode n2; @ \old(\reach(root, BinTreeNode, left + right)).has(n2) == true; @ \old(n2.key) == element) @ <==> \result == true; @ @ ensures (\forall BinTreeNode n3; @ \reach(root, BinTreeNode, left+right).has(n3); @ n3.key != element); @ @ signals (RuntimeException e) false; @*/ public boolean remove( int element ) { //mutGenLimit 0 icse.bintree.BinTreeNode node = root; //mutGenLimit 0 while (node != null && node.key != element) { //mutGenLimit 0 if (element < node.key) { //mutGenLimit 0 node = node.left; //mutGenLimit 0 } else { if (element > node.key) { //mutGenLimit 0 node = node.right; //mutGenLimit 0 } } } if (node == null) { //mutGenLimit 0 return false; //mutGenLimit 0 } else { if (node.left != null && node.right != null) { //mutGenLimit 0 icse.bintree.BinTreeNode predecessor = node.left; //mutGenLimit 0 if (predecessor != null) { //mutGenLimit 0 while (predecessor.right != null) { //mutGenLimit 0 predecessor = predecessor.right; //mutGenLimit 0 } } node.key = predecessor.key; //mutGenLimit 0 node = predecessor; //mutGenLimit 0 } } icse.bintree.BinTreeNode pullUp; //mutGenLimit 0 if (node.left == null) { //mutGenLimit 0 pullUp = node.right; //mutGenLimit 0 } else { pullUp = node.left; //mutGenLimit 0 } if (node == root) { //mutGenLimit 0 root = pullUp; //mutGenLimit 0 if (pullUp != null) { //mutGenLimit 0 pullUp.parent = null; //mutGenLimit 0 } } else { if (node.parent.left == node) { //mutGenLimit 0 node.parent.left = pullUp; //mutGenLimit 0 if (pullUp != null) { //mutGenLimit 0 pullUp.parent = node.parent; //mutGenLimit 0 } } else { node.parent.right = pullUp; //mutGenLimit 0 if (pullUp != null) { //mutGenLimit 0 pullUp.parent = node.parent; //mutGenLimit 0 } } } size--; //mutGenLimit 0 return true; //mutGenLimit 0 } }
gpl-3.0
nrv/NHerveFlickrLib
src/main/java/name/herve/flickrlib/FlickrImageSize.java
1525
/* * Copyright 2011-2013 Nicolas Hervé. * * This file is part of FlickrLib. * * FlickrLib 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. * * FlickrLib 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 FlickrLib. If not, see <http://www.gnu.org/licenses/>. */ package name.herve.flickrlib; /** * * @author Nicolas HERVE - n.herve@laposte.net */ public class FlickrImageSize { private String label; private int width; private int height; private String source; private String url; public FlickrImageSize() { super(); } public String getLabel() { return label; } void setLabel(String label) { this.label = label; } public int getWidth() { return width; } void setWidth(int width) { this.width = width; } public int getHeight() { return height; } void setHeight(int height) { this.height = height; } public String getSource() { return source; } void setSource(String source) { this.source = source; } public String getUrl() { return url; } void setUrl(String url) { this.url = url; } }
gpl-3.0
toxeh/ExecuteQuery
java/src/org/executequery/actions/othercommands/RestoreDefaultsCommand.java
1731
/* * RestoreDefaultsCommand.java * * Copyright (C) 2002-2013 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.actions.othercommands; import java.awt.event.ActionEvent; import org.executequery.gui.prefs.UserPreferenceFunction; /* ---------------------------------------------------------- * CVS NOTE: Changes to the CVS repository prior to the * release of version 3.0.0beta1 has meant a * resetting of CVS revision numbers. * ---------------------------------------------------------- */ /** <p>Restore system defaults command for respective * preferences panels. * * @author Takis Diakoumis * @version $Revision: 160 $ * @date $Date: 2013-02-08 17:15:04 +0400 (пт, 08 фев 2013) $ */ public class RestoreDefaultsCommand extends AbstractBaseCommand { private UserPreferenceFunction frame; public RestoreDefaultsCommand(UserPreferenceFunction frame) { super("Restore Defaults"); this.frame = frame; } public void execute(ActionEvent e) { frame.restoreDefaults(); } }
gpl-3.0
WeiMei-Tian/editor-sql
app/src/main/java/com/gmobile/sqliteeditor/model/AppDataModel.java
5204
package com.gmobile.sqliteeditor.model; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import com.gmobile.data.DataFactory; import com.gmobile.data.FileInfo; import com.gmobile.data.constant.DataConstant; import com.gmobile.data.constant.ResultConstant; import com.gmobile.sqliteeditor.assistant.Utils; import com.gmobile.sqliteeditor.constant.Constant; import com.gmobile.sqliteeditor.model.bean.AppDataObject; import com.gmobile.sqliteeditor.orm.dao.model.AppData; import com.gmobile.sqliteeditor.orm.helper.DbUtils; import com.gmobile.sqliteeditor.ui.event.AppDataType; import com.gmobile.sqliteeditor.ui.event.FileDataType; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Created by admin on 2016/11/22. */ public class AppDataModel extends DataModel<AppDataObject> { private static PackageManager mPm; public AppDataModel(Context context, Bundle bundle) { super(context, bundle); mPm = context.getPackageManager(); } @Override public void loadData() { AppDataType appDataType = (AppDataType) args.getSerializable(Constant.FILE_DATA_TYPE); if (appDataType == null) return; switch (appDataType) { case gointo: int position = args.getInt(Constant.CLICK_POSITION, -1); gotoClickPosition(position); break; case init: case goback: getAllAppNames(); break; case refreshData: // currentPath = args.getString(Constant.BACK_PATH); // refreshCurrentPath(currentPath); break; } } private void refreshCurrentPath(String currentPath) { datas.clear(); } private void gotoClickPosition(int position) { String pkgName = datas.get(position).getAppPackageName(); String dbDirPath = "/data/data/" + pkgName + "/databases"; Log.e("sg", "root----dir-----" + dbDirPath); //TODO 应在主线程做root if (Utils.isRoot(context)) { FileInfo fileInfo = DataFactory.createObject(DataConstant.MEMORY_DATA_ID, dbDirPath); datas.clear(); if (fileInfo.exists() == ResultConstant.EXIST){ List<FileInfo> children = fileInfo.getList(false);//去掉隐藏文件 if (children != null) { datas = listFiles(pkgName, children); } } } } public List<AppDataObject> listFiles(String pkgName, List<FileInfo> children) { List<AppDataObject> objects = new ArrayList<>(); AppDataObject object; for (FileInfo f : children) { object = new AppDataObject(); object.setName(f.getName()); object.setPath(f.getPath()); object.setAppPackageName(pkgName); object.setLastModified(f.getLastModified()); object.setSize(f.getSize()); objects.add(object); } return objects; } public void getAllAppNames() { List<AppData> bList = DbUtils.getAppDataHelper().getAppList(); if (bList != null && bList.size() > 0) { Log.e("sg", "读取App缓存"); for (AppData d : bList) { datas.add(new AppDataObject(d)); } return; } Log.e("sg", "现取App数据"); List<PackageInfo> aiList; try { aiList = mPm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES); } catch (Exception e) { e.printStackTrace(); return; } AppData appData; AppDataObject appDataObject; List<AppData> cacheList = new ArrayList<>(); boolean isSystem; for (PackageInfo packageInfo : aiList) { isSystem = isSystemApp(packageInfo.applicationInfo); if (isSystem){ continue; } appData = initApp(packageInfo, isSystem); if (appData != null) { cacheList.add(appData); appDataObject = new AppDataObject(appData); datas.add(appDataObject); } } DbUtils.getAppDataHelper().saveOrUpdate(cacheList); } private AppData initApp(PackageInfo packageInfo, boolean isSystem) { AppData appData = new AppData(); appData.setAppName(packageInfo.applicationInfo.loadLabel(mPm).toString()); appData.setAppPackageName(packageInfo.packageName); appData.setLastModified(packageInfo.firstInstallTime); appData.setIsSystem(isSystem ? Constant.SYSTEM_APP : Constant.USER_APP); return appData; } private boolean isSystemApp(ApplicationInfo info) { if ((info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) { return false; } else if ((info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) { return false; } return true; } }
gpl-3.0
grtlinux/TAIN_LUCYCRON
APP_LUCYCRON_01/src/tain/kr/com/proj/lucycron/v01/main/server/MainServer.java
3136
/** * Copyright 2014, 2015, 2016, 2017 TAIN, Inc. all rights reserved. * * Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3, 29 June 2007 (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.gnu.org/licenses/ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ----------------------------------------------------------------- * Copyright 2014, 2015, 2016, 2017 TAIN, Inc. * */ package tain.kr.com.proj.lucycron.v01.main.server; import org.apache.log4j.Logger; /** * Code Templates > Comments > Types * * <PRE> * -. FileName : MainServer.java * -. Package : tain.kr.com.proj.lucycron.v01.main.server * -. Comment : * -. Author : taincokr * -. First Date : 2017. 4. 10. {time} * </PRE> * * @author taincokr * */ public class MainServer { private static boolean flag = true; private static final Logger log = Logger.getLogger(MainServer.class); /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /* * constructor */ public MainServer() { if (flag) log.debug(">>>>> in class " + this.getClass().getSimpleName()); } /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /* * static test method */ private static void test01(String[] args) throws Exception { if (flag) new MainServer(); if (flag) { } } /* * main method */ public static void main(String[] args) throws Exception { if (flag) log.debug(">>>>> " + new Object() { }.getClass().getEnclosingClass().getName()); if (flag) test01(args); } }
gpl-3.0
jackybourgeois/active-home-energy
org.active-home.energy.library/src/main/java/org/activehome/energy/library/etp/LinearETP.java
1128
package org.activehome.energy.library.etp; /* * #%L * Active Home :: Energy :: Library * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2016 Active Home Project * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ /** * Linear Energy Tariff Policy. * Price = kWh * rate * * @author Jacky Bourgeois * @version %I%, %G% */ public class LinearETP extends EnergyTariffPolicy { @Override public double calculate(double energyKWh, double rate) { return energyKWh * rate; } }
gpl-3.0
fmntf/BdmCrawler
test/it/unisi/bdm/crawler/ExtensionUrlInspectorTest.java
1908
/** * This file is part of BdmCrawler. * BdmCrawler 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. * * BdmCrawler 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 BdmCrawler. If not, see <http://www.gnu.org/licenses/>. */ package it.unisi.bdm.crawler; import org.junit.Test; import static org.junit.Assert.*; public class ExtensionUrlInspectorTest { @Test public void allowsUrlThatHopefullyWillContainHtml() { ExtensionUrlInspector inspector = new ExtensionUrlInspector(); assertTrue(inspector.isLegal("http://www.google.it")); assertTrue(inspector.isLegal("http://www.google.it/")); assertTrue(inspector.isLegal("http://www.google.it/index.html")); assertTrue(inspector.isLegal("http://www.google.it/index.htm")); assertTrue(inspector.isLegal("http://www.google.it/index.php")); assertTrue(inspector.isLegal("http://www.google.it/index.asp")); assertTrue(inspector.isLegal("http://www.google.it/index.aspx")); assertTrue(inspector.isLegal("http://www.google.it/index.jsp")); } @Test public void blocksUrlsWithNonHtmlContent() { ExtensionUrlInspector inspector = new ExtensionUrlInspector(); assertFalse(inspector.isLegal("http://www.google.it/logo.png")); assertFalse(inspector.isLegal("http://www.google.it/logo.jpg")); assertFalse(inspector.isLegal("http://www.google.it/file.zip")); assertFalse(inspector.isLegal("http://www.google.it/file.tar")); assertFalse(inspector.isLegal("smb://file")); } }
gpl-3.0
jordantdavis/RESTfulSensorNetwork
android/RSN/client/src/main/java/rsn/client/settings/RsnPreferenceActivity.java
396
package rsn.client.settings; import android.os.Bundle; import android.preference.PreferenceActivity; import rsn.client.R; /** * Created by Quinn on 4/27/14. */ public class RsnPreferenceActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.prefs); } }
gpl-3.0
marckdx/mtcs
src/Control/Grafico.java
3312
/* * Here comes the text of your license * Each line should be prefixed with * */ package Control; import java.awt.Color; import java.util.ArrayList; import javax.swing.JPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.general.DatasetGroup; /** * * @author Marco */ public class Grafico { public static void criaAcuracia(ArrayList<Resultado> resultados, JPanel painel) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (Resultado resultado : resultados) { dataset.setValue(resultado.taxaAcerto, "Marks", resultado.nome); } JFreeChart chart = ChartFactory.createBarChart("Acurácia", "Classificador", "Pontuação", dataset, PlotOrientation.HORIZONTAL, false, true, false); CategoryPlot p = chart.getCategoryPlot(); p.setRangeGridlinePaint(Color.LIGHT_GRAY); ChartPanel cp = new ChartPanel(chart); cp.setDomainZoomable(true); painel.add(cp); painel.validate(); } public static void criaTaxaErro(ArrayList<Resultado> resultados, JPanel painel) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (Resultado resultado : resultados) { dataset.setValue(resultado.taxaErro, "Marks", resultado.nome); } JFreeChart chart = ChartFactory.createBarChart("Taxa Erro", "Classificador", "Pontuação", dataset, PlotOrientation.HORIZONTAL, false, true, false); CategoryPlot p = chart.getCategoryPlot(); p.setRangeGridlinePaint(Color.LIGHT_GRAY); ChartPanel cp = new ChartPanel(chart); cp.setDomainZoomable(true); painel.add(cp); painel.validate(); } public static void criaPrecisao(ArrayList<Resultado> resultados, JPanel painel) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (Resultado resultado : resultados) { dataset.setValue(resultado.precisao, "Marks", resultado.nome); } JFreeChart chart = ChartFactory.createBarChart("Precisão", "Classificador", "Pontuação", dataset, PlotOrientation.HORIZONTAL, false, true, false); CategoryPlot p = chart.getCategoryPlot(); p.setRangeGridlinePaint(Color.LIGHT_GRAY); ChartPanel cp = new ChartPanel(chart); cp.setDomainZoomable(true); painel.add(cp); painel.validate(); } public static void criaRevocacao(ArrayList<Resultado> resultados, JPanel painel) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (Resultado resultado : resultados) { dataset.setValue(resultado.revocacao, "Marks", resultado.nome); } JFreeChart chart = ChartFactory.createBarChart("Revocação", "Classificador", "Pontuação", dataset, PlotOrientation.HORIZONTAL, false, true, false); CategoryPlot p = chart.getCategoryPlot(); p.setRangeGridlinePaint(Color.LIGHT_GRAY); ChartPanel cp = new ChartPanel(chart); cp.setDomainZoomable(true); painel.add(cp); painel.validate(); } }
gpl-3.0
rhilker/ReadXplorer
readxplorer-databackend/src/main/java/de/cebitec/readxplorer/databackend/dataobjects/PersistentFeatureI.java
1516
/* * Copyright (C) 2014 Institute for Bioinformatics and Systems Biology, University Giessen, Germany * * 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 de.cebitec.readxplorer.databackend.dataobjects; import de.cebitec.readxplorer.api.enums.FeatureType; import de.cebitec.readxplorer.utils.sequence.GenomicRange; /** * Interface for all persistent features. * <p> * @author Rolf Hilker <rhilker at cebitec.uni-bielefeld.de> */ public interface PersistentFeatureI extends GenomicRange { /** * @return Start of the feature. Always the smaller value among start and * stop. */ @Override int getStart(); /** * @return Stop of the feature. Always the larger value among start and * stop. */ @Override int getStop(); /** * @return Type of the feature among {@link FeatureType}s. */ FeatureType getType(); }
gpl-3.0
GWASpi/GWASpi
src/main/java/org/gwaspi/operations/genotypesflipper/MatrixGenotypesFlipper.java
9997
/* * Copyright (C) 2013 Universitat Pompeu Fabra * * 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.gwaspi.operations.genotypesflipper; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.gwaspi.constants.NetCDFConstants.Defaults.AlleleByte; import org.gwaspi.constants.NetCDFConstants.Defaults.GenotypeEncoding; import org.gwaspi.dao.MatrixService; import org.gwaspi.global.Text; import org.gwaspi.model.ChromosomeInfo; import org.gwaspi.model.ChromosomeKey; import org.gwaspi.model.DataSetSource; import org.gwaspi.model.GenotypesList; import org.gwaspi.model.MarkerKey; import org.gwaspi.model.MarkerMetadata; import org.gwaspi.model.MatricesList; import org.gwaspi.model.MatrixKey; import org.gwaspi.model.MatrixMetadata; import org.gwaspi.model.SampleKey; import org.gwaspi.netCDF.loader.DataSetDestination; import org.gwaspi.netCDF.matrices.MatrixFactory; import org.gwaspi.operations.AbstractMatrixCreatingOperation; import org.gwaspi.operations.DefaultOperationTypeInfo; import org.gwaspi.operations.MatrixOperationFactory; import org.gwaspi.operations.OperationManager; import org.gwaspi.operations.OperationParams; import org.gwaspi.operations.OperationTypeInfo; import org.gwaspi.progress.DefaultProcessInfo; import org.gwaspi.progress.ProcessInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MatrixGenotypesFlipper extends AbstractMatrixCreatingOperation { private final Logger log = LoggerFactory.getLogger(MatrixGenotypesFlipper.class); private static final ProcessInfo PROCESS_INFO = new DefaultProcessInfo( Text.Trafo.flipStrand, Text.Trafo.flipStrand); // TODO We need a more elaborate description of this operation! private static final OperationTypeInfo OPERATION_TYPE_INFO = new DefaultOperationTypeInfo( true, Text.Trafo.flipStrand, Text.Trafo.flipStrand, // TODO We need a more elaborate description of this operation! null); static { // NOTE When converting to OSGi, this would be done in bundle init, // or by annotations. OperationManager.registerOperationFactory(new MatrixOperationFactory( MatrixGenotypesFlipper.class, OPERATION_TYPE_INFO)); } private final MatrixGenotypesFlipperParams params; private final Set<MarkerKey> markersToFlip; /** * Use this constructor to extract data from a matrix * by passing a variable and the criteria to filter items by. */ public MatrixGenotypesFlipper( MatrixGenotypesFlipperParams params, DataSetDestination dataSetDestination) throws IOException { super(dataSetDestination); this.params = params; this.markersToFlip = loadMarkerKeys(params.getFlipperFile()); } private MatrixService getMatrixService() { return MatricesList.getMatrixService(); } @Override public OperationTypeInfo getTypeInfo() { return OPERATION_TYPE_INFO; } @Override public ProcessInfo getProcessInfo() { return PROCESS_INFO; } @Override public OperationParams getParams() { throw new UnsupportedOperationException("Not supported yet."); } /** * Loads a number of marker keys from a plain text file. * @return the loaded marker keys * @throws IOException */ private static Set<MarkerKey> loadMarkerKeys(File flipperFile) throws IOException { Set<MarkerKey> markerKeys = new HashSet<MarkerKey>(); if (flipperFile.isFile()) { FileReader fr = new FileReader(flipperFile); BufferedReader br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { markerKeys.add(MarkerKey.valueOf(line)); } br.close(); } return markerKeys; } @Override public boolean isValid() { return true; } @Override public String getProblemDescription() { String problemDescription = null; try { final MatrixMetadata sourceMetadata = getMatrixService().getMatrix(params.getParent().getMatrixParent()); final GenotypeEncoding genotypeEncoding = sourceMetadata.getGenotypeEncoding(); if (!genotypeEncoding.equals(GenotypeEncoding.O1234) && !genotypeEncoding.equals(GenotypeEncoding.ACGT0)) { problemDescription = Text.Trafo.warnNotACGTor1234; } } catch (IOException ex) { problemDescription = ex.getMessage(); } return problemDescription; } @Override public MatrixKey call() throws IOException { MatrixKey resultMatrixKey; final DataSetSource dataSetSource = MatrixFactory.generateDataSetSource(params.getParent()); final DataSetDestination dataSetDestination = getDataSetDestination(); // simply copy&paste the sample infos dataSetDestination.startLoadingSampleInfos(true); // for (SampleInfo sampleInfo : dataSetSource.getSamplesInfosSource()) { // dataSetDestination.addSampleInfo(sampleInfo); // } for (SampleKey sampleKey : dataSetSource.getSamplesKeysSource()) { dataSetDestination.addSampleKey(sampleKey); } dataSetDestination.finishedLoadingSampleInfos(); // copy&paste the marker metadata aswell, // but flipp dictionary-alleles and strand // of the ones that are selected for flipping dataSetDestination.startLoadingMarkerMetadatas(false); Iterator<MarkerKey> markerKeysIt = dataSetSource.getMarkersKeysSource().iterator(); for (MarkerMetadata origMarkerMetadata : dataSetSource.getMarkersMetadatasSource()) { MarkerKey markerKey = markerKeysIt.next(); MarkerMetadata newMarkerMetadata; if (markersToFlip.contains(markerKey)) { String alleles = flipDictionaryAlleles(origMarkerMetadata.getAlleles()); String strand = flipStranding(origMarkerMetadata.getStrand()); newMarkerMetadata = new MarkerMetadata( origMarkerMetadata.getMarkerId(), origMarkerMetadata.getRsId(), origMarkerMetadata.getChr(), origMarkerMetadata.getPos(), alleles, strand); } else { newMarkerMetadata = origMarkerMetadata; } dataSetDestination.addMarkerMetadata(newMarkerMetadata); } dataSetDestination.finishedLoadingMarkerMetadatas(); // simply copy&paste the chromosomes infos dataSetDestination.startLoadingChromosomeMetadatas(); Iterator<ChromosomeInfo> chromosomesInfosIt = dataSetSource.getChromosomesInfosSource().iterator(); for (ChromosomeKey chromosomeKey : dataSetSource.getChromosomesKeysSource()) { ChromosomeInfo chromosomeInfo = chromosomesInfosIt.next(); dataSetDestination.addChromosomeMetadata(chromosomeKey, chromosomeInfo); } dataSetDestination.finishedLoadingChromosomeMetadatas(); // WRITE GENOTYPES dataSetDestination.startLoadingAlleles(false); int markerIndex = 0; final GenotypeEncoding gtEncoding = dataSetSource.getMatrixMetadata().getGenotypeEncoding(); markerKeysIt = dataSetSource.getMarkersKeysSource().iterator(); for (GenotypesList markerGenotypes : dataSetSource.getMarkersGenotypesSource()) { MarkerKey markerKey = markerKeysIt.next(); if (markersToFlip.contains(markerKey)) { for (byte[] gt : markerGenotypes) { // we deal with references here, so we change the value // in the map. no need to explicitly write it back. flipGenotypes(gt, gtEncoding); } } // Write rdMarkerIdSetMap to A3 ArrayChar and save to wrMatrix dataSetDestination.addMarkerGTAlleles(markerIndex, markerGenotypes); markerIndex++; if ((markerIndex == 1) || ((markerIndex % 10000) == 0)) { log.info("Markers processed: {} / {}", markerIndex, dataSetSource.getMarkersGenotypesSource().size()); } } dataSetDestination.finishedLoadingAlleles(); dataSetDestination.done(); resultMatrixKey = dataSetDestination.getResultMatrixKey(); org.gwaspi.global.Utils.sysoutCompleted("Genotype Flipping to new Matrix"); return resultMatrixKey; } private static String flipDictionaryAlleles(String alleles) { String flippedAlleles = alleles; flippedAlleles = flippedAlleles.replaceAll("A", "t"); flippedAlleles = flippedAlleles.replaceAll("C", "g"); flippedAlleles = flippedAlleles.replaceAll("G", "c"); flippedAlleles = flippedAlleles.replaceAll("T", "a"); flippedAlleles = flippedAlleles.toUpperCase(); return flippedAlleles; } private static String flipStranding(String strand) { if (strand.equals("+")) { return "-"; } else if (strand.equals("-")) { return "+"; } else { return strand; } } private static void flipGenotypes(byte[] gt, GenotypeEncoding gtEncoding) { byte[] result = gt; if (gtEncoding.equals(GenotypeEncoding.ACGT0)) { for (int i = 0; i < gt.length; i++) { if (gt[i] == AlleleByte.A.getValue()) { result[i] = AlleleByte.T.getValue(); } else if (gt[i] == AlleleByte.C.getValue()) { result[i] = AlleleByte.G.getValue(); } else if (gt[i] == AlleleByte.G.getValue()) { result[i] = AlleleByte.C.getValue(); } else if (gt[i] == AlleleByte.T.getValue()) { result[i] = AlleleByte.A.getValue(); } } } if (gtEncoding.equals(GenotypeEncoding.O1234)) { for (int i = 0; i < gt.length; i++) { if (gt[i] == AlleleByte._1.getValue()) { result[i] = AlleleByte._4.getValue(); } else if (gt[i] == AlleleByte._2.getValue()) { result[i] = AlleleByte._3.getValue(); } else if (gt[i] == AlleleByte._3.getValue()) { result[i] = AlleleByte._2.getValue(); } else if (gt[i] == AlleleByte._4.getValue()) { result[i] = AlleleByte._1.getValue(); } } } } }
gpl-3.0
TeddyDev/MCNetwork
Game/src/main/java/me/lukebingham/game/team/Team.java
110
package me.lukebingham.game.team; /** * Created by LukeBingham on 29/03/2017. */ public interface Team { }
gpl-3.0
highsad/iDesktop-Cross
Controls/src/net/infonode/tabbedpanel/TabRemovedEvent.java
1927
/* * Copyright (C) 2004 NNL Technology AB * Visit www.infonode.net for information about InfoNode(R) * products and how to contact NNL Technology AB. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ // $Id: TabRemovedEvent.java,v 1.4 2004/09/22 14:33:49 jesper Exp $ package net.infonode.tabbedpanel; /** * TabRemovedEvent is an event that contains information about the tab that was * removed from a tabbed panel and the tabbed panel it was removed from. * * @author $Author: jesper $ * @version $Revision: 1.4 $ * @see TabbedPanel * @see Tab */ public class TabRemovedEvent extends TabEvent { private TabbedPanel tabbedPanel; /** * Constructs a TabDragEvent * * @param source the Tab ot TabbedPanel that is the source for this * event * @param tab the Tab that was removed * @param tabbedPanel the TabbedPanel that the Tab was removed from */ public TabRemovedEvent(Object source, Tab tab, TabbedPanel tabbedPanel) { super(source, tab); this.tabbedPanel = tabbedPanel; } /** * Gets the TabbedPanel the Tab was removed from * * @return the TabbedPanel the Tab was removed from */ public TabbedPanel getTabbedPanel() { return tabbedPanel; } }
gpl-3.0
mkjung/ivi-media-player
app/src/main/java/io/github/mkjung/iviplayer/gui/tv/browser/interfaces/DetailsFragment.java
1196
/* * ************************************************************************ * MediaFragment.java * ************************************************************************* * Copyright © 2016 VLC authors and VideoLAN * Author: Geoffrey Métais * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * * ************************************************************************* */ package io.github.mkjung.iviplayer.gui.tv.browser.interfaces; public interface DetailsFragment { void showDetails(); }
gpl-3.0
ryanfb/ocular
src/main/java/edu/berkeley/cs/nlp/ocular/data/textreader/Charset.java
14360
package edu.berkeley.cs.nlp.ocular.data.textreader; import static edu.berkeley.cs.nlp.ocular.util.CollectionHelper.getOrElse; import static edu.berkeley.cs.nlp.ocular.util.CollectionHelper.makeSet; import java.util.HashMap; import java.util.Map; import java.util.Set; import edu.berkeley.cs.nlp.ocular.util.StringHelper; import edu.berkeley.cs.nlp.ocular.util.Tuple2; import static edu.berkeley.cs.nlp.ocular.util.Tuple2.makeTuple2; /** * @author Dan Garrette (dhg@cs.utexas.edu) */ public class Charset { public static final String SPACE = " "; public static final String HYPHEN = "-"; public static final String LONG_S = "\u017F"; // ſ /** * Punctuation symbols that should be made available for any language, * regardless of whether they are seen in the language model training * material. */ public static final Set<String> UNIV_PUNC = makeSet("&", ".", ",", "[", "]", HYPHEN, "*", "§", "¶"); /** * Punctuation is anything that is not alphabetic or a digit. */ public static boolean isPunctuation(char c) { return !Character.isWhitespace(c) && !Character.isAlphabetic(c) && !Character.isDigit(c); } public static boolean isPunctuationChar(String s) { for (char c: removeAnyDiacriticFromChar(s).toCharArray()) if (!isPunctuation(c)) return false; return true; } public static final String GRAVE_COMBINING = "\u0300"; public static final String ACUTE_COMBINING = "\u0301"; public static final String CIRCUMFLEX_COMBINING = "\u0302"; public static final String TILDE_COMBINING = "\u0303"; public static final String MACRON_COMBINING = "\u0304"; // shorter overline public static final String BREVE_COMBINING = "\u0306"; public static final String DIAERESIS_COMBINING = "\u0308"; // == umlaut public static final String CEDILLA_COMBINING = "\u0327"; public static final String MACRON_BELOW_COMBINING = "\0331"; public static final Set<String> COMBINING_CHARS = makeSet(GRAVE_COMBINING, ACUTE_COMBINING, CIRCUMFLEX_COMBINING, TILDE_COMBINING, MACRON_COMBINING, BREVE_COMBINING, DIAERESIS_COMBINING, CEDILLA_COMBINING, MACRON_BELOW_COMBINING); public static final String COMBINING_CHARS_RANGE_START = "\u0300"; public static final String COMBINING_CHARS_RANGE_END = "\u036F"; public static boolean isCombiningChar(String c) { return COMBINING_CHARS_RANGE_START.compareTo(c) <= 0 && c.compareTo(COMBINING_CHARS_RANGE_END) <= 0; } public static final String GRAVE_ESCAPE = "\\`"; public static final String ACUTE_ESCAPE = "\\'"; public static final String CIRCUMFLEX_ESCAPE = "\\^"; public static final String TILDE_ESCAPE = "\\~"; public static final String MACRON_ESCAPE = "\\-"; // shorter overline public static final String BREVE_ESCAPE = "\\v"; public static final String DIAERESIS_ESCAPE = "\\\""; // == umlaut public static final String CEDILLA_ESCAPE = "\\c"; public static final String MACRON_BELOW_ESCAPE = "\\_"; public static final Set<String> ESCAPE_CHARS = makeSet(GRAVE_ESCAPE, ACUTE_ESCAPE, CIRCUMFLEX_ESCAPE, TILDE_ESCAPE, MACRON_ESCAPE, BREVE_ESCAPE, DIAERESIS_ESCAPE, CEDILLA_ESCAPE, MACRON_BELOW_ESCAPE); public static String combiningToEscape(String combiningChar) { if (GRAVE_COMBINING.equals(combiningChar)) return GRAVE_ESCAPE; else if (ACUTE_COMBINING.equals(combiningChar)) return ACUTE_ESCAPE; else if (CIRCUMFLEX_COMBINING.equals(combiningChar)) return CIRCUMFLEX_ESCAPE; else if (TILDE_COMBINING.equals(combiningChar)) return TILDE_ESCAPE; else if (MACRON_COMBINING.equals(combiningChar)) return MACRON_ESCAPE; else if (BREVE_COMBINING.equals(combiningChar)) return BREVE_ESCAPE; else if (DIAERESIS_COMBINING.equals(combiningChar)) return DIAERESIS_ESCAPE; else if (CEDILLA_COMBINING.equals(combiningChar)) return CEDILLA_ESCAPE; else if (MACRON_BELOW_COMBINING.equals(combiningChar)) return MACRON_BELOW_ESCAPE; else throw new RuntimeException("Unrecognized combining char: [" + combiningChar + "] (" + StringHelper.toUnicode(combiningChar) + ")"); } public static String escapeToCombining(String escSeq) { if (GRAVE_ESCAPE.equals(escSeq)) return GRAVE_COMBINING; else if (ACUTE_ESCAPE.equals(escSeq)) return ACUTE_COMBINING; else if (CIRCUMFLEX_ESCAPE.equals(escSeq)) return CIRCUMFLEX_COMBINING; else if (TILDE_ESCAPE.equals(escSeq)) return TILDE_COMBINING; else if (MACRON_ESCAPE.equals(escSeq)) return MACRON_COMBINING; else if (BREVE_ESCAPE.equals(escSeq)) return BREVE_COMBINING; else if (DIAERESIS_ESCAPE.equals(escSeq)) return DIAERESIS_COMBINING; else if (CEDILLA_ESCAPE.equals(escSeq)) return CEDILLA_COMBINING; else if (MACRON_BELOW_ESCAPE.equals(escSeq)) return MACRON_BELOW_COMBINING; else throw new RuntimeException("Unrecognized escape sequence: [" + escSeq + "]"); } public static final Map<String, String> PRECOMPOSED_TO_ESCAPED_MAP = new HashMap<String, String>(); static { PRECOMPOSED_TO_ESCAPED_MAP.put("à", "\\`a"); // \`a PRECOMPOSED_TO_ESCAPED_MAP.put("á", "\\'a"); // \'a PRECOMPOSED_TO_ESCAPED_MAP.put("â", "\\^a"); // \^a PRECOMPOSED_TO_ESCAPED_MAP.put("ä", "\\\"a"); // \"a PRECOMPOSED_TO_ESCAPED_MAP.put("ã", "\\~a"); // \~a PRECOMPOSED_TO_ESCAPED_MAP.put("ā", "\\-a"); // \-a PRECOMPOSED_TO_ESCAPED_MAP.put("ă", "\\va"); // \va PRECOMPOSED_TO_ESCAPED_MAP.put("è", "\\`e"); // \`e PRECOMPOSED_TO_ESCAPED_MAP.put("é", "\\'e"); // \'e PRECOMPOSED_TO_ESCAPED_MAP.put("ê", "\\^e"); // \^e PRECOMPOSED_TO_ESCAPED_MAP.put("ë", "\\\"e"); // \"e PRECOMPOSED_TO_ESCAPED_MAP.put("ẽ", "\\~e"); // \~e PRECOMPOSED_TO_ESCAPED_MAP.put("ē", "\\-e"); // \-e PRECOMPOSED_TO_ESCAPED_MAP.put("ĕ", "\\ve"); // \ve PRECOMPOSED_TO_ESCAPED_MAP.put("ì", "\\`i"); // \`i PRECOMPOSED_TO_ESCAPED_MAP.put("í", "\\'i"); // \'i PRECOMPOSED_TO_ESCAPED_MAP.put("î", "\\^i"); // \^i PRECOMPOSED_TO_ESCAPED_MAP.put("ï", "\\\"i"); // \"i PRECOMPOSED_TO_ESCAPED_MAP.put("ĩ", "\\~i"); // \~i PRECOMPOSED_TO_ESCAPED_MAP.put("ī", "\\-i"); // \-i PRECOMPOSED_TO_ESCAPED_MAP.put("ı", "\\ii"); // \ii PRECOMPOSED_TO_ESCAPED_MAP.put("ī", "\\-i"); // \-i PRECOMPOSED_TO_ESCAPED_MAP.put("ĭ", "\\vi"); // \vi PRECOMPOSED_TO_ESCAPED_MAP.put("ò", "\\`o"); // \`o PRECOMPOSED_TO_ESCAPED_MAP.put("ó", "\\'o"); // \'o PRECOMPOSED_TO_ESCAPED_MAP.put("ô", "\\^o"); // \^o PRECOMPOSED_TO_ESCAPED_MAP.put("ö", "\\\"o"); // \"o PRECOMPOSED_TO_ESCAPED_MAP.put("õ", "\\~o"); // \~o PRECOMPOSED_TO_ESCAPED_MAP.put("ō", "\\-o"); // \-o PRECOMPOSED_TO_ESCAPED_MAP.put("ŏ", "\\vo"); // \vo PRECOMPOSED_TO_ESCAPED_MAP.put("ù", "\\`u"); // \`u PRECOMPOSED_TO_ESCAPED_MAP.put("ú", "\\'u"); // \'u PRECOMPOSED_TO_ESCAPED_MAP.put("û", "\\^u"); // \^u PRECOMPOSED_TO_ESCAPED_MAP.put("ü", "\\\"u"); // \"u PRECOMPOSED_TO_ESCAPED_MAP.put("ũ", "\\~u"); // \~u PRECOMPOSED_TO_ESCAPED_MAP.put("ū", "\\-u"); // \-u PRECOMPOSED_TO_ESCAPED_MAP.put("ŭ", "\\vu"); // \vu PRECOMPOSED_TO_ESCAPED_MAP.put("ñ", "\\~n"); // \~n PRECOMPOSED_TO_ESCAPED_MAP.put("ç", "\\cc"); // \cc PRECOMPOSED_TO_ESCAPED_MAP.put("À", "\\`A"); // \`A PRECOMPOSED_TO_ESCAPED_MAP.put("Á", "\\'A"); // \'A PRECOMPOSED_TO_ESCAPED_MAP.put("Â", "\\^A"); // \^A PRECOMPOSED_TO_ESCAPED_MAP.put("Ä", "\\\"A"); // \"A PRECOMPOSED_TO_ESCAPED_MAP.put("Ã", "\\~A"); // \~A PRECOMPOSED_TO_ESCAPED_MAP.put("Ā", "\\-A"); // \-A PRECOMPOSED_TO_ESCAPED_MAP.put("Ă", "\\vA"); // \vA PRECOMPOSED_TO_ESCAPED_MAP.put("È", "\\`E"); // \`E PRECOMPOSED_TO_ESCAPED_MAP.put("É", "\\'E"); // \'E PRECOMPOSED_TO_ESCAPED_MAP.put("Ê", "\\^E"); // \^E PRECOMPOSED_TO_ESCAPED_MAP.put("Ë", "\\\"E"); // \"E PRECOMPOSED_TO_ESCAPED_MAP.put("Ẽ", "\\~E"); // \~E PRECOMPOSED_TO_ESCAPED_MAP.put("Ē", "\\-E"); // \-E PRECOMPOSED_TO_ESCAPED_MAP.put("Ĕ", "\\vE"); // \ve PRECOMPOSED_TO_ESCAPED_MAP.put("Ì", "\\`I"); // \`I PRECOMPOSED_TO_ESCAPED_MAP.put("Í", "\\'I"); // \'I PRECOMPOSED_TO_ESCAPED_MAP.put("Î", "\\^I"); // \^I PRECOMPOSED_TO_ESCAPED_MAP.put("Ï", "\\\"I"); // \"I PRECOMPOSED_TO_ESCAPED_MAP.put("Ĩ", "\\~I"); // \~I PRECOMPOSED_TO_ESCAPED_MAP.put("Ī", "\\-I"); // \-I PRECOMPOSED_TO_ESCAPED_MAP.put("Ĭ", "\\vI"); // \vI PRECOMPOSED_TO_ESCAPED_MAP.put("Ò", "\\`O"); // \`O PRECOMPOSED_TO_ESCAPED_MAP.put("Ó", "\\'O"); // \'O PRECOMPOSED_TO_ESCAPED_MAP.put("Ô", "\\^O"); // \^O PRECOMPOSED_TO_ESCAPED_MAP.put("Ö", "\\\"O"); // \"O PRECOMPOSED_TO_ESCAPED_MAP.put("Õ", "\\~O"); // \~O PRECOMPOSED_TO_ESCAPED_MAP.put("Ō", "\\-O"); // \-O PRECOMPOSED_TO_ESCAPED_MAP.put("Ŏ", "\\vO"); // \vO PRECOMPOSED_TO_ESCAPED_MAP.put("Ù", "\\`U"); // \`U PRECOMPOSED_TO_ESCAPED_MAP.put("Ú", "\\'U"); // \'U PRECOMPOSED_TO_ESCAPED_MAP.put("Û", "\\^U"); // \^U PRECOMPOSED_TO_ESCAPED_MAP.put("Ü", "\\\"U"); // \"U PRECOMPOSED_TO_ESCAPED_MAP.put("Ũ", "\\~U"); // \~U PRECOMPOSED_TO_ESCAPED_MAP.put("Ū", "\\-U"); // \-U PRECOMPOSED_TO_ESCAPED_MAP.put("Ŭ", "\\vU"); // \vU PRECOMPOSED_TO_ESCAPED_MAP.put("Ñ", "\\~N"); // \~N PRECOMPOSED_TO_ESCAPED_MAP.put("Ç", "\\cC"); // \cC // note: superscript is marked \s as in superscript o = \so and superscript r is \sr //note for "breve" (u over letter) mark \va } private static final Map<String, String> ESCAPED_TO_PRECOMPOSED_MAP = new HashMap<String, String>(); static { for (Map.Entry<String, String> entry : PRECOMPOSED_TO_ESCAPED_MAP.entrySet()) ESCAPED_TO_PRECOMPOSED_MAP.put(entry.getValue(), entry.getKey()); } /** * Get the character code including any escaped diacritics that precede * the letter and any unicode "combining characters" that follow it. * * Precomposed accents are given the highest priority. Combining characters * are interpreted as left-associative and high-priority, while escapes are * right-associative and low-priority. So, for a letter x with precomposed * diacritic 0, combining chars 1,2,3, and escapes 4,5,6, the input 654x123 * becomes encoded (with escapes) as 6543210x, and decoded (with precomposed * and combining characters) as x01234656. * * @param s A single character, potentially with diacritics encoded in any * form (composed, precomposed, escaped). * @return A string representing a single fully-escaped character, with all * diacritics (combining and precomposed) converted to their equivalent escape * sequences. * @throws RuntimeException if the parameter `s` does not represent a single * (potentially composed or escaped) character. */ public static String escapeChar(String s) { Tuple2<String, Integer> letterAndLength = readCharAt(s, 0); String c = letterAndLength._1; int length = letterAndLength._2; if (s.length() - length != 0) throw new RuntimeException("Could not escape [" + s + "] because it contains more than one character ("+StringHelper.toUnicode(s)+")"); return c; } /** * @see edu.berkeley.cs.nlp.ocular.data.textreader.textreader.Charset.escapeChar * * @param line A line of text possibly containing characters with diacritics * composed, precomposed, or escaped. * @param offset The offset point in `line` from which to start reading for a * character. * @return A fully-escaped character string, with all diacritics (combining * and precomposed) converted to their equivalent escape sequences. Also * return the length in the ORIGINAL string of the span used to produce this * escaped character (to use as an offset when scanning through the string). */ public static Tuple2<String, Integer> readCharAt(String line, int offset) { int lineLen = line.length(); if (offset >= lineLen) throw new RuntimeException("offset must be less than the line length"); if (lineLen - offset >= 2 && line.substring(offset, offset + 2).equals("\\\\")) return makeTuple2("\\\\", 2); // "\\" is its own character (for "\"), not an escaped diacritic StringBuilder sb = new StringBuilder(); // get any escape prefixes characters int i = offset; while (i < lineLen && line.substring(i, i + 1).equals("\\")) { if (i + 1 >= lineLen) throw new RuntimeException("expected more after escape symbol, but found nothing: " + i + "," + lineLen + " " + line.substring(Math.max(0, i - 10), i) + "[" + line.substring(i) + "]"); String escape = line.substring(i, i + 2); sb.append(escape); i += 2; // accept the 2-character escape sequence } int combiningCharCodeInsertionPoint = i - offset; if (i >= lineLen) throw new RuntimeException("expected a letter after escape code, but found nothing: " + i + "," + lineLen + " " + line.substring(Math.max(0, i - 50), i) + "[" + line.substring(i) + "]"); String letter = line.substring(i, i + 1); i += 1; // accept the letter itself // get any combining characters while (i < lineLen) { String next = line.substring(i, i + 1); if (!isCombiningChar(next)) break; sb.insert(combiningCharCodeInsertionPoint, combiningToEscape(next)); i++; // accept the combining character } sb.append(getOrElse(Charset.PRECOMPOSED_TO_ESCAPED_MAP, letter, letter)); // turn any precomposed letters into escaped letters return makeTuple2(sb.toString(), i - offset); } /** * Convert diacritic escape sequences on a character into unicode precomposed and combining characters */ public static String unescapeChar(String c) { if (c.length() == 1) return c; // no escapes if (c.equals("\\\\")) return c; String e = escapeChar(c); // use escapes only (and make sure it's a valid character) StringBuilder b = new StringBuilder(); // Attempt to make a precomposed letter, falling back to composed otherwise String last = e.substring(e.length() - 3); // last escape + letter String precomposed = ESCAPED_TO_PRECOMPOSED_MAP.get(last); b.append((precomposed != null ? precomposed : last.substring(2) + escapeToCombining(last.substring(0, 2)))); for (int i = e.length() - 5; i >= 0; i -= 2) { String esc = e.substring(i, i + 2); b.append(escapeToCombining(esc)); } return b.toString(); } public static String removeAnyDiacriticFromChar(String c) { if (c.equals("\\\\")) return c; String escaped = escapeChar(c); while (escaped.charAt(0) == '\\') { escaped = escaped.substring(2); } if (escaped.isEmpty()) throw new RuntimeException("Character contains only escape codes!"); return escaped; } }
gpl-3.0
DarioGT/OMS-PluginXML
org.modelsphere.jack/src/org/modelsphere/jack/preference/PropertiesConverter.java
1740
/************************************************************************* Copyright (C) 2009 Grandite This file is part of Open ModelSphere. Open ModelSphere 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/. You can redistribute and/or modify this particular file even under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. You should have received a copy of the GNU Lesser General Public License (LGPL) along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/. You can reach Grandite at: 20-1220 Lebourgneuf Blvd. Quebec, QC Canada G2K 2G4 or open-modelsphere@grandite.com **********************************************************************/ package org.modelsphere.jack.preference; public interface PropertiesConverter { public void convert(PropertiesSet set, int oldversion); }
gpl-3.0
TheTransitClock/transitime
transitclock/src/main/java/org/transitclock/avl/amigocloud/AmigoWebsockets.java
7144
/* * This file is part of Transitime.org * * Transitime.org is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License (GPL) as published by the * Free Software Foundation, either version 3 of the License, or any later * version. * * Transitime.org 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 * Transitime.org . If not, see <http://www.gnu.org/licenses/>. */ package org.transitclock.avl.amigocloud; import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft_10; import org.java_websocket.handshake.ServerHandshake; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.transitclock.configData.AgencyConfig; import org.transitclock.logging.Markers; import java.net.URI; import java.util.Random; /** * * @author AmigoCloud and Michael Smith Credits to the websockets library: * https://github.com/TooTallNate/Java-WebSocket * */ public class AmigoWebsockets { private WebSocketClient mWs = null; private String websocket_token = null; private String userID = ""; private String datasetID = ""; private boolean connected = false; private boolean realtime = false; private AmigoWebsocketListener listener = null; private static final String BASE_URL = "www.amigocloud.com"; private static final String END_POINT = "/amigosocket"; private static final Logger logger = LoggerFactory .getLogger(AmigoWebsockets.class); /********************** Member Functions **************************/ /** * Constructor for a real-time data feed. Determines the websocket_token * that is used in connect(). * * @param userID * @param projectID * @param datasetID * @param apiToken * @param listener * @throws JSONException */ public AmigoWebsockets(long userID, long projectID, long datasetID, String apiToken, AmigoWebsocketListener listener) throws JSONException { this.userID = Long.toString(userID); this.datasetID = Long.toString(datasetID); this.listener = listener; this.realtime = true; AmigoRest client = new AmigoRest(apiToken); String uri = "https://" + BASE_URL + "/api/v1/users/" + userID + "/projects/" + projectID + "/datasets/" + datasetID + "/start_websocket_session"; logger.info("Getting amigocloud websocket session using uri {}", uri); String result = client.get(uri); // If there was a problem getting websocket session then give up. // websocket_token will be null for this situation if (result == null) { logger.error(Markers.email(), "For agencyId={} could not determine websocket session", AgencyConfig.getAgencyId()); return; } JSONObject obj = null; try { obj = new JSONObject(result); websocket_token = obj.getString("websocket_session"); logger.info("Using amigocloud websocket_session={}", websocket_token); } catch (JSONException e) { logger.error("{}", e.getMessage(), e); throw e; } } /** * Constructor for non real-time data feeds * * @param userID * @param apiToken * @param listener */ public AmigoWebsockets(long userID, String apiToken, AmigoWebsocketListener listener) { this.userID = Long.toString(userID); this.listener = listener; AmigoRest client = new AmigoRest(apiToken); String result = client.get("https://" + BASE_URL + "/api/v1/me/start_websocket_session"); JSONObject obj = null; try { obj = new JSONObject(result); websocket_token = obj.getString("websocket_session"); logger.info("Using amigocloud websocket_session={}", websocket_token); } catch (JSONException e) { logger.error("{}", e.getMessage(), e); } } /** * @return true if already successfully connected */ public boolean isConnected() { return connected; } /** * Initiate connection to real-time feed * * @return true if successful */ public boolean connect() { if (websocket_token == null) return false; try { String uri = "ws://" + BASE_URL + ":5005/socket.io/1/websocket/"; Random rand = new Random(); uri += Long.toString(rand.nextLong()); logger.info("Connecting to amigocloud feed using uri {}", uri); mWs = new WebSocketClient(new URI(uri), new Draft_10()) { @Override public void onMessage(String message) { parseMessage(message); } @Override public void onOpen(ServerHandshake handshake) { logger.info("Opened websockets connection"); } @Override public void onClose(int code, String reason, boolean remote) { logger.info("closed connection, remote:" + remote + ", code(" + Integer.toString(code) + "), reason: " + reason); // Let listener know that connection closing so can restart it listener.onClose(code, reason); } @Override public void onError(Exception ex) { logger.error("Error with amigocloud websocket: {}", ex.getMessage(), ex); } }; // open websocket mWs.connect(); // Wait for connection int counter = 100; while (!isConnected() && counter > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { logger.error("Error with amigocloud websocket: {}", e.getMessage(), e); } counter--; } if (counter > 1) { return emit(); } } catch (Exception e) { logger.error("Error with amigocloud websocket: {}", e.getMessage(), e); } return false; } public boolean emit() { String emitargs; if (realtime) { emitargs = "{\"userid\":" + userID + ",\"datasetid\":" + datasetID + ",\"websocket_session\":\"" + websocket_token + "\"}"; } else { emitargs = "{\"userid\":" + userID + ",\"websocket_session\":\"" + websocket_token + "\"}"; } String msg = "{\"name\":\"authenticate\",\"args\":[" + emitargs + "]}"; send(5, msg); return true; } public void send(int type, String msg) { String message; message = Integer.toString(type) + "::" + END_POINT + ":" + msg; mWs.send(message); } public void parseMessage(String message) { String[] msg = message.split("::"); if (msg.length == 0) return; if (msg[0].contentEquals("1")) { if (msg.length == 1) { send(1, ""); // Emit reply } else { connected = true; } return; } if (msg[0].contentEquals("5") && msg.length > 1) { String msg5 = msg[1].replace(END_POINT + ":", ""); ; if (listener != null) { listener.onMessage(msg5); } } if (msg[0].contentEquals("2")) { logger.info("Keep alive message: {}", message); } } }
gpl-3.0
psnc-dl/darceo
wrdz/wrdz-zmd/dao/src/main/java/pl/psnc/synat/wrdz/zmd/dao/object/metadata/FileExtractedMetadataSorterBuilder.java
1053
/** * Copyright 2015 Poznań Supercomputing and Networking Center * * Licensed under the GNU General Public License, Version 3.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.gnu.org/licenses/gpl-3.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pl.psnc.synat.wrdz.zmd.dao.object.metadata; import pl.psnc.synat.wrdz.common.dao.GenericQuerySorterBuilder; import pl.psnc.synat.wrdz.zmd.entity.object.metadata.FileExtractedMetadata; /** * Defines methods producing sorters for queries concerning {@link FileExtractedMetadata} entities. */ public interface FileExtractedMetadataSorterBuilder extends GenericQuerySorterBuilder<FileExtractedMetadata> { }
gpl-3.0
DSI-Ville-Noumea/pdc
src/main/java/nc/noumea/mairie/pdc/services/impl/ProprietaireServiceImpl.java
1944
package nc.noumea.mairie.pdc.services.impl; /* * #%L * Logiciel de Gestion des Permis de Construire de la Ville de Nouméa * %% * Copyright (C) 2013 - 2016 Mairie de Nouméa, Nouvelle-Calédonie * %% * 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% */ import java.util.List; import nc.noumea.mairie.pdc.core.services.impl.GenericServiceImpl; import nc.noumea.mairie.pdc.dao.ProprietaireDao; import nc.noumea.mairie.pdc.entity.Proprietaire; import nc.noumea.mairie.pdc.recherche.RechercheTiers; import nc.noumea.mairie.pdc.services.ProprietaireService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Service; @Service("proprietaireService") @Scope(value = "singleton", proxyMode = ScopedProxyMode.TARGET_CLASS) public class ProprietaireServiceImpl extends GenericServiceImpl<Proprietaire> implements ProprietaireService { @Autowired ProprietaireDao proprietaireDao; @Override public List<Proprietaire> findAllByNomIlike(String texte) { return proprietaireDao.findAllByNomIlike(texte); } @Override public List<Proprietaire> findAllByRecherche(RechercheTiers recherche) { return proprietaireDao.findAllByRecherche(recherche); } }
gpl-3.0
YuKitAs/battle-of-elements
src/main/java/xigua/battle/of/elements/logic/battle/ElementFactory.java
731
package xigua.battle.of.elements.logic.battle; import xigua.battle.of.elements.model.battle.Element; import xigua.battle.of.elements.model.battle.Environment; import java.util.List; import java.util.Random; public class ElementFactory { private final List<Element> elementProportions; private final Random random = new Random(); public ElementFactory(Environment environment) { elementProportions = environment.getElementProportions(); } public ElementFactory(Environment environment, long randomSeed) { this(environment); random.setSeed(randomSeed); } public Element getElement() { return elementProportions.get(random.nextInt(elementProportions.size())); } }
gpl-3.0
murraycu/android-galaxyzoo
app/src/androidTest/java/com/murrayc/galaxyzoo/app/provider/test/ZooniverseClientTest.java
17115
/* * Copyright (C) 2014 Murray Cumming * * This file is part of android-glom * * android-glom 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. * * android-glom 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 android-glom. If not, see <http://www.gnu.org/licenses/>. */ package com.murrayc.galaxyzoo.app.provider.test; import android.app.Instrumentation; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.util.MalformedJsonException; import com.murrayc.galaxyzoo.app.LoginUtils; import com.murrayc.galaxyzoo.app.Utils; import com.murrayc.galaxyzoo.app.provider.Config; import com.murrayc.galaxyzoo.app.provider.HttpUtils; import com.murrayc.galaxyzoo.app.provider.client.ZooniverseClient; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.List; import okhttp3.HttpUrl; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import okio.Buffer; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; public class ZooniverseClientTest{ private static final String TEST_GROUP_ID = "5853fab395ad361930000003"; public static final String TEST_WORKFLOW_ID = "6122"; @Before public void setUp() throws IOException { } @After public void tearDown() { } @Test public void testMoreItems() throws IOException, InterruptedException, ZooniverseClient.RequestMoreItemsException { final MockWebServer server = new MockWebServer(); final String strResponse = getStringFromStream( MoreItemsJsonParserTest.class.getClassLoader().getResourceAsStream("test_more_items_response.json")); assertNotNull(strResponse); server.enqueue(new MockResponse().setBody(strResponse)); server.start(); final ZooniverseClient client = createZooniverseClient(server); final int COUNT = 10; final List<ZooniverseClient.Subject> subjects = client.requestMoreItemsSync(TEST_GROUP_ID, COUNT); assertNotNull(subjects); assertEquals(COUNT, subjects.size()); final ZooniverseClient.Subject subject = subjects.get(0); assertNotNull(subject); assertNotNull(subject.getId()); assertEquals("16216418", subject.getId()); // This is apparently always null in the JSON. // assertNotNull(subject.getZooniverseId()); // assertEquals("AGZ00081ls", subject.getZooniverseId()); // TODO // assertNotNull(subject.getGroupId()); // assertEquals(TEST_GROUP_ID, subject.getGroupId()); assertNotNull(subject.getLocationStandard()); assertEquals("https://panoptes-uploads.zooniverse.org/production/subject_location/772f8b1b-b0fe-4dac-9afe-472f3e8d381a.jpeg", subject.getLocationStandard()); /* TODO: assertNotNull(subject.getLocationThumbnail()); assertEquals("http://www.galaxyzoo.org.s3.amazonaws.com/subjects/thumbnail/goods_full_n_27820_thumbnail.jpg", subject.getLocationThumbnail()); assertNotNull(subject.getLocationInverted()); assertEquals("http://www.galaxyzoo.org.s3.amazonaws.com/subjects/inverted/goods_full_n_27820_inverted.jpg", subject.getLocationInverted()); */ //Test what the server received: assertEquals(1, server.getRequestCount()); final RecordedRequest request = server.takeRequest(); assertEquals("GET", request.getMethod()); //ZooniverseClient uses one of several possible group IDs at random: //See com.murrayc.galaxyzoo.app.provider.Config // TODO: Use more. /subjects/queued?http_cache=true&workflow_id=5853fab395ad361930000003&limit=5 final String possiblePath1 = "/subjects/queued?http_cache=true&workflow_id=" + TEST_GROUP_ID + "&limit=5"; final String possiblePath2 = "/subjects/queued?http_cache=true&workflow_id=" + Config.SUBJECT_GROUP_ID_GAMA_15 + "&limit=5"; //TODO: Can we use this? // assertThat(request.getPath(), anyOf(is(possiblePath1), is(possiblePath2))); final String path = request.getPath(); assertEquals(possiblePath1, path); assertTrue( path.equals(possiblePath1) || path.equals(possiblePath2)); server.shutdown(); } @Test public void testProject() throws IOException, ZooniverseClient.RequestProjectException { final MockWebServer server = new MockWebServer(); final String strResponse = getStringFromStream( MoreItemsJsonParserTest.class.getClassLoader().getResourceAsStream("test_project_response.json")); assertNotNull(strResponse); server.enqueue(new MockResponse().setBody(strResponse)); server.start(); final ZooniverseClient client = createZooniverseClient(server); final ZooniverseClient.Project project = client.requestProjectSync("zookeeper/galaxy-zoo"); assertNotNull(project); assertNotNull(project.id()); assertEquals("5733", project.id()); assertNotNull(project.displayName()); assertEquals("Galaxy Zoo", project.displayName()); final List<String> workflowIds = project.workflowIds(); assertNotNull(workflowIds); assertEquals(5, workflowIds.size()); final List<String> activeWorkflowIds = project.activeWorkflowIds(); assertNotNull(activeWorkflowIds); assertEquals(1, activeWorkflowIds.size()); final String activeWorkflowID = activeWorkflowIds.get(0); assertNotNull(activeWorkflowID); assertEquals("6122", activeWorkflowID); server.shutdown(); } @Test public void testWorkflow() throws IOException, ZooniverseClient.RequestWorkflowException { final MockWebServer server = new MockWebServer(); final String strResponse = getStringFromStream( MoreItemsJsonParserTest.class.getClassLoader().getResourceAsStream("test_workflow_response.json")); assertNotNull(strResponse); server.enqueue(new MockResponse().setBody(strResponse)); server.start(); final ZooniverseClient client = createZooniverseClient(server); final ZooniverseClient.Workflow workflow = client.requestWorkflowSync(TEST_WORKFLOW_ID); assertNotNull(workflow); assertNotNull(workflow.id()); assertEquals(TEST_WORKFLOW_ID, workflow.id()); assertNotNull(workflow.displayName()); assertEquals("DECaLS DR5", workflow.displayName()); final List<ZooniverseClient.Task> tasks = workflow.tasks(); assertNotNull(tasks); assertEquals(11, tasks.size()); assertEquals("T0", tasks.get(0).id()); assertEquals("T1", tasks.get(1).id()); server.shutdown(); } @Test public void testLoginWithSuccess() throws IOException, InterruptedException, ZooniverseClient.LoginException { final MockWebServer server = new MockWebServer(); final String strResponse = getStringFromStream( MoreItemsJsonParserTest.class.getClassLoader().getResourceAsStream("test_login_response_success.json")); assertNotNull(strResponse); server.enqueue(new MockResponse().setBody(strResponse)); server.start(); final ZooniverseClient client = createZooniverseClient(server); final LoginUtils.LoginResult result = client.loginSync("testusername", "testpassword"); assertNotNull(result); assertTrue(result.getSuccess()); assertEquals("testapikey", result.getApiKey()); //Test what the server received: assertEquals(1, server.getRequestCount()); final RecordedRequest request = server.takeRequest(); assertEquals("POST", request.getMethod()); assertEquals("/login", request.getPath()); assertEquals("application/x-www-form-urlencoded", request.getHeader("Content-Type")); final Buffer contents = request.getBody(); final String strContents = contents.readUtf8(); assertEquals("username=testusername&password=testpassword", strContents); server.shutdown(); } @Test public void testLoginWithFailure() throws IOException { final MockWebServer server = new MockWebServer(); //On failure, the server's response code is HTTP_OK, //but it has a "success: false" parameter. final MockResponse response = new MockResponse(); response.setResponseCode(HttpURLConnection.HTTP_OK); response.setBody("test nonsense failure message"); server.enqueue(response); server.start(); final ZooniverseClient client = createZooniverseClient(server); try { final LoginUtils.LoginResult result = client.loginSync("testusername", "testpassword"); assertNotNull(result); assertFalse(result.getSuccess()); } catch (final ZooniverseClient.LoginException e) { assertTrue(e.getCause() instanceof MalformedJsonException); } server.shutdown(); } @Test public void testLoginWithBadResponseContent() throws IOException { final MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("test bad login response")); server.start(); final ZooniverseClient client = createZooniverseClient(server); try { final LoginUtils.LoginResult result = client.loginSync("testusername", "testpassword"); assertNotNull(result); assertFalse(result.getSuccess()); } catch (final ZooniverseClient.LoginException e) { assertTrue(e.getCause() instanceof IOException); } server.shutdown(); } @Test public void testMoreItemsWithBadResponseContent() throws IOException { final MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("some nonsense to try to break things {")); server.start(); final ZooniverseClient client = createZooniverseClient(server); //Mostly we want to check that it doesn't crash on a bad HTTP response. try { final List<ZooniverseClient.Subject> subjects = client.requestMoreItemsSync(TEST_GROUP_ID, 5); assertTrue((subjects == null) || (subjects.isEmpty())); } catch (final ZooniverseClient.RequestMoreItemsException e) { /* We don't care about the actual cause. final Throwable cause = e.getCause(); if (cause != null) { assertTrue(e.getCause() instanceof IOException); } */ } server.shutdown(); } @Test public void testMoreItemsWithBadResponseCode() throws IOException { final MockWebServer server = new MockWebServer(); final MockResponse response = new MockResponse(); response.setResponseCode(HttpURLConnection.HTTP_NOT_FOUND); response.setBody("test nonsense failure message"); server.enqueue(response); server.start(); final ZooniverseClient client = createZooniverseClient(server); //Mostly we want to check that it doesn't crash on a bad HTTP response. try { final List<ZooniverseClient.Subject> subjects = client.requestMoreItemsSync(TEST_GROUP_ID, 5); assertTrue((subjects == null) || (subjects.isEmpty())); } catch (final ZooniverseClient.RequestMoreItemsException e) { assertNotNull(e.getMessage()); //assertTrue(e.getCause() instanceof ExecutionException); } server.shutdown(); } @Test public void testUploadWithSuccess() throws IOException, InterruptedException, ZooniverseClient.UploadException { final MockWebServer server = new MockWebServer(); final MockResponse response = new MockResponse(); response.setResponseCode(HttpURLConnection.HTTP_CREATED); response.setBody("TODO"); server.enqueue(response); server.start(); final ZooniverseClient client = createZooniverseClient(server); //SyncAdapter.doUploadSync() adds an "interface" parameter too, //but we are testing a more generic API here: final List<HttpUtils.NameValuePair> values = new ArrayList<>(); values.add(new HttpUtils.NameValuePair("classification[subject_ids][]", "504e4a38c499611ea6010c6a")); values.add(new HttpUtils.NameValuePair("classification[favorite][]", "true")); values.add(new HttpUtils.NameValuePair("classification[annotations][0][sloan-0]", "a-0")); values.add(new HttpUtils.NameValuePair("classification[annotations][1][sloan-7]", "a-1")); values.add(new HttpUtils.NameValuePair("classification[annotations][2][sloan-5]", "a-0")); values.add(new HttpUtils.NameValuePair("classification[annotations][3][sloan-6]", "x-5")); final boolean result = client.uploadClassificationSync("testAuthName", "testAuthApiKey", TEST_GROUP_ID, values); assertTrue(result); assertEquals(1, server.getRequestCount()); //This is really just a regression test, //so we notice if something changes unexpectedly: final RecordedRequest request = server.takeRequest(); assertEquals("POST", request.getMethod()); assertEquals("/workflows/" + TEST_GROUP_ID + "/classifications", request.getPath()); assertNotNull(request.getHeader("Authorization")); assertEquals("application/x-www-form-urlencoded", request.getHeader("Content-Type")); final Buffer contents = request.getBody(); final String strContents = contents.readUtf8(); assertEquals("classification%5Bsubject_ids%5D%5B%5D=504e4a38c499611ea6010c6a&classification%5Bfavorite%5D%5B%5D=true&classification%5Bannotations%5D%5B0%5D%5Bsloan-0%5D=a-0&classification%5Bannotations%5D%5B1%5D%5Bsloan-7%5D=a-1&classification%5Bannotations%5D%5B2%5D%5Bsloan-5%5D=a-0&classification%5Bannotations%5D%5B3%5D%5Bsloan-6%5D=x-5", strContents); server.shutdown(); } @Test public void testUploadWithFailure() throws IOException { final MockWebServer server = new MockWebServer(); final MockResponse response = new MockResponse(); response.setResponseCode(HttpURLConnection.HTTP_UNAUTHORIZED); response.setBody("test nonsense failure message"); server.enqueue(response); server.start(); final ZooniverseClient client = createZooniverseClient(server); final List<HttpUtils.NameValuePair> values = new ArrayList<>(); values.add(new HttpUtils.NameValuePair("test nonsense", "12345")); try { final boolean result = client.uploadClassificationSync("testAuthName", "testAuthApiKey", TEST_GROUP_ID, values); assertFalse(result); } catch (final ZooniverseClient.UploadException e) { //This is (at least with okhttp.mockwebserver) a normal //event if the upload was refused via an error response code. assertTrue(e.getCause() instanceof IOException); } server.shutdown(); } private static ZooniverseClient createZooniverseClient(final MockWebServer server) { final HttpUrl mockUrl = server.url("/"); final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); final Context context = instrumentation.getTargetContext(); return new ZooniverseClient(context, mockUrl.toString()); } private static String getStringFromStream(final InputStream input) throws IOException { //Don't bother with try/catch because we are in a test case anyway. final InputStreamReader isr = new InputStreamReader(input, Utils.STRING_ENCODING); final BufferedReader bufferedReader = new BufferedReader(isr); final StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { sb.append(line).append("\n"); } bufferedReader.close(); isr.close(); return sb.toString(); } }
gpl-3.0
lauroabogne/android-table-with-fixed-header-and-column
app/src/main/java/table_1/CustomStateListDrawable.java
758
package table_1; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.StateListDrawable; import android.view.View; class CustomStateListDrawable extends StateListDrawable { /** * * @param view = is the source of default background */ protected CustomStateListDrawable(View view) { int stateFocused = android.R.attr.state_focused; int statePressed = android.R.attr.state_pressed; int stateSelected = android.R.attr.state_selected; this.addState(new int[]{ statePressed },new ColorDrawable(Color.LTGRAY)); this.addState(new int[]{-stateFocused, -statePressed, -stateSelected}, view.getBackground()); } }
gpl-3.0
ckaestne/CIDE
CIDE_Language_XML_concrete/src/tmp/generated_people/Content_blockquote_Choice121.java
837
package tmp.generated_people; import cide.gast.*; import cide.gparser.*; import cide.greferences.*; import java.util.*; public class Content_blockquote_Choice121 extends Content_blockquote_Choice1 { public Content_blockquote_Choice121(Element_del element_del, Token firstToken, Token lastToken) { super(new Property[] { new PropertyOne<Element_del>("element_del", element_del) }, firstToken, lastToken); } public Content_blockquote_Choice121(Property[] properties, IToken firstToken, IToken lastToken) { super(properties,firstToken,lastToken); } public ASTNode deepCopy() { return new Content_blockquote_Choice121(cloneProperties(),firstToken,lastToken); } public Element_del getElement_del() { return ((PropertyOne<Element_del>)getProperty("element_del")).getValue(); } }
gpl-3.0
compwiz1548/ElementalTemples
src/main/java/com/compwiz1548/elementaltemples/init/ModItems.java
1240
package com.compwiz1548.elementaltemples.init; import com.compwiz1548.elementaltemples.item.*; import cpw.mods.fml.common.registry.GameRegistry; public class ModItems { //public static final ItemET mapleLeaf = new ItemMapleLeaf(); public static final ItemET skyRelic = new ItemSkyRelic(); public static final ItemET hellRelic = new ItemHellRelic(); public static final ItemET forestRelic = new ItemForestRelic(); public static final ItemET mountainRelic = new ItemMountainRelic(); public static final ItemET oceanRelic = new ItemOceanRelic(); public static final ItemET desertRelic = new ItemDesertRelic(); public static final ItemET enderRelic = new ItemEnderRelic(); public static void init() { //GameRegistry.registerItem(mapleLeaf, "mapleLeaf"); GameRegistry.registerItem(skyRelic, "skyRelic"); GameRegistry.registerItem(hellRelic, "hellRelic"); GameRegistry.registerItem(forestRelic, "forestRelic"); GameRegistry.registerItem(mountainRelic, "mountainRelic"); GameRegistry.registerItem(oceanRelic, "oceanRelic"); GameRegistry.registerItem(desertRelic, "desertRelic"); GameRegistry.registerItem(enderRelic, "enderRelic"); } }
gpl-3.0
kenji1322/kramerius
client/src/main/java/cz/incad/kramerius/client/tools/UTFSortTool.java
346
package cz.incad.kramerius.client.tools; import cz.incad.kramerius.utils.UTFSort; import java.io.IOException; /** * * @author alberto */ public class UTFSortTool { public String translate(String s) throws IOException{ UTFSort utf_sort = new UTFSort(); utf_sort.init(); return utf_sort.translate(s); } }
gpl-3.0
daemonsoft/wwwairlines
src/java/com/udea/controller/SearchServlet.java
5058
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.udea.controller; import com.udea.business.Cabina; import com.udea.business.Vuelo; import com.udea.business.Vueloxcabina; import com.udea.ejb.CabinaFacadeLocal; import com.udea.ejb.VueloFacadeLocal; import com.udea.ejb.VueloxcabinaFacadeLocal; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author JPOH97 */ public class SearchServlet extends HttpServlet { @EJB private VueloFacadeLocal vueloDAO; @EJB private CabinaFacadeLocal cabinaDAO; @EJB private VueloxcabinaFacadeLocal vueloxcabinaDAO; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { HttpSession session = request.getSession(); String idaStr = request.getParameter("ida"); String[] aux1 = idaStr.split("-"); int idvuelo; int idcabina; Vuelo vuelo; Cabina cabina; Vueloxcabina vc; if (aux1 != null && aux1.length > 1) { idvuelo = Integer.parseInt(aux1[0]); idcabina = Integer.parseInt(aux1[1]); vuelo = vueloDAO.find(idvuelo); cabina = cabinaDAO.find(idcabina); session.setAttribute("cabina1", cabina); session.setAttribute("vuelo1", vuelo); vc = vueloxcabinaDAO.find(cabina, vuelo); session.setAttribute("aeropuertosalida1", vc.getVuelo().getAeropuertoSalida().getNombre()); session.setAttribute("aeropuertollegada1", vc.getVuelo().getAeropuertoLlegada().getNombre()); session.setAttribute("fechaida", vc.getVuelo().getFecha()); session.setAttribute("precioida", vc.getPrecio()); } String tipo = (String) request.getSession().getAttribute("tipo"); if (tipo != null && tipo.equalsIgnoreCase("0")) { String regresoStr = request.getParameter("regreso"); String[] aux2 = regresoStr.split("-"); if (aux2 != null && aux2.length > 1) { idvuelo = Integer.parseInt(aux2[0]); idcabina = Integer.parseInt(aux2[1]); vuelo = vueloDAO.find(idvuelo); cabina = cabinaDAO.find(idcabina); session.setAttribute("cabina2", cabina); session.setAttribute("vuelo2", vuelo); vc = vueloxcabinaDAO.find(cabina, vuelo); session.setAttribute("aeropuertosalida2", vc.getVuelo().getAeropuertoSalida().getNombre()); session.setAttribute("aeropuertollegada2", vc.getVuelo().getAeropuertoLlegada().getNombre()); session.setAttribute("fecharegreso", vc.getVuelo().getFecha()); session.setAttribute("precioregreso", vc.getPrecio()); } } request.getRequestDispatcher("/details.jsp").forward(request, response); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
gpl-3.0
JBYoshi/RobotGame
src/main/java/jbyoshi/robotgame/impl/GameView.java
6088
/* * Copyright (C) 2016 JBYoshi. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jbyoshi.robotgame.impl; import java.util.*; import java.util.function.*; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import jbyoshi.robotgame.action.*; import jbyoshi.robotgame.api.*; import jbyoshi.robotgame.model.*; import jbyoshi.robotgame.util.*; public final class GameView implements Game { private final GameModel model; final PlayerImpl player; private final Function<Model, ModelView<?>> views; private final Set<BoundAction> actions = new LinkedHashSet<>(); public GameView(GameModel game, PlayerImpl player) { this.model = game; this.player = player; views = CacheBuilder.newBuilder().weakValues().<Model, ModelView<?>>build( CacheLoader.from(model -> ViewRegistry.wrap(model, this)))::getUnchecked; } @Override public Set<MyRobotView> getMyRobots() { return getMyViews(RobotModel.class, MyRobotView.class); } @Override public Set<MySpawnerView> getMySpawners() { return getMyViews(SpawnerModel.class, MySpawnerView.class); } @Override public Set<? extends Robot> getEnemyRobots() { return getEnemyViews(RobotModel.class, MyRobotView.class); } @Override public Set<? extends Spawner> getEnemySpawners() { return getEnemyViews(SpawnerModel.class, MySpawnerView.class); } @Override public Set<? extends ObjectInGame> getObjectsNear(Located loc, int distance) { Set<ModelView<?>> out = new HashSet<>(); getObjectsNear(loc, distance, new HashSet<>(), out); return out; } private static final int WORLD_SIZE_HALF = WORLD_SIZE / 2; @Override public Optional<Path> createPath(Located start, Located end, Predicate<Point> isWalkable) { return new AStarPathFinder<Point>() { @Override protected Iterable<Point> getNeighbors(Point point) { return Arrays.stream(Direction.values()).map(point::add).filter(isWalkable)::iterator; } @Override protected int getResistance(Point from, Point to) { return getObjectsAt(to).isEmpty() ? 1 : 1000; } @Override protected int estimateDistanceToEnd(Point point, Point end) { return Math.min(Math.min(estimateDistance(point, end), estimateDistance(point.add(WORLD_SIZE_HALF, 0), end.add(WORLD_SIZE_HALF, 0))), Math.min(estimateDistance(point.add(0, WORLD_SIZE_HALF), end.add(0, WORLD_SIZE_HALF)), estimateDistance(point.add(WORLD_SIZE_HALF, WORLD_SIZE_HALF), end.add(50, 50)))); } private int estimateDistance(Point a, Point b) { return Math.abs(a.getX() - b.getX()) + Math.abs(a.getY() - b.getY()); } }.search(start.getLocation(), end.getLocation()).map(points -> new Path(start.getLocation(), points)); } @Override public Optional<Path> createPath(Located start, Predicate<Point> end, Predicate<Point> isWalkable) { return new DijkstraPathFinder<Point>() { @Override protected Iterable<Point> getNeighbors(Point point) { return Arrays.stream(Direction.values()).map(point::add).filter(isWalkable)::iterator; } @Override protected int getResistance(Point from, Point to) { return getObjectsAt(to).isEmpty() ? 1 : 1000; } }.search(start.getLocation(), end).map(points -> new Path(start.getLocation(), points)); } @Override public <T extends ObjectInGame> Optional<T> findNearest(Located start, Class<T> type, Predicate<T> acceptTarget, Predicate<Point> isWalkable) { Map<Point, T> objects = new HashMap<>(); model.getAllModels().stream().map(views).filter(type::isInstance).map(type::cast) .filter(acceptTarget).forEach(view -> objects.put(view.getLocation(), view)); if (objects.isEmpty()) return Optional.empty(); if (objects.containsKey(start.getLocation())) return Optional.of(objects.get(start.getLocation())); if (objects.size() == 1) { // Optimize using astar. return Optional.of(objects.values().iterator().next()).filter(x -> createPath(start, x.getLocation(), isWalkable).isPresent()); } return createPath(start, objects::containsKey, isWalkable).map(path -> path.getPoint(path.getLength() - 1)) .map(objects::get); } @Override public boolean isWall(Point point) { return model.map[point.getX()][point.getY()]; } private void getObjectsNear(Located loc, int distance, Set<Point> checked, Set<ModelView<?>> out) { if (checked.add(loc.getLocation())) { model.getModelsAt(loc.getLocation()).stream().map(views).forEach(out::add); } if (distance > 0) { for (Direction dir : Direction.values()) { getObjectsNear(loc.getLocation().add(dir), distance - 1, checked, out); } } } private <M extends Model, V extends ModelView<M>> Set<V> getMyViews(Class<M> modelType, Class<V> myViewClass) { return model.getModels(modelType).stream().map(views).flatMap(StreamHelpers.casting(myViewClass)) .collect(StreamHelpers.toImmutableSet()); } @SuppressWarnings({"rawtypes", "unchecked"}) private <M extends Model, V extends ModelView<M>> Set<V> getEnemyViews(Class<M> modelType, Class<? extends V> myViewClass) { return (Set) model.getModels(modelType).stream().map(views).filter(view -> !myViewClass.isInstance(view)) .collect(StreamHelpers.toImmutableSet()); } <T extends Model> void addAction(T model, Action<? super T> action) { actions.add(new BoundAction(action, model.getId())); } public Set<BoundAction> popActions() { Set<BoundAction> actions = new LinkedHashSet<>(this.actions); this.actions.clear(); return actions; } }
gpl-3.0
FRCTeam4069/RobotCode2012
src/frc/t4069/robots/subsystems/BallPickupArm.java
645
package frc.t4069.robots.subsystems; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Victor; import frc.t4069.robots.RobotMap; import frc.t4069.utils.Logger; public class BallPickupArm { private Victor m_armMotor; private DigitalInput m_limitswitch1; public static final double SPEED = 0.6; public BallPickupArm() { m_armMotor = new Victor(RobotMap.ARM_MOTOR); m_limitswitch1 = new DigitalInput(RobotMap.ARM_LIMITSWITCH); } public void setArm(double speed) { if (speed < 0) { speed = m_limitswitch1.get() ? 0 : speed; if (speed == 0) Logger.i("Limit switched!"); } m_armMotor.set(speed); } }
gpl-3.0
githubofryry/ActiveHouseV2
app/src/test/java/ahstudios/activehousev2/ExampleUnitTest.java
401
package ahstudios.activehousev2; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
gpl-3.0
mozartframework/cms
src/com/mozartframework/xml/formatter/SVGJPGFormatter.java
3014
package com.mozartframework.xml.formatter; import java.io.OutputStream; import java.io.Writer; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import org.apache.batik.dom.svg.SVGDOMImplementation; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.image.JPEGTranscoder; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; import com.mozartframework.io.InputOutputException; import com.mozartframework.logger.TLogger; import com.mozartframework.xml.Result; public class SVGJPGFormatter extends Formatter { private TLogger logger = new TLogger(SVGJPGFormatter.class); public SVGJPGFormatter() { setContentType("image/jpeg"); } public void format(Result result, OutputStream out) throws InputOutputException { try{ Document doc = result.getDocument(); Transformer transformer = result.getTransformer(); Source src = new DOMSource(doc); String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI; DOMImplementation impl = SVGDOMImplementation.getDOMImplementation(); Document svgDoc = impl.createDocument(svgNS, "svg", null); Element root = doc.getDocumentElement(); svgDoc.getDocumentElement().setAttributeNS(null, "width", root.getAttribute("width")); svgDoc.getDocumentElement().setAttributeNS(null, "height", root.getAttribute("height")); transformer.transform(src, new DOMResult(svgDoc.getDocumentElement())); JPEGTranscoder t = new JPEGTranscoder(); t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(.8)); t.addTranscodingHint(JPEGTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER, new Float(0.2645833f)); //96pi, 0.3528f for 72pi TranscoderInput input = new TranscoderInput(svgDoc); logger.debug("JPEGTranscoder: sending image to client"); TranscoderOutput output = new TranscoderOutput(out); t.transcode(input, output); out.flush(); addIncludes(result.getIncludes()); } catch(Exception e) { throw new InputOutputException(0, e); } } public void format(Document document, OutputStream outstr) throws InputOutputException { throw new RuntimeException("Not implemented"); } public void format(Document document, Writer outWriter) throws InputOutputException { throw new RuntimeException("Not implemented"); } public void format(DocumentFragment frag, OutputStream outstr) throws InputOutputException { throw new RuntimeException("Not implemented"); } public void format(DocumentFragment frag, Writer outWriter) throws InputOutputException { throw new RuntimeException("Not implemented"); } }
gpl-3.0
aherbert/GDSC-SMLM
src/main/java/uk/ac/sussex/gdsc/smlm/results/TraceManager.java
58068
/*- * #%L * Genome Damage and Stability Centre SMLM ImageJ Plugins * * Software for single molecule localisation microscopy (SMLM) * %% * Copyright (C) 2011 - 2020 Alex Herbert * %% * 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 uk.ac.sussex.gdsc.smlm.results; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.set.hash.TIntHashSet; import java.util.ArrayList; import java.util.Arrays; import uk.ac.sussex.gdsc.core.data.utils.ConversionException; import uk.ac.sussex.gdsc.core.data.utils.TypeConverter; import uk.ac.sussex.gdsc.core.logging.TrackProgress; import uk.ac.sussex.gdsc.core.utils.ValidationUtils; import uk.ac.sussex.gdsc.smlm.data.config.CalibrationHelper; import uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration; import uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSF; import uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSFType; import uk.ac.sussex.gdsc.smlm.data.config.PsfHelper; import uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit; import uk.ac.sussex.gdsc.smlm.results.count.Counter; import uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure; /** * Trace localisations through a time stack to identify single molecules. */ public class TraceManager { /** * Set the mode used to search backwards in time. */ public enum TraceMode { //@formatter:off /** * Search the latest localisations first. This is equivalent to a downwards search. * When a localisation is found no more time points will be searched. */ LATEST_FORERUNNER{ @Override public String getName() { return "Latest forerunner"; }}, /** * Search the earliest localisations first. This is equivalent to a depth first search. * When a localisation is found no more time points will be searched. */ EARLIEST_FORERUNNER{ @Override public String getName() { return "Earliest forerunner"; }}, /** * Search all time points within the distance threshold. This is slower as all time points * are searched. It is equivalent to single-linkage clustering with a time constraint on * joined localisations. */ SINGLE_LINKAGE{ @Override public String getName() { return "Single linkage"; }}; //@formatter:on @Override public String toString() { return getName(); } /** * Gets the name. * * @return the name */ public abstract String getName(); } private MemoryPeakResults results; private Localisation[] localisations; private Localisation[] endLocalisations; private int[] indexes; private int[] endIndexes; private int[] maxTime; private int totalTraces; private int totalFiltered; private float distanceThreshSqaured; private float distanceExclusionSquared; private TrackProgress tracker; private int activationFrameInterval; private int activationFrameWindow; private double distanceExclusion; private boolean filterActivationFrames; private TraceMode traceMode = TraceMode.LATEST_FORERUNNER; private int pulseInterval; /** * The distance between the localisation and its assigned forerunner. * * <p>Set in {@link #findForerunner(int, int, int)} and * {@link #findAlternativeForerunner(int, int, int, int, int[])}. */ private float minD; private static class Localisation { int time; int endTime; int id; int trace; float x; float y; Localisation(int id, int time, int endTime, float x, float y) { ValidationUtils.checkArgument(endTime >= time, "End time (%d) is before the start time (%d)", endTime, time); this.time = time; this.endTime = endTime; this.id = id; this.x = x; this.y = y; } float distance2(Localisation other) { final float dx = x - other.x; final float dy = y - other.y; return dx * dx + dy * dy; } } private static class Assignment { int index; float distance; int traceId; public Assignment(int index, float distance, int traceId) { this.index = index; this.distance = distance; this.traceId = traceId; } } /** * Instantiates a new trace manager. * * @param results the results * @throws IllegalArgumentException if results are null or empty */ public TraceManager(final MemoryPeakResults results) { if (results == null || results.size() == 0) { throw new IllegalArgumentException("Results are null or empty"); } this.results = results; // Assign localisations. We use the native result units to avoid conversion exceptions. localisations = new Localisation[results.size()]; Counter counter = new Counter(); results.forEach((PeakResultProcedure) result -> { final int id = counter.getAndIncrement(); localisations[id] = new Localisation(id, result.getFrame(), result.getEndFrame(), result.getXPosition(), result.getYPosition()); }); totalTraces = localisations.length; // Sort by start time Arrays.sort(localisations, (o1, o2) -> Integer.compare(o1.time, o2.time)); // The algorithm assumes minT is positive if (localisations[0].time < 0) { throw new IllegalArgumentException("Lowest start time is negative"); } // Build a second localisations list sorted by end time endLocalisations = Arrays.copyOf(localisations, totalTraces); Arrays.sort(endLocalisations, (o1, o2) -> Integer.compare(o1.endTime, o2.endTime)); // Create a look-up table of the starting index in each localisations array for each possible // time point. This allows looping over all localisations for a given t using the index // index[t] <= i < index[t+1] int maxT = localisations[totalTraces - 1].time; indexes = new int[maxT + 2]; int time = -1; for (int i = 0; i < localisations.length; i++) { while (time < localisations[i].time) { indexes[++time] = i; } } indexes[maxT + 1] = totalTraces; maxT = endLocalisations[totalTraces - 1].endTime; endIndexes = new int[maxT + 2]; time = -1; for (int i = 0; i < endLocalisations.length; i++) { while (time < endLocalisations[i].endTime) { endIndexes[++time] = i; } } endIndexes[maxT + 1] = totalTraces; // TODO - Assign a more efficient localisation representation using a grid } /** * Trace localisations across frames that are the same molecule. * * <p>Any spot that occurred within time threshold and distance threshold of a previous spot is * grouped into the same trace as that previous spot. The resulting trace is assigned a spatial * position equal to the centroid position of all the spots included in the trace. * * <p>See Coltharp, et al. Accurate Construction of Photoactivated Localization Microscopy (PALM) * Images for Quantitative Measurements (2012). PLoS One. 7(12): e51725. DOI: * http://dx.doi.org/10.1371%2Fjournal.pone.0051725 * * <p>Note: The actual traces representing molecules can be obtained by calling * {@link #getTraces()} * * @param distanceThreshold The distance threshold in the native units of the results * @param timeThreshold The time threshold in frames * @return The number of traces */ public int traceMolecules(final double distanceThreshold, final int timeThreshold) { if (timeThreshold <= 0 || distanceThreshold < 0) { totalTraces = localisations.length; return totalTraces; } totalTraces = totalFiltered = 0; distanceThreshSqaured = (float) (distanceThreshold * distanceThreshold); distanceExclusionSquared = (distanceExclusion >= distanceThreshold) ? (float) (distanceExclusion * distanceExclusion) : 0; if (tracker != null) { tracker.progress(0); } // Used to track the highest frame containing spots for a trace maxTime = new int[localisations.length + 1]; final int[] traceIdToLocalisationsIndexMap = new int[localisations.length + 1]; // Initialise the first traces using the first frame int nextIndex = indexes[localisations[0].time + 1]; // findNextStartTimeIndex(0); for (int index = 0; index < nextIndex; index++) { localisations[index].trace = addTrace(index, traceIdToLocalisationsIndexMap, maxTime); } Assignment[] assigned = new Assignment[10]; // Now process the remaining frames, comparing them to previous frames while (nextIndex < localisations.length) { if (tracker != null) { tracker.progress(nextIndex, localisations.length); } final int currentIndex = nextIndex; final int t = localisations[currentIndex].time; nextIndex = indexes[t + 1]; int pastT = Math.max(t - timeThreshold, 0); if (pulseInterval > 0) { // Support for splitting traces across pulse boundaries. Simply round the // previous timepoint to the next pulse boundary. Assume pulses start at t=1 final int intervalBoundary = 1 + pulseInterval * ((t - 1) / pulseInterval); if (pastT < intervalBoundary) { pastT = intervalBoundary; } } final int pastEndIndex = endIndexes[pastT]; final int currentEndIndex = endIndexes[t]; // If no previous spots within the time threshold then create new traces if (pastEndIndex == currentEndIndex) { for (int index = currentIndex; index < nextIndex; index++) { localisations[index].trace = addTrace(index, traceIdToLocalisationsIndexMap, maxTime); } continue; } // Check the allocated buffer is larger enough if (assigned.length < nextIndex - currentIndex) { assigned = new Assignment[nextIndex - currentIndex]; } // Process all spots from this frame. Note if a spot is allocated to an existing trace. int assignedToTrace = 0; for (int index = currentIndex; index < nextIndex; index++) { final int traceId = findForerunner(index, pastEndIndex, currentEndIndex); if (traceId == 0) { localisations[index].trace = addTrace(index, traceIdToLocalisationsIndexMap, maxTime); } else { // Tentatively assign assigned[assignedToTrace++] = new Assignment(index, minD, traceId); } } if (assignedToTrace > 1) { // Check if duplicate allocations are made. Each trace can only // be allocated one localisation so in the event of a multiple // allocation then only the closest spot should be allocated final int[] dualAllocation = new int[assignedToTrace]; final int[] ignore = new int[assignedToTrace]; int ignoreCount = 0; // Only check for duplicates if two assignments are remaining boolean reSort = true; for (int i = 0; i < assignedToTrace - 1; i++) { // If the distance is negative then this can be skipped as it was a new trace // (allocated in a previous loop). if (assigned[i].distance < 0) { continue; } // Sort the remaining allocations by their distance if (reSort) { reSort = false; Arrays.sort(assigned, i, assignedToTrace, (o1, o2) -> Double.compare(o1.distance, o2.distance)); // Check for new traces (allocated in a previous loop). These have distance <0 so will // be sorted to the front. if (assigned[i].distance < 0) { continue; } } int dualAllocationCount = 0; for (int j = i + 1; j < assignedToTrace; j++) { // Dual allocation if (assigned[i].traceId == assigned[j].traceId) { dualAllocation[dualAllocationCount++] = j; } } // This trace has been taken so ignore when finding alternatives ignore[ignoreCount++] = assigned[i].traceId; if (dualAllocationCount > 0) { // Re-allocate the other spots for (int a = 0; a < dualAllocationCount; a++) { final int j = dualAllocation[a]; final int index = assigned[j].index; int traceId = findAlternativeForerunner(index, pastEndIndex, currentEndIndex, ignoreCount, ignore); if (traceId == 0) { traceId = addTrace(index, traceIdToLocalisationsIndexMap, maxTime); // Mark to ignore assigned[j].distance = -1; } else { // Indicate that the distances have changed and a re-sort is needed reSort = true; assigned[j].distance = minD; } assigned[j].traceId = traceId; } } // Ensure nothing can be sorted ahead of this trace assignment assigned[i].distance = -1; } } // Assign the localisations for (int i = 0; i < assignedToTrace; i++) { localisations[assigned[i].index].trace = assigned[i].traceId; maxTime[assigned[i].traceId] = localisations[assigned[i].index].endTime; } } if (tracker != null) { tracker.progress(1.0); } return getTotalTraces(); } private int addTrace(int index, int[] traceIdToLocalisationsIndexMap, int[] maxT) { if (filterActivationFrames // Count the number of traces that will be filtered // (i.e. the time is not within an activation window) && outsideActivationWindow(localisations[index].time)) { totalFiltered++; } final int traceId = ++totalTraces; traceIdToLocalisationsIndexMap[traceId] = index; maxT[traceId] = localisations[index].endTime; return traceId; } private boolean outsideActivationWindow(int time) { return time % activationFrameInterval > activationFrameWindow; } /** * Gets the traces that have been found using {@link #traceMolecules(double, int)}. * * @return The traces */ public Trace[] getTraces() { final PeakResult[] peakResults = results.toArray(); // No tracing yet performed or no thresholds if (totalTraces == localisations.length) { if (filterActivationFrames) { final ArrayList<Trace> traces = new ArrayList<>(); for (int i = 0; i < totalTraces; i++) { final PeakResult peakResult = peakResults[localisations[i].id]; if (!outsideActivationWindow(peakResult.getFrame())) { traces.add(new Trace(peakResult)); } } return traces.toArray(new Trace[0]); } final Trace[] traces = new Trace[localisations.length]; for (int i = 0; i < traces.length; i++) { traces[i] = new Trace(peakResults[localisations[i].id]); } return traces; } if (tracker != null) { tracker.progress(0); } // Build the list of traces final Trace[] traces = new Trace[getTotalTraces()]; int count = 0; // for (int index = 0; index < localisations.length; index++) // if (localisations[index].trace == 0) // System.out.printf("error @ %d\n", index); // Since the trace numbers are allocated by processing the spots in frames, each frame can have // trace number out-of-order. This occurs if re-allocation has been performed, // e.g. [1,2,2,1,3] => [1,2,5,4,3] when spots in group 1 are reallocated before spots in group // 2. final TIntHashSet processedTraces = new TIntHashSet(traces.length); for (int i = 0; i < localisations.length; i++) { if (tracker != null && i % 256 == 0) { tracker.progress(i, localisations.length); } final int traceId = localisations[i].trace; if (!processedTraces.add(traceId)) { // Already present continue; } if (filterActivationFrames && outsideActivationWindow(localisations[i].time)) { continue; } final PeakResult peakResult = peakResults[localisations[i].id]; final Trace nextTrace = new Trace(peakResult); nextTrace.setId(traceId); final int tLimit = maxTime[traceId]; // Check if the trace has later frames if (tLimit > localisations[i].time) { for (int j = i + 1; j < localisations.length; j++) { if (localisations[j].time > tLimit) { break; } if (localisations[j].trace == traceId) { nextTrace.add(peakResults[localisations[j].id]); } } } traces[count++] = nextTrace; } if (tracker != null) { tracker.progress(1.0); } return traces; } /** * Convert a list of traces into peak results. The centroid of each trace is used as the * coordinates. The standard deviation of positions from the centre is used as the width. The * amplitude is the average from all the peaks in the trace. * * @param traces the traces * @return the peak results */ public static MemoryPeakResults toCentroidPeakResults(final Trace[] traces) { final int capacity = 1 + ((traces != null) ? traces.length : 0); final MemoryPeakResults results = new MemoryPeakResults(capacity); if (traces != null) { for (int i = 0; i < traces.length; i++) { final PeakResult result = traces[i].getHead(); if (result == null) { continue; } final float[] centroid = traces[i].getCentroid(); final float sd = traces[i].getStandardDeviation(); final float background = 0; final float signal = (float) traces[i].getSignal(); final float[] params = new float[] {background, signal, 0, centroid[0], centroid[1], sd, sd}; final int endFrame = traces[i].getTail().getEndFrame(); results.add(new ExtendedPeakResult(result.getFrame(), result.getOrigX(), result.getOrigY(), result.getOrigValue(), 0, 0, 0, params, null, endFrame, i + 1)); } } return results; } /** * Convert a list of traces into peak results. The signal weighted centroid of each trace is used * as the coordinates. The weighted localisation precision is used as the precision. The signal is * the sum from all the peaks in the trace. * * <p>If the trace is empty it is ignored. * * <p>The results will only have the standard parameters set [Background,Intensity,X,Y,Z] so a * custom PSF is added to the results. * * @param traces the traces * @param calibration the calibration * @return the peak results * @see PSFType#CUSTOM */ public static MemoryPeakResults toCentroidPeakResults(final Trace[] traces, final Calibration calibration) { final int capacity = 1 + ((traces != null) ? traces.length : 0); final MemoryPeakResults results = new MemoryPeakResults(capacity); results.setCalibration(calibration); results.setPsf(PsfHelper.create(PSFType.CUSTOM)); if (traces != null) { TypeConverter<DistanceUnit> converter = null; if (calibration != null) { try { converter = CalibrationHelper.getDistanceConverter(calibration, DistanceUnit.NM); } catch (final ConversionException ex) { // Ignore } } // Ensure all results are added as extended peak results with their trace ID. for (int i = 0; i < traces.length; i++) { if (traces[i] == null || traces[i].size() == 0) { continue; } final PeakResult result = traces[i].getHead(); if (traces[i].size() == 1) { final AttributePeakResult peakResult = new AttributePeakResult(result.getFrame(), result.getOrigX(), result.getOrigY(), result.getOrigValue(), 0, result.getNoise(), result.getMeanIntensity(), result.getParameters(), null); peakResult.setId(traces[i].getId()); peakResult.setEndFrame(result.getEndFrame()); if (converter != null) { peakResult.setPrecision(traces[i].getLocalisationPrecision(converter)); } results.add(peakResult); } else { traces[i].sort(); traces[i].resetCentroid(); final float[] centroid = traces[i].getCentroid(); float background = 0; double noise = 0; for (final PeakResult r : traces[i].getPoints().toArray()) { noise += r.getNoise() * r.getNoise(); background += r.getBackground(); } noise = Math.sqrt(noise); background /= traces[i].size(); final double signal = traces[i].getSignal(); final int endFrame = traces[i].getTail().getEndFrame(); final AttributePeakResult peakResult = new AttributePeakResult(result.getFrame(), centroid[0], centroid[1], (float) signal); // Build standard peak data peakResult.setBackground(background); peakResult.setNoise((float) noise); // These could be weighted, at the moment we use the first peak peakResult.setOrigX(result.getOrigX()); peakResult.setOrigY(result.getOrigY()); peakResult.setOrigValue(result.getOrigValue()); peakResult.setId(traces[i].getId()); peakResult.setEndFrame(endFrame); if (converter != null) { peakResult.setPrecision(traces[i].getLocalisationPrecision(converter)); } results.add(peakResult); } } } return results; } /** * Convert a list of traces into peak results setting the trace ID into the results. * * <p>If the trace is empty it is ignored. * * @param traces the traces * @param calibration the calibration * @return the peak results */ public static MemoryPeakResults toPeakResults(final Trace[] traces, final Calibration calibration) { return toPeakResults(traces, calibration, false); } /** * Convert a list of traces into peak results setting the trace ID into the results. * * <p>If the trace is empty it is ignored. * * @param traces the traces * @param calibration the calibration * @param newId Set to true to use a new ID for each trace * @return the peak results */ public static MemoryPeakResults toPeakResults(final Trace[] traces, final Calibration calibration, boolean newId) { final int capacity = 1 + ((traces != null) ? traces.length : 0); final MemoryPeakResults results = new MemoryPeakResults(capacity); results.setCalibration(calibration); if (traces != null) { // Ensure all results are added as extended peak results with their trace ID. int id = 0; for (final Trace trace : traces) { if (trace == null || trace.size() == 0) { continue; } final int traceId = (newId) ? ++id : trace.getId(); trace.getPoints().forEach((PeakResultProcedure) result -> { results.add(new ExtendedPeakResult(result.getFrame(), result.getOrigX(), result.getOrigY(), result.getOrigValue(), result.getError(), result.getNoise(), result.getMeanIntensity(), result.getParameters(), result.getParameterDeviations(), result.getEndFrame(), traceId)); }); } } return results; } /** * Convert a list of traces into peak results. The signal weighted centroid of each trace is used * as the coordinates. The weighted localisation precision is used as the width. The amplitude is * the average from all the peaks in the trace. * * <p>Uses the title and bounds from the constructor peak results. The title has the word 'Traced * Centroids' appended. * * @param traces the traces * @return the peak results */ public MemoryPeakResults convertToCentroidPeakResults(final Trace[] traces) { return convertToCentroidPeakResults(results, traces); } /** * Convert a list of traces into peak results. The signal weighted centroid of each trace is used * as the coordinates. The weighted localisation precision is used as the width. The amplitude is * the average from all the peaks in the trace. * * <p>Uses the title and bounds from the provided peak results. The title has the word 'Traced * Centroids' appended. * * @param source the source * @param traces the traces * @return the peak results */ public static MemoryPeakResults convertToCentroidPeakResults(MemoryPeakResults source, final Trace[] traces) { final MemoryPeakResults results = toCentroidPeakResults(traces, source.getCalibration()); // Do not copy the PSF as it is invalid for centroids final PSF psf = results.getPsf(); results.copySettings(source); results.setPsf(psf); // Change name results.setName(source.getSource() + " Traced Centroids"); // TODO - Add the tracing settings return results; } /** * Convert a list of traces into peak results. * * <p>Uses the title and bounds from the constructor peak results. The title has the word 'Traced' * appended. * * @param traces the traces * @return the peak results */ public MemoryPeakResults convertToPeakResults(final Trace[] traces) { return convertToPeakResults(results, traces); } /** * Convert a list of traces into peak results. * * <p>Uses the title and bounds from the provided peak results. The title has the word 'Traced' * appended. * * @param source the source * @param traces the traces * @return the peak results */ public static MemoryPeakResults convertToPeakResults(MemoryPeakResults source, final Trace[] traces) { final MemoryPeakResults results = toPeakResults(traces, source.getCalibration()); results.copySettings(source); // Change name results.setName(source.getSource() + " Traced"); // TODO - Add the tracing settings return results; } /** * From the given index, move forward to a localisation with a new start time frame. If no more * frames return the number of localisations. * * @param index the index * @return The index of the next time frame */ @SuppressWarnings("unused") private int findNextStartTimeIndex(int index) { final int t = localisations[index].time; while (index < localisations.length && localisations[index].time <= t) { index++; } return index; } /** * From the given index, move forward to a localisation with a start time beyond the time * threshold. If no more frames return the number of localisations. * * @param index the index * @param timeThreshold the time threshold * @return The index of the next time frame */ @SuppressWarnings("unused") private int findNextStartTimeIndex(int index, final int timeThreshold) { final int t = localisations[index].time + timeThreshold; while (index < localisations.length && localisations[index].time <= t) { index++; } return index; } /** * From the given index, move backward to the earliest localisations within the time threshold. * * @param index the index * @param timeThreshold the time threshold * @return The index of the earliest localisation within the time threshold */ @SuppressWarnings("unused") private int findPastTimeIndex(int index, final int timeThreshold) { final int t = localisations[index].time - timeThreshold; while (index > 0) { index--; if (localisations[index].time < t) { index++; // Set back to within the time threshold break; } } return index; } /** * Find the earliest forerunner spot (from pastIndex to currentIndex) that is within the distance * threshold of the given spot. In the event that multiple forerunner spots from the same frame * are within the distance, assign the closest spot. * * @param index The index of the spot * @param pastIndex The index of the earliest forerunner spot * @param currentIndex The index of the first spot in the same frame (i.e. end of forerunner * spots) * @return The assigned trace */ private int findForerunner(final int index, final int pastIndex, final int currentIndex) { if (distanceExclusionSquared == 0) { return findForerunnerNoExclusion(index, pastIndex, currentIndex); } return findForerunnerWithExclusion(index, pastIndex, currentIndex); } /** * Find the earliest forerunner spot (from pastIndex to currentIndex) that is within the distance * threshold of the given spot. In the event that multiple forerunner spots from the same frame * are within the distance, assign the closest spot. * * @param index The index of the spot * @param pastIndex The index of the earliest forerunner spot * @param currentIndex The index of the first spot in the same frame (i.e. end of forerunner * spots) * @return The assigned trace */ private int findForerunnerNoExclusion(final int index, final int pastIndex, final int currentIndex) { final Localisation spot = localisations[index]; if (traceMode == TraceMode.EARLIEST_FORERUNNER) { for (int i = pastIndex; i < currentIndex; i++) { final float d2 = spot.distance2(endLocalisations[i]); if (d2 <= distanceThreshSqaured) { minD = d2; int trace = endLocalisations[i].trace; // Search all remaining spots that end in this time frame and pick the closest final int nextIndex = endIndexes[endLocalisations[i].endTime + 1]; for (int ii = i + 1; ii < nextIndex; ii++) { final float dd2 = spot.distance2(endLocalisations[ii]); if (dd2 < minD) { minD = dd2; trace = endLocalisations[ii].trace; } } return trace; } } } else if (traceMode == TraceMode.LATEST_FORERUNNER) { for (int i = currentIndex; i-- > pastIndex;) { final float d2 = spot.distance2(endLocalisations[i]); if (d2 <= distanceThreshSqaured) { minD = d2; int trace = endLocalisations[i].trace; // Search all remaining spots in this time frame and pick the closest final int previousIndex = endIndexes[endLocalisations[i].endTime]; //// DEBUG // int previousIndex = i; //// Look for the index for the previous time-frame // while (previousIndex > 0 && endLocalisations[previousIndex-1].t == //// endLocalisations[i].t) // previousIndex--; // if (previousIndex != endIndex[endLocalisations[i].endT]) // { // System.out.printf("Error when tracing: %d != %d\n", previousIndex, // endIndex[endLocalisations[i].endT]); // } for (int ii = i; ii-- > previousIndex;) { final float dd2 = spot.distance2(endLocalisations[ii]); if (dd2 < minD) { minD = dd2; trace = endLocalisations[ii].trace; } } return trace; } } } else { // traceMode == TraceMode.SINGLE_LINKAGE // Find the closest spot minD = distanceThreshSqaured; int minI = -1; for (int i = pastIndex; i < currentIndex; i++) { final float d2 = spot.distance2(endLocalisations[i]); if (d2 <= minD) { minD = d2; minI = i; } } if (minI == -1) { return 0; } return endLocalisations[minI].trace; } return 0; } /** * Find the earliest forerunner spot (from pastIndex to currentIndex) that is within the distance * threshold of the given spot. In the event that multiple forerunner spots from the same frame * are within the distance, assign the closest spot. * * <p>This method respects the exclusion distance. No spot can be assigned if a the next closest * spot is within the exclusion distance. * * @param index The index of the spot * @param pastIndex The index of the earliest forerunner spot * @param currentIndex The index of the first spot in the same frame (i.e. end of forerunner * spots) * @return The assigned trace */ private int findForerunnerWithExclusion(final int index, final int pastIndex, final int currentIndex) { final Localisation spot = localisations[index]; // Check that the next farthest spot is above the exclusion distance float nextMinD = Float.POSITIVE_INFINITY; int currentT; if (traceMode == TraceMode.EARLIEST_FORERUNNER) { currentT = endLocalisations[pastIndex].time; for (int i = pastIndex; i < currentIndex; i++) { final float d2 = spot.distance2(endLocalisations[i]); if (d2 <= distanceThreshSqaured) { minD = d2; int trace = endLocalisations[i].trace; // Search all remaining spots that end in this time frame and pick the closest final int nextIndex = endIndexes[endLocalisations[i].endTime + 1]; for (int ii = i + 1; ii < nextIndex; ii++) { final float dd2 = spot.distance2(endLocalisations[ii]); if (dd2 < minD) { nextMinD = minD; minD = dd2; trace = endLocalisations[ii].trace; } } return (nextMinD > distanceExclusionSquared) ? trace : 0; } else if (currentT == endLocalisations[i].time) { // Store the minimum distance to the next spot in the same frame if (d2 < nextMinD) { nextMinD = d2; } } else { // New time frame so reset the distance to the next spot in the same frame nextMinD = d2; } currentT = endLocalisations[i].time; } } else if (traceMode == TraceMode.LATEST_FORERUNNER) { currentT = endLocalisations[currentIndex].time; for (int i = currentIndex; i-- > pastIndex;) { final float d2 = spot.distance2(endLocalisations[i]); if (d2 <= distanceThreshSqaured) { minD = d2; int trace = endLocalisations[i].trace; // Search all remaining spots in this time frame and pick the closest final int previousIndex = endIndexes[endLocalisations[i].endTime]; // int previousIndex = i; //// Look for the index for the previous time-frame // while (previousIndex > 0 && endLocalisations[previousIndex-1].t == // endLocalisations[i].t) // previousIndex--; // if (previousIndex != endIndex[endLocalisations[i].endT]) // { // System.out.printf("Error when tracing: %d != %d\n", previousIndex, // endIndex[endLocalisations[i].endT]); // } for (int ii = i; ii-- > previousIndex;) { final float dd2 = spot.distance2(endLocalisations[ii]); if (dd2 < minD) { nextMinD = minD; minD = dd2; trace = endLocalisations[ii].trace; } } return (nextMinD > distanceExclusionSquared) ? trace : 0; } else if (currentT == endLocalisations[i].time) { // Store the minimum distance to the next spot in the same frame if (d2 < nextMinD) { nextMinD = d2; } } else { // New time frame so reset the distance to the next spot in the same frame nextMinD = d2; } currentT = endLocalisations[i].time; } } else { // traceMode == TraceMode.SINGLE_LINKAGE // Find the closest spot minD = distanceThreshSqaured; int minI = -1; for (int i = pastIndex; i < currentIndex; i++) { final float d2 = spot.distance2(endLocalisations[i]); if (d2 <= minD) { minD = d2; minI = i; } } if (minI == -1) { return 0; } if (distanceExclusionSquared > 0) { // Check all spots in the same frame final int previousIndex = endIndexes[endLocalisations[minI].endTime]; final int nextIndex = endIndexes[endLocalisations[minI].endTime + 1]; for (int i = previousIndex; i < nextIndex; i++) { if (i == minI) { continue; } final float d2 = spot.distance2(endLocalisations[i]); if (d2 <= nextMinD) { nextMinD = d2; } } } return (nextMinD > distanceExclusionSquared) ? endLocalisations[minI].trace : 0; } return 0; } /** * Find the earliest forerunner spot (from pastIndex to currentIndex) that is within the distance * threshold of the given spot. In the event that multiple forerunner spots from the same frame * are within the distance, assign the closest spot. * * <p>Do not assigned to the specified trace to ignore. * * @param index The index of the spot * @param pastIndex The index of the earliest forerunner spot * @param currentIndex The index of the first spot in the same frame (i.e. end of forerunner * spots) * @param ignoreCount The count of traces to ignore * @param ignore The traces to ignore * @return The assigned trace */ private int findAlternativeForerunner(final int index, final int pastIndex, final int currentIndex, final int ignoreCount, final int[] ignore) { if (distanceExclusionSquared == 0) { return findAlternativeForerunnerNoExclusion(index, pastIndex, currentIndex, ignoreCount, ignore); } return findAlternativeForerunnerWithExclusion(index, pastIndex, currentIndex, ignoreCount, ignore); } /** * Find the earliest forerunner spot (from pastIndex to currentIndex) that is within the distance * threshold of the given spot. In the event that multiple forerunner spots from the same frame * are within the distance, assign the closest spot. * * <p>Do not assigned to the specified trace to ignore. * * @param index The index of the spot * @param pastIndex The index of the earliest forerunner spot * @param currentIndex The index of the first spot in the same frame (i.e. end of forerunner * spots) * @param ignoreCount The count of traces to ignore * @param ignore The traces to ignore * @return The assigned trace */ private int findAlternativeForerunnerNoExclusion(final int index, final int pastIndex, final int currentIndex, final int ignoreCount, final int[] ignore) { final Localisation spot = localisations[index]; if (traceMode == TraceMode.EARLIEST_FORERUNNER) { for (int i = pastIndex; i < currentIndex; i++) { if (ignore(i, ignoreCount, ignore)) { continue; } final float d2 = spot.distance2(endLocalisations[i]); if (d2 <= distanceThreshSqaured) { minD = d2; int trace = endLocalisations[i].trace; // Search all remaining spots in this time frame and pick the closest final int nextIndex = endIndexes[endLocalisations[i].endTime + 1]; // int nextIndex = i; // // Look for the index for the next time-frame // for (int tt = endLocalisations[i].endT + 1; tt < endIndex.length; tt++) // { // nextIndex = endIndex[tt]; // if (nextIndex != i) // break; // } for (int ii = i + 1; ii < nextIndex; ii++) { if (ignore(ii, ignoreCount, ignore)) { continue; } final float dd2 = spot.distance2(endLocalisations[ii]); if (dd2 < minD) { minD = dd2; trace = endLocalisations[ii].trace; } } return trace; } } } else if (traceMode == TraceMode.LATEST_FORERUNNER) { for (int i = currentIndex; i-- > pastIndex;) { if (ignore(i, ignoreCount, ignore)) { continue; } final float d2 = spot.distance2(endLocalisations[i]); if (d2 <= distanceThreshSqaured) { minD = d2; int trace = endLocalisations[i].trace; // Search all remaining spots in this time frame and pick the closest final int previousIndex = endIndexes[endLocalisations[i].endTime]; // int previousIndex = i; //// Look for the index for the previous time-frame // while (previousIndex > 0 && endLocalisations[previousIndex-1].t == // endLocalisations[i].t) // previousIndex--; // if (previousIndex != endIndex[endLocalisations[i].endT]) // { // System.out.printf("Error when tracing: %d != %d\n", previousIndex, // endIndex[endLocalisations[i].endT]); // } for (int ii = i; ii-- > previousIndex;) { if (ignore(ii, ignoreCount, ignore)) { continue; } final float dd2 = spot.distance2(endLocalisations[ii]); if (dd2 < minD) { minD = dd2; trace = endLocalisations[ii].trace; } } return trace; } } } else { // traceMode == TraceMode.SINGLE_LINKAGE // Find the closest spot minD = distanceThreshSqaured; int minI = -1; for (int i = pastIndex; i < currentIndex; i++) { if (ignore(i, ignoreCount, ignore)) { continue; } final float d2 = spot.distance2(endLocalisations[i]); if (d2 <= minD) { minD = d2; minI = i; } } if (minI == -1) { return 0; } return endLocalisations[minI].trace; } return 0; } /** * Find the earliest forerunner spot (from pastIndex to currentIndex) that is within the distance * threshold of the given spot. In the event that multiple forerunner spots from the same frame * are within the distance, assign the closest spot. * * <p>This method respects the exclusion distance. No spot can be assigned if a the next closest * spot is within the exclusion distance. * * <p>Do not assigned to the specified trace to ignore. * * @param index The index of the spot * @param pastIndex The index of the earliest forerunner spot * @param currentIndex The index of the first spot in the same frame (i.e. end of forerunner * spots) * @param ignoreCount The count of traces to ignore * @param ignore The traces to ignore * @return The assigned trace */ private int findAlternativeForerunnerWithExclusion(final int index, final int pastIndex, final int currentIndex, final int ignoreCount, final int[] ignore) { final Localisation spot = localisations[index]; // Check that the next farthest spot is above the exclusion distance. // Note: It is assumed that the spots to ignore have already been assigned following the // exclusion distance rules. So it should be impossible for any ignore spots to be closer than // the exclusion distance (otherwise they could not be assigned and ignored). float nextMinD = Float.POSITIVE_INFINITY; int currentT; if (traceMode == TraceMode.EARLIEST_FORERUNNER) { currentT = endLocalisations[pastIndex].time; for (int i = pastIndex; i < currentIndex; i++) { if (ignore(i, ignoreCount, ignore)) { continue; } final float d2 = spot.distance2(endLocalisations[i]); if (d2 <= distanceThreshSqaured) { minD = d2; int trace = endLocalisations[i].trace; // Search all remaining spots in this time frame and pick the closest final int nextIndex = endIndexes[endLocalisations[i].endTime + 1]; // int nextIndex = i; // // Look for the index for the next time-frame // for (int tt = endLocalisations[i].endT + 1; tt < endIndex.length; tt++) // { // nextIndex = endIndex[tt]; // if (nextIndex != i) // break; // } for (int ii = i + 1; ii < nextIndex; ii++) { if (ignore(ii, ignoreCount, ignore)) { continue; } final float dd2 = spot.distance2(endLocalisations[ii]); if (dd2 < minD) { nextMinD = minD; minD = dd2; trace = endLocalisations[ii].trace; } } return (nextMinD > distanceExclusionSquared) ? trace : 0; } else if (currentT == endLocalisations[i].time) { // Store the minimum distance to the next spot in the same frame if (d2 < nextMinD) { nextMinD = d2; } } else { // New time frame so reset the distance to the next spot in the same frame nextMinD = d2; } currentT = endLocalisations[i].time; } } else if (traceMode == TraceMode.LATEST_FORERUNNER) { currentT = endLocalisations[currentIndex].time; for (int i = currentIndex; i-- > pastIndex;) { if (ignore(i, ignoreCount, ignore)) { continue; } final float d2 = spot.distance2(endLocalisations[i]); if (d2 <= distanceThreshSqaured) { minD = d2; int trace = endLocalisations[i].trace; // Search all remaining spots in this time frame and pick the closest final int previousIndex = endIndexes[endLocalisations[i].endTime]; // int previousIndex = i; //// Look for the index for the previous time-frame // while (previousIndex > 0 && endLocalisations[previousIndex-1].t == // endLocalisations[i].t) // previousIndex--; // if (previousIndex != endIndex[endLocalisations[i].endT]) // { // System.out.printf("Error when tracing: %d != %d\n", previousIndex, // endIndex[endLocalisations[i].endT]); // } for (int ii = i; ii-- > previousIndex;) { if (ignore(ii, ignoreCount, ignore)) { continue; } final float dd2 = spot.distance2(endLocalisations[ii]); if (dd2 < minD) { nextMinD = minD; minD = dd2; trace = endLocalisations[ii].trace; } } return (nextMinD > distanceExclusionSquared) ? trace : 0; } else if (currentT == endLocalisations[i].time) { // Store the minimum distance to the next spot in the same frame if (d2 < nextMinD) { nextMinD = d2; } } else { // New time frame so reset the distance to the next spot in the same frame nextMinD = d2; } currentT = endLocalisations[i].time; } } else { // traceMode == TraceMode.SINGLE_LINKAGE // Find the closest spot minD = distanceThreshSqaured; int minI = -1; for (int i = pastIndex; i < currentIndex; i++) { if (ignore(i, ignoreCount, ignore)) { continue; } final float d2 = spot.distance2(endLocalisations[i]); if (d2 <= minD) { minD = d2; minI = i; } } if (minI == -1) { return 0; } if (distanceExclusionSquared > 0) { // Check all spots in the same frame final int previousIndex = endIndexes[endLocalisations[minI].endTime]; final int nextIndex = endIndexes[endLocalisations[minI].endTime + 1]; for (int i = previousIndex; i < nextIndex; i++) { if (i == minI || ignore(i, ignoreCount, ignore)) { continue; } final float d2 = spot.distance2(endLocalisations[i]); if (d2 <= nextMinD) { nextMinD = d2; } } } return (nextMinD > distanceExclusionSquared) ? endLocalisations[minI].trace : 0; } return 0; } /** * Check if the localisation at the specified index has a trace ID that matches any in the ignore * array. * * @param index the index * @param ignoreCount the ignore count * @param ignore the ignore * @return true, if successful */ private boolean ignore(int index, int ignoreCount, int[] ignore) { for (int j = 0; j < ignoreCount; j++) { if (localisations[index].trace == ignore[j]) { return true; } } return false; } /** * Gets the tracker. * * @return the tracker. */ public TrackProgress getTracker() { return tracker; } /** * Sets the tracker. * * @param tracker the tracker to set */ public void setTracker(TrackProgress tracker) { this.tracker = tracker; } /** * Gets the activation frame interval. * * @return the activation frame interval * @see #setActivationFrameInterval(int) */ public int getActivationFrameInterval() { return activationFrameInterval; } /** * Set the interval at which the activation laser is used. These form staging points for the * traces. * * @param activationFrameInterval the activationFrameInterval to set */ public void setActivationFrameInterval(int activationFrameInterval) { this.activationFrameInterval = activationFrameInterval; resetFilterActivationFramesFlag(); } /** * Gets the activation frame window. * * @return the activation frame window * @see #setActivationFrameWindow(int) */ public int getActivationFrameWindow() { return activationFrameWindow; } /** * Set the window after the activation pulse that will be used for traces. Any trace that does not * start within this window will be discarded. * * @param activationFrameWindow the activationFrameWindow to set */ public void setActivationFrameWindow(int activationFrameWindow) { this.activationFrameWindow = activationFrameWindow; resetFilterActivationFramesFlag(); } private void resetFilterActivationFramesFlag() { filterActivationFrames = (activationFrameInterval > 1 && activationFrameWindow > 0); } /** * Filter the traces that start during an activation frame. * * @param traces the traces * @param activationFrameInterval the interval at which the activation laser is used * @return the filtered traces */ public Trace[] filterTraces(Trace[] traces, int activationFrameInterval) { final Trace[] newTraces = new Trace[traces.length]; int count = 0; for (final Trace trace : traces) { final PeakResult r = trace.getHead(); if (r != null && (r.getFrame() % activationFrameInterval) == 1) { newTraces[count++] = trace; } } return Arrays.copyOf(newTraces, count); } /** * Gets the trace mode. * * @return the trace mode */ public TraceMode getTraceMode() { return traceMode; } /** * Sets the trace mode. * * @param traceMode the trace mode to set */ public void setTraceMode(TraceMode traceMode) { this.traceMode = traceMode; } /** * Gets the pulse interval. * * @return the pulse interval. */ public int getPulseInterval() { return pulseInterval; } /** * Set a pulse interval. Traces will only be created by joining localisations within each pulse. * * @param pulseInterval the pulse interval */ public void setPulseInterval(int pulseInterval) { this.pulseInterval = Math.max(0, pulseInterval); } /** * Gets the distance exclusion. * * @return the distance exclusion * @see #setDistanceExclusion(double) */ public double getDistanceExclusion() { return distanceExclusion; } /** * Set the minimum distance the next candidate spot must be in the same frame, i.e. choose * localisations closer than the distance threshold but no other spots are closer than this * distance exclusion * * <p>If less that the tracing distance threshold this value is ignored. * * @param distanceExclusion the distance exclusion */ public void setDistanceExclusion(double distanceExclusion) { this.distanceExclusion = distanceExclusion; } /** * Gets the total traces from the last call of {@link #traceMolecules(double, int)}. * * @return the total traces */ public int getTotalTraces() { return totalTraces - totalFiltered; } /** * Return the number of traces that were filtered since the trace was first activated outside the * configured activation window. * * @return the total filtered */ public int getTotalFiltered() { return totalFiltered; } /** * Find the neighbour for each result within the given time and distance thresholds. The neighbour * with the strongest signal is selected. * * @param distanceThreshold The distance threshold in the native units of the results * @param timeThreshold The time threshold in frames * @return A list of traces containing the molecule and neighbour. If no neighbour is found then * the trace will contain a single result */ public Trace[] findNeighbours(final double distanceThreshold, final int timeThreshold) { if (distanceThreshold <= 0 || timeThreshold <= 0) { throw new IllegalArgumentException("Distancet and time thresholds must be positive"); } final Trace[] neighbours = new Trace[results.size()]; final PeakResult[] peakResults = results.toArray(); final float dThresh2 = (float) (distanceThreshold * distanceThreshold); if (tracker != null) { tracker.progress(0); } // Initialise int nextIndex = 0; // Now process all the frames, comparing them to previous and future frames while (nextIndex < localisations.length) { if (tracker != null) { tracker.progress(nextIndex, localisations.length); } final int currentIndex = nextIndex; final int t = localisations[currentIndex].time; // Look for the index for the next time-frame for (int tt = t + 1; tt < indexes.length; tt++) { nextIndex = indexes[tt]; if (nextIndex != currentIndex) { break; } } final int pastEndIndex = endIndexes[Math.max(t - timeThreshold, 0)]; final int currentEndIndex = endIndexes[t]; final int futureIndex = Math.max(nextIndex, indexes[Math.min(t + 1 + timeThreshold, indexes.length - 1)]); // Process all spots from this frame. for (int index = currentIndex; index < nextIndex; index++) { final Localisation l = localisations[index]; float maxSignal = 0; int neighbour = -1; // Look back for (int i = pastEndIndex; i < currentEndIndex; i++) { if (l.distance2(endLocalisations[i]) < dThresh2) { final float signal = peakResults[endLocalisations[i].id].getIntensity(); if (maxSignal < signal) { maxSignal = signal; neighbour = endLocalisations[i].id; } } } // Look forward for (int i = nextIndex; i < futureIndex; i++) { if (l.distance2(localisations[i]) < dThresh2) { final float signal = peakResults[localisations[i].id].getIntensity(); if (maxSignal < signal) { maxSignal = signal; neighbour = localisations[i].id; } } } // Assign final Trace trace = new Trace(peakResults[l.id]); if (neighbour > -1) { trace.add(peakResults[neighbour]); } neighbours[index] = trace; } } if (tracker != null) { tracker.progress(1.0); } return neighbours; } /** * Collect all peak results with the same ID into traces. IDs of zero are ignored. * * @param results the results * @return The traces */ public static Trace[] convert(MemoryPeakResults results) { if (results == null || results.size() == 0) { return new Trace[0]; } final PeakResult[] list = results.toArray(); // Find the max trace ID int max = 0; for (final PeakResult result : list) { if (max < result.getId()) { max = result.getId(); } } if (max == 0) { return new Trace[0]; } if (max < 10000) { // Small set of IDs so just use an array look-up table final Trace[] traces = new Trace[max + 1]; for (final PeakResult result : list) { final int id = result.getId(); if (id > 0) { if (traces[id] == null) { traces[id] = new Trace(); traces[id].setId(id); } traces[id].add(result); } } // Consolidate to remove empty positions int count = 0; for (int i = 1; i < traces.length; i++) { if (traces[i] != null) { traces[count++] = traces[i]; } } return Arrays.copyOf(traces, count); } // Use a map when the size is potentially large final TIntObjectHashMap<Trace> map = new TIntObjectHashMap<>(); Trace next = new Trace(); for (final PeakResult result : list) { final int id = result.getId(); if (id > 0) { Trace trace = map.putIfAbsent(id, next); if (trace == null) { // This was a new key trace = next; trace.setId(id); // Prepare for next absent key next = new Trace(); } trace.add(result); } } // Extract the traces final Trace[] traces = map.values(new Trace[map.size()]); Arrays.sort(traces, (t1, t2) -> Integer.compare(t1.getId(), t2.getId())); return traces; } }
gpl-3.0
CubeEngine/modules-extra
mechanism/src/main/java/org/cubeengine/module/mechanism/sign/Gate.java
13601
/* * This file is part of CubeEngine. * CubeEngine is licensed under the GNU General Public License Version 3. * * CubeEngine 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. * * CubeEngine 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 CubeEngine. If not, see <http://www.gnu.org/licenses/>. */ package org.cubeengine.module.mechanism.sign; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Optional; import com.google.inject.Inject; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.format.NamedTextColor; import org.cubeengine.libcube.service.permission.Permission; import org.cubeengine.libcube.service.permission.PermissionContainer; import org.cubeengine.libcube.service.permission.PermissionManager; import org.cubeengine.module.mechanism.Mechanism; import org.cubeengine.module.mechanism.MechanismData; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.data.Keys; import org.spongepowered.api.data.type.HandTypes; import org.spongepowered.api.entity.living.player.gamemode.GameModes; import org.spongepowered.api.entity.living.player.server.ServerPlayer; import org.spongepowered.api.event.block.InteractBlockEvent; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.registry.RegistryTypes; import org.spongepowered.api.util.Direction; import org.spongepowered.api.world.BlockChangeFlags; import org.spongepowered.api.world.server.ServerLocation; public class Gate extends PermissionContainer implements SignMechanism { public static final String NAME = "gate"; public static final int HORIZONTAL_LIMIT = 16; private static final int VERTICAL_LIMIT = 16; private final Permission gatePerm = this.register("sign.gate.use", "Allows using gates");; @Inject public Gate(PermissionManager pm) { super(pm, Mechanism.class); } @Override public String getName() { return NAME; } @Override public ItemStack makeSign(ItemStack signStack) { signStack.offer(Keys.CUSTOM_NAME, Component.text("[Mechanism]", NamedTextColor.GOLD).append(Component.space()).append(Component.text(NAME, NamedTextColor.DARK_AQUA))); signStack.offer(MechanismData.MECHANISM, NAME); signStack.offer(Keys.LORE, Arrays.asList(Component.text(NAME, NamedTextColor.YELLOW))); return signStack; } @Override public boolean interact(InteractBlockEvent event, ServerPlayer player, ServerLocation loc, boolean hidden) { if (hidden) { return false; } if (!this.gatePerm.check(player)) { return false; } final BlockType gateBlockType = (BlockType)loc.get(MechanismData.GATE_BLOCK_TYPE).flatMap(s -> RegistryTypes.BLOCK_TYPE.get().findValue(ResourceKey.resolve(s))).orElse(null); if (gateBlockType == null) { final Optional<BlockType> blockType = player.itemInHand(HandTypes.MAIN_HAND).type().block(); final Boolean isValidGateMaterial = blockType.map(bt -> bt.isAnyOf(BlockTypes.IRON_BARS, BlockTypes.ACACIA_FENCE, BlockTypes.BIRCH_FENCE, BlockTypes.CRIMSON_FENCE, BlockTypes.DARK_OAK_FENCE, BlockTypes.JUNGLE_FENCE, BlockTypes.NETHER_BRICK_FENCE, BlockTypes.OAK_FENCE, BlockTypes.SPRUCE_FENCE, BlockTypes.WARPED_FENCE) ).orElse(false); if (isValidGateMaterial) { loc.blockEntity().get().offer(MechanismData.GATE_BLOCK_TYPE, blockType.get().key(RegistryTypes.BLOCK_TYPE).asString()); loc.blockEntity().get().transform(Keys.SIGN_LINES, list -> { list.set(2, blockType.get().asComponent().color(NamedTextColor.DARK_GRAY)); return list; }); return true; } return false; } final GateBlocks gateBlocks = new GateBlocks(loc, gateBlockType); if (!gateBlocks.findGate()) { return false; } gateBlocks.toggle(player); return true; } @Override public List<Component> initLines(List<Component> lines) { lines.set(2, Component.text("?TYPE?", NamedTextColor.DARK_RED)); lines.set(3, Component.text(0, NamedTextColor.DARK_RED)); return lines; } private static class GateBlocks { private final List<ServerLocation> upperFrameBlocks = new ArrayList<>(); private final List<ServerLocation> gateBlocks = new ArrayList<>(); private final ServerLocation mainFrameBlock; private final ServerLocation signLoc; private final BlockType gateBlockType; private final Direction leftDir; private final Direction rightDir; private int emptyBlocks = 0; public GateBlocks(ServerLocation signLoc, BlockType gateBlockType) { this.signLoc = signLoc; this.gateBlockType = gateBlockType; final Direction attachedDir = signLoc.get(Keys.DIRECTION).get(); this.mainFrameBlock = signLoc.relativeTo(attachedDir.opposite()); switch (attachedDir) { case NORTH: leftDir = Direction.WEST; rightDir = Direction.EAST; break; case EAST: leftDir = Direction.NORTH; rightDir = Direction.SOUTH; break; case SOUTH: leftDir = Direction.EAST; rightDir = Direction.WEST; break; case WEST: leftDir = Direction.SOUTH; rightDir = Direction.NORTH; break; default: leftDir = null; rightDir = null; } } public boolean findGate() { if (leftDir == null || rightDir == null) { return false; } if (findFrame(leftDir) || findFrame(rightDir)) { this.countEmptyBlocks(); return true; } return false; } private void countEmptyBlocks() { int count = 0; for (ServerLocation frameBlock : this.upperFrameBlocks) { ServerLocation downBlock = frameBlock.relativeTo(Direction.DOWN); for (int i = 0; i < VERTICAL_LIMIT; i++) { downBlock = downBlock.relativeTo(Direction.DOWN); if (downBlock.blockY() == this.mainFrameBlock.blockY()) { i = 0; // Reset height when reaching the main frame-block } if (downBlock.blockType().isAnyOf(BlockTypes.AIR, BlockTypes.WATER)) { this.gateBlocks.add(downBlock); count++; } else if (!downBlock.blockType().isAnyOf(this.gateBlockType)) { break; } else { this.gateBlocks.add(downBlock); } } } this.emptyBlocks = count; } private boolean findFrame(Direction dir) { this.upperFrameBlocks.clear(); ServerLocation relativeBlock = mainFrameBlock; // Search to left and right for gate blocks or air for (int i = 0; i < HORIZONTAL_LIMIT; i++) // left first { relativeBlock = relativeBlock.relativeTo(dir); final BlockType blockType = relativeBlock.blockType(); if (blockType.isAnyOf(BlockTypes.AIR, BlockTypes.WATER) || blockType.isAnyOf(gateBlockType)) { final ServerLocation frameBlock = this.isValidColumn(relativeBlock); if (frameBlock != null) { this.upperFrameBlocks.add(frameBlock); } else { // air block with no valid frame block above return false; } } else { return i > 0; // reached other frame side no gate on this side? } } return false; // Gate not closed or too big } private ServerLocation isValidColumn(ServerLocation startBlock) { ServerLocation upBlock = startBlock; boolean lastUpGate = false; for (int i = 0; i < VERTICAL_LIMIT; i++) { upBlock = upBlock.relativeTo(Direction.UP); if (upBlock.blockType().isAnyOf(BlockTypes.AIR, BlockTypes.WATER)) { lastUpGate = false; continue; } if (upBlock.blockType().isAnyOf(gateBlockType)) { lastUpGate = true; } else { if (lastUpGate) { return upBlock; } return null; } } return null; } public void toggle(ServerPlayer player) { int availableBlocks = signLoc.get(MechanismData.GATE_BLOCKS).orElse(0); boolean allAvailable = availableBlocks >= this.emptyBlocks; boolean creative = player.gameMode().get() == GameModes.CREATIVE.get(); // TODO creative handling? if (this.emptyBlocks == 0) // closed gate? { for (ServerLocation block : this.gateBlocks) { final Boolean isWater = block.get(Keys.IS_WATERLOGGED).orElse(block.blockType().isAnyOf(BlockTypes.WATER)); BlockState gateBlock = isWater ? BlockTypes.WATER.get().defaultState() : BlockTypes.AIR.get().defaultState(); block.setBlock(gateBlock); } availableBlocks = this.gateBlocks.size(); } else { if (!allAvailable) { final ItemStack itemInHand = player.itemInHand(HandTypes.MAIN_HAND); if (itemInHand.type().block().map(bt -> bt.isAnyOf(this.gateBlockType)).orElse(false)) { final int additionalBlockFromHand = Math.min(itemInHand.quantity(), this.emptyBlocks - availableBlocks); itemInHand.setQuantity(itemInHand.quantity() - additionalBlockFromHand); player.setItemInHand(HandTypes.MAIN_HAND, itemInHand); availableBlocks += additionalBlockFromHand; } } this.gateBlocks.sort(Comparator.comparing(ServerLocation::blockY).reversed()); for (ServerLocation block : this.gateBlocks) { if (block.blockType().isAnyOf(gateBlockType)) { continue; } if (availableBlocks <= 0) { break; } availableBlocks--; BlockState gateBlock = this.gateBlockType.defaultState(); gateBlock = gateBlock.with(Keys.IS_WATERLOGGED, block.get(Keys.IS_WATERLOGGED).orElse(block.blockType().isAnyOf(BlockTypes.WATER))).orElse(gateBlock); gateBlock = gateBlock.with(Keys.CONNECTED_DIRECTIONS, new HashSet<>(Arrays.asList(this.leftDir, this.rightDir))).orElse(gateBlock); block.setBlock(gateBlock, BlockChangeFlags.ALL); } } signLoc.blockEntity().get().offer(MechanismData.GATE_BLOCKS, availableBlocks); final TextComponent newAvailableText = Component.text(availableBlocks, allAvailable ? NamedTextColor.DARK_GRAY : NamedTextColor.DARK_RED); signLoc.blockEntity().get().transform(Keys.SIGN_LINES, list -> { list.set(3, newAvailableText); return list; }); } } }
gpl-3.0
sgdc3/AuthMeReloaded
src/main/java/fr/xephi/authme/security/HashAlgorithm.java
2095
package fr.xephi.authme.security; import org.apache.commons.lang.ObjectUtils.Null; /** */ public enum HashAlgorithm { MD5(fr.xephi.authme.security.crypts.MD5.class), SHA1(fr.xephi.authme.security.crypts.SHA1.class), SHA256(fr.xephi.authme.security.crypts.SHA256.class), WHIRLPOOL(fr.xephi.authme.security.crypts.WHIRLPOOL.class), XAUTH(fr.xephi.authme.security.crypts.XAUTH.class), MD5VB(fr.xephi.authme.security.crypts.MD5VB.class), PHPBB(fr.xephi.authme.security.crypts.PHPBB.class), PLAINTEXT(fr.xephi.authme.security.crypts.PLAINTEXT.class), MYBB(fr.xephi.authme.security.crypts.MYBB.class), IPB3(fr.xephi.authme.security.crypts.IPB3.class), PHPFUSION(fr.xephi.authme.security.crypts.PHPFUSION.class), SMF(fr.xephi.authme.security.crypts.SMF.class), XENFORO(fr.xephi.authme.security.crypts.XF.class), SALTED2MD5(fr.xephi.authme.security.crypts.SALTED2MD5.class), JOOMLA(fr.xephi.authme.security.crypts.JOOMLA.class), BCRYPT(fr.xephi.authme.security.crypts.BCRYPT.class), WBB3(fr.xephi.authme.security.crypts.WBB3.class), WBB4(fr.xephi.authme.security.crypts.WBB4.class), SHA512(fr.xephi.authme.security.crypts.SHA512.class), DOUBLEMD5(fr.xephi.authme.security.crypts.DOUBLEMD5.class), PBKDF2(fr.xephi.authme.security.crypts.CryptPBKDF2.class), PBKDF2DJANGO(fr.xephi.authme.security.crypts.CryptPBKDF2Django.class), WORDPRESS(fr.xephi.authme.security.crypts.WORDPRESS.class), ROYALAUTH(fr.xephi.authme.security.crypts.ROYALAUTH.class), CRAZYCRYPT1(fr.xephi.authme.security.crypts.CRAZYCRYPT1.class), BCRYPT2Y(fr.xephi.authme.security.crypts.BCRYPT2Y.class), SALTEDSHA512(fr.xephi.authme.security.crypts.SALTEDSHA512.class), CUSTOM(Null.class); final Class<?> classe; /** * Constructor for HashAlgorithm. * * @param classe Class<?> */ HashAlgorithm(Class<?> classe) { this.classe = classe; } /** * Method getclasse. * * @return Class<?> */ public Class<?> getclasse() { return classe; } }
gpl-3.0
yferras/javartint
crow-javartint/crow-javartint-gea/src/main/java/com/github/yferras/javartint/gea/function/decoder/AbstractDecoderFunction.java
2295
package com.github.yferras.javartint.gea.function.decoder; /* * #%L * Crow JavArtInt GEA * %% Copyright (C) 2014 - 2015 Eng. Ferrás Cecilio, Yeinier * %% 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% */ import com.github.yferras.javartint.core.util.ValidationException; import com.github.yferras.javartint.gea.chromosome.Chromosome; import com.github.yferras.javartint.gea.gene.Gene; import com.github.yferras.javartint.gea.genome.Genome; /** * This class implements the interface * {@link com.github.yferras.javartint.gea.function.decoder.DecoderFunction}. * This class can be derived to create a functions to decode genomes. * * @param <D> * Type of decoded result * @param <T> * Any derived class from * {@link com.github.yferras.javartint.gea.genome.Genome} * @author Eng. Ferrás Cecilio, Yeinier. * @version 0.0.2 */ public abstract class AbstractDecoderFunction<D, T extends Genome<? extends Chromosome<? extends Gene<?>>>> implements DecoderFunction<D, T> { /** * This method must be implemented to decode the genome. * * @param genome * genome to decode * @return decoded value */ protected abstract D decode(T genome); /** * {@inheritDoc} * <p/> * This method validate and performs the decode process. */ @Override public D evaluate(T genome) { validate(genome); return decode(genome); } /** * Validates the input params. * * @param genome * genome to validate. * @throws ValidationException * if argument is {@code null} */ protected void validate(T genome) { if (genome == null) { throw new ValidationException("Genome is null."); } } }
gpl-3.0
AndrewBell/RCbot
src/com/recursivechaos/rcbot/plugins/stoopsnoop/LogListener.java
1289
package com.recursivechaos.rcbot.plugins.stoopsnoop; /** * LogListener listens for events and passes them to the EventLogDAO * * @author Andrew Bell www.recursivechaos.com * */ import org.pircbotx.hooks.Event; import org.pircbotx.hooks.ListenerAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.recursivechaos.rcbot.bot.object.BotException; import com.recursivechaos.rcbot.bot.object.MyPircBotX; import com.recursivechaos.rcbot.plugins.persistence.hibernate.dao.EventLogDAOImpl; import com.recursivechaos.rcbot.plugins.stoopsnoop.log.EventLogDAO; public class LogListener extends ListenerAdapter<MyPircBotX> { Logger logger = LoggerFactory.getLogger(LogListener.class); EventLogDAO eventlog = new EventLogDAOImpl(); @Override public void onEvent(final Event<MyPircBotX> event) throws Exception { try{ eventlog.logEvent(event); }catch(BotException e){ String admin = (event.getBot().getSettings().getAdmin()); event.getBot().sendIRC().message(admin, "I broke: " + e.getMessage()); }finally{ // This throws a generic Exception, but in *theory* the BotException will be caught, // while anything else will be passed on to the bot to handle ever so gracefully. super.onEvent(event); } } }
gpl-3.0
dotCMS/core
dotCMS/src/main/java/com/dotmarketing/business/cache/provider/hazelcast/AbstractHazelcastCacheProvider.java
5767
package com.dotmarketing.business.cache.provider.hazelcast; import java.util.Collection; import java.util.HashSet; import java.util.Set; import com.dotcms.cluster.business.HazelcastUtil; import com.dotcms.cluster.business.HazelcastUtil.HazelcastInstanceType; import com.dotcms.enterprise.license.LicenseManager; import com.dotmarketing.business.cache.provider.CacheProvider; import com.dotmarketing.business.cache.provider.CacheProviderStats; import com.dotmarketing.business.cache.provider.CacheStats; import com.dotmarketing.util.Config; import com.dotmarketing.util.Logger; import com.hazelcast.core.DistributedObject; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.HazelcastInstanceNotActiveException; /** * Created by jasontesser on 3/14/17. */ public abstract class AbstractHazelcastCacheProvider extends CacheProvider { private static final long serialVersionUID = 1L; private boolean initialized = false; private boolean recovering =false; private final boolean ASYNC_PUT = Config.getBooleanProperty("HAZELCAST_ASYNC_PUT", true); protected abstract HazelcastInstanceType getHazelcastInstanceType(); protected abstract CacheStats getStats(String group); protected HazelcastInstance getHazelcastInstance() { return HazelcastUtil.getInstance().getHazel(getHazelcastInstanceType()); } protected void reInitialize(){ if(recovering){ return; } synchronized (this) { if(!recovering){ setRecovering(true); Runnable hazelThread = new ReinitializeHazelThread(this, getHazelcastInstanceType()); hazelThread.run(); } } } @Override public boolean isDistributed() { return true; } @Override public void init() { if(!LicenseManager.getInstance().isEnterprise()){ return; } try {Thread.sleep(1000);}catch (Exception e){} if(isRecovering()){ return; } Logger.debug(this,"Calling HazelUtil to ensure Hazelcast member is up"); getHazelcastInstance(); setInitialized(true); } public boolean isRecovering() { return recovering; } public void setRecovering(boolean recovering){ this.recovering = recovering; } @Override public boolean isInitialized() { return initialized; } public void setInitialized(boolean initialized){ this.initialized=initialized; } @Override public void put(String group, String key, Object content) { if(isRecovering()){ return; } try{ if(ASYNC_PUT){ getHazelcastInstance().getMap(group).setAsync(key, content); }else{ getHazelcastInstance().getMap(group).set(key, content); } } catch (HazelcastInstanceNotActiveException hce){ reInitialize(); } } @Override public Object get(String group, String key) { if(isRecovering()){ return null; } try { return getHazelcastInstance().getMap(group).get(key); } catch (HazelcastInstanceNotActiveException hce){ reInitialize(); return null; } } @Override public void remove(String group, String key) { if(isRecovering()){ return; } try{ if(ASYNC_PUT){ getHazelcastInstance().getMap(group).removeAsync(key); } else{ getHazelcastInstance().getMap(group).remove(key); } } catch (HazelcastInstanceNotActiveException hce){ reInitialize(); } } @Override public void remove(String group) { if(isRecovering()){ return; } try{ getHazelcastInstance().getMap(group).clear(); } catch (HazelcastInstanceNotActiveException hce){ reInitialize(); } } @Override public void removeAll() { if(isRecovering()){ return; } Collection<DistributedObject> distObjs = getHazelcastInstance().getDistributedObjects(); for (DistributedObject distObj : distObjs) { if (distObj.getServiceName().contains("mapService")) { getHazelcastInstance().getMap(distObj.getName()).clear(); } } } @Override public Set<String> getKeys(String group) { Set<String> keys = new HashSet<String>(); if(isRecovering()){ return keys; } for (Object key : getHazelcastInstance().getMap(group).keySet()) { keys.add(key.toString()); } return keys; } @Override public Set<String> getGroups() { Set groups = new HashSet(); if(isRecovering()){ return groups; } Collection<DistributedObject> distObjs = getHazelcastInstance().getDistributedObjects(); for (DistributedObject distObj : distObjs) { if (distObj.getServiceName().contains("mapService")) { groups.add(distObj.getName()); } } return groups; } @Override public CacheProviderStats getStats() { CacheStats providerStats = new CacheStats(); CacheProviderStats ret = new CacheProviderStats(providerStats,getName()); Set groups = new HashSet(); if(isRecovering()){ return ret; } for (String group : getGroups()) { ret.addStatRecord(getStats(group)); } return ret; } @Override public void shutdown() { getHazelcastInstance().shutdown(); } }
gpl-3.0
ChistaMisuto/Eldritch-Infusion
Eldritch-Infusion/EI_common/chista/EI/ore/OreRhodochrosite.java
453
package chista.EI.ore; import java.util.Random; import net.minecraft.block.material.Material; import chista.EI.item.gem.ModGems; import chista.EI.lib.Strings; public class OreRhodochrosite extends ModOreBase { public OreRhodochrosite(int id) { super(id, Material.rock); this.setUnlocalizedName(Strings.RHODOCHROSITEORE_NAME); } @Override public int idDropped(int par1, Random rand, int par2) { return ModGems.rhodochrositeGem.itemID; } }
gpl-3.0
jmalenko/alarm-morning
app/src/test/java/cz/jaro/alarmmorning/model/GlobalManager1NextAlarm2DefaultTest.java
6852
package cz.jaro.alarmmorning.model; import org.junit.Test; import java.util.Calendar; import java.util.GregorianCalendar; import cz.jaro.alarmmorning.Analytics; import cz.jaro.alarmmorning.FixedTimeTest; import cz.jaro.alarmmorning.clock.Clock; import cz.jaro.alarmmorning.clock.FixedClock; import static cz.jaro.alarmmorning.calendar.CalendarUtils.beginningOfTomorrow; import static cz.jaro.alarmmorning.calendar.CalendarUtils.nextSameDayOfWeek; import static cz.jaro.alarmmorning.model.GlobalManager1NextAlarm0NoAlarmTest.RANGE; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Tests when there is only one default enabled. Holiday is not defined. */ public class GlobalManager1NextAlarm2DefaultTest extends FixedTimeTest { private void setDefaultAlarm() { Calendar date = new GregorianCalendar(DayTest.YEAR, DayTest.MONTH, DayTest.DAY, DayTest.HOUR, DayTest.MINUTE); int dayOfWeek = date.get(Calendar.DAY_OF_WEEK); Defaults defaults = new Defaults(); defaults.setDayOfWeek(dayOfWeek); defaults.setState(Defaults.STATE_ENABLED); defaults.setHour(DayTest.HOUR_DEFAULT); defaults.setMinute(DayTest.MINUTE_DEFAULT); Analytics analytics = new Analytics(Analytics.Channel.Test, Analytics.ChannelName.Defaults); globalManager.modifyDefault(defaults, analytics); } @Test public void t10_alarmToday() { setDefaultAlarm(); Clock clock = globalManager.clock(); Calendar nextAlarm = globalManager.getNextAlarm(clock); assertThat("Year", nextAlarm.get(Calendar.YEAR), is(DayTest.YEAR)); assertThat("Month", nextAlarm.get(Calendar.MONTH), is(DayTest.MONTH)); assertThat("Date", nextAlarm.get(Calendar.DAY_OF_MONTH), is(DayTest.DAY)); assertThat("Hour", nextAlarm.get(Calendar.HOUR_OF_DAY), is(DayTest.HOUR_DEFAULT)); assertThat("Minute", nextAlarm.get(Calendar.MINUTE), is(DayTest.MINUTE_DEFAULT)); } @Test public void t11_justBeforeAlarm() { setDefaultAlarm(); Calendar date = new GregorianCalendar(DayTest.YEAR, DayTest.MONTH, DayTest.DAY, DayTest.HOUR_DEFAULT, DayTest.MINUTE_DEFAULT); date.add(Calendar.SECOND, -1); FixedClock clock = new FixedClock(date); Calendar nextAlarm = globalManager.getNextAlarm(clock); assertThat("Year", nextAlarm.get(Calendar.YEAR), is(DayTest.YEAR)); assertThat("Month", nextAlarm.get(Calendar.MONTH), is(DayTest.MONTH)); assertThat("Date", nextAlarm.get(Calendar.DAY_OF_MONTH), is(DayTest.DAY)); assertThat("Hour", nextAlarm.get(Calendar.HOUR_OF_DAY), is(DayTest.HOUR_DEFAULT)); assertThat("Minute", nextAlarm.get(Calendar.MINUTE), is(DayTest.MINUTE_DEFAULT)); } @Test public void t21_yesterday() { setDefaultAlarm(); Calendar date = new GregorianCalendar(DayTest.YEAR, DayTest.MONTH, DayTest.DAY, DayTest.HOUR, DayTest.MINUTE); date.add(Calendar.DAY_OF_MONTH, -1); FixedClock clock = new FixedClock(date); Calendar nextAlarm = globalManager.getNextAlarm(clock); assertThat("Year", nextAlarm.get(Calendar.YEAR), is(DayTest.YEAR)); assertThat("Month", nextAlarm.get(Calendar.MONTH), is(DayTest.MONTH)); assertThat("Date", nextAlarm.get(Calendar.DAY_OF_MONTH), is(DayTest.DAY)); assertThat("Hour", nextAlarm.get(Calendar.HOUR_OF_DAY), is(DayTest.HOUR_DEFAULT)); assertThat("Minute", nextAlarm.get(Calendar.MINUTE), is(DayTest.MINUTE_DEFAULT)); } @Test public void t31_justAfterAlarm() { setDefaultAlarm(); Calendar date = new GregorianCalendar(DayTest.YEAR, DayTest.MONTH, DayTest.DAY, DayTest.HOUR_DEFAULT, DayTest.MINUTE_DEFAULT); date.add(Calendar.SECOND, 1); FixedClock clock = new FixedClock(date); Calendar nextAlarm = globalManager.getNextAlarm(clock); Calendar tomorrowBeginning = beginningOfTomorrow(date); Calendar nextSameDayOfWeek = nextSameDayOfWeek(tomorrowBeginning, dayOfWeek()); assertThat("Year", nextAlarm.get(Calendar.YEAR), is(nextSameDayOfWeek.get(Calendar.YEAR))); assertThat("Month", nextAlarm.get(Calendar.MONTH), is(nextSameDayOfWeek.get(Calendar.MONTH))); assertThat("Date", nextAlarm.get(Calendar.DAY_OF_MONTH), is(nextSameDayOfWeek.get(Calendar.DAY_OF_MONTH))); assertThat("Hour", nextAlarm.get(Calendar.HOUR_OF_DAY), is(DayTest.HOUR_DEFAULT)); assertThat("Minute", nextAlarm.get(Calendar.MINUTE), is(DayTest.MINUTE_DEFAULT)); } @Test public void t32_tomorrow() { setDefaultAlarm(); Calendar date = new GregorianCalendar(DayTest.YEAR, DayTest.MONTH, DayTest.DAY, DayTest.HOUR, DayTest.MINUTE); date.add(Calendar.DAY_OF_MONTH, 1); FixedClock clock = new FixedClock(date); Calendar nextAlarm = globalManager.getNextAlarm(clock); Calendar nextSameDayOfWeekDay = nextSameDayOfWeek(date, dayOfWeek()); assertThat("Year", nextAlarm.get(Calendar.YEAR), is(nextSameDayOfWeekDay.get(Calendar.YEAR))); assertThat("Month", nextAlarm.get(Calendar.MONTH), is(nextSameDayOfWeekDay.get(Calendar.MONTH))); assertThat("Date", nextAlarm.get(Calendar.DAY_OF_MONTH), is(nextSameDayOfWeekDay.get(Calendar.DAY_OF_MONTH))); assertThat("Hour", nextAlarm.get(Calendar.HOUR_OF_DAY), is(DayTest.HOUR_DEFAULT)); assertThat("Minute", nextAlarm.get(Calendar.MINUTE), is(DayTest.MINUTE_DEFAULT)); } @Test public void t40_everyDay() { setDefaultAlarm(); Calendar now = globalManager.clock().now(); for (int i = -RANGE; i <= RANGE; i++) { Calendar date = (Calendar) now.clone(); date.add(Calendar.DATE, i); FixedClock clock = new FixedClock(date); Calendar nextAlarm = globalManager.getNextAlarm(clock); Calendar nextSameDayOfWeekDay = nextSameDayOfWeek(date, dayOfWeek()); String str = " on " + date.getTime(); assertThat("Year" + str, nextAlarm.get(Calendar.YEAR), is(nextSameDayOfWeekDay.get(Calendar.YEAR))); assertThat("Month" + str, nextAlarm.get(Calendar.MONTH), is(nextSameDayOfWeekDay.get(Calendar.MONTH))); assertThat("Date" + str, nextAlarm.get(Calendar.DAY_OF_MONTH), is(nextSameDayOfWeekDay.get(Calendar.DAY_OF_MONTH))); assertThat("Hour" + str, nextAlarm.get(Calendar.HOUR_OF_DAY), is(DayTest.HOUR_DEFAULT)); assertThat("Minute" + str, nextAlarm.get(Calendar.MINUTE), is(DayTest.MINUTE_DEFAULT)); } } static int dayOfWeek() { Calendar dateDefault = new GregorianCalendar(DayTest.YEAR, DayTest.MONTH, DayTest.DAY, DayTest.HOUR, DayTest.MINUTE); return dateDefault.get(Calendar.DAY_OF_WEEK); } }
gpl-3.0
songscribe/SongScribe
src/main/java/songscribe/publisher/publisheractions/ToTopComponentAction.java
1846
/* SongScribe song notation program Copyright (C) 2006 Csaba Kavai This file is part of SongScribe. SongScribe 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. SongScribe 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/>. Created on Jun 14, 2007 */ package songscribe.publisher.publisheractions; import songscribe.publisher.Publisher; import songscribe.publisher.pagecomponents.PageComponent; import javax.swing.*; import java.awt.event.ActionEvent; /** * @author Csaba Kávai */ public class ToTopComponentAction extends AbstractAction { private Publisher publisher; public ToTopComponentAction(Publisher publisher) { this.publisher = publisher; putValue(Action.NAME, "Move to Top"); putValue(Action.SMALL_ICON, new ImageIcon(Publisher.getImage("2uparrow.png"))); } public void actionPerformed(ActionEvent e) { if (publisher.isBookNull()) { return; } PageComponent pc = publisher.getBook().getSelectedComponent(); if (pc != null) { publisher.getBook().getSelectedComponentsPage().toTopComponent(pc); publisher.getBook().repaintWhole(); } else { JOptionPane.showMessageDialog(publisher, "You must select a component first to raise it."); } } }
gpl-3.0
dotCMS/core
dotCMS/src/integration-test/java/com/dotmarketing/portlets/languagesmanager/business/LanguageAPITest.java
13205
package com.dotmarketing.portlets.languagesmanager.business; import static com.dotcms.datagen.TestDataUtils.getNewsLikeContentType; import static com.dotcms.integrationtestutil.content.ContentUtils.createTestKeyValueContent; import static com.dotcms.integrationtestutil.content.ContentUtils.deleteContentlets; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.dotcms.content.elasticsearch.business.DotIndexException; import com.dotcms.contenttype.model.type.ContentType; import com.dotcms.datagen.ContentTypeDataGen; import com.dotcms.datagen.ContentletDataGen; import com.dotcms.languagevariable.business.LanguageVariableAPI; import com.dotcms.util.IntegrationTestInitService; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.CacheLocator; import com.dotmarketing.business.DotStateException; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotLanguageException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.contentlet.business.ContentletAPI; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.contentlet.model.IndexPolicy; import com.dotmarketing.portlets.languagesmanager.model.Language; import com.dotmarketing.util.UUIDGenerator; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.liferay.portal.language.LanguageUtil; import com.liferay.portal.model.User; import com.rainerhahnekamp.sneakythrow.Sneaky; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; @RunWith(DataProviderRunner.class) public class LanguageAPITest { private static User systemUser; private static Language language; @BeforeClass public static void prepare() throws Exception { //Setting web app environment IntegrationTestInitService.getInstance().init(); systemUser = APILocator.systemUser(); language= new LanguageDataGen().nextPersisted(); } /* * 1- Put things in cache * 2- Add a language * 3- Make sure cache have all the languages * 4- Remove a language * 5- Make sure cache remove the language * 6- Clear cache * */ @Test public void languageCache() throws Exception { int existingLanguagesCount = APILocator.getLanguageAPI().getLanguages().size(); APILocator.getLanguageAPI().getLanguages(); Assert.assertEquals(existingLanguagesCount, CacheLocator.getLanguageCache().getLanguages().size()); Language lan = new LanguageDataGen().nextPersisted(); existingLanguagesCount = APILocator.getLanguageAPI().getLanguages().size(); CacheLocator.getLanguageCache().clearCache(); APILocator.getLanguageAPI().getLanguages(); Assert.assertEquals(existingLanguagesCount, CacheLocator.getLanguageCache().getLanguages().size()); APILocator.getLanguageAPI().deleteLanguage(lan); Assert.assertEquals(existingLanguagesCount - 1, APILocator.getLanguageAPI().getLanguages().size()); Assert.assertEquals(existingLanguagesCount - 1, CacheLocator.getLanguageCache().getLanguages().size()); existingLanguagesCount = APILocator.getLanguageAPI().getLanguages().size(); CacheLocator.getLanguageCache().clearCache(); APILocator.getLanguageAPI().getLanguages(); Assert.assertEquals(existingLanguagesCount, CacheLocator.getLanguageCache().getLanguages().size()); } /** * This test is for a language key that exist as a content, * so it's returned */ @Test public void getStringKey_returnLanguageVariableContent() throws Exception{ final String KEY_1 = "KEY_"+System.currentTimeMillis(); final String VALUE_1 = "VALUE_"+System.currentTimeMillis(); Contentlet contentletEnglish = null; try{ // Using the provided Language Variable Content Type final ContentType languageVariableContentType = APILocator.getContentTypeAPI(systemUser) .find(LanguageVariableAPI.LANGUAGEVARIABLE); contentletEnglish = createTestKeyValueContent( KEY_1, VALUE_1, language.getId(), languageVariableContentType, systemUser); final String value = APILocator.getLanguageAPI().getStringKey(language,KEY_1); Assert.assertEquals(VALUE_1,value); }finally { //Clean up if (null != contentletEnglish) { deleteContentlets(systemUser, contentletEnglish); } } } /** * This test is for a language key that exist in the properties file, * but afterwards is created as a content, so that * language variable gets the priority so the value changes. */ @Test public void getStringKey_KeyExistsPropertiesFileAndAsAContent_returnsLanguageVariableContent() throws Exception{ final String KEY_1 = "email-address"; final String VALUE_1 = "Electronic Mail Address"; Contentlet contentletEnglish = null; try{ String value = APILocator.getLanguageAPI().getStringKey(APILocator.getLanguageAPI().getDefaultLanguage(),KEY_1); Assert.assertEquals("Email Address",value); // Using the provided Language Variable Content Type final ContentType languageVariableContentType = APILocator.getContentTypeAPI(systemUser) .find(LanguageVariableAPI.LANGUAGEVARIABLE); contentletEnglish = createTestKeyValueContent( KEY_1, VALUE_1, 1, languageVariableContentType, systemUser); CacheLocator.getESQueryCache().clearCache(); value = APILocator.getLanguageAPI().getStringKey(APILocator.getLanguageAPI().getDefaultLanguage(),KEY_1); Assert.assertEquals(VALUE_1,value); }finally { //Clean up if (null != contentletEnglish) { deleteContentlets(systemUser, contentletEnglish); } } } /** * This test is for a language key that does not exists neither as a content or * in the properties file, so the key will be returned. */ @Test public void getStringKey_returnKey(){ final String KEY_1 = "KEY DOES NOT EXISTS"; final String value = APILocator.getLanguageAPI().getStringKey(APILocator.getLanguageAPI().getDefaultLanguage(),KEY_1); Assert.assertEquals(KEY_1,value); } /** * This test is for a language key that does not exists neither as a content or in the properties * file, so the key will be returned. */ @Test public void getStringsAsMap_returnMap() throws Exception { final String uniq = UUIDGenerator.shorty(); final String BAD_KEY = "KEY-DOES-NOT-EXIST"; final String CONTENTLET_KEY = "key-exists-as-contentlet" + uniq; final String PROPERTYFILE_KEY = "key-exists-in-properties" + uniq; final String SYSTEM_PROPERTYFILE_KEY = "contenttypes.action.cancel"; final LanguageAPIImpl languageAPi = new LanguageAPIImpl(); final Language language = new LanguageDataGen().nextPersisted(); final LanguageAPIImpl lapi = Mockito.spy(languageAPi); Mockito.doReturn(APILocator.systemUser()).when(lapi).getUser(); final ContentType langKeyType = APILocator.getContentTypeAPI(APILocator.systemUser()).find("Languagevariable"); Contentlet con = new ContentletDataGen(langKeyType.id()) .setProperty("key", CONTENTLET_KEY) .setProperty("value", CONTENTLET_KEY + "works") .languageId(language.getId()) .nextPersisted(); APILocator.getContentletAPI().publish(con, APILocator.systemUser(), false); // Add Languague Variable to local properties lapi.saveLanguageKeys(language, ImmutableMap.of(PROPERTYFILE_KEY, PROPERTYFILE_KEY + "works"), new HashMap<>(), ImmutableSet.of()); final List<String> keys = ImmutableList.of(BAD_KEY, CONTENTLET_KEY,PROPERTYFILE_KEY,SYSTEM_PROPERTYFILE_KEY ); final Locale locale = language.asLocale(); final Map<String, String> translatedMap = lapi.getStringsAsMap(locale, keys); // If key does not exist, we just return the key as the value assertEquals(translatedMap.get(BAD_KEY), BAD_KEY); // We should check content based keys - languagevariables - before .properties files assertEquals(CONTENTLET_KEY+"works", translatedMap.get(CONTENTLET_KEY)); // then we should check properties files based on the locale assertEquals(PROPERTYFILE_KEY+"works",translatedMap.get(PROPERTYFILE_KEY)); assertEquals(LanguageUtil.get( new Locale("en", "us"), SYSTEM_PROPERTYFILE_KEY ), translatedMap.get(SYSTEM_PROPERTYFILE_KEY) ); } @DataProvider public static Object[] dataProviderSaveLanguage() { return new Language[]{ null, new Language(0, "", null, null, null), new Language(0, "it", null, null, null), new Language(0, "", "IT", null, null), }; } @Test(expected = IllegalArgumentException.class) @UseDataProvider("dataProviderSaveLanguage") public void test_saveLanguage_InvalidLanguage_ShouldThrowException(final Language language) { APILocator.getLanguageAPI().saveLanguage(language); } @Test(expected = DotStateException.class) public void test_deleteLanguage_WithExistingContent_ShouldFail() { Language newLanguage = null; ContentType testType = null; try { newLanguage = new LanguageDataGen().nextPersisted(); testType = new ContentTypeDataGen().nextPersisted(); // We don't care about the reference to the content since deleting the type will take care of it new ContentletDataGen(testType.id()) .languageId(newLanguage.getId()) .nextPersisted(); APILocator.getLanguageAPI().deleteLanguage(newLanguage); } finally { // clean up // new final var to be able to use Sneaky final ContentType typeToDelete = testType; if(testType!=null) { Sneaky.sneaked(()-> APILocator.getContentTypeAPI(systemUser).delete(typeToDelete) ); } if(language!=null) { APILocator.getLanguageAPI().deleteLanguage(newLanguage); } } } /** * Basically we test two methods in conjunction {@link LanguageAPI#makeDefault(Long, User)} and {@link LanguageAPI#transferAssets(Long, Long, User)} * Given scenario: Create 2 Languages besides the default. Then Create content under the default and switch to a new language. And Call the transferAssets method * Expected Result: The api should be able to switch to a new lang and transfer all assets under the old lang to a new default lang. * * @throws DotDataException * @throws DotSecurityException * @throws DotIndexException */ @Test public void Create_Content_Under_Default_Lang_Make_New_Default_Language_And_Test_Assets_Lang_Transfer() throws DotDataException, DotSecurityException, DotIndexException { final LanguageAPI languageAPI = APILocator.getLanguageAPI(); final Language defaultLang = languageAPI.getDefaultLanguage(); final Language newDefaultLanguage = new LanguageDataGen().nextPersisted(); final User admin = mockAdminUser(); try { final Language thirdLanguage = new LanguageDataGen().nextPersisted(); final ContentType news = getNewsLikeContentType("News"); final Contentlet persistedWithOldDefaultLang = new ContentletDataGen(news) .languageId(defaultLang.getId()) .setProperty("title", "News Test") .setProperty("urlTitle", "news-test").setProperty("byline", "news-test") .setProperty("sysPublishDate", new Date()).setProperty("story", "news-test") .nextPersisted(); final Contentlet persistedWithThirdLang = new ContentletDataGen(news) .languageId(thirdLanguage.getId()) .setProperty("title", "News Test") .setProperty("urlTitle", "news-test").setProperty("byline", "news-test") .setProperty("sysPublishDate", new Date()).setProperty("story", "news-test") .nextPersisted(); languageAPI.makeDefault(newDefaultLanguage.getId(), admin); assertEquals(newDefaultLanguage, languageAPI.getDefaultLanguage()); languageAPI.transferAssets(defaultLang.getId(), newDefaultLanguage.getId(), admin); final ContentletAPI contentletAPI = APILocator.getContentletAPI(); Contentlet contentlet = contentletAPI .find(persistedWithOldDefaultLang.getInode(), admin, false); assertEquals(newDefaultLanguage.getId(), contentlet.getLanguageId()); contentlet = contentletAPI .find(persistedWithThirdLang.getInode(), admin, false); assertEquals(thirdLanguage.getId(), contentlet.getLanguageId()); } finally { languageAPI.makeDefault(defaultLang.getId(), admin); languageAPI.transferAssets(newDefaultLanguage.getId(), defaultLang.getId(), admin); } } private User mockAdminUser() { final User adminUser = mock(User.class); when(adminUser.getUserId()).thenReturn("dotcms.org.1"); when(adminUser.getEmailAddress()).thenReturn("admin@dotcms.com"); when(adminUser.getFirstName()).thenReturn("Admin"); when(adminUser.getLastName()).thenReturn("User"); when(adminUser.isAdmin()).thenReturn(true); return adminUser; } }
gpl-3.0
SamRaven2/DualCraft
src/main/java/com/bats/dualcraft/DualCraft.java
1303
package com.bats.dualcraft; import com.bats.dualcraft.handler.GuiHandler; import com.bats.dualcraft.handler.WorldEventHandler; import com.bats.dualcraft.reference.Reference; import com.bats.dualcraft.util.LogHelper; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkRegistry; import net.minecraftforge.common.MinecraftForge; @Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.VERSION, dependencies = "after:NotEnoughItems") public class DualCraft { @Mod.Instance(Reference.MOD_ID) public static DualCraft instance; @EventHandler public void preInit(FMLPreInitializationEvent event) { } @EventHandler public void init(FMLInitializationEvent event) { LogHelper.info("Beginning Init Phase"); MinecraftForge.EVENT_BUS.register(new WorldEventHandler()); NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler()); LogHelper.info("Ending Init Phase"); } @EventHandler public void postInit(FMLPostInitializationEvent event) { } }
gpl-3.0
ckaestne/CIDE
CIDE_Language_XML_concrete/src/tmp/generated_people/STag_tt.java
755
package tmp.generated_people; import cide.gast.*; import cide.gparser.*; import cide.greferences.*; import java.util.*; public class STag_tt extends GenASTNode { public STag_tt(ArrayList<Attribute> attribute, Token firstToken, Token lastToken) { super(new Property[] { new PropertyZeroOrMore<Attribute>("attribute", attribute) }, firstToken, lastToken); } public STag_tt(Property[] properties, IToken firstToken, IToken lastToken) { super(properties,firstToken,lastToken); } public ASTNode deepCopy() { return new STag_tt(cloneProperties(),firstToken,lastToken); } public ArrayList<Attribute> getAttribute() { return ((PropertyZeroOrMore<Attribute>)getProperty("attribute")).getValue(); } }
gpl-3.0
chrisj42/minicraft-plus-revived
src/main/java/minicraft/level/tile/farming/Plant.java
2384
package minicraft.level.tile.farming; import minicraft.entity.Direction; import minicraft.entity.Entity; import minicraft.entity.ItemEntity; import minicraft.entity.mob.Mob; import minicraft.entity.mob.Player; import minicraft.gfx.Sprite; import minicraft.item.Items; import minicraft.level.Level; import minicraft.level.tile.Tile; import minicraft.level.tile.Tiles; public class Plant extends FarmTile { protected static int maxAge = 100; private String name; protected Plant(String name) { super(name, (Sprite)null); this.name = name; } @Override public void steppedOn(Level level, int xt, int yt, Entity entity) { if (entity instanceof ItemEntity) return; super.steppedOn(level, xt, yt, entity); harvest(level, xt, yt, entity); } @Override public boolean hurt(Level level, int x, int y, Mob source, int dmg, Direction attackDir) { harvest(level, x, y, source); return true; } @Override public boolean tick(Level level, int xt, int yt) { if (random.nextInt(2) == 0) return false; int age = level.getData(xt, yt); if (age < maxAge) { if (!IfWater(level, xt, yt)) level.setData(xt, yt, age + 1); else if (IfWater(level, xt, yt)) level.setData(xt, yt, age + 2); return true; } return false; } protected boolean IfWater(Level level, int xs, int ys) { Tile[] areaTiles = level.getAreaTiles(xs, ys, 1); for(Tile t: areaTiles) if(t == Tiles.get("Water")) return true; return false; } /** Default harvest method, used for everything that doesn't really need any special behavior. */ protected void harvest(Level level, int x, int y, Entity entity) { int age = level.getData(x, y); level.dropItem(x * 16 + 8, y * 16 + 8, 1, Items.get(name + " Seeds")); int count = 0; if (age >= maxAge) { count = random.nextInt(3) + 2; } else if (age >= maxAge - maxAge / 5) { count = random.nextInt(2) + 1; } level.dropItem(x * 16 + 8, y * 16 + 8, count, Items.get(name)); if (age >= maxAge && entity instanceof Player) { ((Player)entity).addScore(random.nextInt(5) + 1); } level.setTile(x, y, Tiles.get("Dirt")); } }
gpl-3.0
appnativa/rare
source/rare/swingx/com/appnativa/rare/platform/swing/ui/view/FormsView.java
7362
/* * Copyright appNativa Inc. All Rights Reserved. * * This file is part of the Real-time Application Rendering Engine (RARE). * * RARE 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.appnativa.rare.platform.swing.ui.view; import com.appnativa.rare.iConstants; import com.appnativa.rare.platform.swing.ui.util.SwingHelper; import com.appnativa.rare.ui.Component; import com.appnativa.rare.ui.Container; import com.appnativa.rare.ui.UIDimension; import com.appnativa.rare.ui.UIInsets; import com.appnativa.rare.ui.iPlatformComponent; import com.appnativa.rare.ui.iPlatformGraphics; import com.appnativa.rare.ui.painter.UICellPainter; import com.appnativa.rare.ui.painter.iPainter; import com.appnativa.rare.ui.painter.iPlatformPainter; import com.appnativa.jgoodies.forms.layout.CellConstraints; import com.appnativa.jgoodies.forms.layout.FormLayout; import com.appnativa.jgoodies.forms.layout.FormLayout.LayoutInfo; import java.awt.Dimension; import java.awt.Graphics; import java.util.Arrays; public class FormsView extends UtilityPanel { protected FormLayout.LayoutInfo layoutInfo; protected iPlatformPainter[] painters; private UIDimension size = new UIDimension(); private UIInsets insets = new UIInsets(); private FormLayout layout; protected boolean cacheLayoutInfo; public FormsView() { this(new FormLayout()); } public FormsView(FormLayout layout) { super(); this.layout = layout; } @Override public void add(iPlatformComponent c, Object constraints, int position) { c.putClientProperty(iConstants.RARE_CONSTRAINTS_PROPERTY, constraints); add(c.getView()); CellConstraints cc = (CellConstraints) constraints; layout.addLayoutComponent(c, cc); } @Override public Dimension getPreferredSize() { // TODO Auto-generated method stub return super.getPreferredSize(); } public void dispose() { if (painters != null) { Arrays.fill(painters, null); } } @Override public void invalidateLayout(java.awt.Container target) { if (layout != null) { layout.invalidateCaches(); } } @Override public Dimension minimumLayoutSize(java.awt.Container parent) { getMinimumSize(size, 0); return SwingHelper.setDimension(null, size); } @Override public Dimension preferredLayoutSize(java.awt.Container parent) { getPreferredSize(size); return SwingHelper.setDimension(null, size); } @Override public void remove(iPlatformComponent c) { if (c != null) { remove(c.getView()); layout.removeLayoutComponent(c); } } @Override public void removeAll() { super.removeAll(); layout.invalidateCaches(); } public void requestLayout() { if (layout != null) { layout.invalidateCaches(); revalidate(); } } public void setCellPainters(iPlatformPainter[] painters) { this.painters = painters; } public CellConstraints getCellConstraints(iPlatformComponent c) { return (CellConstraints) c.getClientProperty(iConstants.RARE_CONSTRAINTS_PROPERTY); } @Override public Object getConstraints(iPlatformComponent c) { return c.getClientProperty(iConstants.RARE_CONSTRAINTS_PROPERTY); } public iPlatformComponent getFormComponentAt(int col, int row) { CellConstraints cc; Container container = (Container) Component.fromView(this); int len = container.getComponentCount(); for (int i = 0; i < len; i++) { iPlatformComponent c = container.getComponentAt(i); cc = (CellConstraints) c.getClientProperty(iConstants.RARE_CONSTRAINTS_PROPERTY); if (cc == null) { continue; } if ((cc.gridX == col) && (cc.gridY == row)) { return c; } } return null; } public FormLayout getFormLayout() { return layout; } public void setFormLayout(FormLayout layout) { this.layout = layout; } @Override public void getMinimumSize(UIDimension size, int maxWidth) { Container container = (Container) Component.fromView(this); getFormLayout().getMinimumSize(container, size,maxWidth); } public void getPreferredSize(UIDimension size) { Container container = (Container) Component.fromView(this); getFormLayout().getPreferredSize(container, size, 0); } protected void adjustPainters(int[] columnOrigins, int[] rowOrigins) { int len = (painters == null) ? 0 : painters.length; if (len == 0) { return; } int rlen = rowOrigins.length; int clen = columnOrigins.length; for (int i = 0; i < len; i++) { UICellPainter cp = (UICellPainter) painters[i]; int x1 = cp.column; int y1 = cp.row; int x2 = cp.column + cp.columnSpan; int y2 = cp.row + cp.rowSpan; if ((x1 < 0) || (y1 < 0) || (y2 < 0) || (x2 < 0)) { continue; } if (y2 >= rlen) { y2 = rlen - 1; } if ((x1 >= clen) || (y1 >= rlen)) { cp.width = 0; cp.height = 0; continue; } if (x2 >= clen) { x2 = clen - 1; } if ((x2 < clen) && (y2 < rlen)) { cp.x = columnOrigins[x1]; cp.y = rowOrigins[y1]; cp.width = columnOrigins[x2] - cp.x; cp.height = rowOrigins[y2] - cp.y; } } } @Override protected void layoutContainerEx(int width, int height) { Container container = (Container) Component.fromView(this); if ((layout == null) || (container == null) || container.isDisposed()) { return; } int x[], y[]; if (layoutInfo != null) { x = layoutInfo.columnOrigins; y = layoutInfo.rowOrigins; } else { size.setSize(width, height); insets = container.getInsets(insets); layout.initializeColAndRowComponentLists(container); LayoutInfo layoutInfo = layout.computeLayout(container, size, insets); x = layoutInfo.columnOrigins; y = layoutInfo.rowOrigins; } layout.layoutComponents(container, x, y); adjustPainters(x, y); } /** * Performs the painting of the cell painters * @param g the graphics context */ protected void paintCells(iPlatformGraphics g) { if (painters != null) { g.saveState(); try { int len = painters.length; final int w = getWidth(); final int h = getHeight(); for (int i = 0; i < len; i++) { painters[i].paint(g, 0, 0, w, h, iPainter.UNKNOWN); } } finally { g.restoreState(); } } } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); paintCells(graphics); } }
gpl-3.0
jhpoelen/eol-globi-data
eol-globi-doi-resolver/src/test/java/org/eol/globi/service/DOIResolverImplIT.java
11577
package org.eol.globi.service; import org.globalbioticinteractions.doi.DOI; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Map; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.junit.Assert.assertNotNull; import static org.hamcrest.MatcherAssert.assertThat; public class DOIResolverImplIT { private static final String HOCKING = "Hocking, B. 1968. Insect-flower associations in the high Arctic with special reference to nectar. Oikos 19:359-388."; private static final String MEDAN = "Medan, D., N. H. Montaldo, M. Devoto, A. Mantese, V. Vasellati, and N. H. Bartoloni. 2002. Plant-pollinator relationships at two altitudes in the Andes of Mendoza, Argentina. Arctic Antarctic and Alpine Research 34:233-241."; private static final DOI HOCKING_DOI = new DOI("2307", "3565022"); private static final String MEDAN_DOI = "10.2307/1552480"; @Test public void resolveDOIByReferenceNoMatch() throws IOException { DOI doi = new DOIResolverImpl().resolveDoiFor("James D. Simons Food habits and trophic structure of the demersal fish assemblages on the Mississippi-Alabama continental shelf"); assertThat(doi, is(nullValue())); } @Test public void resolveDOIByReferenceNoMatch2() throws IOException { DOI doi = new DOIResolverImpl().resolveDoiFor("Petanidou, T. (1991). Pollination ecology in a phryganic ecosystem. Unp. PhD. Thesis, Aristotelian University, Thessaloniki."); assertThat(doi, is(nullValue())); } @Test public void resolveDOIByReferenceMatch8() throws IOException { DOI doi = new DOIResolverImpl().resolveDoiFor("Tutin, C.E.G., Ham, R.M., White, L.J.T., Harrison, M.J.S. 1997. The primate community of the Lopé Reserve, Gabon: diets, responses to fruit scarcity, and effects on biomass. American Journal of Primatology, 42: 1-24."); assertThat(doi.toString(), is("10.1002/(sici)1098-2345(1997)42:1<1::aid-ajp1>3.0.co;2-0")); } @Test public void resolveDOIByReferenceNoMatchToBookReview() throws IOException { DOI doi = new DOIResolverImpl().resolveDoiFor("J. N. Kremer and S. W. Nixon, A Coastal Marine Ecosystem: Simulation and Analysis, Vol. 24 of Ecol. Studies (Springer-Verlag, Berlin, 1978), from p. 12."); assertThat(doi, is(nullValue())); } @Test public void resolveDOIByNonExistentCitation() throws IOException { DOI doi = new DOIResolverImpl().resolveDoiFor("A. Thessen. 2014. Species associations extracted from EOL text data objects via text mining. Accessed at <associations_all_revised.txt> on 05 Feb 2018 and add some more and other things"); assertThat(doi, is(nullValue())); } @Test public void resolveDOIByNonExistentCitation3() throws IOException { DOI doi = new DOIResolverImpl().resolveDoiFor("Bundgaard, M. (2003). Tidslig og rumlig variation i et plante-bestøvernetværk. Msc thesis. University of Aarhus. Aarhus, Denmark."); assertThat(doi, is(nullValue())); } @Test public void resolveDOIByNonExistentCitation2() throws IOException { DOI doi = new DOIResolverImpl().resolveDoiFor("donald duck and mickey mouse run around"); assertThat(doi, is(nullValue())); } @Test public void possiblyMalformedDOI() throws IOException { DOI doi = new DOIResolverImpl().resolveDoiFor("Tutin, C.E.G., Ham, R.M., White, L.J.T., Harrison, M.J.S. 1997. The primate community of the Lopé Reserve, Gabon: diets, responses to fruit scarcity, and effects on biomass. American Journal of Primatology, 42: 1-24."); assertNotNull(doi); assertThat(doi.toString(), is("10.1002/(sici)1098-2345(1997)42:1<1::aid-ajp1>3.0.co;2-0")); } @Test @Ignore public void resolveDOIByReferenceURL() throws IOException { DOI doi = new DOIResolverImpl().resolveDoiFor("http://www.ncbi.nlm.nih.gov/nuccore/7109271"); assertThat(doi, is("10.1002/bimj.4710230217")); } @Test public void resolveDOIByReferenceTamarins() throws IOException { DOI doi = new DOIResolverImpl().resolveDoiFor("Raboy, Becky E., and James M. Dietz. Diet, Foraging, and Use of Space in Wild Golden-headed Lion Tamarins. American Journal of Primatology, 63(1):, 2004, 1-15. Accessed April 20, 2015. http://hdl.handle.net/10088/4251."); assertThat(doi.toString(), is("10.1002/ajp.20032")); } @Test public void resolveDOIByReferenceMatch2() throws IOException { DOI doi = new DOIResolverImpl().resolveDoiFor(MEDAN); assertThat(doi.toString(), is(MEDAN_DOI)); } @Test public void resolveDOIByReferenceMatch3() throws IOException { DOI doi = new DOIResolverImpl().resolveDoiFor(HOCKING); assertThat(doi.toString(), is(HOCKING_DOI.toString())); } @Test public void resolveDOIByReferenceMatchBatch() throws IOException { Map<String, DOI> doiMap = new DOIResolverImpl().resolveDoiFor(Arrays.asList(MEDAN, HOCKING)); assertThat(doiMap.get(HOCKING).toString(), is(HOCKING_DOI.toString())); assertThat(doiMap.get(MEDAN).toString(), is(MEDAN_DOI)); } @Test public void resolveDOIBugFixedServerError() throws IOException { String citation = new DOIResolverImpl().findCitationForDOI(new DOI("2307", "4070736")); assertThat(citation, is("Anon. McAtee’s “Food Habits of the Grosbeaks” Food Habits of the Grosbeaks W. L. McAtee. The Auk [Internet]. 1908 April;25(2):245–246. Available from: http://dx.doi.org/10.2307/4070736")); } @Test public void resolveWithCrossRefIntermittentRuntimeError() throws IOException { // see https://github.com/CrossRef/rest-api-doc/issues/93 String citation = new DOIResolverImpl().findCitationForDOI(new DOI("1017", "s0266467499000760")); assertThat(citation, is("Poulin B, Wright SJ, Lefebvre G, Calderón O. Interspecific synchrony and asynchrony in the fruiting phenologies of congeneric bird-dispersed plants in Panama. Journal of Tropical Ecology [Internet]. 1999 March;15(2):213–227. Available from: http://dx.doi.org/10.1017/s0266467499000760")); } @Test public void resolveBioInfoCitation() throws IOException { DOI doi = new DOIResolverImpl().resolveDoiFor("Galea, V.J. & Price, T.V.. 1988. Infection of Lettuce by Microdochium panattonianum. Transactions of the British Mycological Society. Vol Vol 91 (3). pp 419-425"); DOI expectedDoi = new DOI("1016", "s0007-1536(88)80117-7"); assertThat(doi, is(expectedDoi)); String citation = new DOIResolverImpl().findCitationForDOI(doi); assertThat(citation, containsString("Galea VJ, Price TV")); } @Test public void findCitationForDOIStrangeCharacters() throws IOException { String citation = new DOIResolverImpl().findCitationForDOI(new DOI("1007", "s00300-004-0645-x")); assertThat(citation, is("La Mesa M, Dalú M, Vacchi M. Trophic ecology of the emerald notothen Trematomus bernacchii (Pisces, Nototheniidae) from Terra Nova Bay, Ross Sea, Antarctica. Polar Biology [Internet]. 2004 July 27;27(11):721–728. Available from: http://dx.doi.org/10.1007/s00300-004-0645-x")); } @Test public void findCitationForDOI() throws IOException { String citationForDOI = new DOIResolverImpl().findCitationForDOI(new DOI("1086", "283073")); assertThat(citationForDOI, is("Menge BA, Sutherland JP. Species Diversity Gradients: Synthesis of the Roles of Predation, Competition, and Temporal Heterogeneity. The American Naturalist [Internet]. 1976 May;110(973):351–369. Available from: http://dx.doi.org/10.1086/283073")); } @Test public void findCitationForDOITRex() throws IOException { String citationForDOI = new DOIResolverImpl().findCitationForDOI(new DOI("1073", "pnas.1216534110")); assertThat(citationForDOI, is("DePalma RA, Burnham DA, Martin LD, Rothschild BM, Larson PL. Physical evidence of predatory behavior in Tyrannosaurus rex. Proceedings of the National Academy of Sciences [Internet]. 2013 July 15;110(31):12560–12564. Available from: http://dx.doi.org/10.1073/pnas.1216534110")); } @Test public void findCitationForDOIEscaped() throws IOException { String citationForDOI = new DOIResolverImpl().findCitationForDOI(new DOI("1577", "1548-8659(1973)102<511:fhojmf>2.0.co;2")); assertThat(citationForDOI, is("Carr WES, Adams CA. Food Habits of Juvenile Marine Fishes Occupying Seagrass Beds in the Estuarine Zone near Crystal River, Florida. Transactions of the American Fisheries Society [Internet]. 1973 July;102(3):511–540. Available from: http://dx.doi.org/10.1577/1548-8659(1973)102<511:fhojmf>2.0.co;2")); } @Test public void findCitationForDOI2() throws IOException { String citationForDOI = new DOIResolverImpl().findCitationForDOI(new DOI("1371", "journal.pone.0052967")); assertThat(citationForDOI, is("García-Robledo C, Erickson DL, Staines CL, Erwin TL, Kress WJ. Tropical Plant–Herbivore Networks: Reconstructing Species Interactions Using DNA Barcodes Heil M, editor. PLoS ONE [Internet]. 2013 January 8;8(1):e52967. Available from: http://dx.doi.org/10.1371/journal.pone.0052967")); } @Test public void findCitationForDOI3() throws IOException { String citationForDOI = new DOIResolverImpl().findCitationForDOI(new DOI("2307", "177149")); assertThat(citationForDOI, is("Yodzis P. DIFFUSE EFFECTS IN FOOD WEBS. Ecology [Internet]. 2000 January;81(1):261–266. Available from: http://dx.doi.org/10.1890/0012-9658(2000)081[0261:DEIFW]2.0.CO;2")); } @Test public void findMalformedCitationWithMalformedDOIURL() throws IOException { String citationForDOI = new DOIResolverImpl().findCitationForDOI(null); assertThat(citationForDOI, nullValue()); } @Test(expected = IOException.class) public void findNotResponding() throws IOException { new DOIResolverImpl("http://google.com").resolveDoiFor("some reference"); } @Test public void findCitationForDOIWithUnescapeChars() throws IOException, URISyntaxException { String citationForDOI = new DOIResolverImpl().findCitationForDOI(new DOI("1642", "0004-8038(2005)122[1182:baemfa]2.0.co;2")); assertThat(citationForDOI, is(notNullValue())); } @Test public void findCitationForDOIVariableInternalServerError() throws IOException, URISyntaxException { // see https://github.com/CrossRef/rest-api-doc/issues/93 assertThat(new DOIResolverImpl().findCitationForDOI(new DOI("1007", "s003000050412")), is(notNullValue())); assertThat(new DOIResolverImpl().findCitationForDOI(new DOI("1007", "s003000050412")), is(notNullValue())); } @Test public void findCitationForShortDOI() throws IOException, URISyntaxException { String citationForDOI = new DOIResolverImpl().findCitationForDOI(new DOI("1007", "s13127-011-0039-1")); assertThat(citationForDOI, is(notNullValue())); } @Test public void findCitationForShortDOIUpperCase() throws IOException, URISyntaxException { String citationForDOI = new DOIResolverImpl().findCitationForDOI(new DOI("5962", "bhl.title.2633")); assertThat(citationForDOI, is(notNullValue())); } }
gpl-3.0
beckg/common
src/org/aventinus/database/Binder.java
1669
//----------------------------------------------------------------------------------- // Copyright (c) 2009-2013, Gordon Beck (gordon.beck@aventinus.org). All rights reserved. // // This file is part of a suite of tools. // // The tools are 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. // // The tools are distributed in the hope that they 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 these tools. If not, see <http://www.gnu.org/licenses/>. //----------------------------------------------------------------------------------- package org.aventinus.database; import java.util.*; //----------------------------------------------------------------------------------------------- // //----------------------------------------------------------------------------------------------- public interface Binder { //------------------------------------------------------------------------------------------- // //------------------------------------------------------------------------------------------- public String getString(int bind); public int getInteger(int bind); public long getLong(int bind); public double getDouble(int bind); public long getDate(int column); }
gpl-3.0
mehah/Greencode-Framework
src/com/jrender/jscript/dom/elements/BdiElement.java
404
package com.jrender.jscript.dom.elements; import com.jrender.jscript.dom.Element; import com.jrender.jscript.dom.ElementHandle; import com.jrender.jscript.dom.Window; /**Only supported in HTML5.*/ public class BdiElement extends Element { protected BdiElement(Window window) { super(window, "bdi"); } public static BdiElement cast(Element e) { return ElementHandle.cast(e, BdiElement.class); } }
gpl-3.0
hunering/smartreport
src/public/nc/ui/smp/tuikuan/ClientUIGetter.java
511
package nc.ui.smp.tuikuan; import java.io.Serializable; import nc.vo.trade.pub.IBDGetCheckClass2; /** * <b> ǰ̨УÑéÀàµÄGetterÀà </b> * * <p> * ÔÚ´Ë´¦Ìí¼Ó´ËÀàµÄÃèÊöÐÅÏ¢ * </p> * * * @author author * @version tempProject version */ public class ClientUIGetter implements IBDGetCheckClass2,Serializable { /** * ǰ̨УÑéÀà */ public String getUICheckClass() { return "nc.ui.smp.tuikuan.ClientUICheckRule"; } /** * ºǫ́УÑéÀà */ public String getCheckClass() { return null; } }
gpl-3.0
316181444/Hxms
src/main/java/net/sf/odinms/server/fourthjobquests/FourthJobQuestsPortalHandler.java
3986
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.odinms.server.fourthjobquests; import java.util.Collection; import net.sf.odinms.client.MapleCharacter; import net.sf.odinms.client.MapleJob; import net.sf.odinms.client.messages.ServerNoticeMapleClientMessageCallback; import net.sf.odinms.net.StringValueHolder; import net.sf.odinms.net.world.MapleParty; import net.sf.odinms.net.world.MaplePartyCharacter; import net.sf.odinms.tools.MaplePacketCreator; /** * * @author AngelSL */ public class FourthJobQuestsPortalHandler { public enum FourthJobQuests implements StringValueHolder { RUSH("s4rush"), BERSERK("s4berserk"); private final String name; private FourthJobQuests(String Newname) { this.name = Newname; } @Override public String getValue() { return name; } } private FourthJobQuestsPortalHandler() { } public static boolean handlePortal(String name, MapleCharacter c) { ServerNoticeMapleClientMessageCallback snmcmc = new ServerNoticeMapleClientMessageCallback( 5, c.getClient()); if (name.equals(FourthJobQuests.RUSH.getValue())) { if (!checkPartyLeader(c) && !checkRush(c)) { snmcmc.dropMessage("You step into the portal, but it swiftly kicks you out."); c.getClient().getSession() .write(MaplePacketCreator.enableActions()); } if (!checkPartyLeader(c) && checkRush(c)) { snmcmc.dropMessage("你不是队长."); c.getClient().getSession() .write(MaplePacketCreator.enableActions()); return true; } if (!checkRush(c)) { snmcmc.dropMessage("Someone in your party is not a 4th Job warrior."); c.getClient().getSession() .write(MaplePacketCreator.enableActions()); return true; } c.getClient().getChannelServer().getEventSM() .getEventManager("4jrush") .startInstance(c.getParty(), c.getMap()); return true; } else if (name.equals(FourthJobQuests.BERSERK.getValue())) { if (!checkBerserk(c)) { snmcmc.dropMessage("The portal to the Forgotten Shrine is locked"); c.getClient().getSession() .write(MaplePacketCreator.enableActions()); return true; } c.getClient().getChannelServer().getEventSM() .getEventManager("4jberserk") .startInstance(c.getParty(), c.getMap()); return true; } return false; } private static boolean checkRush(MapleCharacter c) { MapleParty CsParty = c.getParty(); Collection<MaplePartyCharacter> CsPartyMembers = CsParty.getMembers(); for (MaplePartyCharacter mpc : CsPartyMembers) { if (!MapleJob.getById(mpc.getJobId()).isA(MapleJob.WARRIOR)) { return false; } if (!(MapleJob.getById(mpc.getJobId()).isA(MapleJob.HERO) || MapleJob.getById(mpc.getJobId()).isA(MapleJob.PALADIN) || MapleJob .getById(mpc.getJobId()).isA(MapleJob.DARKKNIGHT))) { return false; } } return true; } private static boolean checkPartyLeader(MapleCharacter c) { return c.getParty().getLeader().getId() == c.getId(); } private static boolean checkBerserk(MapleCharacter c) { return c.haveItem(4031475, 1, false, false); } }
gpl-3.0
exteso/alf.io
src/main/java/alfio/controller/api/admin/ExtensionApiController.java
12103
/** * This file is part of alf.io. * * alf.io 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. * * alf.io 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 alf.io. If not, see <http://www.gnu.org/licenses/>. */ package alfio.controller.api.admin; import alfio.controller.api.support.PageAndContent; import alfio.extension.Extension; import alfio.extension.ExtensionService; import alfio.manager.user.UserManager; import alfio.model.EventAndOrganizationId; import alfio.model.ExtensionLog; import alfio.model.ExtensionSupport; import alfio.model.ExtensionSupport.ExtensionMetadataValue; import alfio.model.ExtensionSupport.ExtensionParameterMetadataAndValue; import alfio.model.user.Organization; import alfio.model.user.User; import alfio.repository.EventRepository; import alfio.repository.user.OrganizationRepository; import lombok.AllArgsConstructor; import lombok.extern.log4j.Log4j2; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.tuple.Pair; import org.springframework.core.io.ClassPathResource; import org.springframework.http.ResponseEntity; import org.springframework.util.StreamUtils; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.io.InputStream; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.security.Principal; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @RestController @AllArgsConstructor @RequestMapping("/admin/api/extensions") @Log4j2 public class ExtensionApiController { private static final String SAMPLE_JS; static { try (InputStream is = new ClassPathResource("/alfio/extension/sample.js").getInputStream()){ SAMPLE_JS = StreamUtils.copyToString(is, StandardCharsets.UTF_8); } catch (IOException e) { throw new IllegalStateException("cannot read sample file", e); } } private final ExtensionService extensionService; private final UserManager userManager; private final OrganizationRepository organizationRepository; private final EventRepository eventRepository; @GetMapping("") public List<ExtensionSupport> listAll(Principal principal) { ensureAdmin(principal); return extensionService.listAll(); } @GetMapping("/sample") public ExtensionSupport getSample() { return new ExtensionSupport(null, "-", "", null, true, true, SAMPLE_JS, null); } @PostMapping(value = "") public ResponseEntity<SerializablePair<Boolean, String>> create(@RequestBody Extension script, Principal principal) { return createOrUpdate(null, null, script, principal); } @PostMapping(value = "{path}/{name}") public ResponseEntity<SerializablePair<Boolean, String>> update(@PathVariable("path") String path, @PathVariable("name") String name, @RequestBody Extension script, Principal principal) { return createOrUpdate(path, name, script, principal); } private ResponseEntity<SerializablePair<Boolean, String>> createOrUpdate(String previousPath, String previousName, Extension script, Principal principal) { try { ensureAdmin(principal); extensionService.createOrUpdate(previousPath, previousName, script); return ResponseEntity.ok(SerializablePair.of(true, null)); } catch (Throwable t) { log.error("unexpected exception", t); return ResponseEntity.badRequest().body(SerializablePair.of(false, t.getMessage())); } } @GetMapping("{path}/{name}") public ResponseEntity<ExtensionSupport> loadSingle(@PathVariable("path") String path, @PathVariable("name") String name, Principal principal) { ensureAdmin(principal); return extensionService.getSingle(URLDecoder.decode(path, StandardCharsets.UTF_8), name).map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); } @DeleteMapping(value = "{path}/{name}") public void delete(@PathVariable("path") String path, @PathVariable("name") String name, Principal principal) { ensureAdmin(principal); extensionService.delete(path, name); } @PostMapping(value = "/{path}/{name}/toggle/{enable}") public void toggle(@PathVariable("path") String path, @PathVariable("name") String name, @PathVariable("enable") boolean enable, Principal principal) { ensureAdmin(principal); extensionService.toggle(path, name, enable); } // @GetMapping("/setting/system") public Map<Integer, List<ExtensionParameterMetadataAndValue>> getParametersFor(Principal principal) { if(userManager.isAdmin(userManager.findUserByUsername(principal.getName()))) { return extensionService.getConfigurationParametersFor("-", "-%", "SYSTEM") .stream().collect(Collectors.groupingBy(ExtensionParameterMetadataAndValue::getExtensionId)); } return Map.of(); } @PostMapping("/setting/system/bulk-update") public void bulkUpdateSystem(@RequestBody List<ExtensionMetadataValue> toUpdate, Principal principal) { ensureAdmin(principal); ensureIdsArePresent(toUpdate, extensionService.getConfigurationParametersFor("-", "-%", "SYSTEM")); extensionService.bulkUpdateSystemSettings(toUpdate); } @DeleteMapping("/setting/system/{id}") public void deleteSystemSettingValue(@PathVariable("id") int id, Principal principal) { ensureAdmin(principal); extensionService.deleteSettingValue(id, "-"); } @GetMapping("/setting/organization/{orgId}") public Map<Integer, List<ExtensionParameterMetadataAndValue>> getParametersFor(@PathVariable("orgId") int orgId, Principal principal) { Organization org = organizationRepository.getById(orgId); ensureOrganization(principal, org); return extensionService.getConfigurationParametersFor("-" + org.getId(), "-" + org.getId()+"-%", "ORGANIZATION") .stream().collect(Collectors.groupingBy(ExtensionParameterMetadataAndValue::getExtensionId)); } @PostMapping("/setting/organization/{orgId}/bulk-update") public void bulkUpdateOrganization(@PathVariable("orgId") int orgId, @RequestBody List<ExtensionMetadataValue> toUpdate, Principal principal) { Organization org = organizationRepository.getById(orgId); ensureOrganization(principal, org); ensureIdsArePresent(toUpdate, extensionService.getConfigurationParametersFor("-" + org.getId(), "-" + org.getId()+"-%", "ORGANIZATION")); extensionService.bulkUpdateOrganizationSettings(org, toUpdate); } @DeleteMapping("/setting/organization/{orgId}/{id}") public void deleteOrganizationSettingValue(@PathVariable("orgId") int orgId, @PathVariable("id") int id, Principal principal) { Organization org = organizationRepository.getById(orgId); ensureOrganization(principal, org); extensionService.deleteSettingValue(id, "-" + org.getId()); } @GetMapping("/setting/organization/{orgId}/event/{shortName}") public Map<Integer, List<ExtensionParameterMetadataAndValue>> getParametersFor(@PathVariable("orgId") int orgId, @PathVariable("shortName") String eventShortName, Principal principal) { Organization org = organizationRepository.getById(orgId); ensureOrganization(principal, org); var event = eventRepository.findOptionalEventAndOrganizationIdByShortName(eventShortName).orElseThrow(IllegalStateException::new); ensureEventInOrganization(org, event); String pattern = generatePatternFrom(event); return extensionService.getConfigurationParametersFor(pattern, pattern,"EVENT") .stream().collect(Collectors.groupingBy(ExtensionParameterMetadataAndValue::getExtensionId)); } @PostMapping("/setting/organization/{orgId}/event/{shortName}/bulk-update") public void bulkUpdateEvent(@PathVariable("orgId") int orgId, @PathVariable("shortName") String eventShortName, @RequestBody List<ExtensionMetadataValue> toUpdate, Principal principal) { Organization org = organizationRepository.getById(orgId); ensureOrganization(principal, org); var event = eventRepository.findOptionalEventAndOrganizationIdByShortName(eventShortName).orElseThrow(IllegalStateException::new); ensureEventInOrganization(org, event); String pattern = generatePatternFrom(event); ensureIdsArePresent(toUpdate, extensionService.getConfigurationParametersFor(pattern, pattern, "EVENT")); extensionService.bulkUpdateEventSettings(org, event, toUpdate); } @DeleteMapping("/setting/organization/{orgId}/event/{shortName}/{id}") public void deleteEventSettingValue(@PathVariable("orgId") int orgId, @PathVariable("shortName") String eventShortName, @PathVariable("id") int id, Principal principal) { Organization org = organizationRepository.getById(orgId); ensureOrganization(principal, org); var event = eventRepository.findOptionalEventAndOrganizationIdByShortName(eventShortName).orElseThrow(IllegalStateException::new); ensureEventInOrganization(org, event); extensionService.deleteSettingValue(id, generatePatternFrom(event)); } private static String generatePatternFrom(EventAndOrganizationId event) { return String.format("-%d-%d", event.getOrganizationId(), event.getId()); } //check that the ids are coherent private static void ensureIdsArePresent(List<ExtensionMetadataValue> toUpdate, List<ExtensionParameterMetadataAndValue> system) { Set<Integer> validIds = system.stream().map(ExtensionParameterMetadataAndValue::getId).collect(Collectors.toSet()); Set<Integer> toUpdateIds = toUpdate.stream().map(ExtensionMetadataValue::getId).collect(Collectors.toSet()); if(!validIds.containsAll(toUpdateIds)) { throw new IllegalStateException(); } } // @GetMapping("/log") public PageAndContent<List<ExtensionLog>> getLog(@RequestParam(required = false, name = "path") String path, @RequestParam(required = false, name = "name") String name, @RequestParam(required = false, name = "type") ExtensionLog.Type type, @RequestParam(required = false, name = "page", defaultValue = "0") Integer page, Principal principal) { ensureAdmin(principal); final int pageSize = 50; Pair<List<ExtensionLog>, Integer> res = extensionService.getLog(StringUtils.trimToNull(path), StringUtils.trimToNull(name), type, pageSize, (page == null ? 0 : page) * pageSize); return new PageAndContent<>(res.getLeft(), res.getRight()); } private void ensureAdmin(Principal principal) { Validate.isTrue(userManager.isAdmin(userManager.findUserByUsername(principal.getName()))); } private void ensureOrganization(Principal principal, Organization organization) { User user = userManager.findUserByUsername(principal.getName()); Validate.isTrue(userManager.isOwnerOfOrganization(user, organization.getId())); } private static void ensureEventInOrganization(Organization organization, EventAndOrganizationId event) { Validate.isTrue(organization.getId() == event.getOrganizationId()); } }
gpl-3.0
Nasso/Elektrode
src/io/github/nasso/elektrode/view/Renderable.java
213
package io.github.nasso.elektrode.view; public interface Renderable { public double getX(); public double getY(); public double getWidth(); public double getHeight(); public int getOrientation(); }
gpl-3.0
automenta/jcog
spacegraph/jcog/spacegraph/math/NormalCalc.java
4800
/* * gleem -- OpenGL Extremely Easy-To-Use Manipulators. * Copyright (C) 1998-2003 Kenneth B. Russell (kbrussel@alum.mit.edu) * * Copying, distribution and use of this software in source and binary * forms, with or without modification, is permitted provided that the * following conditions are met: * * Distributions of source code must reproduce the copyright notice, * this list of conditions and the following disclaimer in the source * code header files; and Distributions of binary code must reproduce * the copyright notice, this list of conditions and the following * disclaimer in the documentation, Read me file, license file and/or * other materials provided with the software distribution. * * The names of Sun Microsystems, Inc. ("Sun") and/or the copyright * holder may not be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED "AS IS," WITHOUT A WARRANTY OF ANY * KIND. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, NON-INTERFERENCE, ACCURACY OF * INFORMATIONAL CONTENT OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. THE * COPYRIGHT HOLDER, SUN AND SUN'S LICENSORS SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL THE * COPYRIGHT HOLDER, SUN OR SUN'S LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR * INABILITY TO USE THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGES. YOU ACKNOWLEDGE THAT THIS SOFTWARE IS NOT * DESIGNED, LICENSED OR INTENDED FOR USE IN THE DESIGN, CONSTRUCTION, * OPERATION OR MAINTENANCE OF ANY NUCLEAR FACILITY. THE COPYRIGHT * HOLDER, SUN AND SUN'S LICENSORS DISCLAIM ANY EXPRESS OR IMPLIED * WARRANTY OF FITNESS FOR SUCH USES. */ package jcog.spacegraph.math; import jcog.spacegraph.math.linalg.Vec3f; /** Calculates normals for a set of polygons. */ public class NormalCalc { /** Set of normals computed using {@link gleem.NormalCalc}. */ public static class NormalInfo { public Vec3f[] normals; public int[] normalIndices; NormalInfo(Vec3f[] normals, int[] normalIndices) { this.normals = normals; this.normalIndices = normalIndices; } } /** Returns null upon failure, or a set of Vec3fs and integers which represent faceted (non-averaged) normals, but per-vertex. Performs bounds checking on indices with respect to vertex list. Index list must represent independent triangles; indices are taken in groups of three. If index list doesn't represent triangles or other error occurred then returns null. ccw flag indicates whether triangles are specified counterclockwise when viewed from top or not. */ public static NormalInfo computeFacetedNormals(Vec3f[] vertices, int[] indices, boolean ccw) { if ((indices.length % 3) != 0) { System.err.println("NormalCalc.computeFacetedNormals: numIndices wasn't " + "divisible by 3, so it can't possibly " + "represent a set of triangles"); return null; } Vec3f[] outputNormals = new Vec3f[indices.length / 3]; int[] outputNormalIndices = new int[indices.length]; Vec3f d1 = new Vec3f(); Vec3f d2 = new Vec3f(); int curNormalIndex = 0; for (int i = 0; i < indices.length; i += 3) { int i0 = indices[i]; int i1 = indices[i+1]; int i2 = indices[i+2]; if ((i0 < 0) || (i0 >= indices.length) || (i1 < 0) || (i1 >= indices.length) || (i2 < 0) || (i2 >= indices.length)) { System.err.println("NormalCalc.computeFacetedNormals: ERROR: " + "vertex index out of bounds or no end of triangle " + "index found"); return null; } Vec3f v0 = vertices[i0]; Vec3f v1 = vertices[i1]; Vec3f v2 = vertices[i2]; d1.sub(v1, v0); d2.sub(v2, v0); Vec3f n = new Vec3f(); if (ccw) { n.cross(d1, d2); } else { n.cross(d2, d1); } n.normalize(); outputNormals[curNormalIndex] = n; outputNormalIndices[i] = curNormalIndex; outputNormalIndices[i+1] = curNormalIndex; outputNormalIndices[i+2] = curNormalIndex; curNormalIndex++; } return new NormalInfo(outputNormals, outputNormalIndices); } }
gpl-3.0
azeckoski/iclicker-sakai-integrate
src/main/java/org/sakaiproject/iclicker/model/ClickerUserKey.java
3837
/** * Copyright (c) 2009 i>clicker (R) <http://www.iclicker.com/dnn/> * * This file is part of i>clicker Sakai integrate. * * i>clicker Sakai integrate 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. * * i>clicker Sakai integrate 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 i>clicker Sakai integrate. If not, see <http://www.gnu.org/licenses/>. */ package org.sakaiproject.iclicker.model; import java.io.Serializable; import java.util.Date; /** * This represents a clicker user key which is assigned to instructors on demand when used with an * LMS which uses a single sign on system. They key is used in place of a password and is a randomly * generated alphanum char sequence. * * @author Aaron Zeckoski (azeckoski @ gmail.com) */ public class ClickerUserKey implements Serializable { private static final long serialVersionUID = 1L; private Long id; /** * Sakai userId (internal, not EID/USERNAME) */ private String userId; /** * The encoded user key */ private String userKey; private Date dateCreated; private Date dateModified; /** * Default constructor */ public ClickerUserKey() { } /** * Full constructor */ public ClickerUserKey(String userKey, String userId) { this.userKey = userKey; this.userId = userId; this.dateCreated = new Date(); this.dateModified = this.dateCreated; } /** * Special copy constructor which ensures we are not handing around the persistent object */ public ClickerUserKey(ClickerUserKey cluk) { this.id = cluk.getId(); this.userKey = cluk.getUserKey(); this.userId = cluk.getUserId(); this.dateCreated = cluk.getDateCreated(); this.dateModified = cluk.getDateModified(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ClickerUserKey other = (ClickerUserKey) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return "ClickerUserKey [id=" + id + ", userId=" + userId + ", userKey=" + userKey + "]"; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserKey() { return userKey; } public void setUserKey(String userKey) { this.userKey = userKey; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public Date getDateModified() { return dateModified; } public void setDateModified(Date dateModified) { this.dateModified = dateModified; } }
gpl-3.0
talek69/curso
stimulsoft/src/com/stimulsoft/report/events/StiExportingEvent.java
971
/* * Decompiled with CFR 0_114. */ package com.stimulsoft.report.events; import com.stimulsoft.report.codedom.StiParameterInfo; import com.stimulsoft.report.components.StiComponent; import com.stimulsoft.report.events.StiEvent; import com.stimulsoft.report.events.StiExportEventArgs; import com.stimulsoft.report.events.StiExportEventHandler; public class StiExportingEvent extends StiEvent { public StiParameterInfo[] getParameters() { return new StiParameterInfo[]{new StiParameterInfo(Object.class, "sender"), new StiParameterInfo(StiExportEventArgs.class, "e")}; } public Class getEventType() { return StiExportEventHandler.class; } public String toString() { return "Exporting"; } public StiExportingEvent() { this(""); } public StiExportingEvent(String string) { super(string); } public StiExportingEvent(StiComponent stiComponent) { super(stiComponent); } }
gpl-3.0
Dahie/DDS-Utils
Radds/src/de/danielsenff/radds/models/ColorChannel.java
708
/** * */ package de.danielsenff.radds.models; import ddsutil.ImageOperations; /** * @author danielsenff * */ public class ColorChannel { ImageOperations.ChannelMode channel; String titel; /** * */ public ColorChannel(ImageOperations.ChannelMode channel, String titel) { this.channel = channel; this.titel = titel; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return this.titel; } /** * Returns the titel of the Channel * @return */ public String getTitel() { return this.titel; } /** * Return the channel * @return */ public ImageOperations.ChannelMode getChannel() { return this.channel; } }
gpl-3.0
blynkkk/blynk-server
server/http-core/src/main/java/cc/blynk/core/http/utils/AdminHttpUtil.java
4171
package cc.blynk.core.http.utils; import cc.blynk.core.http.model.NameCountResponse; import cc.blynk.server.core.model.serialization.JsonParser; import cc.blynk.server.core.stats.model.CommandStat; import java.lang.reflect.Field; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * The Blynk Project. * Created by Dmitriy Dumanskiy. * Created on 09.12.15. */ public final class AdminHttpUtil { private AdminHttpUtil() { } @SuppressWarnings("unchecked") public static List<?> sortStringAsInt(List<?> list, String field, String order) { if (list.size() == 0) { return list; } Comparator c = new GenericStringAsIntComparator(list.get(0).getClass(), field); list.sort("asc".equalsIgnoreCase(order) ? c : Collections.reverseOrder(c)); return list; } @SuppressWarnings("unchecked") public static List<?> sort(List<?> list, String field, String order) { if (list.size() == 0) { return list; } Comparator c = new GenericComparator(list.get(0).getClass(), field); list.sort("asc".equalsIgnoreCase(order) ? c : Collections.reverseOrder(c)); return list; } public static List<NameCountResponse> convertMapToPair(Map<String, ?> map) { return map.entrySet().stream().map(NameCountResponse::new).collect(Collectors.toList()); } @SuppressWarnings("unchecked") public static List<NameCountResponse> convertObjectToMap(CommandStat commandStat) { return convertMapToPair(JsonParser.MAPPER.convertValue(commandStat, Map.class)); } /** * The Blynk Project. * Created by Dmitriy Dumanskiy. * Created on 10.12.15. */ public static class GenericComparator implements Comparator { private final Class<?> fieldType; private final Field field; GenericComparator(Class<?> type, String sortField) { try { this.field = type.getField(sortField); } catch (NoSuchFieldException nsfe) { throw new RuntimeException("Can't find field " + sortField + " for " + type.getName()); } this.fieldType = field.getType(); } @Override public int compare(Object o1, Object o2) { try { Object v1 = field.get(o1); Object v2 = field.get(o2); return compareActual(v1, v2, fieldType); } catch (Exception e) { throw new RuntimeException("Error on compare during sorting. Type : " + e.getMessage()); } } public int compareActual(Object v1, Object v2, Class<?> returnType) { if (returnType == int.class || returnType == Integer.class) { return Integer.compare((int) v1, (int) v2); } if (returnType == long.class || returnType == Long.class) { return Long.compare((long) v1, (long) v2); } if (returnType == String.class) { return ((String) v1).compareTo((String) v2); } throw new RuntimeException("Unexpected field type. Type : " + returnType.getName()); } } public static class GenericStringAsIntComparator extends GenericComparator { GenericStringAsIntComparator(Class<?> type, String sortField) { super(type, sortField); } @Override public int compareActual(Object v1, Object v2, Class<?> returnType) { if (returnType == int.class || returnType == Integer.class) { return Integer.compare((int) v1, (int) v2); } if (returnType == long.class || returnType == Long.class) { return Long.compare((long) v1, (long) v2); } if (returnType == String.class) { return Integer.valueOf((String) v1).compareTo(Integer.valueOf((String) v2)); } throw new RuntimeException("Unexpected field type. Type : " + returnType.getName()); } } }
gpl-3.0
Nuvolect/SecureSuite-Android
SecureSuite/src/main/java/com/nuvolect/securesuite/data/ImportUtil.java
3165
/* * Copyright (c) 2017. Nuvolect LLC * * 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. * * Contact legal@nuvolect.com for a less restrictive commercial license if you would like to use the * software without the GPLv3 restrictions. * * 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.nuvolect.securesuite.data; import java.util.HashMap; import java.util.Locale; import java.util.Map; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.os.Bundle; import android.provider.ContactsContract; public class ImportUtil { /** * Get the RawContacts data summary for each account * @return */ public static Bundle generateCloudSummary(Context ctx){ Bundle bundle = new Bundle(); String selectionA = ContactsContract.RawContacts.DELETED + " != 1"; String selectionB = ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY + " <> ''"; String selection = DatabaseUtils.concatenateWhere( selectionA, selectionB); HashMap<String, Integer> rawContactsMap = new HashMap<String, Integer>(); Cursor c = ctx.getContentResolver().query( ContactsContract.RawContacts.CONTENT_URI, new String[]{ ContactsContract.RawContacts.ACCOUNT_NAME, ContactsContract.RawContacts.CONTACT_ID, }, selection, null, null ); //Tally all of the raw contacts by account while( c.moveToNext()){ String account = c.getString( 0 ); // Build contact data sums for each account if( rawContactsMap.containsKey(account)){ Integer rawContactTotal = rawContactsMap.get(account); rawContactsMap.put(account, ++rawContactTotal); }else rawContactsMap.put(account, 1); } c.close(); final CharSequence[] accountList = new CharSequence[ rawContactsMap.size()]; final int[] countList = new int[ rawContactsMap.size()]; int i=0; for( Map.Entry<String, Integer> anAccount : rawContactsMap.entrySet()){ String currentAccount = anAccount.getKey().toLowerCase(Locale.US); int rawContactsThisAccount = anAccount.getValue(); accountList[ i ] = currentAccount+"\n"+rawContactsThisAccount+" contacts"; countList[ i++] = rawContactsThisAccount; } bundle.putCharSequenceArray("accountList", accountList); bundle.putIntArray("countList", countList); return bundle; } }
gpl-3.0
igaidai4uk/blynk-server
server/core/src/test/java/cc/blynk/server/core/model/PinStorageSerializationTest.java
2291
package cc.blynk.server.core.model; import cc.blynk.server.core.model.auth.User; import cc.blynk.server.core.model.enums.PinType; import cc.blynk.utils.JsonParser; import org.junit.Test; import java.util.HashMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * The Blynk Project. * Created by Dmitriy Dumanskiy. * Created on 19.11.16. */ public class PinStorageSerializationTest { @Test public void testSerialize() { User user = new User(); user.name = "123"; user.profile = new Profile(); user.profile.dashBoards = new DashBoard[] { new DashBoard() }; user.lastModifiedTs = 0; user.profile.dashBoards[0].pinsStorage = new HashMap<>(); PinStorageKey pinStorageKey = new PinStorageKey(0, PinType.VIRTUAL, (byte) 0); PinStorageKey pinStorageKey2 = new PinStorageKey(0, PinType.DIGITAL, (byte) 1); user.profile.dashBoards[0].pinsStorage.put(pinStorageKey, "0"); user.profile.dashBoards[0].pinsStorage.put(pinStorageKey2, "1"); String result = user.toString(); assertTrue(result.contains("0-v0")); assertTrue(result.contains("0-d1")); } @Test public void testDeserialize() throws Exception{ String expectedString = "{\"name\":\"123\",\"appName\":\"Blynk\",\"lastModifiedTs\":0,\"lastLoggedAt\":0,\"profile\":{\"dashBoards\":[{\"id\":0,\"createdAt\":0,\"updatedAt\":0,\"theme\":\"Blynk\",\"keepScreenOn\":false,\"isShared\":false,\"isActive\":false," + "\"pinsStorage\":{\"0-v0\":\"0\",\"0-d1\":\"1\"}" + "}]},\"isFacebookUser\":false,\"energy\":2000,\"id\":\"123-Blynk\"}"; User user = JsonParser.parseUserFromString(expectedString); assertNotNull(user); assertEquals(2, user.profile.dashBoards[0].pinsStorage.size()); PinStorageKey pinStorageKey = new PinStorageKey(0, PinType.VIRTUAL, (byte) 0); PinStorageKey pinStorageKey2 = new PinStorageKey(0, PinType.DIGITAL, (byte) 1); assertEquals("0", user.profile.dashBoards[0].pinsStorage.get(pinStorageKey)); assertEquals("1", user.profile.dashBoards[0].pinsStorage.get(pinStorageKey2)); } }
gpl-3.0
PlamenNeshkov/Treehouse-Android-Track
InteractiveStory/app/src/main/java/com/teamtreehouse/interactivestory/ui/MainActivity.java
1167
package com.teamtreehouse.interactivestory.ui; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.teamtreehouse.interactivestory.R; public class MainActivity extends AppCompatActivity { private EditText mNameField; private Button mStartButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mNameField = (EditText) findViewById(R.id.nameEditText); mStartButton = (Button) findViewById(R.id.startButton); mStartButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startStory(mNameField.getText().toString()); } }); } private void startStory(String name) { Intent intent = new Intent(this, StoryActivity.class); intent.putExtra(getString(R.string.key_name), name); startActivity(intent); } }
gpl-3.0
SwedishMonkey/MoreTools
src/main/java/com/swedishmonkey/moretools/shovel/RedstoneShovel.java
332
package com.swedishmonkey.moretools.shovel; import com.swedishmonkey.moretools.common.MoreTools; import net.minecraft.item.ItemSpade; public class RedstoneShovel extends ItemSpade { public RedstoneShovel(int i, ToolMaterial p_i45353_1_) { super(p_i45353_1_); this.setCreativeTab(MoreTools.tabTools); } }
gpl-3.0
KuppiliVenkataS/Coordination
CacheFramework/src/main/java/project/ResponseTimeSimulation/CommunityCache_Response/Query_Response.java
6680
package project.ResponseTimeSimulation.CommunityCache_Response; import project.QueryEnvironment.ExprTreeNode; import project.QueryEnvironment.ExpressionTree; import project.QueryEnvironment.Query_Subj_Predicate; import java.util.ArrayList; /** * Created by santhilata on 25/03/15. */ public class Query_Response implements Comparable{ //STATE 1 : start state private int startTime; // Time at state 1 private int queryNumber; // query number in the supplied list of queries private ExpressionTree remainingQuery; private double dataSizeFound; private double remaingDataNeeded; private Query_Subj_Predicate QSP; private StartState_State1 state1; private QuerySentOnLAN_State2 state2; private CacheProcessing_State3 state3; private CacheResultOnLAN_State4 state4; private RemainingQueryExecution_State5 state5; private QueryTransferOnWAN_State6 state6; private DataServer_State7 state7; private DataTransferOnWAN_State8 state8; private ResultAggregation_State9 state9; private int endTime;// Time ends for a query private boolean foundInCache; private String queryLocation; // user location String status; public Query_Response(){ this.state1 = new StartState_State1(); this.status = state1.status; } public Query_Response(int startTime){ this.startTime = startTime; this.state1 = new StartState_State1(startTime); this.status = state1.status; } public Query_Response(int startTime, int query){ this.startTime = startTime; this.queryNumber = query; this.state1 = new StartState_State1(startTime); this.status = state1.status; } //the following constructor is used only in Simple main public Query_Response(int startTime, String query, String queryLocation){ this.startTime = startTime; this.QSP = new Query_Subj_Predicate(query); this.state1 = new StartState_State1(startTime); this.status = state1.status; this.queryLocation = queryLocation; } public String getQueryLocation() { return queryLocation; } public void setQueryLocation(String queryLocation) { this.queryLocation = queryLocation; } public Query_Subj_Predicate getQSP() { return QSP; } public boolean isFoundInCache() { return foundInCache; } public void setFoundInCache(boolean foundInCache) { this.foundInCache = foundInCache; } public void setQSP(Query_Subj_Predicate QSP) { this.QSP = QSP; } public int getStartTime() { return startTime; } public void setStartTime(int startTime) { this.startTime = startTime; } public int getQueryNumber() { return queryNumber; } public void setQuery(int query) { this.queryNumber = query; } public StartState_State1 getState1() { return state1; } public void setState1(StartState_State1 state1) { this.state1 = state1; } public QuerySentOnLAN_State2 getState2() { return state2; } public void setState2(QuerySentOnLAN_State2 state2) { this.state2 = state2; } public CacheProcessing_State3 getState3() { return state3; } public void setState3(CacheProcessing_State3 state3) { this.state3 = state3; } public CacheResultOnLAN_State4 getState4() { return state4; } public void setState4(CacheResultOnLAN_State4 state4) { this.state4 = state4; } public RemainingQueryExecution_State5 getState5() { return state5; } public void setState5(RemainingQueryExecution_State5 state5) { this.state5 = state5; } public QueryTransferOnWAN_State6 getState6() { return state6; } public void setState6(QueryTransferOnWAN_State6 state6) { this.state6 = state6; } public DataServer_State7 getState7() { return state7; } public void setState7(DataServer_State7 state7) { this.state7 = state7; } public DataTransferOnWAN_State8 getState8() { return state8; } public void setState8(DataTransferOnWAN_State8 state8) { this.state8 = state8; } public ResultAggregation_State9 getState9() { return state9; } public void setState9(ResultAggregation_State9 state9) { this.state9 = state9; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public int getEndTime() { return endTime; } public void setEndTime(int endTime) { this.endTime = endTime; } public ExpressionTree getRemainingQuery() { return remainingQuery; } public void setRemainingQueryPartial(ExpressionTree remainingQuery) { this.remainingQuery = remainingQuery; this.setDataSizeFound(remainingQuery.calculateDataSizeFoundTree()); this.setRemaingDataNeeded(remainingQuery.calculateTotalDataSizeNeededTree()-this.getDataSizeFound()); } public double getRemaingDataNeeded() { return remaingDataNeeded; } private void setRemaingDataNeeded(double remaingDataNeeded) { this.remaingDataNeeded = remaingDataNeeded; } public double getDataSizeFound() { return dataSizeFound; } public void setRemainingQueryFull(ExpressionTree remainingQuery) { this.remainingQuery = remainingQuery; ArrayList<ExprTreeNode> someList = remainingQuery.packTreeInBFS_array(); for(ExprTreeNode etn: someList){ if (etn.isNodeFoundInCache()) System.out.println("From Query response full "+etn.getValue() .getQueryExpression()); } this.setDataSizeFound(remainingQuery.calculateTotalDataSizeNeededTree()); this.setRemaingDataNeeded(0); } private void setDataSizeFound(double dataSizeFound) { this.dataSizeFound = dataSizeFound; } @Override public int compareTo(Object o) { Query_Response that = (Query_Response)o; if (this.startTime > that.startTime) return 1; if (this.startTime <that.startTime) return -1; return 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Query_Response)) return false; Query_Response that = (Query_Response) o; if (startTime != that.startTime) return false; return true; } @Override public int hashCode() { return startTime; } }
gpl-3.0
natis1/void-Plague
src/org/apfloat/internal/LongCarryCRTStepStrategy.java
10074
package org.apfloat.internal; import java.math.BigInteger; import org.apfloat.ApfloatRuntimeException; import org.apfloat.spi.CarryCRTStepStrategy; import org.apfloat.spi.DataStorage; import static org.apfloat.internal.LongModConstants.*; /** * Class for performing the final steps of a three-modulus * Number Theoretic Transform based convolution. Works for the * <code>long</code> type.<p> * * All access to this class must be externally synchronized. * * @since 1.7.0 * @version 1.8.0 * @author Mikko Tommila */ public class LongCarryCRTStepStrategy extends LongCRTMath implements CarryCRTStepStrategy<long[]> { /** * Creates a carry-CRT steps object using the specified radix. * * @param radix The radix that will be used. */ public LongCarryCRTStepStrategy(int radix) { super(radix); } public long[] crt(DataStorage resultMod0, DataStorage resultMod1, DataStorage resultMod2, DataStorage dataStorage, long size, long resultSize, long offset, long length) throws ApfloatRuntimeException { long skipSize = (offset == 0 ? size - resultSize + 1: 0); // For the first block, ignore the first 1-3 elements long lastSize = (offset + length == size ? 1: 0); // For the last block, add 1 element long nonLastSize = 1 - lastSize; // For the other than last blocks, move 1 element long subResultSize = length - skipSize + lastSize; long subStart = size - offset, subEnd = subStart - length, subResultStart = size - offset - length + nonLastSize + subResultSize, subResultEnd = subResultStart - subResultSize; DataStorage.Iterator src0 = resultMod0.iterator(DataStorage.READ, subStart, subEnd), src1 = resultMod1.iterator(DataStorage.READ, subStart, subEnd), src2 = resultMod2.iterator(DataStorage.READ, subStart, subEnd), dst = dataStorage.iterator(DataStorage.WRITE, subResultStart, subResultEnd); long[] carryResult = new long[3], sum = new long[3], tmp = new long[3]; // Preliminary carry-CRT calculation (happens in parallel in multiple blocks) for (long i = 0; i < length; i++) { long y0 = MATH_MOD_0.modMultiply(T0, src0.getLong()), y1 = MATH_MOD_1.modMultiply(T1, src1.getLong()), y2 = MATH_MOD_2.modMultiply(T2, src2.getLong()); multiply(M12, y0, sum); multiply(M02, y1, tmp); if (add(tmp, sum) != 0 || compare(sum, M012) >= 0) { subtract(M012, sum); } multiply(M01, y2, tmp); if (add(tmp, sum) != 0 || compare(sum, M012) >= 0) { subtract(M012, sum); } add(sum, carryResult); long result = divide(carryResult); // In the first block, ignore the first element (it's zero in full precision calculations) // and possibly one or two more in limited precision calculations if (i >= skipSize) { dst.setLong(result); dst.next(); } src0.next(); src1.next(); src2.next(); } // Calculate the last words (in base math) long result0 = divide(carryResult); long result1 = carryResult[2]; assert (carryResult[0] == 0); assert (carryResult[1] == 0); // Last block has one extra element (corresponding to the one skipped in the first block) if (subResultSize == length - skipSize + 1) { dst.setLong(result0); dst.close(); result0 = result1; assert (result1 == 0); } long[] results = { result1, result0 }; return results; } public long[] carry(DataStorage dataStorage, long size, long resultSize, long offset, long length, long[] results, long[] previousResults) throws ApfloatRuntimeException { long skipSize = (offset == 0 ? size - resultSize + 1: 0); // For the first block, ignore the first 1-3 elements long lastSize = (offset + length == size ? 1: 0); // For the last block, add 1 element long nonLastSize = 1 - lastSize; // For the other than last blocks, move 1 element long subResultSize = length - skipSize + lastSize; long subResultStart = size - offset - length + nonLastSize + subResultSize, subResultEnd = subResultStart - subResultSize; // Get iterators for the previous block carries, and dst, padded with this block's carries // Note that size could be 1 but carries size is 2 DataStorage.Iterator src = arrayIterator(previousResults); DataStorage.Iterator dst = compositeIterator(dataStorage.iterator(DataStorage.READ_WRITE, subResultStart, subResultEnd), subResultSize, arrayIterator(results)); // Propagate base addition through dst, and this block's carries long carry = baseAdd(dst, src, 0, dst, previousResults.length); carry = baseCarry(dst, carry, subResultSize); dst.close(); // Iterator likely was not iterated to end assert (carry == 0); return results; } private long baseCarry(DataStorage.Iterator srcDst, long carry, long size) throws ApfloatRuntimeException { for (long i = 0; i < size && carry > 0; i++) { carry = baseAdd(srcDst, null, carry, srcDst, 1); } return carry; } // Wrap an array in a simple reverse-order iterator, padded with zeros private static DataStorage.Iterator arrayIterator(final long[] data) { return new DataStorage.Iterator() { public boolean hasNext() { return true; } public void next() { this.position--; } public long getLong() { assert (this.position >= 0); return data[this.position]; } public void setLong(long value) { assert (this.position >= 0); data[this.position] = value; } private static final long serialVersionUID = 1L; private int position = data.length - 1; }; } // Composite iterator, made by concatenating two iterators private static DataStorage.Iterator compositeIterator(final DataStorage.Iterator iterator1, final long size, final DataStorage.Iterator iterator2) { return new DataStorage.Iterator() { public boolean hasNext() { return (this.position < size ? iterator1.hasNext() : iterator2.hasNext()); } public void next() throws ApfloatRuntimeException { (this.position < size ? iterator1 : iterator2).next(); this.position++; } public long getLong() throws ApfloatRuntimeException { return (this.position < size ? iterator1 : iterator2).getLong(); } public void setLong(long value) throws ApfloatRuntimeException { (this.position < size ? iterator1 : iterator2).setLong(value); } public void close() throws ApfloatRuntimeException { (this.position < size ? iterator1 : iterator2).close(); } private static final long serialVersionUID = 1L; private long position; }; } private static final long serialVersionUID = -1851512769800204475L; private static final LongModMath MATH_MOD_0, MATH_MOD_1, MATH_MOD_2; private static final long T0, T1, T2; private static final long[] M01, M02, M12, M012; static { MATH_MOD_0 = new LongModMath(); MATH_MOD_1 = new LongModMath(); MATH_MOD_2 = new LongModMath(); MATH_MOD_0.setModulus(MODULUS[0]); MATH_MOD_1.setModulus(MODULUS[1]); MATH_MOD_2.setModulus(MODULUS[2]); // Probably sub-optimal, but it's a one-time operation BigInteger base = BigInteger.valueOf(Math.abs((long) MAX_POWER_OF_TWO_BASE)), // In int case the base is 0x80000000 m0 = BigInteger.valueOf((long) MODULUS[0]), m1 = BigInteger.valueOf((long) MODULUS[1]), m2 = BigInteger.valueOf((long) MODULUS[2]), m01 = m0.multiply(m1), m02 = m0.multiply(m2), m12 = m1.multiply(m2); T0 = m12.modInverse(m0).longValue(); T1 = m02.modInverse(m1).longValue(); T2 = m01.modInverse(m2).longValue(); M01 = new long[2]; M02 = new long[2]; M12 = new long[2]; M012 = new long[3]; BigInteger[] qr = m01.divideAndRemainder(base); M01[0] = qr[0].longValue(); M01[1] = qr[1].longValue(); qr = m02.divideAndRemainder(base); M02[0] = qr[0].longValue(); M02[1] = qr[1].longValue(); qr = m12.divideAndRemainder(base); M12[0] = qr[0].longValue(); M12[1] = qr[1].longValue(); qr = m0.multiply(m12).divideAndRemainder(base); M012[2] = qr[1].longValue(); qr = qr[0].divideAndRemainder(base); M012[0] = qr[0].longValue(); M012[1] = qr[1].longValue(); } }
gpl-3.0
annavicente/poo2
UsuarioSerializadoMensagem/src/Serializa/Mensagem.java
575
/* * 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 Serializa; import java.io.Serializable; import java.util.ArrayList; /** * * @author Ana */ public class Mensagem implements Serializable { private String texto; public Mensagem(String texto){ this.texto = texto; } public String getTexto() { return texto; } public void setTexto(String texto) { this.texto = texto; } }
gpl-3.0
Tomucha/coordinator
coordinator-server/src/main/java/cz/clovekvtisni/coordinator/server/domain/CoordinatorConfig.java
22120
package cz.clovekvtisni.coordinator.server.domain; import cz.clovekvtisni.coordinator.domain.config.*; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root; import org.simpleframework.xml.core.Commit; import org.simpleframework.xml.core.Validate; import java.util.*; /** * Created with IntelliJ IDEA. * User: jka * Date: 31.10.12 */ @Root(name = "coordinator") public class CoordinatorConfig { @ElementList(type = Role.class, name = "role_list", required = false) private List<Role> roleList; @ElementList(type = Skill.class, name = "skill_list", required = false) private List<Skill> skillList; @ElementList(type = Equipment.class, name = "equipment_list", required = false) private List<Equipment> equipmentList; @ElementList(type = Organization.class, name = "organization_list", required = false) private List<Organization> organizationList; @ElementList(type = Workflow.class, name = "workflow_list", required = false) private List<Workflow> workflowList; @ElementList(type = PoiCategory.class, name = "poi_category_list", required = false) private List<PoiCategory> poiCategoryList; private Map<String, PoiCategory> poiCategoryMap; private HashMap<String, String> countryMap; private Map<String, List<String>> roleParentMap; public List<Role> getRoleList() { return roleList; } public Map<String, Role> getRoleMap() { if (roleList == null) return new HashMap<String, Role>(0); Map<String, Role> map = new HashMap<String, Role>(roleList.size()); for (Role role : roleList) { map.put(role.getId(), role); } return map; } public Map<String, Workflow> getWorkflowMap() { if (workflowList == null) return new HashMap<String, Workflow>(0); Map<String, Workflow> map = new HashMap<String, Workflow>(workflowList.size()); for (Workflow workflow : workflowList) { map.put(workflow.getId(), workflow); } return map; } public List<Skill> getSkillList() { return skillList; } public Map<String, Skill> getSkillMap() { if (skillList == null) return new HashMap<String, Skill>(0); Map<String, Skill> map = new HashMap<String, Skill>(skillList.size()); for (Skill skill : skillList) { map.put(skill.getId(), skill); } return map; } public List<Equipment> getEquipmentList() { return equipmentList; } public Map<String, Equipment> getEquipmentMap() { if (equipmentList == null) return new HashMap<String, Equipment>(0); Map<String, Equipment> map = new HashMap<String, Equipment>(equipmentList.size()); for (Equipment equipment : equipmentList) { map.put(equipment.getId(), equipment); } return map; } public List<Organization> getOrganizationList() { return organizationList; } public List<Workflow> getWorkflowList() { return workflowList; } public List<PoiCategory> getPoiCategoryList() { return poiCategoryList; } @Validate public void validate() { Map<String, Role> roleMap = getRoleMap(); Map<String, Workflow> workflowMap = getWorkflowMap(); if (roleList != null) { for (Role role : roleList) { checkKeysExist(roleMap, role.getExtendsRoleId()); List<Role> parents = roleWithParents(role); Set<RolePermission> perms = new HashSet<RolePermission>(); for (Role parent : parents) { if (parent.getPermissions() != null) { for (RolePermission permission : parent.getPermissions()) { perms.add(permission); } } } role.setPermissions(perms.toArray(new RolePermission[0])); } } if (workflowList != null) { for (Workflow workflow : workflowList) { checkKeysExist(roleMap, workflow.getCanBeStartedBy()); if (workflow.getStates() != null) { for (WorkflowState state : workflow.getStates()) { checkKeysExist(roleMap, state.getEditableForRole()); checkKeysExist(roleMap, state.getVisibleForRole()); WorkflowTransition[] transitions = state.getTransitions(); if (transitions != null) { Map<String, WorkflowState> stateMap = workflow.getStateMap(); for (WorkflowTransition transition : transitions) { checkKeysExist(stateMap, transition.getFromStateId(), transition.getToStateId()); checkKeysExist(roleMap, transition.getAllowedForRole()); } } } } } } if (poiCategoryList != null) { for (PoiCategory poiCategory : poiCategoryList) { checkKeysExist(workflowMap, poiCategory.getWorkflowId()); } } if (organizationList != null) { Map<String, Skill> skillMap = getSkillMap(); Map<String, Equipment> equipmentMap = getEquipmentMap(); for (Organization organization : organizationList) { checkKeysExist(skillMap, organization.getPreRegistrationSkills()); checkKeysExist(equipmentMap, organization.getPreRegistrationEquipment()); } } } private <T extends AbstractStaticEntity> void checkKeysExist(Map<String, T> map, String... keys) { if (keys == null) return; for (String key : keys) { if (key != null && !map.containsKey(key)) { throw new IllegalStateException("Inconsistent configuration. Key=" + key + " does not exist."); } } } private List<Role> roleWithParents(Role role) { Map<String, Role> roleMap = getRoleMap(); List<Role> parents = new ArrayList<Role>(); if (role == null) return parents; parents.add(role); Role next = role; while (next != null && next.getExtendsRoleId() != null) { next = roleMap.get(next.getExtendsRoleId()); parents.add(next); } return parents; } public Map<String, Organization> getOrganizationMap() { List<Organization> organizations = getOrganizationList(); HashMap<String, Organization> organizationMap = new HashMap<String, Organization>(organizations.size()); if (organizations != null) { for (Organization organization : organizations) { organizationMap.put(organization.getId(), organization); } }; return organizationMap; } public Map<String, PoiCategory> getPoiCategoryMap() { if (poiCategoryList == null) return new TreeMap<String, PoiCategory>(); if (poiCategoryMap != null) return poiCategoryMap; final Map<String, PoiCategory> map = new HashMap<String, PoiCategory>(poiCategoryList.size()); for (PoiCategory category : poiCategoryList) { map.put(category.getId(), category); } Map<String, PoiCategory> sorted = new TreeMap<String, PoiCategory>(new Comparator<String>() { @Override public int compare(String o1, String o2) { String val1 = map.get(o1).getName(); String val2 = map.get(o2).getName(); if (val1 == null) return 1; if (val2 == null) return -1; return val1.compareTo(val2); } }); sorted.putAll(map); return poiCategoryMap = sorted; } public Map<String, String> getCountryMap() { if (countryMap != null) return countryMap; countryMap = new LinkedHashMap<String, String>(384); countryMap.put("CZ", "Czech Republic"); countryMap.put("AF", "Afghanistan"); countryMap.put("AL", "Albania"); countryMap.put("DZ", "Algeria"); countryMap.put("AS", "American Samoa"); countryMap.put("AD", "Andorra"); countryMap.put("AO", "Angola"); countryMap.put("AI", "Anguilla"); countryMap.put("AQ", "Antarctica"); countryMap.put("AG", "Antigua and Barbuda"); countryMap.put("AR", "Argentina"); countryMap.put("AM", "Armenia"); countryMap.put("AW", "Aruba"); countryMap.put("AU", "Australia"); countryMap.put("AT", "Austria"); countryMap.put("AZ", "Azerbaijan"); countryMap.put("BS", "Bahamas"); countryMap.put("BH", "Bahrain"); countryMap.put("BD", "Bangladesh"); countryMap.put("BB", "Barbados"); countryMap.put("BY", "Belarus"); countryMap.put("BE", "Belgium"); countryMap.put("BZ", "Belize"); countryMap.put("BJ", "Benin"); countryMap.put("BM", "Bermuda"); countryMap.put("BT", "Bhutan"); countryMap.put("BO", "Bolivia, Plurinational State of"); countryMap.put("BA", "Bosnia and Herzegovina"); countryMap.put("BW", "Botswana"); countryMap.put("BV", "Bouvet Island"); countryMap.put("BR", "Brazil"); countryMap.put("IO", "British Indian Ocean Territory"); countryMap.put("BN", "Brunei Darussalam"); countryMap.put("BG", "Bulgaria"); countryMap.put("BF", "Burkina Faso"); countryMap.put("BI", "Burundi"); countryMap.put("KH", "Cambodia"); countryMap.put("CM", "Cameroon"); countryMap.put("CA", "Canada"); countryMap.put("CV", "Cape Verde"); countryMap.put("KY", "Cayman Islands"); countryMap.put("CF", "Central African Republic"); countryMap.put("TD", "Chad"); countryMap.put("CL", "Chile"); countryMap.put("CN", "China"); countryMap.put("CX", "Christmas Island"); countryMap.put("CC", "Cocos (Keeling) Islands"); countryMap.put("CO", "Colombia"); countryMap.put("KM", "Comoros"); countryMap.put("CG", "Congo"); countryMap.put("CD", "Congo, the Democratic Republic of the"); countryMap.put("CK", "Cook Islands"); countryMap.put("CR", "Costa Rica"); countryMap.put("CI", "C&ocirc;te d'Ivoire"); countryMap.put("HR", "Croatia"); countryMap.put("CU", "Cuba"); countryMap.put("CY", "Cyprus"); countryMap.put("DK", "Denmark"); countryMap.put("DJ", "Djibouti"); countryMap.put("DM", "Dominica"); countryMap.put("DO", "Dominican Republic"); countryMap.put("EC", "Ecuador"); countryMap.put("EG", "Egypt"); countryMap.put("SV", "El Salvador"); countryMap.put("GQ", "Equatorial Guinea"); countryMap.put("ER", "Eritrea"); countryMap.put("EE", "Estonia"); countryMap.put("ET", "Ethiopia"); countryMap.put("FK", "Falkland Islands (Malvinas)"); countryMap.put("FO", "Faroe Islands"); countryMap.put("FJ", "Fiji"); countryMap.put("FI", "Finland"); countryMap.put("FR", "France"); countryMap.put("GF", "French Guiana"); countryMap.put("PF", "French Polynesia"); countryMap.put("TF", "French Southern Territories"); countryMap.put("GA", "Gabon"); countryMap.put("GM", "Gambia"); countryMap.put("GE", "Georgia"); countryMap.put("DE", "Germany"); countryMap.put("GH", "Ghana"); countryMap.put("GI", "Gibraltar"); countryMap.put("GR", "Greece"); countryMap.put("GL", "Greenland"); countryMap.put("GD", "Grenada"); countryMap.put("GP", "Guadeloupe"); countryMap.put("GU", "Guam"); countryMap.put("GT", "Guatemala"); countryMap.put("GG", "Guernsey"); countryMap.put("GN", "Guinea"); countryMap.put("GW", "Guinea-Bissau"); countryMap.put("GY", "Guyana"); countryMap.put("HT", "Haiti"); countryMap.put("HM", "Heard Island and McDonald Islands"); countryMap.put("VA", "Holy See (Vatican City State)"); countryMap.put("HN", "Honduras"); countryMap.put("HK", "Hong Kong"); countryMap.put("HU", "Hungary"); countryMap.put("IS", "Iceland"); countryMap.put("IN", "India"); countryMap.put("ID", "Indonesia"); countryMap.put("IR", "Iran, Islamic Republic of"); countryMap.put("IQ", "Iraq"); countryMap.put("IE", "Ireland"); countryMap.put("IM", "Isle of Man"); countryMap.put("IL", "Israel"); countryMap.put("IT", "Italy"); countryMap.put("JM", "Jamaica"); countryMap.put("JP", "Japan"); countryMap.put("JE", "Jersey"); countryMap.put("JO", "Jordan"); countryMap.put("KZ", "Kazakhstan"); countryMap.put("KE", "Kenya"); countryMap.put("KI", "Kiribati"); countryMap.put("KP", "Korea, Democratic People's Republic of"); countryMap.put("KR", "Korea, Republic of"); countryMap.put("KW", "Kuwait"); countryMap.put("KG", "Kyrgyzstan"); countryMap.put("LA", "Lao People's Democratic Republic"); countryMap.put("LV", "Latvia"); countryMap.put("LB", "Lebanon"); countryMap.put("LS", "Lesotho"); countryMap.put("LR", "Liberia"); countryMap.put("LY", "Libyan Arab Jamahiriya"); countryMap.put("LI", "Liechtenstein"); countryMap.put("LT", "Lithuania"); countryMap.put("LU", "Luxembourg"); countryMap.put("MO", "Macao"); countryMap.put("MK", "Macedonia, the former Yugoslav Republic of"); countryMap.put("MG", "Madagascar"); countryMap.put("MW", "Malawi"); countryMap.put("MY", "Malaysia"); countryMap.put("MV", "Maldives"); countryMap.put("ML", "Mali"); countryMap.put("MT", "Malta"); countryMap.put("MH", "Marshall Islands"); countryMap.put("MQ", "Martinique"); countryMap.put("MR", "Mauritania"); countryMap.put("MU", "Mauritius"); countryMap.put("YT", "Mayotte"); countryMap.put("MX", "Mexico"); countryMap.put("FM", "Micronesia, Federated States of"); countryMap.put("MD", "Moldova, Republic of"); countryMap.put("MC", "Monaco"); countryMap.put("MN", "Mongolia"); countryMap.put("ME", "Montenegro"); countryMap.put("MS", "Montserrat"); countryMap.put("MA", "Morocco"); countryMap.put("MZ", "Mozambique"); countryMap.put("MM", "Myanmar"); countryMap.put("NA", "Namibia"); countryMap.put("NR", "Nauru"); countryMap.put("NP", "Nepal"); countryMap.put("NL", "Netherlands"); countryMap.put("AN", "Netherlands Antilles"); countryMap.put("NC", "New Caledonia"); countryMap.put("NZ", "New Zealand"); countryMap.put("NI", "Nicaragua"); countryMap.put("NE", "Niger"); countryMap.put("NG", "Nigeria"); countryMap.put("NU", "Niue"); countryMap.put("NF", "Norfolk Island"); countryMap.put("MP", "Northern Mariana Islands"); countryMap.put("NO", "Norway"); countryMap.put("OM", "Oman"); countryMap.put("PK", "Pakistan"); countryMap.put("PW", "Palau"); countryMap.put("PS", "Palestinian Territory, Occupied"); countryMap.put("PA", "Panama"); countryMap.put("PG", "Papua New Guinea"); countryMap.put("PY", "Paraguay"); countryMap.put("PE", "Peru"); countryMap.put("PH", "Philippines"); countryMap.put("PN", "Pitcairn"); countryMap.put("PL", "Poland"); countryMap.put("PT", "Portugal"); countryMap.put("PR", "Puerto Rico"); countryMap.put("QA", "Qatar"); countryMap.put("RE", "R&eacute;union"); countryMap.put("RO", "Romania"); countryMap.put("RU", "Russian Federation"); countryMap.put("RW", "Rwanda"); countryMap.put("BL", "Saint Barth&eacute;lemy"); countryMap.put("SH", "Saint Helena, Ascension and Tristan da Cunha"); countryMap.put("KN", "Saint Kitts and Nevis"); countryMap.put("LC", "Saint Lucia"); countryMap.put("MF", "Saint Martin (French part)"); countryMap.put("PM", "Saint Pierre and Miquelon"); countryMap.put("VC", "Saint Vincent and the Grenadines"); countryMap.put("WS", "Samoa"); countryMap.put("SM", "San Marino"); countryMap.put("ST", "Sao Tome and Principe"); countryMap.put("SA", "Saudi Arabia"); countryMap.put("SN", "Senegal"); countryMap.put("RS", "Serbia"); countryMap.put("SC", "Seychelles"); countryMap.put("SL", "Sierra Leone"); countryMap.put("SG", "Singapore"); countryMap.put("SK", "Slovakia"); countryMap.put("SI", "Slovenia"); countryMap.put("SB", "Solomon Islands"); countryMap.put("SO", "Somalia"); countryMap.put("ZA", "South Africa"); countryMap.put("GS", "South Georgia and the South Sandwich Islands"); countryMap.put("ES", "Spain"); countryMap.put("LK", "Sri Lanka"); countryMap.put("SD", "Sudan"); countryMap.put("SR", "Suriname"); countryMap.put("SJ", "Svalbard and Jan Mayen"); countryMap.put("SZ", "Swaziland"); countryMap.put("SE", "Sweden"); countryMap.put("CH", "Switzerland"); countryMap.put("SY", "Syrian Arab Republic"); countryMap.put("TW", "Taiwan, Province of China"); countryMap.put("TJ", "Tajikistan"); countryMap.put("TZ", "Tanzania, United Republic of"); countryMap.put("TH", "Thailand"); countryMap.put("TL", "Timor-Leste"); countryMap.put("TG", "Togo"); countryMap.put("TK", "Tokelau"); countryMap.put("TO", "Tonga"); countryMap.put("TT", "Trinidad and Tobago"); countryMap.put("TN", "Tunisia"); countryMap.put("TR", "Turkey"); countryMap.put("TM", "Turkmenistan"); countryMap.put("TC", "Turks and Caicos Islands"); countryMap.put("TV", "Tuvalu"); countryMap.put("UG", "Uganda"); countryMap.put("UA", "Ukraine"); countryMap.put("AE", "United Arab Emirates"); countryMap.put("GB", "United Kingdom"); countryMap.put("US", "United States"); countryMap.put("UM", "United States Minor Outlying Islands"); countryMap.put("UY", "Uruguay"); countryMap.put("UZ", "Uzbekistan"); countryMap.put("VU", "Vanuatu"); countryMap.put("VE", "Venezuela"); countryMap.put("VN", "Viet Nam"); countryMap.put("VG", "Virgin Islands, British"); countryMap.put("VI", "Virgin Islands, U.S."); countryMap.put("WF", "Wallis and Futuna"); countryMap.put("EH", "Western Sahara"); countryMap.put("YE", "Yemen"); countryMap.put("ZM", "Zambia"); countryMap.put("ZW", "Zimbabwe"); return countryMap; } @Commit public void afterLoad() { if (roleList != null) { Collections.sort(roleList, new Comparator<Role>() { @Override public int compare(Role o1, Role o2) { return o1.getName() != null ? o1.getName().compareTo(o2.getName()) : -1; } }); Map<String, Role> roleMap = getRoleMap(); roleParentMap = new HashMap<String, List<String>>(roleMap.size()); for (Role role : roleMap.values()) { List<String> ids = new ArrayList<String>(); roleParentMap.put(role.getId(), ids); String parentId = role.getExtendsRoleId(); while (parentId != null) { ids.add(parentId); Role parent = roleMap.get(parentId); parentId = parent.getExtendsRoleId(); } } } if (skillList != null) { Collections.sort(skillList, new Comparator<Skill>() { @Override public int compare(Skill o1, Skill o2) { return o1.getName() != null ? o1.getName().compareTo(o2.getName()) : -1; } }); } if (equipmentList != null) { Collections.sort(equipmentList, new Comparator<Equipment>() { @Override public int compare(Equipment o1, Equipment o2) { return o1.getName() != null ? o1.getName().compareTo(o2.getName()) : -1; } }); } if (organizationList != null) { Collections.sort(organizationList, new Comparator<Organization>() { @Override public int compare(Organization o1, Organization o2) { return o1.getName() != null ? o1.getName().compareTo(o2.getName()) : -1; } }); } if (poiCategoryList != null) { Collections.sort(poiCategoryList, new Comparator<PoiCategory>() { @Override public int compare(PoiCategory o1, PoiCategory o2) { return o1.getName() != null ? o1.getName().compareTo(o2.getName()) : -1; } }); } } public Map<String, List<String>> getRoleParentMap() { return roleParentMap; } @Override public String toString() { return "CoordinatorConfig{" + "roleList=" + roleList + ", skillList=" + skillList + ", equipmentList=" + equipmentList + ", organizationList=" + organizationList + ", workflowList=" + workflowList + ", poiCategoryList=" + poiCategoryList + '}'; } }
gpl-3.0
markusheiden/serialthreads
src/main/java/org/serialthreads/transformer/code/MethodCode.java
9902
package org.serialthreads.transformer.code; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.*; import org.objectweb.asm.tree.analysis.BasicValue; import org.objectweb.asm.tree.analysis.Frame; import org.objectweb.asm.tree.analysis.Value; import org.serialthreads.context.IRunnable; import org.serialthreads.transformer.analyzer.ExtendedValue; import org.serialthreads.transformer.classcache.IClassInfoCache; import org.serialthreads.transformer.strategies.MetaInfo; import java.util.ArrayList; import java.util.List; import static org.objectweb.asm.Opcodes.*; /** * Method related code. */ public class MethodCode { private static final String IRUNNABLE_NAME = Type.getType(IRunnable.class).getInternalName(); // // method call specific code // /** * Is a static method been called?. * * @param methodCall method call */ public static boolean isStatic(MethodInsnNode methodCall) { return methodCall.getOpcode() == Opcodes.INVOKESTATIC; } /** * Is a not static method been called?. * * @param methodCall method call */ public static boolean isNotStatic(MethodInsnNode methodCall) { return !isStatic(methodCall); } /** * Is a not void method been called?. * * @param methodCall method call */ public static boolean isNotVoid(MethodInsnNode methodCall) { return !Type.getReturnType(methodCall.desc).equals(Type.VOID_TYPE); } /** * Is the call a call to a method on the same object (this)? * * @param methodCall method call * @param metaInfo Meta information about method call */ public static boolean isSelfCall(MethodInsnNode methodCall, MetaInfo metaInfo) { if (methodCall.getOpcode() == Opcodes.INVOKESTATIC) { // static methods have no owner return false; } Frame frameBefore = metaInfo.frameBefore; // "pop" all arguments from stack Type[] argumentTypes = Type.getArgumentTypes(methodCall.desc); int s = frameBefore.getStackSize() - argumentTypes.length; assert s > 0 : "Check: stack pointer is positive"; Value ownerType = frameBefore.getStack(s - 1); return ownerType instanceof ExtendedValue && ((ExtendedValue) ownerType).getLocals().contains(0); } /** * Check if the called method is IRunnable.run(). * * @param methodCall method call * @param classInfoCache classInfoCache */ public static boolean isRun(MethodInsnNode methodCall, IClassInfoCache classInfoCache) { return classInfoCache.hasSuperClass(methodCall.owner, IRUNNABLE_NAME) && methodCall.name.equals("run") && methodCall.desc.equals("()V"); } /** * Create dummy arguments for call to the given method for restoring code. * Creates appropriate argument values for a method call with 0 or null values. * * @param method method node to create arguments for */ public static InsnList dummyArguments(MethodInsnNode method) { InsnList instructions = new InsnList(); for (Type type : Type.getArgumentTypes(method.desc)) { instructions.add(ValueCodeFactory.code(type).pushNull()); } return instructions; } // // class specific code // /** * Is the class an interface?. * * @param clazz class */ public static boolean isInterface(ClassNode clazz) { return (clazz.access & Opcodes.ACC_INTERFACE) != 0; } // // method specific code // /** * Check if method is static. * * @param method method */ public static boolean isStatic(MethodNode method) { return (method.access & Opcodes.ACC_STATIC) != 0; } /** * Check if method is not static. * * @param method method */ public static boolean isNotStatic(MethodNode method) { return (method.access & Opcodes.ACC_STATIC) == 0; } /** * Is the method abstract?. * * @param method method */ public static boolean isAbstract(MethodNode method) { return (method.access & Opcodes.ACC_ABSTRACT) != 0; } /** * Check if the method is not void. * * @param method method */ public static boolean isNotVoid(MethodNode method) { return !Type.getReturnType(method.desc).equals(Type.VOID_TYPE); } /** * Check if the method is IRunnable.run() or an implementation of it. * * @param clazz owner of method * @param method method * @param classInfoCache class info cache */ public static boolean isRun(ClassNode clazz, MethodNode method, IClassInfoCache classInfoCache) { // TODO 2009-11-04 mh: remove special handling for clazz == null return (clazz == null || classInfoCache.hasSuperClass(clazz.name, IRUNNABLE_NAME)) && method.name.equals("run") && method.desc.equals("()V"); } /** * The first parameter of a method. * For static methods the first parameter is in local 0. * For non-static methods local 0 contains "this" and the first parameter is in local 1. * * @param method method */ public static int firstParam(MethodNode method) { return isNotStatic(method) ? 1 : 0; } /** * The first local of a method that is no parameter. * * @param method method */ public static int firstLocal(MethodNode method) { int local = firstParam(method); for (Type type : Type.getArgumentTypes(method.desc)) { local += type.getSize(); } return local; } /** * Create dummy return statement for capturing code. * Creates appropriate return statement for a method with a 0, null or void return value. * * @param method method node to create return statement for */ public static InsnList dummyReturnStatement(MethodNode method) { Type returnType = Type.getReturnType(method.desc); if (returnType.getSort() == Type.VOID) { InsnList instructions = new InsnList(); instructions.add(new InsnNode(Opcodes.RETURN)); return instructions; } return ValueCodeFactory.code(returnType).returnNull(); } /** * Check if frame is still compatible with the method arguments. * * @param method method * @param frame frame check */ public static boolean isCompatible(MethodNode method, Frame frame) { Type[] arguments = Type.getArgumentTypes(method.desc); // Condition "l < frame.getLocals()" holds always, because each argument is stored in a local for (int l = isNotStatic(method) ? 1 : 0, a = 0; a < arguments.length; a++) { BasicValue local = (BasicValue) frame.getLocal(l); if (BasicValue.UNINITIALIZED_VALUE.equals(local)) { throw new IllegalArgumentException("Locals have to be initialized at least with arguments"); } Type argument = arguments[a]; if (!ValueCodeFactory.code(local).isCompatibleWith(argument)) { return false; } l += argument.getSize(); } // scanned all arguments and they passed the test return true; } /** * Escapes descriptor to make it suitable for method names. * * @param desc Descriptor. */ public static String escapeForMethodName(String desc) { return desc.replaceAll("[()\\[/;]", "_"); } // // code related to the instructions of a method // /** * All return instructions. * * @param method method */ public static List<AbstractInsnNode> returnInstructions(MethodNode method) { List<AbstractInsnNode> result = new ArrayList<>(); for (AbstractInsnNode instruction : method.instructions.toArray()) { if (isReturn(instruction)) { result.add(instruction); } } return result; } /** * Is an instruction a return?. * * @param instruction Instruction */ public static boolean isReturn(AbstractInsnNode instruction) { return instruction != null && instruction.getOpcode() >= IRETURN && instruction.getOpcode() <= RETURN; } /** * Is an instruction a load?. * * @param instruction Instruction */ public static boolean isLoad(AbstractInsnNode instruction) { int opcode = instruction.getOpcode(); return opcode >= ILOAD && opcode <= ALOAD; } /** * Is an instruction a store?. * * @param instruction Instruction */ public static boolean isStore(AbstractInsnNode instruction) { int opcode = instruction.getOpcode(); return opcode >= ISTORE && opcode <= ASTORE; } /** * The previous instruction. Skips labels etc. * * @param instruction Instruction */ public static AbstractInsnNode previousInstruction(AbstractInsnNode instruction) { for (AbstractInsnNode result = instruction.getPrevious(); result != null; result = result.getPrevious()) { if (result.getOpcode() >= 0) { return result; } } return null; } /** * The next instruction. Skips labels etc. * * @param instruction Instruction */ public static AbstractInsnNode nextInstruction(AbstractInsnNode instruction) { for (AbstractInsnNode result = instruction.getNext(); result != null; result = result.getNext()) { if (result.getOpcode() >= 0) { return result; } } return null; } // // Log / debug code // /** * Generate identification string for a method. * * @param clazz owning class * @param method method */ public static String methodName(ClassNode clazz, MethodNode method) { return methodName(clazz.name, method.name, method.desc); } /** * Generate identification string for a method call. * * @param method method call */ public static String methodName(MethodInsnNode method) { return methodName(method.owner, method.name, method.desc); } /** * Generate identification string for a method. * * @param owner owning class * @param name method name * @param desc method descriptor */ public static String methodName(String owner, String name, String desc) { return owner + "#" + name + desc; } }
gpl-3.0
kenshinthebattosai/KennyClassIQ
src/com/kenny/classiq/junit/FENTest.java
1683
/* * This file is part of "Kenny ClassIQ", (c) Kenshin Himura, 2013. * * "Kenny ClassIQ" 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. * * "Kenny ClassIQ" 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 "Kenny ClassIQ". If not, see <http://www.gnu.org/licenses/>. * */ package com.kenny.classiq.junit; import static org.junit.Assert.*; import org.junit.Test; import com.kenny.classiq.definitions.Definitions; import com.kenny.classiq.game.Game; public class FENTest { @Test public void test() { Game chessGame=new Game(Definitions.startPositionFEN); chessGame.showBoard(); System.out.println(); String newFen="rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/" +"PPPP1PPP/RNBQKB1R b KQkq - 1 2"; Game chessGame2=new Game(newFen); chessGame2.showBoard(); System.out.println(); newFen="rnbqkbnr/pp1ppppp/8/8/8/8/PPP2PPP/RNBQKBNR w KQkq c6 0 2"; Game chessGame3=new Game(newFen); chessGame3.showBoard(); chessGame=new Game(Definitions.startPositionFEN); chessGame.setFen(newFen); chessGame.showBoard(); assertEquals("Great!","c6",chessGame3.getEnPassantSquare().getName()); assertEquals("Nice!",0,chessGame3.getHalfMoveClock(),0); assertEquals("Wow!",2,chessGame3.getMoveNumber(),0); } }
gpl-3.0
alexnlederman/scoutingapp
vanguard2/src/main/java/com/example/vanguard/pages/activities/SettingsActivity.java
10203
package com.example.vanguard.pages.activities; import android.app.Activity; import android.app.DialogFragment; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Environment; import android.os.Parcel; import android.util.Log; import android.view.View; import android.widget.Toast; import com.example.vanguard.bluetooth.AcceptThread; import com.example.vanguard.bluetooth.BluetoothManager; import com.example.vanguard.bluetooth.ConnectThread; import com.example.vanguard.bluetooth.server.ServerBroadcastReceiver; import com.example.vanguard.custom_ui_elements.SettingsView; import com.example.vanguard.pages.fragments.dialog_fragments.AddEventDialogFragment; import com.example.vanguard.pages.fragments.dialog_fragments.ConfirmationDialogFragment; import com.example.vanguard.pages.fragments.dialog_fragments.SetTeamNumberDialogFragment; import com.example.vanguard.questions.AnswerList; import com.example.vanguard.questions.Question; import com.example.vanguard.R; import com.example.vanguard.questions.question_types.CubeDeliveryQuestion; import com.example.vanguard.responses.Response; import java.io.File; import java.io.FileOutputStream; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import static android.os.Environment.DIRECTORY_DOWNLOADS; public class SettingsActivity extends AbstractActivity { Activity that; private final int DISCOVERABLE_DURATION = 60; BluetoothAdapter bluetoothAdapter; ServerBroadcastReceiver receiver; public SettingsActivity() { super(R.layout.activity_settings, R.string.setting_page_title); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); that = this; SettingsView addEvent = (SettingsView) findViewById(R.id.add_event); addEvent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogFragment fragment = AddEventDialogFragment.newInstance(new AddEventDialogFragment.DialogOpener() { @Override public void openDialog(DialogFragment dialog) { dialog.show(getFragmentManager(), "Fragment"); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { } }); fragment.show(getFragmentManager(), "Event Adder"); } }); SettingsView scoutSettings = (SettingsView) findViewById(R.id.scout_settings); scoutSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(that, ScoutSettingsActivity.class); startActivity(intent); } }); SettingsView deleteResponsesSettings = (SettingsView) findViewById(R.id.delete_responses); deleteResponsesSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogFragment fragment = ConfirmationDialogFragment.newInstance(R.string.confirm_delete_responses_dialog_title, R.string.confirm_delete_responses_dialog_text, new ConfirmationDialogFragment.ConfirmDialogListener() { @Override public void confirm() { AnswerList<Question> questions = MainActivity.databaseManager.getPitQuestions(); questions.addAll(MainActivity.databaseManager.getMatchQuestions()); for (Question question : questions) { question.resetResponses(); } MainActivity.databaseManager.saveResponses(questions); Toast.makeText(that, "Responses Successfully Deleted", Toast.LENGTH_LONG).show(); } }); fragment.show(getFragmentManager(), "Question Responses Delete"); } }); SettingsView setTeamNumber = (SettingsView) findViewById(R.id.set_team_number); setTeamNumber.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SetTeamNumberDialogFragment teamNumberDialogFragment = SetTeamNumberDialogFragment.newInstance(null); teamNumberDialogFragment.show(getFragmentManager(), "Set Team Number"); } }); SettingsView saveMatchDataSetting = (SettingsView) findViewById(R.id.export_match_responses); saveMatchDataSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { exportMatchResponses(); } }); SettingsView savePitDataSetting = (SettingsView) findViewById(R.id.export_pit_responses); savePitDataSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { exportPitResponses(); } }); SettingsView setupBluetoothSetting = (SettingsView) findViewById(R.id.setup_bluetooth); bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); IntentFilter bluetoothDeviceFilter = new IntentFilter(); bluetoothDeviceFilter.addAction(BluetoothDevice.ACTION_FOUND); bluetoothDeviceFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); bluetoothDeviceFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); receiver = new ServerBroadcastReceiver(bluetoothAdapter, this); this.registerReceiver(receiver, bluetoothDeviceFilter); setupBluetoothSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (bluetoothAdapter == null) { Toast.makeText(that, "Bluetooth Not Supported On Device", Toast.LENGTH_LONG).show(); } else { if (bluetoothAdapter.isEnabled()) { setupPairing(); } else { Toast.makeText(that, "Bluetooth Not Enabled", Toast.LENGTH_LONG).show(); } } } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == DISCOVERABLE_DURATION && resultCode == DISCOVERABLE_DURATION) { BluetoothManager.setBluetoothDeviceName(this, this.bluetoothAdapter); } } private void setupPairing() { if (!BluetoothManager.isServer(this)) { this.receiver.reset(); this.bluetoothAdapter.startDiscovery(); } else { Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION); startActivityForResult(discoverableIntent, DISCOVERABLE_DURATION); AcceptThread acceptThread = new AcceptThread(this, bluetoothAdapter); acceptThread.start(); } } private void exportMatchResponses() { String fileName = "match_responses.csv"; String csv = generateMatchResponsesCSV(); saveCSV(fileName, csv); } private void exportPitResponses() { String fileName = "pit_responses.csv"; String csv = generatePitResponsesCSV(); saveCSV(fileName, csv); } private void saveCSV(String fileName, String csv) { File file = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS), fileName); try { FileOutputStream outputStream = new FileOutputStream(file); outputStream.write(csv.getBytes()); outputStream.close(); Toast.makeText(this, "CSV in downloads folder on phone", Toast.LENGTH_LONG).show(); } catch (java.io.IOException e) { e.printStackTrace(); Toast.makeText(this, "Failed to save CSV", Toast.LENGTH_LONG).show(); } } private String generateMatchResponsesCSV() { AnswerList<Question> matchQuestions = MainActivity.databaseManager.getMatchQuestions(); String csv = "Event,Match Type"; for (Question question : matchQuestions) { if (question instanceof CubeDeliveryQuestion) { if (question.getResponses().size() > 0) { Set<String> keys = ((Map<String, Number>)((CubeDeliveryQuestion) question).getResponses().get(0).getValue()).keySet(); for (String key : keys) { csv += "," + key; } } else { csv += "," + question.getLabel(); } } else { csv += "," + question.getLabel(); } } List<Integer> eventTeams = MainActivity.databaseManager.getCurrentEventTeams(); for (Integer team : eventTeams) { HashMap<Integer, String> matchToCSV = new HashMap<>(); for (Question question : matchQuestions) { AnswerList<Response<?>> responses = question.getResponses().getTeamAnswers(team); for (Response<?> response : responses) { String currentCSV = matchToCSV.get(response.getMatchNumber()); String responseCSVValue = ""; if (question instanceof CubeDeliveryQuestion) { Collection<Number> values = ((Map<String, Number>) response.getValue()).values(); Log.d("Values", String.valueOf(values)); for (Object value : values) { responseCSVValue += "," + value; } Log.d("Values", responseCSVValue); } else { responseCSVValue = "," + response.getValue(); } if (currentCSV != null) { matchToCSV.put(response.getMatchNumber(), currentCSV + responseCSVValue); } else { if (response.isPracticeMatchResponse()) { matchToCSV.put(response.getMatchNumber(), response.getEventKey() + "," + "Playoff Match" + responseCSVValue); } else { matchToCSV.put(response.getMatchNumber(), response.getEventKey() + "," + "Qual Match" + responseCSVValue); } } } } for (String matchCSV : matchToCSV.values()) { csv += "\n" + matchCSV; } } Log.d("CSV", csv); return csv; } private String generatePitResponsesCSV() { AnswerList<Question> matchQuestions = MainActivity.databaseManager.getPitQuestions(); String csv = ""; for (Question question : matchQuestions) { csv += "," + question.getLabel(); } csv = csv.substring(1) + "\n"; List<Integer> eventTeams = MainActivity.databaseManager.getCurrentEventTeams(); for (Integer team : eventTeams) { for (Question question : matchQuestions) { AnswerList<Response> teamResponse = question.getResponses().getTeamAnswers(team); if (teamResponse.size() == 0) { csv += ","; } else { csv += teamResponse.get(0).getValue() + ","; } } csv = csv.substring(0, csv.length() - 1) + "\n"; } Log.d("Pit csv", csv); return csv; } @Override protected void onDestroy() { this.unregisterReceiver(receiver); super.onDestroy(); } }
gpl-3.0
eldersantos/community
kernel/src/main/java/org/neo4j/kernel/impl/cache/LruCache.java
6178
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j 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.neo4j.kernel.impl.cache; import java.util.LinkedHashMap; import java.util.Map; /** * Simple implementation of Least-recently-used cache. * * The cache has a <CODE>maxSize</CODE> set and when the number of cached * elements exceeds that limit the least recently used element will be removed. */ public class LruCache<K,E> implements Cache<K,E> { private final String name; int maxSize = 1000; private boolean resizing = false; private boolean adaptive = false; private final AdaptiveCacheManager cacheManager; private Map<K,E> cache = new LinkedHashMap<K,E>( 500, 0.75f, true ) { protected boolean removeEldestEntry( Map.Entry<K,E> eldest ) { // synchronization miss with old value on maxSize here is ok if ( super.size() > maxSize ) { if ( isAdaptive() && !isResizing() ) { adaptCache(); } else { super.remove( eldest.getKey() ); elementCleaned( eldest.getValue() ); } } return false; } }; void adaptCache() { if ( cacheManager != null ) { cacheManager.adaptCache( this ); } } // public void setMaxSize( int maxSize ) // { // this.maxSize = maxSize; // } /** * Creates a LRU cache. If <CODE>maxSize < 1</CODE> an * IllegalArgumentException is thrown. * * @param name * name of cache * @param maxSize * maximum size of this cache * @param cacheManager * adaptive cache manager or null if adaptive caching not needed */ public LruCache( String name, int maxSize, AdaptiveCacheManager cacheManager ) { this.cacheManager = cacheManager; if ( name == null || maxSize < 1 ) { throw new IllegalArgumentException( "maxSize=" + maxSize + ", name=" + name ); } this.name = name; this.maxSize = maxSize; } public String getName() { return this.name; } public synchronized void put( K key, E element ) { if ( key == null || element == null ) { throw new IllegalArgumentException( "key=" + key + ", element=" + element ); } cache.put( key, element ); } public synchronized E remove( K key ) { if ( key == null ) { throw new IllegalArgumentException( "Null parameter" ); } return cache.remove( key ); } public synchronized E get( K key ) { if ( key == null ) { throw new IllegalArgumentException(); } return cache.get( key ); } public synchronized void clear() { resizeInternal( 0 ); } public synchronized int size() { return cache.size(); } /** * Returns the maximum size of this cache. * * @return maximum size */ public int maxSize() { return maxSize; } /** * Changes the max size of the cache. If <CODE>newMaxSize</CODE> is * greater then <CODE>maxSize()</CODE> next invoke to <CODE>maxSize()</CODE> * will return <CODE>newMaxSize</CODE> and the entries in cache will not * be modified. * <p> * If <CODE>newMaxSize</CODE> is less then <CODE>size()</CODE> * the cache will shrink itself removing least recently used element until * <CODE>size()</CODE> equals <CODE>newMaxSize</CODE>. For each element * removed the {@link #elementCleaned} method is invoked. * <p> * If <CODE>newMaxSize</CODE> is less then <CODE>1</CODE> an * {@link IllegalArgumentException} is thrown. * * @param newMaxSize * the new maximum size of the cache */ public synchronized void resize( int newMaxSize ) { if ( newMaxSize < 1 ) { throw new IllegalArgumentException( "newMaxSize=" + newMaxSize ); } resizeInternal( newMaxSize ); } private void resizeInternal( int newMaxSize ) { resizing = true; try { if ( newMaxSize >= size() ) { maxSize = newMaxSize; } else if ( newMaxSize == 0 ) { cache.clear(); } else { maxSize = newMaxSize; java.util.Iterator<Map.Entry<K,E>> itr = cache.entrySet() .iterator(); while ( itr.hasNext() && cache.size() > maxSize ) { E element = itr.next().getValue(); itr.remove(); elementCleaned( element ); } } } finally { resizing = false; } } boolean isResizing() { return resizing; } public void elementCleaned( E element ) { } public boolean isAdaptive() { return adaptive; } public void setAdaptiveStatus( boolean status ) { this.adaptive = status; } public void putAll( Map<K, E> map ) { cache.putAll( map ); } }
gpl-3.0
julianwi/awtonandroid
android/src/julianwi/awtpeer/WindowActivity.java
2394
package julianwi.awtpeer; import java.io.DataOutputStream; import java.io.FileDescriptor; import java.io.IOException; import android.app.Activity; import android.content.res.Configuration; import android.net.LocalServerSocket; import android.net.LocalSocket; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.Window; import android.view.SurfaceView; public class WindowActivity extends Activity { public DataOutputStream pipeout; public LocalSocket socket = new LocalSocket(); public static LocalServerSocket server; static{ System.loadLibrary("awtpeer"); } private native FileDescriptor createsock(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { if(server == null){ server = new LocalServerSocket(createsock()); } } catch (IOException e) { e.printStackTrace(); } try { pipeout = new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } try { Window.class.getMethod("takeSurface", Class.forName("android.view.SurfaceHolder$Callback2")).invoke(getWindow(), Class.forName("julianwi.awtpeer.ListenerNewApi").getConstructor(WindowActivity.class).newInstance(this)); System.out.println("succes!"); } catch (Exception e) { System.out.println("error"); e.printStackTrace(); //view = new GraphicsView(this); SurfaceView view = new SurfaceView(this); view.getHolder().addCallback(new ListenerOldApi(this)); setContentView(view); } } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if(-1<ev.getAction()&&ev.getAction()<3){ try { synchronized (pipeout) { pipeout.write(0x02+ev.getAction()); pipeout.writeInt((int) ev.getX()); pipeout.writeInt((int) ev.getY()); } return true; } catch (IOException e) { e.printStackTrace(); } } return false; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); try { DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); synchronized (pipeout) { pipeout.write(0x01); pipeout.writeInt(metrics.widthPixels); pipeout.writeInt(metrics.heightPixels); } } catch (IOException e) { e.printStackTrace(); } } }
gpl-3.0
Evgorion/FinanceHelper
core/src/main/java/com/dagaz/yvgeny/financehelper/core/abstracts/AbstractTreeNode.java
2294
package com.dagaz.yvgeny.financehelper.core.abstracts; import com.dagaz.yvgeny.financehelper.core.interfaces.TreeNode; import java.util.ArrayList; import java.util.List; /** * Created by yvgeny on 31/05/16. */ public abstract class AbstractTreeNode implements TreeNode{ private long id; private List<TreeNode> childs = new ArrayList<>(); private TreeNode parent; private String name; public AbstractTreeNode() { } public AbstractTreeNode(String name) { this.name = name; } public AbstractTreeNode(List<TreeNode> childs) { this.childs = childs; } public AbstractTreeNode(String name, long id) { this.name = name; this.id = id; } public AbstractTreeNode(long id, List<TreeNode> childs, TreeNode parent, String name) { this.id = id; this.childs = childs; this.parent = parent; this.name = name; } @Override public void add(TreeNode child) { child.setParent(this); childs.add(child); } @Override public void setParent(TreeNode parent) { this.parent = parent; } @Override public TreeNode getParent() { return parent; } @Override public void remove(TreeNode child) { childs.remove(child); } @Override public List<TreeNode> getChilds() { return childs; } @Override public long getId() { return 0; } public void setId(long id) { this.id = id; } @Override public TreeNode getChild(long id) { for (TreeNode child: childs) { if (child.getId() == id){ return child; } } return null; } @Override public String toString() { return name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AbstractTreeNode that = (AbstractTreeNode) o; return id == that.id; } @Override public int hashCode() { return (int) (id ^ (id >>> 32)); } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } }
gpl-3.0
0be1/odm
src/main/java/fr/mtlx/odm/model/OrganizationalPerson.java
2675
package fr.mtlx.odm.model; /* * #%L * fr.mtlx.odm * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2012 - 2013 Alexandre Mathieu <me@mtlx.fr> * %% * 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% */ import fr.mtlx.odm.Attribute; import fr.mtlx.odm.Entry; @Entry(objectClasses = { "organizationalPerson" }) public class OrganizationalPerson extends Person { private static final long serialVersionUID = 497283357577415187L; @Attribute private String facsimileTelephoneNumber; @Attribute(aliases = { "l" }) private String localityName; @Attribute private String personalTitle; @Attribute private String postalAddress; @Attribute private String postalCode; @Attribute private String postOfficeBox; @Attribute(aliases = "streetAddress") private String street; @Attribute private String title; public String getFacsimileTelephoneNumber() { return facsimileTelephoneNumber; } public void setFacsimileTelephoneNumber(String facsimileTelephoneNumber) { this.facsimileTelephoneNumber = facsimileTelephoneNumber; } public String getLocalityName() { return localityName; } public void setLocalityName(String localityName) { this.localityName = localityName; } public String getPersonalTitle() { return personalTitle; } public void setPersonalTitle(String personalTitle) { this.personalTitle = personalTitle; } public String getPostalAddress() { return postalAddress; } public void setPostalAddress(String postalAddress) { this.postalAddress = postalAddress; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getPostOfficeBox() { return postOfficeBox; } public void setPostOfficeBox(String postOfficeBox) { this.postOfficeBox = postOfficeBox; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
gpl-3.0
TrentHouliston/JsonFL
src/main/java/au/com/houliston/jsonfl/NotJsonMatcher.java
1842
/** * This file is part of JsonFL. * * JsonFL is free software: you can redistribute it and/or modify it under the * terms of the Lesser GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * JsonFL is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the Lesser GNU General Public License for more * details. * * You should have received a copy of the Lesser GNU General Public License * along with JsonFL. If not, see <http://www.gnu.org/licenses/>. */ package au.com.houliston.jsonfl; import java.util.Map; /** * This matcher implements a not group, it will match if and only if none of the * objects within it match. The contents of the not are an implicit and * * Example: {'!not':{'foo':'bar'}} * * Matches: {'key':'value'} * * @author Trent Houliston * @version 1.0 */ class NotJsonMatcher extends GroupJsonMatcher { /** * This is the implicit inner and */ private final AndJsonMatcher inner; /** * This creates a not Json matcher, It contains an implicit and of the * object matched to its key * * @param json The root definition for this not * * @throws InvalidJsonQueryException If this or any of the SubObjects are * invalid JsonFL */ public NotJsonMatcher(Map<String, Object> json) throws InvalidJsonFLException { inner = new AndJsonMatcher(json); } /** * Checks if the inner and does not match * * @param json The definition for this not * * @return True if the inner and did not match false otherwise */ @Override public boolean match(Map<String, Object> json) { return !inner.match(json); } }
gpl-3.0
desaiankitb/MTech
DAA/LAB8/MCM.java
1203
class MCM { static int P[] = {3,3,3,3,3,3}; static int s[][] = new int[P.length][P.length]; public static void main(String args[]) { int n = P.length-1;//6-1=5 int j = 0; int m[][] = new int[P.length][P.length]; int i=0,k=0,l=0,t=0,ans=0; for(i=0;i<n;i++) { m[i][i] = 0; } for(l=1;l<=n-1;l++) { //System.out.println("l="+l+" "); for(i=0;i<=(n-(l+2)+1);i++) { //System.out.print("i="+i+" "); j=(l+1)+i-1; m[i][j] = 999999; //System.out.print("j="+j+" "); for(k=i;k<=j-1;k++) { t = m[i][k] + m[k+1][j] + (P[i]*P[k+1]*P[j+1]); //System.out.print((P[i]*P[k+1]*P[j+1])); //System.out.print("m["+i+"]"+"["+k+"]="+m[i][k]+"+"); //System.out.print("m["+(k+1)+"]"+"["+j+"]="+m[k+1][j]); //System.out.print("\t"+"m["+i+"]"+"["+j+"]="+t+"\t"); //System.out.print("k="+k+" "); ans = t; if(t < m[i][j]) { m[i][j] = t; s[i][j] = k; } } //System.out.println(); } //System.out.println(); } System.out.println(" "+m[0][4]); for(i=1;i<P.length;i++) { for(j=1;j<P.length;j++) { if(i<=j) System.out.print(" "+s[i][j]); } System.out.println(); } } }
gpl-3.0
NewCell/Call-Text-v1
src/com/newcell/calltext/ui/filters/EditFilter.java
8956
/** * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr) * This file is part of CSipSimple. * * CSipSimple 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. * If you own a pjsip commercial license you can also redistribute it * and/or modify it under the terms of the GNU Lesser General Public License * as an android library. * * CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>. */ package com.newcell.calltext.ui.filters; import android.app.Activity; import android.content.ContentUris; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import com.newcell.calltext.R; import com.newcell.calltext.api.SipManager; import com.newcell.calltext.api.SipProfile; import com.newcell.calltext.models.Filter; import com.newcell.calltext.models.Filter.RegExpRepresentation; import com.newcell.calltext.utils.Log; public class EditFilter extends Activity implements OnItemSelectedListener, TextWatcher { private static final String THIS_FILE = "EditFilter"; private Long filterId; private Filter filter; private Button saveButton; private long accountId; private EditText replaceTextEditor; private Spinner actionSpinner; private EditText matchesTextEditor; // private View matchesContainer; private View replaceContainer; private Spinner replaceSpinner; private Spinner matcherSpinner; private boolean initMatcherSpinner; private boolean initReplaceSpinner; @Override protected void onCreate(Bundle savedInstanceState) { //Get back the concerned account and if any set the current (if not a new account is created) Intent intent = getIntent(); filterId = intent.getLongExtra(Intent.EXTRA_UID, -1); accountId = intent.getLongExtra(Filter.FIELD_ACCOUNT, SipProfile.INVALID_ID); if(accountId == SipProfile.INVALID_ID) { Log.e(THIS_FILE, "Invalid account"); finish(); } filter = Filter.getFilterFromDbId(this, filterId, Filter.FULL_PROJ); super.onCreate(savedInstanceState); setContentView(R.layout.edit_filter); // Bind view objects actionSpinner = (Spinner) findViewById(R.id.filter_action); matcherSpinner = (Spinner) findViewById(R.id.matcher_type); replaceSpinner = (Spinner) findViewById(R.id.replace_type); replaceTextEditor = (EditText) findViewById(R.id.filter_replace); matchesTextEditor = (EditText) findViewById(R.id.filter_matches); //Bind containers objects // matchesContainer = (View) findViewById(R.id.matcher_block); replaceContainer = (View) findViewById(R.id.replace_block); actionSpinner.setOnItemSelectedListener(this); matcherSpinner.setOnItemSelectedListener(this); initMatcherSpinner = false; replaceSpinner.setOnItemSelectedListener(this); initReplaceSpinner = false; matchesTextEditor.addTextChangedListener(this); replaceTextEditor.addTextChangedListener(this); // Bind buttons to their actions Button bt = (Button) findViewById(R.id.cancel_bt); bt.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { //TODO : clean prefs setResult(RESULT_CANCELED, getIntent()); finish(); } }); saveButton = (Button) findViewById(R.id.save_bt); saveButton.setEnabled(false); saveButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { saveFilter(); setResult(RESULT_OK, getIntent()); finish(); } }); fillLayout(); checkFormValidity(); } private void saveFilter() { //Update filter object filter.account = (int) accountId; filter.action = Filter.getActionForPosition(actionSpinner.getSelectedItemPosition()); RegExpRepresentation repr = new RegExpRepresentation(); //Matcher repr.type = Filter.getMatcherForPosition(matcherSpinner.getSelectedItemPosition()); repr.fieldContent = matchesTextEditor.getText().toString(); filter.setMatcherRepresentation(repr); //Rewriter if(filter.action == Filter.ACTION_REPLACE) { repr.fieldContent = replaceTextEditor.getText().toString(); repr.type = Filter.getReplaceForPosition(replaceSpinner.getSelectedItemPosition()); filter.setReplaceRepresentation(repr); }else if(filter.action == Filter.ACTION_AUTO_ANSWER){ filter.replacePattern = replaceTextEditor.getText().toString(); }else{ filter.replacePattern = ""; } //Save if(filterId < 0) { Cursor currentCursor = getContentResolver().query(SipManager.FILTER_URI, new String[] {Filter._ID}, Filter.FIELD_ACCOUNT + "=?", new String[] { filter.account.toString() }, null); filter.priority = 0; if(currentCursor != null) { filter.priority = currentCursor.getCount(); currentCursor.close(); } getContentResolver().insert(SipManager.FILTER_URI, filter.getDbContentValues()); }else { getContentResolver().update(ContentUris.withAppendedId(SipManager.FILTER_ID_URI_BASE, filterId), filter.getDbContentValues(), null, null); } } private void fillLayout() { //Set action actionSpinner.setSelection(Filter.getPositionForAction(filter.action)); RegExpRepresentation repr = filter.getRepresentationForMatcher(); //Set matcher - selection must be done first since raise on item change listener matcherSpinner.setSelection(Filter.getPositionForMatcher(repr.type)); matchesTextEditor.setText(repr.fieldContent); //Set replace repr = filter.getRepresentationForReplace(); replaceSpinner.setSelection(Filter.getPositionForReplace(repr.type)); replaceTextEditor.setText(repr.fieldContent); } private void checkFormValidity() { boolean isValid = true; int action = Filter.getActionForPosition(actionSpinner.getSelectedItemPosition()); if(TextUtils.isEmpty(matchesTextEditor.getText().toString()) && matcherNeedsText() ){ isValid = false; } if(action == Filter.ACTION_AUTO_ANSWER) { if(!TextUtils.isEmpty(replaceTextEditor.getText().toString())) { try{ Integer.parseInt(replaceTextEditor.getText().toString()); }catch(NumberFormatException e) { isValid = false; } } } saveButton.setEnabled(isValid); } @Override public void onItemSelected(AdapterView<?> spinner, View arg1, int arg2, long arg3) { int spinnerId = spinner.getId(); if (spinnerId == R.id.filter_action) { int action = Filter.getActionForPosition(actionSpinner.getSelectedItemPosition()) ; if(action == Filter.ACTION_REPLACE || action == Filter.ACTION_AUTO_ANSWER) { replaceContainer.setVisibility(View.VISIBLE); if(action == Filter.ACTION_REPLACE) { replaceSpinner.setVisibility(View.VISIBLE); replaceTextEditor.setHint(""); }else { replaceSpinner.setVisibility(View.GONE); replaceTextEditor.setHint(R.string.optional_sip_code); } }else { replaceContainer.setVisibility(View.GONE); } } else if (spinnerId == R.id.matcher_type) { if(initMatcherSpinner) { matchesTextEditor.setText(""); }else { initMatcherSpinner = true; } } else if (spinnerId == R.id.replace_type) { if(initReplaceSpinner) { replaceTextEditor.setText(""); }else { initReplaceSpinner = true; } } matchesTextEditor.setVisibility(matcherNeedsText() ? View.VISIBLE : View.GONE); checkFormValidity(); } private boolean matcherNeedsText() { int fmatcher = Filter.getMatcherForPosition(matcherSpinner.getSelectedItemPosition() ); return fmatcher != Filter.MATCHER_ALL && fmatcher != Filter.MATCHER_BLUETOOTH && fmatcher != Filter.MATCHER_CALLINFO_AUTOREPLY; } @Override public void onNothingSelected(AdapterView<?> arg0) { checkFormValidity(); } @Override public void afterTextChanged(Editable s) { // Nothing to do } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Nothing to do } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { checkFormValidity(); } }
gpl-3.0
jonpchin/Go-Bible
GoBible/app/src/main/java/com/goplaychess/gobible/ReadBook.java
6033
package com.goplaychess.gobible; import android.app.Activity; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.view.GestureDetectorCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.InputType; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.EditText; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * Created by jonc on 5/22/2016. */ public class ReadBook extends AppCompatActivity implements View.OnTouchListener { //keeps track of what chapter is being read int chapter = 1; int totalChapters; TextView textView; String bookTitle = ""; // or other values String bibleVersion = "ASV"; private GestureDetectorCompat gestureDetector; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.read_book); Activity activity = (Activity)ReadBook.this; textView = (TextView)activity.findViewById(R.id.book_text_read); Bundle b = getIntent().getExtras(); if(b != null){ bookTitle = b.getString("key"); totalChapters = b.getInt("total"); bibleVersion = b.getString("version"); } getSupportActionBar().setTitle(bookTitle + " " + 1); //load the initial chapter of the book loadNextChapter(1); OnSwipeListener onSwipeListener = new OnSwipeListener() { @Override public boolean onSwipe(Direction direction) { // Possible implementation if (direction == Direction.left && chapter < totalChapters) { chapter++; loadNextChapter(chapter); return true; } else if (direction == Direction.right && chapter > 1) { chapter--; loadNextChapter(chapter); return true; } return super.onSwipe(direction); } }; gestureDetector = new GestureDetectorCompat(getApplicationContext(), onSwipeListener); textView.setOnTouchListener(this); } @Override public boolean onTouch(View view, MotionEvent motionEvent) { return gestureDetector.onTouchEvent(motionEvent); } @Override public boolean dispatchTouchEvent(MotionEvent ev){ super.dispatchTouchEvent(ev); return gestureDetector.onTouchEvent(ev); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.book_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_left && chapter > 1) { chapter--; loadNextChapter(chapter); return true; }else if(id == R.id.action_right && chapter < totalChapters){ chapter++; loadNextChapter(chapter); return true; }else if(id == R.id.search_chapter){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Search Chapter"); // Set up the input final EditText input = new EditText(this); // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text input.setInputType(InputType.TYPE_CLASS_NUMBER); builder.setView(input); // Set up the buttons builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { int specifiedChapter = Integer.parseInt(input.getText().toString()); if(specifiedChapter > 0 && specifiedChapter <= totalChapters){ loadNextChapter(specifiedChapter); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } return super.onOptionsItemSelected(item); } //loads the specified chapter of the bible when user presses next or previous button public void loadNextChapter(int target){ //reading from file and displaying in the textview StringBuilder stringBuilder = new StringBuilder(); String bookText = bibleVersion + "/" + bookTitle + "/" + bookTitle + target + ".txt"; InputStream inputStream = null; try { inputStream = getApplicationContext().getAssets().open(bookText); } catch (IOException e) { e.printStackTrace(); } BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; try { while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line).append("\n"); } bufferedReader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } getSupportActionBar().setTitle(bookTitle + " " + target); textView.setText(stringBuilder.toString()); chapter = target; } }
gpl-3.0
puzis/kpp
src/topology/BasicVertexInfo.java
2313
package topology; import java.io.Serializable; public class BasicVertexInfo implements Serializable { private static final long serialVersionUID = 1L; protected int m_vertexNum = 0; protected String m_label = null; /** * Vertex's coordinates in the network. */ protected double m_x, m_y, m_z = 0; protected int m_multiplicity = 1; protected double m_latency = 0.0; public BasicVertexInfo() { } public void setVertexNum(int vertexNum) { m_vertexNum = vertexNum; } public int getVertexNum() { return m_vertexNum; } public int getMultiplicity() { return m_multiplicity; } public void setMultiplicity(int m) { m_multiplicity = m; } public double getLatency() { return m_latency; } public void setLatency(double l) { m_latency = l; } public void setLabel(String lable) { m_label = lable; } public String getLable() { return m_label; } public void setX(double x) { m_x = x; } public double getX() { return m_x; } public void setY(double y) { m_y = y; } public double getY() { return m_y; } public void setZ(double z) { m_z = z; } public double getz() { return m_z; } public BasicVertexInfo(int vertexNum, String label) { m_vertexNum = vertexNum; m_label = label; } public BasicVertexInfo(int vertexNum, String label, double x, double y, double z) { this(vertexNum, label); m_x = x; m_y = y; m_z = z; m_multiplicity = 1; m_latency = 0; } public BasicVertexInfo(int vertexNum, String label, double x, double y, double z, int multiplicity, double latency) { this(vertexNum, label, x, y, z); m_multiplicity = multiplicity; m_latency = latency; } public BasicVertexInfo(BasicVertexInfo other) { this(other.m_vertexNum, other.m_label, other.m_x, other.m_y, other.m_z, other.m_multiplicity, other.m_latency); } public BasicVertexInfo clone() { return new BasicVertexInfo(this); } }
gpl-3.0
senbox-org/snap-desktop
snap-worldwind/src/main/java/org/esa/snap/worldwind/ProductPanel.java
5052
/* * Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca * * 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.esa.snap.worldwind; import gov.nasa.worldwind.WorldWindow; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.worldwind.layers.DefaultProductLayer; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.CompoundBorder; import javax.swing.border.TitledBorder; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; class ProductPanel extends JPanel { private final DefaultProductLayer defaultProductLayer; private JPanel layersPanel; private JPanel westPanel; private JScrollPane scrollPane; private Font defaultFont = null; public ProductPanel(WorldWindow wwd, DefaultProductLayer prodLayer) { super(new BorderLayout()); defaultProductLayer = prodLayer; this.makePanel(wwd, new Dimension(100, 400)); } private void makePanel(WorldWindow wwd, Dimension size) { // Make and fill the panel holding the layer titles. this.layersPanel = new JPanel(new GridLayout(0, 1, 0, 4)); this.layersPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); this.fill(wwd); // Must put the layer grid in a container to prevent scroll panel from stretching their vertical spacing. final JPanel dummyPanel = new JPanel(new BorderLayout()); dummyPanel.add(this.layersPanel, BorderLayout.NORTH); // Put the name panel in a scroll bar. this.scrollPane = new JScrollPane(dummyPanel); this.scrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); if (size != null) this.scrollPane.setPreferredSize(size); // Add the scroll bar and name panel to a titled panel that will resize with the main window. westPanel = new JPanel(new GridLayout(0, 1, 0, 10)); westPanel.setBorder( new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Products"))); westPanel.setToolTipText("Products to Show"); westPanel.add(scrollPane); this.add(westPanel, BorderLayout.CENTER); } private void fill(WorldWindow wwd) { final String[] productNames = defaultProductLayer.getProductNames(); for (String name : productNames) { final LayerAction action = new LayerAction(defaultProductLayer, wwd, name, defaultProductLayer.getOpacity(name) != 0); final JCheckBox jcb = new JCheckBox(action); jcb.setSelected(action.selected); this.layersPanel.add(jcb); if (defaultFont == null) { this.defaultFont = jcb.getFont(); } } } public void update(WorldWindow wwd) { // Replace all the layer names in the layers panel with the names of the current layers. this.layersPanel.removeAll(); this.fill(wwd); this.westPanel.revalidate(); this.westPanel.repaint(); } @Override public void setToolTipText(String string) { this.scrollPane.setToolTipText(string); } private static class LayerAction extends AbstractAction { final WorldWindow wwd; private final DefaultProductLayer layer; private final boolean selected; private final String name; public LayerAction(DefaultProductLayer layer, WorldWindow wwd, String name, boolean selected) { super(name); this.wwd = wwd; this.layer = layer; this.name = name; this.selected = selected; this.layer.setEnabled(this.selected); } public void actionPerformed(ActionEvent actionEvent) { SystemUtils.LOG.fine("actionPerformed " + actionEvent); // Simply enable or disable the layer based on its toggle button. //System.out.println("Product click " + layer); //System.out.println(layer.getOpacity()); if (((JCheckBox) actionEvent.getSource()).isSelected()) { this.layer.setOpacity(name, this.layer.getOpacity()); } else { this.layer.setOpacity(name, 0); } wwd.redraw(); } } }
gpl-3.0
Lessnic/CAISS
src/main/java/util/package-info.java
912
/* * Computer and algorithm interaction simulation software (CAISS). * Copyright (C) 2016 Sergey Pomelov. * * 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/>. */ /** * Project wide utility class' package. * @author Sergey Pomelov on 02/05/2016. */ package util;
gpl-3.0
ekisa/lighthouse
src/main/java/tr/com/turktelecom/lighthouse/config/Constants.java
786
package tr.com.turktelecom.lighthouse.config; /** * Application constants. */ public final class Constants { // Spring profile for development, production and "fast", see http://jhipster.github.io/profiles.html public static final String SPRING_PROFILE_DEVELOPMENT = "dev"; public static final String SPRING_PROFILE_PRODUCTION = "prod"; public static final String SPRING_PROFILE_FAST = "fast"; // Spring profile used when deploying with Spring Cloud (used when deploying to CloudFoundry) public static final String SPRING_PROFILE_CLOUD = "cloud"; // Spring profile used when deploying to Heroku public static final String SPRING_PROFILE_HEROKU = "heroku"; public static final String SYSTEM_ACCOUNT = "system"; private Constants() { } }
gpl-3.0
senbox-org/snap-desktop
snap-rcp/src/main/java/org/esa/snap/rcp/session/dom/RasterDataNodeDomConverter.java
1653
/* * Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de) * * 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.esa.snap.rcp.session.dom; import com.bc.ceres.binding.dom.DomElement; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductManager; import org.esa.snap.core.datamodel.RasterDataNode; class RasterDataNodeDomConverter extends ProductNodeDomConverter<RasterDataNode> { RasterDataNodeDomConverter(ProductManager productManager) { super(RasterDataNode.class, productManager); } @Override protected RasterDataNode getProductNode(DomElement parentElement, Product product) { final DomElement rasterName = parentElement.getChild("rasterName"); return product.getRasterDataNode(rasterName.getValue()); } @Override protected void convertProductNodeToDom(RasterDataNode raster, DomElement parentElement) { final DomElement rasterName = parentElement.createChild("rasterName"); rasterName.setValue(raster.getName()); } }
gpl-3.0
BlueMoonParkour/PersonalEnergy
src/main/java/bluemoonparkour/personalenergy/PersonalEnergy.java
1545
package bluemoonparkour.personalenergy; import bluemoonparkour.personalenergy.init.ModBlocks; import bluemoonparkour.personalenergy.proxy.CommonProxy; import bluemoonparkour.personalenergy.reference.Reference; import bluemoonparkour.personalenergy.tabs.PETab; import net.minecraft.creativetab.CreativeTabs; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; @Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.VERSION, acceptedMinecraftVersions = Reference.ACCEPTED_VERISONS) public class PersonalEnergy { @Instance public static PersonalEnergy instance; @SidedProxy(clientSide = Reference.CLIENT_PROXY_CLASS, serverSide = Reference.SERVER_PROXY_CLASS) public static CommonProxy proxy; public static final CreativeTabs CREATIVE_TABS = new PETab(); @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { System.out.println("PRE INIT"); ModBlocks.init(); ModBlocks.register(); } @Mod.EventHandler public void init(FMLInitializationEvent event) { System.out.println("INIT"); } @Mod.EventHandler public void postInit(FMLPostInitializationEvent event) { System.out.println("POST INIT"); } }
gpl-3.0
jjm2473/DroidDLNA
app/src/main/java/org/fourthline/cling/model/types/DeviceType.java
5932
/* * Copyright (C) 2013 4th Line GmbH, Switzerland * * The contents of this file are subject to the terms of either the GNU * Lesser General Public License Version 2 or later ("LGPL") or the * Common Development and Distribution License Version 1 or later * ("CDDL") (collectively, the "License"). You may not use this file * except in compliance with the License. See LICENSE.txt for more * information. * * 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. */ package org.fourthline.cling.model.types; import org.fourthline.cling.model.Constants; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Represents a device type, for example <code>urn:my-domain-namespace:device:MyDevice:1</code>. * <p> * Although decimal versions are accepted and parsed, the version used for * comparison is only the integer without the fraction. * </p> * * @author Christian Bauer */ public class DeviceType { public static final String UNKNOWN = "UNKNOWN"; public static final Pattern PATTERN = Pattern.compile("urn:(" + Constants.REGEX_NAMESPACE + "):device:(" + Constants.REGEX_TYPE + "):([0-9]+).*"); final private static Logger log = Logger.getLogger(DeviceType.class.getName()); private String namespace; private String type; private int version = 1; public DeviceType(String namespace, String type) { this(namespace, type, 1); } public DeviceType(String namespace, String type, int version) { if (namespace != null && !namespace.matches(Constants.REGEX_NAMESPACE)) { throw new IllegalArgumentException("Device type namespace contains illegal characters"); } this.namespace = namespace; if (type != null && !type.matches(Constants.REGEX_TYPE)) { throw new IllegalArgumentException("Device type suffix too long (64) or contains illegal characters"); } this.type = type; this.version = version; } /** * @return Either a {@link UDADeviceType} or a more generic {@link DeviceType}. */ public static DeviceType valueOf(String s) throws InvalidValueException { DeviceType deviceType = null; // Sometimes crazy UPnP devices deliver spaces in a URN, don't ask... s = s.replaceAll("\\s", ""); // First try UDADeviceType parse try { deviceType = UDADeviceType.valueOf(s); } catch (Exception ex) { // Ignore } if (deviceType != null) return deviceType; try { // Now try a generic DeviceType parse Matcher matcher = PATTERN.matcher(s); if (matcher.matches()) { return new DeviceType(matcher.group(1), matcher.group(2), Integer.valueOf(matcher.group(3))); } // TODO: UPNP VIOLATION: Escient doesn't provide any device type token // urn:schemas-upnp-org:device::1 matcher = Pattern.compile("urn:(" + Constants.REGEX_NAMESPACE + "):device::([0-9]+).*").matcher(s); if (matcher.matches() && matcher.groupCount() >= 2) { log.warning("UPnP specification violation, no device type token, defaulting to " + UNKNOWN + ": " + s); return new DeviceType(matcher.group(1), UNKNOWN, Integer.valueOf(matcher.group(2))); } // TODO: UPNP VIOLATION: EyeTV Netstream uses colons in device type token // urn:schemas-microsoft-com:service:pbda:tuner:1 matcher = Pattern.compile("urn:(" + Constants.REGEX_NAMESPACE + "):device:(.+?):([0-9]+).*").matcher(s); if (matcher.matches() && matcher.groupCount() >= 3) { String cleanToken = matcher.group(2).replaceAll("[^a-zA-Z_0-9\\-]", "-"); log.warning( "UPnP specification violation, replacing invalid device type token '" + matcher.group(2) + "' with: " + cleanToken ); return new DeviceType(matcher.group(1), cleanToken, Integer.valueOf(matcher.group(3))); } } catch (RuntimeException e) { throw new InvalidValueException(String.format( "Can't parse device type string (namespace/type/version) '%s': %s", s, e.toString() )); } throw new InvalidValueException("Can't parse device type string (namespace/type/version): " + s); } public String getNamespace() { return namespace; } public String getType() { return type; } public int getVersion() { return version; } public boolean implementsVersion(DeviceType that) { if (!namespace.equals(that.namespace)) return false; if (!type.equals(that.type)) return false; if (version < that.version) return false; return true; } public String getDisplayString() { return getType(); } @Override public String toString() { return "urn:" + getNamespace() + ":device:" + getType() + ":" + getVersion(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof DeviceType)) return false; DeviceType that = (DeviceType) o; if (version != that.version) return false; if (!namespace.equals(that.namespace)) return false; if (!type.equals(that.type)) return false; return true; } @Override public int hashCode() { int result = namespace.hashCode(); result = 31 * result + type.hashCode(); result = 31 * result + version; return result; } }
gpl-3.0
mshams/appiconizer
src/net/coobird/thumbnailator/resizers/FixedResizerFactory.java
872
package net.coobird.thumbnailator.resizers; import java.awt.Dimension; /** * A {@link ResizerFactory} that returns a specific {@link Resizer} * unconditionally. * * @author coobird * @since 0.4.0 */ public class FixedResizerFactory implements ResizerFactory { /** * The resizer which is to be returned unconditionally by this class. */ private final Resizer resizer; /** * Creates an instance of the {@link FixedResizerFactory} which returns * the speicifed {@link Resizer} under all circumstances. * * @param resizer The {@link Resizer} instance that is to be returned * under all circumstances. */ public FixedResizerFactory(Resizer resizer) { this.resizer = resizer; } public Resizer getResizer() { return resizer; } public Resizer getResizer(Dimension originalSize, Dimension thumbnailSize) { return resizer; } }
mpl-2.0
kavi87/seed
shell/src/it/java/org/seedstack/seed/shell/internal/commands/ErroneousTestCommand.java
730
/** * Copyright (c) 2013-2015, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.seed.shell.internal.commands; import org.seedstack.seed.spi.command.CommandDefinition; import org.seedstack.seed.spi.command.Command; @CommandDefinition(scope = "test", name = "exception", description = "Erroneous test command") public class ErroneousTestCommand implements Command { @Override public Object execute(Object object) throws Exception { throw new RuntimeException("test exception"); } }
mpl-2.0
Devexperts/QD
qd-rmi/src/main/java/com/devexperts/rmi/task/RMIObservableServiceDescriptors.java
1243
/* * !++ * QDS - Quick Data Signalling Library * !- * Copyright (C) 2002 - 2021 Devexperts LLC * !- * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * !__ */ package com.devexperts.rmi.task; /** * Defines objects that can monitor the changes {@link RMIServiceDescriptor}. */ public interface RMIObservableServiceDescriptors { /** * Adds the specified {@link RMIServiceDescriptorsListener listener} to this object. * @param listener newly adding {@link RMIServiceDescriptorsListener}. */ void addServiceDescriptorsListener(RMIServiceDescriptorsListener listener); /** * Removes the specified {@link RMIServiceDescriptorsListener listener} from this object * @param listener removing {@link RMIServiceDescriptorsListener}. */ void removeServiceDescriptorsListener(RMIServiceDescriptorsListener listener); /** * Returns true if the implementation of service is available from current endpoint. * @return true if the implementation of service is available from current endpoint */ public boolean isAvailable(); }
mpl-2.0
zyxakarene/LearningOpenGl
MainGame/src/zyx/utils/geometry/IntRectangle.java
428
package zyx.utils.geometry; public class IntRectangle { public int x, y; public int width, height; public IntRectangle() { } public IntRectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } public void copyFrom(IntRectangle source) { this.x = source.x; this.y = source.y; this.width = source.width; this.height = source.height; } }
mpl-2.0
Tropicraft/Tropicraft
src/main/java/net/tropicraft/core/common/entity/placeable/UmbrellaEntity.java
704
package net.tropicraft.core.common.entity.placeable; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.ItemStack; import net.minecraft.world.phys.HitResult; import net.minecraft.world.level.Level; import net.tropicraft.core.common.item.TropicraftItems; public class UmbrellaEntity extends FurnitureEntity { public UmbrellaEntity(EntityType<?> entityTypeIn, Level worldIn) { super(entityTypeIn, worldIn, TropicraftItems.UMBRELLAS); } @Override public ItemStack getPickedResult(HitResult target) { return new ItemStack(TropicraftItems.UMBRELLAS.get(DyeColor.byId(getColor().getId())).get()); } }
mpl-2.0
cicomponents/cicomponents
cicomponents-badges-api/src/main/java/org/cicomponents/badges/BadgeSubject.java
420
/** * Copyright (c) 2016, All Contributors (see CONTRIBUTORS file) * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.cicomponents.badges; import lombok.Value; @Value public class BadgeSubject implements BadgeProperty { private String text; }
mpl-2.0
cFerg/MineJava
src/main/java/minejava/material/Attachable.java
152
package minejava.material; import minejava.block.BlockFace; public interface Attachable extends Directional{ public BlockFace getAttachedFace(); }
mpl-2.0
SebaRev1989/MyTwitterClient
app/src/main/java/com/reverso/seba/mytwitterclient/images/ImagesRepository.java
150
package com.reverso.seba.mytwitterclient.images; /** * Created by seba on 16/06/16. */ public interface ImagesRepository { void getImages(); }
mpl-2.0
mkodekar/Fennece-Browser
base/PrintHelper.java
5343
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko; import org.mozilla.gecko.AppConstants.Versions; import org.mozilla.gecko.GeckoAppShell; import org.mozilla.gecko.util.GeckoRequest; import org.mozilla.gecko.util.IOUtils; import org.mozilla.gecko.util.NativeJSObject; import org.mozilla.gecko.util.ThreadUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import android.content.Context; import android.os.Bundle; import android.os.CancellationSignal; import android.os.ParcelFileDescriptor; import android.print.PrintAttributes; import android.print.PrintDocumentAdapter; import android.print.PrintDocumentAdapter.LayoutResultCallback; import android.print.PrintDocumentAdapter.WriteResultCallback; import android.print.PrintDocumentInfo; import android.print.PrintManager; import android.print.PageRange; import android.util.Log; public class PrintHelper { private static final String LOGTAG = "GeckoPrintUtils"; public static void printPDF(final Context context) { GeckoAppShell.sendRequestToGecko(new GeckoRequest("Print:PDF", new JSONObject()) { @Override public void onResponse(NativeJSObject nativeJSObject) { final String filePath = nativeJSObject.getString("file"); final String title = nativeJSObject.getString("title"); finish(context, filePath, title); } @Override public void onError(NativeJSObject error) { // Gecko didn't respond due to state change, javascript error, etc. Log.d(LOGTAG, "No response from Gecko on request to generate a PDF"); } private void finish(final Context context, final String filePath, final String title) { PrintManager printManager = (PrintManager) context.getSystemService(Context.PRINT_SERVICE); String jobName = title; // The adapter methods are all called on the UI thread by the PrintManager. Put the heavyweight code // in onWrite on the background thread. PrintDocumentAdapter pda = new PrintDocumentAdapter() { @Override public void onWrite(final PageRange[] pages, final ParcelFileDescriptor destination, final CancellationSignal cancellationSignal, final WriteResultCallback callback) { ThreadUtils.postToBackgroundThread(new Runnable() { @Override public void run() { InputStream input = null; OutputStream output = null; try { File pdfFile = new File(filePath); input = new FileInputStream(pdfFile); output = new FileOutputStream(destination.getFileDescriptor()); byte[] buf = new byte[8192]; int bytesRead; while ((bytesRead = input.read(buf)) > 0) { output.write(buf, 0, bytesRead); } callback.onWriteFinished(new PageRange[] { PageRange.ALL_PAGES }); // File is not really deleted until the input stream closes it pdfFile.delete(); } catch (FileNotFoundException ee) { Log.d(LOGTAG, "Unable to find the temporary PDF file."); } catch (IOException ioe) { Log.e(LOGTAG, "IOException while transferring temporary PDF file: ", ioe); } finally { IOUtils.safeStreamClose(input); IOUtils.safeStreamClose(output); } } }); } @Override public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){ if (cancellationSignal.isCanceled()) { callback.onLayoutCancelled(); return; } PrintDocumentInfo pdi = new PrintDocumentInfo.Builder(filePath).setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build(); callback.onLayoutFinished(pdi, true); } }; printManager.print(jobName, pda, null); } }); } }
mpl-2.0
zhougithui/bookstore-single
src/test/java/org/bear/bookstore/test/xml/simple/MySpringBean.java
871
package org.bear.bookstore.test.xml.simple; import java.util.Properties; import lombok.Getter; import lombok.Setter; public class MySpringBean { @Setter @Getter private String msg; @Setter @Getter private int i; @Setter @Getter private Properties pro; @Setter @Getter private MySpringBean2 myBean; public MySpringBean(){} public MySpringBean(String msg, int i) { super(); this.msg = msg; this.i = i; } public MySpringBean(String msg, int i, MySpringBean2 myBean) { super(); this.msg = msg; this.i = i; this.myBean = myBean; } public void hello() { System.out.println("hello world!"); } public void hello2() { myBean.hello(); } private void init(){ System.out.println("init " + msg); } private void destroy(){ System.out.println("destroy " + msg); } }
mpl-2.0
digidotcom/XBeeJavaLibrary
library/src/test/java/com/digi/xbee/api/models/FrameErrorTest.java
2372
/** * Copyright 2017, Digi International Inc. * * 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/. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.digi.xbee.api.models; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class FrameErrorTest { // Variables. private FrameError[] errors; @Before public void setup() { // Retrieve the list of enum. values. errors = FrameError.values(); } /** * Test method for {@link com.digi.xbee.api.models.FrameError#getID()}. * * <p>Verify that the ID of each {@code FrameError} entry is valid.</p> */ @Test public void testFrameErrorEnumValues() { for (FrameError error:errors) assertTrue(error.getID() >= 0); } /** * Test method for {@link com.digi.xbee.api.models.FrameError#getName()}. * * <p>Verify that the name of each {@code FrameError} entry is valid. * </p> */ @Test public void testFrameErrorEnumNames() { for (FrameError error:errors) { assertNotNull(error.getName()); assertTrue(error.name().length() > 0); } } /** * Test method for {@link com.digi.xbee.api.models.FrameError#get(int)}. * * <p>Verify that each {@code FrameError} entry can be retrieved * statically using its value.</p> */ @Test public void testFrameErrorStaticAccess() { for (FrameError error:errors) assertEquals(error, FrameError.get(error.getID())); } /** * Test method for {@link com.digi.xbee.api.models.FrameError#toString()}. * * <p>Verify that the {@code toString()} method of a {@code FrameError} * entry returns its description correctly.</p> */ @Test public void testFrameErrorToString() { for (FrameError error:errors) assertEquals(error.getName(), error.toString()); } }
mpl-2.0
digidotcom/XBeeJavaLibrary
library/src/main/java/com/digi/xbee/api/exceptions/InvalidPacketException.java
1889
/** * Copyright 2017, Digi International Inc. * * 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/. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.digi.xbee.api.exceptions; /** * This exception will be thrown when there is an error parsing an API packet * from the input stream. * * @see CommunicationException */ public class InvalidPacketException extends CommunicationException { // Constants private static final long serialVersionUID = 1L; private static final String DEFAULT_MESSAGE = "The XBee API packet is not properly formed."; /** * Creates a {@code InvalidPacketException} with {@value #DEFAULT_MESSAGE} * as its error detail message. */ public InvalidPacketException() { super(DEFAULT_MESSAGE); } /** * Creates a {@code InvalidPacketException} with the specified message. * * @param message The associated message. */ public InvalidPacketException(String message) { super(message); } /** * Creates an {@code InvalidPacketException} with the specified * message and cause. * * @param message The associated message. * @param cause The cause of this exception. * * @see Throwable */ public InvalidPacketException(String message, Throwable cause) { super(message, cause); } }
mpl-2.0