repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
rslemos/cobolg
parser/src/test/java/br/eti/rslemos/cobolg/CompilerHelper.java
2659
/******************************************************************************* * BEGIN COPYRIGHT NOTICE * * This file is part of program "cobolg" * Copyright 2016 Rodrigo Lemos * * 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/>. * * END COPYRIGHT NOTICE ******************************************************************************/ package br.eti.rslemos.cobolg; import static br.eti.rslemos.cobolg.SimpleCompiler.parserForFreeFormat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Arrays; import java.util.List; import org.antlr.v4.runtime.ANTLRErrorListener; import org.antlr.v4.runtime.ConsoleErrorListener; import org.antlr.v4.runtime.RuleContext; public abstract class CompilerHelper<T extends RuleContext> { private static final List<String> ruleNames = Arrays.asList(COBOLParser.ruleNames); protected abstract T parsePart(); protected Compiler parser; public T compile(String source, ANTLRErrorListener... listeners) { prepare(source, listeners); return parsePart(); } public String compileAndGetTree(String source, ANTLRErrorListener... listeners) { T tree = compile(source, listeners); return tree.toStringTree(ruleNames); } public void compileAndVerify(String source, String expectedTree) { ErrorDetector detector = new ErrorDetector(); String actualTree = compileAndGetTree(source, detector, ConsoleErrorListener.INSTANCE); detector.check(); assertThat(actualTree, is(equalTo(expectedTree))); } private void prepare(String source, ANTLRErrorListener... listeners) { try { parser = createCompiler(new StringReader(source)); for (ANTLRErrorListener listener : listeners) parser.addErrorListener(listener); } catch (Exception e) { throw new RuntimeException(e); } } protected Compiler createCompiler(Reader source) throws IOException { return parserForFreeFormat(source); } }
gpl-3.0
alien-house/Android
ASG.ViewList/app/src/test/java/com/example/shinji/asgviewlist/ExampleUnitTest.java
398
package com.example.shinji.asgviewlist; 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
active-citizen/android.java
app/src/main/java/ru/mos/polls/event/state/EventState.java
2727
package ru.mos.polls.event.state; import android.content.Context; import android.support.annotation.Nullable; import me.ilich.juggler.gui.JugglerFragment; import me.ilich.juggler.states.ContentBelowToolbarState; import me.ilich.juggler.states.State; import ru.mos.polls.R; import ru.mos.polls.base.ui.CommonToolbarFragment; import ru.mos.polls.event.gui.fragment.EventDetailFragment; import ru.mos.polls.event.gui.fragment.EventFragment; import ru.mos.polls.event.model.EventDetail; /** * Класс для построения экрана через Juggler с передачей аргументов во фрагмент. * * @author Rosherh (gorelykhaa@altarix.ru) */ public class EventState extends ContentBelowToolbarState<EventState.Params> { /** * Конструктор для состояния, когда передается только ID мероприятия. * * @param actionId Id мероприятия */ public EventState(Long actionId) { super(new EventState.Params(actionId)); } /** * Конструктор для состония, когда передается целый объект мероприятия для того, чтобы его * полностью отобразить. * * @param detail модель мероприятия */ public EventState(EventDetail detail) { super(new EventState.Params(detail)); } /** * Устанавливаем заголовок экрана в {@link android.support.v7.widget.Toolbar}. */ @Override public String getTitle(Context context, Params params) { return context.getString(R.string.about_event); } /** * Вызываем наш фрагмент и передаем туда необходимые параметры. */ @Override protected JugglerFragment onConvertContent(Params params, @Nullable JugglerFragment fragment) { if (params.detail != null) { return EventDetailFragment.instance(params.detail); } return EventFragment.instance(params.id); } /** * Создаем Toolbar. */ @Override protected JugglerFragment onConvertToolbar(Params params, @Nullable JugglerFragment fragment) { return CommonToolbarFragment.createBack(); } /** * Класс, который передает данные во фрагмент. */ static class Params extends State.Params { Long id; EventDetail detail; public Params(Long actionId) { this.id = actionId; } public Params(EventDetail detail) { this.detail = detail; } } }
gpl-3.0
SPACEDAC7/TrabajoFinalGrado
uploads/34f7f021ecaf167f6e9669e45c4483ec/java_source/com/buzzfeed/buffet/ui/view/InterceptTouchCardView.java
913
/* * Decompiled with CFR 0_115. * * Could not load the following classes: * android.content.Context * android.util.AttributeSet * android.view.MotionEvent */ package com.buzzfeed.buffet.ui.view; import android.content.Context; import android.support.annotation.Nullable; import android.support.v7.widget.CardView; import android.util.AttributeSet; import android.view.MotionEvent; public class InterceptTouchCardView extends CardView { public InterceptTouchCardView(Context context) { super(context); } public InterceptTouchCardView(Context context, @Nullable AttributeSet attributeSet) { super(context, attributeSet); } public InterceptTouchCardView(Context context, @Nullable AttributeSet attributeSet, int n2) { super(context, attributeSet, n2); } public boolean onInterceptTouchEvent(MotionEvent motionEvent) { return true; } }
gpl-3.0
ilagunap/process-profiler
java_methods_profiler/javaassist/javassist-3.16.1-GA/src/main/javassist/bytecode/stackmap/BasicBlock.java
14255
/* * Javassist, a Java-bytecode translator toolkit. * Copyright (C) 1999- Shigeru Chiba. All Rights Reserved. * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. Alternatively, the contents of this file may be used under * the terms of the GNU Lesser General Public License Version 2.1 or later, * or the Apache License Version 2.0. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. */ package javassist.bytecode.stackmap; import javassist.bytecode.*; import java.util.HashMap; import java.util.ArrayList; /** * A basic block is a sequence of bytecode that does not contain jump/branch * instructions except at the last bytecode. * Since Java6 or later does not allow JSR, this class deals with JSR as a * non-branch instruction. */ public class BasicBlock { protected int position, length; protected int incoming; // the number of incoming branches. protected BasicBlock[] exit; // null if the block is a leaf. protected boolean stop; // true if the block ends with an unconditional jump. protected Catch toCatch; protected BasicBlock(int pos) { position = pos; length = 0; incoming = 0; } public static BasicBlock find(BasicBlock[] blocks, int pos) throws BadBytecode { for (int i = 0; i < blocks.length; i++) { int iPos = blocks[i].position; if (iPos <= pos && pos < iPos + blocks[i].length) return blocks[i]; } throw new BadBytecode("no basic block at " + pos); } public static class Catch { public Catch next; public BasicBlock body; public int typeIndex; Catch(BasicBlock b, int i, Catch c) { body = b; typeIndex = i; next = c; } } public String toString() { StringBuffer sbuf = new StringBuffer(); String cname = this.getClass().getName(); int i = cname.lastIndexOf('.'); sbuf.append(i < 0 ? cname : cname.substring(i + 1)); sbuf.append("["); toString2(sbuf); sbuf.append("]"); return sbuf.toString(); } protected void toString2(StringBuffer sbuf) { sbuf.append("pos=").append(position).append(", len=") .append(length).append(", in=").append(incoming) .append(", exit{"); if (exit != null) { for (int i = 0; i < exit.length; i++) sbuf.append(exit[i].position).append(","); } sbuf.append("}, {"); Catch th = toCatch; while (th != null) { sbuf.append("(").append(th.body.position).append(", ") .append(th.typeIndex).append("), "); th = th.next; } sbuf.append("}"); } static class Mark implements Comparable { int position; BasicBlock block; BasicBlock[] jump; boolean alwaysJmp; // true if an unconditional branch. int size; // 0 unless the mark indicates RETURN etc. Catch catcher; Mark(int p) { position = p; block = null; jump = null; alwaysJmp = false; size = 0; catcher = null; } public int compareTo(Object obj) { if (obj instanceof Mark) { int pos = ((Mark)obj).position; return position - pos; } return -1; } void setJump(BasicBlock[] bb, int s, boolean always) { jump = bb; size = s; alwaysJmp = always; } } public static class Maker { /* Override these two methods if a subclass of BasicBlock must be * instantiated. */ protected BasicBlock makeBlock(int pos) { return new BasicBlock(pos); } protected BasicBlock[] makeArray(int size) { return new BasicBlock[size]; } private BasicBlock[] makeArray(BasicBlock b) { BasicBlock[] array = makeArray(1); array[0] = b; return array; } private BasicBlock[] makeArray(BasicBlock b1, BasicBlock b2) { BasicBlock[] array = makeArray(2); array[0] = b1; array[1] = b2; return array; } public BasicBlock[] make(MethodInfo minfo) throws BadBytecode { CodeAttribute ca = minfo.getCodeAttribute(); if (ca == null) return null; CodeIterator ci = ca.iterator(); return make(ci, 0, ci.getCodeLength(), ca.getExceptionTable()); } public BasicBlock[] make(CodeIterator ci, int begin, int end, ExceptionTable et) throws BadBytecode { HashMap marks = makeMarks(ci, begin, end, et); BasicBlock[] bb = makeBlocks(marks); addCatchers(bb, et); return bb; } /* Branch target */ private Mark makeMark(HashMap table, int pos) { return makeMark0(table, pos, true, true); } /* Branch instruction. * size > 0 */ private Mark makeMark(HashMap table, int pos, BasicBlock[] jump, int size, boolean always) { Mark m = makeMark0(table, pos, false, false); m.setJump(jump, size, always); return m; } private Mark makeMark0(HashMap table, int pos, boolean isBlockBegin, boolean isTarget) { Integer p = new Integer(pos); Mark m = (Mark)table.get(p); if (m == null) { m = new Mark(pos); table.put(p, m); } if (isBlockBegin) { if (m.block == null) m.block = makeBlock(pos); if (isTarget) m.block.incoming++; } return m; } private HashMap makeMarks(CodeIterator ci, int begin, int end, ExceptionTable et) throws BadBytecode { ci.begin(); ci.move(begin); HashMap marks = new HashMap(); while (ci.hasNext()) { int index = ci.next(); if (index >= end) break; int op = ci.byteAt(index); if ((Opcode.IFEQ <= op && op <= Opcode.IF_ACMPNE) || op == Opcode.IFNULL || op == Opcode.IFNONNULL) { Mark to = makeMark(marks, index + ci.s16bitAt(index + 1)); Mark next = makeMark(marks, index + 3); makeMark(marks, index, makeArray(to.block, next.block), 3, false); } else if (Opcode.GOTO <= op && op <= Opcode.LOOKUPSWITCH) switch (op) { case Opcode.GOTO : makeGoto(marks, index, index + ci.s16bitAt(index + 1), 3); break; case Opcode.JSR : makeJsr(marks, index, index + ci.s16bitAt(index + 1), 3); break; case Opcode.RET : makeMark(marks, index, null, 2, true); break; case Opcode.TABLESWITCH : { int pos = (index & ~3) + 4; int low = ci.s32bitAt(pos + 4); int high = ci.s32bitAt(pos + 8); int ncases = high - low + 1; BasicBlock[] to = makeArray(ncases + 1); to[0] = makeMark(marks, index + ci.s32bitAt(pos)).block; // default branch target int p = pos + 12; int n = p + ncases * 4; int k = 1; while (p < n) { to[k++] = makeMark(marks, index + ci.s32bitAt(p)).block; p += 4; } makeMark(marks, index, to, n - index, true); break; } case Opcode.LOOKUPSWITCH : { int pos = (index & ~3) + 4; int ncases = ci.s32bitAt(pos + 4); BasicBlock[] to = makeArray(ncases + 1); to[0] = makeMark(marks, index + ci.s32bitAt(pos)).block; // default branch target int p = pos + 8 + 4; int n = p + ncases * 8 - 4; int k = 1; while (p < n) { to[k++] = makeMark(marks, index + ci.s32bitAt(p)).block; p += 8; } makeMark(marks, index, to, n - index, true); break; } } else if ((Opcode.IRETURN <= op && op <= Opcode.RETURN) || op == Opcode.ATHROW) makeMark(marks, index, null, 1, true); else if (op == Opcode.GOTO_W) makeGoto(marks, index, index + ci.s32bitAt(index + 1), 5); else if (op == Opcode.JSR_W) makeJsr(marks, index, index + ci.s32bitAt(index + 1), 5); else if (op == Opcode.WIDE && ci.byteAt(index + 1) == Opcode.RET) makeMark(marks, index, null, 1, true); } if (et != null) { int i = et.size(); while (--i >= 0) { makeMark0(marks, et.startPc(i), true, false); makeMark(marks, et.handlerPc(i)); } } return marks; } private void makeGoto(HashMap marks, int pos, int target, int size) { Mark to = makeMark(marks, target); BasicBlock[] jumps = makeArray(to.block); makeMark(marks, pos, jumps, size, true); } /** * We ignore JSR since Java 6 or later does not allow it. */ protected void makeJsr(HashMap marks, int pos, int target, int size) { /* Mark to = makeMark(marks, target); Mark next = makeMark(marks, pos + size); BasicBlock[] jumps = makeArray(to.block, next.block); makeMark(marks, pos, jumps, size, false); */ } private BasicBlock[] makeBlocks(HashMap markTable) { Mark[] marks = (Mark[])markTable.values() .toArray(new Mark[markTable.size()]); java.util.Arrays.sort(marks); ArrayList blocks = new ArrayList(); int i = 0; BasicBlock prev; if (marks.length > 0 && marks[0].position == 0 && marks[0].block != null) prev = getBBlock(marks[i++]); else prev = makeBlock(0); blocks.add(prev); while (i < marks.length) { Mark m = marks[i++]; BasicBlock bb = getBBlock(m); if (bb == null) { // the mark indicates a branch instruction if (prev.length > 0) { // the previous mark already has exits. prev = makeBlock(prev.position + prev.length); blocks.add(prev); } prev.length = m.position + m.size - prev.position; prev.exit = m.jump; prev.stop = m.alwaysJmp; } else { // the mark indicates a branch target if (prev.length == 0) { prev.length = m.position - prev.position; bb.incoming++; prev.exit = makeArray(bb); } else { // the previous mark already has exits. int prevPos = prev.position; if (prevPos + prev.length < m.position) { prev = makeBlock(prevPos + prev.length); prev.length = m.position - prevPos; // the incoming flow from dead code is not counted // bb.incoming++; prev.exit = makeArray(bb); } } blocks.add(bb); prev = bb; } } return (BasicBlock[])blocks.toArray(makeArray(blocks.size())); } private static BasicBlock getBBlock(Mark m) { BasicBlock b = m.block; if (b != null && m.size > 0) { b.exit = m.jump; b.length = m.size; b.stop = m.alwaysJmp; } return b; } private void addCatchers(BasicBlock[] blocks, ExceptionTable et) throws BadBytecode { if (et == null) return; int i = et.size(); while (--i >= 0) { BasicBlock handler = find(blocks, et.handlerPc(i)); int start = et.startPc(i); int end = et.endPc(i); int type = et.catchType(i); handler.incoming--; for (int k = 0; k < blocks.length; k++) { BasicBlock bb = blocks[k]; int iPos = bb.position; if (start <= iPos && iPos < end) { bb.toCatch = new Catch(handler, type, bb.toCatch); handler.incoming++; } } } } } }
gpl-3.0
wanghongfei/taolijie
src/main/java/com/fh/taolijie/controller/restful/RestSignController.java
5657
package com.fh.taolijie.controller.restful; import cn.fh.security.credential.Credential; import com.fh.taolijie.component.ResponseText; import com.fh.taolijie.constant.ErrorCode; import com.fh.taolijie.constant.PicType; import com.fh.taolijie.dto.SignAndPolicy; import com.fh.taolijie.service.impl.SeqService; import com.fh.taolijie.utils.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; /** * Created by whf on 9/14/15. */ @RestController @RequestMapping("/api/user/sign") public class RestSignController { @Autowired private SeqService seqService; /** * 生成七牛签名 */ @RequestMapping(value = "/n", method = RequestMethod.GET, produces = Constants.Produce.JSON) public ResponseText qiniuSign(HttpServletRequest req) { Integer memId = SessionUtils.getCredential(req).getId(); // 检查上次请求间隔 // 不能少于1s if (!seqService.checkInterval(memId)) { return new ResponseText(ErrorCode.TOO_FREQUENT); } return new ResponseText(seqService.genQiniuToken()); } /** * 生成签名 * @return */ @RequestMapping(value = "", method = RequestMethod.GET, produces = Constants.Produce.JSON) public ResponseText genToken(@RequestParam("expiration") Long expiration, @RequestParam Integer picType, @RequestParam(value = "content-length-range", required = false) String fileRange, @RequestParam(value = "content-md5", required = false) String md5, @RequestParam(value = "content-secret", required = false) String secret, @RequestParam(value = "content-type", required = false) String contentType, @RequestParam(value = "image-width-range", required = false) String imgWidthRange, @RequestParam(value = "image-height-range", required = false) String imgHeightRange, @RequestParam(value = "notify-url", required = false) String notiUrl, @RequestParam(value = "return-url", required = false) String returnUrl, @RequestParam(value = "x-gmkerl-thumbnail", required = false) String thumbnail, @RequestParam(value = "x-gmkerl-type", required = false) String gmkerlType, @RequestParam(value = "x-gmkerl-value", required = false) String gmkerlValue, @RequestParam(value = "x-gmkerl-quality", required = false) String gmkerlQuality, @RequestParam(value = "x-gmkerl-unsharp", required = false) String gmkerlUnsharp, @RequestParam(value = "x-gmkerl-rotate", required = false) String gmkerlRotate, @RequestParam(value = "x-gmkerl-crop", required = false) String gmkerlCrop, @RequestParam(value = "x-gmkerl-exif-switch", required = false) String gmkerlExif, @RequestParam(value = "ext-param", required = false) String extParam, @RequestParam(value = "allow-file-type", required = false) String fileType, HttpServletRequest req) { Credential credential = SessionUtils.getCredential(req); // 检查上次请求间隔 // 不能少于2s if (!seqService.checkInterval(credential.getId())) { return new ResponseText(ErrorCode.TOO_FREQUENT); } Map<String, Object> parmMap = new HashMap<>(30); parmMap.put("bucket", "taolijie-pic"); parmMap.put("expiration", expiration); parmMap.put("content-length-range", fileRange); parmMap.put("content-md5", md5); parmMap.put("content-secret", secret); parmMap.put("content-type", contentType); parmMap.put("image-width-range", imgWidthRange); parmMap.put("image-height-range", imgHeightRange); parmMap.put("notify-url", notiUrl); parmMap.put("return-url", returnUrl); parmMap.put("x-gmkerl-thumbnail", thumbnail); parmMap.put("x-gmkerl-type", gmkerlType); parmMap.put("x-gmkerl-value", gmkerlValue); parmMap.put("x-gmkerl-quality", gmkerlQuality); parmMap.put("x-gmkerl-unsharp", gmkerlUnsharp); parmMap.put("x-gmkerl-rotate", gmkerlRotate); parmMap.put("x-gmkerl-crop", gmkerlCrop); parmMap.put("x-gmkerl-exif-switch", gmkerlExif); parmMap.put("ext-param", extParam); parmMap.put("allow-file-type", fileType); // 将状态字符串转换成enum PicType pt = PicType.fromCode(picType); if (null == pt) { return new ResponseText(ErrorCode.INVALID_PARAMETER); } // 生成key名 String key = seqService.genKey(pt); parmMap.put("save-key", key); // 签名 SignAndPolicy sap = new SignAndPolicy(); sap.policy = UpYunUtils.genPolicy(parmMap); sap.sign = UpYunUtils.sign(sap.policy); sap.saveKey = key; return new ResponseText(sap); } }
gpl-3.0
brunorohde/BITSLC
src/com/wordpress/brunorohde/bitslc/multitouch/ClassForMTCallBack.java
540
package com.wordpress.brunorohde.bitslc.multitouch; public class ClassForMTCallBack { private MTListenerCallBack MTCBclass; ClassForMTCallBack(MTListenerCallBack mClass) { MTCBclass = mClass; } public void sendToCallBackMethod (int id, float x, float y) { MTCBclass.screenTouched(id, x, y); } public void sendToCallBackMethod (int id, float x, float y, float d, float ang) { MTCBclass.screenTouchedDragged(id, x, y, d, ang); } public void sendToCallBackMethod (int id) { MTCBclass.screenTouchedReleased(id); } }
gpl-3.0
cameronleger/neural-style-gui
src/main/java/com/cameronleger/neuralstylegui/listwrapview/DataModel.java
2615
package com.cameronleger.neuralstylegui.listwrapview; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.util.Callback; import java.util.ArrayList; class DataModel<T> implements ListChangeListener<T> { private final ArrayList<Entry<T>> itemNodes = new ArrayList<>(); private final ObservableList<Node> flowNodes; private Callback<Void, CellNode<T>> cellFactory; private SimpleObjectProperty<T> selectedItem; public DataModel() { flowNodes = FXCollections.observableArrayList(); cellFactory = null; selectedItem = new SimpleObjectProperty<>(); } public void onChanged(Change<? extends T> c) { while (c.next()) { for (T item : c.getRemoved()) { removeItemsNode(item); } ObservableList<? extends T> list = c.getList(); for (final T item : c.getAddedSubList()) { int index = list.indexOf(item); addItemsNode(index, item); } } } private void removeItemsNode(T item) { Entry<T> cellNode = null; for (Entry<T> entry : itemNodes) { if (entry.it.equals(item)) { cellNode = entry; break; } } if (cellNode != null) { itemNodes.remove(cellNode); flowNodes.remove(cellNode.cellNode.getNode()); } } private void addItemsNode(int index, final T item) { CellNode<T> cellNode; cellNode = cellFactory.call(null); cellNode.getNode().setOnMouseClicked(e -> cellNode.getCell().actionItem(item, e.getButton())); updateItem(item, false, cellNode); itemNodes.add(new Entry<T>(item, cellNode)); flowNodes.add(index, cellNode.getNode()); } private void updateItem(T item, boolean empty, CellNode<T> node) { node.getCell().updateItem(item, empty); } public void setCellFactory(Callback<Void, CellNode<T>> cellFactory) { this.cellFactory = cellFactory; } public ObservableList<Node> getFlowNodes() { return flowNodes; } public SimpleObjectProperty<T> selectedItemProperty() { return selectedItem; } private static class Entry<T> { final T it; final CellNode<T> cellNode; public Entry(T it, CellNode<T> cellNode) { this.it = it; this.cellNode = cellNode; } } }
gpl-3.0
lobbi44/CtfPlugin
CtfPlugin/src/lobbi44/ctf/util/OfflinePlayerHelper.java
1837
package lobbi44.ctf.util; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import java.util.Map; import java.util.logging.Logger; /** * @author lobbi44 * This class supports the porting of offline players. * The events have to be registered first! */ public class OfflinePlayerHelper implements Listener { private Map<OfflinePlayer, OfflineJob> tpJobs; private Logger logger; //todo: Pass a save file here //todo: When shutting down the server, this has to be saved! public OfflinePlayerHelper(Map<OfflinePlayer, OfflineJob> jobs, Logger logger) { tpJobs = jobs; this.logger = logger; } public void doJob(OfflinePlayer player, OfflineJob job) { if (player.isOnline()) { job.doJob(player.getPlayer()); logger.warning("Job executed"); } else tpJobs.put(player, job); } public void tpPlayer(OfflinePlayer player, Location loc) { doJob(player, new TpJob(loc)); } /** * Checks if any actions were planned for a newly joined player */ @EventHandler public void onPlayerJoinEvent(PlayerJoinEvent e) { Player p = e.getPlayer(); if (tpJobs.containsKey(p)) { tpJobs.get(p).doJob(p); tpJobs.remove(p); } } } interface OfflineJob { //todo: Add success variable? Error handler? Lambdas? boolean doJob(Player p); } class TpJob implements OfflineJob { private Location loc; public TpJob(Location loc) { this.loc = loc; } @Override public boolean doJob(Player p) { p.teleport(loc); return true; } }
gpl-3.0
mnemotron/Revenue
revenue.service/src/revenue/service/bond/entity/ReqBondItemBuy.java
1203
package revenue.service.bond.entity; import java.util.Date; public class ReqBondItemBuy { private long id; private long portfolioId; private long depotId; private long bondId; private Date buyDate; private double buyPercent; private double nominalValue; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getPortfolioId() { return portfolioId; } public void setPortfolioId(long portfolioId) { this.portfolioId = portfolioId; } public long getDepotId() { return depotId; } public void setDepotId(long depotId) { this.depotId = depotId; } public long getBondId() { return bondId; } public void setBondId(long bondId) { this.bondId = bondId; } public Date getBuyDate() { return buyDate; } public void setBuyDate(Date buyDate) { this.buyDate = buyDate; } public double getBuyPercent() { return buyPercent; } public void setBuyPercent(double buyPercent) { this.buyPercent = buyPercent; } public double getNominalValue() { return nominalValue; } public void setNominalValue(double nominalValue) { this.nominalValue = nominalValue; } public ReqBondItemBuy() { } }
gpl-3.0
johannesgerer/unicenta
src-beans/com/openbravo/editor/JEditorCurrency.java
1432
// uniCenta oPOS - Touch Friendly Point Of Sale // Copyright (c) 2009-2014 uniCenta & previous Openbravo POS works // http://www.unicenta.com // // This file is part of uniCenta oPOS // // uniCenta oPOS 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. // // uniCenta oPOS 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 uniCenta oPOS. If not, see <http://www.gnu.org/licenses/>. package com.openbravo.editor; import com.openbravo.format.Formats; /** * * @author JG uniCenta */ public class JEditorCurrency extends JEditorNumber { private static final long serialVersionUID = 5096754100573262803L; /** Creates a new instance of JEditorCurrency */ public JEditorCurrency() { } /** * * @return */ protected Formats getFormat() { return Formats.CURRENCY; } /** * * @return */ protected int getMode() { return EditorKeys.MODE_DOUBLE; } }
gpl-3.0
Lilylicious/MysteriousMiscellany
src/main/java/lilylicious/mysteriousmiscellany/utils/Predicates.java
792
package lilylicious.mysteriousmiscellany.utils; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import java.util.function.BiPredicate; import java.util.function.Predicate; public final class Predicates { public static final Predicate<Block> IS_WATER = input -> input == Blocks.WATER || input == Blocks.FLOWING_WATER; public static final Predicate<Block> IS_DYEABLE = input -> input == Blocks.HARDENED_CLAY || input == Blocks.STAINED_GLASS || input == Blocks.STAINED_GLASS_PANE || input == Blocks.GLASS_PANE || input == Blocks.STAINED_HARDENED_CLAY || input == Blocks.GLASS || input == Blocks.CARPET || input == Blocks.WOOL; public static final BiPredicate<Block, Block> ICE_NOT_ICE = (current, target) -> current == Blocks.ICE && target != Blocks.ICE; }
gpl-3.0
aijony/neuralnetworksimulation
src/graphics/RendererInterface.java
165
package graphics; /* *Use whenever classs/object HAS-A single renderer */ public interface RendererInterface { public void render(); public void dispose(); }
gpl-3.0
tryggvil/eucalyptus
clc/modules/core/src/edu/ucsb/eucalyptus/cloud/exceptions/ExceptionList.java
6979
package edu.ucsb.eucalyptus.cloud.exceptions; /******************************************************************************* * Copyright (c) 2009 Eucalyptus Systems, Inc. * * 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, only version 3 of the License. * * * This file 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/>. * * Please contact Eucalyptus Systems, Inc., 130 Castilian * Dr., Goleta, CA 93101 USA or visit <http://www.eucalyptus.com/licenses/> * if you need additional information or have any questions. * * This file may incorporate work covered under the following copyright and * permission notice: * * Software License Agreement (BSD License) * * Copyright (c) 2008, Regents of the University of California * All rights reserved. * * Redistribution and use of this software in source and binary forms, with * or without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. USERS OF * THIS SOFTWARE ACKNOWLEDGE THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE * LICENSED MATERIAL, COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS * SOFTWARE, AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING * IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, SANTA * BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, WHICH IN * THE REGENTS’ DISCRETION MAY INCLUDE, WITHOUT LIMITATION, REPLACEMENT * OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO IDENTIFIED, OR * WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT NEEDED TO COMPLY WITH * ANY SUCH LICENSES OR RIGHTS. ******************************************************************************/ /* * Author: Chris Grzegorczyk grze@cs.ucsb.edu */ /* * as documented at: * http://docs.amazonwebservices.com/AWSEC2/2008-08-08/DeveloperGuide/index.html?api-error-codes.html */ public class ExceptionList { public static String ERR_ADDRESS_LIMIT_EXCEEDED = "AddressLimitExceeded"; public static String ERR_ATTACHMENT_LIMIT_EXCEEDED = "AttachmentLimitExceeded"; public static String ERR_AUTH_FAILURE = "AuthFailure"; public static String ERR_INCORRECT_STATE = "IncorrectState"; public static String ERR_INSTANCE_LIMIT_EXCEEDED = "InstanceLimitExceeded"; public static String ERR_INVALID_AMI_ATTRIBUTE_ITEM_VALUE = "InvalidAMIAttributeItemValue"; public static String ERR_INVALID_AMIID_MALFORMED = "InvalidAMIID.Malformed"; public static String ERR_INVALID_AMIID_NOTFOUND = "InvalidAMIID.NotFound"; public static String ERR_INVALID_AMIID_UNAVAILABLE = "InvalidAMIID.Unavailable"; public static String ERR_INVALID_ATTACHMENT_NOTFOUND = "InvalidAttachment.NotFound"; public static String ERR_INVALID_DEVICE_INUSE = "InvalidDevice.InUse"; public static String ERR_INVALID_INSTANCEID_MALFORMED = "InvalidInstanceID.Malformed"; public static String ERR_INVALID_INSTANCEID_NOTFOUND = "InvalidInstanceID.NotFound"; public static String ERR_INVALID_KEYPAIR_NOTFOUND = "InvalidKeyPair.NotFound"; public static String ERR_INVALID_KEYPAIR_DUPLICATE = "InvalidKeyPair.Duplicate"; public static String ERR_INVALID_GROUP_NOTFOUND = "InvalidGroup.NotFound"; public static String ERR_INVALID_GROUP_DUPLICATE = "InvalidGroup.Duplicate"; public static String ERR_INVALID_GROUP_INUSE = "InvalidGroup.InUse"; public static String ERR_INVALID_GROUP_RESERVED = "InvalidGroup.Reserved"; public static String ERR_INVALID_MANIFEST = "InvalidManifest"; public static String ERR_INVALID_PARAMETER_VALUE = "InvalidParameterValue"; public static String ERR_INVALID_PERMISSION_DUPLICATE = "InvalidPermission.Duplicate"; public static String ERR_INVALID_PERMISSION_MALFORMED = "InvalidPermission.Malformed"; public static String ERR_INVALID_RESERVATIONID_MALFORMED = "InvalidReservationID.Malformed"; public static String ERR_INVALID_RESERVATIONID_NOTFOUND = "InvalidReservationID.NotFound"; public static String ERR_INVALID_PARAMETERCOMBINATION = "InvalidParameterCombination"; public static String ERR_INVALID_SNAPSHOTID_MALFORMED = "InvalidSnapshotID.Malformed"; public static String ERR_INVALID_SNAPSHOTID_NOTFOUND = "InvalidSnapshotID.NotFound"; public static String ERR_INVALID_USERID_MALFORMED = "InvalidUserID.Malformed"; public static String ERR_INVALID_VOLUMEID_MALFORMED = "InvalidVolumeID.Malformed"; public static String ERR_INVALID_VOLUMEID_NOT_FOUND = "InvalidVolumeID.NotFound"; public static String ERR_INVALID_VOLUMEID_DUPLICATE = "InvalidVolumeID.Duplicate"; public static String ERR_INVALID_VOLUMEID_ZONE_MISMATCH = "InvalidVolumeID.ZoneMismatch"; public static String ERR_INVALID_ZONE_NOT_FOUND = "InvalidZone.NotFound"; public static String ERR_NON_EBS_INSTANCE = "NonEBSInstance"; public static String ERR_PENDING_SNAPSHOT_LIMIT_EXCEEDED = "PendingSnapshotLimitExceeded"; public static String ERR_SNAPSHOT_LIMIT_EXCEEDED = "SnapshotLimitExceeded"; public static String ERR_UNKNOWN_PARAMETER = "UnknownParameter"; public static String ERR_VOLUME_LIMIT_EXCEEDED = "VolumeLimitExceeded"; public static String ERR_SYS_INTERNAL_ERROR = "InternalError"; public static String ERR_SYS_INSUFFICIENT_ADDRESS_CAPACITY = "InsufficientAddressCapacity"; public static String ERR_SYS_INSUFFICIENT_INSTANCE_CAPACITY = "InsufficientInstanceCapacity"; public static String ERR_SYS_UNAVAILABLE = "Unavailable"; }
gpl-3.0
drenteria/psp21
src/main/java/edu/uniandes/ecos/psp21/controller/WebController.java
2541
package edu.uniandes.ecos.psp21.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.uniandes.ecos.psp21.model.XValueFinder; /** * This class acts as the controller for the MVC pattern * to reflect the user view for the Webb deploy of this application * @author drenteria * */ public class WebController { /** * This method sends to the response of the given request the printing * of the input data form * @param req The incoming HTTP request * @param rsp The outgoing HTTP response * @throws IOException */ public static void showInputForm(HttpServletRequest req, HttpServletResponse rsp) throws IOException{ String formString = "<html>" + "<body>" + "<h1>PSP21 X Value finder in T-Distribution using Simpson Rule Integration!</h1>" + "<p>Please, write needed numeric parameters to calculate X value.</p>" + "<form action=\"findx\" method=\"post\"><br/>" + "Degrees of Freedom: <input type=\"text\" name=\"dof\"><br/>" + "Expected P Value: <input type=\"text\" name=\"pvalue\"><br/>" + "Allowed Error (E): <input type=\"text\" name=\"error\"><br/>" + "<input type=\"submit\" value=\"Find X!\">" + "</body>" + "</html>"; PrintWriter writer = rsp.getWriter(); writer.write(formString); } /** * This method makes the required calculations and prints the results * in the * @param req * @param rsp * @param dof * @param expectedP * @param allowedError * @throws Exception */ public static void showResultsForX(HttpServletRequest req, HttpServletResponse rsp, Integer dof, Double expectedP, Double allowedError) throws Exception { XValueFinder xFinder = new XValueFinder(dof, expectedP, allowedError); xFinder.findXValue(); double xValue = xFinder.getXValue(); double error = xFinder.getCurrentErrorValue(); String formString = "<html>" + "<body>" + "<h1>PSP21 X Value finder in T-Distribution using Simpson Rule Integration!</h1>" + "<p>X value find results:.</p>" + "Degrees of Freedom: " + String.valueOf(dof) + "<br/>" + "Expected P Value: " + String.valueOf(expectedP) + "<br/>" + "Allowed Error (E): " + String.valueOf(allowedError) + "<br/>" + "Calculated Error: " + String.valueOf(error) + "<br/>" + "X closest value found: " + String.valueOf(xValue) + "<br/>" + "</body>" + "</html>"; PrintWriter writer = rsp.getWriter(); writer.write(formString); } }
gpl-3.0
Young-Phoenix/designpattern
src/com/lcf/dp/simplefactory/Car.java
150
package com.lcf.dp.simplefactory; public class Car implements Moveable { @Override public void run() { System.out.println("Car ÔÚÅÜ¡­¡­"); } }
gpl-3.0
nfell2009/Skript
src/main/java/ch/njol/skript/events/EvtItem.java
5048
/* * This file is part of Skript. * * Skript 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. * * Skript 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 Skript. If not, see <http://www.gnu.org/licenses/>. * * * Copyright 2011-2014 Peter Güttinger * */ package ch.njol.skript.events; import org.bukkit.event.Event; import org.bukkit.event.block.BlockDispenseEvent; import org.bukkit.event.entity.ItemSpawnEvent; import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.inventory.ItemStack; import org.eclipse.jdt.annotation.Nullable; import ch.njol.skript.Skript; import ch.njol.skript.aliases.ItemType; import ch.njol.skript.lang.Literal; import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.util.Checker; /** * @author Peter Güttinger */ public class EvtItem extends SkriptEvent { private final static boolean hasConsumeEvent = Skript.classExists("org.bukkit.event.player.PlayerItemConsumeEvent"); static { Skript.registerEvent("Dispense", EvtItem.class, BlockDispenseEvent.class, "dispens(e|ing) [[of] %itemtypes%]") .description("Called when a dispenser dispenses an item.") .examples("") .since(""); Skript.registerEvent("Item Spawn", EvtItem.class, ItemSpawnEvent.class, "item spawn[ing] [[of] %itemtypes%]") .description("Called whenever an item stack is spawned in a world, e.g. as drop of a block or mob, a player throwing items out of his inventory, or a dispenser dispensing an item (not shooting it).") .examples("") .since(""); Skript.registerEvent("Drop", EvtItem.class, PlayerDropItemEvent.class, "[player] drop[ing] [[of] %itemtypes%]") .description("Called when a player drops an item from his inventory.") .examples("") .since(""); // TODO limit to InventoryAction.PICKUP_* and similar (e.g. COLLECT_TO_CURSOR) Skript.registerEvent("Craft", EvtItem.class, CraftItemEvent.class, "[player] craft[ing] [[of] %itemtypes%]") .description("Called when a player crafts an item.") .examples("") .since(""); Skript.registerEvent("Pick Up", EvtItem.class, PlayerPickupItemEvent.class, "[player] (pick[ ]up|picking up) [[of] %itemtypes%]") .description("Called when a player picks up an item. Please note that the item is still on the ground when this event is called.") .examples("") .since(""); // TODO brew event // Skript.registerEvent("Brew", EvtItem.class, BrewEvent.class, "brew[ing] [[of] %itemtypes%]") // .description("Called when a potion finished brewing.") // .examples("") // .since("2.0"); if (hasConsumeEvent) { Skript.registerEvent("Consume", EvtItem.class, PlayerItemConsumeEvent.class, "[player] ((eat|drink)[ing]|consum(e|ing)) [[of] %itemtypes%]") .description("Called when a player is done eating/drinking something, e.g. an apple, bread, meat, milk or a potion.") .examples("") .since("2.0"); } } @Nullable private Literal<ItemType> types; @SuppressWarnings("unchecked") @Override public boolean init(final Literal<?>[] args, final int matchedPattern, final ParseResult parser) { types = (Literal<ItemType>) args[0]; return true; } @SuppressWarnings("null") @Override public boolean check(final Event e) { if (types == null) return true; final ItemStack is; if (e instanceof BlockDispenseEvent) { is = ((BlockDispenseEvent) e).getItem(); } else if (e instanceof ItemSpawnEvent) { is = ((ItemSpawnEvent) e).getEntity().getItemStack(); } else if (e instanceof PlayerDropItemEvent) { is = ((PlayerDropItemEvent) e).getItemDrop().getItemStack(); } else if (e instanceof CraftItemEvent) { is = ((CraftItemEvent) e).getRecipe().getResult(); } else if (e instanceof PlayerPickupItemEvent) { is = ((PlayerPickupItemEvent) e).getItem().getItemStack(); } else if (hasConsumeEvent && e instanceof PlayerItemConsumeEvent) { is = ((PlayerItemConsumeEvent) e).getItem(); // } else if (e instanceof BrewEvent) // is = ((BrewEvent) e).getContents().getContents() } else { assert false; return false; } return types.check(e, new Checker<ItemType>() { @Override public boolean check(final ItemType t) { return t.isOfType(is); } }); } @Override public String toString(final @Nullable Event e, final boolean debug) { return "dispense/spawn/drop/craft/pickup/consume/break" + (types == null ? "" : " of " + types); } }
gpl-3.0
jhelom/Nukkit
src/main/java/cn/nukkit/network/protocol/MovePlayerPacket.java
1395
package cn.nukkit.network.protocol; import cn.nukkit.math.Vector3f; /** * Created on 15-10-14. */ public class MovePlayerPacket extends DataPacket { public static final byte NETWORK_ID = ProtocolInfo.MOVE_PLAYER_PACKET; public static final byte MODE_NORMAL = 0; public static final byte MODE_RESET = 1; public static final byte MODE_ROTATION = 2; public long eid; public float x; public float y; public float z; public float yaw; public float headYaw; public float pitch; public byte mode = MODE_NORMAL; public boolean onGround; @Override public void decode() { this.eid = this.getVarLong(); Vector3f v = this.getVector3f(); this.x = v.x; this.y = v.y; this.z = v.z; this.pitch = this.getLFloat(); this.headYaw = this.getLFloat(); this.yaw = this.getLFloat(); this.mode = (byte) this.getByte(); this.onGround = this.getBoolean(); } @Override public void encode() { this.reset(); this.putVarLong(this.eid); this.putVector3f(this.x, this.y, this.z); this.putLFloat(this.pitch); this.putLFloat(this.yaw); this.putLFloat(this.headYaw); this.putByte(this.mode); this.putBoolean(this.onGround); } @Override public byte pid() { return NETWORK_ID; } }
gpl-3.0
cgd/haplotype-analysis
src/java/org/jax/haplotype/analysis/visualization/SimplePhylogenyTreeImageFactory.java
32393
/* * Copyright (c) 2010 The Jackson Laboratory * * This 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 software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. */ package org.jax.haplotype.analysis.visualization; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Paint; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Dimension2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JPanel; import org.jax.haplotype.phylogeny.data.PhylogenyTreeEdge; import org.jax.haplotype.phylogeny.data.PhylogenyTreeEdgeWithRealValue; import org.jax.haplotype.phylogeny.data.PhylogenyTreeNode; import org.jax.util.TextWrapper; import org.jax.util.gui.Dimension2DDouble; import org.jax.util.gui.Java2DUtils; import org.jfree.chart.renderer.PaintScale; /** * A phylogeny tree image factory that doesn't depend on external * tree rendering libraries * @author <A HREF="mailto:keith.sheppard@jax.org">Keith Sheppard</A> */ public class SimplePhylogenyTreeImageFactory implements PhylogenyTreeImageFactory { private static final Logger LOG = Logger.getLogger( SimplePhylogenyTreeImageFactory.class.getName()); private static final Font LABEL_FONT = new Font("SansSerif", Font.BOLD, 12); private static final int LABEL_BORDER_ROUNDING_ARC_SIZE = 10; private static final double LEAF_ANGLE_WEIGHTING = 2; // TODO imlement some kind of strain weighting scheme private static final double STRAIN_ANGLE_WEIGHTING = 0; private static final Color FOREGROUND_COLOR = Color.BLACK; private static final Color SHADOW_COLOR = Color.LIGHT_GRAY; private static final Color BACKGROUND_COLOR = new Color(1.0F, 1.0F, 1.0F, 0.5F); private static final Stroke LINE_STROKE = new BasicStroke(2, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); private static final AffineTransform SHADOW_TRANSFORM = new AffineTransform(); static { // this is the transform that we use to draw the pretty shadow // background SHADOW_TRANSFORM.translate(3.0, 3.0); } private static final int BORDER_WHITE_SPACE = 10; private static final int NODE_LABEL_WRAP_LIMIT = 25; private final PaintScale paintScale; /** * Constructor */ public SimplePhylogenyTreeImageFactory() { this(null); } /** * Constructor * @param paintScale * the paint scale to use */ public SimplePhylogenyTreeImageFactory(PaintScale paintScale) { this.paintScale = paintScale; } /** * {@inheritDoc} */ public BufferedImage createPhylogenyImage( PhylogenyTreeNode phylogenyTree, int imageWidth, int imageHeight) { if(LOG.isLoggable(Level.FINE)) { LOG.fine( "Creating phylogeny image for: " + phylogenyTree.resolveToSingleStrainLeafNodes(0.0).toNewickFormat()); } BufferedImage bi = new BufferedImage( imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D graphics = bi.createGraphics(); graphics.setStroke(LINE_STROKE); graphics.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setColor(Color.BLACK); this.paintPhylogenyTree( graphics, phylogenyTree, imageWidth, imageHeight); return bi; } /** * Paint the given tree * @param graphics * the graphics to paint with * @param phylogenyTree * the tree to paint */ private void paintPhylogenyTree( Graphics2D graphics, PhylogenyTreeNode phylogenyTree, int imageWidth, int imageHeight) { VisualTreeNode treeLayout = this.createTreeLayout(phylogenyTree); this.transformTreeLayout( treeLayout, imageWidth, imageHeight, graphics.getFontRenderContext()); this.paintPhylogenyTree( graphics, treeLayout); } /** * Paint the given tree layout * @param graphics * the graphics to paint with * @param treeLayout * the layout to paint */ private void paintPhylogenyTree( Graphics2D graphics, VisualTreeNode treeLayout) { int childNodeCount = treeLayout.getChildNodes().size(); for(int i = 0; i < childNodeCount; i++) { VisualTreeNode visualChild = treeLayout.getChildNodes().get(i); Shape branchShape = new Line2D.Double( treeLayout.getPosition(), visualChild.getPosition()); Shape branchShadowShape = SHADOW_TRANSFORM.createTransformedShape( branchShape); graphics.setColor(SHADOW_COLOR); graphics.draw(branchShadowShape); if(this.paintScale != null) { PhylogenyTreeEdge phylogenyEdge = treeLayout.getPhylogenyTreeNode().getChildEdges().get(i); if(phylogenyEdge instanceof PhylogenyTreeEdgeWithRealValue) { PhylogenyTreeEdgeWithRealValue phylogenyEdgeWithValue = (PhylogenyTreeEdgeWithRealValue)phylogenyEdge; Paint paint = this.paintScale.getPaint( phylogenyEdgeWithValue.getRealValue()); graphics.setPaint(paint); } else { graphics.setColor(FOREGROUND_COLOR); } } else { graphics.setColor(FOREGROUND_COLOR); } graphics.draw(branchShape); // recurse this.paintPhylogenyTree( graphics, visualChild); } if(!treeLayout.getPhylogenyTreeNode().getStrains().isEmpty()) { Shape textShape = this.getLabelShape(treeLayout, graphics.getFontRenderContext()); Shape borderShape = this.getLabelBorder(textShape); graphics.setColor(BACKGROUND_COLOR); graphics.fill(borderShape); graphics.setColor(SHADOW_COLOR); Area borderShadowShape = new Area(SHADOW_TRANSFORM.createTransformedShape(borderShape)); borderShadowShape.subtract(new Area(borderShape)); graphics.draw(borderShadowShape); graphics.setColor(FOREGROUND_COLOR); graphics.draw(borderShape); graphics.fill(textShape); } } /** * Get the label shape for the given tree node * @param treeNode * the tree node * @param frc * the font rendering context * @return * the label shape */ private Shape getLabelShape(VisualTreeNode treeNode, FontRenderContext frc) { // convert the strain list to a comma separated list then wrap it List<String> strainList = treeNode.getPhylogenyTreeNode().getStrains(); int strainCount = strainList.size(); StringBuffer commaSeparatedStrains = new StringBuffer(); for(int i = 0; i < strainCount; i++) { if(i >= 1) { commaSeparatedStrains.append(", "); } commaSeparatedStrains.append(strainList.get(i)); } String[] wrappedStrains = TextWrapper.wrapText( commaSeparatedStrains.toString(), NODE_LABEL_WRAP_LIMIT); Shape textShape = Java2DUtils.createCenteredMultilineTextShape( wrappedStrains, LABEL_FONT, frc); AffineTransform transform = new AffineTransform(); transform.translate( treeNode.getPosition().getX(), treeNode.getPosition().getY()); textShape = transform.createTransformedShape(textShape); return textShape; } /** * Get the border shape for the given label shape * @param labelShape * the label shape that we're going to draw a border around * @return * the border shape */ private Shape getLabelBorder(Shape labelShape) { Rectangle2D labelBounds = labelShape.getBounds2D(); return new RoundRectangle2D.Double( labelBounds.getX() - LABEL_BORDER_ROUNDING_ARC_SIZE, labelBounds.getY() - LABEL_BORDER_ROUNDING_ARC_SIZE, labelBounds.getWidth() + (LABEL_BORDER_ROUNDING_ARC_SIZE * 2), labelBounds.getHeight() + (LABEL_BORDER_ROUNDING_ARC_SIZE * 2), LABEL_BORDER_ROUNDING_ARC_SIZE, LABEL_BORDER_ROUNDING_ARC_SIZE); } /** * Transform the tree layout so that it fits nicely in the given image * dimensions * @param treeLayout * the layout to transform * @param imageWidth * the image width * @param imageHeight * the image height */ private void transformTreeLayout( VisualTreeNode treeLayout, int imageWidth, int imageHeight, FontRenderContext frc) { Dimension2D maximalNodeLabelDimension = this.calculateMaximalNodeDimension( treeLayout, frc); double widthBuffer = maximalNodeLabelDimension.getWidth() + BORDER_WHITE_SPACE; double heightBuffer = maximalNodeLabelDimension.getHeight() + BORDER_WHITE_SPACE; // perform rotation to improve the use of space { // center around 0, 0 VisualTreeNode[] mostDistantPair = this.getMostDistantNodePair(treeLayout); Point2D distantPoint1 = mostDistantPair[0].getPosition(); Point2D distantPoint2 = mostDistantPair[1].getPosition(); double xDiff = distantPoint1.getX() - distantPoint2.getX(); double yDiff = distantPoint1.getY() - distantPoint2.getY(); this.translateTreeLayout( treeLayout, (xDiff / 2.0) - distantPoint1.getX(), (yDiff / 2.0) - distantPoint2.getY()); // rotate double thetaRadians = Math.atan2(yDiff, xDiff); if(imageWidth >= imageHeight) { this.rotateTreeLayout(treeLayout, -thetaRadians); } else { this.rotateTreeLayout(treeLayout, (Math.PI / 2.0 - thetaRadians)); } } Rectangle2D boundingRectangle = this.calculateBounds(treeLayout, null); // center around the middle of the display area this.translateTreeLayout( treeLayout, -boundingRectangle.getX(), -boundingRectangle.getY()); // grow the image to fill a larger area double xScale = (imageWidth - widthBuffer) / boundingRectangle.getWidth(); double yScale = (imageHeight - heightBuffer) / boundingRectangle.getHeight(); double smallerScale = Math.min(xScale, yScale); this.scaleTreeLayout(treeLayout, smallerScale); // center around the middle of the display area boundingRectangle = this.calculateBounds(treeLayout, null); this.translateTreeLayout( treeLayout, ((imageWidth - boundingRectangle.getWidth()) / 2.0) - boundingRectangle.getX(), ((imageHeight - boundingRectangle.getHeight()) / 2.0) - boundingRectangle.getY()); } /** * Find the biggest width and height of tree node labels * @param treeLayout * the tree layout * @param frc * the {@link FontRenderContext} * @return * the biggest width and height */ private Dimension2D calculateMaximalNodeDimension( VisualTreeNode treeLayout, FontRenderContext frc) { Dimension2DDouble maximalNodeDimension = new Dimension2DDouble(); this.calculateMaximalNodeDimensionRecursive( maximalNodeDimension, treeLayout, frc); return maximalNodeDimension; } /** * A recursive version of * {@link #calculateMaximalNodeDimension(VisualTreeNode, FontRenderContext)} * @param maximalNodeDimension * the biggest width and height * @param treeLayout * the tree layout * @param frc * the {@link FontRenderContext} */ private void calculateMaximalNodeDimensionRecursive( Dimension2DDouble maximalNodeDimension, VisualTreeNode treeLayout, FontRenderContext frc) { Shape textShape = this.getLabelShape(treeLayout, frc); Shape borderShape = this.getLabelBorder(textShape); Rectangle2D borderBounds = borderShape.getBounds2D(); if(borderBounds.getWidth() > maximalNodeDimension.getWidth()) { maximalNodeDimension.setWidth(borderBounds.getWidth()); } if(borderBounds.getHeight() > maximalNodeDimension.getHeight()) { maximalNodeDimension.setHeight(borderBounds.getHeight()); } for(VisualTreeNode childNode: treeLayout.getChildNodes()) { this.calculateMaximalNodeDimensionRecursive( maximalNodeDimension, childNode, frc); } } /** * Rotate the given tree layout * @param treeLayout * the layout to rotate * @param thetaRadians * the rotation in radians */ private void rotateTreeLayout( VisualTreeNode treeLayout, double thetaRadians) { double cosTheta = Math.cos(thetaRadians); double sinTheta = Math.sin(thetaRadians); this.rotateTreeLayoutRecursive( treeLayout, cosTheta, sinTheta); } /** * Recursively rotate the given tree node * @param treeNode * the node to recursively rotate * @param cosTheta * the cosine of the rotation angle * @param sinTheta * the sin of the rotation angle */ private void rotateTreeLayoutRecursive( VisualTreeNode treeNode, double cosTheta, double sinTheta) { // rotate this node double origX = treeNode.getPosition().getX(); double origY = treeNode.getPosition().getY(); double rotX = (origX * cosTheta) - (origY * sinTheta); double rotY = (origX * sinTheta) + (origY * cosTheta); treeNode.getPosition().setLocation(rotX, rotY); for(VisualTreeNode childNode: treeNode.getChildNodes()) { // recurse this.rotateTreeLayoutRecursive(childNode, cosTheta, sinTheta); } } /** * Apply a scaling factor to the tree layout * @param treeLayout * the layout to scale * @param scale * the scaling factor to apply */ private void scaleTreeLayout(VisualTreeNode treeLayout, double scale) { treeLayout.getPosition().x *= scale; treeLayout.getPosition().y *= scale; for(VisualTreeNode child: treeLayout.getChildNodes()) { this.scaleTreeLayout(child, scale); } } /** * Apply a translation to the tree layout * @param treeLayout * the layout to translate * @param xTranslation * the x translation * @param yTranslation * the y translation */ private void translateTreeLayout( VisualTreeNode treeLayout, double xTranslation, double yTranslation) { treeLayout.getPosition().x += xTranslation; treeLayout.getPosition().y += yTranslation; for(VisualTreeNode child: treeLayout.getChildNodes()) { this.translateTreeLayout( child, xTranslation, yTranslation); } } /** * Method for calculating the minimum bounding rectangle for the given * tree layout * @param treeLayout * the layout to calculate MBR for * @param rectangle * the rectangle up to now (should be null initially) * @return * the MBR */ private Rectangle2D.Double calculateBounds(VisualTreeNode treeLayout, Rectangle2D.Double rectangle) { Point2D position = treeLayout.getPosition(); if(rectangle == null) { rectangle = new Rectangle2D.Double( position.getX(), position.getY(), 0.0, 0.0); } else { if(position.getX() < rectangle.getMinX()) { double xDiff = rectangle.getMinX() - position.getX(); rectangle.x -= xDiff; rectangle.width += xDiff; } else if(position.getX() > rectangle.getMaxX()) { double xDiff = position.getX() - rectangle.getMaxX(); rectangle.width += xDiff; } if(position.getY() < rectangle.getMinY()) { double yDiff = rectangle.getMinY() - position.getY(); rectangle.y -= yDiff; rectangle.height += yDiff; } else if(position.getY() > rectangle.getMaxY()) { double yDiff = position.getY() - rectangle.getMaxY(); rectangle.height += yDiff; } } for(VisualTreeNode childNode: treeLayout.getChildNodes()) { rectangle = this.calculateBounds(childNode, rectangle); } return rectangle; } /** * Create a layout for the given phylogeny * @param phylogenyTree * the tree to create a layout for * @return * the layout */ private VisualTreeNode createTreeLayout( PhylogenyTreeNode phylogenyTree) { // how many leaves are there? List<PhylogenyTreeNode> leafNodes = phylogenyTree.getAllLeafNodes(); int leafCount = leafNodes.size(); int leavesUsed = 0; if(phylogenyTree.getChildEdges().size() == 1) { // this is a leaf if you ignore directionality... so remove // one slice of the pie to indicate that we've rendered a leaf leafCount++; leavesUsed++; } // TODO: implement real strain weighting logic // how many strains are there? List<String> strains = phylogenyTree.getAllStrains(); int strainCount = strains.size(); int strainsUsed = phylogenyTree.getStrains().size(); // figure out the angle weightings between strains and leaves double weightedSliceCount = (leafCount * LEAF_ANGLE_WEIGHTING) + (strainCount * STRAIN_ANGLE_WEIGHTING); double weightedRadiansPerSlice = (2 * Math.PI) / weightedSliceCount; double radiansPerLeaf = weightedRadiansPerSlice * LEAF_ANGLE_WEIGHTING; double radiansPerStrain = weightedRadiansPerSlice * STRAIN_ANGLE_WEIGHTING; VisualTreeNode root = new VisualTreeNode(phylogenyTree); this.createTreeLayoutRecursive( root, radiansPerLeaf, leavesUsed); return root; } /** * A recursive function for building the tree layout * @param parentNode * the parent node that we're filling out * @param radiansPerLeaf * the number of radians to use per leaf * @param leavesAlreadyUsed * the number of leaves that have already been used by * previous calls */ private void createTreeLayoutRecursive( VisualTreeNode parentNode, double radiansPerLeaf, int leavesAlreadyUsed) { double parentX = parentNode.getPosition().getX(); double parentY = parentNode.getPosition().getY(); int cumulativeLeavesUsed = leavesAlreadyUsed; for(PhylogenyTreeEdge childEdge: parentNode.getPhylogenyTreeNode().getChildEdges()) { // how many leaves are taken up by this child? PhylogenyTreeNode childNode = childEdge.getNode(); List<PhylogenyTreeNode> childLeafNodes = childNode.getAllLeafNodes(); int currChildLeaves = childLeafNodes.size(); // find the angle to use in placing the child double currChildAngleRadians = ((currChildLeaves / 2.0) + cumulativeLeavesUsed) * radiansPerLeaf; // find the x & y positions from the angle and parent position // Here's the trig we'll use // sin(angle) = y/branch_length // y = sin(angle)*branch_length // cos(angle) = x/branch_length // x = cos(angle)*branch_length double branchLength = childEdge.getEdgeLength(); double yOffset = Math.sin(currChildAngleRadians) * branchLength; double xOffset = Math.cos(currChildAngleRadians) * branchLength; // create the new child and add it VisualTreeNode childLayout = new VisualTreeNode(childNode); childLayout.getPosition().setLocation( parentX + xOffset, parentY + yOffset); parentNode.getChildNodes().add(childLayout); // recurse this.createTreeLayoutRecursive( childLayout, radiansPerLeaf, cumulativeLeavesUsed); cumulativeLeavesUsed += currChildLeaves; } } /** * Find the tree nodes that are farthest apart * @param tree * the tree to search through * @return * the most distant pair or null if there are less than * two nodes */ private VisualTreeNode[] getMostDistantNodePair(VisualTreeNode tree) { List<VisualTreeNode> leaves = this.getTreeLayoutLeaves(tree); // TODO there may be a faster way to do this VisualTreeNode[] mostDistantPair = null; double greatestDistance = -1.0; int leafCount = leaves.size(); for(int i = 0; i < leafCount; i++) { for(int j = i + 1; j < leafCount; j++) { double currDistance = leaves.get(i).getPosition().distance( leaves.get(j).getPosition()); if(currDistance > greatestDistance) { greatestDistance = currDistance; mostDistantPair = new VisualTreeNode[] { leaves.get(i), leaves.get(j)}; } } } return mostDistantPair; } /** * Get all of the leaves in the tree layout (including the tree itself if * it is a leaf ignoring directionality * @param treeNode * the tree * @return * the leaves */ private List<VisualTreeNode> getTreeLayoutLeaves(VisualTreeNode treeNode) { List<VisualTreeNode> leaves = new ArrayList<VisualTreeNode>(); this.getTreeLayoutLeavesRecursive(treeNode, leaves); // since directionality doesn't matter we need to check if the // root is a leaf too if(treeNode.getChildNodes().size() == 1) { leaves.add(treeNode); } return leaves; } /** * Recursively get leaf nodes * @param treeNode * the node to recurse into * @param leaves * the leaves to add to */ private void getTreeLayoutLeavesRecursive( VisualTreeNode treeNode, List<VisualTreeNode> leaves) { for(VisualTreeNode childNode: treeNode.getChildNodes()) { if(childNode.getChildNodes().isEmpty()) { leaves.add(childNode); } else { this.getTreeLayoutLeavesRecursive( childNode, leaves); } } } /** * An class for positioning tree nodes */ private static final class VisualTreeNode { private final PhylogenyTreeNode phylogenyTreeNode; private Point2D.Double position = new Point2D.Double(); private List<VisualTreeNode> childNodes = new ArrayList<VisualTreeNode>(); public VisualTreeNode(PhylogenyTreeNode phylogenyTreeNode) { this.phylogenyTreeNode = phylogenyTreeNode; } public List<VisualTreeNode> getChildNodes() { return this.childNodes; } public Point2D.Double getPosition() { return this.position; } public void setPosition(Point2D.Double position) { this.position = position; } public PhylogenyTreeNode getPhylogenyTreeNode() { return this.phylogenyTreeNode; } } /** * Create a test tree * @return * the test tree */ @SuppressWarnings("all") protected static PhylogenyTreeNode createTestTree() { PhylogenyTreeNode phylogenyTree = new PhylogenyTreeNode(); phylogenyTree.getStrains().add("parent"); PhylogenyTreeNode child = new PhylogenyTreeNode(); child.getStrains().add("child strain1"); PhylogenyTreeEdge phylogenyTreeEdge = new PhylogenyTreeEdge( new BitSet(0), child, 1.0); phylogenyTree.getChildEdges().add(phylogenyTreeEdge); PhylogenyTreeNode child2 = new PhylogenyTreeNode(); // child2.getStrains().add("child strain2"); PhylogenyTreeEdge phylogenyTreeEdge2 = new PhylogenyTreeEdge( new BitSet(0), child2, 1.0); phylogenyTree.getChildEdges().add(phylogenyTreeEdge2); PhylogenyTreeNode child3 = new PhylogenyTreeNode(); child3.getStrains().add("child strain3"); PhylogenyTreeEdge phylogenyTreeEdge3 = new PhylogenyTreeEdge( new BitSet(0), child3, 1.0); phylogenyTree.getChildEdges().add(phylogenyTreeEdge3); PhylogenyTreeNode child4 = new PhylogenyTreeNode(); child4.getStrains().add("child strain4"); PhylogenyTreeEdge phylogenyTreeEdge4 = new PhylogenyTreeEdge( new BitSet(0), child4, 1.0); child3.getChildEdges().add(phylogenyTreeEdge4); PhylogenyTreeNode child5 = new PhylogenyTreeNode(); child5.getStrains().add("child strain5"); PhylogenyTreeEdge phylogenyTreeEdge5 = new PhylogenyTreeEdge( new BitSet(0), child5, 1.0); child3.getChildEdges().add(phylogenyTreeEdge5); PhylogenyTreeNode child8 = null; // for(int i = 0; i < 12; i++) for(int i = 0; i < 6; i++) { child8 = new PhylogenyTreeNode(); child8.getStrains().add("child strain6." + i); PhylogenyTreeEdge phylogenyTreeEdge8 = new PhylogenyTreeEdge( new BitSet(0), child8, 1.0); child2.getChildEdges().add(phylogenyTreeEdge8); } // for(int i = 0; i < 15; i++) for(int i = 0; i < 10; i++) { PhylogenyTreeNode child9 = new PhylogenyTreeNode(); child9.getStrains().add("child strain7." + i); PhylogenyTreeEdge phylogenyTreeEdge8 = new PhylogenyTreeEdgeWithRealValue( new BitSet(0), child9, 1.0, Math.random()); child8.getChildEdges().add(phylogenyTreeEdge8); for(int j = 0; j < 10; j++) { child9.getStrains().add("strain8." + j); } } return phylogenyTree; } /** * A tester main * @param args * don't care */ @SuppressWarnings("all") public static void main(String[] args) { final PhylogenyTreeImageFactory colorFactory = new SimplePhylogenyTreeImageFactory( new SmoothPaintScale( 0.0, 1.0, Color.BLUE, Color.RED)); JPanel colorTreePanel = new JPanel() { /** * {@inheritDoc} */ @Override protected void paintComponent(Graphics g) { BufferedImage image = colorFactory.createPhylogenyImage( SimplePhylogenyTreeImageFactory.createTestTree(), this.getWidth(), this.getHeight()); g.drawImage(image, 0, 0, this); } }; final PhylogenyTreeImageFactory noColorFactory = new SimplePhylogenyTreeImageFactory(); JPanel noColorTreePanel = new JPanel() { /** * {@inheritDoc} */ @Override protected void paintComponent(Graphics g) { BufferedImage image = noColorFactory.createPhylogenyImage( SimplePhylogenyTreeImageFactory.createTestTree(), this.getWidth(), this.getHeight()); g.drawImage(image, 0, 0, this); } }; JFrame treeFrame = new JFrame(); treeFrame.getContentPane().setLayout(new GridLayout()); treeFrame.getContentPane().add(colorTreePanel); treeFrame.getContentPane().add(noColorTreePanel); treeFrame.setVisible(true); } }
gpl-3.0
ngcurrier/ProteusCFD
TPLs/hdf5/hdf5-1.10.2/java/test/TestH5G.java
18531
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the COPYING file, which can be found at the root of the source code * * distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. * * If you do not have access to either file, you may request a copy from * * help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import hdf.hdf5lib.H5; import hdf.hdf5lib.HDF5Constants; import hdf.hdf5lib.exceptions.HDF5LibraryException; import hdf.hdf5lib.structs.H5G_info_t; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; public class TestH5G { @Rule public TestName testname = new TestName(); private static final String H5_FILE = "test.h5"; private static final String H5_FILE2 = "test2.h5"; private static final String[] GROUPS = { "/G1", "/G1/G11", "/G1/G12", "/G1/G11/G111", "/G1/G11/G112", "/G1/G11/G113", "/G1/G11/G114" }; private static final String[] GROUPS2 = { "/G1", "/G1/G14", "/G1/G12", "/G1/G13", "/G1/G11"}; long H5fid = -1; long H5fid2 = -1; private final long _createGroup(long fid, String name) { long gid = -1; try { gid = H5.H5Gcreate(fid, name, HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT); } catch (Throwable err) { err.printStackTrace(); fail("H5.H5Gcreate: " + err); } assertTrue("TestH5G._createGroup: ", gid > 0); return gid; } private final long _createGroup2(long fid, String name) { long gid = -1; long gcpl = -1; try { gcpl = H5.H5Pcreate(HDF5Constants.H5P_GROUP_CREATE); //create gcpl } catch (final Exception ex) { fail("H5.H5Pcreate(): " + ex); } assertTrue("TestH5G._createGroup2: ", gcpl >= 0); try { H5.H5Pset_link_creation_order(gcpl, HDF5Constants.H5P_CRT_ORDER_TRACKED + HDF5Constants.H5P_CRT_ORDER_INDEXED); // Set link creation order } catch (final Exception ex) { try {H5.H5Pclose(gcpl);} catch (final Exception exx) {} fail("H5.H5Pset_link_creation_order: " + ex); } try { gid = H5.H5Gcreate(fid, name, HDF5Constants.H5P_DEFAULT, gcpl, HDF5Constants.H5P_DEFAULT); } catch (Throwable err) { err.printStackTrace(); fail("H5.H5Gcreate: " + err); } finally { try {H5.H5Pclose(gcpl);} catch (final Exception ex) {} } assertTrue("TestH5G._createGroup2: ", gid > 0); return gid; } private final long _openGroup(long fid, String name) { long gid = -1; try { gid = H5.H5Gopen(fid, name, HDF5Constants.H5P_DEFAULT); } catch (Throwable err) { gid = -1; err.printStackTrace(); fail("H5.H5Gopen: " + err); } assertTrue("TestH5G._openGroup: ", gid > 0); return gid; } private final void _deleteFile(String filename) { File file = new File(filename); if (file.exists()) { try {file.delete();} catch (SecurityException e) {} } } @Before public void createH5file() throws HDF5LibraryException, NullPointerException { assertTrue("H5 open ids is 0",H5.getOpenIDCount()==0); System.out.print(testname.getMethodName()); try { H5fid = H5.H5Fcreate(H5_FILE, HDF5Constants.H5F_ACC_TRUNC, HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT); H5fid2 = H5.H5Fcreate(H5_FILE2, HDF5Constants.H5F_ACC_TRUNC, HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.createH5file: " + err); } assertTrue("TestH5G.createH5file: H5.H5Fcreate: ", H5fid > 0); assertTrue("TestH5G.createH5file: H5.H5Fcreate: ", H5fid2 > 0); long gid = -1; for (int i = 0; i < GROUPS.length; i++) { gid = _createGroup(H5fid, GROUPS[i]); try {H5.H5Gclose(gid);} catch (Exception ex) {} } for (int i = 0; i < GROUPS2.length; i++) { gid = _createGroup2(H5fid2, GROUPS2[i]); try {H5.H5Gclose(gid);} catch (Exception ex) {} } H5.H5Fflush(H5fid, HDF5Constants.H5F_SCOPE_LOCAL); H5.H5Fflush(H5fid2, HDF5Constants.H5F_SCOPE_LOCAL); } @After public void deleteH5file() throws HDF5LibraryException { if (H5fid > 0) { try {H5.H5Fclose(H5fid);} catch (Exception ex) {} } if (H5fid2 > 0) { try {H5.H5Fclose(H5fid2);} catch (Exception ex) {} } _deleteFile(H5_FILE); _deleteFile(H5_FILE2); System.out.println(); } @Test public void testH5Gopen() { long gid = -1; for (int i = 0; i < GROUPS.length; i++) { try { gid = H5.H5Gopen(H5fid, GROUPS[i], HDF5Constants.H5P_DEFAULT); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gopen: H5.H5Gopen: " + err); } assertTrue("TestH5G.testH5Gopen: ", gid > 0); try { H5.H5Gclose(gid); } catch (Exception ex) { } } } @Test public void testH5Gget_create_plist() { long gid = -1; long pid = -1; for (int i = 0; i < GROUPS.length; i++) { try { gid = H5.H5Gopen(H5fid, GROUPS[i], HDF5Constants.H5P_DEFAULT); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_create_plist: H5.H5Gopen: " + err); } assertTrue("TestH5G.testH5Gget_create_plist: ", gid > 0); try { pid = H5.H5Gget_create_plist(gid); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_create_plist: H5.H5Gget_create_plist: " + err); } assertTrue("TestH5G.testH5Gget_create_plist: ", pid > 0); try { H5.H5Gclose(gid); } catch (Exception ex) { } } } @Test public void testH5Gget_info() { H5G_info_t info = null; for (int i = 0; i < GROUPS.length; i++) { try { info = H5.H5Gget_info(H5fid); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_info: H5.H5Gget_info: " + err); } assertNotNull("TestH5G.testH5Gget_info: ", info); } } @Test public void testH5Gget_info_by_name() { H5G_info_t info = null; for (int i = 0; i < GROUPS.length; i++) { try { info = H5.H5Gget_info_by_name(H5fid, GROUPS[i], HDF5Constants.H5P_DEFAULT); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_info_by_name: H5.H5Gget_info_by_name: " + err); } assertNotNull("TestH5G.testH5Gget_info_by_name: ", info); } } @Test public void testH5Gget_info_by_idx() { H5G_info_t info = null; for (int i = 0; i < 2; i++) { try { info = H5.H5Gget_info_by_idx(H5fid, "/G1", HDF5Constants.H5_INDEX_NAME, HDF5Constants.H5_ITER_INC, i, HDF5Constants.H5P_DEFAULT); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_info_by_idx: H5.H5Gget_info_by_idx: " + err); } assertNotNull("TestH5G.testH5Gget_info_by_idx: ", info); } } @Test public void testH5Gget_obj_info_all() { H5G_info_t info = null; long gid = _openGroup(H5fid, GROUPS[0]); try { info = H5.H5Gget_info(gid); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_obj_info_all: H5.H5Gget_info: " + err); } finally { try {H5.H5Gclose(gid);} catch (Exception ex) { } } assertNotNull("TestH5G.testH5Gget_obj_info_all: ", info); assertTrue("TestH5G.testH5Gget_obj_info_all: number of links is empty", info.nlinks > 0); String objNames[] = new String[(int) info.nlinks]; int objTypes[] = new int[(int) info.nlinks]; int lnkTypes[] = new int[(int) info.nlinks]; long objRefs[] = new long[(int) info.nlinks]; int names_found = 0; try { names_found = H5.H5Gget_obj_info_all(H5fid, GROUPS[0], objNames, objTypes, lnkTypes, objRefs, HDF5Constants.H5_INDEX_NAME); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_obj_info_all: H5.H5Gget_obj_info_all: " + err); } assertTrue("number found[" + names_found + "] different than expected[" + objNames.length + "]", names_found == objNames.length); for (int i = 0; i < objNames.length; i++) { assertNotNull("name #" + i + " does not exist", objNames[i]); assertTrue("TestH5G.testH5Gget_obj_info_all: ", objNames[i].length() > 0); } } @Test public void testH5Gget_obj_info_all_gid() { H5G_info_t info = null; long gid = _openGroup(H5fid, GROUPS[0]); try { info = H5.H5Gget_info(gid); assertNotNull("TestH5G.testH5Gget_obj_info_all_gid: ", info); assertTrue("TestH5G.testH5Gget_obj_info_all_gid: number of links is empty", info.nlinks > 0); String objNames[] = new String[(int) info.nlinks]; long objRefs[] = new long[(int) info.nlinks]; int lnkTypes[] = new int[(int) info.nlinks]; int objTypes[] = new int[(int) info.nlinks]; int names_found = 0; try { names_found = H5.H5Gget_obj_info_all(gid, null, objNames, objTypes, lnkTypes, objRefs, HDF5Constants.H5_INDEX_NAME); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_obj_info_all_gid: H5.H5Gget_obj_info_all: " + err); } assertTrue("TestH5G.testH5Gget_obj_info_all_gid: number found[" + names_found + "] different than expected[" + objNames.length + "]", names_found == objNames.length); for (int i = 0; i < objNames.length; i++) { assertNotNull("TestH5G.testH5Gget_obj_info_all_gid: name #" + i + " does not exist", objNames[i]); assertTrue("TestH5G.testH5Gget_obj_info_all_gid: ", objNames[i].length() > 0); } } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_obj_info_all_gid: H5.H5Gget_info: " + err); } finally { try {H5.H5Gclose(gid);} catch (Exception ex) { } } } @Test public void testH5Gget_obj_info_all_gid2() { H5G_info_t info = null; long gid = _openGroup(H5fid, GROUPS[1]); try { info = H5.H5Gget_info(gid); assertNotNull("TestH5G.testH5Gget_obj_info_all_gid2: ", info); assertTrue("TestH5G.testH5Gget_obj_info_all_gid2: number of links is empty", info.nlinks > 0); String objNames[] = new String[(int) info.nlinks]; long objRefs[] = new long[(int) info.nlinks]; int lnkTypes[] = new int[(int) info.nlinks]; int objTypes[] = new int[(int) info.nlinks]; int names_found = 0; try { names_found = H5.H5Gget_obj_info_all(gid, null, objNames, objTypes, lnkTypes, objRefs, HDF5Constants.H5_INDEX_NAME); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_obj_info_all_gid2: H5.H5Gget_obj_info_all: " + err); } assertTrue("TestH5G.testH5Gget_obj_info_all_gid2: number found[" + names_found + "] different than expected[" + objNames.length + "]", names_found == objNames.length); for (int i = 0; i < objNames.length; i++) { assertNotNull("TestH5G.testH5Gget_obj_info_all_gid2: name #" + i + " does not exist", objNames[i]); assertTrue("TestH5G.testH5Gget_obj_info_all_gid2: ", objNames[i].length() > 0); } } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_obj_info_all_gid2: H5.H5Gget_info: " + err); } finally { try {H5.H5Gclose(gid);} catch (Exception ex) { } } } @Test public void testH5Gget_obj_info_max() { long gid = _openGroup(H5fid, GROUPS[0]); long groups_max_size = GROUPS.length + 1; String objNames[] = new String[(int)groups_max_size]; int objTypes[] = new int[(int)groups_max_size]; int lnkTypes[] = new int[(int)groups_max_size]; long objRefs[] = new long[(int)groups_max_size]; int names_found = 0; try { names_found = H5.H5Gget_obj_info_max(gid, objNames, objTypes, lnkTypes, objRefs, groups_max_size); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_obj_info_max: H5.H5Gget_obj_info_max: " + err); } finally { try {H5.H5Gclose(gid);} catch (Exception ex) { } } // expected number does not include root group assertTrue("TestH5G.testH5Gget_obj_info_max: number found[" + names_found + "] different than expected[" + (GROUPS.length - 1) + "]", names_found == (GROUPS.length - 1)); for (int i = 0; i < GROUPS.length-1; i++) { assertNotNull("TestH5G.testH5Gget_obj_info_max: name #"+i+" does not exist",objNames[i]); assertTrue("TestH5G.testH5Gget_obj_info_max: ", objNames[i].length()>0); } } @Test public void testH5Gget_obj_info_max_limit() { long gid = _openGroup(H5fid, GROUPS[0]); long groups_max_size = GROUPS.length - 3; String objNames[] = new String[(int)groups_max_size]; int objTypes[] = new int[(int)groups_max_size]; int lnkTypes[] = new int[(int)groups_max_size]; long objRefs[] = new long[(int)groups_max_size]; int names_found = 0; try { names_found = H5.H5Gget_obj_info_max(gid, objNames, objTypes, lnkTypes, objRefs, groups_max_size); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_obj_info_max_limit: H5.H5Gget_obj_info_max: " + err); } finally { try {H5.H5Gclose(gid);} catch (Exception ex) { } } assertTrue("TestH5G.testH5Gget_obj_info_max_limit: number found[" + names_found + "] different than expected[" + groups_max_size + "]", names_found == groups_max_size); for (int i = 0; i < objNames.length; i++) { assertNotNull("TestH5G.testH5Gget_obj_info_max_limit: name #" + i + " does not exist", objNames[i]); assertTrue("TestH5G.testH5Gget_obj_info_max_limit: ", objNames[i].length() > 0); } } @Test public void testH5Gget_obj_info_all_byIndexType() { H5G_info_t info = null; long gid = _openGroup(H5fid2, GROUPS2[0]); try { info = H5.H5Gget_info(gid); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_obj_info_all_byIndexType: H5.H5Gget_info: " + err); } finally { try {H5.H5Gclose(gid);} catch (Exception ex) { } } assertNotNull("TestH5G.testH5Gget_obj_info_all_byIndexType: ", info); assertTrue("TestH5G.testH5Gget_obj_info_all_byIndexType: number of links is empty", info.nlinks > 0); String objNames[] = new String[(int) info.nlinks]; int objTypes[] = new int[(int) info.nlinks]; int lnkTypes[] = new int[(int) info.nlinks]; long objRefs[] = new long[(int) info.nlinks]; try { H5.H5Gget_obj_info_all(H5fid2, GROUPS2[0], objNames, objTypes, lnkTypes, objRefs, HDF5Constants.H5_INDEX_CRT_ORDER); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_obj_info_all_byIndexType: H5.H5Gget_obj_info_all: " + err); } assertEquals("G12",objNames[1]); assertEquals("G13", objNames[2] ); assertEquals("G11", objNames[3] ); try { H5.H5Gget_obj_info_all(H5fid2, GROUPS2[0], objNames, objTypes, lnkTypes, objRefs, HDF5Constants.H5_INDEX_NAME); } catch (Throwable err) { err.printStackTrace(); fail("TestH5G.testH5Gget_obj_info_all_byIndexType: H5.H5Gget_obj_info_all: " + err); } assertEquals("G12",objNames[1]); assertEquals("G13", objNames[2] ); assertEquals("G14", objNames[3] ); } }
gpl-3.0
AdeebNqo/Thula
Thula/src/main/java/com/adeebnqo/Thula/ui/popup/QKReplyActivity.java
11836
package com.adeebnqo.Thula.ui.popup; import android.app.LoaderManager; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.adeebnqo.Thula.R; import com.adeebnqo.Thula.data.Conversation; import com.adeebnqo.Thula.data.ConversationLegacy; import com.adeebnqo.Thula.data.Message; import com.adeebnqo.Thula.interfaces.ActivityLauncher; import com.adeebnqo.Thula.service.CopyUnreadMessageTextService; import com.adeebnqo.Thula.service.DeleteUnreadMessageService; import com.adeebnqo.Thula.common.utils.CursorUtils; import com.adeebnqo.Thula.common.utils.KeyboardUtils; import com.adeebnqo.Thula.transaction.SmsHelper; import com.adeebnqo.Thula.ui.MainActivity; import com.adeebnqo.Thula.ui.base.QKActivity; import com.adeebnqo.Thula.ui.base.QKPopupActivity; import com.adeebnqo.Thula.ui.messagelist.MessageColumns; import com.adeebnqo.Thula.ui.messagelist.MessageListAdapter; import com.adeebnqo.Thula.ui.view.ComposeView; import com.adeebnqo.Thula.ui.view.MessageListRecyclerView; import com.adeebnqo.Thula.ui.view.WrappingLinearLayoutManager; import com.adeebnqo.Thula.ui.welcome.DemoConversationCursorLoader; public class QKReplyActivity extends QKActivity implements DialogInterface.OnDismissListener, LoaderManager.LoaderCallbacks<Cursor>, ActivityLauncher, ComposeView.OnSendListener { @SuppressWarnings("unused") private String TAG = "QKReplyActivity"; // Intent extras for configuring a QuickReplyActivity intent public static final String EXTRA_THREAD_ID = "thread_id"; public static final String EXTRA_SHOW_KEYBOARD = "open_keyboard"; public static boolean sIsShowing = false; public static long sThreadId; private Conversation mConversation; private ConversationLegacy mConversationLegacy; private Cursor mCursor; private boolean mShowUnreadOnly = true; private MessageListRecyclerView mRecyclerView; private WrappingLinearLayoutManager mLayoutManager; private MessageListAdapter mAdapter; private ComposeView mComposeView; /** * True if we're starting an activity. This will let us know whether or not we should finish() * in onPause(). */ private boolean mIsStartingActivity = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutResource()); Bundle extras = getIntent().getExtras(); mConversation = Conversation.get(this, extras.getLong(EXTRA_THREAD_ID), false); mConversationLegacy = new ConversationLegacy(this, extras.getLong(EXTRA_THREAD_ID)); // Set up the compose view. mComposeView = (ComposeView) findViewById(R.id.compose_view); mComposeView.setActivityLauncher(this); mComposeView.setOnSendListener(this); mComposeView.setLabel("QKReply"); mComposeView.refresh(); mLayoutManager = new WrappingLinearLayoutManager(this); mLayoutManager.setStackFromEnd(true); mAdapter = new MessageListAdapter(this); mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onChanged() { LinearLayoutManager manager = (LinearLayoutManager) mRecyclerView.getLayoutManager(); int position = CursorUtils.isValid(mCursor) && mCursor.getCount() > 0 ? mCursor.getCount() - 1 : 0; manager.smoothScrollToPosition(mRecyclerView, null, position); } }); mRecyclerView = (MessageListRecyclerView) findViewById(R.id.popup_messages); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.setAdapter(mAdapter); // Disable the compose view for the welcome screen (so that they can't send texts to nobody) if (extras.getLong(EXTRA_THREAD_ID) == DemoConversationCursorLoader.THREAD_ID_WELCOME_SCREEN) { String sendingBlockedMessage = getString(R.string.sending_blocked_welcome_screen_message); mComposeView.setSendingBlocked(sendingBlockedMessage); } // Set the conversation data objects. These are used to save drafts, send sms messages, etc. mComposeView.onOpenConversation(mConversation, mConversationLegacy); // If the user has the "show keyboard" for popups option enabled, show the keyboard here by // requesting the focus on the reply text. if (extras.getBoolean(EXTRA_SHOW_KEYBOARD, false)) { mComposeView.requestReplyTextFocus(); } new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { mConversationLegacy.getName(true); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); // FIXME if (sThreadId == DemoConversationCursorLoader.THREAD_ID_WELCOME_SCREEN) { setTitle("QKSMS"); } else { setTitle(mConversationLegacy.getName(true)); } initLoaderManager(); } }.execute((Void[]) null); } protected int getLayoutResource() { return R.layout.activity_qkreply; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.qkreply, menu); return super.onCreateOptionsMenu(menu); } private void switchView() { mShowUnreadOnly = !mShowUnreadOnly; getLoaderManager().restartLoader(0, null, this); } private void initLoaderManager() { getLoaderManager().initLoader(0, null, this); } @Override protected void onPause() { super.onPause(); KeyboardUtils.hide(this, mComposeView); mComposeView.saveDraft(); sIsShowing = false; sThreadId = 0; // When the home button is pressed, this ensures that the QK Reply is shut down // Don't shut it down if it pauses and the screen is off though if (!mIsStartingActivity && !isChangingConfigurations() && isScreenOn()) { finish(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); boolean handledByComposeView = mComposeView.onActivityResult(requestCode, resultCode, data); if (!handledByComposeView) { // ... } } @Override protected void onResume() { super.onResume(); sIsShowing = true; sThreadId = mConversationLegacy.getThreadId(); mIsStartingActivity = false; } @Override public void finish() { // Override pending transitions so that we don't see black for a second when QuickReply // closes super.finish(); overridePendingTransition(0, 0); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_fold: switchView(); if (mShowUnreadOnly) { item.setIcon(R.drawable.ic_unfold); item.setTitle(R.string.menu_show_all); } else { item.setIcon(R.drawable.ic_fold); item.setTitle(R.string.menu_show_unread); } return true; case R.id.menu_open_thread: Intent threadIntent = new Intent(this, MainActivity.class); threadIntent.putExtra(MainActivity.EXTRA_THREAD_ID, mConversationLegacy.getThreadId()); startActivity(threadIntent); finish(); return true; case R.id.menu_call: Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:" + mConversationLegacy.getAddress())); startActivity(callIntent); return true; case R.id.menu_mark_read: mConversationLegacy.markRead(); finish(); return true; case R.id.menu_delete: Intent intent = new Intent(this, DeleteUnreadMessageService.class); intent.putExtra(DeleteUnreadMessageService.EXTRA_THREAD_URI, mConversation.getUri()); startService(intent); finish(); return true; case R.id.menu_copy: Intent copyIntent = new Intent(this, CopyUnreadMessageTextService.class); copyIntent.putExtra(DeleteUnreadMessageService.EXTRA_THREAD_URI, mConversation.getUri()); startService(copyIntent); return true; case R.id.menu_forward: Intent forwardIntent = new Intent(this, QKComposeActivity.class); forwardIntent.putExtra("sms_body", SmsHelper.getUnreadMessageText(this, mConversation.getUri())); startActivity(forwardIntent); finish(); return true; } return super.onOptionsItemSelected(item); } @Override public void onDismiss(DialogInterface dialog) { finish(); } public Loader<Cursor> onCreateLoader(int id, Bundle args) { String selection = mShowUnreadOnly ? SmsHelper.UNREAD_SELECTION : null; if (sThreadId == DemoConversationCursorLoader.THREAD_ID_WELCOME_SCREEN) { return new DemoConversationCursorLoader(this, sThreadId, selection); } else { return new CursorLoader(this, Uri.withAppendedPath(Message.MMS_SMS_CONTENT_PROVIDER, "" + mConversationLegacy.getThreadId()), MessageColumns.PROJECTION, selection, null, "normalized_date ASC"); } } public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (mAdapter != null) { mAdapter.changeCursor(data); } mCursor = data; mRecyclerView.scrollToPosition(CursorUtils.isValid(mCursor) && mCursor.getCount() > 0 ? mCursor.getCount() - 1 : 0); } public void onLoaderReset(Loader<Cursor> loader) { if (mAdapter != null) { mAdapter.changeCursor(null); } mCursor = null; } public static void close() { System.exit(0); } @Override public void onSend(String[] addresses, String body) { // When we send an SMS, mark the conversation as read, and close the quick reply activity. if (mConversation != null) { mConversation.markAsRead(); } if (mConversationLegacy != null) { mConversationLegacy.markRead(); } finish(); } /** * Launches an activity with the given request code. * <p/> * Note: The `ActivityLauncher` interface exposes this method for views (such as ComposeView) * to use. */ @Override public void startActivityForResult(Intent intent, int requestCode) { super.startActivityForResult(intent, requestCode); mIsStartingActivity = true; // 0 for the exit anim so that the dialog appears to not fade out while you're choosing an // attachment. overridePendingTransition(R.anim.abc_fade_in, 0); } }
gpl-3.0
jefalbino/jsmartdb-test
src/test/java/entity/Epsilon.java
3082
/* * JSmartDB - Java ORM Framework * Copyright (c) 2014, Jeferson Albino da Silva, All rights reserved. * * This library 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.0 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. */ package entity; import java.math.BigDecimal; import java.util.Set; import com.jsmartdb.framework.types.CascadeType; import com.jsmartdb.framework.types.JoinType; import com.jsmartdb.framework.annotation.Column; import com.jsmartdb.framework.annotation.Id; import com.jsmartdb.framework.annotation.Join; import com.jsmartdb.framework.annotation.OneToMany; import com.jsmartdb.framework.annotation.Table; import com.jsmartdb.framework.manager.Entity; @Table(name = "epsilon") public class Epsilon extends Entity { @Id(name = "id", generated = true) private Integer id; @Column(name = "strng", length = 45) private String string; @Column(name = "txt", length = Column.NO_LENGTH) private String text; @Column(name = "intgr") private Integer integer; @Column(name = "lng") private Long longi; @Column(name = "flt") private Float floati; @Column(name = "dbl") private Double doubli; @Column(name = "bl") private Boolean bool; @Column(name = "dcml") private BigDecimal decimal; @OneToMany(join = @Join(type = JoinType.LEFT_OUTER_JOIN), cascade = {CascadeType.INSERT, CascadeType.UPDATE, CascadeType.DELETE}) private Set<Iota> iotas; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getString() { return string; } public void setString(String string) { this.string = string; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Integer getInteger() { return integer; } public void setInteger(Integer integer) { this.integer = integer; } public Long getLongi() { return longi; } public void setLongi(Long longi) { this.longi = longi; } public Float getFloati() { return floati; } public void setFloati(Float floati) { this.floati = floati; } public Double getDoubli() { return doubli; } public void setDoubli(Double doubli) { this.doubli = doubli; } public Boolean getBool() { return bool; } public void setBool(Boolean bool) { this.bool = bool; } public BigDecimal getDecimal() { return decimal; } public void setDecimal(BigDecimal decimal) { this.decimal = decimal; } public Set<Iota> getIotas() { return iotas; } public void setIotas(Set<Iota> iotas) { this.iotas = iotas; } }
gpl-3.0
XFactHD/RFUtilities
1.10.2/src/main/java/XFactHD/rfutilities/common/utils/capability/forge/RFUEnergyHandlerDiode.java
1642
/* Copyright (C) <2016> <XFactHD> 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 XFactHD.rfutilities.common.utils.capability.forge; import XFactHD.rfutilities.common.blocks.tileEntity.TileEntityDiode; import net.minecraftforge.energy.IEnergyStorage; public class RFUEnergyHandlerDiode implements IEnergyStorage { private TileEntityDiode diode; public RFUEnergyHandlerDiode(TileEntityDiode diode) { this.diode = diode; } @Override public int receiveEnergy(int maxReceive, boolean simulate) { return diode.transferEnergy(maxReceive, simulate); } @Override public int extractEnergy(int maxExtract, boolean simulate) { return 0; } @Override public int getEnergyStored() { return 0; } @Override public int getMaxEnergyStored() { return 0; } @Override public boolean canExtract() { return false; } @Override public boolean canReceive() { return true; } }
gpl-3.0
obulpathi/java
deitel/ch31/Blackjack/src/java/com/deitel/blackjack/Blackjack.java
4187
// Fig. 31.17: Blackjack.java // Blackjack web service that deals cards and evaluates hands package com.deitel.blackjack; import com.sun.xml.ws.developer.servlet.HttpSessionScope; import java.util.ArrayList; import java.util.Random; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; @HttpSessionScope // enable web service to maintain session state @WebService() public class Blackjack { private ArrayList< String > deck; // deck of cards for one user session private static final Random randomObject = new Random(); // deal one card @WebMethod( operationName = "dealCard" ) public String dealCard() { String card = ""; card = deck.get( 0 ); // get top card of deck deck.remove( 0 ); // remove top card of deck return card; } // end WebMethod dealCard // shuffle the deck @WebMethod( operationName = "shuffle" ) public void shuffle() { // create new deck when shuffle is called deck = new ArrayList< String >(); // populate deck of cards for ( int face = 1; face <= 13; face++ ) // loop through faces for ( int suit = 0; suit <= 3; suit++ ) // loop through suits deck.add( face + " " + suit ); // add each card to deck String tempCard; // holds card temporarily durring swapping int index; // index of randomly selected card for ( int i = 0; i < deck.size() ; i++ ) // shuffle { index = randomObject.nextInt( deck.size() - 1 ); // swap card at position i with randomly selected card tempCard = deck.get( i ); deck.set( i, deck.get( index ) ); deck.set( index, tempCard ); } // end for } // end WebMethod shuffle // determine a hand's value @WebMethod( operationName = "getHandValue" ) public int getHandValue( @WebParam( name = "hand" ) String hand ) { // split hand into cards String[] cards = hand.split( "\t" ); int total = 0; // total value of cards in hand int face; // face of current card int aceCount = 0; // number of aces in hand for ( int i = 0; i < cards.length; i++ ) { // parse string and get first int in String face = Integer.parseInt( cards[ i ].substring( 0, cards[ i ].indexOf( " " ) ) ); switch ( face ) { case 1: // in ace, increment aceCount ++aceCount; break; case 11: // jack case 12: // queen case 13: // king total += 10; break; default: // otherwise, add face total += face; break; } // end switch } // end for // calculate optimal use of aces if ( aceCount > 0 ) { // if possible, count one ace as 11 if ( total + 11 + aceCount - 1 <= 21 ) total += 11 + aceCount - 1; else // otherwise, count all aces as 1 total += aceCount; } // end if return total; } // end WebMethod getHandValue } // end class Blackjack /************************************************************************** * (C) Copyright 1992-2012 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
gpl-3.0
akardapolov/ASH-Viewer
jfreechart-fse/src/test/java/org/jfree/chart/block/GridArrangementTest.java
10671
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2012, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * GridArrangementTests.java * ------------------------- * (C) Copyright 2005-2012, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 08-Mar-2005 : Version 1 (DG); * 03-Dec-2008 : Added more tests (DG); * 17-Jun-2012 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.block; import org.jfree.chart.ui.Size2D; import org.jfree.data.Range; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * Tests for the {@link GridArrangement} class. */ public class GridArrangementTest { /** * Confirm that the equals() method can distinguish all the required fields. */ @Test public void testEquals() { GridArrangement f1 = new GridArrangement(11, 22); GridArrangement f2 = new GridArrangement(11, 22); assertEquals(f1, f2); assertEquals(f2, f1); f1 = new GridArrangement(33, 22); assertFalse(f1.equals(f2)); f2 = new GridArrangement(33, 22); assertEquals(f1, f2); f1 = new GridArrangement(33, 44); assertFalse(f1.equals(f2)); f2 = new GridArrangement(33, 44); assertEquals(f1, f2); } /** * Immutable - cloning is not necessary. */ @Test public void testCloning() throws CloneNotSupportedException { GridArrangement f1 = new GridArrangement(1, 2); assertFalse(f1 instanceof Cloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() throws IOException, ClassNotFoundException { GridArrangement f1 = new GridArrangement(33, 44); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(f1); out.close(); ObjectInput in = new ObjectInputStream(new ByteArrayInputStream( buffer.toByteArray())); GridArrangement f2 = (GridArrangement) in.readObject(); in.close(); assertEquals(f1, f2); } private static final double EPSILON = 0.000000001; /** * Test arrangement with no constraints. */ @Test public void testNN() { BlockContainer c = createTestContainer1(); Size2D s = c.arrange(null, RectangleConstraint.NONE); assertEquals(90.0, s.width, EPSILON); assertEquals(33.0, s.height, EPSILON); } /** * Test arrangement with a fixed width and no height constraint. */ @Test public void testFN() { BlockContainer c = createTestContainer1(); RectangleConstraint constraint = new RectangleConstraint(100.0, null, LengthConstraintType.FIXED, 0.0, null, LengthConstraintType.NONE); Size2D s = c.arrange(null, constraint); assertEquals(100.0, s.width, EPSILON); assertEquals(33.0, s.height, EPSILON); } /** * Test arrangement with a fixed height and no width constraint. */ @Test public void testNF() { BlockContainer c = createTestContainer1(); RectangleConstraint constraint = RectangleConstraint.NONE.toFixedHeight( 100.0); Size2D s = c.arrange(null, constraint); assertEquals(90.0, s.width, EPSILON); assertEquals(100.0, s.height, EPSILON); } /** * Test arrangement with a range for the width and a fixed height. */ @Test public void testRF() { BlockContainer c = createTestContainer1(); RectangleConstraint constraint = new RectangleConstraint(new Range(40.0, 60.0), 100.0); Size2D s = c.arrange(null, constraint); assertEquals(60.0, s.width, EPSILON); assertEquals(100.0, s.height, EPSILON); } /** * Test arrangement with a range for the width and height. */ @Test public void testRR() { BlockContainer c = createTestContainer1(); RectangleConstraint constraint = new RectangleConstraint(new Range(40.0, 60.0), new Range(50.0, 70.0)); Size2D s = c.arrange(null, constraint); assertEquals(60.0, s.width, EPSILON); assertEquals(50.0, s.height, EPSILON); } /** * Test arrangement with a range for the width and no height constraint. */ @Test public void testRN() { BlockContainer c = createTestContainer1(); RectangleConstraint constraint = RectangleConstraint.NONE.toRangeWidth( new Range(40.0, 60.0)); Size2D s = c.arrange(null, constraint); assertEquals(60.0, s.width, EPSILON); assertEquals(33.0, s.height, EPSILON); } /** * Test arrangement with a range for the height and no width constraint. */ @Test public void testNR() { BlockContainer c = createTestContainer1(); RectangleConstraint constraint = RectangleConstraint.NONE.toRangeHeight( new Range(40.0, 60.0)); Size2D s = c.arrange(null, constraint); assertEquals(90.0, s.width, EPSILON); assertEquals(40.0, s.height, EPSILON); } private BlockContainer createTestContainer1() { Block b1 = new EmptyBlock(10, 11); Block b2 = new EmptyBlock(20, 22); Block b3 = new EmptyBlock(30, 33); BlockContainer result = new BlockContainer(new GridArrangement(1, 3)); result.add(b1); result.add(b2); result.add(b3); return result; } /** * The arrangement should be able to handle null blocks in the layout. */ @Test public void testNullBlock_FF() { BlockContainer c = new BlockContainer(new GridArrangement(1, 1)); c.add(null); Size2D s = c.arrange(null, new RectangleConstraint(20, 10)); assertEquals(20.0, s.getWidth(), EPSILON); assertEquals(10.0, s.getHeight(), EPSILON); } /** * The arrangement should be able to handle null blocks in the layout. */ @Test public void testNullBlock_FN() { BlockContainer c = new BlockContainer(new GridArrangement(1, 1)); c.add(null); Size2D s = c.arrange(null, RectangleConstraint.NONE.toFixedWidth(10)); assertEquals(10.0, s.getWidth(), EPSILON); assertEquals(0.0, s.getHeight(), EPSILON); } /** * The arrangement should be able to handle null blocks in the layout. */ @Test public void testNullBlock_FR() { BlockContainer c = new BlockContainer(new GridArrangement(1, 1)); c.add(null); Size2D s = c.arrange(null, new RectangleConstraint(30.0, new Range(5.0, 10.0))); assertEquals(30.0, s.getWidth(), EPSILON); assertEquals(5.0, s.getHeight(), EPSILON); } /** * The arrangement should be able to handle null blocks in the layout. */ @Test public void testNullBlock_NN() { BlockContainer c = new BlockContainer(new GridArrangement(1, 1)); c.add(null); Size2D s = c.arrange(null, RectangleConstraint.NONE); assertEquals(0.0, s.getWidth(), EPSILON); assertEquals(0.0, s.getHeight(), EPSILON); } /** * The arrangement should be able to handle less blocks than grid spaces. */ @Test public void testGridNotFull_FF() { Block b1 = new EmptyBlock(5, 5); BlockContainer c = new BlockContainer(new GridArrangement(2, 3)); c.add(b1); Size2D s = c.arrange(null, new RectangleConstraint(200, 100)); assertEquals(200.0, s.getWidth(), EPSILON); assertEquals(100.0, s.getHeight(), EPSILON); } /** * The arrangement should be able to handle less blocks than grid spaces. */ @Test public void testGridNotFull_FN() { Block b1 = new EmptyBlock(5, 5); BlockContainer c = new BlockContainer(new GridArrangement(2, 3)); c.add(b1); Size2D s = c.arrange(null, RectangleConstraint.NONE.toFixedWidth(30.0)); assertEquals(30.0, s.getWidth(), EPSILON); assertEquals(10.0, s.getHeight(), EPSILON); } /** * The arrangement should be able to handle less blocks than grid spaces. */ @Test public void testGridNotFull_FR() { Block b1 = new EmptyBlock(5, 5); BlockContainer c = new BlockContainer(new GridArrangement(2, 3)); c.add(b1); Size2D s = c.arrange(null, new RectangleConstraint(30.0, new Range(5.0, 10.0))); assertEquals(30.0, s.getWidth(), EPSILON); assertEquals(10.0, s.getHeight(), EPSILON); } /** * The arrangement should be able to handle less blocks than grid spaces. */ @Test public void testGridNotFull_NN() { Block b1 = new EmptyBlock(5, 5); BlockContainer c = new BlockContainer(new GridArrangement(2, 3)); c.add(b1); Size2D s = c.arrange(null, RectangleConstraint.NONE); assertEquals(15.0, s.getWidth(), EPSILON); assertEquals(10.0, s.getHeight(), EPSILON); } }
gpl-3.0
luis-r-izquierdo/netlogo-fuzzy-logic-extension
fuzzy/src/tfg/fuzzy/primitives/creation/Gaussian.java
1677
package tfg.fuzzy.primitives.creation; import java.util.ArrayList; import java.util.List; import org.nlogo.api.Argument; import org.nlogo.api.Context; import org.nlogo.api.Reporter; import org.nlogo.api.ExtensionException; import org.nlogo.api.LogoException; import org.nlogo.core.LogoList; import org.nlogo.core.Syntax; import org.nlogo.core.SyntaxJ; import tfg.fuzzy.general.SupportFunctions; import tfg.fuzzy.sets.function.GaussianSet; /** * This class creates a new gaussian set. Implements the primitive * "gaussian-set". * * @author Marcos Almendres. * */ public class Gaussian implements Reporter { /** * This method tells Netlogo the appropriate syntax of the primitive. * Receives a list and returns a Wildcard. */ public Syntax getSyntax() { return SyntaxJ.reporterSyntax(new int[] { Syntax.ListType() }, Syntax.WildcardType()); } /** * This method respond to the call from Netlogo and returns the set. * * @param arg0 * Arguments from Netlogo call, in this case a list. * @param arg1 * Context of Netlogo when the call was done. * @return A new GaussianSet. */ @Override public Object report(Argument[] arg0, Context arg1) throws ExtensionException, LogoException { LogoList params = arg0[0].getList(); List<Double> resultParams = new ArrayList<Double>(); // Checks the format of the parameters double[] universe = SupportFunctions.LGEFormat(params, 3); // Add the parameters to a list resultParams.add((Double) params.first()); resultParams.add((Double) params.get(1)); // Create and return the new set return new GaussianSet(resultParams, true, "gaussian", universe); } }
gpl-3.0
physalix-enrollment/physalix
UserGui/src/main/java/hsa/awp/usergui/util/DraggablePrioListTarget.java
6272
/* * Copyright (c) 2010-2012 Matthias Klass, Johannes Leimer, * Rico Lieback, Sebastian Gabriel, Lothar Gesslein, * Alexander Rampp, Kai Weidner * * This file is part of the Physalix Enrollment System * * Foobar 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. * * Foobar 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ package hsa.awp.usergui.util; import hsa.awp.usergui.prioritylistselectors.AbstractPriorityListSelector; import hsa.awp.usergui.util.DragAndDrop.AbstractDropAndSortableBox; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.behavior.SimpleAttributeModifier; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.Panel; import org.wicketstuff.scriptaculous.dragdrop.DraggableTarget; /** * Priolistitem which can recieve items. * * @author basti */ public class DraggablePrioListTarget extends Panel { /** * generated UID. */ private static final long serialVersionUID = 1L; /** * reference to partent box. */ private AbstractDropAndSortableBox box; /** * draggableTarget which can recieve {@link DragableElement}. */ private DraggableTarget draggableTarget; /** * element which is hold by this container. */ private DragableElement element; /** * index of this slot in the priolist. */ private int index; private boolean isActive; /** * Constructor which creates a new instance. * * @param id wicket id * @param box reference to partent box. * @param index index of this slot in the priolist. */ public DraggablePrioListTarget(String id, AbstractDropAndSortableBox box, int index) { this(id, box, index, null); } /** * Constructor which creates a new instance. * * @param id wicket id * @param box reference to partent box. * @param index index of this slot in the priolist. * @param element element to display. */ public DraggablePrioListTarget(String id, AbstractDropAndSortableBox box, int index, DragableElement element) { this(id, box, index, element, true); } /** * Constructor which creates a new instance. * * @param id wicket id * @param box reference to partent box. * @param index index of this slot in the priolist. * @param element element to display. * @param isActive true if draggabiliy is given */ public DraggablePrioListTarget(String id, AbstractDropAndSortableBox box, int index, DragableElement element, boolean isActive) { super(id); this.box = box; this.index = index; this.element = element; this.isActive = isActive; draggableTarget = new DropTarget("DraggablePrioListTarget.target"); if (element != null) { draggableTarget.add(new DragableElement("DraggablePrioListTarget.element", element.getEvent(), isActive)); } else { draggableTarget.add(addDummyLabel(index)); } draggableTarget.setOutputMarkupId(true); add(draggableTarget); } /** * Getter for element. * * @return the element */ public DragableElement getElement() { return element; } /** * Setter for element. * * @param element the element to set */ public void setElement(DragableElement element) { this.element = element; } /** * updates this component with {@link AjaxRequestTarget}. * * @param target target which will be used for update. */ public void update(AjaxRequestTarget target) { DraggableTarget contentBox = new DropTarget("DraggablePrioListTarget.target"); if (element != null) { contentBox.add(new DragableElement("DraggablePrioListTarget.element", element.getEvent(), isActive)); } else { contentBox.add(addDummyLabel(index)); } draggableTarget.replaceWith(contentBox); draggableTarget = (DraggableTarget) contentBox; target.addComponent(draggableTarget); } /** * Implementation of {@link DraggableTarget}. * * @author basti */ private class DropTarget extends DraggableTarget { /** * generated UID. */ private static final long serialVersionUID = 3224838902620487634L; /** * default wicket constructor. * * @param id wicket id */ public DropTarget(String id) { super(id); } @Override protected void onDrop(Component component, AjaxRequestTarget target) { DragableElement element = null; try { element = component.findParent(DragableElement.class); DragAndDropableBox ddb = element.findParent(DragAndDropableBox.class); if (ddb != null) { ddb.removeElementFromList(element, target); } DraggablePrioListTarget.this.box.itemDropped(element, DraggablePrioListTarget.this, target); AbstractDropAndSortableBox dsb = element.findParent(AbstractDropAndSortableBox.class); if (dsb != null && !dsb.listContainsElement(element)) { dsb.removeItem(element, target); } AbstractPriorityListSelector pls = findParent(AbstractPriorityListSelector.class); if (pls != null) { pls.updateLists(target); } } catch (ClassCastException e) { // TODO exception handling e.printStackTrace(); } catch (NullPointerException e) { // TODO repair this return; } } } private Label addDummyLabel(int index){ Label label = new Label("DraggablePrioListTarget.element", "" + (index + 1) + ". Priorität"); label.add(new SimpleAttributeModifier("style", "font-size: 24px; font-style: bold; text-align: center; margin-top: auto; margin-buttom: auto")); return label; } }
gpl-3.0
gammalgris/jmul
Utilities/Reflection-Tests/src/test/jmul/reflection/classes/PrimitiveTypeTest.java
3958
/* * SPDX-License-Identifier: GPL-3.0 * * * (J)ava (M)iscellaneous (U)tilities (L)ibrary * * JMUL is a central repository for utilities which are used in my * other public and private repositories. * * Copyright (C) 2017 Kristian Kutin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * e-mail: kristian.kutin@arcor.de */ /* * This section contains meta informations. * * $Id$ */ package test.jmul.reflection.classes; import java.util.ArrayList; import java.util.Collection; import jmul.reflection.classes.ClassDefinition; import jmul.reflection.classes.ClassHelper; import jmul.test.classification.UnitTest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; /** * This class contains tests to check primitive types and their wrappers. * * @author Kristian Kutin */ @UnitTest @RunWith(Parameterized.class) public class PrimitiveTypeTest { /** * Returns a matrix of input data. * * @return a matrix of input data */ @Parameterized.Parameters public static Collection<Object[]> data() { Collection<Object[]> parameters = new ArrayList<Object[]>(); parameters.add(new Object[] { Byte.TYPE, Byte.class }); parameters.add(new Object[] { Short.TYPE, Short.class }); parameters.add(new Object[] { Integer.TYPE, Integer.class }); parameters.add(new Object[] { Long.TYPE, Long.class }); parameters.add(new Object[] { Float.TYPE, Float.class }); parameters.add(new Object[] { Double.TYPE, Double.class }); parameters.add(new Object[] { Boolean.TYPE, Boolean.class }); parameters.add(new Object[] { Character.TYPE, Character.class }); return parameters; } /** * A class definition. */ private ClassDefinition primitiveType; /** * A class definition. */ private ClassDefinition wrapperType; /** * Creates a new test according to the specified parameters. * * @param aPrimitiveType * a primitive type * @param aWrapperType * the corresponding wrapper type * * @throws ClassNotFoundException * is thrown if there is no corresponding class definition */ public PrimitiveTypeTest(Class aPrimitiveType, Class aWrapperType) throws ClassNotFoundException { primitiveType = ClassHelper.getClass(aPrimitiveType); wrapperType = ClassHelper.getClass(aWrapperType); } /** * Tests properties of the class. */ @Test public void testTypeProperties() { { String message = "The specified class " + primitiveType + " is no primitive type!"; assertTrue(message, primitiveType.isPrimitiveType()); } { String message = "The specified class " + wrapperType + " is no primitive wrapper type!"; assertTrue(message, wrapperType.isPrimitiveWrapper()); } { String message = " The specified primitive type " + primitiveType + " and the corresponding wrapper type " + wrapperType + " don't match!"; assertEquals(message, primitiveType, wrapperType.getCorrespondingPrimitiveType()); } } }
gpl-3.0
Jire/Nital
src/us/nital/util/PrimitiveUtils.java
1544
/* * Nital is an effort to provide a well documented, powerful, scalable, and robust * RuneScape server framework delivered open-source to all users. * * Copyright (C) 2011 Nital Software * * 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 us.nital.util; /** * Utility methods in this class deal with primitive data types. * * @author Thomas Nappo */ public class PrimitiveUtils { /** * Converts a primitive boolean to an integer by using * it's status as a marker for the bit value. * @param b The boolean to convert. * @return The bit value of the boolean. */ public static int toInteger(boolean b) { return b ? 1 : 0; } /** * Converts a primitive integer to a boolean by using * it's value as a marker for the boolean value. * @param i The integer to convert. * @return The appropriate status value of the boolean. */ public static boolean toBoolean(int i) { return i > 0; } }
gpl-3.0
JaspervanRiet/Jager
app/src/main/java/com/jaspervanriet/huntingthatproduct/Presenters/ProductPresenter.java
1277
/* * Copyright (C) 2015 Jasper van Riet * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.jaspervanriet.huntingthatproduct.Presenters; import android.os.Bundle; import android.view.View; import com.jaspervanriet.huntingthatproduct.Entities.Product; public interface ProductPresenter { void onActivityCreated (Bundle savedInstanceState); void onSaveInstanceState (Bundle outState); void onDestroy (); void onRefresh (); void onDateSet (int year, int monthOfYear, int dayOfMonth); void onShareClick (int feedItem); void onImageClick (View v, int feedItem); void onCommentsClick (View v, Product product); void onTabClick (String tabName); }
gpl-3.0
MHTaleb/Encologim
lib/JasperReport/src/net/sf/jasperreports/engine/export/oasis/JROdsExporter.java
32510
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2016 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ /* * Special thanks to Google 'Summer of Code 2005' program for supporting this development * * Contributors: * Majid Ali Khan - majidkk@users.sourceforge.net * Frank Sch�nheit - Frank.Schoenheit@Sun.COM */ package net.sf.jasperreports.engine.export.oasis; import java.awt.Color; import java.awt.Dimension; import java.awt.geom.Dimension2D; import java.io.IOException; import java.io.OutputStream; import java.text.AttributedCharacterIterator; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import net.sf.jasperreports.engine.DefaultJasperReportsContext; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRGenericElementType; import net.sf.jasperreports.engine.JRGenericPrintElement; import net.sf.jasperreports.engine.JRLineBox; import net.sf.jasperreports.engine.JRPen; import net.sf.jasperreports.engine.JRPrintFrame; import net.sf.jasperreports.engine.JRPrintGraphicElement; import net.sf.jasperreports.engine.JRPrintHyperlink; import net.sf.jasperreports.engine.JRPrintImage; import net.sf.jasperreports.engine.JRPrintLine; import net.sf.jasperreports.engine.JRPrintPage; import net.sf.jasperreports.engine.JRPrintText; import net.sf.jasperreports.engine.JRPropertiesUtil; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReportsContext; import net.sf.jasperreports.engine.PrintPageFormat; import net.sf.jasperreports.engine.base.JRBaseLineBox; import net.sf.jasperreports.engine.export.Cut; import net.sf.jasperreports.engine.export.CutsInfo; import net.sf.jasperreports.engine.export.ElementGridCell; import net.sf.jasperreports.engine.export.GenericElementHandlerEnviroment; import net.sf.jasperreports.engine.export.HyperlinkUtil; import net.sf.jasperreports.engine.export.JRExporterGridCell; import net.sf.jasperreports.engine.export.JRGridLayout; import net.sf.jasperreports.engine.export.JRHyperlinkProducer; import net.sf.jasperreports.engine.export.JRXlsAbstractExporter; import net.sf.jasperreports.engine.export.LengthUtil; import net.sf.jasperreports.engine.export.OccupiedGridCell; import net.sf.jasperreports.engine.export.XlsRowLevelInfo; import net.sf.jasperreports.engine.export.zip.ExportZipEntry; import net.sf.jasperreports.engine.export.zip.FileBufferedZipEntry; import net.sf.jasperreports.engine.type.LineDirectionEnum; import net.sf.jasperreports.engine.type.ModeEnum; import net.sf.jasperreports.engine.util.ImageUtil; import net.sf.jasperreports.engine.util.JRStringUtil; import net.sf.jasperreports.engine.util.JRStyledText; import net.sf.jasperreports.export.OdsExporterConfiguration; import net.sf.jasperreports.export.OdsReportConfiguration; import net.sf.jasperreports.export.XlsReportConfiguration; import net.sf.jasperreports.renderers.DimensionRenderable; import net.sf.jasperreports.renderers.Renderable; import net.sf.jasperreports.renderers.ResourceRenderer; import net.sf.jasperreports.renderers.util.RendererUtil; /** * Exports a JasperReports document to Open Document Spreadsheet format. It has character output type * and exports the document to a grid-based layout. * <p/> * The {@link net.sf.jasperreports.engine.export.oasis.JROdsExporter} exporter * implementation produces documents that comply with the Open Document Format for * Office Applications specifications for spreadsheets. These documents use the * <code>.ods</code> file extension. * <p/> * Because spreadsheet documents are made of sheets containing cells, this exporter is a * grid exporter, as well, therefore having the known limitations of grid exporters. * <p/> * Special exporter configuration settings, that can be applied to a * {@link net.sf.jasperreports.engine.export.oasis.JROdsExporter} instance * to control its behavior, can be found in {@link net.sf.jasperreports.export.OdsReportConfiguration} * and in its {@link net.sf.jasperreports.export.XlsReportConfiguration} superclass. * * @see net.sf.jasperreports.export.OdsReportConfiguration * @see net.sf.jasperreports.export.XlsReportConfiguration * @author Teodor Danciu (teodord@users.sourceforge.net) */ public class JROdsExporter extends JRXlsAbstractExporter<OdsReportConfiguration, OdsExporterConfiguration, JROdsExporterContext> { /** * */ protected static final String JR_PAGE_ANCHOR_PREFIX = "JR_PAGE_ANCHOR_"; protected static final String DEFAULT_COLUMN = "A"; protected static final String DEFAULT_ADDRESS = "$A$1"; /** * */ protected OasisZip oasisZip; protected ExportZipEntry tempBodyEntry; protected ExportZipEntry tempStyleEntry; protected WriterHelper tempBodyWriter; protected WriterHelper tempStyleWriter; protected WriterHelper stylesWriter; protected StyleCache styleCache; protected DocumentBuilder documentBuilder; protected TableBuilder tableBuilder; protected StyleBuilder styleBuilder; protected boolean startPage; protected PrintPageFormat oldPageFormat; protected int pageFormatIndex; protected StringBuilder namedExpressions; protected Map<Integer, String> rowStyles = new HashMap<Integer, String>(); protected Map<Integer, String> columnStyles = new HashMap<Integer, String>(); @Override protected void openWorkbook(OutputStream os) throws JRException, IOException { oasisZip = new FileBufferedOasisZip(OasisZip.MIME_TYPE_ODS); tempBodyEntry = new FileBufferedZipEntry(null); tempStyleEntry = new FileBufferedZipEntry(null); tempBodyWriter = new WriterHelper(jasperReportsContext, tempBodyEntry.getWriter()); tempStyleWriter = new WriterHelper(jasperReportsContext, tempStyleEntry.getWriter()); rowStyles.clear(); columnStyles.clear(); documentBuilder = new OdsDocumentBuilder(oasisZip); styleCache = new StyleCache(jasperReportsContext, tempStyleWriter, getExporterKey()); stylesWriter = new WriterHelper(jasperReportsContext, oasisZip.getStylesEntry().getWriter()); styleBuilder = new StyleBuilder(stylesWriter); styleBuilder.buildBeforeAutomaticStyles(jasperPrint); namedExpressions = new StringBuilder("<table:named-expressions>\n"); pageFormatIndex = -1; maxColumnIndex = 1023; } @Override protected int exportPage(JRPrintPage page, CutsInfo xCuts, int startRow, String defaultSheetName) throws JRException { if (oldPageFormat != pageFormat) { styleBuilder.buildPageLayout(++pageFormatIndex, pageFormat); oldPageFormat = pageFormat; } return super.exportPage(page, xCuts, startRow, defaultSheetName); } @Override protected void createSheet(CutsInfo xCuts, SheetInfo sheetInfo) { startPage = true; // CutsInfo xCuts = gridLayout.getXCuts(); // JRExporterGridCell[][] grid = gridLayout.getGrid(); // TableBuilder tableBuilder = frameIndex == null // ? new TableBuilder(reportIndex, pageIndex, tempBodyWriter, tempStyleWriter) // : new TableBuilder(frameIndex.toString(), tempBodyWriter, tempStyleWriter); tableBuilder = new OdsTableBuilder( documentBuilder, jasperPrint, pageFormatIndex, pageIndex, tempBodyWriter, tempStyleWriter, styleCache, rowStyles, columnStyles, sheetInfo.sheetName, sheetInfo.tabColor); // tableBuilder.buildTableStyle(gridLayout.getWidth()); tableBuilder.buildTableStyle(xCuts.getLastCutOffset());//FIXMEODS tableBuilder.buildTableHeader(); // for(int col = 1; col < xCuts.size(); col++) // { // tableBuilder.buildColumnStyle( // col - 1, // xCuts.getCutOffset(col) - xCuts.getCutOffset(col - 1) // ); // tableBuilder.buildColumnHeader(col - 1); // tableBuilder.buildColumnFooter(); // } } @Override protected void closeSheet() { if (tableBuilder != null) { tableBuilder.buildRowFooter(); tableBuilder.buildTableFooter(); } } @Override protected void closeWorkbook(OutputStream os) throws JRException, IOException { styleBuilder.buildMasterPages(pageFormatIndex); stylesWriter.flush(); tempBodyWriter.flush(); tempStyleWriter.flush(); stylesWriter.close(); tempBodyWriter.close(); tempStyleWriter.close(); namedExpressions.append("</table:named-expressions>\n"); /* */ ContentBuilder contentBuilder = new ContentBuilder( oasisZip.getContentEntry(), tempStyleEntry, tempBodyEntry, styleCache.getFontFaces(), OasisZip.MIME_TYPE_ODS, namedExpressions ); contentBuilder.build(); tempStyleEntry.dispose(); tempBodyEntry.dispose(); oasisZip.zipEntries(os); oasisZip.dispose(); } @Override protected void setColumnWidth(int col, int width, boolean autoFit) { tableBuilder.buildColumnStyle(col - 1, width); tableBuilder.buildColumnHeader(width); tableBuilder.buildColumnFooter(); } @Override protected void setRowHeight( int rowIndex, int lastRowHeight, Cut yCut, XlsRowLevelInfo levelInfo ) throws JRException { boolean isFlexibleRowHeight = getCurrentItemConfiguration().isFlexibleRowHeight(); tableBuilder.buildRowStyle(rowIndex, isFlexibleRowHeight ? -1 : lastRowHeight); tableBuilder.buildRow(rowIndex, isFlexibleRowHeight ? -1 : lastRowHeight); } @Override protected void addRowBreak(int rowIndex) { //FIXMEODS sheet.setRowBreak(rowIndex); } // @Override // protected void setCell( // JRExporterGridCell gridCell, // int colIndex, // int rowIndex) // { // //nothing to do // } @Override protected void addBlankCell( JRExporterGridCell gridCell, int colIndex, int rowIndex ) { tempBodyWriter.write("<table:table-cell"); //tempBodyWriter.write(" office:value-type=\"string\""); if (gridCell == null) { tempBodyWriter.write(" table:style-name=\"empty-cell\""); } else { tempBodyWriter.write(" table:style-name=\"" + styleCache.getCellStyle(gridCell) + "\""); } // if (emptyCellColSpan > 1) // { // tempBodyWriter.write(" table:number-columns-spanned=\"" + emptyCellColSpan + "\""); // } tempBodyWriter.write("/>\n"); // // exportOccupiedCells(emptyCellColSpan - 1); } @Override protected void addOccupiedCell( OccupiedGridCell occupiedGridCell, int colIndex, int rowIndex ) throws JRException { ElementGridCell elementGridCell = (ElementGridCell)occupiedGridCell.getOccupier(); addBlankCell(elementGridCell, colIndex, rowIndex); } @Override public void exportText( JRPrintText text, JRExporterGridCell gridCell, int colIndex, int rowIndex ) throws JRException { tableBuilder.exportText(text, gridCell, isShrinkToFit(text), isWrapText(text), isIgnoreTextFormatting(text)); XlsReportConfiguration configuration = getCurrentItemConfiguration(); if (!configuration.isIgnoreAnchors() && text.getAnchorName() != null) { String cellAddress = "$&apos;" + tableBuilder.getTableName() + "&apos;." + getCellAddress(rowIndex, colIndex); int lastCol = Math.max(0, colIndex + gridCell.getColSpan() -1); String cellRangeAddress = getCellAddress(rowIndex + gridCell.getRowSpan() - 1, lastCol); namedExpressions.append("<table:named-range table:name=\""+ JRStringUtil.xmlEncode(text.getAnchorName()) +"\" table:base-cell-address=\"" + cellAddress +"\" table:cell-range-address=\"" + cellAddress +":" +cellRangeAddress +"\"/>\n"); } } @Override public void exportImage( JRPrintImage image, JRExporterGridCell gridCell, int colIndex, int rowIndex, int emptyCols, int yCutsRow, JRGridLayout layout ) throws JRException { int topPadding = Math.max(image.getLineBox().getTopPadding().intValue(), Math.round(image.getLineBox().getTopPen().getLineWidth().floatValue())); int leftPadding = Math.max(image.getLineBox().getLeftPadding().intValue(), Math.round(image.getLineBox().getLeftPen().getLineWidth().floatValue())); int bottomPadding = Math.max(image.getLineBox().getBottomPadding().intValue(), Math.round(image.getLineBox().getBottomPen().getLineWidth().floatValue())); int rightPadding = Math.max(image.getLineBox().getRightPadding().intValue(), Math.round(image.getLineBox().getRightPen().getLineWidth().floatValue())); int availableImageWidth = image.getWidth() - leftPadding - rightPadding; availableImageWidth = availableImageWidth < 0 ? 0 : availableImageWidth; int availableImageHeight = image.getHeight() - topPadding - bottomPadding; availableImageHeight = availableImageHeight < 0 ? 0 : availableImageHeight; tableBuilder.buildCellHeader(styleCache.getCellStyle(gridCell), gridCell.getColSpan(), gridCell.getRowSpan()); Renderable renderer = image.getRenderer(); if ( renderer != null && availableImageWidth > 0 && availableImageHeight > 0 ) { InternalImageProcessor imageProcessor = new InternalImageProcessor( image, gridCell, availableImageWidth, availableImageHeight ); InternalImageProcessorResult imageProcessorResult = null; try { imageProcessorResult = imageProcessor.process(renderer); } catch (Exception e) { Renderable onErrorRenderer = getRendererUtil().handleImageError(e, image.getOnErrorTypeValue()); if (onErrorRenderer != null) { imageProcessorResult = imageProcessor.process(onErrorRenderer); } } if (imageProcessorResult != null) { XlsReportConfiguration configuration = getCurrentItemConfiguration(); boolean isOnePagePerSheet = configuration.isOnePagePerSheet(); // tempBodyWriter.write("<text:p>"); documentBuilder.insertPageAnchor(tableBuilder); if (!configuration.isIgnoreAnchors() && image.getAnchorName() != null) { tableBuilder.exportAnchor(JRStringUtil.xmlEncode(image.getAnchorName())); String cellAddress = "$&apos;" + tableBuilder.getTableName() + "&apos;." + getCellAddress(rowIndex, colIndex); int lastCol = Math.max(0, colIndex + gridCell.getColSpan() - 1); String cellRangeAddress = getCellAddress(rowIndex + gridCell.getRowSpan() - 1, lastCol); namedExpressions.append("<table:named-range table:name=\""+ image.getAnchorName() +"\" table:base-cell-address=\"" + cellAddress +"\" table:cell-range-address=\"" + cellAddress +":" + cellRangeAddress +"\"/>\n"); } boolean startedHyperlink = tableBuilder.startHyperlink(image,false, isOnePagePerSheet); //String cellAddress = getCellAddress(rowIndex + gridCell.getRowSpan(), colIndex + gridCell.getColSpan() - 1); String cellAddress = getCellAddress(rowIndex + gridCell.getRowSpan(), colIndex + gridCell.getColSpan()); cellAddress = cellAddress == null ? "" : "table:end-cell-address=\"" + cellAddress + "\" "; tempBodyWriter.write( "<draw:frame text:anchor-type=\"frame\" " + "draw:style-name=\"" + styleCache.getGraphicStyle(image) + "\" " + cellAddress // + "table:end-x=\"" + LengthUtil.inchRound(image.getWidth()) + "in\" " // + "table:end-y=\"" + LengthUtil.inchRound(image.getHeight()) + "in\" " + "table:end-x=\"0in\" " + "table:end-y=\"0in\" " // + "svg:x=\"" + LengthUtil.inch(image.getX() + leftPadding + imageProcessorResult.xoffset) + "in\" " // + "svg:y=\"" + LengthUtil.inch(image.getY() + topPadding + imageProcessorResult.yoffset) + "in\" " + "svg:x=\"0in\" " + "svg:y=\"0in\" " + "svg:width=\"" + LengthUtil.inchRound(image.getWidth()) + "in\" " + "svg:height=\"" + LengthUtil.inchRound(image.getHeight()) + "in\"" + ">" ); tempBodyWriter.write("<draw:image "); tempBodyWriter.write(" xlink:href=\"" + JRStringUtil.xmlEncode(imageProcessorResult.imagePath) + "\""); tempBodyWriter.write(" xlink:type=\"simple\""); tempBodyWriter.write(" xlink:show=\"embed\""); tempBodyWriter.write(" xlink:actuate=\"onLoad\""); tempBodyWriter.write("/>\n"); tempBodyWriter.write("</draw:frame>"); if (startedHyperlink) { tableBuilder.endHyperlink(false); } // tempBodyWriter.write("</text:p>"); } } tableBuilder.buildCellFooter(); } private class InternalImageProcessor { private final JRPrintImage imageElement; private final JRExporterGridCell cell; private final int availableImageWidth; private final int availableImageHeight; protected InternalImageProcessor( JRPrintImage imageElement, JRExporterGridCell cell, int availableImageWidth, int availableImageHeight ) { this.imageElement = imageElement; this.cell = cell; this.availableImageWidth = availableImageWidth; this.availableImageHeight = availableImageHeight; } private InternalImageProcessorResult process(Renderable renderer) throws JRException { boolean isLazy = RendererUtil.isLazy(renderer); if (!isLazy) { if (renderer instanceof ResourceRenderer) { renderer = documentBuilder.getRenderersCache().getLoadedRenderer((ResourceRenderer)renderer); } } // check dimension first, to avoid caching renderers that might not be used eventually, due to their dimension errors int width = availableImageWidth; int height = availableImageHeight; int xoffset = 0; int yoffset = 0; switch (imageElement.getScaleImageValue()) { case FILL_FRAME : { width = availableImageWidth; height = availableImageHeight; xoffset = 0; yoffset = 0; break; } case CLIP : case RETAIN_SHAPE : default : { double normalWidth = availableImageWidth; double normalHeight = availableImageHeight; if (!isLazy) { DimensionRenderable dimensionRenderer = documentBuilder.getRenderersCache().getDimensionRenderable(renderer); Dimension2D dimension = dimensionRenderer == null ? null : dimensionRenderer.getDimension(jasperReportsContext); if (dimension != null) { normalWidth = dimension.getWidth(); normalHeight = dimension.getHeight(); } } double ratio = normalWidth / normalHeight; if( ratio > availableImageWidth / (double)availableImageHeight ) { width = availableImageWidth; height = (int)(width/ratio); } else { height = availableImageHeight; width = (int)(ratio * height); } xoffset = (int)(ImageUtil.getXAlignFactor(imageElement) * (availableImageWidth - width)); yoffset = (int)(ImageUtil.getYAlignFactor(imageElement) * (availableImageHeight - height)); } } String imagePath = documentBuilder.getImagePath( renderer, new Dimension(availableImageWidth, availableImageHeight), ModeEnum.OPAQUE == imageElement.getModeValue() ? imageElement.getBackcolor() : null, cell, isLazy ); return new InternalImageProcessorResult( imagePath, width, height, xoffset, yoffset ); } } private class InternalImageProcessorResult { protected final String imagePath; protected int width; protected int height; protected int xoffset; protected int yoffset; protected InternalImageProcessorResult( String imagePath, int width, int height, int xoffset, int yoffset ) { this.imagePath = imagePath; this.width = width; this.height = height; this.xoffset = xoffset; this.yoffset = yoffset; } } protected String getCellAddress(int row, int col) { String address = null; if(row > -1 && row < 1048577 && col > -1 && col < maxColumnIndex) { address = "$" + getColumIndexName(col, maxColumnIndex) + "$" + (row + 1); } return address == null ? DEFAULT_ADDRESS : address; } @Override protected void exportRectangle( JRPrintGraphicElement rectangle, JRExporterGridCell gridCell, int colIndex, int rowIndex ) throws JRException { tableBuilder.exportRectangle(rectangle, gridCell); } @Override protected void exportLine( JRPrintLine line, JRExporterGridCell gridCell, int colIndex, int rowIndex ) throws JRException { JRLineBox box = new JRBaseLineBox(null); JRPen pen = null; float ratio = line.getWidth() / line.getHeight(); if (ratio > 1) { if (line.getDirectionValue() == LineDirectionEnum.TOP_DOWN) { pen = box.getTopPen(); } else { pen = box.getBottomPen(); } } else { if (line.getDirectionValue() == LineDirectionEnum.TOP_DOWN) { pen = box.getLeftPen(); } else { pen = box.getRightPen(); } } pen.setLineColor(line.getLinePen().getLineColor()); pen.setLineStyle(line.getLinePen().getLineStyleValue()); pen.setLineWidth(line.getLinePen().getLineWidth()); gridCell.setBox(box);//CAUTION: only some exporters set the cell box tableBuilder.buildCellHeader(styleCache.getCellStyle(gridCell), gridCell.getColSpan(), gridCell.getRowSpan()); // double x1, y1, x2, y2; // // if (line.getDirection() == JRLine.DIRECTION_TOP_DOWN) // { // x1 = Utility.translatePixelsToInches(0); // y1 = Utility.translatePixelsToInches(0); // x2 = Utility.translatePixelsToInches(line.getWidth() - 1); // y2 = Utility.translatePixelsToInches(line.getHeight() - 1); // } // else // { // x1 = Utility.translatePixelsToInches(0); // y1 = Utility.translatePixelsToInches(line.getHeight() - 1); // x2 = Utility.translatePixelsToInches(line.getWidth() - 1); // y2 = Utility.translatePixelsToInches(0); // } tempBodyWriter.write("<text:p>"); //FIXMEODS insertPageAnchor(); // tempBodyWriter.write( // "<draw:line text:anchor-type=\"paragraph\" " // + "draw:style-name=\"" + styleCache.getGraphicStyle(line) + "\" " // + "svg:x1=\"" + x1 + "in\" " // + "svg:y1=\"" + y1 + "in\" " // + "svg:x2=\"" + x2 + "in\" " // + "svg:y2=\"" + y2 + "in\">" // //+ "</draw:line>" // + "<text:p/></draw:line>" // ); tempBodyWriter.write("</text:p>"); tableBuilder.buildCellFooter(); } @Override protected void exportFrame( JRPrintFrame frame, JRExporterGridCell cell, int colIndex, int rowIndex ) throws JRException { addBlankCell(cell, colIndex, rowIndex); } @Override protected void exportGenericElement( JRGenericPrintElement element, JRExporterGridCell gridCell, int colIndex, int rowIndex, int emptyCols, int yCutsRow, JRGridLayout layout ) throws JRException { GenericElementOdsHandler handler = (GenericElementOdsHandler) GenericElementHandlerEnviroment.getInstance(getJasperReportsContext()).getElementHandler( element.getGenericType(), ODS_EXPORTER_KEY); if (handler != null) { JROdsExporterContext exporterContext = new ExporterContext(tableBuilder); handler.exportElement(exporterContext, element, gridCell, colIndex, rowIndex, emptyCols, yCutsRow, layout); } else { if (log.isDebugEnabled()) { log.debug("No ODS generic element handler for " + element.getGenericType()); } } } @Override protected void setFreezePane(int rowIndex, int colIndex) { // nothing to do here } /** * @deprecated to be removed; replaced by {@link #setFreezePane(int, int)} */ @Override protected void setFreezePane(int rowIndex, int colIndex, boolean isRowEdge, boolean isColumnEdge) { // nothing to do here } @Override protected void setSheetName(String sheetName) { // TODO Auto-generated method stub } @Override protected void setAutoFilter(String autoFilterRange) { // TODO Auto-generated method stub } @Override protected void setRowLevels(XlsRowLevelInfo levelInfo, String level) { // TODO Auto-generated method stub } private static final Log log = LogFactory.getLog(JROdsExporter.class); protected static final String ODS_EXPORTER_PROPERTIES_PREFIX = JRPropertiesUtil.PROPERTY_PREFIX + "export.ods."; /** * The exporter key, as used in * {@link GenericElementHandlerEnviroment#getElementHandler(JRGenericElementType, String)}. */ public static final String ODS_EXPORTER_KEY = JRPropertiesUtil.PROPERTY_PREFIX + "ods"; protected class ExporterContext extends BaseExporterContext implements JROdsExporterContext { TableBuilder tableBuilder = null; public ExporterContext(TableBuilder tableBuidler) { this.tableBuilder = tableBuidler; } @Override public TableBuilder getTableBuilder() { return tableBuilder; } } protected class OdsDocumentBuilder extends DocumentBuilder { public OdsDocumentBuilder(OasisZip oasisZip) { super(oasisZip); } @Override public JRStyledText getStyledText(JRPrintText text) { return JROdsExporter.this.getStyledText(text); } @Override public Locale getTextLocale(JRPrintText text) { return JROdsExporter.this.getTextLocale(text); } @Override public String getInvalidCharReplacement() { return JROdsExporter.this.invalidCharReplacement; } @Override protected void insertPageAnchor(TableBuilder tableBuilder) { JROdsExporter.this.insertPageAnchor(tableBuilder); } @Override protected JRHyperlinkProducer getHyperlinkProducer(JRPrintHyperlink link) { return JROdsExporter.this.getHyperlinkProducer(link); } @Override protected JasperReportsContext getJasperReportsContext() { return JROdsExporter.this.getJasperReportsContext(); } @Override protected int getReportIndex() { return JROdsExporter.this.reportIndex; } @Override protected int getPageIndex() { return JROdsExporter.this.pageIndex; } } protected class OdsTableBuilder extends TableBuilder { protected OdsTableBuilder( DocumentBuilder documentBuilder, JasperPrint jasperPrint, int pageFormatIndex, int pageIndex, WriterHelper bodyWriter, WriterHelper styleWriter, StyleCache styleCache, Map<Integer, String> rowStyles, Map<Integer, String> columnStyles, Color tabColor) { super( documentBuilder, jasperPrint, pageFormatIndex, pageIndex, bodyWriter, styleWriter, styleCache, rowStyles, columnStyles, tabColor); } protected OdsTableBuilder( DocumentBuilder documentBuilder, JasperPrint jasperPrint, int pageFormatIndex, int pageIndex, WriterHelper bodyWriter, WriterHelper styleWriter, StyleCache styleCache, Map<Integer, String> rowStyles, Map<Integer, String> columnStyles, String sheetName, Color tabColor) { super( documentBuilder, jasperPrint, pageFormatIndex, pageIndex, bodyWriter, styleWriter, styleCache, rowStyles, columnStyles, tabColor); this.tableName = sheetName; } @Override protected String getIgnoreHyperlinkProperty() { return XlsReportConfiguration.PROPERTY_IGNORE_HYPERLINK; } @Override protected void exportTextContents(JRPrintText textElement) { String href = null; String ignLnkPropName = getIgnoreHyperlinkProperty(); Boolean ignoreHyperlink = HyperlinkUtil.getIgnoreHyperlink(ignLnkPropName, textElement); boolean isIgnoreTextFormatting = isIgnoreTextFormatting(textElement); if (ignoreHyperlink == null) { ignoreHyperlink = getPropertiesUtil().getBooleanProperty(jasperPrint, ignLnkPropName, false); } if (!ignoreHyperlink) { href = documentBuilder.getHyperlinkURL(textElement, getCurrentItemConfiguration().isOnePagePerSheet()); } if (href == null) { exportStyledText(textElement, false, isIgnoreTextFormatting); } else { JRStyledText styledText = getStyledText(textElement); if (styledText != null && styledText.length() > 0) { String text = styledText.getText(); Locale locale = getTextLocale(textElement); int runLimit = 0; AttributedCharacterIterator iterator = styledText.getAttributedString().getIterator(); while(runLimit < styledText.length() && (runLimit = iterator.getRunLimit()) <= styledText.length()) { // ODS does not like text:span inside text:a // writing one text:a inside text:span for each style run String runText = text.substring(iterator.getIndex(), runLimit); startTextSpan( iterator.getAttributes(), runText, locale, isIgnoreTextFormatting); writeHyperlink(textElement, href, true); writeText(runText); endHyperlink(true); endTextSpan(); iterator.setIndex(runLimit); } } } } } /** * @see #JROdsExporter(JasperReportsContext) */ public JROdsExporter() { this(DefaultJasperReportsContext.getInstance()); } /** * */ public JROdsExporter(JasperReportsContext jasperReportsContext) { super(jasperReportsContext); exporterContext = new ExporterContext(null); } @Override protected Class<OdsExporterConfiguration> getConfigurationInterface() { return OdsExporterConfiguration.class; } @Override protected Class<OdsReportConfiguration> getItemConfigurationInterface() { return OdsReportConfiguration.class; } @Override protected void initExport() { super.initExport(); // macroTemplate = macroTemplate == null ? getPropertiesUtil().getProperty(jasperPrint, PROPERTY_MACRO_TEMPLATE) : macroTemplate; // // password = // getStringParameter( // JExcelApiExporterParameter.PASSWORD, // JExcelApiExporterParameter.PROPERTY_PASSWORD // ); } @Override protected void initReport() { super.initReport(); XlsReportConfiguration configuration = getCurrentItemConfiguration(); //FIXMEODS setBackground() nature = new JROdsExporterNature( jasperReportsContext, filter, configuration.isIgnoreGraphics(), configuration.isIgnorePageMargins() ); } // /** // * // */ // protected void exportEllipse(TableBuilder tableBuilder, JRPrintEllipse ellipse, JRExporterGridCell gridCell) throws IOException // { // JRLineBox box = new JRBaseLineBox(null); // JRPen pen = box.getPen(); // pen.setLineColor(ellipse.getLinePen().getLineColor()); // pen.setLineStyle(ellipse.getLinePen().getLineStyleValue()); // pen.setLineWidth(ellipse.getLinePen().getLineWidth()); // // gridCell.setBox(box);//CAUTION: only some exporters set the cell box // // tableBuilder.buildCellHeader(styleCache.getCellStyle(gridCell), gridCell.getColSpan(), gridCell.getRowSpan()); // tempBodyWriter.write("<text:p>"); // insertPageAnchor(); //// tempBodyWriter.write( //// "<draw:ellipse text:anchor-type=\"paragraph\" " //// + "draw:style-name=\"" + styleCache.getGraphicStyle(ellipse) + "\" " //// + "svg:width=\"" + Utility.translatePixelsToInches(ellipse.getWidth()) + "in\" " //// + "svg:height=\"" + Utility.translatePixelsToInches(ellipse.getHeight()) + "in\" " //// + "svg:x=\"0in\" " //// + "svg:y=\"0in\">" //// + "<text:p/></draw:ellipse>" //// ); // tempBodyWriter.write("</text:p>"); // tableBuilder.buildCellFooter(); // } @Override public String getExporterKey() { return ODS_EXPORTER_KEY; } @Override public String getExporterPropertiesPrefix() { return ODS_EXPORTER_PROPERTIES_PREFIX; } /** * */ protected void insertPageAnchor(TableBuilder tableBuilder) { if(startPage) { String pageName = DocumentBuilder.JR_PAGE_ANCHOR_PREFIX + reportIndex + "_" + (sheetIndex - sheetsBeforeCurrentReport); String cellAddress = "$&apos;" + tableBuilder.getTableName() + "&apos;.$A$1"; tableBuilder.exportAnchor(pageName); namedExpressions.append("<table:named-range table:name=\""+ pageName +"\" table:base-cell-address=\"" + cellAddress +"\" table:cell-range-address=\"" +cellAddress +"\"/>\n"); startPage = false; } } @Override protected void exportEmptyReport() throws JRException, IOException { // does nothing in ODS export } }
gpl-3.0
glastonbridge/ScanVox
src/org/isophonics/scanvox/Arrangement.java
4626
/* This file is part of ScanVox (c) 2010 Queen Mary University of London ScanVox 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. ScanVox 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 ScanVox. If not, see <http://www.gnu.org/licenses/>. */ package org.isophonics.scanvox; import java.util.Iterator; import java.util.LinkedList; import java.util.Vector; import android.util.Log; /** * The structure of the sounds as they are laid out in the loop. * @author alex * */ public class Arrangement { public static enum EventType { SOUND_START, SOUND_END } public static final String TAG = "Arrangement"; protected int length = 16; /** The length of the loop, in ticks */ protected int ticksPerBeat = 1; public Arrangement(int numRows) { for (int i=0;i<numRows; ++i) rows.add(new Row()); } /** * Represents one sound, and where it begins and ends in this arrangement * @author alex * */ public class Sound { private float startTime = 0; private float length = 0; protected PlayingSound id; public Sound(PlayingSound id,float s, float l) { this.id = id; startTime = s % Arrangement.this.length; if(startTime<0) startTime = s + Arrangement.this.length; // quietly force into the +ve domain length = l; } public float getStartTime() { return startTime; } public float getEndTime() { return startTime+length; } public float getLength() { return length; } @Override public int hashCode() { return id.getRecordBuffer(); } public boolean equals(Object rhs) { return (rhs instanceof Sound && this.hashCode() == rhs.hashCode()); } public boolean wrapsLoop() { return getEndTime()>Arrangement.this.length; } } public Vector<Row> rows=new Vector<Row>(); public int bpm; /** * Represents a row of arranged sounds. The choice of row for a * sound does not affect its playback, it is purely to make it * easier for the user to lay stuff out. * * @author alex * */ public class Row implements Iterable<Sound> { private LinkedList<Sound> contents = new LinkedList<Sound>(); /** * Grab the sound that is being played back at the given * playback time, remove it from this row and return it. * * @param needle * @return sound being played, null if no sound is being played */ public Sound grabSoundAt(float needle) { int item = 0; Sound result = null; for (Sound s : contents) { if (needle>=s.getStartTime()) { if (needle <= s.getEndTime()) result = s; break; } ++item; } if (result != null) contents.remove(item); return result; } /** * Add a sound at the right place in the row. * * @TODO: I'm not particularly fond of this algorithm but I * can't think of anything better right now. * * @return false if the sound cannot currently fit in that * place. */ public boolean add(Sound newSound) { // Hello new sound, do you fit into this arrangement? if (newSound.getStartTime()>Arrangement.this.length) return false; float newSoundStartTime = newSound.getStartTime(); int index = 0; // Do you belong right at the beginning? if (contents.size() == 0 ) { contents.add(newSound); return true; } else { float firstStartTime = contents.get(0).getStartTime(); if (firstStartTime <= newSoundStartTime) { if (firstStartTime < newSound.getEndTime()) { return false; } else { // You fit! contents.add(0,newSound); return true; } } } // Who do you come after? for (Sound s : contents) { if (newSoundStartTime >= s.getEndTime()) { ++index; break; } ++index; } // Do you fit in front of the thing you come before? if ( contents.size()>index+1 && newSound.getEndTime() > contents.get(index+1).getStartTime()) return false; // Well done, you have defeated the guardians! contents.add(index,newSound); return true; } /** * Exposes an iterator to the underlying linkedlist. */ public Iterator<Sound> iterator() { return contents.iterator(); } public boolean isEmpty() { return contents.isEmpty(); } } }
gpl-3.0
pavloff-de/spark4knime
src/de/pavloff/spark4knime/actions/TakeSampleNodeView.java
1451
package de.pavloff.spark4knime.actions; import org.knime.core.node.NodeView; import de.pavloff.spark4knime.TableCellUtils.RddViewer; /** * <code>NodeView</code> for the "TakeSample" Node. Returns a random sample of * RDD as list * * @author Oleg Pavlov, University of Heidelberg */ public class TakeSampleNodeView extends NodeView<TakeSampleNodeModel> { /** * Creates a new view. * * @param nodeModel * The model (class: {@link TakeSampleNodeModel}) */ protected TakeSampleNodeView(final TakeSampleNodeModel nodeModel) { super(nodeModel); // instantiate the components of the view here. } /** * {@inheritDoc} */ @Override protected void modelChanged() { // retrieve the new model from your nodemodel and update the view. TakeSampleNodeModel nodeModel = (TakeSampleNodeModel) getNodeModel(); assert nodeModel != null; // be aware of a possibly not executed nodeModel! The data you retrieve // from your nodemodel could be null, emtpy, or invalid in any kind. } /** * {@inheritDoc} */ @Override protected void onClose() { // things to do when closing the view } /** * {@inheritDoc} */ @Override protected void onOpen() { // things to do when opening the view TakeSampleNodeModel nodeModel = (TakeSampleNodeModel) getNodeModel(); assert nodeModel != null; RddViewer view = nodeModel.getRddViewer(); assert (view != null); setComponent(view.getTableView()); } }
gpl-3.0
jindrapetrik/jpexs-decompiler
libsrc/ffdec_lib/src/com/jpexs/decompiler/flash/action/model/SetPropertyActionItem.java
6929
/* * Copyright (C) 2010-2021 JPEXS, All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3.0 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. */ package com.jpexs.decompiler.flash.action.model; import com.jpexs.decompiler.flash.SourceGeneratorLocalData; import com.jpexs.decompiler.flash.action.Action; import com.jpexs.decompiler.flash.action.parser.script.ActionSourceGenerator; import com.jpexs.decompiler.flash.action.swf4.ActionPush; import com.jpexs.decompiler.flash.action.swf4.ActionSetProperty; import com.jpexs.decompiler.flash.action.swf4.RegisterNumber; import com.jpexs.decompiler.flash.action.swf5.ActionStoreRegister; import com.jpexs.decompiler.flash.helpers.GraphTextWriter; import com.jpexs.decompiler.graph.CompilationException; import com.jpexs.decompiler.graph.GraphPart; import com.jpexs.decompiler.graph.GraphSourceItem; import com.jpexs.decompiler.graph.GraphSourceItemPos; import com.jpexs.decompiler.graph.GraphTargetItem; import com.jpexs.decompiler.graph.SourceGenerator; import com.jpexs.decompiler.graph.model.LocalData; import java.util.List; import java.util.Objects; /** * * @author JPEXS */ public class SetPropertyActionItem extends ActionItem implements SetTypeActionItem { public GraphTargetItem target; public int propertyIndex; @Override public GraphPart getFirstPart() { return value.getFirstPart(); } @Override public void setValue(GraphTargetItem value) { this.value = value; } private int tempRegister = -1; @Override public int getTempRegister() { return tempRegister; } @Override public void setTempRegister(int tempRegister) { this.tempRegister = tempRegister; } @Override public GraphTargetItem getValue() { return value; } public SetPropertyActionItem(GraphSourceItem instruction, GraphSourceItem lineStartIns, GraphTargetItem target, int propertyIndex, GraphTargetItem value) { super(instruction, lineStartIns, PRECEDENCE_ASSIGMENT, value); this.target = target; this.propertyIndex = propertyIndex; } @Override public GraphTextWriter appendTo(GraphTextWriter writer, LocalData localData) throws InterruptedException { if (isEmptyString(target)) { writer.append(Action.propertyNames[propertyIndex]).append(" = "); return value.toString(writer, localData); } writer.append("setProperty"); writer.spaceBeforeCallParenthesies(3); writer.append("("); target.appendTo(writer, localData); writer.append(", "); writer.append(Action.propertyNames[propertyIndex]); writer.append(", "); value.appendTo(writer, localData); writer.append(")"); return writer; } @Override public GraphTargetItem getObject() { return new GetPropertyActionItem(getSrc(), getLineStartItem(), target, propertyIndex); } @Override public List<GraphSourceItemPos> getNeededSources() { List<GraphSourceItemPos> ret = super.getNeededSources(); ret.addAll(target.getNeededSources()); ret.addAll(value.getNeededSources()); return ret; } @Override public boolean hasSideEffect() { return true; } @Override public List<GraphSourceItem> toSource(SourceGeneratorLocalData localData, SourceGenerator generator) throws CompilationException { ActionSourceGenerator asGenerator = (ActionSourceGenerator) generator; int tmpReg = asGenerator.getTempRegister(localData); try { return toSourceMerge(localData, generator, target, new ActionPush((Long) (long) propertyIndex), value, new ActionStoreRegister(tmpReg), new ActionSetProperty(), new ActionPush(new RegisterNumber(tmpReg))); } finally { asGenerator.releaseTempRegister(localData, tmpReg); } } @Override public List<GraphSourceItem> toSourceIgnoreReturnValue(SourceGeneratorLocalData localData, SourceGenerator generator) throws CompilationException { return toSourceMerge(localData, generator, target, new ActionPush((Long) (long) propertyIndex), value, new ActionSetProperty()); } @Override public boolean hasReturnValue() { return false; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.target); hash = 97 * hash + this.propertyIndex; return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SetPropertyActionItem other = (SetPropertyActionItem) obj; if (this.propertyIndex != other.propertyIndex) { return false; } if (!Objects.equals(this.target, other.target)) { return false; } if (!Objects.equals(this.value, other.value)) { return false; } return true; } @Override public boolean valueEquals(GraphTargetItem obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SetPropertyActionItem other = (SetPropertyActionItem) obj; if (this.propertyIndex != other.propertyIndex) { return false; } if (!GraphTargetItem.objectsValueEquals(this.target, other.target)) { return false; } if (!GraphTargetItem.objectsValueEquals(this.value, other.value)) { return false; } return true; } @Override public GraphTargetItem getCompoundValue() { throw new UnsupportedOperationException("Not supported."); } @Override public void setCompoundValue(GraphTargetItem value) { throw new UnsupportedOperationException("Not supported."); } @Override public void setCompoundOperator(String operator) { throw new UnsupportedOperationException("Not supported."); } @Override public String getCompoundOperator() { throw new UnsupportedOperationException("Not supported."); } }
gpl-3.0
NEMESIS13cz/Evercraft
java/evercraft/NEMESIS13cz/TileEntity/Slot/SlotCentrifuge.java
3228
package evercraft.NEMESIS13cz.TileEntity.Slot; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import evercraft.NEMESIS13cz.MachineRecipes.CentrifugeRecipes; public class SlotCentrifuge extends Slot { /** * The player that is using the GUI where this slot resides. */ private EntityPlayer thePlayer; private int field_75228_b; public SlotCentrifuge(EntityPlayer par1EntityPlayer, IInventory par2IInventory, int par3, int par4, int par5) { super(par2IInventory, par3, par4, par5); this.thePlayer = par1EntityPlayer; } /** * Check if the stack is a valid item for this slot. Always true beside for the armor slots. */ public boolean isItemValid(ItemStack par1ItemStack) { return false; } /** * Decrease the size of the stack in slot (first int arg) by the amount of the second int arg. Returns the new * stack. */ public ItemStack decrStackSize(int par1) { if (this.getHasStack()) { this.field_75228_b += Math.min(par1, this.getStack().stackSize); } return super.decrStackSize(par1); } public void onPickupFromSlot(EntityPlayer par1EntityPlayer, ItemStack par2ItemStack) { this.onCrafting(par2ItemStack); super.onPickupFromSlot(par1EntityPlayer, par2ItemStack); } /** * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. Typically increases an * internal count then calls onCrafting(item). */ protected void onCrafting(ItemStack par1ItemStack, int par2) { this.field_75228_b += par2; this.onCrafting(par1ItemStack); } /** * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. */ protected void onCrafting(ItemStack par1ItemStack) { par1ItemStack.onCrafting(this.thePlayer.worldObj, this.thePlayer, this.field_75228_b); if (!this.thePlayer.worldObj.isRemote) { int i = this.field_75228_b; float f = CentrifugeRecipes.centrifuging().func_151398_b(par1ItemStack); int j; if (f == 0.0F) { i = 0; } else if (f < 1.0F) { j = MathHelper.floor_float((float)i * f); if (j < MathHelper.ceiling_float_int((float)i * f) && (float)Math.random() < (float)i * f - (float)j) { ++j; } i = j; } while (i > 0) { j = EntityXPOrb.getXPSplit(i); i -= j; this.thePlayer.worldObj.spawnEntityInWorld(new EntityXPOrb(this.thePlayer.worldObj, this.thePlayer.posX, this.thePlayer.posY + 0.5D, this.thePlayer.posZ + 0.5D, j)); } } this.field_75228_b = 0; } }
gpl-3.0
BenObiWan/common
src/common_configuration_core/src/common/config/display/IntegerDisplayType.java
300
package common.config.display; /** * An enum describing how to display a int value. * * @author benobiwan * */ public enum IntegerDisplayType { /** * Value for the spinner. */ SPINNER, /** * Value for the slider. */ SLIDER, /** * Value for the text field. */ TEXTFIELD; }
gpl-3.0
hcondec/anzen
OfficeAssistant/src/main/java/mx/com/anzen/officeassistant/service/PurchaseOrdersService.java
306
package mx.com.anzen.officeassistant.service; import java.util.List; import mx.com.anzen.officeassistant.domain.PurchaseOrder; public interface PurchaseOrdersService { public PurchaseOrder getPurchaseOrder(long id); public List<PurchaseOrder> getNotificationPurchaseOrders(long purchaseOrderId); }
gpl-3.0
ThoNill/BuchhaltungsSimulation
BuchhaltungsSimulation/src/buchhaltung/views/FontResize.java
993
package buchhaltung.views; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.util.Enumeration; import javax.swing.AbstractAction; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.plaf.FontUIResource; /** * Vergrößern, verkleinern des Fonts * * @author Thomas Nill * */ public class FontResize extends AbstractAction { private static final long serialVersionUID = -8497261599407576036L; private boolean verkleinern = true; private FontScale scale; public FontResize(boolean verkleinern,FontScale scale) { super((verkleinern) ? "Schrift--" : "Schrift++"); this.verkleinern = verkleinern; this.scale = scale; } @Override public void actionPerformed(ActionEvent arg0) { scale.expand((verkleinern) ? 1 / 1.2f : 1.2f); } public float getFontScale() { return scale.getScale(); } }
gpl-3.0
Mikescher/jClipCorn
src/main/de/jClipCorn/features/table/filter/customFilter/CustomExactLanguageFilter.java
2406
package de.jClipCorn.features.table.filter.customFilter; import de.jClipCorn.database.CCMovieList; import de.jClipCorn.database.databaseElement.CCEpisode; import de.jClipCorn.database.databaseElement.CCMovie; import de.jClipCorn.database.databaseElement.columnTypes.CCDBLanguageSet; import de.jClipCorn.features.table.filter.AbstractCustomFilter; import de.jClipCorn.features.table.filter.AbstractCustomStructureElementFilter; import de.jClipCorn.features.table.filter.filterConfig.CustomFilterConfig; import de.jClipCorn.features.table.filter.filterConfig.CustomFilterLanguageListConfig; import de.jClipCorn.features.table.filter.filterSerialization.FilterSerializationConfig; import de.jClipCorn.gui.localization.LocaleBundle; public class CustomExactLanguageFilter extends AbstractCustomStructureElementFilter { private CCDBLanguageSet languagelist = CCDBLanguageSet.EMPTY; public CustomExactLanguageFilter(CCMovieList ml) { super(ml); } @Override public boolean includes(CCMovie e) { return e.getLanguage().equals(languagelist); } @Override public boolean includes(CCEpisode e) { return e.getLanguage().equals(languagelist); } @Override public String getName() { return LocaleBundle.getFormattedString("FilterTree.Custom.CustomFilterNames.ExactLanguage", languagelist.toOutputString()); //$NON-NLS-1$ } @Override public String getPrecreateName() { return LocaleBundle.getDeformattedString("FilterTree.Custom.CustomFilterNames.ExactLanguage").replace("()", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } @Override public int getID() { return AbstractCustomFilter.CUSTOMFILTERID_EXACTLANGUAGE; } @Override @SuppressWarnings("nls") protected void initSerialization(FilterSerializationConfig cfg) { cfg.addLong("languagelist", (d) -> this.languagelist = CCDBLanguageSet.fromBitmask(d), () -> this.languagelist.serializeToLong()); } @Override public AbstractCustomFilter createNew(CCMovieList ml) { return new CustomExactLanguageFilter(ml); } public static CustomExactLanguageFilter create(CCMovieList ml, CCDBLanguageSet data) { CustomExactLanguageFilter f = new CustomExactLanguageFilter(ml); f.languagelist = data; return f; } @Override public CustomFilterConfig[] createConfig(CCMovieList ml) { return new CustomFilterConfig[] { new CustomFilterLanguageListConfig(ml, () -> languagelist,p -> languagelist = p), }; } }
gpl-3.0
Mikescher/jClipCorn
src/main/de/jClipCorn/gui/localization/LocaleBundle.java
4746
package de.jClipCorn.gui.localization; import de.jClipCorn.features.log.CCLog; import de.jClipCorn.properties.CCProperties; import de.jClipCorn.util.Str; import java.util.*; public class LocaleBundle { private final static int DEFAULT = 1; private final static String DEFAULT_BASENAME = "de.jClipCorn.gui.localization.locale"; //$NON-NLS-1$ private final static Locale[] LOCALES = {Locale.getDefault(), new Locale("dl", "DL"), Locale.GERMAN, Locale.US}; //$NON-NLS-1$ //$NON-NLS-2$ private static ResourceBundle bundle = null; private static Locale getLocale(CCProperties ccprops) { return LOCALES[ccprops.PROP_UI_LANG.getValue().asInt()]; } private static Locale getLocale(int langID) { return LOCALES[langID]; } private static Locale getDefaultLocale() { return LOCALES[DEFAULT]; } public static String getStringOrDefault(String ident, String def) { try { if (ident.startsWith("@")) return ident.substring(1); //$NON-NLS-1$ if (bundle == null) { return ResourceBundle.getBundle(DEFAULT_BASENAME, getDefaultLocale()).getString(ident); } else { if (! bundle.containsKey(ident)) return def; return bundle.getString(ident); } } catch (MissingResourceException e) { CCLog.addError(e); return ""; //$NON-NLS-1$ } } @SuppressWarnings("nls") public static String getString(String ident) { try { if (ident.startsWith("@")) return ident.substring(1); if (bundle == null) { return ResourceBundle.getBundle(DEFAULT_BASENAME, getDefaultLocale()).getString(ident); } else { return bundle.getString(ident); } } catch (MissingResourceException e) { if (ident.startsWith("CCLog.")) return Str.Empty; // prevent infinite log recursion if _no_ locales were found CCLog.addError(e); return Str.Empty; } } public static String getFormattedString(String ident, Object... args) { return String.format(getString(ident), args); } public static String getMFFormattedString(String ident, Object... args) { return Str.format(getString(ident), args); } public static String getDeformattedString(String ident) { String val = getString(ident); StringBuilder builder = new StringBuilder(); int pos = 0; boolean isSpecial = false; while (pos < val.length()) { boolean skip = false; char c = val.charAt(pos); if (isSpecial) { isSpecial = false; if (Character.isLetter(c)) { skip = true; builder.deleteCharAt(builder.length() - 1); } } else { if (c == '%') isSpecial = true; } if (! skip) { builder.append(c); } pos++; } return builder.toString(); } public static void updateLang(CCProperties ccprops) { bundle = ResourceBundle.getBundle(DEFAULT_BASENAME, getLocale(ccprops)); } public static void updateLangManual(int overrideLang) { bundle = ResourceBundle.getBundle(DEFAULT_BASENAME, getLocale(overrideLang)); } public static int getTranslationCount(CCProperties ccprops) { int c = 0; for (Enumeration<String> enum_s = ResourceBundle.getBundle(DEFAULT_BASENAME, getLocale(ccprops)).getKeys(); enum_s.hasMoreElements(); enum_s.nextElement()) { c++; } return c; } public static Locale getCurrentLocale(CCProperties ccprops) { return getLocale(ccprops); } @SuppressWarnings("nls") private static void addSubListToBuilder(StringBuilder builder, String prefix, List<String> list, int depth) { list.remove(prefix); boolean finished = false; while(! finished) { finished = true; for (int i = 0; i < list.size(); i++) { String s = list.get(i); if (s.startsWith(prefix)) { finished = false; String newPrefix = s.substring(0, prefix.length()); if (s.indexOf('.', newPrefix.length()+1) > 0) newPrefix = s.substring(0, s.indexOf('.', newPrefix.length()+1)); else newPrefix = s; builder.append(Str.repeat(" ", Math.max(0, depth))); builder.append(newPrefix.substring(newPrefix.lastIndexOf('.')+1)); if (bundle.containsKey(s)) builder.append(" (\"").append(getString(s).replaceAll("\r\n", "\\\\r\\\\n")).append("\")"); builder.append("\r\n"); addSubListToBuilder(builder, newPrefix, list, depth + 1); break; } } } } private static String getTranslationTree() { Enumeration<String> enumer = bundle.getKeys(); List<String> list = new ArrayList<>(); StringBuilder builder = new StringBuilder(); while (enumer.hasMoreElements()) { String s = enumer.nextElement(); list.add(s); } Collections.sort(list); addSubListToBuilder(builder, "", list, 0); //$NON-NLS-1$ return builder.toString(); } public static void printTranslationTree() { CCLog.addDebug(getTranslationTree()); } }
gpl-3.0
sicodetv20/dev.sicodetv2.1
src/main/java/ve/com/fsjv/devsicodetv/models/Role.java
2543
package ve.com.fsjv.devsicodetv.models; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; /** * * @author TecnoSoluciones-NS */ @Entity @Table(name="role") public class Role { @Id @GeneratedValue(strategy=IDENTITY) @Column(name="id", unique=true, nullable=false) private long id; @Column(name="title", nullable=false) private String title; @Column(name="description", nullable=true) private String description; @Column(name="status", nullable=false) private int status; @Column(name="createDate", nullable=false) private java.sql.Timestamp createDate; @Column(name="lastUpdated", nullable=false) private java.sql.Timestamp lastUpdated; @Column(name="lastSelected", nullable=false) private java.sql.Timestamp lastSelected; public Role() { } public Role(long id, String title, String description, int status, Timestamp createDate, Timestamp lastUpdated, Timestamp lastSelected) { this.id = id; this.title = title; this.description = description; this.status = status; this.createDate = createDate; this.lastUpdated = lastUpdated; this.lastSelected = lastSelected; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Timestamp getCreateDate() { return createDate; } public void setCreateDate(Timestamp createDate) { this.createDate = createDate; } public Timestamp getLastUpdated() { return lastUpdated; } public void setLastUpdated(Timestamp lastUpdated) { this.lastUpdated = lastUpdated; } public Timestamp getLastSelected() { return lastSelected; } public void setLastSelected(Timestamp lastSelected) { this.lastSelected = lastSelected; } }
gpl-3.0
krampstudio/YajMember
src/main/java/org/yajug/users/servlets/auth/LogoutServlet.java
683
package org.yajug.users.servlets.auth; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class LogoutServlet extends HttpServlet{ private static final long serialVersionUID = 7267921282117546473L; @Inject private LogoutHelper logoutHelper; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logoutHelper.logout(req); resp.sendRedirect("logint.html"); } }
gpl-3.0
wandora-team/wandora
src/org/wandora/application/tools/exporters/ExportSchemaMap.java
7048
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2016 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ExportSchemaMap.java * * Created on August 26, 2004, 2:59 PM */ package org.wandora.application.tools.exporters; import org.wandora.piccolo.WandoraManager; import org.wandora.application.gui.*; import org.wandora.topicmap.*; import org.wandora.application.*; import org.wandora.application.contexts.*; import org.wandora.application.gui.simple.*; import org.wandora.utils.*; import java.io.*; import java.util.*; import javax.swing.*; /** * * @author olli */ public class ExportSchemaMap extends AbstractExportTool implements WandoraTool { public static String[] exportTypes=new String[]{ SchemaBox.CONTENTTYPE_SI, SchemaBox.ASSOCIATIONTYPE_SI, SchemaBox.OCCURRENCETYPE_SI, SchemaBox.ROLE_SI, SchemaBox.ROLECLASS_SI, XTMPSI.LANGUAGE, XTMPSI.SUPERCLASS_SUBCLASS, XTMPSI.DISPLAY, XTMPSI.OCCURRENCE, XTMPSI.SORT, XTMPSI.TOPIC, XTMPSI.SUPERCLASS, XTMPSI.SUBCLASS, XTMPSI.CLASS, XTMPSI.CLASS_INSTANCE, XTMPSI.INSTANCE }; /** * Creates a new instance of ExportSchemaMap */ public ExportSchemaMap() { } @Override public String getName() { return "Export schema topic map"; } @Override public String getDescription() { return "Export schema topic map"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/export_topicmap_schema.png"); } @Override public boolean requiresRefresh() { return false; } @Override public void execute(Wandora admin, Context context) throws TopicMapException { SimpleFileChooser chooser = UIConstants.getFileChooser(); chooser.setDialogTitle("Export Wandora schema..."); if(chooser.open(admin, "Export")==SimpleFileChooser.APPROVE_OPTION){ setDefaultLogger(); File file = chooser.getSelectedFile(); try{ file = IObox.addFileExtension(file, "xtm"); // Ensure file extension exists! TopicMap topicMap = solveContextTopicMap(admin, context); TopicMap schemaTopicMap = exportTypeDefs(topicMap); String name = solveNameForTopicMap(admin, topicMap); if(name != null) { log("Exporting Wandora schema topics of layer '"+ name +"' to '"+ file.getName() + "'."); } else { log("Exporting Wandora schema topics to '"+ file.getName() + "'."); } OutputStream out = new FileOutputStream(file); schemaTopicMap.exportXTM(out); out.close(); log("Ready."); } catch(IOException e) { log(e); } setState(WAIT); } } public static TopicMap exportTypeDefs(TopicMap tm) throws TopicMapException { TopicMap export=new org.wandora.topicmap.memory.TopicMapImpl(); HashSet copyTypes=new HashSet(); for(int i=0;i<exportTypes.length;i++){ Topic t=tm.getTopic(exportTypes[i]); if(t==null) { continue; } copyTypes.add(t); } HashSet copied=new HashSet(); Iterator iter=copyTypes.iterator(); while(iter.hasNext()){ Topic type=(Topic)iter.next(); Iterator iter2=tm.getTopicsOfType(type).iterator(); while(iter2.hasNext()){ Topic topic=(Topic)iter2.next(); if(!copied.contains(topic)){ export.copyTopicIn(topic,false); Iterator iter3=topic.getAssociations().iterator(); while(iter3.hasNext()){ Association a=(Association)iter3.next(); if(copyTypes.contains(a.getType())){ export.copyAssociationIn(a); } } copied.add(topic); } } } copyTypes=new HashSet(); for(int i=0;i<exportTypes.length;i++){ Topic t=export.getTopic(exportTypes[i]); if(t==null) { continue; } copyTypes.add(t); } Topic wandoraClass=export.getTopic(WandoraManager.WANDORACLASS_SI); Topic hideLevel=export.getTopic(WandoraManager.HIDELEVEL_SI); iter=export.getTopics(); while(iter.hasNext()){ Topic t=(Topic)iter.next(); Iterator iter2=new ArrayList(t.getVariantScopes()).iterator(); while(iter2.hasNext()){ Set scope=(Set)iter2.next(); t.removeVariant(scope); } iter2=new ArrayList(t.getDataTypes()).iterator(); while(iter2.hasNext()){ Topic type=(Topic)iter2.next(); if(type!=hideLevel){ t.removeData(type); } } iter2=new ArrayList(t.getTypes()).iterator(); while(iter2.hasNext()){ Topic type=(Topic)iter2.next(); if(!copyTypes.contains(type) && type!=wandoraClass) { t.removeType(type); } } } iter=export.getTopics(); Vector v=new Vector(); while(iter.hasNext()){ Topic t=(Topic)iter.next(); if(t.getAssociations().size()==0 && export.getTopicsOfType(t).size()==0){ v.add(t); } } iter=v.iterator(); while(iter.hasNext()){ Topic t=(Topic)iter.next(); try{ t.remove(); }catch(TopicInUseException tiue){} } TMBox.getOrCreateTopic(export,XTMPSI.getLang("fi")); TMBox.getOrCreateTopic(export,XTMPSI.getLang("en")); TMBox.getOrCreateTopic(export,XTMPSI.DISPLAY); TMBox.getOrCreateTopic(export,XTMPSI.SORT); TMBox.getOrCreateTopic(export,WandoraManager.LANGINDEPENDENT_SI); return export; } }
gpl-3.0
thiagogt/Paraky_estacionamento
test/test/com/br/parakyEstacionamento/mailSender/MailSenderTester.java
489
package test.com.br.parakyEstacionamento.mailSender; import static org.junit.Assert.*; import mailService.MailService; import org.apache.commons.mail.EmailException; import org.junit.Test; public class MailSenderTester { @Test public void shouldSendMailToThimakgt() { try { MailService.sendMail("It Works", "Hi", "thimakgt@gmail.com"); assertTrue(true); } catch (EmailException e) { fail("Nao foi mandado o email: "+e.getMessage()); System.out.println(e); } } }
gpl-3.0
riking/srcds-controller
src/main/java/de/eqc/srcds/handlers/ShutdownHandler.java
2505
/** * This file is part of the Source Dedicated Server Controller 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>. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with srcds-controller (or a modified version of that library), * containing parts covered by the terms of GNU General Public License, * the licensors of this Program grant you additional permission to convey * the resulting work. {Corresponding Source for a non-source form of such a * combination shall include the source code for the parts of srcds-controller * used as well as that of the covered work.} * * For more information, please consult: * <http://www.earthquake-clan.de/srcds/> * <http://code.google.com/p/srcds-controller/> */ package de.eqc.srcds.handlers; import static de.eqc.srcds.core.Constants.SHUTDOWN_DELAY_MILLIS; import java.io.IOException; import java.util.Timer; import com.sun.net.httpserver.HttpExchange; import de.eqc.srcds.core.ShutdownTimer; import de.eqc.srcds.core.Utils; import de.eqc.srcds.xmlbeans.enums.ResponseCode; import de.eqc.srcds.xmlbeans.impl.ControllerResponse; import de.eqc.srcds.xmlbeans.impl.Message; public class ShutdownHandler extends AbstractRegisteredHandler implements RegisteredHandler { @Override public String getPath() { return "/shutdown"; } public void handleRequest(final HttpExchange httpExchange) throws IOException { final ResponseCode code = ResponseCode.INFORMATION; final Message message = new Message(String.format("Controller is going down in %d seconds...", Utils.millisToSecs(SHUTDOWN_DELAY_MILLIS))); outputXmlContent(new ControllerResponse(code, message).toXml()); final Timer timer = new Timer(); timer.schedule(new ShutdownTimer(Utils.millisToSecs(SHUTDOWN_DELAY_MILLIS)), SHUTDOWN_DELAY_MILLIS); } }
gpl-3.0
pmar/lplibs4j
src/test/java/org/lplibs4j/AllTests.java
628
package org.lplibs4j; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ UtilsTest.class, LinearProgramTest.class, SmallLinearProgramTest.class, QuadraticProgramTest.class}) public class AllTests { @BeforeClass public static void setUpClasses() { System.out.println("Test Suite for org.lplibs4j."); System.out.println("Master up."); } @AfterClass public static void tearDownClasses() { System.out.println("Master down."); } }
gpl-3.0
arraydev/snap-desktop
snap-visat-rcp/src/main/java/org/esa/snap/visat/toolviews/placemark/PlacemarkDialog.java
14445
/* * Copyright (C) 2012 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.visat.toolviews.placemark; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.PropertyPane; import org.esa.snap.framework.datamodel.CrsGeoCoding; import org.esa.snap.framework.datamodel.GeoCoding; import org.esa.snap.framework.datamodel.GeoPos; import org.esa.snap.framework.datamodel.PinDescriptor; import org.esa.snap.framework.datamodel.PixelPos; import org.esa.snap.framework.datamodel.Placemark; import org.esa.snap.framework.datamodel.PlacemarkDescriptor; import org.esa.snap.framework.datamodel.Product; import org.esa.snap.framework.datamodel.ProductNode; import org.esa.snap.framework.ui.ModalDialog; import org.esa.snap.util.Guardian; import org.esa.snap.util.StringUtils; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.opengis.referencing.FactoryException; import org.opengis.referencing.operation.TransformException; import java.awt.Window; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * A dialog used to create new placemarks or edit existing placemarks. */ public class PlacemarkDialog extends ModalDialog { private final static String PROPERTY_NAME_NAME = "name"; private final static String PROPERTY_NAME_LABEL = "label"; private final static String PROPERTY_NAME_DESCRIPTION = "description"; private final static String PROPERTY_NAME_STYLE_CSS = "styleCss"; private final static String PROPERTY_NAME_LAT = "lat"; private final static String PROPERTY_NAME_LON = "lon"; private final static String PROPERTY_NAME_PIXEL_X = "pixelX"; private final static String PROPERTY_NAME_PIXEL_Y = "pixelY"; private final static String PROPERTY_NAME_USE_PIXEL_POS = "usePixelPos"; private final Product product; private final boolean canGetPixelPos; private final boolean canGetGeoPos; private final PlacemarkDescriptor placemarkDescriptor; private final BindingContext bindingContext; private boolean adjusting; public PlacemarkDialog(final Window parent, final Product product, final PlacemarkDescriptor placemarkDescriptor, boolean switchGeoAndPixelPositionsEditable) { super(parent, "New " + placemarkDescriptor.getRoleLabel(), ModalDialog.ID_OK_CANCEL, null); /*I18N*/ Guardian.assertNotNull("product", product); this.product = product; this.placemarkDescriptor = placemarkDescriptor; bindingContext = new BindingContext(); final GeoCoding geoCoding = this.product.getGeoCoding(); final boolean hasGeoCoding = geoCoding != null; canGetPixelPos = hasGeoCoding && geoCoding.canGetPixelPos(); canGetGeoPos = hasGeoCoding && geoCoding.canGetGeoPos(); boolean usePixelPos = !hasGeoCoding && switchGeoAndPixelPositionsEditable; PropertySet propertySet = bindingContext.getPropertySet(); propertySet.addProperties(Property.create(PROPERTY_NAME_NAME, ""), Property.create(PROPERTY_NAME_LABEL, ""), Property.create(PROPERTY_NAME_DESCRIPTION, ""), Property.create(PROPERTY_NAME_STYLE_CSS, ""), Property.create(PROPERTY_NAME_LAT, 0.0), Property.create(PROPERTY_NAME_LON, 0.0), Property.create(PROPERTY_NAME_PIXEL_X, 0.0), Property.create(PROPERTY_NAME_PIXEL_Y, 0.0), Property.create(PROPERTY_NAME_USE_PIXEL_POS, usePixelPos) ); propertySet.getProperty(PROPERTY_NAME_USE_PIXEL_POS).getDescriptor().setAttribute("enabled", hasGeoCoding && switchGeoAndPixelPositionsEditable); propertySet.getProperty(PROPERTY_NAME_LAT).getDescriptor().setDisplayName("Latitude"); propertySet.getProperty(PROPERTY_NAME_LAT).getDescriptor().setUnit("deg"); propertySet.getProperty(PROPERTY_NAME_LON).getDescriptor().setDisplayName("Longitude"); propertySet.getProperty(PROPERTY_NAME_LON).getDescriptor().setUnit("deg"); propertySet.getProperty(PROPERTY_NAME_PIXEL_X).getDescriptor().setDisplayName("Pixel X"); propertySet.getProperty(PROPERTY_NAME_PIXEL_X).getDescriptor().setUnit("pixels"); propertySet.getProperty(PROPERTY_NAME_PIXEL_Y).getDescriptor().setDisplayName("Pixel Y"); propertySet.getProperty(PROPERTY_NAME_PIXEL_Y).getDescriptor().setUnit("pixels"); PropertyChangeListener geoChangeListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { updatePixelPos(); } }; propertySet.getProperty(PROPERTY_NAME_LAT).addPropertyChangeListener(geoChangeListener); propertySet.getProperty(PROPERTY_NAME_LON).addPropertyChangeListener(geoChangeListener); PropertyChangeListener pixelChangeListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { updateGeoPos(); } }; propertySet.getProperty(PROPERTY_NAME_PIXEL_X).addPropertyChangeListener(pixelChangeListener); propertySet.getProperty(PROPERTY_NAME_PIXEL_Y).addPropertyChangeListener(pixelChangeListener); /* symbolLabel = new JLabel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (g instanceof Graphics2D) { Graphics2D g2d = (Graphics2D) g; final PixelPos refPoint = symbol.getRefPoint(); Rectangle2D bounds = symbol.getBounds(); double tx = refPoint.getX() - bounds.getX() / 2; double ty = refPoint.getY() - bounds.getY() / 2; g2d.translate(tx, ty); symbol.draw(g2d); g2d.translate(-tx, -ty); } } }; symbolLabel.setPreferredSize(new Dimension(40, 40)); */ setContent(new PropertyPane(bindingContext).createPanel()); if (switchGeoAndPixelPositionsEditable) { bindingContext.bindEnabledState(PROPERTY_NAME_LAT, false, PROPERTY_NAME_USE_PIXEL_POS, true); bindingContext.bindEnabledState(PROPERTY_NAME_LON, false, PROPERTY_NAME_USE_PIXEL_POS, true); bindingContext.bindEnabledState(PROPERTY_NAME_PIXEL_X, true, PROPERTY_NAME_USE_PIXEL_POS, true); bindingContext.bindEnabledState(PROPERTY_NAME_PIXEL_Y, true, PROPERTY_NAME_USE_PIXEL_POS, true); } } public Product getProduct() { return product; } @Override protected void onOK() { if (ProductNode.isValidNodeName(getName())) { super.onOK(); } else { showInformationDialog("'" + getName() + "' is not a valid " + placemarkDescriptor.getRoleLabel() + " name."); /*I18N*/ } } public String getName() { return bindingContext.getPropertySet().getValue(PROPERTY_NAME_NAME); } public void setName(String name) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_NAME, name); } public String getLabel() { return bindingContext.getPropertySet().getValue(PROPERTY_NAME_LABEL); } public void setLabel(String label) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_LABEL, label); } public String getDescription() { return bindingContext.getPropertySet().getValue(PROPERTY_NAME_DESCRIPTION); } public void setDescription(String description) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_DESCRIPTION, description); } public String getStyleCss() { return bindingContext.getPropertySet().getValue(PROPERTY_NAME_STYLE_CSS); } private void setStyleCss(String styleCss) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_STYLE_CSS, styleCss); } public double getPixelX() { return (Double) bindingContext.getPropertySet().getValue(PROPERTY_NAME_PIXEL_X); } public void setPixelX(double pixelX) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_PIXEL_X, pixelX); } public double getPixelY() { return (Double) bindingContext.getPropertySet().getValue(PROPERTY_NAME_PIXEL_Y); } public void setPixelY(double pixelY) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_PIXEL_Y, pixelY); } public double getLat() { return (Double) bindingContext.getPropertySet().getValue(PROPERTY_NAME_LAT); } public void setLat(double lat) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_LAT, lat); } public double getLon() { return (Double) bindingContext.getPropertySet().getValue(PROPERTY_NAME_LON); } public void setLon(double lon) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_LON, lon); } public GeoPos getGeoPos() { return new GeoPos(getLat(), getLon()); } public void setGeoPos(GeoPos geoPos) { if (geoPos != null) { setLat(geoPos.lat); setLon(geoPos.lon); } else { setLat(0.0F); setLon(0.0F); } } public PixelPos getPixelPos() { return new PixelPos(getPixelX(), getPixelY()); } public void setPixelPos(PixelPos pixelPos) { if (pixelPos != null) { setPixelX(pixelPos.x); setPixelY(pixelPos.y); } else { setPixelX(0.0F); setPixelY(0.0F); } } private void updatePixelPos() { if (canGetPixelPos && !adjusting) { adjusting = true; PixelPos pixelPos = placemarkDescriptor.updatePixelPos(product.getGeoCoding(), getGeoPos(), getPixelPos()); setPixelPos(pixelPos); adjusting = false; } } private void updateGeoPos() { if (canGetGeoPos && !adjusting) { adjusting = true; GeoPos geoPos = placemarkDescriptor.updateGeoPos(product.getGeoCoding(), getPixelPos(), getGeoPos()); setGeoPos(geoPos); adjusting = false; } } /** * Shows a dialog to edit the properties of an placemark. * If the placemark does not belong to a product it will be added after editing. * * @param parent the parent window fo the dialog * @param product the product where the placemark is already contained or where it will be added * @param placemark the placemark to edit * @param placemarkDescriptor the descriptor of the placemark * @return <code>true</code> if editing was successful, otherwise <code>false</code>. */ public static boolean showEditPlacemarkDialog(Window parent, Product product, Placemark placemark, PlacemarkDescriptor placemarkDescriptor) { final PlacemarkDialog dialog = new PlacemarkDialog(parent, product, placemarkDescriptor, placemarkDescriptor instanceof PinDescriptor); boolean belongsToProduct = placemark.getProduct() != null; String titlePrefix = belongsToProduct ? "Edit" : "New"; String roleLabel = StringUtils.firstLetterUp(placemarkDescriptor.getRoleLabel()); dialog.getJDialog().setTitle(titlePrefix + " " + roleLabel); dialog.getJDialog().setName(titlePrefix + "_" + roleLabel); dialog.setName(placemark.getName()); dialog.setLabel(placemark.getLabel()); dialog.setDescription(placemark.getDescription() != null ? placemark.getDescription() : ""); // prevent that geoPos change updates pixelPos and vice versa during dialog creation dialog.adjusting = true; dialog.setPixelPos(placemark.getPixelPos()); GeoPos geoPos = placemark.getGeoPos(); dialog.setGeoPos(geoPos != null ? geoPos : new GeoPos(Float.NaN, Float.NaN)); dialog.adjusting = false; dialog.setStyleCss(placemark.getStyleCss()); boolean ok = (dialog.show() == ID_OK); if (ok) { if (!belongsToProduct) { // must add to product, otherwise setting the pixel position wil fail placemarkDescriptor.getPlacemarkGroup(product).add(placemark); } placemark.setName(dialog.getName()); placemark.setLabel(dialog.getLabel()); placemark.setDescription(dialog.getDescription()); placemark.setGeoPos(dialog.getGeoPos()); placemark.setPixelPos(dialog.getPixelPos()); placemark.setStyleCss(dialog.getStyleCss()); } return ok; } public static void main(String[] args) throws TransformException, FactoryException { Product product1 = new Product("A", "B", 360, 180); product1.setGeoCoding(new CrsGeoCoding(DefaultGeographicCRS.WGS84, 360, 180, -180.0, 90.0, 1.0, 1.0, 0.0, 0.0)); PinDescriptor descriptor = PinDescriptor.getInstance(); Placemark pin1 = Placemark.createPointPlacemark(descriptor, "pin_1", "Pin 1", "Schnatter!", new PixelPos(0, 0), new GeoPos(), product1.getGeoCoding()); product1.getPinGroup().add(pin1); showEditPlacemarkDialog(null, product1, pin1, descriptor); } }
gpl-3.0
ktg/ect
equip/src/equip/net/TraderMoniker.java
5276
/* <COPYRIGHT> Copyright (c) 2002-2005, University of Nottingham All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the University of Nottingham nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. </COPYRIGHT> Created by: Chris Greenhalgh (University of Nottingham) Contributors: Chris Greenhalgh (University of Nottingham) */ /* TraderMoniker * autogenerated from ../../include/eqTraderTypes.idl * by eqidl * DO NOT MODIFY */ package equip.net; import equip.runtime.*; /** moniker that uses the trader to look up another moniker * (IDL'd in eqTraderTypes.idl) */ public abstract class TraderMoniker extends equip.net.Moniker { /** Default no-arg constructor */ public TraderMoniker() {} /* member variables */ /** The (simple?) moniker of the trader itself */ public equip.net.Moniker trader; /** the name of the class wanted from the trader */ public String classname; /** the name with which the instance is registered with the trader * (as in EQUIP trader URL) */ public String name; /** Ask moniker to contact the specific trader and * (re)register itself. * * @return true = ok */ public abstract boolean rebind(equip.net.Moniker proxyMoniker); /** IDL-generated helper routine to get module name (currently <b>unimplemented</b>). * @return name of this class's module */ public String getModuleName() { return null; } /** Standard IDL-generated equality test. * @param c The object to be compared against this. * @return true if this is equal to <code>c</code> */ public boolean equals(java.lang.Object c) { if (c==null) return false; if (!c.getClass().equals(getClass())) return false; return _equals_helper((TraderMoniker)c); } /** Internal IDL-generated equality test helper */ public boolean _equals_helper(TraderMoniker c) { if (c==null) return false; if (!super._equals_helper(c)) return false; if (trader!=c.trader && (trader==null || !trader.equals(c.trader))) return false; if(classname!=c.classname && (classname==null || c.classname == null || !classname.equals(c.classname))) return false; if(name!=c.name && (name==null || c.name == null || !name.equals(c.name))) return false; return true; } /** Standard IDL-generated template match test. * @param c The object to be checked against this template. * @return true if <code>this</code> (as a template) matches the argument */ public boolean matches(java.lang.Object c) { if (c==null || !(c instanceof TraderMoniker)) return false; return _matches_helper((TraderMoniker)c); } /** Internal IDL-generated match test helper */ public boolean _matches_helper(TraderMoniker c) { if (c==null) return false; if (!super._matches_helper(c)) return false; if (trader!=null && !trader.matches(c.trader)) return false; if(classname!=null && (c.classname == null || !classname.equals(c.classname))) return false; if(name!=null && (c.name == null || !name.equals(c.name))) return false; return true; } /** Internal IDL-generated serialisation helper. Used by {@link equip.runtime.ObjectInputStream} and {@link equip.runtime.ObjectOutputStream} only. */ public void writeObject(ObjectOutputStream out) throws java.io.IOException { super.writeObject(out); out.writeObjectStart(); out.writeObject(trader); out.writeString(classname); out.writeString(name); out.writeObjectEnd(); } /** Internal IDL-generated serialisation helper. Used by {@link ObjectInputStream} and {@link ObjectOutputStream} only. */ public void readObject(ObjectInputStream in) throws java.io.IOException, ClassNotFoundException, InstantiationException { super.readObject(in); in.readObjectStart(); trader = (equip.net.Moniker )in.readObject(); classname = in.readString(); name = in.readString(); in.readObjectEnd(); } } /* class TraderMoniker */ /* EOF */
gpl-3.0
sergioramossilva/TCC
src/br/edu/utfpr/cm/tcc/MinhasRotas.java
64
package br.edu.utfpr.cm.tcc; public class MinhasRotas { }
gpl-3.0
drbizzaro/diggime
base/main/src/com/diggime/modules/contact_person/model/ContactMethod.java
294
package com.diggime.modules.contact_person.model; import java.time.LocalDateTime; public interface ContactMethod { int getId(); ContactMethodType getType(); String getOwnNameType(); String getAddress(); LocalDateTime getFromDate(); LocalDateTime getToDate(); }
gpl-3.0
j0ach1mmall3/PermissionsShop
src/main/java/com/j0ach1mmall3/permissionsshop/config/Shops.java
3185
package com.j0ach1mmall3.permissionsshop.config; import com.j0ach1mmall3.jlib.storage.file.yaml.ConfigLoader; import com.j0ach1mmall3.permissionsshop.Main; import com.j0ach1mmall3.permissionsshop.api.Category; import com.j0ach1mmall3.permissionsshop.api.CategoryPackageHolder; import com.j0ach1mmall3.permissionsshop.api.Package; import com.j0ach1mmall3.permissionsshop.api.Shop; import java.util.List; import java.util.stream.Collectors; public final class Shops extends ConfigLoader<Main> { private final List<Shop> shops; public Shops(Main plugin) { super("shops.yml", plugin); this.shops = this.customConfig.getKeys("Shops").stream().map(this::loadShopByIdentifier).collect(Collectors.toList()); } private Shop loadShopByIdentifier(String identifier) { Shop shop = new Shop( identifier, this.config.getString("Shops." + identifier + ".Command"), this.config.getString("Shops." + identifier + ".Permission"), this.config.getDouble("Shops." + identifier + ".Price"), this.config.getString("Shops." + identifier + ".GuiName"), this.config.getInt("Shops." + identifier + ".GuiSize") ); shop.setParent(null); shop.setCategories(this.customConfig.getKeys("Shops." + identifier + ".Categories").stream().map(s -> this.loadCategoryByIdentifier("Shops." + identifier + ".Categories." + s, s, shop)).collect(Collectors.toList())); shop.setPackages(this.customConfig.getKeys("Shops." + identifier + ".Packages").stream().map(s -> this.loadPackageByIdentifier("Shops." + identifier + ".Packages." + s, s, shop)).collect(Collectors.toList())); return shop; } private Category loadCategoryByIdentifier(String path, String identifier, CategoryPackageHolder parent) { Category category = new Category( identifier, this.config.getString(path + ".Permission"), this.config.getDouble(path + ".Price"), this.customConfig.getJLibItem(this.config, path), this.config.getInt(path + ".GuiSize") ); category.setParent(parent); category.setCategories(this.customConfig.getKeys(path + ".Categories").stream().map(s -> this.loadCategoryByIdentifier(path + ".Categories." + s, s, category)).collect(Collectors.toList())); category.setPackages(this.customConfig.getKeys(path + ".Packages").stream().map(s -> this.loadPackageByIdentifier(path + ".Packages." + s, s, category)).collect(Collectors.toList())); return category; } private Package loadPackageByIdentifier(String path, String identifier, CategoryPackageHolder parent) { Package pckage = new Package( identifier, this.config.getString(path + ".Permission"), this.config.getDouble(path + ".Price"), this.customConfig.getJLibItem(this.config, path), this.config.getStringList(path + ".Commands") ); pckage.setParent(parent); return pckage; } public List<Shop> getShops() { return this.shops; } }
gpl-3.0
straumat/api-base-sirene
src/main/java/com/oakinvest/abs/service/ImportService.java
71
package com.oakinvest.abs.service; public interface ImportService { }
gpl-3.0
HFTSoftwareProject/MoJEC-Backend
src/main/java/de/hftstuttgart/exceptions/NoZipFileException.java
375
package de.hftstuttgart.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** * Created by Marcel Bochtler on 29.11.16. */ @ResponseStatus(HttpStatus.BAD_REQUEST) public class NoZipFileException extends RuntimeException { public NoZipFileException(String message) { super(message); } }
gpl-3.0
JhonPolitecnico/Proyectos-2014
MIDIPlayer/src/gui/load/Load.java
2193
package gui.load; /** * MIDIPlayer * * @author Jhon Jairo Eslava * @code 1310012946 * */ import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JScrollPane; import javax.swing.JList; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.JButton; import javax.swing.ListSelectionModel; import playlist.PlayList; public abstract class Load extends JFrame { private static final long serialVersionUID = 7374801605100165298L; protected JPanel contentPane; protected JList<PlayList> list; protected JButton btnLoad; /** * Create the frame. */ public Load() { setTitle("Cargar Lista"); setName("frmSave"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 237, 488); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); JScrollPane scrollPane = new JScrollPane(); btnLoad = new JButton("Cargar"); GroupLayout gl_contentPane = new GroupLayout(contentPane); gl_contentPane.setHorizontalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING).addGroup( gl_contentPane .createSequentialGroup() .addContainerGap() .addGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup().addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE).addContainerGap()) .addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup().addComponent(btnLoad).addGap(68))))); gl_contentPane.setVerticalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING).addGroup( gl_contentPane.createSequentialGroup().addContainerGap().addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 397, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(btnLoad).addGap(2))); list = new JList<PlayList>(); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); scrollPane.setViewportView(list); contentPane.setLayout(gl_contentPane); } }
gpl-3.0
jaffa-projects/jaffa-framework
jaffa-core/source/java/org/jaffa/persistence/engines/jdbcengine/querygenerator/PreparedStatementHelper.java
18928
/* * ==================================================================== * JAFFA - Java Application Framework For All * * Copyright (C) 2002 JAFFA Development Group * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Redistribution and use of this software and associated documentation ("Software"), * with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain copyright statements and notices. * Redistributions must also contain a copy of this document. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name "JAFFA" must not be used to endorse or promote products derived from * this Software without prior written permission. For written permission, * please contact mail to: jaffagroup@yahoo.com. * 4. Products derived from this Software may not be called "JAFFA" nor may "JAFFA" * appear in their names without prior written permission. * 5. Due credit should be given to the JAFFA Project (http://jaffa.sourceforge.net). * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== */ package org.jaffa.persistence.engines.jdbcengine.querygenerator; import java.util.*; import org.jaffa.persistence.Criteria; import org.jaffa.persistence.engines.jdbcengine.configservice.ClassMetaData; import org.jaffa.persistence.engines.jdbcengine.variants.Variant; /** This class has functions to return SQL Strings used in PreparedStatements. * These Strings are cached for efficiency purposes. */ public class PreparedStatementHelper { // the caches private static Map c_insertStatementCache = new WeakHashMap(); private static Map c_updateStatementCache = new WeakHashMap(); private static Map c_deleteStatementCache = new WeakHashMap(); private static Map c_lockStatementCache = new WeakHashMap(); private static Map c_findByPKStatementCache = new WeakHashMap(); private static Map c_findByPKForUpdateStatementCache = new WeakHashMap(); private static Map c_existsStatementCache = new WeakHashMap(); // some constants used in the methods. private static final String INSERT_INTO = "INSERT INTO"; private static final String VALUES = "VALUES"; private static final String UPDATE = "UPDATE"; private static final String SET = "SET"; private static final String WHERE = "WHERE"; private static final String AND = "AND"; private static final String DELETE_FROM = "DELETE FROM"; private static final String SELECT_1_FROM = "SELECT 1 FROM"; private static final String SELECT = "SELECT"; private static final String DOT_STAR = ".*"; private static final String FROM = "FROM"; private static final String SELECT_COUNT_STAR_FROM = "SELECT COUNT(*) \"" + Criteria.ID_FUNCTION_COUNT + "\" FROM"; /** Returns a SQL String for use in PreparedStatements for inserting records into the table corresponding to the input ClassMetaData object. * This String is cached. * @param classMetaData the meta object, for which the PreparedStatement String is to be generated. * @return a SQL String for use in PreparedStatements for inserting records. */ public static String getInsertPreparedStatementString(ClassMetaData classMetaData, String engineType) { String sql; synchronized (c_insertStatementCache) { sql = (String)c_insertStatementCache.get(classMetaData.getClassName()); } if (sql == null) { StringBuffer buf1 = new StringBuffer(); buf1.append('('); // the fieldlist buffer StringBuffer buf2 = new StringBuffer(); buf2.append('('); // the Values buffer boolean first = true; for (Iterator i = classMetaData.getNonAutoKeyFieldNames().iterator(); i.hasNext();) { if (first) { first = false; } else { buf1.append(','); buf2.append(','); } buf1.append(formatSqlName(classMetaData.getSqlName((String) i.next()), engineType)); buf2.append('?'); } for (Iterator i = classMetaData.getAttributes().iterator(); i.hasNext();) { if (first) { first = false; } else { buf1.append(','); buf2.append(','); } buf1.append(formatSqlName(classMetaData.getSqlName((String) i.next()), engineType)); buf2.append('?'); } buf1.append(')'); buf2.append(')'); StringBuffer buf = new StringBuffer(INSERT_INTO); buf.append(' '); buf.append(classMetaData.getTable()); buf.append(buf1); buf.append(' '); buf.append(VALUES); buf.append(buf2); synchronized(c_insertStatementCache) { //check again before inserting into cache sql = (String) c_insertStatementCache.get(classMetaData.getClassName()); if (sql == null) { sql = buf.toString(); c_insertStatementCache.put(classMetaData.getClassName(), sql); } } } return sql; } /** Returns a SQL String for use in PreparedStatements for updating records in the table corresponding to the input ClassMetaData object. * This String is cached. * @param classMetaData the meta object, for which the PreparedStatement String is to be generated. * @return a SQL String for use in PreparedStatements for updating records. */ public static String getUpdatePreparedStatementString(ClassMetaData classMetaData, String engineType) { String sql; synchronized (c_updateStatementCache) { sql = (String)c_updateStatementCache.get(classMetaData.getClassName()); } if (sql == null) { StringBuffer buf = new StringBuffer(UPDATE); buf.append(' '); buf.append(classMetaData.getTable()); buf.append(' '); buf.append(SET); buf.append(' '); boolean first = true; for (Iterator i = classMetaData.getAttributes().iterator(); i.hasNext();) { if (first) { first = false; } else { buf.append(','); } buf.append(formatSqlName(classMetaData.getSqlName((String) i.next()), engineType)); buf.append('='); buf.append('?'); } buf.append(' '); buf.append(WHERE); buf.append(' '); first = true; for (Iterator i = classMetaData.getAllKeyFieldNames().iterator(); i.hasNext();) { if (first) { first = false; } else { buf.append(' '); buf.append(AND); buf.append(' '); } buf.append(formatSqlName(classMetaData.getSqlName((String) i.next()), engineType)); buf.append('='); buf.append('?'); } synchronized(c_updateStatementCache) { //check again before inserting into cache sql = (String) c_updateStatementCache.get(classMetaData.getClassName()); if (sql == null) { sql = buf.toString(); c_updateStatementCache.put(classMetaData.getClassName(), sql); } } } return sql; } /** Returns a SQL String for use in PreparedStatements for deleting records from the table corresponding to the input ClassMetaData object. * This String is cached. * @param classMetaData the meta object, for which the PreparedStatement String is to be generated. * @return a SQL String for use in PreparedStatements for deleting records. */ public static String getDeletePreparedStatementString(ClassMetaData classMetaData, String engineType) { String sql; synchronized (c_deleteStatementCache) { sql = (String)c_deleteStatementCache.get(classMetaData.getClassName()); } if (sql == null) { StringBuffer buf = new StringBuffer(DELETE_FROM); buf.append(' '); buf.append(classMetaData.getTable()); buf.append(' '); buf.append(WHERE); buf.append(' '); boolean first = true; for (Iterator i = classMetaData.getAllKeyFieldNames().iterator(); i.hasNext();) { if (first) { first = false; } else { buf.append(' '); buf.append(AND); buf.append(' '); } buf.append(formatSqlName(classMetaData.getSqlName((String) i.next()), engineType)); buf.append('='); buf.append('?'); } synchronized(c_deleteStatementCache) { //check again before inserting into cache sql = (String) c_deleteStatementCache.get(classMetaData.getClassName()); if (sql == null) { sql = buf.toString(); c_deleteStatementCache.put(classMetaData.getClassName(), sql); } } } return sql; } /** Returns a SQL String for use in PreparedStatements for locking records in the table corresponding to the input ClassMetaData object. * This String is cached. * @param classMetaData the meta object, for which the PreparedStatement String is to be generated. * @param engineType The engine type as defined in init.xml * @return a SQL String for use in PreparedStatements for locking records. */ public static String getLockPreparedStatementString(ClassMetaData classMetaData, String engineType) { String sql; synchronized(c_lockStatementCache) { sql = (String)c_lockStatementCache.get(classMetaData.getClassName()); } if (sql == null) { StringBuffer buf = new StringBuffer(SELECT_1_FROM); buf.append(' '); buf.append(classMetaData.getTable()); buf.append(' '); // Added for supplying Locking 'Hints' used by SqlServer buf.append(Variant.getProperty(engineType, Variant.PROP_LOCK_CONSTRUCT_IN_FROM_SELECT_STATEMENT)); buf.append(' '); buf.append(WHERE); buf.append(' '); boolean first = true; for (Iterator i = classMetaData.getAllKeyFieldNames().iterator(); i.hasNext();) { if (first) { first = false; } else { buf.append(AND); buf.append(' '); } buf.append(formatSqlName(classMetaData.getSqlName((String) i.next()), engineType)); buf.append('='); buf.append('?'); buf.append(' '); } buf.append(Variant.getProperty(engineType, Variant.PROP_LOCK_CONSTRUCT_IN_SELECT_STATEMENT)); synchronized(c_lockStatementCache) { //check again before inserting into cache sql = (String) c_lockStatementCache.get(classMetaData.getClassName()); if (sql == null) { sql = buf.toString(); c_lockStatementCache.put(classMetaData.getClassName(), sql); } } } return sql; } /** Returns a SQL String for use in PreparedStatements for retrieving records by their primary key. * @param locking the locking strategy for a query. * @param classMetaData the meta object, for which the PreparedStatement String is to be generated. * @param engineType The engine type as defined in init.xml * @return a SQL String for use in PreparedStatements for retrieving records by their primary key. */ public static String getFindByPKPreparedStatementString(int locking, ClassMetaData classMetaData, String engineType) { String sql = null; if (locking == Criteria.LOCKING_PARANOID && classMetaData.isLockable()) { synchronized (c_findByPKForUpdateStatementCache) { sql = (String)c_findByPKForUpdateStatementCache.get(classMetaData.getClassName()); } } else { synchronized (c_findByPKStatementCache) { sql = (String)c_findByPKStatementCache.get(classMetaData.getClassName()); } } if (sql == null) { StringBuffer whereBuf = new StringBuffer(); for (Iterator i = classMetaData.getAllKeyFieldNames().iterator(); i.hasNext();) { if (whereBuf.length() > 0) whereBuf.append(' ').append(AND).append(' '); String attributeName = (String) i.next(); whereBuf.append(formatSqlName(classMetaData.getSqlName(attributeName), engineType)).append('=').append('?'); } StringBuffer buf = new StringBuffer(SELECT) .append(' ') .append(classMetaData.getTable()).append(DOT_STAR) .append(' ') .append(FROM) .append(' ') .append(classMetaData.getTable()); // Added for supplying Locking 'Hints' used by MS-Sql-Server if (locking == Criteria.LOCKING_PARANOID && classMetaData.isLockable()) buf.append(' ').append(Variant.getProperty(engineType, Variant.PROP_LOCK_CONSTRUCT_IN_FROM_SELECT_STATEMENT)); buf.append(' ') .append(WHERE) .append(' ') .append(whereBuf); if (locking == Criteria.LOCKING_PARANOID && classMetaData.isLockable()) buf.append(' ').append(Variant.getProperty(engineType, Variant.PROP_LOCK_CONSTRUCT_IN_SELECT_STATEMENT)); //check again before inserting into cache if (locking == Criteria.LOCKING_PARANOID && classMetaData.isLockable()) { synchronized(c_findByPKForUpdateStatementCache) { sql = (String) c_findByPKForUpdateStatementCache.get(classMetaData.getClassName()); if (sql == null) { sql = buf.toString(); c_findByPKForUpdateStatementCache.put(classMetaData.getClassName(), sql); } } } else { synchronized(c_findByPKStatementCache) { sql = (String) c_findByPKStatementCache.get(classMetaData.getClassName()); if (sql == null) { sql = buf.toString(); c_findByPKStatementCache.put(classMetaData.getClassName(), sql); } } } } return sql; } /** Returns a SQL String for use in PreparedStatements for checking the existence of records by their primary key. * @param classMetaData the meta object, for which the PreparedStatement String is to be generated. * @param engineType The engine type as defined in init.xml * @return a SQL String for use in PreparedStatements for existence checks. */ public static String getExistsPreparedStatementString(ClassMetaData classMetaData, String engineType) { String sql; synchronized (c_existsStatementCache) { sql = (String)c_existsStatementCache.get(classMetaData.getClassName()); } if (sql == null) { StringBuffer buf = new StringBuffer(SELECT_COUNT_STAR_FROM) .append(' ') .append(classMetaData.getTable()) .append(' ') .append(WHERE); boolean first = true; for (Iterator i = classMetaData.getAllKeyFieldNames().iterator(); i.hasNext();) { if (first) first = false; else buf.append(' ').append(AND); String attributeName = (String) i.next(); buf.append(' ').append(formatSqlName(classMetaData.getSqlName(attributeName), engineType)).append('=').append('?'); } synchronized(c_existsStatementCache) { //check again before inserting into cache sql = (String) c_existsStatementCache.get(classMetaData.getClassName()); if (sql == null) { sql = buf.toString(); c_existsStatementCache.put(classMetaData.getClassName(), sql); } } } return sql; } private static String formatSqlName(String sqlName, String engineType) { if (sqlName != null && "mssqlserver".equals(engineType)) { sqlName = "[" + sqlName + "]"; } return sqlName; } }
gpl-3.0
aleatorio12/ProVentasConnector
jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/crosstabs/design/JRDesignCrosstabRowGroup.java
4033
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.crosstabs.design; import java.io.IOException; import java.io.ObjectInputStream; import net.sf.jasperreports.crosstabs.JRCrosstabRowGroup; import net.sf.jasperreports.crosstabs.type.CrosstabRowPositionEnum; import net.sf.jasperreports.engine.JRConstants; /** * Crosstab row group implementation to be used for report designing. * * @author Lucian Chirita (lucianc@users.sourceforge.net) */ public class JRDesignCrosstabRowGroup extends JRDesignCrosstabGroup implements JRCrosstabRowGroup { private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID; public static final String PROPERTY_POSITION = "position"; public static final String PROPERTY_WIDTH = "width"; protected int width; protected CrosstabRowPositionEnum positionValue = CrosstabRowPositionEnum.TOP; public JRDesignCrosstabRowGroup() { super(); } public CrosstabRowPositionEnum getPositionValue() { return positionValue; } /** * Sets the header contents stretch position. * * @param positionValue the header contents stretch position * @see JRCrosstabRowGroup#getPositionValue() */ public void setPosition(CrosstabRowPositionEnum positionValue) { Object old = this.positionValue; this.positionValue = positionValue; getEventSupport().firePropertyChange(PROPERTY_POSITION, old, this.positionValue); } public int getWidth() { return width; } /** * Sets the header cell width. * * @param width the width * @see JRCrosstabRowGroup#getWidth() */ public void setWidth(int width) { int old = this.width; this.width = width; getEventSupport().firePropertyChange(PROPERTY_WIDTH, old, this.width); } public void setHeader(JRDesignCellContents header) { super.setHeader(header); setCellOrigin(this.header, new JRCrosstabOrigin(getParent(), JRCrosstabOrigin.TYPE_ROW_GROUP_HEADER, getName(), null)); } public void setTotalHeader(JRDesignCellContents totalHeader) { super.setTotalHeader(totalHeader); setCellOrigin(this.totalHeader, new JRCrosstabOrigin(getParent(), JRCrosstabOrigin.TYPE_ROW_GROUP_TOTAL_HEADER, getName(), null)); } void setParent(JRDesignCrosstab parent) { super.setParent(parent); setCellOrigin(this.header, new JRCrosstabOrigin(getParent(), JRCrosstabOrigin.TYPE_ROW_GROUP_HEADER, getName(), null)); setCellOrigin(this.totalHeader, new JRCrosstabOrigin(getParent(), JRCrosstabOrigin.TYPE_ROW_GROUP_TOTAL_HEADER, getName(), null)); } /* * These fields are only for serialization backward compatibility. */ private int PSEUDO_SERIAL_VERSION_UID = JRConstants.PSEUDO_SERIAL_VERSION_UID; //NOPMD /** * @deprecated */ private byte position; @SuppressWarnings("deprecation") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (PSEUDO_SERIAL_VERSION_UID < JRConstants.PSEUDO_SERIAL_VERSION_UID_3_7_2) { positionValue = CrosstabRowPositionEnum.getByValue(position); } } }
gpl-3.0
LeoTremblay/activityinfo
server/src/main/java/org/activityinfo/ui/client/component/report/editor/map/layerOptions/ClusteringOptionsWidget.java
6860
package org.activityinfo.ui.client.component.report.editor.map.layerOptions; /* * #%L * ActivityInfo Server * %% * Copyright (C) 2009 - 2013 UNICEF * %% * 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.extjs.gxt.ui.client.Style.Orientation; import com.extjs.gxt.ui.client.event.Events; import com.extjs.gxt.ui.client.event.FieldEvent; import com.extjs.gxt.ui.client.event.Listener; import com.extjs.gxt.ui.client.widget.LayoutContainer; import com.extjs.gxt.ui.client.widget.form.Radio; import com.extjs.gxt.ui.client.widget.form.RadioGroup; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.HasValue; import org.activityinfo.i18n.shared.I18N; import org.activityinfo.legacy.client.Dispatcher; import org.activityinfo.legacy.shared.command.GetSchema; import org.activityinfo.legacy.shared.model.*; import org.activityinfo.legacy.shared.reports.model.clustering.AdministrativeLevelClustering; import org.activityinfo.legacy.shared.reports.model.clustering.AutomaticClustering; import org.activityinfo.legacy.shared.reports.model.clustering.Clustering; import org.activityinfo.legacy.shared.reports.model.clustering.NoClustering; import org.activityinfo.legacy.shared.reports.model.layers.MapLayer; import java.util.List; import java.util.Set; /* * Shows a list of options to aggregate markers on the map */ public class ClusteringOptionsWidget extends LayoutContainer implements HasValue<Clustering> { private Clustering value = new NoClustering(); private class ClusteringRadio extends Radio { private Clustering clustering; ClusteringRadio(String label, Clustering clustering) { this.clustering = clustering; this.setBoxLabel(label); } public Clustering getClustering() { return clustering; } } private List<ClusteringRadio> radios; private RadioGroup radioGroup; private Dispatcher service; public ClusteringOptionsWidget(Dispatcher service) { super(); this.service = service; } private void destroyForm() { if (radioGroup != null) { radioGroup.removeAllListeners(); } radioGroup = null; removeAll(); } public void loadForm(final MapLayer layer) { // mask(); destroyForm(); service.execute(new GetSchema(), new AsyncCallback<SchemaDTO>() { @Override public void onFailure(Throwable caught) { // TODO Auto-generated method stub } @Override public void onSuccess(SchemaDTO schema) { buildForm(countriesForLayer(schema, layer)); } }); } private void buildForm(Set<CountryDTO> countries) { radios = Lists.newArrayList(); radios.add(new ClusteringRadio(I18N.CONSTANTS.none(), new NoClustering())); radios.add(new ClusteringRadio(I18N.CONSTANTS.automatic(), new AutomaticClustering())); if (countries.size() == 1) { CountryDTO country = countries.iterator().next(); for (AdminLevelDTO level : country.getAdminLevels()) { AdministrativeLevelClustering clustering = new AdministrativeLevelClustering(); clustering.getAdminLevels().add(level.getId()); radios.add(new ClusteringRadio(level.getName(), clustering)); } } radioGroup = new RadioGroup(); radioGroup.setOrientation(Orientation.VERTICAL); radioGroup.setStyleAttribute("padding", "5px"); for (ClusteringRadio radio : radios) { radioGroup.add(radio); if (radio.getClustering().equals(value)) { radioGroup.setValue(radio); } } add(radioGroup); radioGroup.addListener(Events.Change, new Listener<FieldEvent>() { @Override public void handleEvent(FieldEvent be) { ClusteringRadio radio = (ClusteringRadio) radioGroup.getValue(); setValue(radio.getClustering(), true); } }); layout(); // unmask(); } private Set<CountryDTO> countriesForLayer(SchemaDTO schema, MapLayer layer) { Set<Integer> indicatorIds = Sets.newHashSet(layer.getIndicatorIds()); Set<CountryDTO> countries = Sets.newHashSet(); for (UserDatabaseDTO database : schema.getDatabases()) { if (databaseContainsIndicatorId(database, indicatorIds)) { countries.add(database.getCountry()); } } return countries; } private boolean databaseContainsIndicatorId(UserDatabaseDTO database, Set<Integer> indicatorIds) { for (ActivityDTO activity : database.getActivities()) { for (IndicatorDTO indicator : activity.getIndicators()) { if (indicatorIds.contains(indicator.getId())) { return true; } } } return false; } @Override public HandlerRegistration addValueChangeHandler(ValueChangeHandler<Clustering> handler) { return addHandler(handler, ValueChangeEvent.getType()); } @Override public Clustering getValue() { return ((ClusteringRadio) radioGroup.getValue()).getClustering(); } @Override public void setValue(Clustering value) { setValue(value, true); } @Override public void setValue(Clustering value, boolean fireEvents) { this.value = value; if (radioGroup != null) { updateSelectedRadio(); } if (fireEvents) { ValueChangeEvent.fire(this, value); } } private void updateSelectedRadio() { for (ClusteringRadio radio : radios) { if (radio.getClustering().equals(value)) { radioGroup.setValue(radio); return; } } } }
gpl-3.0
WIPeinJavaProjekt/WIPProjekt
Snowventure/src/servlets/StartServlet.java
4453
package servlets; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import classes.Article; import classes.ArticleColor; import classes.Categorie; import classes.User; import classes.Utils; import services.ArticleColorService; import services.ArticleService; import services.ArticleSizesService; import services.ArtilceManufacturerService; import services.CategorieService; /** * Start servlet implementation for the main page and the navigation */ /** * Beschreibung: * @author Garrit Kniepkamp, Fabian Meise * */ @WebServlet("/start") public class StartServlet extends HttpServlet { private static final long serialVersionUID = 1L; public StartServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ArrayList<Article> articles; request.getSession().setAttribute("availableSizes", Utils.getAllSizes()); try { ArrayList<Categorie> categories = CategorieService.GetCategories(); ArrayList<String> manufacturers = ArtilceManufacturerService.GetAllPossibleManufacturers(); ArrayList<String> sizes = ArticleSizesService.GetAllPossibleSizes(); ArrayList<ArticleColor> colors = ArticleColorService.GetAllPossibleColors(); Article bestseller = ArticleService.GetArticle(39); request.getSession().setAttribute("articleColors", colors); request.getSession().setAttribute("availableSizes", sizes); request.getSession().setAttribute("availableManufacturers", manufacturers); request.getSession().setAttribute("categories", categories); request.getSession().setAttribute("bestseller", bestseller); } catch (SQLException e) { e.printStackTrace(); } User currentUser = (User) request.getSession().getAttribute("currentUser"); RequestDispatcher rd = request.getRequestDispatcher("/JSP/welcome.jsp"); rd.forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(request.getParameter("login") != null) { response.sendRedirect(request.getContextPath() + "/login"); return; } else if(request.getParameter("logout") != null) { logout(request); response.sendRedirect("start"); return; } else if(request.getParameter("start") != null) { response.sendRedirect("start"); return; } else if(request.getParameter("search") != null) { String searchPattern = request.getParameter("searchArticlePattern").replaceAll("[^a-zA-Z 0-9]+", ""); int category = Integer.parseInt(request.getParameter("categorie")); request.getSession().setAttribute("selectedCategory", category); findArticles(request, category,searchPattern); response.sendRedirect("articles"); return; } else if(request.getParameter("settings") != null) { response.sendRedirect("users"); return; } else if(request.getParameter("cart") != null) { response.sendRedirect("cart"); return; } doGet(request, response); } /** * Logout-Methode zum Logout eines Users. Session wird beendet. * @param request HttpServletRequest */ public void logout(HttpServletRequest request) { request.getSession().setAttribute("currentUser", null); request.getSession().invalidate(); } /** * Gibt alle Artikel zurück, die mit dem eingegeben Text des Suchfeldes übereinstimmen. * @param request * @param searchPattern Input search pattern to compare * @throws IOException */ private void findArticles(HttpServletRequest request,int category ,String searchPattern) throws IOException { ArrayList<Article> articles = null; try { if(category ==-1) { articles = ArticleService.GetAllArticlesByName(searchPattern,1,1); } else { articles = ArticleService.GetAllArticlesByCategorie(category, searchPattern,1,1); } } catch (SQLException e) { e.printStackTrace(); } if(articles.size() == 0) { request.getSession().setAttribute("noArticleFound", true); } else { request.getSession().setAttribute("noArticleFound", false); } request.getSession().setAttribute("articles", articles); } }
gpl-3.0
Redcof/codeinfer
codeinfer/PreProcessing/SourceCodeDetails.java
777
/* * 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 codeinfer.PreProcessing; /** * * @author soumen */ public class SourceCodeDetails { private String Attribute; private String Value; public SourceCodeDetails(String Attribute, String Value) { this.Attribute = Attribute; this.Value = Value; } public String getAttribute() { return Attribute; } public void setAttribute(String Attribute) { this.Attribute = Attribute; } public String getValue() { return Value; } public void setValue(String Value) { this.Value = Value; } }
gpl-3.0
jschang/jSchangLib
investing/src/main/java/com/jonschang/investing/QuoteService.java
2905
/* ############################### # Copyright (C) 2012 Jon Schang # # This file is part of jSchangLib, released under the LGPLv3 # # jSchangLib is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # jSchangLib is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with jSchangLib. If not, see <http://www.gnu.org/licenses/>. ############################### */ package com.jonschang.investing; import java.util.Date; import java.util.List; import java.util.Collection; import com.jonschang.investing.model.Quotable; import com.jonschang.investing.model.Quote; import com.jonschang.utils.TimeInterval; import com.jonschang.utils.DateRange; import com.jonschang.utils.HasGetObjectByObject; /** * interface to define quote services * the intention is that quote services are stateless when it comes to pulling quotes * @author schang * @param <Q> the quote * @param <I> the quotable that has the quotes, the parameter to Quotable has been intentionally left off */ @SuppressWarnings(value={"unchecked"}) public interface QuoteService<Q extends Quote<I>, I extends Quotable> { boolean supports(TimeInterval interval); /** * pulls a date ordered list of quotes in a given time-frame * @param quotable the quotables to look up * @param start the start of the time interval; must be truncated to the marketContext date if in the future. * if this day is not a business day, for each exchange, then it will be set to the closest prior business day * @param end the end of the time interval; must be truncated to the marketContext date if in the future. * if this day is not a business day, for each exchange, then it will be set to the closest prior business day * @return a map of quotable/date ordered list pairs * @throws Exception */ List<I> pullDateRange(Collection<I> quotables,DateRange range, TimeInterval interval) throws ServiceException; /** * pull a number of quotes of a interval from a reference date for a set of stocks * @param quotables the quotables to pull * @param refDate the date to either start or end on * @param number number of quotes to pull...if negative, then refDate is the beginning, else refDate is the end * @param interval * @return * @throws Exception */ List<I> pullNumber(Collection<I> quotables, Date refDate, int number, TimeInterval interval) throws ServiceException; }
gpl-3.0
00-Evan/shattered-pixel-dungeon-gdx
core/src/com/shatteredpixel/shatteredpixeldungeon/levels/rooms/standard/ExitRoom.java
1831
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2019 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.levels.rooms.standard; import com.shatteredpixel.shatteredpixeldungeon.levels.Level; import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain; import com.shatteredpixel.shatteredpixeldungeon.levels.painters.Painter; import com.shatteredpixel.shatteredpixeldungeon.levels.rooms.Room; import com.watabou.utils.Point; public class ExitRoom extends StandardRoom { @Override public int minWidth() { return Math.max(super.minWidth(), 5); } @Override public int minHeight() { return Math.max(super.minHeight(), 5); } public void paint(Level level) { Painter.fill( level, this, Terrain.WALL ); Painter.fill( level, this, 1, Terrain.EMPTY ); for (Room.Door door : connected.values()) { door.set( Room.Door.Type.REGULAR ); } level.exit = level.pointToCell(random( 2 )); Painter.set( level, level.exit, Terrain.EXIT ); } @Override public boolean canPlaceCharacter(Point p, Level l) { return super.canPlaceCharacter(p, l) && l.pointToCell(p) != l.exit; } }
gpl-3.0
BGI-flexlab/SOAPgaeaDevelopment4.0
src/main/java/org/bgi/flexlab/gaea/tools/bamqualtiycontrol/report/BasicReport.java
7939
/******************************************************************************* * Copyright (c) 2017, BGI-Shenzhen * * 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.bgi.flexlab.gaea.tools.bamqualtiycontrol.report; import org.apache.hadoop.mapreduce.Reducer.Context; import org.bgi.flexlab.gaea.data.structure.reference.ChromosomeInformationShare; import org.bgi.flexlab.gaea.data.structure.reference.ReferenceShare; import org.bgi.flexlab.gaea.tools.bamqualtiycontrol.counter.BaseCounter; import org.bgi.flexlab.gaea.tools.bamqualtiycontrol.counter.CounterProperty.BaseType; import org.bgi.flexlab.gaea.tools.bamqualtiycontrol.counter.CounterProperty.ReadType; import org.bgi.flexlab.gaea.tools.bamqualtiycontrol.counter.ReadsCounter; import org.bgi.flexlab.gaea.tools.bamqualtiycontrol.counter.Tracker; import org.bgi.flexlab.gaea.tools.bamqualtiycontrol.counter.Tracker.BaseTracker; import org.bgi.flexlab.gaea.tools.bamqualtiycontrol.counter.Tracker.ReadsTracker; import org.bgi.flexlab.gaea.util.SamRecordDatum; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; public class BasicReport{ private BaseTracker bTracker; private ReadsTracker rTracker; public BasicReport() { bTracker = new Tracker.BaseTracker(); rTracker = new Tracker.ReadsTracker(); register(); } public boolean constructMapReport(SamRecordDatum datum, ReferenceShare genome, String chrName, Context context) { ChromosomeInformationShare chrInfo = genome.getChromosomeInfo(chrName); rTracker.setTrackerAttribute(ReadType.TOTALREADS); // 当位点坐标值+read长度大于染色体的长度时,则不处理该read,进入下一次循环 if(datum.getEnd() >= chrInfo.getLength()) { if(context != null) context.getCounter("Exception", "read end pos more than chr end pos").increment(1); return false; } rTracker.setTrackerAttribute(ReadType.MAPPED); bTracker.setTrackerAttribute(BaseType.TOTALBASE.setCount(datum.getBaseCount())); if(datum.isUniqueAlignment()) { rTracker.setTrackerAttribute(ReadType.UNIQUE); } if ((datum.getFlag() & 0x400) != 0) { rTracker.setTrackerAttribute(ReadType.DUP); } if ((datum.getFlag() & 0x40) != 0 && (datum.getFlag() & 0x8) == 0) { rTracker.setTrackerAttribute(ReadType.PE); } String cigar = datum.getCigarString(); if (cigar.contains("S") || cigar.contains("H")) { rTracker.setTrackerAttribute(ReadType.CLIPPED); } if (cigar.contains("D") || cigar.contains("I")) { rTracker.setTrackerAttribute(ReadType.INDEL); } if (isMismatch(datum, chrInfo)) { rTracker.setTrackerAttribute(ReadType.MISMATCHREADS); } return true; } @Override public String toString() { DecimalFormat df = new DecimalFormat("0.000"); df.setRoundingMode(RoundingMode.HALF_UP); StringBuffer basicString = new StringBuffer(); basicString.append("Basic Information:\n"); basicString.append("Total Reads Number:\t"); basicString.append(rTracker.getReadsCount(ReadType.TOTALREADS)); basicString.append("\nTotal mapped bases:\t"); basicString.append(bTracker.getProperty(BaseType.TOTALBASE)); basicString.append("\nMapping Rate:\t"); basicString.append(df.format(getRateOf(ReadType.MAPPED))); basicString.append("%\nUniq Mapping Rate:\t"); if(getRateOf(ReadType.MAPPED) == getRateOf(ReadType.UNIQUE)) basicString.append("NA"); else basicString.append(df.format(getRateOf(ReadType.UNIQUE))); basicString.append("%\nPE Mapping Rate:\t"); basicString.append(df.format(getRateOf(ReadType.PE))); basicString.append("%\nDuplication Rate:\t"); basicString.append(df.format(getRateOf(ReadType.DUP))); basicString.append("%\nClipped Reads Rate:\t"); basicString.append(df.format(getRateOf(ReadType.CLIPPED))); basicString.append("%\nMismatch Reads Rate:\t"); basicString.append(df.format(getRateOf(ReadType.MISMATCHREADS))); basicString.append("%\nIndel Reads Rate:\t"); basicString.append(df.format(getRateOf(ReadType.INDEL))); /*basicString.append("\nMismatch Rate in all mapped bases:\t"); basicString.append(getMimatchRate()); basicString.append("\nInsertion Rate in all mapped bases:\t"); basicString.append(getInsertionRate()); basicString.append("\nDeletion Rate in all mapped bases:\t"); basicString.append(getDeletionRate());*/ basicString.append("%\n"); return basicString.toString(); } public String toReducerString() { StringBuffer basicString = new StringBuffer(); basicString.append("Basic Information:\n"); for(Entry<String, ReadsCounter> counter : rTracker.getCounterMap().entrySet()) { basicString.append(counter.getKey()); basicString.append(" "); basicString.append(counter.getValue().getReadsCount()); basicString.append("\t"); } for(Entry<String, BaseCounter> counter : bTracker.getCounterMap().entrySet()) { basicString.append(counter.getKey()); basicString.append(" "); basicString.append(counter.getValue().getProperty()); basicString.append("\t"); } basicString.append("\n"); return basicString.toString(); } private boolean isMismatch(SamRecordDatum datum, ChromosomeInformationShare chrInfo) { boolean isMismatch = false; for (int i = (int) datum.getPosition(); i <= datum.getEnd(); i++) { int qpos = datum.getCigarState().resolveCigar(i, datum.getPosition()); if (qpos < 0) { continue; } byte rbase = chrInfo.getBinaryBase(i); byte qbase = datum.getBinaryBase(qpos); if (rbase != qbase) { bTracker.setTrackerAttribute(BaseType.MISMATCH); isMismatch = true; } } datum.getCigarState().reSetCigarstate(); return isMismatch; } public void parse(String line) { String[] splitArray = line.split("\t"); for(String keyValue : splitArray) parseKeyValue(keyValue); } private void parseKeyValue(String keyValue) { String key = keyValue.split(" ")[0]; String value = keyValue.split(" ")[1]; ReadsCounter rCounter = null; BaseCounter bCounter = null; if((rCounter = rTracker.getCounterMap().get(key)) != null) rCounter.setReadsCount(Long.parseLong(value)); else if((bCounter = bTracker.getCounterMap().get(key)) != null) bCounter.setBaseCount(Long.parseLong(value)); else { throw new RuntimeException("Can not idenity counter with name " + key); } } public void register() { rTracker.register(createReadsCounters()); bTracker.register(createBaseCounters()); } public BaseTracker getBaseTracker() { return bTracker; } public ReadsTracker getReadsTracker() { return rTracker; } public double getRateOf(ReadType type) { long totalReads = rTracker.getReadsCount(ReadType.TOTALREADS); long target = rTracker.getReadsCount(type); return (100 * (target/(double)totalReads)); } public List<BaseCounter> createBaseCounters() { List<BaseCounter> counters = new ArrayList<>(); counters.add(new BaseCounter(BaseType.TOTALBASE)); counters.add(new BaseCounter(BaseType.MISMATCH)); return counters; } public List<ReadsCounter> createReadsCounters() { List<ReadsCounter> counters = new ArrayList<>(); for(ReadType type : ReadType.values()) counters.add(new ReadsCounter(type)); return counters; } }
gpl-3.0
martlin2cz/JRest
src/main/java/cz/martlin/jrest/impl/jarmil/serializers/TargetsSerializer.java
1845
package cz.martlin.jrest.impl.jarmil.serializers; import java.util.List; import cz.martlin.jrest.impl.jarmil.target.TargetOnGuest; import cz.martlin.jrest.impl.jarmil.target.TargetType; import cz.martlin.jrest.impl.jarmil.targets.guest.NewObjectOnGuestTarget; import cz.martlin.jrest.impl.jarmil.targets.guest.ObjectOnGuestTarget; import cz.martlin.jrest.impl.jarmil.targets.guest.StaticClassOnGuestTarget; /** * The serializer of targets. Assumes following format: * * <pre> * [target type specifier] [target identifier] ... (the rest) * </pre> * * @author martin * */ public class TargetsSerializer { public TargetsSerializer() { } /** * Deserializes the serialized target. * * @param serialized * @return * @throws IllegalArgumentException */ public TargetOnGuest deserialize(List<String> serialized) throws IllegalArgumentException { TargetType type = deserializeType(serialized.get(0)); String identifier = serialized.get(1); switch (type) { case NEW: return NewObjectOnGuestTarget.create(identifier); case OBJECT: return ObjectOnGuestTarget.create(identifier); case STATIC: return StaticClassOnGuestTarget.create(identifier); default: throw new IllegalArgumentException("Unsupported target type " + type); } } private TargetType deserializeType(String string) { try { return TargetType.valueOf(string.toUpperCase()); } catch (EnumConstantNotPresentException e) { throw new IllegalArgumentException("Target type " + string + " unknown"); } } /** * Serializes given target by adding into given list. * * @param target * @param into */ public void serialize(TargetOnGuest target, List<String> into) { String type = target.getType().name().toLowerCase(); into.add(type); String identifier = target.getIdentifier(); into.add(identifier); } }
gpl-3.0
Taybou/JiaanApp
app/src/main/java/dz/btesto/upmc/jiaanapp/activities/account/LoginActivity.java
4944
package dz.btesto.upmc.jiaanapp.activities.account; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import dz.btesto.upmc.jiaanapp.R; import dz.btesto.upmc.jiaanapp.activities.MainActivity; /** * ------------------------- * ### JI3AN APPLICATION ### * ------------------------- * <p> * Created by : * ------------ * ++ Nour Elislam SAIDI * ++ Mohamed Tayeb BENTERKI * <p> * ------ 2016-2017 -------- */ public class LoginActivity extends AppCompatActivity { private EditText inputEmail, inputPassword; private FirebaseAuth auth; private ProgressBar progressBar; private Button btnSignup, btnLogin, btnReset; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Get Firebase auth instance auth = FirebaseAuth.getInstance(); if (auth.getCurrentUser() != null) { startActivity(new Intent(LoginActivity.this, MainActivity.class)); finish(); } // set the view now setContentView(R.layout.activity_login); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); inputEmail = (EditText) findViewById(R.id.email); inputPassword = (EditText) findViewById(R.id.password); progressBar = (ProgressBar) findViewById(R.id.progressBar); btnSignup = (Button) findViewById(R.id.btn_signup); btnLogin = (Button) findViewById(R.id.btn_login); btnReset = (Button) findViewById(R.id.btn_reset_password); //Get Firebase auth instance auth = FirebaseAuth.getInstance(); btnSignup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(LoginActivity.this, SignupActivity.class)); } }); btnReset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class)); } }); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email = inputEmail.getText().toString(); final String password = inputPassword.getText().toString(); if (TextUtils.isEmpty(email)) { Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(password)) { Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show(); return; } progressBar.setVisibility(View.VISIBLE); //authenticate user auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. progressBar.setVisibility(View.GONE); if (!task.isSuccessful()) { // there was an error if (password.length() < 6) { inputPassword.setError(getString(R.string.minimum_password)); } else { Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show(); } } else { Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); //finish(); } } }); } }); } }
gpl-3.0
VisualizeMobile/AKANAndroid
src/br/com/visualize/akan/domain/model/Statistic.java
2956
package br.com.visualize.akan.domain.model; import br.com.visualize.akan.domain.enumeration.Month; import br.com.visualize.akan.domain.enumeration.SubQuota; public class Statistic { private SubQuota subquota; private int idStatistic; private int year; private Month month; private double stdDeviation; private double average; private double maxValue; public int getIdStatistic() { return idStatistic; } public void setIdStatistic(int idStatistic) { this.idStatistic = idStatistic; } public SubQuota getSubquota() { return subquota; } public void setSubquota( SubQuota subquota ) { this.subquota = subquota; } public void setSubquotaByNumber (int type){ switch(type){ case 1: setSubquota(SubQuota.OFFICE); break; case 3: setSubquota(SubQuota.FUEL); break; case 4: setSubquota(SubQuota.TECHNICAL_WORK_AND_CONSULTING); break; case 5: setSubquota(SubQuota.DISCLOSURE_PARLIAMENTARY_ACTIVITY); break; case 8: setSubquota(SubQuota.SAFETY); break; case 9: setSubquota(SubQuota.ISSUANCE_OF_AIR_TICKETS); break; case 10: setSubquota(SubQuota.TELEPHONY); break; case 11: setSubquota(SubQuota.POSTAL_SERVICES); break; case 12: setSubquota(SubQuota.SIGNATURE_OF_PUBLICATION); break; case 13: setSubquota(SubQuota.ALIMENTATION); break; case 14: setSubquota(SubQuota.ACCOMMODATION); break; case 15: setSubquota(SubQuota.LEASE_OF_VEHICLES); break; case 119: setSubquota(SubQuota.AIR_FREIGHT); break; default: setSubquota(SubQuota.WITHOUT_TYPE); } } public int getYear() { return year; } public void setYear( int year ) { this.year = year; } public Month getMonth() { return month; } public void setMonthByNumber (int type){ switch(type){ case 0: setMonth(Month.WITHOUT_MONTH); break; case 1: setMonth(Month.JANUARY); break; case 2: setMonth(Month.FEBRUARY); break; case 3: setMonth(Month.MARCH); break; case 4: setMonth(Month.APRIL); break; case 5: setMonth(Month.MAY); break; case 6: setMonth(Month.JUNE); break; case 7: setMonth(Month.JULY); break; case 8: setMonth(Month.AUGUST); break; case 9: setMonth(Month.SEPTEMBER); break; case 10: setMonth(Month.OCTOBER); break; case 11: setMonth(Month.NOVEMBER); break; case 12: setMonth(Month.DECEMBER); break; default: //nothing to do } } public void setMonth( Month month ) { this.month = month; } public double getStdDeviation() { return stdDeviation; } public void setStdDeviation( double stdDeviation ) { this.stdDeviation = stdDeviation; } public double getAverage() { return average; } public void setAverage( double average ) { this.average = average; } public double getMaxValue() { return maxValue; } public void setMaxValue( double maxValue ) { this.maxValue = maxValue; } }
gpl-3.0
kotcrab/arget
src/pl/kotcrab/arget/gui/components/ServerMenuItem.java
1535
/******************************************************************************* Copyright 2014 Pawel Pastuszak This file is part of Arget. Arget 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. Arget 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 Arget. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package pl.kotcrab.arget.gui.components; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JMenuItem; import pl.kotcrab.arget.gui.MainWindowCallback; import pl.kotcrab.arget.server.ServerDescriptor; public class ServerMenuItem extends JMenuItem implements ActionListener { private MainWindowCallback callback; private ServerDescriptor info; public ServerMenuItem (MainWindowCallback callback, ServerDescriptor info) { super(info.toString()); this.callback = callback; this.info = info; addActionListener(this); } @Override public void actionPerformed (ActionEvent e) { callback.connectToServer(info); } }
gpl-3.0
timcampbell/1.9TestingMod
src/main/java/com/sopa89/testingmod/proxy/ServerProxy.java
88
package com.sopa89.testingmod.proxy; public class ServerProxy extends CommonProxy { }
gpl-3.0
shelllbw/workcraft
WorkcraftCore/src/org/workcraft/serialisation/Format.java
4021
/* * * Copyright 2008,2009 Newcastle University * * This file is part of Workcraft. * * Workcraft 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. * * Workcraft 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 Workcraft. If not, see <http://www.gnu.org/licenses/>. * */ package org.workcraft.serialisation; import java.util.UUID; public class Format { public static final UUID workcraftXML = UUID.fromString("6ea20f69-c9c4-4888-9124-252fe4345309"); public static final UUID defaultVisualXML = UUID.fromString("2fa9669c-a1bf-4be4-8622-007635d672e5"); public static final UUID STG = UUID.fromString("000199d9-4ac1-4423-b8ea-9017d838e45b"); public static final UUID SG = UUID.fromString("f309012a-ab89-4036-bb80-8b1a161e8899"); public static final UUID SVG = UUID.fromString("99439c3c-753b-46e3-a5d5-6a0993305a2c"); public static final UUID PS = UUID.fromString("9b5bd9f0-b5cf-11df-8d81-0800200c9a66"); public static final UUID EPS = UUID.fromString("c6158d84-e242-4f8c-9ec9-3a6cf045b769"); public static final UUID PDF = UUID.fromString("fa1da69d-3a17-4296-809e-a71f28066fc0"); public static final UUID PNG = UUID.fromString("c09714a6-cae9-4744-95cb-17ba4d28f5ef"); public static final UUID EMF = UUID.fromString("c8f9fe37-87d2-42bd-8a25-9e1d38813549"); public static final UUID DOT = UUID.fromString("f1596b60-e294-11de-8a39-0800200c9a66"); public static final UUID EQN = UUID.fromString("58b3c8d0-e297-11de-8a39-0800200c9a66"); public static final UUID VERILOG = UUID.fromString("fdd4414e-fd02-4702-b143-09b24430fdd1"); public static String getDescription(UUID format) { if (format.equals(workcraftXML)) { return ".xml (Workcraft math model)"; } else if (format.equals(defaultVisualXML)) { return ".xml (Workcraft visual model)"; } else if (format.equals(STG)) { return ".g (Signal Transition Graph)"; } else if (format.equals(SG)) { return ".sg (State Graph)"; } else if (format.equals(SVG)) { return ".svg (Scalable Vector Graphics)"; } else if (format.equals(PS)) { return ".ps (PostScript)"; } else if (format.equals(EPS)) { return ".eps (Encapsulated PostScript)"; } else if (format.equals(PDF)) { return ".pdf (Portable Document Format)"; } else if (format.equals(PNG)) { return ".png (Portable Network Graphics)"; } else if (format.equals(EMF)) { return ".emf (Enhanced Mediafile)"; } else if (format.equals(DOT)) { return ".dot (GraphViz dot)"; } else if (format.equals(EQN)) { return ".eqn (Signal equations)"; } else if (format.equals(VERILOG)) { return ".v (Verilog netlist)"; } else { return "Unknown format"; } } public static UUID getUUID(String name) { if ("workcraftXML".equals(name)) return workcraftXML; if ("defaultVisualXML".equals(name)) return defaultVisualXML; if ("STG".equals(name)) return STG; if ("SG".equals(name)) return SG; if ("SVG".equals(name)) return SVG; if ("PS".equals(name)) return PS; if ("EPS".equals(name)) return EPS; if ("PDF".equals(name)) return PDF; if ("PNG".equals(name)) return PNG; if ("EMF".equals(name)) return EMF; if ("DOT".equals(name)) return DOT; if ("EQN".equals(name)) return EQN; if ("VERILOG".equals(name)) return VERILOG; return null; } }
gpl-3.0
waikato-datamining/adams-base
adams-core/src/test/java/adams/data/conversion/IntToStringTest.java
2501
/* * 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/>. */ /** * IntToStringTest.java * Copyright (C) 2011-2014 University of Waikato, Hamilton, New Zealand */ package adams.data.conversion; import adams.core.ByteFormatString; import junit.framework.Test; import junit.framework.TestSuite; import adams.env.Environment; /** * Tests the IntToString conversion. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class IntToStringTest extends AbstractConversionTestCase { /** * Constructs the test case. Called by subclasses. * * @param name the name of the test */ public IntToStringTest(String name) { super(name); } /** * Returns the input data to use in the regression test. * * @return the objects */ @Override protected Object[] getRegressionInput() { return new Integer[]{ 1, -1, 31415, -31415 }; } /** * Returns the setups to use in the regression test. * * @return the setups */ @Override protected Conversion[] getRegressionSetups() { IntToString[] result; result = new IntToString[2]; result[0] = new IntToString(); result[1] = new IntToString(); result[1].setUseFormat(true); result[1].setFormat(new ByteFormatString("B.2K")); return result; } /** * Returns the ignored line indices to use in the regression test. * * @return the setups */ @Override protected int[] getRegressionIgnoredLineIndices() { return new int[0]; } /** * Returns the test suite. * * @return the suite */ public static Test suite() { return new TestSuite(IntToStringTest.class); } /** * Runs the test from commandline. * * @param args ignored */ public static void main(String[] args) { Environment.setEnvironmentClass(Environment.class); runTest(suite()); } }
gpl-3.0
waikato-datamining/adams-base
adams-spreadsheet/src/main/java/adams/gui/visualization/spreadsheet/SpreadSheetRowContainerModel.java
2103
/* * 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/>. */ /* * SpreadSheetRowContainerModel.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand */ package adams.gui.visualization.spreadsheet; import adams.gui.visualization.container.ContainerListManager; import adams.gui.visualization.container.ContainerModel; /** * A model for displaying the currently loaded SpreadSheetRow objects. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 4584 $ */ public class SpreadSheetRowContainerModel extends ContainerModel<SpreadSheetRowContainerManager, SpreadSheetRowContainer> { /** for serialization. */ private static final long serialVersionUID = -6259301933663814155L; /** * Initializes the model. * * @param manager the managing object to obtain the data from */ public SpreadSheetRowContainerModel(ContainerListManager<SpreadSheetRowContainerManager> manager) { super((manager == null) ? null : manager.getContainerManager()); } /** * Initializes the model. * * @param manager the manager to obtain the data from */ public SpreadSheetRowContainerModel(SpreadSheetRowContainerManager manager) { super(manager); } /** * Initializes the members. */ protected void initialize() { super.initialize(); m_Generator = new SpreadSheetRowContainerDisplayIDGenerator(); m_ColumnNameGenerator = new SpreadSheetRowContainerTableColumnNameGenerator(); } }
gpl-3.0
aherbert/GDSC-SMLM
src/main/java/uk/ac/sussex/gdsc/smlm/ij/plugins/CmosAnalysis.java
40883
/*- * #%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.ij.plugins; import gnu.trove.set.hash.TIntHashSet; import ij.IJ; import ij.ImagePlus; import ij.ImageStack; import ij.Prefs; import ij.WindowManager; import ij.gui.GenericDialog; import ij.gui.Plot; import ij.io.Opener; import ij.plugin.PlugIn; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.concurrent.ConcurrentRuntimeException; import org.apache.commons.lang3.time.StopWatch; import org.apache.commons.math3.stat.correlation.PearsonsCorrelation; import org.apache.commons.math3.stat.inference.TestUtils; import org.apache.commons.math3.stat.inference.WilcoxonSignedRankTest; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.sampling.distribution.ContinuousSampler; import org.apache.commons.rng.sampling.distribution.DiscreteSampler; import org.apache.commons.rng.sampling.distribution.NormalizedGaussianSampler; import org.apache.commons.rng.sampling.distribution.SharedStateContinuousSampler; import uk.ac.sussex.gdsc.core.data.IntegerType; import uk.ac.sussex.gdsc.core.data.SiPrefix; import uk.ac.sussex.gdsc.core.ij.HistogramPlot; import uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder; import uk.ac.sussex.gdsc.core.ij.ImageJTrackProgress; import uk.ac.sussex.gdsc.core.ij.ImageJUtils; import uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog; import uk.ac.sussex.gdsc.core.ij.io.CustomTiffEncoder; import uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser; import uk.ac.sussex.gdsc.core.logging.Ticker; import uk.ac.sussex.gdsc.core.math.ArrayMoment; import uk.ac.sussex.gdsc.core.math.IntegerArrayMoment; import uk.ac.sussex.gdsc.core.math.RollingArrayMoment; import uk.ac.sussex.gdsc.core.math.SimpleArrayMoment; import uk.ac.sussex.gdsc.core.utils.DoubleData; import uk.ac.sussex.gdsc.core.utils.LocalList; import uk.ac.sussex.gdsc.core.utils.MathUtils; import uk.ac.sussex.gdsc.core.utils.SimpleArrayUtils; import uk.ac.sussex.gdsc.core.utils.Statistics; import uk.ac.sussex.gdsc.core.utils.TextUtils; import uk.ac.sussex.gdsc.core.utils.concurrent.ConcurrencyUtils; import uk.ac.sussex.gdsc.core.utils.rng.Pcg32; import uk.ac.sussex.gdsc.core.utils.rng.PoissonSamplerUtils; import uk.ac.sussex.gdsc.core.utils.rng.SamplerUtils; import uk.ac.sussex.gdsc.core.utils.rng.UniformRandomProviders; import uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource; import uk.ac.sussex.gdsc.smlm.ij.settings.Constants; import uk.ac.sussex.gdsc.smlm.model.camera.PerPixelCameraModel; /** * Analyse the per pixel offset, variance and gain from a sCMOS camera. * * <p>See Huang et al (2013) Video-rate nanoscopy using sCMOS camera–specific single-molecule * localization algorithms. Nature Methods 10, 653-658 (Supplementary Information). */ public class CmosAnalysis implements PlugIn { private static final String TITLE = "sCMOS Analysis"; private static final String REJECT = "reject"; private static final String ACCEPT = "accept"; private int numberOfThreads; // The simulated offset, variance and gain private ImagePlus simulationImp; // The measured offset, variance and gain private ImageStack measuredStack; // The sub-directories containing the sCMOS images private LocalList<SubDir> subDirs; /** The plugin settings. */ private Settings settings; /** * Contains the settings that are the re-usable state of the plugin. */ private static class Settings { private static final String DEFAULT_PHOTONS = "50, 100, 200, 400, 800"; /** The last settings used by the plugin. This should be updated after plugin execution. */ private static final AtomicReference<Settings> lastSettings = new AtomicReference<>(new Settings()); String directory; String modelDirectory; String modelName; boolean rollingAlgorithm; boolean reuseProcessedData; double offset; double variance; double gain; double gainStdDev; int size; int frames; int imagejNThreads; int lastNumberOfThreads; String simulationPhotons; Settings() { // Set defaults directory = Prefs.get(Constants.sCMOSAnalysisDirectory, ""); reuseProcessedData = true; // The simulation can default roughly to the values displayed // in the Huang sCMOS paper supplementary figure 1: // Offset = Approximately Normal or Poisson. We use Poisson // since that is an integer distribution which would be expected // for an offset & Poisson approaches the Gaussian at high mean. offset = 100; // Variance = Exponential (equivalent to chi-squared with k=1, i.e. // sum of the squares of 1 normal distribution). // We want 99.9% @ 400 ADU based on supplementary figure 1.a/1.b // cumul = 1 - e^-lx (l = 1/mean) // => e^-lx = 1 - cumul // => -lx = log(1-0.999) // => l = -log(0.001) / 400 (since x==400) // => 1/l = 57.9 variance = 57.9; // SD = 7.6 // Gain = Approximately Normal gain = 2.2; gainStdDev = 0.2; size = 512; frames = 500; imagejNThreads = Prefs.getThreads(); lastNumberOfThreads = imagejNThreads; simulationPhotons = DEFAULT_PHOTONS; } Settings(Settings source) { directory = source.directory; modelDirectory = source.modelDirectory; modelName = source.modelName; rollingAlgorithm = source.rollingAlgorithm; reuseProcessedData = source.reuseProcessedData; offset = source.offset; variance = source.variance; gain = source.gain; gainStdDev = source.gainStdDev; size = source.size; frames = source.frames; imagejNThreads = source.imagejNThreads; lastNumberOfThreads = source.lastNumberOfThreads; simulationPhotons = source.simulationPhotons; } Settings copy() { return new Settings(this); } /** * Load a copy of the settings. * * @return the settings */ static Settings load() { return lastSettings.get().copy(); } /** * Save the settings. This can be called only once as it saves via a reference. */ void save() { lastSettings.set(this); } /** * Gets the photons from the simulation photons string. * * @return the photons */ int[] getPhotons() { final TIntHashSet list = new TIntHashSet(); list.add(0); for (final String key : simulationPhotons.split(",")) { try { final int value = Integer.parseInt(key.trim()); if (value < 0 || (value * gain) > (1 << 16)) { throw new NumberFormatException("Invalid number of photons after gain: " + value); } list.add(value); } catch (final NumberFormatException ex) { throw new NumberFormatException("Invalid number of photons: " + key); } } final int[] result = list.toArray(); Arrays.sort(result); return result; } } private static class SimulationWorker implements Runnable { /** The maximum value for a short integer. */ static final short MAX_SHORT = (short) 0xffff; final Ticker ticker; final UniformRandomProvider rg; final String out; final float[] pixelOffset; final float[] pixelVariance; final float[] pixelGain; final int from; final int to; final int blockSize; final int photons; final NormalizedGaussianSampler gauss; SimulationWorker(Ticker ticker, UniformRandomProvider rng, String out, ImageStack stack, int from, int to, int blockSize, int photons) { this.ticker = ticker; rg = rng; pixelOffset = (float[]) stack.getPixels(1); pixelVariance = (float[]) stack.getPixels(2); pixelGain = (float[]) stack.getPixels(3); this.out = out; this.from = from; this.to = to; this.blockSize = blockSize; this.photons = photons; gauss = SamplerUtils.createNormalizedGaussianSampler(rg); } @Override public void run() { // Avoid the status bar talking to the current image WindowManager.setTempCurrentImage(null); // Convert variance to SD final float[] pixelSd = new float[pixelVariance.length]; for (int i = 0; i < pixelVariance.length; i++) { pixelSd[i] = (float) Math.sqrt(pixelVariance[i]); } final int size = (int) Math.sqrt(pixelVariance.length); // Pre-compute a set of Poisson numbers since this is slow final DiscreteSampler pd = PoissonSamplerUtils.createPoissonSampler(rg, photons); // // For speed we can precompute a set of random numbers to reuse // final int[] poisson = new int[pixelVariance.length]; // for (int i = poisson.length; i-- > 0;) { // poisson[i] = pd.sample(); // } // Save image in blocks ImageStack stack = new ImageStack(size, size); int start = from; for (int i = from; i < to; i++) { // Create image final short[] pixels = new short[pixelOffset.length]; if (photons == 0) { for (int j = 0; j < pixelOffset.length; j++) { // Fixed offset per pixel plus a variance final double p = pixelOffset[j] + gauss.sample() * pixelSd[j]; pixels[j] = clip16bit(p); } } else { for (int j = 0; j < pixelOffset.length; j++) { // Fixed offset per pixel plus a variance plus a // fixed gain multiplied by a Poisson sample of the photons final double p = pixelOffset[j] + gauss.sample() * pixelSd[j] + (pd.sample() * pixelGain[j]); pixels[j] = clip16bit(p); } // Rotate Poisson numbers. // Shuffling what we have is faster than generating new values // and we should have enough. // RandomUtils.shuffle(poisson, rg); } // Save image stack.addSlice(null, pixels); if (stack.getSize() == blockSize) { save(stack, start); start = i + 1; stack = new ImageStack(size, size); } ticker.tick(); } // This should not happen if we control the to-from range correctly if (stack.getSize() != 0) { save(stack, start); } } /** * Clip to the range for a 16-bit image. * * @param value the value * @return the clipped value */ private static short clip16bit(double value) { final int i = (int) Math.round(value); if (value < 0) { return 0; } if (i > 0xffff) { return MAX_SHORT; } return (short) i; } private void save(ImageStack stack, int start) { final ImagePlus imp = new ImagePlus("", stack); final CustomTiffEncoder file = new CustomTiffEncoder(imp.getFileInfo()); try ( OutputStream os = Files.newOutputStream(Paths.get(out, String.format("image%06d.tif", start))); BufferedOutputStream bos = new BufferedOutputStream(os)) { file.write(bos); } catch (IOException ex) { throw new ConcurrentRuntimeException("Failed to save image", ex); } } } private static class SubDir { int exposureTime; File path; String name; SubDir(int exposureTime, File path, String name) { this.exposureTime = exposureTime; this.path = path; this.name = name; } /** * Compare the two results. * * @param r1 the first result * @param r2 the second result * @return -1, 0 or 1 */ static int compare(SubDir r1, SubDir r2) { return Integer.compare(r1.exposureTime, r2.exposureTime); } } /** * Used to allow multi-threading of the scoring the filters. */ private static class ImageWorker implements Runnable { /** The signal to stop processing jobs. */ static final Object STOP_SIGNAL = new Object(); final Ticker ticker; volatile boolean finished; final BlockingQueue<Object> jobs; final ArrayMoment moment; int bitDepth; ImageWorker(Ticker ticker, BlockingQueue<Object> jobs, ArrayMoment moment) { this.ticker = ticker; this.jobs = jobs; this.moment = moment.newInstance(); } @Override public void run() { try { for (;;) { final Object pixels = jobs.take(); if (pixels == STOP_SIGNAL) { break; } if (!finished) { // Only run jobs when not finished. This allows the queue to be emptied. run(pixels); } } } catch (final InterruptedException ex) { ConcurrencyUtils.interruptAndThrowUncheckedIf(!finished, ex); } finally { finished = true; } } private void run(Object pixels) { if (ImageJUtils.isInterrupted()) { finished = true; return; } if (bitDepth == 0) { bitDepth = ImageJUtils.getBitDepth(pixels); } // Most likely first if (bitDepth == 16) { moment.addUnsigned((short[]) pixels); } else if (bitDepth == 32) { moment.add((float[]) pixels); } else if (bitDepth == 8) { moment.addUnsigned((byte[]) pixels); } else { throw new IllegalStateException("Unsupported bit depth"); } ticker.tick(); } } /** * Gets the last number of threads used in the input dialog. * * @return the last number of threads */ private int getLastNumberOfThreads() { // See if ImageJ preference were updated if (settings.imagejNThreads != Prefs.getThreads()) { settings.lastNumberOfThreads = settings.imagejNThreads = Prefs.getThreads(); } // Otherwise use the last user input return settings.lastNumberOfThreads; } /** * Gets the threads to use for multi-threaded computation. * * @return the threads */ private int getThreads() { if (numberOfThreads == 0) { numberOfThreads = Prefs.getThreads(); } return numberOfThreads; } /** * Sets the threads to use for multi-threaded computation. * * @param numberOfThreads the new threads */ private void setThreads(int numberOfThreads) { this.numberOfThreads = Math.max(1, numberOfThreads); // Save user input settings.lastNumberOfThreads = this.numberOfThreads; } @Override public void run(String arg) { SmlmUsageTracker.recordPlugin(this.getClass(), arg); final boolean extraOptions = ImageJUtils.isExtraOptions(); // Avoid the status bar talking to the current image WindowManager.setTempCurrentImage(null); //@formatter:off IJ.log(TextUtils.wrap( TITLE + ": Analyse the per-pixel offset, variance and gain of sCMOS images. " + "See Huang et al (2013) Video-rate nanoscopy using sCMOS camera–specific " + "single-molecule localization algorithms. Nature Methods 10, 653-658 " + "(Supplementary Information).", 80)); //@formatter:on settings = Settings.load(); final String dir = ImageJUtils.getDirectory(TITLE, settings.directory); if (TextUtils.isNullOrEmpty(dir)) { return; } settings.directory = dir; settings.save(); Prefs.set(Constants.sCMOSAnalysisDirectory, dir); final boolean simulate = "simulate".equals(arg); if (simulate || extraOptions) { if (!showSimulateDialog()) { return; } try { simulate(); } catch (final IOException ex) { IJ.error(TITLE, "Failed to perform simulation: " + ex.getMessage()); return; } } if (!showDialog()) { return; } runAnalysis(); if (simulationImp == null) { // Just in case an old simulation is in the directory final ImagePlus imp = IJ.openImage(new File(settings.directory, "perPixelSimulation.tif").getPath()); if (imp != null && imp.getStackSize() == 3 && imp.getWidth() == measuredStack.getWidth() && imp.getHeight() == measuredStack.getHeight()) { simulationImp = imp; } } if (simulationImp != null) { computeError(); } } private void simulate() throws IOException { // Create the offset, variance and gain for each pixel final int n = settings.size * settings.size; final float[] pixelOffset = new float[n]; final float[] pixelVariance = new float[n]; final float[] pixelGain = new float[n]; IJ.showStatus("Creating random per-pixel readout"); final long start = System.currentTimeMillis(); final UniformRandomProvider rg = UniformRandomProviders.create(); final DiscreteSampler pd = PoissonSamplerUtils.createPoissonSampler(rg, settings.offset); final ContinuousSampler ed = SamplerUtils.createExponentialSampler(rg, settings.variance); final SharedStateContinuousSampler gauss = SamplerUtils.createGaussianSampler(rg, settings.gain, settings.gainStdDev); Ticker ticker = ImageJUtils.createTicker(n, 0); for (int i = 0; i < n; i++) { // Q. Should these be clipped to a sensible range? pixelOffset[i] = pd.sample(); pixelVariance[i] = (float) ed.sample(); pixelGain[i] = (float) gauss.sample(); ticker.tick(); } IJ.showProgress(1); // Save to the directory as a stack final ImageStack simulationStack = new ImageStack(settings.size, settings.size); simulationStack.addSlice("Offset", pixelOffset); simulationStack.addSlice("Variance", pixelVariance); simulationStack.addSlice("Gain", pixelGain); simulationImp = new ImagePlus("PerPixel", simulationStack); // Only the info property is saved to the TIFF file simulationImp.setProperty("Info", String.format("Offset=%s; Variance=%s; Gain=%s +/- %s", MathUtils.rounded(settings.offset), MathUtils.rounded(settings.variance), MathUtils.rounded(settings.gain), MathUtils.rounded(settings.gainStdDev))); IJ.save(simulationImp, new File(settings.directory, "perPixelSimulation.tif").getPath()); // Create thread pool and workers final int threadCount = getThreads(); final ExecutorService executor = Executors.newFixedThreadPool(threadCount); final LocalList<Future<?>> futures = new LocalList<>(numberOfThreads); // Simulate the exposure input. final int[] photons = settings.getPhotons(); final int blockSize = 10; // For saving stacks int numberPerThread = (int) Math.ceil((double) settings.frames / numberOfThreads); // Convert to fit the block size numberPerThread = (int) Math.ceil((double) numberPerThread / blockSize) * blockSize; final Pcg32 rng = Pcg32.xshrs(start); // Note the bias is increased by 3-fold so add 2 to the length ticker = Ticker.createStarted(new ImageJTrackProgress(true), (long) (photons.length + 2) * settings.frames, threadCount > 1); for (final int p : photons) { ImageJUtils.showStatus(() -> "Simulating " + TextUtils.pleural(p, "photon")); // Create the directory final Path out = Paths.get(settings.directory, String.format("photon%03d", p)); Files.createDirectories(out); // Increase frames for bias image final int frames = settings.frames * (p == 0 ? 3 : 1); for (int from = 0; from < frames;) { final int to = Math.min(from + numberPerThread, frames); futures.add(executor.submit(new SimulationWorker(ticker, rng.split(), out.toString(), simulationStack, from, to, blockSize, p))); from = to; } ConcurrencyUtils.waitForCompletionUnchecked(futures); futures.clear(); } final String msg = "Simulation time = " + TextUtils.millisToString(System.currentTimeMillis() - start); IJ.showStatus(msg); ImageJUtils.clearSlowProgress(); executor.shutdown(); ImageJUtils.log(msg); } private boolean showSimulateDialog() { final GenericDialog gd = new GenericDialog(TITLE); gd.addHelp(HelpUrls.getUrl("scmos-analysis")); gd.addMessage("Simulate per-pixel offset, variance and gain of sCMOS images."); gd.addNumericField("nThreads", getLastNumberOfThreads(), 0); gd.addNumericField("Offset (Poisson)", settings.offset, 3); gd.addNumericField("Variance (Exponential)", settings.variance, 3); gd.addNumericField("Gain (Gaussian)", settings.gain, 3); gd.addNumericField("Gain_SD", settings.gainStdDev, 3); gd.addNumericField("Size", settings.size, 0); gd.addNumericField("Frames", settings.frames, 0); gd.addStringField("Photons (comma-delimited)", settings.simulationPhotons, 20); gd.showDialog(); if (gd.wasCanceled()) { return false; } setThreads((int) gd.getNextNumber()); settings.offset = Math.abs(gd.getNextNumber()); settings.variance = Math.abs(gd.getNextNumber()); settings.gain = Math.abs(gd.getNextNumber()); settings.gainStdDev = Math.abs(gd.getNextNumber()); settings.size = Math.abs((int) gd.getNextNumber()); settings.frames = Math.abs((int) gd.getNextNumber()); settings.simulationPhotons = gd.getNextString(); // Check arguments try { ParameterUtils.isAboveZero("Offset", settings.offset); ParameterUtils.isAboveZero("Variance", settings.variance); ParameterUtils.isAboveZero("Gain", settings.gain); ParameterUtils.isAboveZero("Gain SD", settings.gainStdDev); ParameterUtils.isAboveZero("Size", settings.size); ParameterUtils.isAboveZero("Frames", settings.frames); } catch (final IllegalArgumentException ex) { ImageJUtils.log(TITLE + ": " + ex.getMessage()); return false; } return true; } private boolean showDialog() { // Determine sub-directories to process final File dir = new File(settings.directory); final File[] dirs = dir.listFiles(File::isDirectory); if (ArrayUtils.isEmpty(dirs)) { IJ.error(TITLE, "No sub-directories"); return false; } // Get only those with numbers at the end. // These should correspond to exposure times subDirs = new LocalList<>(); final Pattern p = Pattern.compile("([0-9]+)$"); for (final File path : dirs) { final String name = path.getName(); final Matcher m = p.matcher(name); if (m.find()) { final int t = Integer.parseInt(m.group(1)); subDirs.add(new SubDir(t, path, name)); } } if (subDirs.size() < 2) { IJ.error(TITLE, "Not enough sub-directories with exposure time suffix"); return false; } Collections.sort(subDirs, SubDir::compare); if (subDirs.get(0).exposureTime != 0) { IJ.error(TITLE, "No sub-directories with exposure time 0"); return false; } for (final SubDir sd : subDirs) { ImageJUtils.log("Sub-directory: %s. Exposure time = %d", sd.name, sd.exposureTime); } final GenericDialog gd = new GenericDialog(TITLE); gd.addHelp(HelpUrls.getUrl("scmos-analysis")); //@formatter:off gd.addMessage("Analyse the per-pixel offset, variance and gain of sCMOS images.\n \n" + TextUtils.wrap( "See Huang et al (2013) Video-rate nanoscopy using sCMOS camera–specific " + "single-molecule localization algorithms. Nature Methods 10, 653-658 " + "(Supplementary Information).", 80)); //@formatter:on gd.addNumericField("nThreads", getLastNumberOfThreads(), 0); gd.addMessage(TextUtils.wrap("A rolling algorithm can handle any size of data but is slower. " + "Otherwise the camera is assumed to produce a maximum of 16-bit unsigned data.", 80)); gd.addCheckbox("Rolling_algorithm", settings.rollingAlgorithm); gd.addCheckbox("Re-use_processed_data", settings.reuseProcessedData); gd.showDialog(); if (gd.wasCanceled()) { return false; } setThreads((int) gd.getNextNumber()); settings.rollingAlgorithm = gd.getNextBoolean(); settings.reuseProcessedData = gd.getNextBoolean(); return true; } private void runAnalysis() { final long start = System.currentTimeMillis(); // Create thread pool and workers. The system is likely to be IO limited // so reduce the computation threads to allow the reading thread in the // SeriesImageSource to run. // If the images are small enough to fit into memory then 3 threads are used, // otherwise it is 1. final int nThreads = Math.max(1, getThreads() - 3); final ExecutorService executor = Executors.newFixedThreadPool(nThreads); final LocalList<Future<?>> futures = new LocalList<>(nThreads); final LocalList<ImageWorker> workers = new LocalList<>(nThreads); final double[][] data = new double[subDirs.size() * 2][]; double[] pixelOffset = null; double[] pixelVariance = null; Statistics statsOffset = null; Statistics statsVariance = null; // For each sub-directory compute the mean and variance final int nSubDirs = subDirs.size(); boolean error = false; int width = 0; int height = 0; for (int n = 0; n < nSubDirs; n++) { ImageJUtils.showSlowProgress(n, nSubDirs); final SubDir sd = subDirs.unsafeGet(n); ImageJUtils.showStatus(() -> "Analysing " + sd.name); final StopWatch sw = StopWatch.createStarted(); // Option to reuse data final File file = new File(settings.directory, "perPixel" + sd.name + ".tif"); boolean found = false; if (settings.reuseProcessedData && file.exists()) { final Opener opener = new Opener(); opener.setSilentMode(true); final ImagePlus imp = opener.openImage(file.getPath()); if (imp != null && imp.getStackSize() == 2 && imp.getBitDepth() == 32) { if (n == 0) { width = imp.getWidth(); height = imp.getHeight(); } else if (width != imp.getWidth() || height != imp.getHeight()) { error = true; IJ.error(TITLE, "Image width/height mismatch in image series: " + file.getPath() + String.format("\n \nExpected %dx%d, Found %dx%d", width, height, imp.getWidth(), imp.getHeight())); break; } final ImageStack stack = imp.getImageStack(); data[2 * n] = SimpleArrayUtils.toDouble((float[]) stack.getPixels(1)); data[2 * n + 1] = SimpleArrayUtils.toDouble((float[]) stack.getPixels(2)); found = true; } } if (!found) { // Open the series final SeriesImageSource source = new SeriesImageSource(sd.name, sd.path.getPath()); if (!source.open()) { error = true; IJ.error(TITLE, "Failed to open image series: " + sd.path.getPath()); break; } if (n == 0) { width = source.getWidth(); height = source.getHeight(); } else if (width != source.getWidth() || height != source.getHeight()) { error = true; IJ.error(TITLE, "Image width/height mismatch in image series: " + sd.path.getPath() + String.format("\n \nExpected %dx%d, Found %dx%d", width, height, source.getWidth(), source.getHeight())); break; } // So the bar remains at 99% when workers have finished use frames + 1 final Ticker ticker = ImageJUtils.createTicker(source.getFrames() + 1L, nThreads); // Open the first frame to get the bit depth. // Assume the first pixels are not empty as the source is open. Object pixels = source.nextRaw(); final int bitDepth = ImageJUtils.getBitDepth(pixels); ArrayMoment moment; if (settings.rollingAlgorithm) { moment = new RollingArrayMoment(); // We assume 16-bit camera at the maximum } else if (bitDepth <= 16 && IntegerArrayMoment.isValid(IntegerType.UNSIGNED_16, source.getFrames())) { moment = new IntegerArrayMoment(); } else { moment = new SimpleArrayMoment(); } final BlockingQueue<Object> jobs = new ArrayBlockingQueue<>(nThreads * 2); for (int i = 0; i < nThreads; i++) { final ImageWorker worker = new ImageWorker(ticker, jobs, moment); workers.add(worker); futures.add(executor.submit(worker)); } // Process the raw pixel data long lastTime = 0; while (pixels != null) { final long time = System.currentTimeMillis(); if (time - lastTime > 150) { if (ImageJUtils.isInterrupted()) { error = true; break; } lastTime = time; IJ.showStatus("Analysing " + sd.name + " Frame " + source.getStartFrameNumber()); } put(jobs, pixels); pixels = source.nextRaw(); } source.close(); if (error) { // Kill the workers workers.stream().forEach(worker -> worker.finished = true); // Clear the queue jobs.clear(); // Signal any waiting workers workers.stream().forEach(worker -> jobs.add(ImageWorker.STOP_SIGNAL)); // Cancel by interruption. We set the finished flag so the ImageWorker should // ignore the interrupt. futures.stream().forEach(future -> future.cancel(true)); break; } // Finish all the worker threads cleanly workers.stream().forEach(worker -> jobs.add(ImageWorker.STOP_SIGNAL)); // Wait for all to finish ConcurrencyUtils.waitForCompletionUnchecked(futures); // Create the final aggregate statistics for (final ImageWorker w : workers) { moment.add(w.moment); } data[2 * n] = moment.getMean(); data[2 * n + 1] = moment.getVariance(); // Get the processing speed. sw.stop(); // ticker holds the number of number of frames processed final double bits = (double) bitDepth * source.getFrames() * source.getWidth() * source.getHeight(); final double bps = bits / sw.getTime(TimeUnit.SECONDS); final SiPrefix prefix = SiPrefix.getSiPrefix(bps); ImageJUtils.log("Processed %d frames. Time = %s. Rate = %s %sbits/s", moment.getN(), sw.toString(), MathUtils.rounded(prefix.convert(bps)), prefix.getPrefix()); // Reset futures.clear(); workers.clear(); final ImageStack stack = new ImageStack(width, height); stack.addSlice("Mean", SimpleArrayUtils.toFloat(data[2 * n])); stack.addSlice("Variance", SimpleArrayUtils.toFloat(data[2 * n + 1])); IJ.save(new ImagePlus("PerPixel", stack), file.getPath()); } final Statistics s = Statistics.create(data[2 * n]); if (pixelOffset != null) { // Compute mean ADU final Statistics signal = new Statistics(); final double[] mean = data[2 * n]; for (int i = 0; i < pixelOffset.length; i++) { signal.add(mean[i] - pixelOffset[i]); } ImageJUtils.log("%s Mean = %s +/- %s. Signal = %s +/- %s ADU", sd.name, MathUtils.rounded(s.getMean()), MathUtils.rounded(s.getStandardDeviation()), MathUtils.rounded(signal.getMean()), MathUtils.rounded(signal.getStandardDeviation())); } else { // Set the offset assuming the first sub-directory is the bias image pixelOffset = data[0]; pixelVariance = data[1]; statsOffset = s; statsVariance = Statistics.create(pixelVariance); ImageJUtils.log("%s Offset = %s +/- %s. Variance = %s +/- %s", sd.name, MathUtils.rounded(s.getMean()), MathUtils.rounded(s.getStandardDeviation()), MathUtils.rounded(statsVariance.getMean()), MathUtils.rounded(statsVariance.getStandardDeviation())); } IJ.showProgress(1); } ImageJUtils.clearSlowProgress(); if (error) { executor.shutdownNow(); IJ.showStatus(TITLE + " cancelled"); return; } executor.shutdown(); if (pixelOffset == null || pixelVariance == null) { IJ.showStatus(TITLE + " error: no bias image"); return; } // Compute the gain ImageJUtils.showStatus("Computing gain"); final double[] pixelGain = new double[pixelOffset.length]; final double[] bibiT = new double[pixelGain.length]; final double[] biaiT = new double[pixelGain.length]; // Ignore first as this is the 0 exposure image for (int n = 1; n < nSubDirs; n++) { // Use equation 2.5 from the Huang et al paper. final double[] b = data[2 * n]; final double[] a = data[2 * n + 1]; for (int i = 0; i < pixelGain.length; i++) { final double bi = b[i] - pixelOffset[i]; final double ai = a[i] - pixelVariance[i]; bibiT[i] += bi * bi; biaiT[i] += bi * ai; } } for (int i = 0; i < pixelGain.length; i++) { pixelGain[i] = biaiT[i] / bibiT[i]; } final Statistics statsGain = Statistics.create(pixelGain); ImageJUtils.log("Gain Mean = %s +/- %s", MathUtils.rounded(statsGain.getMean()), MathUtils.rounded(statsGain.getStandardDeviation())); // Histogram of offset, variance and gain final int bins = 2 * HistogramPlot.getBinsSturgesRule(pixelGain.length); final WindowOrganiser wo = new WindowOrganiser(); showHistogram("Offset (ADU)", pixelOffset, bins, statsOffset, wo); showHistogram("Variance (ADU^2)", pixelVariance, bins, statsVariance, wo); showHistogram("Gain (ADU/e)", pixelGain, bins, statsGain, wo); wo.tile(); // Save final float[] bias = SimpleArrayUtils.toFloat(pixelOffset); final float[] variance = SimpleArrayUtils.toFloat(pixelVariance); final float[] gain = SimpleArrayUtils.toFloat(pixelGain); measuredStack = new ImageStack(width, height); measuredStack.addSlice("Offset", bias); measuredStack.addSlice("Variance", variance); measuredStack.addSlice("Gain", gain); final ExtendedGenericDialog egd = new ExtendedGenericDialog(TITLE); egd.addMessage("Save the sCMOS camera model?"); if (settings.modelDirectory == null) { settings.modelDirectory = settings.directory; settings.modelName = "sCMOS Camera"; } egd.addStringField("Model_name", settings.modelName, 30); egd.addDirectoryField("Model_directory", settings.modelDirectory); egd.showDialog(); if (!egd.wasCanceled()) { settings.modelName = egd.getNextString(); settings.modelDirectory = egd.getNextString(); final PerPixelCameraModel cameraModel = new PerPixelCameraModel(width, height, bias, gain, variance); if (!CameraModelManager.save(cameraModel, new File(settings.modelDirectory, settings.modelName).getPath())) { IJ.error(TITLE, "Failed to save model to file"); } } IJ.showStatus(""); // Remove the status from the ij.io.ImageWriter class ImageJUtils .log("Analysis time = " + TextUtils.millisToString(System.currentTimeMillis() - start)); } private static void showHistogram(String name, double[] values, int bins, Statistics stats, WindowOrganiser wo) { final DoubleData data = DoubleData.wrap(values); final double minWidth = 0; final int removeOutliers = 0; final int shape = Plot.CIRCLE; final String label = String.format("Mean = %s +/- %s", MathUtils.rounded(stats.getMean()), MathUtils.rounded(stats.getStandardDeviation())); final HistogramPlot histogramPlot = new HistogramPlotBuilder(TITLE, data, name) .setMinBinWidth(minWidth).setRemoveOutliersOption(removeOutliers).setNumberOfBins(bins) .setPlotShape(shape).setPlotLabel(label).build(); histogramPlot.show(wo); // Redraw using a log scale. This requires a non-zero y-min final Plot plot = histogramPlot.getPlot(); final double[] limits = plot.getLimits(); plot.setLimits(limits[0], limits[1], 1, limits[3]); plot.setAxisYLog(true); plot.updateImage(); } private static <T> void put(BlockingQueue<T> jobs, T job) { try { jobs.put(job); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); throw new ConcurrentRuntimeException("Unexpected interruption", ex); } } private void computeError() { // Assume the simulation stack and measured stack are not null. ImageJUtils.log("Comparison to simulation: %s (%dx%dpx)", simulationImp.getInfoProperty(), simulationImp.getWidth(), simulationImp.getHeight()); WindowOrganiser wo = new WindowOrganiser(); final ImageStack simulationStack = simulationImp.getImageStack(); for (int slice = 1; slice <= 3; slice++) { computeError(slice, simulationStack, wo); } wo.tile(); } private void computeError(int slice, ImageStack simulationStack, WindowOrganiser wo) { final String label = simulationStack.getSliceLabel(slice); final float[] e = (float[]) simulationStack.getPixels(slice); final float[] o = (float[]) measuredStack.getPixels(slice); // Get the mean error final double[] error = new double[e.length]; for (int i = e.length; i-- > 0;) { error[i] = (double) o[i] - e[i]; } final Statistics s = new Statistics(); s.add(error); final StringBuilder result = new StringBuilder("Error ").append(label); result.append(" = ").append(MathUtils.rounded(s.getMean())); result.append(" +/- ").append(MathUtils.rounded(s.getStandardDeviation())); // Do statistical tests final double[] x = SimpleArrayUtils.toDouble(e); final double[] y = SimpleArrayUtils.toDouble(o); final PearsonsCorrelation c = new PearsonsCorrelation(); result.append(" : R=").append(MathUtils.rounded(c.correlation(x, y))); // Plot these String title = TITLE + " " + label + " Simulation vs Measured"; final Plot plot = new Plot(title, "simulated", "measured"); plot.addPoints(e, o, Plot.DOT); plot.addLabel(0, 0, result.toString()); ImageJUtils.display(title, plot, wo); // Histogram the error new HistogramPlotBuilder(TITLE + " " + label, DoubleData.wrap(error), "Error") .setPlotLabel(result.toString()).show(wo); // Kolmogorov–Smirnov test that the distributions are the same double pvalue = TestUtils.kolmogorovSmirnovTest(x, y); result.append(" : Kolmogorov–Smirnov p=").append(MathUtils.rounded(pvalue)).append(' ') .append(((pvalue < 0.001) ? REJECT : ACCEPT)); if (slice == 3) { // Paired T-Test compares two related samples to assess whether their // population means differ. // T-Test is valid when the difference between the means is normally // distributed, e.g. gain pvalue = TestUtils.pairedTTest(x, y); result.append(" : Paired T-Test p=").append(MathUtils.rounded(pvalue)).append(' ') .append(((pvalue < 0.001) ? REJECT : ACCEPT)); } else { // Wilcoxon Signed Rank test compares two related samples to assess whether their // population mean ranks differ final WilcoxonSignedRankTest wsrTest = new WilcoxonSignedRankTest(); pvalue = wsrTest.wilcoxonSignedRankTest(x, y, false); result.append(" : Wilcoxon Signed Rank p=").append(MathUtils.rounded(pvalue)).append(' ') .append(((pvalue < 0.001) ? REJECT : ACCEPT)); } ImageJUtils.log(result.toString()); } }
gpl-3.0
groovejames/groovejames
src/main/java/groovejames/service/PlayServiceListener.java
402
package groovejames.service; import groovejames.model.Track; public interface PlayServiceListener extends DownloadListener { void playbackStarted(Track track); void playbackPaused(Track track); void playbackFinished(Track track); void positionChanged(Track track, int audioPosition); void exception(Track track, Exception ex); void noMoreRadioSongs(); }
gpl-3.0
markusheiden/c64dt
assembler/src/main/java/de/heiden/c64dt/assembler/OpcodeMode.java
3846
package de.heiden.c64dt.assembler; import static de.heiden.c64dt.bytes.HexUtil.hexByte; import static de.heiden.c64dt.bytes.HexUtil.hexWord; import static de.heiden.c64dt.common.Requirements.R; /** * Opcode address mode. */ public enum OpcodeMode { // direct DIR(0, false) { @Override public String toString(int pc, int argument) { return ""; } @Override public String toString(String argument) { return ""; } }, // #$00 IMM(1, false) { @Override public String toString(String argument) { return "#" + argument; } }, // $00 ZPD(1, true) { @Override public String toString(String argument) { return argument; } }, // $00,X ZPX(1, true) { @Override public String toString(String argument) { return argument + ",X"; } }, // $00,Y ZPY(1, true) { @Override public String toString(String argument) { return argument + ",Y"; } }, // ($00,X) IZX(1, true) { @Override public String toString(String argument) { return "(" + argument + ",X)"; } }, // ($00),Y IZY(1, true) { @Override public String toString(String argument) { return "(" + argument + "),Y"; } }, // $0000 ABS(2, true) { @Override public String toString(String argument) { return argument; } }, // $0000,X ABX(2, true) { @Override public String toString(String argument) { return argument + ",X"; } }, // $0000,Y ABY(2, true) { @Override public String toString(String argument) { return argument + ",Y"; } }, // ($0000) IND(2, true) { @Override public String toString(String argument) { return "(" + argument + ")"; } }, // $0000, PC-relative REL(1, true) { @Override public int getAddress(int pc, int argument) { // argument is a signed byte return (pc + 2 + (byte) argument) & 0xFFFF; } @Override public String toString(int pc, int argument) { return toString(hexWord(getAddress(pc, argument))); } @Override public String toString(String argument) { return argument; } }; private final int size; private final boolean isAddress; /** * Number of bytes this address mode uses. */ public final int getSize() { R.requireThat(size, "size").isGreaterThanOrEqualTo(0).isLessThanOrEqualTo(2); return size; } /** * Does this address mode use an address?. */ public boolean isAddress() { return isAddress; } /** * Does this address mode have an argument?. */ public final boolean hasArgument() { return size != 0; } /** * Compute absolute address. * * @param pc Program counter */ public int getAddress(int pc, int argument) { R.requireThat(isAddress(), "isAddress()").isTrue(); return argument; } /** * String representation for this address mode with a given argument. * * @param pc address of opcode * @param argument argument of opcode */ public String toString(int pc, int argument) { // Default implementation, will be overridden by some modes return toString(getSize() == 1 ? hexByte(argument) : hexWord(argument)); } /** * String representation for this address mode with a given (generic) argument. * This method is used for reassembling, if the argument is label. * * @param argument argument */ public abstract String toString(String argument); /** * Constructor. * * @param size number of bytes the argument takes * @param isAddress is the argument a (non zero page) address? */ OpcodeMode(int size, boolean isAddress) { R.requireThat(size, "size").isGreaterThanOrEqualTo(0).isLessThanOrEqualTo(2); this.size = size; this.isAddress = isAddress; } }
gpl-3.0
tkohegyi/adoration
adoration-application/modules/adoration-webapp/src/main/java/org/rockhill/adoration/web/service/FacebookUser.java
721
package org.rockhill.adoration.web.service; import org.rockhill.adoration.database.tables.Person; import org.rockhill.adoration.database.tables.Social; /** * Facebook type of AuthenticatedUser. */ public class FacebookUser extends AuthenticatedUser { /** * Creates a Facebook User login class. * * @param social is the associated Social login record. * @param person is the associated Person record (real life person) if exists * @param sessionTimeoutInSec determines the validity of he session */ public FacebookUser(Social social, Person person, Integer sessionTimeoutInSec) { super("Facebook", social, person, sessionTimeoutInSec); } }
gpl-3.0
PavelClaudiuStefan/LaserTag
src/lasertag/data/InfoMessage.java
827
package lasertag.data; import java.io.Serializable; public class InfoMessage implements Serializable { protected static final long serialVersionUID = 1112122200L; private int sourcePlayer; private int targetPlayer; private boolean endConnection; public InfoMessage(String end) { if(end.compareTo("end") == 0) { endConnection = true; } } public InfoMessage(int sourcePlayer, int targetPlayer) { this.sourcePlayer = sourcePlayer; this.targetPlayer = targetPlayer; endConnection = false; } public int getSourcePlayer() { return sourcePlayer; } public int getTargetPlayer() { return targetPlayer; } public boolean isEnding(){ return endConnection; } }
gpl-3.0
cismet/belis-client
src/main/java/de/cismet/cids/custom/beans/belis2/GeomCustomBean.java
4580
/*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package de.cismet.cids.custom.beans.belis2; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import com.vividsolutions.jts.io.WKTWriter; import de.cismet.cismap.commons.CrsTransformer; import de.cismet.commons.server.entity.BaseEntity; /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ public class GeomCustomBean extends BaseEntity { //~ Static fields/initializers --------------------------------------------- private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(GeomCustomBean.class); public static final String TABLE = "geom"; public static final String PROP__GEO_FIELD = "geo_field"; public static final String PROP__WGS84_WKT = "wgs84_wkt"; //~ Instance fields -------------------------------------------------------- private final WKTWriter WKT_WRITER = new WKTWriter(); private final WKTReader WKT_READER = new WKTReader(); private final int SRID_WGS84 = 4326; private Geometry geo_field; private String wgs84_wkt; //~ Constructors ----------------------------------------------------------- /** * Creates a new BauartCustomBean object. */ public GeomCustomBean() { addPropertyNames( new String[] { PROP__GEO_FIELD, PROP__WGS84_WKT }); } //~ Methods ---------------------------------------------------------------- /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public static GeomCustomBean createNew() { return (GeomCustomBean)createNew(TABLE); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public Geometry getGeo_field() { return geo_field; } /** * DOCUMENT ME! * * @param geo_field DOCUMENT ME! */ public void setGeo_field(final Geometry geo_field) { simpleSetGeo_field(geo_field); if (geo_field == null) { simpleSetWgs84_wkt(null); } else { final String crs = CrsTransformer.createCrsFromSrid(SRID_WGS84); final Geometry transformedGeom = CrsTransformer.transformToGivenCrs(geo_field, crs); transformedGeom.setSRID(SRID_WGS84); simpleSetWgs84_wkt(WKT_WRITER.write(transformedGeom)); } } /** * DOCUMENT ME! * * @param geo_field DOCUMENT ME! */ public void simpleSetGeo_field(final Geometry geo_field) { final Geometry old = this.geo_field; this.geo_field = geo_field; this.propertyChangeSupport.firePropertyChange(PROP__GEO_FIELD, old, this.geo_field); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public Geometry getGeomField() { return getGeo_field(); } /** * DOCUMENT ME! * * @param geomField val DOCUMENT ME! */ public void setGeomField(final Geometry geomField) { setGeo_field(geomField); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public String getWgs84_wkt() { return wgs84_wkt; } /** * DOCUMENT ME! * * @param wgs84_wkt DOCUMENT ME! */ public void setWgs84_wkt(final String wgs84_wkt) { simpleSetWgs84_wkt(wgs84_wkt); if (wgs84_wkt == null) { simpleSetGeo_field(null); } else { try { final Geometry fromWkt = WKT_READER.read(wgs84_wkt); fromWkt.setSRID(SRID_WGS84); final int currentSrid = CrsTransformer.getCurrentSrid(); final String crs = CrsTransformer.createCrsFromSrid(currentSrid); final Geometry transformedGeom = CrsTransformer.transformToGivenCrs(fromWkt, crs); transformedGeom.setSRID(currentSrid); simpleSetGeo_field(transformedGeom); } catch (ParseException ex) { simpleSetGeo_field(null); } } } /** * DOCUMENT ME! * * @param wgs84_wkt DOCUMENT ME! */ private void simpleSetWgs84_wkt(final String wgs84_wkt) { final String old = this.wgs84_wkt; this.wgs84_wkt = wgs84_wkt; this.propertyChangeSupport.firePropertyChange(PROP__WGS84_WKT, old, this.wgs84_wkt); } }
gpl-3.0
asanzdiego/curso-jsf-hibernate-spring-2012
src/jsf-04-facelets/src/com/arcmind/jsfquickstart/controller/ShoppingCartController.java
2538
/* * Created on May 16, 2004 * */ package com.arcmind.jsfquickstart.controller; import com.arcmind.jsfquickstart.model.CD; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.faces.context.FacesContext; /** * DOCUMENT ME! * * @author Richard Hightower */ public class ShoppingCartController { //~ Instance fields -------------------------------------------------------- /** DOCUMENT ME! */ private List items = new ArrayList(); /** DOCUMENT ME! */ private Map itemMap = new TreeMap(); //~ Methods ---------------------------------------------------------------- /** * TODO DOCUMENT ME! * * @return TODO DOCUMENT ME! * * @uml.property name="items" */ public Collection getItems() { return items; } /** * TODO DOCUMENT ME! * * @return TODO DOCUMENT ME! */ public String add() { /* Grab the request map from the faces context */ FacesContext context = FacesContext.getCurrentInstance(); Map map = context.getExternalContext().getRequestParameterMap(); /* Make sure we don't add the same title twice */ String title = (String) map.get("title"); CD cd = (CD) itemMap.get(title); if (cd != null) { return "add"; } /* Grab the aritst and title fields from the request map */ String artist = (String) map.get("artist"); float price = Float.parseFloat((String) map.get("price")); /* Create a new CD and add it to the list and map */ cd = new CD(title, artist, price, ""); itemMap.put(cd.getTitle(), cd); items.add(cd); return "add"; } /** * TODO DOCUMENT ME! * * @return TODO DOCUMENT ME! */ public String remove() { /* Grab the request map from the faces context. */ FacesContext context = FacesContext.getCurrentInstance(); Map map = context.getExternalContext().getRequestParameterMap(); /* Grab the title from the request parameter. * Use the title to remove the CD from the collection and map.*/ String title = (String) map.get("title"); CD cd = (CD) itemMap.get(title); itemMap.remove(cd.getTitle()); itemMap.remove(title); items.remove(cd); return "remove"; } }
gpl-3.0
lummax/moco
src/main/java/de/uni/bremen/monty/moco/ast/expression/CastExpression.java
3568
/* * moco, the Monty Compiler * Copyright (c) 2013-2014, Monty's Coconut, All rights reserved. * * This file is part of moco, the Monty Compiler. * * moco 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.0 of the License, or (at your option) any later version. * * moco 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. * * Linking this program and/or its accompanying libraries statically or * dynamically with other modules is making a combined work based on this * program. Thus, the terms and conditions of the GNU General Public License * cover the whole combination. * * As a special exception, the copyright holders of moco give * you permission to link this programm and/or its accompanying libraries * with independent modules to produce an executable, regardless of the * license terms of these independent modules, and to copy and distribute the * resulting executable under terms of your choice, provided that you also meet, * for each linked independent module, the terms and conditions of the * license of that module. * * An independent module is a module which is not * derived from or based on this program and/or its accompanying libraries. * If you modify this library, you may extend this exception to your version of * the program or library, but you are not obliged to do so. If you do not wish * to do so, delete this exception statement from your version. * * You should have received a copy of the GNU General Public * License along with this library. */ package de.uni.bremen.monty.moco.ast.expression; import de.uni.bremen.monty.moco.ast.*; import de.uni.bremen.monty.moco.visitor.BaseVisitor; public class CastExpression extends Expression { private Expression expression; private ResolvableIdentifier castIdentifier; private Expression inferTypeParameterFrom; public CastExpression(Position position, Expression expression, ResolvableIdentifier castIdentifier) { super(position); this.expression = expression; this.castIdentifier = castIdentifier; this.inferTypeParameterFrom = null; } public CastExpression(Position position, Expression expression, ResolvableIdentifier castIdentifier, Expression inferTypeParameterFrom) { super(position); this.expression = expression; this.castIdentifier = castIdentifier; this.inferTypeParameterFrom = inferTypeParameterFrom; } public ResolvableIdentifier getCastIdentifier() { return castIdentifier; } public Expression getExpression() { return expression; } public boolean typeParameterMustBeInferred() { return inferTypeParameterFrom != null; } public void inferTypeParameter() { if (inferTypeParameterFrom.getType().getIdentifier() instanceof ResolvableIdentifier) { ResolvableIdentifier otherIdent = (ResolvableIdentifier) inferTypeParameterFrom.getType().getIdentifier(); int max = Math.min(otherIdent.getGenericTypes().size(), castIdentifier.getGenericTypes().size()); for (int i = 0; i < max; i++) { castIdentifier.getGenericTypes().set(i, otherIdent.getGenericTypes().get(i)); } } } @Override public void visit(BaseVisitor visitor) { visitor.visit(this); } @Override public void visitChildren(BaseVisitor visitor) { visitor.visitDoubleDispatched(expression); } }
gpl-3.0
bbockelm/xrootd_old_git
src/XrdClient/XrdClientAdminJNI.java
1636
package xrootdadmin; public class XrdClientAdminJNI { // This usually is an xrootd redirector String firsturl; public native boolean chmod(String locpathfile1, int user, int group, int other); public native boolean dirlist(String path, String[] lst); public native boolean existfiles(String[] pathslist, boolean[] res); public native boolean existdirs(String[] pathslist, boolean[] res); public native boolean getchecksum(String pathname, String chksum); public native boolean isfileonline(String[] pathslist, boolean[] res); // Finds one of the final locations for a given file // Returns false if errors occurred public native boolean locate(String pathfile, String hostname); public native boolean mv(String locpathfile1, String locpathfile2); public native boolean mkdir(String locpathfile1, int user, int group, int other); public native boolean rm(String locpathfile); public native boolean rmdir(String locpath); public native boolean prepare(String[] pathnamelist, char opts, char priority); // Gives info for a given file public native boolean stat(String pathfile, int id, long size, int flags, int modtime); public XrdClientAdminJNI(String hostname) { firsturl = "xroot://"+hostname+"//dummy"; }; public static void main(String args[]) { XrdClientAdminJNI a = new XrdClientAdminJNI("kanolb-a.slac.stanford.edu"); String newhost = ""; boolean r = a.locate("pippo.root", newhost); System.out.println("Locate Result: " + r + " host: '" + newhost + "'"); } static { System.loadLibrary("XrdClientAdminJNI"); } }
gpl-3.0
mejariamol/open-event-orga-app
app/src/main/java/org/fossasia/openevent/app/data/models/SimpleModel.java
1377
package org.fossasia.openevent.app.data.models; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.structure.BaseModel; import org.fossasia.openevent.app.data.db.configuration.OrgaDatabase; @Table(database = OrgaDatabase.class, allFields = true) public class SimpleModel extends BaseModel { @PrimaryKey public long id; public String name; public String description; SimpleModel() {} public SimpleModel(long id, String name, String description) { this.id = id; this.name = name; this.description = description; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SimpleModel that = (SimpleModel) o; if (id != that.id) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; return description != null ? description.equals(that.description) : that.description == null; } @Override public int hashCode() { int result = (int) (id ^ (id >>> 32)); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (description != null ? description.hashCode() : 0); return result; } }
gpl-3.0
Paget96/substratum
app/src/main/java/projekt/substratum/adapters/OverlayManagerAdapter.java
4835
/* * Copyright (c) 2016-2017 Projekt Substratum * This file is part of Substratum. * * Substratum 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. * * Substratum 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 Substratum. If not, see <http://www.gnu.org/licenses/>. */ package projekt.substratum.adapters; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import projekt.substratum.R; import projekt.substratum.config.References; import projekt.substratum.model.OverlayManager; public class OverlayManagerAdapter extends RecyclerView.Adapter<OverlayManagerAdapter.ViewHolder> { private List<OverlayManager> overlayList; public OverlayManagerAdapter(List<OverlayManager> overlays) { this.overlayList = overlays; } @Override public OverlayManagerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate( R.layout.overlay_manager_row, parent, false); return new ViewHolder(itemLayoutView); } @Override public void onBindViewHolder(final ViewHolder viewHolder, int position) { final int position_fixed = position; viewHolder.tvName.setText(References.grabPackageName( overlayList.get(position_fixed).getContext(), References.grabOverlayTarget( overlayList.get(position_fixed).getContext(), overlayList.get(position_fixed).getName()))); viewHolder.tvDesc.setText(overlayList.get(position_fixed).getName()); viewHolder.tvName.setTextColor(overlayList.get(position_fixed).getActivationValue()); viewHolder.chkSelected.setChecked(overlayList.get(position_fixed).isSelected()); viewHolder.chkSelected.setTag(overlayList.get(position_fixed)); viewHolder.chkSelected.setOnClickListener(v -> { CheckBox cb = (CheckBox) v; OverlayManager contact = (OverlayManager) cb.getTag(); contact.setSelected(cb.isChecked()); overlayList.get(position_fixed).setSelected(cb.isChecked()); }); viewHolder.card.setOnClickListener(v -> { viewHolder.chkSelected.setChecked(!viewHolder.chkSelected.isChecked()); CheckBox cb = viewHolder.chkSelected; OverlayManager contact = (OverlayManager) cb.getTag(); contact.setSelected(cb.isChecked()); contact.setSelected(cb.isChecked()); }); viewHolder.appIcon.setImageDrawable(References.grabAppIcon( overlayList.get(position_fixed).getContext(), References.grabOverlayParent( overlayList.get(position_fixed).getContext(), overlayList.get(position_fixed).getName()))); viewHolder.appIconTarget.setImageDrawable(References.grabAppIcon( overlayList.get(position_fixed).getContext(), References.grabOverlayTarget( overlayList.get(position_fixed).getContext(), overlayList.get(position_fixed).getName()))); } @Override public int getItemCount() { return overlayList.size(); } public List<OverlayManager> getOverlayManagerList() { return overlayList; } static class ViewHolder extends RecyclerView.ViewHolder { TextView tvName; TextView tvDesc; CheckBox chkSelected; CardView card; ImageView appIcon; ImageView appIconTarget; ViewHolder(View itemLayoutView) { super(itemLayoutView); tvName = (TextView) itemLayoutView.findViewById(R.id.tvName); tvDesc = (TextView) itemLayoutView.findViewById(R.id.tvDesc); card = (CardView) itemLayoutView.findViewById(R.id.overlayCard); chkSelected = (CheckBox) itemLayoutView.findViewById(R.id.chkSelected); appIcon = (ImageView) itemLayoutView.findViewById(R.id.app_icon); appIconTarget = (ImageView) itemLayoutView.findViewById(R.id.app_icon_sub); } } }
gpl-3.0
apruden/opal
opal-core-ws/src/main/java/org/obiba/opal/web/magma/support/PagingVectorSource.java
657
/******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * 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.obiba.opal.web.magma.support; import org.obiba.magma.Value; public interface PagingVectorSource { Iterable<Value> getValues(int offset, int limit); }
gpl-3.0
imyelmo/relod.net
reload/Common/KindId.java
1902
/******************************************************************************* * <relod.net: GPLv3 beta software implementing RELOAD - draft-ietf-p2psip-base-26 > * Copyright (C) <2013> <Marcos Lopez-Samaniego, Isaias Martinez-Yelmo, Roberto Gonzalez-Sanchez> Contact: isaias.martinezy@uah.es * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *******************************************************************************/ package reload.Common; import java.io.*; import reload.Common.*; import reload.Storage.*; public class KindId{ private int data; public KindId(int data){ this.data = data; } public KindId(byte[] data){ this.data = Utils.toInt(data, 0); } public byte[] getBytes() throws IOException{ return Utils.toByte(data); } public int getId(){ return data; } public DataModel getDataModel(){ return Module.si.kind_model.getDataModel(data); } }
gpl-3.0
Zaik0/Programacion-Concurrente
P1/NewtonRaphson.java
1959
package P1; import static java.lang.Math.cos; import static java.lang.Math.pow; import static java.lang.Math.sin; import java.util.Scanner; /**Fichero NewtonRaphson.java * @author Antonio * @version 1.-- * Practica 1 Semana 3 * Ejercicio 2 */ public class NewtonRaphson { public static double fun1 (double x){ return (cos(x)-pow(x,3)); } public static double der1 (double x){ return (-sin(x) - 3*pow(x,2) ); } public static double fun2 (double x){ return (pow(x,2)-5); } public static double der2 (double x){ return (2*x); } public static void main(String[] args) { Scanner teclado = new Scanner(System.in); System.out.println("Introduzca la aproximación Inicial x0:"); double x = teclado.nextDouble(); System.out.println("Introduzca el numero de Iteraciones(cuanto más iteraciones,más exactitud:"); int iteraciones = teclado.nextInt(); System.out.println("Para que funcion quiere hallar el punto de corte :"); System.out.println("1. f(x) = cos(x) - x^3 \n2. f(x) = x^2 - 5"); int opcion; do{ opcion = teclado.nextInt(); switch(opcion){ case 1: for(int i =0;i<=iteraciones;i++){ x = x -(fun1(x)/der1(x)); System.out.println("La aproximacion para el valor x"+i+" es:"+x); } break; case 2: for(int i =0;i<=iteraciones;i++){ x = x - (fun2(x)/der2(x)); System.out.println("La aproximacion para el valor x"+i+" es:"+x); } break; default: System.out.println("Introduzca otra opcion que este contemplada"); } }while(opcion <= 2); } }
gpl-3.0
Camelion/JTS-V3
gameserver/src/main/java/ru/jts_dev/gameserver/packets/in/ValidatePosition.java
2351
/* * Copyright (c) 2015, 2016, 2017 JTS-Team authors and/or its affiliates. All rights reserved. * * This file is part of JTS-V3 Project. * * JTS-V3 Project 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. * * JTS-V3 Project 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 JTS-V3 Project. If not, see <http://www.gnu.org/licenses/>. */ package ru.jts_dev.gameserver.packets.in; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.springframework.beans.factory.annotation.Autowired; import ru.jts_dev.common.packets.IncomingMessageWrapper; import ru.jts_dev.gameserver.packets.Opcode; import ru.jts_dev.gameserver.service.BroadcastService; import ru.jts_dev.gameserver.service.GameSessionService; import ru.jts_dev.gameserver.service.PlayerService; import ru.jts_dev.gameserver.util.RotationUtils; /** * @author Java-man * @since 11.01.2016 */ @Opcode(0x59) public class ValidatePosition extends IncomingMessageWrapper { @Autowired private BroadcastService broadcastService; @Autowired private GameSessionService sessionService; @Autowired private PlayerService playerService; @Autowired private RotationUtils rotationUtils; private Vector3D location; private int heading; private int boatObjectId; @Override public void prepare() { location = new Vector3D(readInt(), readInt(), readInt()); heading = readInt(); boatObjectId = readInt(); } @Override public void run() { // TODO /*final GameSession session = sessionService.getSessionBy(getConnectionId()); final GameCharacter character = playerService.getCharacterBy(getConnectionId()); final int clientHeading = rotationUtils.convertAngleToClientHeading((int) character.getAngle()); broadcastService.send(session, new ValidateLocation(character, clientHeading));*/ } }
gpl-3.0
xframium/xframium-java
framework/src/org/xframium/page/keyWord/step/KeyWordStepFactory.java
16531
/******************************************************************************* * xFramium * * Copyright 2016 by Moreland Labs, Ltd. (http://www.morelandlabs.com) * * Some open source application is free software: you can redistribute * it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * * Some open source application is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with xFramium. If not, see <http://www.gnu.org/licenses/>. * * @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+> *******************************************************************************/ package org.xframium.page.keyWord.step; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xframium.page.keyWord.KeyWordStep; import org.xframium.page.keyWord.KeyWordStep.StepFailure; import org.xframium.page.keyWord.KeyWordStep.ValidationType; import org.xframium.page.keyWord.KeyWordToken; import org.xframium.page.keyWord.step.spi.KWSAccessibility; import org.xframium.page.keyWord.step.spi.KWSAddDevice; import org.xframium.page.keyWord.step.spi.KWSAddDevice2; import org.xframium.page.keyWord.step.spi.KWSAlert; import org.xframium.page.keyWord.step.spi.KWSAlign; import org.xframium.page.keyWord.step.spi.KWSApplication; import org.xframium.page.keyWord.step.spi.KWSAt; import org.xframium.page.keyWord.step.spi.KWSAttribute; import org.xframium.page.keyWord.step.spi.KWSBreak; import org.xframium.page.keyWord.step.spi.KWSBrowser; import org.xframium.page.keyWord.step.spi.KWSCache; import org.xframium.page.keyWord.step.spi.KWSCall; import org.xframium.page.keyWord.step.spi.KWSCall2; import org.xframium.page.keyWord.step.spi.KWSCheckColor; import org.xframium.page.keyWord.step.spi.KWSClick; import org.xframium.page.keyWord.step.spi.KWSCommand; import org.xframium.page.keyWord.step.spi.KWSCompare; import org.xframium.page.keyWord.step.spi.KWSCompare2; import org.xframium.page.keyWord.step.spi.KWSConsole; import org.xframium.page.keyWord.step.spi.KWSContext; import org.xframium.page.keyWord.step.spi.KWSContrastRatio; import org.xframium.page.keyWord.step.spi.KWSDate; import org.xframium.page.keyWord.step.spi.KWSDebug; import org.xframium.page.keyWord.step.spi.KWSDevice; import org.xframium.page.keyWord.step.spi.KWSDumpState; import org.xframium.page.keyWord.step.spi.KWSElse; import org.xframium.page.keyWord.step.spi.KWSEmail; import org.xframium.page.keyWord.step.spi.KWSEnabled; import org.xframium.page.keyWord.step.spi.KWSExecJS; import org.xframium.page.keyWord.step.spi.KWSExecWS; import org.xframium.page.keyWord.step.spi.KWSExists; import org.xframium.page.keyWord.step.spi.KWSFlow; import org.xframium.page.keyWord.step.spi.KWSFocus; import org.xframium.page.keyWord.step.spi.KWSFork; import org.xframium.page.keyWord.step.spi.KWSFunction; import org.xframium.page.keyWord.step.spi.KWSGesture; import org.xframium.page.keyWord.step.spi.KWSGherkin; import org.xframium.page.keyWord.step.spi.KWSLoop; import org.xframium.page.keyWord.step.spi.KWSMath; import org.xframium.page.keyWord.step.spi.KWSMouse; import org.xframium.page.keyWord.step.spi.KWSNavigate; import org.xframium.page.keyWord.step.spi.KWSOperator; import org.xframium.page.keyWord.step.spi.KWSRandom; import org.xframium.page.keyWord.step.spi.KWSReport; import org.xframium.page.keyWord.step.spi.KWSReturn; import org.xframium.page.keyWord.step.spi.KWSSQL; import org.xframium.page.keyWord.step.spi.KWSScript; import org.xframium.page.keyWord.step.spi.KWSSelected; import org.xframium.page.keyWord.step.spi.KWSSet; import org.xframium.page.keyWord.step.spi.KWSSetContentKey; import org.xframium.page.keyWord.step.spi.KWSString; import org.xframium.page.keyWord.step.spi.KWSString2; import org.xframium.page.keyWord.step.spi.KWSSwitch; import org.xframium.page.keyWord.step.spi.KWSSync; import org.xframium.page.keyWord.step.spi.KWSValue; import org.xframium.page.keyWord.step.spi.KWSVisible; import org.xframium.page.keyWord.step.spi.KWSVisual; import org.xframium.page.keyWord.step.spi.KWSWait; import org.xframium.page.keyWord.step.spi.KWSWaitFor; import org.xframium.page.keyWord.step.spi.KWSWindow; import com.xframium.serialization.SerializationManager; import com.xframium.serialization.json.ReflectionSerializer; // TODO: Auto-generated Javadoc /** * A factory for creating KeyWordStep objects. */ public class KeyWordStepFactory { /** The singleton. */ private static KeyWordStepFactory singleton = new KeyWordStepFactory(); /** * Instance. * * @return the key word step factory */ public static KeyWordStepFactory instance() { return singleton; } /** The step map. */ private Map<String, Class> stepMap = new HashMap<String, Class>( 20 ); private Map<Class, String> classMap = new HashMap<Class, String>( 20 ); /** The log. */ private Log log = LogFactory.getLog( KeyWordStepFactory.class ); public String getKW( Class currentClass ) { return classMap.get( currentClass ); } /** * Instantiates a new key word step factory. */ private KeyWordStepFactory() { initializeDefaults(); } public List<KeyWordStep> getSupportedKeywords() { List<KeyWordStep> supportedKeywords = new ArrayList<KeyWordStep>( 20 ); for ( Class keyword : stepMap.values() ) { try { supportedKeywords.add( (KeyWordStep) keyword.newInstance() ); } catch( Exception e ) { } } return supportedKeywords; } /** * Initialize defaults. */ private void initializeDefaults() { addKeyWord( "CALL", KWSCall.class ); addKeyWord( "CALL2", KWSCall2.class ); addKeyWord( "CLICK", KWSClick.class ); addKeyWord( "EXISTS", KWSExists.class ); addKeyWord( "FUNCTION", KWSFunction.class ); addKeyWord( "GESTURE", KWSGesture.class ); addKeyWord( "RETURN", KWSReturn.class ); addKeyWord( "SET", KWSSet.class ); addKeyWord( "GET", KWSValue.class ); addKeyWord( "WAIT", KWSWait.class ); addKeyWord( "WAIT_FOR", KWSWaitFor.class ); addKeyWord( "ATTRIBUTE", KWSAttribute.class ); addKeyWord( "LOOP", KWSLoop.class ); addKeyWord( "BREAK", KWSBreak.class ); addKeyWord( "DEVICE", KWSDevice.class ); addKeyWord( "FORK", KWSFork.class ); addKeyWord( "VISIBLE", KWSVisible.class ); addKeyWord( "VERIFY_COLOR", KWSCheckColor.class ); addKeyWord( "VERIFY_CONTRAST", KWSContrastRatio.class ); addKeyWord( "WINDOW", KWSWindow.class ); addKeyWord( "EXECJS", KWSExecJS.class ); addKeyWord( "EXECWS", KWSExecWS.class ); addKeyWord( "COMPARE", KWSCompare.class ); addKeyWord( "COMPARE2", KWSCompare2.class ); addKeyWord( "STRING", KWSString.class ); addKeyWord( "STRING2", KWSString2.class ); addKeyWord( "MATH", KWSMath.class ); addKeyWord( "MOUSE", KWSMouse.class ); addKeyWord( "CACHE", KWSCache.class ); addKeyWord( "REPORT", KWSReport.class ); addKeyWord( "ADD_DEVICE", KWSAddDevice.class ); addKeyWord( "ADD_DEVICE2", KWSAddDevice2.class ); addKeyWord( "HAS_FOCUS", KWSFocus.class ); addKeyWord( "ALIGN", KWSAlign.class ); addKeyWord( "SYNC", KWSSync.class ); addKeyWord( "AT", KWSAt.class ); addKeyWord( "ELSE", KWSElse.class ); addKeyWord( "STATE", KWSDumpState.class ); addKeyWord( "ALERT", KWSAlert.class ); addKeyWord( "SQL", KWSSQL.class ); addKeyWord( "OPERATOR", KWSOperator.class ); addKeyWord( "NAVIGATE", KWSNavigate.class ); addKeyWord( "VISUAL", KWSVisual.class ); addKeyWord( "SET_CONTENT_KEY", KWSSetContentKey.class ); addKeyWord( "BROWSER", KWSBrowser.class ); addKeyWord( "ENABLED", KWSEnabled.class ); addKeyWord( "COMMAND", KWSCommand.class ); addKeyWord( "EMAIL", KWSEmail.class ); addKeyWord( "CONSOLE", KWSConsole.class ); addKeyWord( "APPLICATION", KWSApplication.class ); addKeyWord( "FLOW", KWSFlow.class ); addKeyWord( "RANDOM", KWSRandom.class ); addKeyWord( "SELECTED", KWSSelected.class ); addKeyWord( "DATE", KWSDate.class ); addKeyWord( "DEBUG", KWSDebug.class ); addKeyWord( "CONTEXT", KWSContext.class ); addKeyWord( "ACCESSIBILITY", KWSAccessibility.class ); addKeyWord( "GHERKIN", KWSGherkin.class ); addKeyWord( "SWITCH", KWSSwitch.class ); addKeyWord( "SCRIPT", KWSScript.class ); } /** * Adds the key word. * * @param keyWord * the key word * @param kwImpl * the kw impl */ public void addKeyWord( String keyWord, Class kwImpl ) { if ( stepMap.containsKey( keyWord ) ) log.warn( "Overwriting Keyword [" + keyWord + "] of type [" + stepMap.get( keyWord ).getClass().getSimpleName() + "] with [" + kwImpl.getClass().getSimpleName() ); stepMap.put( keyWord.toUpperCase(), kwImpl ); classMap.put( kwImpl, keyWord ); SerializationManager.instance().getAdapter( SerializationManager.JSON_SERIALIZATION ).addCustomMapping( kwImpl, new ReflectionSerializer() ); } /** * Creates a new KeyWordStep object. * * @param name * the name * @param pageName * the page name * @param active * the active * @param type * the type * @param linkId * the link id * @param timed * the timed * @param sFailure * the s failure * @param inverse * the inverse * @param os * the os * @param poi * the poi * @param threshold * the threshold * @param description * the description * @param waitTime * the wait time * @param context * the context * @param validation * the validation * @param device * the device * @param validationType * the validation type * @return the key word step */ public KeyWordStep createStep( String name, String pageName, boolean active, String type, String linkId, boolean timed, StepFailure sFailure, boolean inverse, String os, String browser, String poi, int threshold, String description, long waitTime, String context, String validation, String device, ValidationType validationType, String tagNames, boolean startAt, boolean breakpoint, String deviceTags, String siteName, Map<String,String> overrideMap, String version, String appContext, String waitFor, boolean trace, String successReport, String failureReport, boolean allowMultiple ) { Class kwImpl = stepMap.get( type.toUpperCase() ); if ( kwImpl == null ) { log.error( "Unknown KeyWord [" + type + "]" ); } try { KeyWordStep returnValue = (KeyWordStep) kwImpl.newInstance(); returnValue.setActive( active ); returnValue.setLinkId( linkId ); returnValue.setName( name ); returnValue.setPageName( pageName ); returnValue.setTimed( timed ); returnValue.setFailure( sFailure ); returnValue.setInverse( inverse ); returnValue.setOs( os ); returnValue.setBrowser( browser ); returnValue.setPoi( poi ); returnValue.setSuccessReport( successReport ); returnValue.setFailureReport( failureReport ); returnValue.setAllowMultiple(allowMultiple); if ( threshold > 0 ) { String thresholdModifier = overrideMap.get( "thresholdModifier" ); if ( thresholdModifier != null ) { double modifierPercent = ( Integer.parseInt( thresholdModifier ) / 100.0 ); double modifierValue = Math.abs( modifierPercent ) * (double) threshold; if ( modifierPercent > 0 ) returnValue.setThreshold( threshold + (int)modifierValue ); else returnValue.setThreshold( threshold - (int)modifierValue ); } } else returnValue.setThreshold( threshold ); returnValue.setDescription( description ); if ( waitTime > 0 ) { String waitModifier = overrideMap.get( "waitModifier" ); if ( waitModifier != null ) { double modifierPercent = ( Integer.parseInt( waitModifier ) / 100.0 ); double modifierValue = Math.abs( modifierPercent ) * (double) waitTime; if ( modifierPercent > 0 ) returnValue.setWait( waitTime + (int)modifierValue ); else returnValue.setWait( waitTime - (int)modifierValue ); } else returnValue.setWait( waitTime ); } returnValue.setValidation( validation ); returnValue.setValidationType( validationType ); returnValue.setContext( context ); returnValue.setDevice( device ); returnValue.setTagNames( tagNames ); returnValue.setStartAt( startAt ); returnValue.setBreakpoint( breakpoint ); returnValue.setDeviceTags( deviceTags ); if ( siteName != null && siteName.trim().length() > 0 ) returnValue.setSiteName( siteName ); returnValue.setVersion( version ); returnValue.setAppContext( appContext ); returnValue.setWaitFor(waitFor); returnValue.setTrace(trace); return returnValue; } catch ( Exception e ) { throw new IllegalArgumentException( "Unknown KeyWord [" + type + "]", e ); } } public KeyWordStep createStep( KeyWordStep k ) { KeyWordStep kW = createStep( k.getName(), k.getPageName(), k.isActive(), k.getKw(), k.getLinkId(), k.isTimed(), k.getFailure(), k.isInverse(), k.getOs(), k.getBrowser(), k.getPoi(), k.getThreshold(), k.getDescription(), k.getWait(), k.getContext(), k.getValidation(), k.getDevice(), k.getValidationType(), null, k.isStartAt(), k.isBreakpoint(), null, k.getSiteName(), new HashMap<String,String>(), k.getVersion() != null ? k.getVersion().toString() : null, k.getAppContext(), k.getWaitFor(), k.isTrace(), k.getSuccessReport(), k.getFailureReport(), k.isAllowMultiple() ); kW.setTagNames( k.getTagNames() ); kW.setDeviceTags( k.getDeviceTags() ); for ( KeyWordToken t : k.getReportTokenList() ) kW.addReportingToken( t ); return kW; } private String getValue( String attributeName, String attributeValue, Map<String,String> overrideMap ) { String keyName = attributeName; if ( System.getProperty( keyName ) != null ) return System.getProperty( keyName ); if ( overrideMap.containsKey( keyName ) ) return overrideMap.get( keyName ); else return attributeValue; } }
gpl-3.0
dakside/shacc
HaccCore/test/dakside/hacc/core/dao/db4o/Db4oSuite.java
2581
/* * Copyright (C) 2009 Le Tuan Anh * * 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 dakside.hacc.core.dao.db4o; import org.dakside.dao.ConnectionInfo; import org.dakside.dao.DAOException; import dakside.hacc.core.dao.DAOFactory; import org.dakside.exceptions.ArgumentException; import java.io.File; import java.util.logging.Level; import java.util.logging.Logger; import org.dakside.utils.SystemHelper; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * * @author LeTuanAnh <tuananh.ke@gmail.com> */ @RunWith(Suite.class) @Suite.SuiteClasses({dakside.hacc.core.dao.db4o.DB4OTransactionDAOTest.class, dakside.hacc.core.dao.db4o.DB4OAccountDAOTest.class, dakside.hacc.core.dao.db4o.DB4ODAOFactoryTest.class}) public class Db4oSuite { @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } public static DAOFactory buildFactory() throws ArgumentException { try { System.out.println("Test get account DAO"); int dbType = DAOFactory.DB4O_DATABASE; //XXX test DB file path (change this if test on linux) String path = SystemHelper.getTempDir() + SystemHelper.getPathSeparator() + "testdb.db"; File f = new File(path); if (f.exists()) { f.delete(); } ConnectionInfo info = new ConnectionInfo(f.getAbsolutePath(), dbType); return DAOFactory.getDAOFactory(info); } catch (DAOException ex) { Logger.getLogger(Db4oSuite.class.getName()).log(Level.SEVERE, null, ex); } return null; } }
gpl-3.0
danielhams/mad-java
2COMMONPROJECTS/audio-services/src/uk/co/modularaudio/mads/base/specamplarge/ui/SpecAmpLargeDisplayUiJComponent.java
1680
/** * * Copyright (C) 2015 - Daniel Hams, Modular Audio Limited * daniel.hams@gmail.com * * Mad 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. * * Mad 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 Mad. If not, see <http://www.gnu.org/licenses/>. * */ package uk.co.modularaudio.mads.base.specamplarge.ui; import uk.co.modularaudio.mads.base.specampgen.ui.SpectralAmpGenDisplayUiJComponent; import uk.co.modularaudio.mads.base.specamplarge.mu.SpecAmpLargeMadDefinition; import uk.co.modularaudio.mads.base.specamplarge.mu.SpecAmpLargeMadInstance; public class SpecAmpLargeDisplayUiJComponent extends SpectralAmpGenDisplayUiJComponent<SpecAmpLargeMadDefinition, SpecAmpLargeMadInstance, SpecAmpLargeMadUiInstance> { private static final long serialVersionUID = 4479101298784505822L; private static final int NUM_AMP_MARKERS = 10; private static final int NUM_FREQ_MARKERS = 18; public SpecAmpLargeDisplayUiJComponent( final SpecAmpLargeMadDefinition definition, final SpecAmpLargeMadInstance instance, final SpecAmpLargeMadUiInstance uiInstance, final int controlIndex ) { super( definition, instance, uiInstance, controlIndex, NUM_AMP_MARKERS, NUM_FREQ_MARKERS ); } }
gpl-3.0
claudiofus/WeatherApp
app/src/androidTest/java/com/claudiofus/clock2/ApplicationTest.java
1068
/* * Copyright 2017 Phillip Hsu * * This file is part of ClockPlus. * * ClockPlus 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. * * ClockPlus 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 ClockPlus. If not, see <http://www.gnu.org/licenses/>. */ package com.claudiofus.clock2; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
gpl-3.0
rabsouza/arcadia-caller-app
app/src/main/java/br/com/battista/arcadiacaller/util/MailUtil.java
816
package br.com.battista.arcadiacaller.util; import com.google.common.base.Strings; import java.util.regex.Pattern; public class MailUtil { private static final String CHAR_MAIL = "@"; private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; private MailUtil() { } public static boolean isValidEmailAddress(final String mail) { Pattern pattern = Pattern.compile(EMAIL_PATTERN); return pattern.matcher(mail).matches(); } public static String extractUsernameByMail(String mail) { if (Strings.isNullOrEmpty(mail) || !isValidEmailAddress(mail)) { return mail; } else { return mail.substring(0, mail.indexOf(CHAR_MAIL)); } } }
gpl-3.0
avdata99/SIAT
siat-1.0-SOURCE/src/view/src/WEB-INF/src/ar/gov/rosario/siat/gde/view/struts/AdministrarDeudaExcProMasAgregarDAction.java
8701
//Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda. //This file is part of SIAT. SIAT is licensed under the terms //of the GNU General Public License, version 3. //See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt> package ar.gov.rosario.siat.gde.view.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import ar.gov.rosario.siat.base.view.struts.BaseDispatchAction; import ar.gov.rosario.siat.base.view.util.UserSession; import ar.gov.rosario.siat.gde.iface.model.DeudaExcProMasAgregarSearchPage; import ar.gov.rosario.siat.gde.iface.service.GdeServiceLocator; import ar.gov.rosario.siat.gde.iface.util.GdeSecurityConstants; import ar.gov.rosario.siat.gde.view.util.GdeConstants; import coop.tecso.demoda.iface.helper.DemodaUtil; import coop.tecso.demoda.iface.model.NavModel; //Administra la agregacion de la seleccion almacenada de la deuda a excluir del proceso de envio a judicial public final class AdministrarDeudaExcProMasAgregarDAction extends BaseDispatchAction { private Log log = LogFactory.getLog(AdministrarDeudaExcProMasAgregarDAction.class); public ActionForward inicializar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String funcName = DemodaUtil.currentMethodName(); if (log.isDebugEnabled()) log.debug("entrando en " + funcName); // TODO revisar el canAccess: asunto permisos y constantes UserSession userSession = canAccess(request, mapping, GdeSecurityConstants.ABM_PROCESO_PROCESO_MASIVO, GdeConstants.ACT_ADMINISTRAR_PROCESO_PROCESO_MASIVO); if (userSession == null) return forwardErrorSession(request); NavModel navModel = userSession.getNavModel(); String stringServicio = ""; // ActionForward actionForward = null; try { //CommonKey commonKey = new CommonKey(navModel.getSelectedId()); // Bajo el searchPage del userSession DeudaExcProMasAgregarSearchPage deudaExcProMasAgregarSearchPageVO = (DeudaExcProMasAgregarSearchPage) userSession.get(DeudaExcProMasAgregarSearchPage.NAME); // Si es nulo no se puede continuar if (deudaExcProMasAgregarSearchPageVO == null) { log.error("error en: " + funcName + ": " + DeudaExcProMasAgregarSearchPage.NAME + " IS NULL. No se pudo obtener de la sesion"); return forwardErrorSessionNullObject(mapping, request, funcName, DeudaExcProMasAgregarSearchPage.NAME); } // invocar al servicio que vuelve a ejecutar la consulta contenida en el searchPage stringServicio = "getDeudaExcProMasAgregSelIndSeachPageInit(userSession, deudaExcProMasAgregarSearchPageVO)"; deudaExcProMasAgregarSearchPageVO = GdeServiceLocator.getGestionDeudaJudicialService().getDeudaExcProMasAgregarSelIndSeachPage(userSession, deudaExcProMasAgregarSearchPageVO); // Tiene errores recuperables if (deudaExcProMasAgregarSearchPageVO.hasErrorRecoverable()) { log.error("recoverable error en: " + funcName + ": " + deudaExcProMasAgregarSearchPageVO.infoString()); saveDemodaErrors(request, deudaExcProMasAgregarSearchPageVO); return forwardErrorRecoverable(mapping, request, userSession, DeudaExcProMasAgregarSearchPage.NAME, deudaExcProMasAgregarSearchPageVO); } // Tiene errores no recuperables if (deudaExcProMasAgregarSearchPageVO.hasErrorNonRecoverable()) { log.error("error en: " + funcName + ": " + deudaExcProMasAgregarSearchPageVO.errorString()); return forwardErrorNonRecoverable(mapping, request, funcName, DeudaExcProMasAgregarSearchPage.NAME, deudaExcProMasAgregarSearchPageVO); } // Seteo los valores de navegacion en el adapter deudaExcProMasAgregarSearchPageVO.setValuesFromNavModel(navModel); // para que se dibuje la lista de resultados porque getView trabaja sobre el pageNumber deudaExcProMasAgregarSearchPageVO.setPageNumber(1L); // Subo el apdater al userSession userSession.put(DeudaExcProMasAgregarSearchPage.NAME, deudaExcProMasAgregarSearchPageVO); saveDemodaMessages(request, deudaExcProMasAgregarSearchPageVO); // Envio el VO al request request.setAttribute(DeudaExcProMasAgregarSearchPage.NAME, deudaExcProMasAgregarSearchPageVO); return mapping.findForward(GdeConstants.FWD_DEUDA_EXC_PRO_MAS_AGREGAR_SELEC_IND_SEARCHPAGE); } catch (Exception exception) { return baseException(mapping, request, funcName, exception, DeudaExcProMasAgregarSearchPage.NAME); } } // agregar seleccion individual public ActionForward agregarSeleccionIndividual(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String funcName = DemodaUtil.currentMethodName(); if (log.isDebugEnabled()) log.debug("entrando en " + funcName); // TODO ver constantes del canAccess UserSession userSession = canAccess(request, mapping, GdeSecurityConstants.ABM_PROCESO_PROCESO_MASIVO, GdeConstants.ACT_ADMINISTRAR_PROCESO_PROCESO_MASIVO); if (userSession==null) return forwardErrorSession(request); try { // Bajo el SearchPage del userSession DeudaExcProMasAgregarSearchPage deudaExcProMasAgregarSelecIndSearchPageVO = (DeudaExcProMasAgregarSearchPage) userSession.get(DeudaExcProMasAgregarSearchPage.NAME); // Si es nulo no se puede continuar if (deudaExcProMasAgregarSelecIndSearchPageVO == null) { log.error("error en: " + funcName + ": " + DeudaExcProMasAgregarSearchPage.NAME + " IS NULL. No se pudo obtener de la sesion"); return forwardErrorSessionNullObject(mapping, request, funcName, DeudaExcProMasAgregarSearchPage.NAME); } // no realizamos populate ya que solo leemos del request la lista de ids seleccionados deudaExcProMasAgregarSelecIndSearchPageVO.setListIdDeudaAdmin(request.getParameterValues("listIdDeudaAdmin")); // Tiene errores recuperables if (deudaExcProMasAgregarSelecIndSearchPageVO.hasErrorRecoverable()) { log.error("recoverable error en: " + funcName + ": " + deudaExcProMasAgregarSelecIndSearchPageVO.infoString()); saveDemodaErrors(request, deudaExcProMasAgregarSelecIndSearchPageVO); return forwardErrorRecoverable(mapping, request, userSession, DeudaExcProMasAgregarSearchPage.NAME, deudaExcProMasAgregarSelecIndSearchPageVO); } // llamada al servicio deudaExcProMasAgregarSelecIndSearchPageVO = GdeServiceLocator.getGestionDeudaJudicialService().agregarSelIndDeudaExcProMas(userSession, deudaExcProMasAgregarSelecIndSearchPageVO); // Tiene errores recuperables if (deudaExcProMasAgregarSelecIndSearchPageVO.hasErrorRecoverable()) { log.error("recoverable error en: " + funcName + ": " + deudaExcProMasAgregarSelecIndSearchPageVO.infoString()); saveDemodaErrors(request, deudaExcProMasAgregarSelecIndSearchPageVO); request.setAttribute(DeudaExcProMasAgregarSearchPage.NAME, deudaExcProMasAgregarSelecIndSearchPageVO); return mapping.getInputForward(); //return forwardErrorRecoverable(mapping, request, userSession, DeudaExcProMasAgregarSearchPage.NAME, deudaExcProMasAgregarSelecIndSearchPageVO); } // Tiene errores no recuperables if (deudaExcProMasAgregarSelecIndSearchPageVO.hasErrorNonRecoverable()) { log.error("error en: " + funcName + ": " + deudaExcProMasAgregarSelecIndSearchPageVO.errorString()); return forwardErrorNonRecoverable(mapping, request, funcName, DeudaExcProMasAgregarSearchPage.NAME, deudaExcProMasAgregarSelecIndSearchPageVO); } // Fue Exitoso //le seteo la accion y metodo a donde ir al navModel para que la use despues del Confirmar String actionConfirmacion = "/gde/BuscarDeudaExcProMasAgregar"; String methodConfirmacion = "buscar"; String act = ""; // no hace falta el act para el metodo buscar del action BuscarDeudaExcProMasAgregar // voName es "" para que no saque el VO de la sesion ya que se utiliza cuando vuelve return forwardConfirmarOk(mapping, request, funcName, "", actionConfirmacion , methodConfirmacion, act); } catch (Exception exception) { return baseException(mapping, request, funcName, exception, DeudaExcProMasAgregarSearchPage.NAME); } } public ActionForward volver(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // no se realiza un baseVolver para no alterar la misma instancia del SearchPage utilizado por los 2 actions return mapping.findForward(GdeConstants.FWD_BUSCAR_DEUDA_EXC_PRO_MAS_AGREGAR); } }
gpl-3.0
Danstahr/Geokuk
src/main/java/cz/geokuk/plugins/mapy/kachle/CacheNaKachleDisk.java
6044
package cz.geokuk.plugins.mapy.kachle; import java.awt.Image; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import cz.geokuk.util.exception.EExceptionSeverity; import cz.geokuk.util.exception.FExceptionDumper; import cz.geokuk.util.pocitadla.PocitadloNula; import cz.geokuk.util.pocitadla.PocitadloRoste; /** * To je keš na kachlice * * @author tatinek */ class CacheNaKachleDisk { private static final int LIMIT_POZADAVKU_VE_FRONTE_PRO_NECEKANI = 20; private static final int MAXIMALNI_VELIKOST_FRONTY_ZAPISUJICI_NA_DISK = 100000; private final PocitadloRoste pocitMinutiDiskoveKese = new PocitadloRoste("Počet minutí dlaždic v DISK cache", "Kolikrát se nepodařilo hledanou dlaždici v paměťové keši minout, co se dělo dál není tímto atributem určeno.."); private final PocitadloRoste pocitZasahDiskoveKese = new PocitadloRoste("Počet zásahů dlaždic v DISK cache", "Kolikrát se podařilo hledanou dlaždici zasáhnout na disku, tedy naloadovat. Číslo stále roste a mělo by být ve srovnání s ostatními zásahy co největší."); private final PocitadloRoste pocitZapsanoNaDisk = new PocitadloRoste("Počet zapsaných dlaždic na disk", "Kolik dlaždic bylo úspěšně zapsáno na disk asynchronním zapisovačem."); private final PocitadloNula pocitVelikostZapisoveFronty = new PocitadloNula("Veliksot fronty pro zápisdlaždic na disk", "Kolik dlaždic je ještě ve frontě a čeká na zápis na disk."); private final KachleManager km; private final BlockingQueue<DiskSaveRequest> naZapsaniNaDisk = new LinkedBlockingQueue<>( MAXIMALNI_VELIKOST_FRONTY_ZAPISUJICI_NA_DISK); private final CacheNaKachleMemory cache = new CacheNaKachleMemory(); private final KachleModel kachleModel; public CacheNaKachleDisk(KachleModel kachleModel) { this.kachleModel = kachleModel; km = KachleManagerFactory.getInstance(kachleModel.getKachleCacheFolderHolder()); } /** * Uloží obrázek do paměťové keše a nechá ho zapsat na disk. * A to i když tam už jsou. * Volající zodpovídá za to, že předaný image a dss * mají stejná data. * * @param klic * @param img * @param dss Nemusí být, pak se neukládá. */ public void putKachle(Ka0 klic, Image img, ImageSaver dss) { if (img == null) return; cache.putKachle(klic, img); if (dss != null) { DiskSaveRequest dsr = new DiskSaveRequest(klic, img, dss); try { naZapsaniNaDisk.put(dsr); } catch (InterruptedException e) { // Nevím, kdo by zabrejkoval, ale nic se nestane, když na disk nezapíšeme FExceptionDumper.dump(e, EExceptionSeverity.WORKARROUND, "Tak na disk nezapíšeme, no"); } // nebudeme blokovat, snad bude rychle zapisovat pocitVelikostZapisoveFronty.set(naZapsaniNaDisk.size()); } } public void putKachle(Ka0 klic, Image img, byte[] data) { if (img == null) return; // v offline režimu putKachle(klic, img, data == null ? null : new DiskSaveByteArray(data)); } public boolean isOnDiskOrMemory(Ka0 klic) { return memoryCachedImage(klic) != null || isOnDisk(klic); } public boolean isOnDisk(Ka0 ki) { return km.exists(ki); } public Image memoryCachedImage(Ka0 klic) { return cache.memoryCachedImage(klic); } /** * Nahraje z disku kachli a strčí ji do paměťové keše. * Pokud však už byla v paměti, s diskem se nezatěžuje. * * @param klic * @return */ public Image diskCachedImage(Ka0 klic) { Image img = cache.memoryCachedImage(klic); if (img != null) return img; if (!km.exists(klic)) { pocitMinutiDiskoveKese.inc(); return null; } img = km.load(klic); if (img != null) { pocitZasahDiskoveKese.inc(); cache.putKachle(klic, img); // do paměťové keše vždy, když se vytáhne z disku //System.out.println("Loaded from disk: " + ki); } else { pocitMinutiDiskoveKese.inc(); //System.err.println("KUKU diskCachedImage 3: " + ki); // System.out.println("Nepovedlo se naloudovat: " + ki); } return img; // samozřejmě, že se } private class DiskovyZapisovac implements Runnable { @Override public void run() { for (; ; ) { try { List<DiskSaveRequest> requests = new ArrayList<>(); naZapsaniNaDisk.drainTo(requests, MAXIMALNI_VELIKOST_FRONTY_ZAPISUJICI_NA_DISK); if (!requests.isEmpty()) { if (kachleModel.isUkladatMapyNaDisk()) { km.save(requests); } pocitZapsanoNaDisk.add(requests.size()); int size = naZapsaniNaDisk.size(); pocitVelikostZapisoveFronty.set(size); if (size < LIMIT_POZADAVKU_VE_FRONTE_PRO_NECEKANI) { // čekáme, jen když toho máme málo, abychom zbytečně nebrzdili, // pokud fronta roste, musíme ukládat. Thread.sleep(20); } } else { Thread.sleep(20); } // System.out.println("Ukládám na disk: " + dsr); } catch (Throwable e) { // vlákno nesmí spadnout // toa by ani nemelo přijít, ale jinak jedeme dál FExceptionDumper.dump(e, EExceptionSeverity.WORKARROUND, "Spadlo zapisování kachle do keše na disk"); try { Thread.sleep(200); } catch (InterruptedException e1) { // no, tak nás přerušili FExceptionDumper.dump(e1, EExceptionSeverity.WORKARROUND, "Přerušení k vláknu zapisující na disk"); } } } } } { // inicializace instance DiskovyZapisovac dz = new DiskovyZapisovac(); Thread thread = new Thread(dz, "Diskovy zapisovac"); thread.setPriority(Thread.NORM_PRIORITY - 1); thread.setDaemon(true); thread.start(); } public void clearMemoryCache() { cache.clearMemoryCache(); } }
gpl-3.0
zpxocivuby/freetong_mobile
ItafMobileApp/src/itaf/mobile/app/task/netreader/DistOrderPagerTask.java
1733
package itaf.mobile.app.task.netreader; import itaf.framework.base.dto.WsPageResult; import itaf.framework.merchant.dto.BzDistOrderDto; import itaf.mobile.app.task.ReaderTask; import itaf.mobile.app.task.Task; import itaf.mobile.app.task.TaskIds; import itaf.mobile.core.base.BaseActivity; import itaf.mobile.ds.ws.merchant.WsDistOrderClient; import java.util.HashMap; import java.util.Map; /** * 订单列表任务 * * @author * */ public class DistOrderPagerTask extends ReaderTask { public static final String TP_KEY_BZ_DIST_COMPANY_ID = "bzDistCompanyId"; public static final String TP_KEY_BZ_MERCHANT_ID = "bzMerchantId"; public static final String TP_KEY_COMPANY_NAME = "companyName"; public static final String TP_KEY_ORDER_STATUS = "orderStatus"; public static final String TP_KEY_ORDER_TYPE = "orderType"; public static final String TP_QUERY_MAP = "queryMap"; public static final String TP_CURRENT_INDEX = "currentIndex"; public static final String TP_PAGE_SIZE = "pageSize"; private WsDistOrderClient client = new WsDistOrderClient(); public DistOrderPagerTask(BaseActivity activity, Map<String, Object> map) { super(activity, getTaskId(), map); } public static int getTaskId() { return TaskIds.TASK_ORDER_PAGER; } @SuppressWarnings("unchecked") @Override public void loadMsgObj() { HashMap<String, Object> queryMap = (HashMap<String, Object>) this .getParams().get(TP_QUERY_MAP); int currentIndex = (Integer) this.getParams().get(TP_CURRENT_INDEX); int pageSize = (Integer) this.getParams().get(TP_PAGE_SIZE); WsPageResult<BzDistOrderDto> result = client.findPager(queryMap, currentIndex, pageSize); this.setMsgObj(result); this.setState(Task.State.COMPLETED); } }
gpl-3.0
AbuDhabi/StarSys
src/starsys/model/Star.java
1920
/* * Copyright (C) 2017 abudhabi * * 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 starsys.model; import starsys.util.SpectralClass; import java.awt.Color; import java.awt.geom.Point2D; import java.util.List; import starsys.util.Constants; /** * * @author abudhabi */ public class Star extends MassiveBody { private final SpectralClass spectralClass; public Star(SpectralClass spectralClass, double tilt, double rotationVelocity, double mass, double radius, double temperature, double albedo, Color color, long id, String name, double cachedTime, int offset, Point2D.Double center, OrbitalPoint parent, List<OrbitalPoint> children, double semiMajorAxis, double angularVelocity, double eccentricity, double inclination) { super(tilt, rotationVelocity, mass, radius, temperature, albedo, color, id, name, cachedTime, offset, center, parent, children, semiMajorAxis, angularVelocity, eccentricity, inclination); this.spectralClass = spectralClass; } // In joules per day. public double getLuminosity() { return 4*Math.PI*Math.pow(radius, 2) * Constants.STEFAN_BOLTZMAN_CONSTANT * Math.pow(temperature, 4); } /** * @return the spectralClass */ public SpectralClass getSpectralClass() { return spectralClass; } }
gpl-3.0
CDMirel/Executer
src/de/toth/executer/browser/FileListAdapter.java
3577
/* Executer Copyright (C) 2012 Alfred Toth 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.toth.executer.browser; import java.io.File; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import de.toth.executer.R; import de.toth.executer.data.FileData; import de.toth.executer.utils.FileUtils; public class FileListAdapter extends BaseAdapter { private Context context = null; private ArrayList<FileData> files = new ArrayList<FileData>(); private LayoutInflater inflater; // private Integer filenameColor = null; public FileListAdapter(Context c) { this.context = c; this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // this.filenameColor = this.context.getResources().getColor(R.color.filename); } public int getCount() { return this.files.size(); } public Object getItem(int position) { return this.files.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = this.inflater.inflate(R.layout.listitem, parent, false); } // hole die Daten der Datei/Verzeichnis zur Position FileData fileData = this.files.get(position); File file = fileData.file; // setze Bild ImageView image = (ImageView) convertView.findViewById(R.id.listItemImage); if (fileData.drawable == -1) { if (file.isFile() == true) { if(file.getName().endsWith(".sh")) { image.setImageResource(R.drawable.script); } else { image.setImageResource(R.drawable.file); } } else { image.setImageResource(R.drawable.folder); } } else { image.setImageResource(fileData.drawable); } // setze Name der Datei/des Verzeichnisses TextView name = (TextView) convertView.findViewById(R.id.listItemName); if(fileData.alias == null) { name.setText(file.getName()); } else { name.setText(fileData.alias); } // if(file.exists() == false) { // name.setTextColor(Color.RED); // } // else { // name.setTextColor(this.filenameColor); // } // setze Beschreibung TextView descr = (TextView) convertView.findViewById(R.id.listItemDescr); if (fileData.descr != null && fileData.descr.length() > 0) { descr.setText(fileData.descr); } else { if (file.isFile() == true) { String temp = FileUtils.toHumanReadable(file.length()); fileData.descr = temp; descr.setText(temp); } else { descr.setText(""); } } convertView.setTag(position); // convertView.setOnClickListener((OnClickListener)parent.getContext()); return convertView; } public void addFile(FileData fileData) { this.files.add(fileData); } public void clear() { this.files.clear(); } }
gpl-3.0
241180/Oryx
dashboard-demo-8.0/src/main/java/com/vaadin/demo/dashboard/view/transactions/TransactionsView.java
9040
package com.vaadin.demo.dashboard.view.transactions; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.Set; import java.util.stream.Collectors; import com.google.common.eventbus.Subscribe; import com.vaadin.data.provider.ListDataProvider; import com.vaadin.demo.dashboard.DashboardUI; import com.vaadin.demo.dashboard.domain.Transaction; import com.vaadin.demo.dashboard.event.DashboardEvent.BrowserResizeEvent; import com.vaadin.demo.dashboard.event.DashboardEvent.TransactionReportEvent; import com.vaadin.demo.dashboard.event.DashboardEventBus; import com.vaadin.demo.dashboard.view.DashboardViewType; import com.vaadin.event.ShortcutAction.KeyCode; import com.vaadin.event.ShortcutListener; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.server.FontAwesome; import com.vaadin.server.Page; import com.vaadin.server.Responsive; import com.vaadin.ui.Button; import com.vaadin.ui.Component; import com.vaadin.ui.Grid; import com.vaadin.ui.Grid.Column; import com.vaadin.ui.Grid.SelectionMode; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.SingleSelect; import com.vaadin.ui.TextField; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.renderers.NumberRenderer; import com.vaadin.ui.themes.ValoTheme; @SuppressWarnings("serial") public final class TransactionsView extends VerticalLayout implements View { private final Grid<Transaction> grid; private SingleSelect<Transaction> singleSelect; private Button createReport; private String filterValue = ""; private static final DateFormat DATEFORMAT = new SimpleDateFormat( "MM/dd/yyyy hh:mm:ss a"); private static final DecimalFormat DECIMALFORMAT = new DecimalFormat( "#.##"); private static final Set<Column<Transaction, ?>> collapsibleColumns = new LinkedHashSet<>(); public TransactionsView() { setSizeFull(); addStyleName("transactions"); setMargin(false); setSpacing(false); DashboardEventBus.register(this); addComponent(buildToolbar()); grid = buildGrid(); singleSelect = grid.asSingleSelect(); addComponent(grid); setExpandRatio(grid, 1); } @Override public void detach() { super.detach(); // A new instance of TransactionsView is created every time it's // navigated to so we'll need to clean up references to it on detach. DashboardEventBus.unregister(this); } private Component buildToolbar() { HorizontalLayout header = new HorizontalLayout(); header.addStyleName("viewheader"); Responsive.makeResponsive(header); Label title = new Label("Latest Transactions"); title.setSizeUndefined(); title.addStyleName(ValoTheme.LABEL_H1); title.addStyleName(ValoTheme.LABEL_NO_MARGIN); header.addComponent(title); createReport = buildCreateReport(); HorizontalLayout tools = new HorizontalLayout(buildFilter(), createReport); tools.addStyleName("toolbar"); header.addComponent(tools); return header; } private Button buildCreateReport() { final Button createReport = new Button("Create Report"); createReport.setDescription( "Create a new report from the selected transactions"); createReport.addClickListener(event -> createNewReportFromSelection()); createReport.setEnabled(false); return createReport; } private Component buildFilter() { final TextField filter = new TextField(); // TODO use new filtering API filter.addValueChangeListener(event -> { Collection<Transaction> transactions = DashboardUI.getDataProvider() .getRecentTransactions(200).stream().filter(transaction -> { filterValue = filter.getValue().trim().toLowerCase(); return passesFilter(transaction.getCountry()) || passesFilter(transaction.getTitle()) || passesFilter(transaction.getCity()); }).collect(Collectors.toList()); ListDataProvider<Transaction> dataProvider = com.vaadin.data.provider.DataProvider .ofCollection(transactions); dataProvider.addSortComparator(Comparator .comparing(Transaction::getTime).reversed()::compare); grid.setDataProvider(dataProvider); }); filter.setPlaceholder("Filter"); filter.setIcon(FontAwesome.SEARCH); filter.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON); filter.addShortcutListener( new ShortcutListener("Clear", KeyCode.ESCAPE, null) { @Override public void handleAction(final Object sender, final Object target) { filter.setValue(""); } }); return filter; } private Grid<Transaction> buildGrid() { final Grid<Transaction> grid = new Grid<>(); grid.setSelectionMode(SelectionMode.SINGLE); grid.setSizeFull(); Column<Transaction, String> time = grid.addColumn( transaction -> DATEFORMAT.format(transaction.getTime())); time.setId("Time").setHidable(true); collapsibleColumns .add(grid.addColumn(Transaction::getCountry).setId("Country")); collapsibleColumns .add(grid.addColumn(Transaction::getCity).setId("City")); collapsibleColumns .add(grid.addColumn(Transaction::getTheater).setId("Theater")); collapsibleColumns .add(grid.addColumn(Transaction::getRoom).setId("Room")); collapsibleColumns .add(grid.addColumn(Transaction::getRoom).setId("Title")); collapsibleColumns .add(grid.addColumn(Transaction::getSeats, new NumberRenderer()) .setId("Seats")); grid.addColumn(transaction -> "$" + DECIMALFORMAT.format(transaction.getPrice())).setId("Price") .setHidable(true); grid.setColumnReorderingAllowed(true); ListDataProvider<Transaction> dataProvider = com.vaadin.data.provider.DataProvider .ofCollection(DashboardUI.getDataProvider() .getRecentTransactions(200)); dataProvider.addSortComparator( Comparator.comparing(Transaction::getTime).reversed()::compare); grid.setDataProvider(dataProvider); // TODO either add these to grid or do it with style generators here // grid.setColumnAlignment("seats", Align.RIGHT); // grid.setColumnAlignment("price", Align.RIGHT); // TODO add when footers implemented in v8 // grid.setFooterVisible(true); // grid.setColumnFooter("time", "Total"); // grid.setColumnFooter("price", "$" + DECIMALFORMAT // .format(DashboardUI.getDataProvider().getTotalSum())); // TODO add this functionality to grid? // grid.addActionHandler(new TransactionsActionHandler()); grid.addSelectionListener( event -> createReport.setEnabled(!singleSelect.isEmpty())); return grid; } private boolean defaultColumnsVisible() { boolean result = true; for (Column<Transaction, ?> column : collapsibleColumns) { if (column.isHidden() == Page.getCurrent() .getBrowserWindowWidth() < 800) { result = false; } } return result; } @Subscribe public void browserResized(final BrowserResizeEvent event) { // Some columns are collapsed when browser window width gets small // enough to make the table fit better. if (defaultColumnsVisible()) { for (Column<Transaction, ?> column : collapsibleColumns) { column.setHidden( Page.getCurrent().getBrowserWindowWidth() < 800); } } } void createNewReportFromSelection() { if (!singleSelect.isEmpty()) { UI.getCurrent().getNavigator() .navigateTo(DashboardViewType.REPORTS.getViewName()); DashboardEventBus.post(new TransactionReportEvent( Collections.singletonList(singleSelect.getValue()))); } } private boolean passesFilter(String subject) { if (subject == null) { return false; } return subject.trim().toLowerCase().contains(filterValue); } @Override public void enter(final ViewChangeEvent event) { } }
gpl-3.0
arVahedi/JavaTelegramBotAPI
src/main/java/telegram/bot/api/requestobject/RequestGetUserProfilePhotos.java
991
package telegram.bot.api.requestobject; import telegram.bot.api.entity.User; /** * Created by Gladiator on 2/5/2016 AD. */ public class RequestGetUserProfilePhotos { //region Fields private User user; private int offset; private int limit; //endregion //region Constructor public RequestGetUserProfilePhotos() { } public RequestGetUserProfilePhotos(User user) { this.user = user; } public RequestGetUserProfilePhotos(int userId) { this.user = new User(userId); } //endregion //region Getter and Setter public User getUser() { return user; } public void setUser(User user) { this.user = user; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } //endregion }
gpl-3.0
TheLanguageArchive/ASV
metadata-browser-pages/src/test/java/nl/mpi/metadatabrowser/services/mock/MockNodePresentationProvider.java
1474
/* * Copyright (C) 2013 Max Planck Institute for Psycholinguistics * * 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 nl.mpi.metadatabrowser.services.mock; import java.util.Collection; import nl.mpi.metadatabrowser.model.TypedCorpusNode; import nl.mpi.metadatabrowser.services.NodePresentationProvider; import org.apache.wicket.Component; import org.apache.wicket.markup.html.basic.Label; /** * * @author Twan Goosen <twan.goosen@mpi.nl> */ public class MockNodePresentationProvider implements NodePresentationProvider { @Override public Component getNodePresentation(String wicketId, Collection<TypedCorpusNode> nodes) { if (nodes.isEmpty()) { return null; } else { final TypedCorpusNode node = nodes.iterator().next(); return new Label(wicketId, String.format("[%s] %s", node.getNodeType().getName(), node.getName())); } } }
gpl-3.0
shoopi/get-controller
src/main/java/nl/tue/ieis/get/activiti/service/DynamicAdaptationRequest.java
1345
package main.java.nl.tue.ieis.get.activiti.service; import org.activiti.rest.service.api.RestActionRequest; public class DynamicAdaptationRequest extends RestActionRequest { private String oldCase; private String newProcessId; private String route; private String sourceAddress; private String destAddress; private String sourceDate; private String destDate; public String getOldCase() { return oldCase; } public void setOldCase(String oldCase) { this.oldCase = oldCase; } public String getNewProcessId() { return newProcessId; } public void setNewProcessId(String newProcessId) { this.newProcessId = newProcessId; } public String getRoute() { return route; } public void setRoute(String route) { this.route = route; } public String getSourceAddress() { return sourceAddress; } public void setSourceAddress(String sourceAddress) { this.sourceAddress = sourceAddress; } public String getDestAddress() { return destAddress; } public void setDestAddress(String destAddress) { this.destAddress = destAddress; } public String getSourceDate() { return sourceDate; } public void setSourceDate(String sourceDate) { this.sourceDate = sourceDate; } public String getDestDate() { return destDate; } public void setDestDate(String destDate) { this.destDate = destDate; } }
gpl-3.0
Naoghuman/Dream-Better-Worlds
DBW-Feature-Voting-Impl/src/main/java/de/pro/dbw/feature/voting/impl/votingchooser/VotingChooserPresenter.java
1375
/* * Copyright (C) 2015 Dream Better Worlds * * 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.pro.dbw.feature.voting.impl.votingchooser; import de.pro.lib.logger.api.LoggerFacade; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.Initializable; /** * * @author PRo */ public class VotingChooserPresenter implements Initializable { // @FXML private Button bNo; @Override public void initialize(URL location, ResourceBundle resources) { LoggerFacade.INSTANCE.info(this.getClass(), "Initialize VotingChooserPresenter"); // assert (bNo != null) : "fx:id=\"bNo\" was not injected: check your FXML file 'DeleteDialog.fxml'."; // NOI18N } }
gpl-3.0