code
stringlengths
3
1.04M
repo_name
stringlengths
5
109
path
stringlengths
6
306
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.04M
/* No-Babylon a job search engine with filtering ability Copyright (C) 2012-2014 ferenc.jdev@gmail.com This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ package org.laatusys.nobabylon.support; import java.util.regex.Pattern; public class ExcludeRegexpFilter implements Filter { private final Pattern pattern; public ExcludeRegexpFilter(String regexp, boolean caseSensitive) { pattern = caseSensitive ? Pattern.compile(regexp) : Pattern.compile(regexp, Pattern.CASE_INSENSITIVE); } public ExcludeRegexpFilter(String regexp) { this(regexp, false); } @Override public boolean accept(String description) { return !pattern.matcher(description).find(); } }
ferenc-jdev/no-babylon
src/main/java/org/laatusys/nobabylon/support/ExcludeRegexpFilter.java
Java
gpl-3.0
1,328
package com.sk89q.craftbook.cart; import java.util.ArrayList; import java.util.Arrays; import org.bukkit.block.Chest; import org.bukkit.block.Sign; import org.bukkit.entity.Minecart; import org.bukkit.entity.StorageMinecart; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import com.sk89q.craftbook.util.RailUtil; import com.sk89q.craftbook.util.RedstoneUtil.Power; import com.sk89q.craftbook.util.RegexUtil; public class CartDeposit extends CartMechanism { @Override public void impact(Minecart cart, CartMechanismBlocks blocks, boolean minor) { // validate if (cart == null) return; // care? if (minor) return; if (!(cart instanceof StorageMinecart)) return; Inventory cartinventory = ((StorageMinecart) cart).getInventory(); // enabled? if (Power.OFF == isActive(blocks.rail, blocks.base, blocks.sign)) return; // collect/deposit set? if (blocks.sign == null) return; if (!blocks.matches("collect") && !blocks.matches("deposit")) return; boolean collecting = blocks.matches("collect"); // search for containers ArrayList<Chest> containers = RailUtil.getNearbyChests(blocks.base); // are there any containers? if (containers.isEmpty()) return; // go ArrayList<ItemStack> leftovers = new ArrayList<ItemStack>(); int itemID = -1; byte itemData = -1; try { String[] splitLine = RegexUtil.COLON_PATTERN.split(((Sign) blocks.sign.getState()).getLine(2)); itemID = Integer.parseInt(splitLine[0]); itemData = Byte.parseByte(splitLine[1]); } catch (Exception ignored) { } if (collecting) { // collecting ArrayList<ItemStack> transferItems = new ArrayList<ItemStack>(); if (!((Sign) blocks.sign.getState()).getLine(2).isEmpty()) { for (ItemStack item : cartinventory.getContents()) { if (item == null) { continue; } if (itemID < 0 || itemID == item.getTypeId()) { if (itemData < 0 || itemData == item.getDurability()) { transferItems.add(new ItemStack(item.getTypeId(), item.getAmount(), item.getDurability())); cartinventory.remove(item); } } } } else { transferItems.addAll(Arrays.asList(cartinventory.getContents())); cartinventory.clear(); } while (transferItems.remove(null)) { } // is cart non-empty? if (transferItems.isEmpty()) return; // System.out.println("collecting " + transferItems.size() + " item stacks"); // for (ItemStack stack: transferItems) System.out.println("collecting " + stack.getAmount() + " items of // type " + stack.getType().toString()); for (Chest container : containers) { if (transferItems.isEmpty()) { break; } Inventory containerinventory = container.getInventory(); leftovers.addAll(containerinventory.addItem(transferItems.toArray(new ItemStack[transferItems.size() ])).values()); transferItems.clear(); transferItems.addAll(leftovers); leftovers.clear(); container.update(); } // System.out.println("collected items. " + transferItems.size() + " stacks left over."); leftovers.addAll(cartinventory.addItem(transferItems.toArray(new ItemStack[transferItems.size()])).values ()); transferItems.clear(); transferItems.addAll(leftovers); leftovers.clear(); // System.out.println("collection done. " + transferItems.size() + " stacks wouldn't fit back."); } else { // depositing ArrayList<ItemStack> transferitems = new ArrayList<ItemStack>(); for (Chest container : containers) { Inventory containerinventory = container.getInventory(); if (!((Sign) blocks.sign.getState()).getLine(2).isEmpty()) { for (ItemStack item : containerinventory.getContents()) { if (item == null) { continue; } if (itemID < 0 || itemID == item.getTypeId()) if (itemData < 0 || itemData == item.getDurability()) { transferitems.add(new ItemStack(item.getTypeId(), item.getAmount(), item.getDurability())); containerinventory.remove(item); } } } else { transferitems.addAll(Arrays.asList(containerinventory.getContents())); containerinventory.clear(); } container.update(); } while (transferitems.remove(null)) { } // are chests empty? if (transferitems.isEmpty()) return; // System.out.println("depositing " + transferitems.size() + " stacks"); // for (ItemStack stack: transferitems) System.out.println("depositing " + stack.getAmount() + " items of // type " + stack.getType().toString()); leftovers.addAll(cartinventory.addItem(transferitems.toArray(new ItemStack[transferitems.size()])).values ()); transferitems.clear(); transferitems.addAll(leftovers); leftovers.clear(); // System.out.println("deposited, " + transferitems.size() + " items left over."); for (Chest container : containers) { if (transferitems.isEmpty()) { break; } Inventory containerinventory = container.getInventory(); leftovers.addAll(containerinventory.addItem(transferitems.toArray(new ItemStack[transferitems.size() ])).values()); transferitems.clear(); transferitems.addAll(leftovers); leftovers.clear(); } // System.out.println("deposit done. " + transferitems.size() + " items wouldn't fit back."); } } @Override public String getName() { return "Deposit"; } @Override public String[] getApplicableSigns() { return new String[] {"Collect", "Deposit"}; } }
wizjany/craftbook
src/main/java/com/sk89q/craftbook/cart/CartDeposit.java
Java
gpl-3.0
7,011
/* * This file is part of CRISIS, an economics simulator. * * Copyright (C) 2015 Victor Spirin * * CRISIS 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. * * CRISIS 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 CRISIS. If not, see <http://www.gnu.org/licenses/>. */ package eu.crisis_economics.abm.markets.nonclearing; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import eu.crisis_economics.abm.markets.Party; import eu.crisis_economics.abm.markets.nonclearing.DefaultFilters.Filter; /** * Represents relationships between banks in the interbank market * * @author Victor Spirin */ public class InterbankNetwork { private final Map<Party, Set<Party>> adj = new HashMap<Party, Set<Party>>(); /** * Adds a new node to the graph. If the node already exists, this * function is a no-op. * * @param node The node to add. * @return Whether or not the node was added. */ private boolean addNode(Party node) { /* If the node already exists, don't do anything. */ if (adj.containsKey(node)) return false; /* Otherwise, add the node with an empty set of outgoing edges. */ adj.put(node, new HashSet<Party>()); return true; } // protected /** * Generates a filter from the network. This allows the network class to be used * with a Limit Order Book. * * @param a Bank, for which we want to generate a filter * @return Returns a Limit Order Book filter for the given bank. If the bank is not in the network, returns an empty filter. */ protected Filter generateFilter(Party party) { if (!adj.containsKey(party)) return DefaultFilters.only(party); return DefaultFilters.only((Party[]) adj.get(party).toArray()); } // public interface /** * Adds a bilateral relationship between banks 'a' and 'b'. * If the banks are not already in the network, also adds them to the network. * * @param a Bank a * @param b Bank b */ public void addRelationship(Party a, Party b) { /* Confirm both endpoints exist. */ if (!adj.containsKey(a)) addNode(a); if (!adj.containsKey(b)) addNode(b); /* Add the edge in both directions. */ adj.get(a).add(b); adj.get(b).add(a); } /** * Removes a bilateral relationship between banks 'a' and 'b'. * If the banks are not already in the network, throws a NoSuchElementException * * @param a Bank a * @param b Bank b */ public void removeRelationship(Party a, Party b) { /* Confirm both endpoints exist. */ if (!adj.containsKey(a) || !adj.containsKey(b)) throw new NoSuchElementException("Both banks must be in the network."); /* Remove the edges from both adjacency lists. */ adj.get(a).remove(b); adj.get(b).remove(a); } /** * Returns true if there is a bilateral relationship between banks 'a' and 'b'. * If the banks are not already in the network, throws a NoSuchElementException * * @param a Bank a * @param b Bank b * @return Returns true if there is a relationship between banks 'a' and 'b' */ public boolean isRelated(Party a, Party b) { /* Confirm both endpoints exist. */ if (!adj.containsKey(a) || !adj.containsKey(b)) throw new NoSuchElementException("Both banks must be in the network."); /* Network is symmetric, so we can just check either endpoint. */ return adj.get(a).contains(b); } }
crisis-economics/CRISIS
CRISIS/src/eu/crisis_economics/abm/markets/nonclearing/InterbankNetwork.java
Java
gpl-3.0
4,215
/** * */ /** * @author dewan * */ package gradingTools.comp401f16.assignment11.testcases;
pdewan/Comp401LocalChecks
src/gradingTools/comp401f16/assignment11/testcases/package-info.java
Java
gpl-3.0
95
package mcid.anubisset.letsmodreboot.block; import mcid.anubisset.letsmodreboot.creativetab.CreativeTabLMRB; /** * Created by Luke on 30/08/2014. */ public class BlockFlag extends BlockLMRB { public BlockFlag() { super(); this.setBlockName("flag"); this.setBlockTextureName("flag"); } }
AnubisSet/LetsModReboot
src/main/java/mcid/anubisset/letsmodreboot/block/BlockFlag.java
Java
gpl-3.0
327
package tmp.generated_people; import cide.gast.*; import cide.gparser.*; import cide.greferences.*; import java.util.*; public abstract class Element_ol extends GenASTNode { protected Element_ol(Property[] p, Token firstToken, Token lastToken) { super(p, firstToken, lastToken); } protected Element_ol(Property[] p, IToken firstToken, IToken lastToken) { super(p, firstToken, lastToken); } }
ckaestne/CIDE
CIDE_Language_XML_concrete/src/tmp/generated_people/Element_ol.java
Java
gpl-3.0
404
/******************************************************************************* * Copyright (c) 2008, 2010 Xuggle Inc. All rights reserved. * * This file is part of Xuggle-Utils. * * Xuggle-Utils 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. * * Xuggle-Utils 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 Xuggle-Utils. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ /** * Provides convenience methods for registering, and * special implementations of, * {@link com.xuggle.utils.event.IEventHandler}. * <p> * There are certain types of {@link com.xuggle.utils.event.IEventHandler} * implementations that are very common. For example, sometimes * you want to forward an event from one * {@link com.xuggle.utils.event.IEventDispatcher} * to another. * Sometimes you only want * a {@link com.xuggle.utils.event.IEventHandler} to execute if the * {@link com.xuggle.utils.event.IEvent#getSource()} is equal to * a given source. * Sometimes you only * want to handler to execute a maximum number of times. * </p> * <p> * This class tries to provide some of those implementations for you. * </p> * <p> * Use the {@link com.xuggle.utils.event.handler.Handler} class to find * Factory methods for the special handlers you want. * </p> * @see com.xuggle.utils.event.handler.Handler * */ package com.xuggle.utils.event.handler;
artclarke/xuggle-utils
src/main/java/com/xuggle/utils/event/handler/package-info.java
Java
gpl-3.0
1,917
/* * _____ _ _ _____ _ * | __ \| | | | / ____| | | * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| * | | * |_| * PlotSquared plot management system for Minecraft * Copyright (C) 2021 IntellectualSites * * 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 <https://www.gnu.org/licenses/>. */ package com.plotsquared.core.command; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.util.task.RunnableVal2; import com.plotsquared.core.util.task.RunnableVal3; import java.util.concurrent.CompletableFuture; /** * SubCommand class * * @see Command#Command(Command, boolean) * @deprecated In favor of normal Command class */ public abstract class SubCommand extends Command { public SubCommand() { super(MainCommand.getInstance(), true); } public SubCommand(Argument<?>... arguments) { this(); setRequiredArguments(arguments); } @Override public CompletableFuture<Boolean> execute( PlotPlayer<?> player, String[] args, RunnableVal3<Command, Runnable, Runnable> confirm, RunnableVal2<Command, CommandResult> whenDone ) { return CompletableFuture.completedFuture(onCommand(player, args)); } public abstract boolean onCommand(PlotPlayer<?> player, String[] args); }
IntellectualCrafters/PlotSquared
Core/src/main/java/com/plotsquared/core/command/SubCommand.java
Java
gpl-3.0
2,321
package com.cloudera.cmf.service.yarn; import com.cloudera.cmf.command.flow.CmdWorkCtx; import com.cloudera.cmf.command.flow.WorkOutput; import com.cloudera.cmf.command.flow.work.OneOffRoleProcCmdWork; import com.cloudera.cmf.model.DbProcess; import com.cloudera.cmf.model.DbRole; import com.cloudera.cmf.model.RoleState; import com.cloudera.cmf.service.ServiceDataProvider; import com.cloudera.cmf.service.components.ProcessHelper; import com.cloudera.enterprise.MessageWithArgs; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.util.List; public class RmFormatStateStoreCmdWork extends OneOffRoleProcCmdWork { private RmFormatStateStoreCmdWork(@JsonProperty("roleId") Long roleId) { super(roleId); } public MessageWithArgs getDescription(CmdWorkCtx ctx) { return MessageWithArgs.of("message.command.rmFormatStateStoreCmdWork.desc", new String[0]); } public String getProcessName() { return "rm-format-state-store"; } protected void beforeProcessCreation(CmdWorkCtx ctx, DbProcess proc, DbRole role) { ctx.getServiceDataProvider().getProcessHelper().runAsRole(proc, role); List args = ImmutableList.of("resourcemanager", "-format-state-store"); proc.setProgram("yarn/yarn.sh"); proc.setArguments(args); } protected RoleState getRoleStateAfterProcess(WorkOutput output, CmdWorkCtx ctx) { return RoleState.STOPPED; } public static RmFormatStateStoreCmdWork of(DbRole r) { Preconditions.checkNotNull(r); Preconditions.checkNotNull(r.getId()); Preconditions.checkArgument(YarnServiceHandler.RoleNames.RESOURCEMANAGER.name().equals(r.getRoleType())); return new RmFormatStateStoreCmdWork(r.getId()); } }
Mapleroid/cm-server
server-5.11.0.src/com/cloudera/cmf/service/yarn/RmFormatStateStoreCmdWork.java
Java
gpl-3.0
1,852
package com.github.sandokandias.payments.interfaces.rest.model; import com.github.sandokandias.payments.infrastructure.util.i18n.I18nMessage; import lombok.Data; import java.util.Set; @Data public class ErrorResponse { private Set<I18nMessage> errors; }
sandokandias/spring-boot-ddd
src/main/java/com/github/sandokandias/payments/interfaces/rest/model/ErrorResponse.java
Java
gpl-3.0
262
package pt.uminho.sysbio.biosynthframework.integration.model; import pt.uminho.sysbio.biosynth.integration.io.dao.neo4j.MetaboliteMajorLabel; public interface IntegrationEngine { public IntegrationMap<String, MetaboliteMajorLabel> integrate(IntegrationMap<String, MetaboliteMajorLabel> imap); }
Fxe/biosynth-framework
biosynth-integration/src/main/java/pt/uminho/sysbio/biosynthframework/integration/model/IntegrationEngine.java
Java
gpl-3.0
299
package vrml.external.field; import vrml.external.field.FieldTypes; import vrml.external.Browser; import java.awt.*; import java.math.BigInteger; public class EventInSFImage extends EventIn { public EventInSFImage() { EventType = FieldTypes.SFIMAGE; } public void setValue(int width, int height, int components, byte[] pixels) throws IllegalArgumentException { int count; int pixcount; String val; BigInteger newval; byte xx[]; if (pixels.length != (width*height*components)) { throw new IllegalArgumentException(); } if ((components < 1) || (components > 4)) { throw new IllegalArgumentException(); } // use BigInt to ensure sign bit does not frick us up. xx = new byte[components+1]; xx[0] = (byte) 0; // no sign bit here! val = new String("" + width + " " + height + " " + components); if (pixels== null) { pixcount = 0;} else {pixcount=pixels.length;} if (components == 1) { for (count = 0; count < pixcount; count++) { xx[1] = pixels[count]; newval = new BigInteger(xx); //System.out.println ("Big int " + newval.toString(16)); val = val.concat(" 0x" + newval.toString(16)); } } if (components == 2) { for (count = 0; count < pixcount; count+=2) { xx[1] = pixels[count]; xx[2] = pixels[count+1]; newval = new BigInteger(xx); //System.out.println ("Big int " + newval.toString(16)); val = val.concat(" 0x" + newval.toString(16)); } } if (components == 3) { for (count = 0; count < pixcount; count+=3) { xx[1] = pixels[count]; xx[2] = pixels[count+1]; xx[3]=pixels[count+2]; newval = new BigInteger(xx); //System.out.println ("Big int " + newval.toString(16)); val = val.concat(" 0x" + newval.toString(16)); } } if (components == 4) { for (count = 0; count < pixcount; count+=4) { xx[1] = pixels[count]; xx[2] = pixels[count+1]; xx[3]=pixels[count+2]; xx[4]=pixels[count+3]; newval = new BigInteger(xx); //System.out.println ("Big int " + newval.toString(16)); val = val.concat(" 0x" + newval.toString(16)); } } //System.out.println ("sending " + val); Browser.newSendEvent (this, val.length() + ":" + val + " "); return; } }
cbuehler/freewrl
src/java/vrml/external/field/EventInSFImage.java
Java
gpl-3.0
2,162
/* * AJDebug.java * * This file is part of Tritonus: http://www.tritonus.org/ */ /* * Copyright (c) 1999 - 2002 by Matthias Pfisterer * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* |<--- this code is formatted to fit into 80 columns --->| */ package org.tritonus.debug; import org.aspectj.lang.JoinPoint; import javax.sound.midi.MidiSystem; import javax.sound.midi.Synthesizer; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.SourceDataLine; import org.tritonus.core.TMidiConfig; import org.tritonus.core.TInit; import org.tritonus.share.TDebug; import org.tritonus.share.midi.TSequencer; import org.tritonus.midi.device.alsa.AlsaSequencer; import org.tritonus.midi.device.alsa.AlsaSequencer.PlaybackAlsaMidiInListener; import org.tritonus.midi.device.alsa.AlsaSequencer.RecordingAlsaMidiInListener; import org.tritonus.midi.device.alsa.AlsaSequencer.AlsaSequencerReceiver; import org.tritonus.midi.device.alsa.AlsaSequencer.AlsaSequencerTransmitter; import org.tritonus.midi.device.alsa.AlsaSequencer.LoaderThread; import org.tritonus.midi.device.alsa.AlsaSequencer.MasterSynchronizer; import org.tritonus.share.sampled.convert.TAsynchronousFilteredAudioInputStream; /** Debugging output aspect. */ public aspect AJDebug extends Utils { pointcut allExceptions(): handler(Throwable+); // TAudioConfig, TMidiConfig, TInit pointcut TMidiConfigCalls(): execution(* TMidiConfig.*(..)); pointcut TInitCalls(): execution(* TInit.*(..)); // share // midi pointcut MidiSystemCalls(): execution(* MidiSystem.*(..)); pointcut Sequencer(): execution(TSequencer+.new(..)) || execution(* TSequencer+.*(..)) || execution(* PlaybackAlsaMidiInListener.*(..)) || execution(* RecordingAlsaMidiInListener.*(..)) || execution(* AlsaSequencerReceiver.*(..)) || execution(* AlsaSequencerTransmitter.*(..)) || execution(LoaderThread.new(..)) || execution(* LoaderThread.*(..)) || execution(MasterSynchronizer.new(..)) || execution(* MasterSynchronizer.*(..)); // audio pointcut AudioSystemCalls(): execution(* AudioSystem.*(..)); pointcut sourceDataLine(): call(* SourceDataLine+.*(..)); // OLD // pointcut playerStates(): // execution(private void TPlayer.setState(int)); // currently not used pointcut printVelocity(): execution(* JavaSoundToneGenerator.playTone(..)) && call(JavaSoundToneGenerator.ToneThread.new(..)); // pointcut tracedCall(): execution(protected void JavaSoundAudioPlayer.doRealize() throws Exception); /////////////////////////////////////////////////////// // // ACTIONS // /////////////////////////////////////////////////////// before(): MidiSystemCalls() { if (TDebug.TraceMidiSystem) outEnteringJoinPoint(thisJoinPoint); } after(): MidiSystemCalls() { if (TDebug.TraceSequencer) outLeavingJoinPoint(thisJoinPoint); } before(): Sequencer() { if (TDebug.TraceSequencer) outEnteringJoinPoint(thisJoinPoint); } after(): Sequencer() { if (TDebug.TraceSequencer) outLeavingJoinPoint(thisJoinPoint); } before(): TInitCalls() { if (TDebug.TraceInit) outEnteringJoinPoint(thisJoinPoint); } after(): TInitCalls() { if (TDebug.TraceInit) outLeavingJoinPoint(thisJoinPoint); } before(): TMidiConfigCalls() { if (TDebug.TraceMidiConfig) outEnteringJoinPoint(thisJoinPoint); } after(): TMidiConfigCalls() { if (TDebug.TraceMidiConfig) outLeavingJoinPoint(thisJoinPoint); } // execution(* TAsynchronousFilteredAudioInputStream.read(..)) before(): execution(* TAsynchronousFilteredAudioInputStream.read()) { if (TDebug.TraceAudioConverter) outEnteringJoinPoint(thisJoinPoint); } after(): execution(* TAsynchronousFilteredAudioInputStream.read()) { if (TDebug.TraceAudioConverter) outLeavingJoinPoint(thisJoinPoint); } before(): execution(* TAsynchronousFilteredAudioInputStream.read(byte[])) { if (TDebug.TraceAudioConverter) outEnteringJoinPoint(thisJoinPoint); } after(): execution(* TAsynchronousFilteredAudioInputStream.read(byte[])) { if (TDebug.TraceAudioConverter) outLeavingJoinPoint(thisJoinPoint); } before(): execution(* TAsynchronousFilteredAudioInputStream.read(byte[], int, int)) { if (TDebug.TraceAudioConverter) outEnteringJoinPoint(thisJoinPoint); } after(): execution(* TAsynchronousFilteredAudioInputStream.read(byte[], int, int)) { if (TDebug.TraceAudioConverter) outLeavingJoinPoint(thisJoinPoint); } after() returning(int nBytes): call(* TAsynchronousFilteredAudioInputStream.read(byte[], int, int)) { if (TDebug.TraceAudioConverter) TDebug.out("returning bytes: " + nBytes); } // before(int nState): playerStates() && args(nState) // { // // if (TDebug.TracePlayerStates) // // { // // TDebug.out("TPlayer.setState(): " + nState); // // } // } // before(): playerStateTransitions() // { // // if (TDebug.TracePlayerStateTransitions) // // { // // TDebug.out("Entering: " + thisJoinPoint); // // } // } // Synthesizer around(): call(* MidiSystem.getSynthesizer()) // { // // Synthesizer s = proceed(); // // if (TDebug.TraceToneGenerator) // // { // // TDebug.out("MidiSystem.getSynthesizer() gives: " + s); // // } // // return s; // // only to get no compilation errors // return null; // } // TODO: v gives an error; find out what to do // before(int v): printVelocity() && args(nVelocity) // { // if (TDebug.TraceToneGenerator) // { // TDebug.out("velocity: " + v); // } // } before(Throwable t): allExceptions() && args(t) { if (TDebug.TraceAllExceptions) TDebug.out(t); } } /*** AJDebug.java ***/
srnsw/xena
plugins/audio/ext/src/tritonus/src/classes/org/tritonus/debug/AJDebug.java
Java
gpl-3.0
6,383
/* Copyright 2011-2014 Red Hat, Inc This file is part of PressGang CCMS. PressGang CCMS 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. PressGang CCMS 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 PressGang CCMS. If not, see <http://www.gnu.org/licenses/>. */ package org.jboss.pressgang.ccms.rest.v1.query; import java.util.ArrayList; import java.util.List; import org.jboss.pressgang.ccms.rest.v1.constants.CommonFilterConstants; import org.jboss.pressgang.ccms.rest.v1.query.base.RESTBaseQueryBuilderV1; import org.jboss.pressgang.ccms.utils.structures.Pair; public class RESTPropertyCategoryQueryBuilderV1 extends RESTBaseQueryBuilderV1 { private static List<Pair<String, String>> filterPairs = new ArrayList<Pair<String, String>>() { private static final long serialVersionUID = -8638470044710698912L; { add(new Pair<String, String>(CommonFilterConstants.PROP_CATEGORY_IDS_FILTER_VAR, CommonFilterConstants.PROP_CATEGORY_IDS_FILTER_VAR_DESC)); add(new Pair<String, String>(CommonFilterConstants.PROP_CATEGORY_NAME_FILTER_VAR, CommonFilterConstants.PROP_CATEGORY_NAME_FILTER_VAR_DESC)); add(new Pair<String, String>(CommonFilterConstants.PROP_CATEGORY_DESCRIPTION_FILTER_VAR, CommonFilterConstants.PROP_CATEGORY_DESCRIPTION_FILTER_VAR_DESC)); } }; public static List<Pair<String, String>> getFilterInfo() { return filterPairs; } public static String getFilterDesc(final String varName) { if (varName == null) return null; final List<Pair<String, String>> filterInfo = getFilterInfo(); for (final Pair<String, String> varInfo : filterInfo) { if (varInfo.getFirst().equals(varName)) { return varInfo.getSecond(); } } return null; } public List<Integer> getPropertyCategoryIds() { final String propertyCategoryIdsString = get(CommonFilterConstants.PROP_CATEGORY_IDS_FILTER_VAR); return getIntegerList(propertyCategoryIdsString); } public void setPropertyCategoryIds(final List<Integer> propertyCategoryIds) { put(CommonFilterConstants.PROP_CATEGORY_IDS_FILTER_VAR, propertyCategoryIds); } public String getPropertyCategoryName() { return get(CommonFilterConstants.PROP_CATEGORY_NAME_FILTER_VAR); } public void setPropertyCategoryName(final String propertyCategoryName) { put(CommonFilterConstants.PROP_CATEGORY_NAME_FILTER_VAR, propertyCategoryName); } public String getPropertyCategoryDescription() { return get(CommonFilterConstants.PROP_CATEGORY_DESCRIPTION_FILTER_VAR); } public void setPropertyCategoryDescription(final String propertyCategoryDescription) { put(CommonFilterConstants.PROP_CATEGORY_DESCRIPTION_FILTER_VAR, propertyCategoryDescription); } }
pressgang-ccms/PressGangCCMSRESTv1Common
src/main/java/org/jboss/pressgang/ccms/rest/v1/query/RESTPropertyCategoryQueryBuilderV1.java
Java
gpl-3.0
3,394
/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana * * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA. * * For more information, contact: * * Generalitat Valenciana * Conselleria d'Infraestructures i Transport * Av. Blasco Ibáñez, 50 * 46010 VALENCIA * SPAIN * * +34 963862235 * gvsig@gva.es * www.gvsig.gva.es * * or * * IVER T.I. S.A * Salamanca 50 * 46005 Valencia * Spain * * +34 963163400 * dac@iver.es */ package com.iver.cit.gvsig.fmap.layers; import java.awt.Graphics2D; import java.awt.Point; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.net.URI; import java.util.ArrayList; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.standard.PrintQuality; import org.apache.log4j.Logger; import org.cresques.cts.ICoordTrans; import org.gvsig.tools.file.PathGenerator; import com.hardcode.gdbms.driver.exceptions.ReadDriverException; import com.hardcode.gdbms.engine.data.DataSourceFactory; import com.hardcode.gdbms.engine.data.NoSuchTableException; import com.hardcode.gdbms.engine.data.driver.DriverException; import com.hardcode.gdbms.engine.instruction.FieldNotFoundException; import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException; import com.iver.cit.gvsig.exceptions.layers.LegendLayerException; import com.iver.cit.gvsig.exceptions.layers.ReloadLayerException; import com.iver.cit.gvsig.exceptions.layers.ReprojectLayerException; import com.iver.cit.gvsig.exceptions.layers.StartEditionLayerException; import com.iver.cit.gvsig.exceptions.visitors.StartWriterVisitorException; import com.iver.cit.gvsig.exceptions.visitors.VisitorException; import com.iver.cit.gvsig.fmap.MapContext; import com.iver.cit.gvsig.fmap.MapControl; import com.iver.cit.gvsig.fmap.ViewPort; import com.iver.cit.gvsig.fmap.core.CartographicSupport; import com.iver.cit.gvsig.fmap.core.FPoint2D; import com.iver.cit.gvsig.fmap.core.FShape; import com.iver.cit.gvsig.fmap.core.IFeature; import com.iver.cit.gvsig.fmap.core.IGeometry; import com.iver.cit.gvsig.fmap.core.ILabelable; import com.iver.cit.gvsig.fmap.core.IRow; import com.iver.cit.gvsig.fmap.core.symbols.IMultiLayerSymbol; import com.iver.cit.gvsig.fmap.core.symbols.ISymbol; import com.iver.cit.gvsig.fmap.core.symbols.SimpleLineSymbol; import com.iver.cit.gvsig.fmap.core.v02.FConverter; import com.iver.cit.gvsig.fmap.core.v02.FSymbol; import com.iver.cit.gvsig.fmap.drivers.BoundedShapes; import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator; import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver; import com.iver.cit.gvsig.fmap.drivers.VectorialDriver; import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend; import com.iver.cit.gvsig.fmap.drivers.featureiterators.JoinFeatureIterator; import com.iver.cit.gvsig.fmap.edition.AfterFieldEditEvent; import com.iver.cit.gvsig.fmap.edition.AfterRowEditEvent; import com.iver.cit.gvsig.fmap.edition.AnnotationEditableAdapter; import com.iver.cit.gvsig.fmap.edition.BeforeFieldEditEvent; import com.iver.cit.gvsig.fmap.edition.BeforeRowEditEvent; import com.iver.cit.gvsig.fmap.edition.EditionEvent; import com.iver.cit.gvsig.fmap.edition.IEditionListener; import com.iver.cit.gvsig.fmap.edition.ISpatialWriter; import com.iver.cit.gvsig.fmap.edition.IWriteable; import com.iver.cit.gvsig.fmap.edition.IWriter; import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter; import com.iver.cit.gvsig.fmap.edition.VectorialEditableDBAdapter; import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData; import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial; import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint; import com.iver.cit.gvsig.fmap.layers.layerOperations.RandomVectorialData; import com.iver.cit.gvsig.fmap.layers.layerOperations.SingleLayer; import com.iver.cit.gvsig.fmap.layers.layerOperations.VectorialData; import com.iver.cit.gvsig.fmap.layers.layerOperations.VectorialXMLItem; import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem; import com.iver.cit.gvsig.fmap.operations.strategies.FeatureVisitor; import com.iver.cit.gvsig.fmap.operations.strategies.Strategy; import com.iver.cit.gvsig.fmap.operations.strategies.StrategyManager; import com.iver.cit.gvsig.fmap.rendering.IClassifiedVectorLegend; import com.iver.cit.gvsig.fmap.rendering.ILegend; import com.iver.cit.gvsig.fmap.rendering.IVectorLegend; import com.iver.cit.gvsig.fmap.rendering.LegendClearEvent; import com.iver.cit.gvsig.fmap.rendering.LegendContentsChangedListener; import com.iver.cit.gvsig.fmap.rendering.LegendFactory; import com.iver.cit.gvsig.fmap.rendering.SingleSymbolLegend; import com.iver.cit.gvsig.fmap.rendering.SymbolLegendEvent; import com.iver.cit.gvsig.fmap.rendering.ZSort; import com.iver.cit.gvsig.fmap.rendering.styling.labeling.AttrInTableLabelingStrategy; import com.iver.cit.gvsig.fmap.rendering.styling.labeling.ILabelingStrategy; import com.iver.cit.gvsig.fmap.rendering.styling.labeling.LabelingFactory; import com.iver.cit.gvsig.fmap.spatialindex.IPersistentSpatialIndex; import com.iver.cit.gvsig.fmap.spatialindex.ISpatialIndex; import com.iver.cit.gvsig.fmap.spatialindex.QuadtreeGt2; import com.iver.cit.gvsig.fmap.spatialindex.QuadtreeJts; import com.iver.cit.gvsig.fmap.spatialindex.SpatialIndexException; import com.iver.utiles.FileUtils; import com.iver.utiles.IPersistence; import com.iver.utiles.NotExistInXMLEntity; import com.iver.utiles.PostProcessSupport; import com.iver.utiles.XMLEntity; import com.iver.utiles.swing.threads.Cancellable; import com.iver.utiles.swing.threads.CancellableMonitorable; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jts.geom.TopologyException; /** * Capa básica Vectorial. * * @author Fernando González Cortés */ public class FLyrVect extends FLyrDefault implements ILabelable, ClassifiableVectorial, SingleLayer, VectorialData, RandomVectorialData, AlphanumericData, InfoByPoint, SelectionListener, IEditionListener, LegendContentsChangedListener { private static Logger logger = Logger.getLogger(FLyrVect.class.getName()); /** Leyenda de la capa vectorial */ private IVectorLegend legend; private int typeShape = -1; private ReadableVectorial source; private SelectableDataSource sds; private SpatialCache spatialCache = new SpatialCache(); private boolean spatialCacheEnabled = false; /** * An implementation of gvSIG spatial index */ protected ISpatialIndex spatialIndex = null; private boolean bHasJoin = false; private XMLEntity orgXMLEntity = null; private XMLEntity loadSelection = null; private IVectorLegend loadLegend = null; //Lo añado. Características de HyperEnlace (LINK) private FLyrVectLinkProperties linkProperties=new FLyrVectLinkProperties(); //private ArrayList linkProperties=null; private boolean waitTodraw=false; private static PathGenerator pathGenerator=PathGenerator.getInstance(); public boolean isWaitTodraw() { return waitTodraw; } public void setWaitTodraw(boolean waitTodraw) { this.waitTodraw = waitTodraw; } /** * Devuelve el VectorialAdapater de la capa. * * @return VectorialAdapter. */ public ReadableVectorial getSource() { if (!this.isAvailable()) return null; return source; } /** * If we use a persistent spatial index associated with this layer, and the * index is not intrisic to the layer (for example spatial databases) this * method looks for existent spatial index, and loads it. * */ private void loadSpatialIndex() { //FIXME: Al abrir el indice en fichero... //¿Cómo lo liberamos? un metodo Layer.shutdown() ReadableVectorial source = getSource(); //REVISAR QUE PASA CON LOS DRIVERS DXF, DGN, etc. //PUES SON VECTORIALFILEADAPTER if (!(source instanceof VectorialFileAdapter)) { // we are not interested in db adapters return; } VectorialDriver driver = source.getDriver(); if (!(driver instanceof BoundedShapes)) { // we dont spatially index layers that are not bounded return; } File file = ((VectorialFileAdapter) source).getFile(); String fileName = file.getAbsolutePath(); File sptFile = new File(fileName + ".qix"); if (!sptFile.exists() || (!(sptFile.length() > 0))) { // before to exit, look for it in temp path String tempPath = System.getProperty("java.io.tmpdir"); fileName = tempPath + File.separator + sptFile.getName(); sptFile = new File(fileName); // it doesnt exists, must to create if (!sptFile.exists() || (!(sptFile.length() > 0))) { return; }// if }// if try { source.start(); spatialIndex = new QuadtreeGt2(FileUtils.getFileWithoutExtension(sptFile), "NM", source.getFullExtent(), source.getShapeCount(), false); source.setSpatialIndex(spatialIndex); } catch (SpatialIndexException e) { spatialIndex = null; e.printStackTrace(); return; } catch (ReadDriverException e) { spatialIndex = null; e.printStackTrace(); return; } } /** * Checks if it has associated an external spatial index * (an spatial index file). * * It looks for it in main file path, or in temp system path. * If main file is rivers.shp, it looks for a file called * rivers.shp.qix. * @return */ public boolean isExternallySpatiallyIndexed() { /* * FIXME (AZABALA): Independizar del tipo de fichero de índice * con el que se trabaje (ahora mismo considera la extension .qix, * pero esto dependerá del tipo de índice) * */ ReadableVectorial source = getSource(); if (!(source instanceof VectorialFileAdapter)) { // we are not interested in db adapters. // think in non spatial dbs, like HSQLDB return false; } File file = ((VectorialFileAdapter) source).getFile(); String fileName = file.getAbsolutePath(); File sptFile = new File(fileName + ".qix"); if (!sptFile.exists() || (!(sptFile.length() > 0))) { // before to exit, look for it in temp path // it doesnt exists, must to create String tempPath = System.getProperty("java.io.tmpdir"); fileName = tempPath + File.separator + sptFile.getName(); sptFile = new File(fileName); if (!sptFile.exists() || (!(sptFile.length() > 0))) { return false; }// if }// if return true; } /** * Inserta el VectorialAdapter a la capa. * * @param va * VectorialAdapter. */ public void setSource(ReadableVectorial rv) { source = rv; // azabala: we check if this layer could have a file spatial index // and load it if it exists loadSpatialIndex(); } public Rectangle2D getFullExtent() throws ReadDriverException, ExpansionFileReadException { Rectangle2D rAux; source.start(); rAux = (Rectangle2D)source.getFullExtent().clone(); source.stop(); // Si existe reproyección, reproyectar el extent if (!(this.getProjection()!=null && this.getMapContext().getProjection()!=null && this.getProjection().getAbrev().equals(this.getMapContext().getProjection().getAbrev()))){ ICoordTrans ct = getCoordTrans(); try{ if (ct != null) { Point2D pt1 = new Point2D.Double(rAux.getMinX(), rAux.getMinY()); Point2D pt2 = new Point2D.Double(rAux.getMaxX(), rAux.getMaxY()); pt1 = ct.convert(pt1, null); pt2 = ct.convert(pt2, null); rAux = new Rectangle2D.Double(); rAux.setFrameFromDiagonal(pt1, pt2); } }catch (IllegalStateException e) { this.setAvailable(false); this.addError(new ReprojectLayerException(getName(), e)); } } //Esto es para cuando se crea una capa nueva con el fullExtent de ancho y alto 0. if (rAux.getWidth()==0 && rAux.getHeight()==0) { rAux=new Rectangle2D.Double(0,0,100,100); } return rAux; } /** * Draws using IFeatureIterator. This method will replace the old draw(...) one. * @autor jaume dominguez faus - jaume.dominguez@iver.es * @param image * @param g * @param viewPort * @param cancel * @param scale * @throws ReadDriverException */ private void _draw(BufferedImage image, Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale) throws ReadDriverException { boolean bDrawShapes = true; if (legend instanceof SingleSymbolLegend) { bDrawShapes = legend.getDefaultSymbol().isShapeVisible(); } Point2D offset = viewPort.getOffset(); double dpi = MapContext.getScreenDPI(); if (bDrawShapes) { boolean cacheFeatures = isSpatialCacheEnabled(); SpatialCache cache = null; if (cacheFeatures) { getSpatialCache().clearAll(); cache = getSpatialCache(); } try { ArrayList<String> fieldList = new ArrayList<String>(); // fields from legend String[] aux = null; if (legend instanceof IClassifiedVectorLegend) { aux = ((IClassifiedVectorLegend) legend).getClassifyingFieldNames(); if (aux!=null) { for (int i = 0; i < aux.length; i++) { // check fields exists if (sds.getFieldIndexByName(aux[i]) == -1) { logger.warn("Error en leyenda de " + getName() + ". El campo " + aux[i] + " no está."); legend = LegendFactory.createSingleSymbolLegend(getShapeType()); break; } fieldList.add(aux[i]); } } } // Get the iterator over the visible features IFeatureIterator it = null; if (isJoined()) { it = new JoinFeatureIterator(this, viewPort, fieldList.toArray(new String[fieldList.size()])); } else { ReadableVectorial rv=getSource(); // rv.start(); it = rv.getFeatureIterator( viewPort.getAdjustedExtent(), fieldList.toArray(new String[fieldList.size()]), viewPort.getProjection(), true); // rv.stop(); } ZSort zSort = ((IVectorLegend) getLegend()).getZSort(); boolean bSymbolLevelError = false; // if layer has map levels it will use a ZSort boolean useZSort = zSort != null && zSort.isUsingZSort(); // -- visual FX stuff long time = System.currentTimeMillis(); BufferedImage virtualBim; Graphics2D virtualGraphics; // render temporary map each screenRefreshRate milliseconds; int screenRefreshDelay = (int) ((1D/MapControl.getDrawFrameRate())*3*1000); BufferedImage[] imageLevels = null; Graphics2D[] graphics = null; if (useZSort) { imageLevels = new BufferedImage[zSort.getLevelCount()]; graphics = new Graphics2D[imageLevels.length]; for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) { imageLevels[i] = new BufferedImage(image.getWidth(), image.getHeight(), image.getType()); graphics[i] = imageLevels[i].createGraphics(); graphics[i].setTransform(g.getTransform()); graphics[i].setRenderingHints(g.getRenderingHints()); } } // -- end visual FX stuff boolean isInMemory = false; if (getSource().getDriverAttributes() != null){ isInMemory = getSource().getDriverAttributes().isLoadedInMemory(); } SelectionSupport selectionSupport=getSelectionSupport(); // Iteration over each feature while ( !cancel.isCanceled() && it.hasNext()) { IFeature feat = it.next(); IGeometry geom = null; if (isInMemory){ geom = feat.getGeometry().cloneGeometry(); }else{ geom = feat.getGeometry(); } if (cacheFeatures) { if (cache.getMaxFeatures() >= cache.size()) { // already reprojected cache.insert(geom.getBounds2D(), geom); } } // retrieve the symbol associated to such feature ISymbol sym = legend.getSymbolByFeature(feat); if (sym == null) continue; //Código para poder acceder a los índices para ver si está seleccionado un Feature ReadableVectorial rv=getSource(); int selectionIndex=-1; if (rv instanceof ISpatialDB){ selectionIndex = ((ISpatialDB)rv).getRowIndexByFID(feat); }else{ selectionIndex = Integer.parseInt(feat.getID()); } if (selectionIndex!=-1) { if (selectionSupport.isSelected(selectionIndex)) { sym = sym.getSymbolForSelection(); } } // Check if this symbol is sized with CartographicSupport CartographicSupport csSym = null; int symbolType = sym.getSymbolType(); boolean bDrawCartographicSupport = false; if ( symbolType == FShape.POINT || symbolType == FShape.LINE || sym instanceof CartographicSupport) { // patch if (!sym.getClass().equals(FSymbol.class)) { csSym = (CartographicSupport) sym; bDrawCartographicSupport = (csSym.getUnit() != -1); } } int x = -1; int y = -1; int[] xyCoords = new int[2]; // Check if size is a pixel boolean onePoint = bDrawCartographicSupport ? isOnePoint(g.getTransform(), viewPort, MapContext.getScreenDPI(), csSym, geom, xyCoords) : isOnePoint(g.getTransform(), viewPort, geom, xyCoords); // Avoid out of bounds exceptions if (onePoint) { x = xyCoords[0]; y = xyCoords[1]; if (x<0 || y<0 || x>= viewPort.getImageWidth() || y>=viewPort.getImageHeight()) continue; } if (useZSort) { // Check if this symbol is a multilayer int[] symLevels = zSort.getLevels(sym); if (sym instanceof IMultiLayerSymbol) { // if so, treat each of its layers as a single symbol // in its corresponding map level IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym; for (int i = 0; !cancel.isCanceled() && i < mlSym.getLayerCount(); i++) { ISymbol mySym = mlSym.getLayer(i); int symbolLevel = 0; if (symLevels != null) { symbolLevel = symLevels[i]; } else { /* an error occured when managing symbol levels. * some of the legend changed events regarding the * symbols did not finish satisfactory and the legend * is now inconsistent. For this drawing, it will finish * as it was at the bottom (level 0) but, when done, the * ZSort will be reset to avoid app crashes. This is * a bug that has to be fixed. */ bSymbolLevelError = true; } if (onePoint) { if (x<0 || y<0 || x>= imageLevels[symbolLevel].getWidth() || y>=imageLevels[symbolLevel].getHeight()) continue; imageLevels[symbolLevel].setRGB(x, y, mySym.getOnePointRgb()); } else { if (!bDrawCartographicSupport) { geom.drawInts(graphics[symbolLevel], viewPort, mySym, cancel); } else { geom.drawInts(graphics[symbolLevel], viewPort, dpi, (CartographicSupport) mySym, cancel); } } } } else { // else, just draw the symbol in its level int symbolLevel = 0; if (symLevels != null) { symbolLevel=symLevels[0]; } else { /* If symLevels == null * an error occured when managing symbol levels. * some of the legend changed events regarding the * symbols did not finish satisfactory and the legend * is now inconsistent. For this drawing, it will finish * as it was at the bottom (level 0). This is * a bug that has to be fixed. */ // bSymbolLevelError = true; } if (!bDrawCartographicSupport) { geom.drawInts(graphics[symbolLevel], viewPort, sym, cancel); } else { geom.drawInts(graphics[symbolLevel], viewPort, dpi, csSym, cancel); } } // -- visual FX stuff // Cuando el offset!=0 se está dibujando sobre el Layout y por tanto no tiene que ejecutar el siguiente código. if (offset.getX()==0 && offset.getY()==0) if ((System.currentTimeMillis() - time) > screenRefreshDelay) { virtualBim = new BufferedImage(image.getWidth(),image.getHeight(),BufferedImage.TYPE_INT_ARGB); virtualGraphics = virtualBim.createGraphics(); virtualGraphics.drawImage(image,0,0, null); for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) { virtualGraphics.drawImage(imageLevels[i],0,0, null); } g.clearRect(0, 0, image.getWidth(), image.getHeight()); g.drawImage(virtualBim, 0, 0, null); time = System.currentTimeMillis(); } // -- end visual FX stuff } else { // no ZSort, so there is only a map level, symbols are // just drawn. if (onePoint) { if (x<0 || y<0 || x>= image.getWidth() || y>=image.getHeight()) continue; image.setRGB(x, y, sym.getOnePointRgb()); } else { if (!bDrawCartographicSupport) { geom.drawInts(g, viewPort, sym, cancel); } else { geom.drawInts(g, viewPort, dpi, csSym, cancel); } } } } if (useZSort) { g.drawImage(image, (int)offset.getX(), (int)offset.getY(), null); g.translate(offset.getX(), offset.getY()); for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) { g.drawImage(imageLevels[i],0,0, null); imageLevels[i] = null; graphics[i] = null; } g.translate(-offset.getX(), -offset.getY()); imageLevels = null; graphics = null; } it.closeIterator(); if (bSymbolLevelError) { ((IVectorLegend) getLegend()).setZSort(null); } } catch (ReadDriverException e) { this.setVisible(false); this.setActive(false); throw e; } } } public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale) throws ReadDriverException { if (isWaitTodraw()) { return; } if (getStrategy() != null) { getStrategy().draw(image, g, viewPort, cancel); } else { _draw(image, g, viewPort, cancel, scale); } } public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties, boolean highlight) throws ReadDriverException { boolean bDrawShapes = true; boolean cutGeom = true; if (legend instanceof SingleSymbolLegend) { bDrawShapes = legend.getDefaultSymbol().isShapeVisible(); } if (bDrawShapes) { try { double dpi = 72; PrintQuality resolution=(PrintQuality)properties.get(PrintQuality.class); if (resolution.equals(PrintQuality.NORMAL)){ dpi = 300; } else if (resolution.equals(PrintQuality.HIGH)){ dpi = 600; } else if (resolution.equals(PrintQuality.DRAFT)){ dpi = 72; } ArrayList<String> fieldList = new ArrayList<String>(); String[] aux; // fields from legend if (legend instanceof IClassifiedVectorLegend) { aux = ((IClassifiedVectorLegend) legend).getClassifyingFieldNames(); for (int i = 0; i < aux.length; i++) { fieldList.add(aux[i]); } } // // // fields from labeling // if (isLabeled()) { // aux = getLabelingStrategy().getUsedFields(); // for (int i = 0; i < aux.length; i++) { // fieldList.add(aux[i]); // } // } ZSort zSort = ((IVectorLegend) getLegend()).getZSort(); // if layer has map levels it will use a ZSort boolean useZSort = zSort != null && zSort.isUsingZSort(); int mapLevelCount = (useZSort) ? zSort.getLevelCount() : 1; for (int mapPass = 0; mapPass < mapLevelCount; mapPass++) { // Get the iterator over the visible features // IFeatureIterator it = getSource().getFeatureIterator( // viewPort.getAdjustedExtent(), // fieldList.toArray(new String[fieldList.size()]), // viewPort.getProjection(), // true); IFeatureIterator it = null; if (isJoined()) { it = new JoinFeatureIterator(this, viewPort, fieldList.toArray(new String[fieldList.size()])); } else { it = getSource().getFeatureIterator( viewPort.getAdjustedExtent(), fieldList.toArray(new String[fieldList.size()]), viewPort.getProjection(), true); } // Iteration over each feature while ( !cancel.isCanceled() && it.hasNext()) { IFeature feat = it.next(); IGeometry geom = feat.getGeometry(); // retreive the symbol associated to such feature ISymbol sym = legend.getSymbolByFeature(feat); if (sym == null) { continue; } SelectionSupport selectionSupport=getSelectionSupport(); if (highlight) { //Código para poder acceder a los índices para ver si está seleccionado un Feature ReadableVectorial rv=getSource(); int selectionIndex=-1; if (rv instanceof ISpatialDB){ selectionIndex = ((ISpatialDB)rv).getRowIndexByFID(feat); } else { selectionIndex = Integer.parseInt(feat.getID()); } if (selectionIndex!=-1) { if (selectionSupport.isSelected(selectionIndex)) { sym = sym.getSymbolForSelection(); } } } if (useZSort) { int[] symLevels = zSort.getLevels(sym); if(symLevels != null){ // Check if this symbol is a multilayer if (sym instanceof IMultiLayerSymbol) { // if so, get the layer corresponding to the current // level. If none, continue to next iteration IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym; for (int i = 0; i < mlSym.getLayerCount(); i++) { ISymbol mySym = mlSym.getLayer(i); if (symLevels[i] == mapPass) { sym = mySym; break; } System.out.println("avoided layer "+i+"of symbol '"+mlSym.getDescription()+"' (pass "+mapPass+")"); } } else { // else, just draw the symbol in its level if (symLevels[0] != mapPass) { System.out.println("avoided single layer symbol '"+sym.getDescription()+"' (pass "+mapPass+")"); continue; } } } } // Check if this symbol is sized with CartographicSupport CartographicSupport csSym = null; int symbolType = sym.getSymbolType(); if (symbolType == FShape.POINT || symbolType == FShape.LINE || sym instanceof CartographicSupport) { csSym = (CartographicSupport) sym; if (sym instanceof SimpleLineSymbol) { SimpleLineSymbol lineSym = new SimpleLineSymbol(); lineSym.setXMLEntity(sym.getXMLEntity()); if (((SimpleLineSymbol) sym).getLineStyle() .getArrowDecorator() != null) { // Lines with decorators should not be cut // because the decorators would be drawn in // the wrong places cutGeom = false; if (!((SimpleLineSymbol) sym) .getLineStyle().getArrowDecorator() .isScaleArrow()) { // Hack for increasing non-scaled arrow // marker size, which usually looks // smaller when printing lineSym.getLineStyle() .getArrowDecorator() .getMarker() .setSize( lineSym.getLineStyle() .getArrowDecorator() .getMarker() .getSize() * 3); } } else { // Make default lines slightly thinner when // printing lineSym.setLineWidth(lineSym.getLineWidth() * 0.75); } csSym = lineSym; } } //System.err.println("passada "+mapPass+" pinte símboll "+sym.getDescription()); // We check if the geometry seems to intersect with the // view extent Rectangle2D extent = viewPort.getExtent(); IGeometry geomToPrint = null; if (cutGeom) { try { if (geom.fastIntersects(extent.getX(), extent.getY(), extent.getWidth(), extent.getHeight())) { // If it does, then we create a rectangle // based on // the view extent and cut the geometries by // it // before drawing them GeometryFactory geomF = new GeometryFactory(); Geometry intersection = geom .toJTSGeometry() .intersection( new Polygon( geomF.createLinearRing(new Coordinate[] { new Coordinate( extent.getMinX(), extent.getMaxY()), new Coordinate( extent.getMaxX(), extent.getMaxY()), new Coordinate( extent.getMaxX(), extent.getMinY()), new Coordinate( extent.getMinX(), extent.getMinY()), new Coordinate( extent.getMinX(), extent.getMaxY()) }), null, geomF)); if (!intersection.isEmpty()) { geomToPrint = FConverter .jts_to_igeometry(intersection); } } } catch (TopologyException e) { logger.warn( "Some error happened while trying to cut a polygon with the view extent before printing (layer '" + this.getName() + "' / feature id " + feat.getID() + "). The whole polygon will be drawn. ", e); geomToPrint = geom; } } else { geomToPrint = geom; } if (geomToPrint != null) { if (csSym == null) { geomToPrint.drawInts(g, viewPort, sym, null); } else { geomToPrint.drawInts(g, viewPort, dpi, csSym, cancel); } } } it.closeIterator(); } } catch (ReadDriverException e) { this.setVisible(false); this.setActive(false); throw e; } } } public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties) throws ReadDriverException { print(g, viewPort, cancel, scale, properties, false); } public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties, boolean highlight) throws ReadDriverException { if (isVisible() && isWithinScale(scale)) { _print(g, viewPort, cancel, scale, properties, highlight); } } public void deleteSpatialIndex() { //must we delete possible spatial indexes files? spatialIndex = null; } /** * <p> * Creates an spatial index associated to this layer. * The spatial index will used * the native projection of the layer, so if the layer is reprojected, it will * be ignored. * </p> * @param cancelMonitor instance of CancellableMonitorable that allows * to monitor progress of spatial index creation, and cancel the process */ public void createSpatialIndex(CancellableMonitorable cancelMonitor){ // FJP: ESTO HABRÁ QUE CAMBIARLO. PARA LAS CAPAS SECUENCIALES, TENDREMOS // QUE ACCEDER CON UN WHILE NEXT. (O mejorar lo de los FeatureVisitor // para que acepten recorrer sin geometria, solo con rectangulos. //If this vectorial layer is based in a spatial database, the spatial //index is already implicit. We only will index file drivers ReadableVectorial va = getSource(); //We must think in non spatial databases, like HSQLDB if(!(va instanceof VectorialFileAdapter)){ return; } if (!(va.getDriver() instanceof BoundedShapes)) { return; } File file = ((VectorialFileAdapter) va).getFile(); String fileName = file.getAbsolutePath(); ISpatialIndex localCopy = null; try { va.start(); localCopy = new QuadtreeGt2(fileName, "NM", va.getFullExtent(), va.getShapeCount(), true); } catch (SpatialIndexException e1) { // Probably we dont have writing permissions String directoryName = System.getProperty("java.io.tmpdir"); File newFile = new File(directoryName + File.separator + file.getName()); String newFileName = newFile.getName(); try { localCopy = new QuadtreeGt2(newFileName, "NM", va.getFullExtent(), va.getShapeCount(), true); } catch (SpatialIndexException e) { // if we cant build a file based spatial index, we'll build // a pure memory spatial index localCopy = new QuadtreeJts(); } catch (ReadDriverException e) { localCopy = new QuadtreeJts(); } } catch(Exception e){ e.printStackTrace(); }//try BoundedShapes shapeBounds = (BoundedShapes) va.getDriver(); try { for (int i=0; i < va.getShapeCount(); i++) { if(cancelMonitor != null){ if(cancelMonitor.isCanceled()) return; cancelMonitor.reportStep(); } Rectangle2D r = shapeBounds.getShapeBounds(i); if(r != null) localCopy.insert(r, i); } // for va.stop(); if(localCopy instanceof IPersistentSpatialIndex) ((IPersistentSpatialIndex) localCopy).flush(); spatialIndex = localCopy; //vectorial adapter needs a reference to the spatial index, to solve //request for feature iteration based in spatial queries source.setSpatialIndex(spatialIndex); } catch (ReadDriverException e) { e.printStackTrace(); } } public void createSpatialIndex() { createSpatialIndex(null); } public void process(FeatureVisitor visitor, FBitSet subset) throws ReadDriverException, ExpansionFileReadException, VisitorException { Strategy s = StrategyManager.getStrategy(this); s.process(visitor, subset); } public void process(FeatureVisitor visitor) throws ReadDriverException, VisitorException { Strategy s = StrategyManager.getStrategy(this); s.process(visitor); } public void process(FeatureVisitor visitor, Rectangle2D rect) throws ReadDriverException, ExpansionFileReadException, VisitorException { Strategy s = StrategyManager.getStrategy(this); s.process(visitor, rect); } public FBitSet queryByRect(Rectangle2D rect) throws ReadDriverException, VisitorException { Strategy s = StrategyManager.getStrategy(this); return s.queryByRect(rect); } public FBitSet queryByPoint(Point2D p, double tolerance) throws ReadDriverException, VisitorException { Strategy s = StrategyManager.getStrategy(this); return s.queryByPoint(p, tolerance); } public FBitSet queryByShape(IGeometry g, int relationship) throws ReadDriverException, VisitorException { Strategy s = StrategyManager.getStrategy(this); return s.queryByShape(g, relationship); } public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws ReadDriverException, VisitorException { Point2D pReal = this.getMapContext().getViewPort().toMapPoint(p); FBitSet bs = queryByPoint(pReal, tolerance); VectorialXMLItem[] item = new VectorialXMLItem[1]; item[0] = new VectorialXMLItem(bs, this); return item; } public void setLegend(IVectorLegend r) throws LegendLayerException { if (this.legend == r){ return; } if (this.legend != null && this.legend.equals(r)){ return; } IVectorLegend oldLegend = legend; /* * Parche para discriminar las leyendas clasificadas cuyos campos de * clasificación no están en la fuente de la capa. * * Esto puede ocurrir porque en versiones anteriores se admitían * leyendas clasificadas en capas que se han unido a una tabla * por campos que pertenecían a la tabla y no sólo a la capa. * */ // if(r instanceof IClassifiedVectorLegend){ // IClassifiedVectorLegend classifiedLegend = (IClassifiedVectorLegend)r; // String[] fieldNames = classifiedLegend.getClassifyingFieldNames(); // // for (int i = 0; i < fieldNames.length; i++) { // try { // if(this.getRecordset().getFieldIndexByName(fieldNames[i]) == -1){ //// if(this.getSource().getRecordset().getFieldIndexByName(fieldNames[i]) == -1){ // logger.warn("Some fields of the classification of the legend doesn't belong with the source of the layer."); // if (this.legend == null){ // r = LegendFactory.createSingleSymbolLegend(this.getShapeType()); // } else { // return; // } // } // } catch (ReadDriverException e1) { // throw new LegendLayerException(getName(),e1); // } // } // } /* Fin del parche */ legend = r; try { legend.setDataSource(getRecordset()); } catch (FieldNotFoundException e1) { throw new LegendLayerException(getName(),e1); } catch (ReadDriverException e1) { throw new LegendLayerException(getName(),e1); } finally{ this.updateDrawVersion(); } if (oldLegend != null){ oldLegend.removeLegendListener(this); } if (legend != null){ legend.addLegendListener(this); } LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent( oldLegend, legend); e.setLayer(this); callLegendChanged(e); } /** * Devuelve la Leyenda de la capa. * * @return Leyenda. */ public ILegend getLegend() { return legend; } /** * Devuelve el tipo de shape que contiene la capa. * * @return tipo de shape. * * @throws DriverException */ public int getShapeType() throws ReadDriverException { if (typeShape == -1) { getSource().start(); typeShape = getSource().getShapeType(); getSource().stop(); } return typeShape; } public XMLEntity getXMLEntity() throws XMLException { if (!this.isAvailable() && this.orgXMLEntity != null) { return this.orgXMLEntity; } XMLEntity xml = super.getXMLEntity(); if (getLegend()!=null) xml.addChild(getLegend().getXMLEntity()); try { if (getRecordset()!=null) xml.addChild(getRecordset().getSelectionSupport().getXMLEntity()); } catch (ReadDriverException e1) { e1.printStackTrace(); throw new XMLException(e1); } // Repongo el mismo ReadableVectorial más abajo para cuando se guarda el proyecto. ReadableVectorial rv=getSource(); xml.putProperty("type", "vectorial"); if (source instanceof VectorialEditableAdapter) { setSource(((VectorialEditableAdapter) source).getOriginalAdapter()); } if (source instanceof VectorialFileAdapter) { xml.putProperty("type", "vectorial"); xml.putProperty("absolutePath",((VectorialFileAdapter) source) .getFile().getAbsolutePath()); xml.putProperty("file", pathGenerator.getPath(((VectorialFileAdapter) source) .getFile().getAbsolutePath())); try { xml.putProperty("recordset-name", source.getRecordset() .getName()); } catch (ReadDriverException e) { throw new XMLException(e); } catch (RuntimeException e) { e.printStackTrace(); } } else if (source instanceof VectorialDBAdapter) { xml.putProperty("type", "vectorial"); IVectorialDatabaseDriver dbDriver = (IVectorialDatabaseDriver) source .getDriver(); // Guardamos el nombre del driver para poder recuperarlo // con el DriverManager de Fernando. xml.putProperty("db", dbDriver.getName()); try { xml.putProperty("recordset-name", source.getRecordset() .getName()); } catch (ReadDriverException e) { throw new XMLException(e); } catch (RuntimeException e) { e.printStackTrace(); } xml.addChild(dbDriver.getXMLEntity()); // Tercer child. Antes hemos // metido la leyenda y el // selection support } else if (source instanceof VectorialAdapter) { // Se supone que hemos hecho algo genérico. xml.putProperty("type", "vectorial"); VectorialDriver driver = source.getDriver(); // Guardamos el nombre del driver para poder recuperarlo // con el DriverManager de Fernando. xml.putProperty("other", driver.getName()); // try { try { xml.putProperty("recordset-name", source.getRecordset() .getName()); } catch (ReadDriverException e) { throw new XMLException(e); } catch (RuntimeException e) { e.printStackTrace(); } if (driver instanceof IPersistence) { // xml.putProperty("className", driver.getClass().getName()); IPersistence persist = (IPersistence) driver; xml.addChild(persist.getXMLEntity()); // Tercer child. Antes // hemos metido la // leyenda y el // selection support } } if (rv!=null) setSource(rv); xml.putProperty("driverName", source.getDriver().getName()); if (bHasJoin) xml.putProperty("hasJoin", "true"); // properties from ILabelable xml.putProperty("isLabeled", isLabeled); if (strategy != null) { XMLEntity strategyXML = strategy.getXMLEntity(); strategyXML.putProperty("Strategy", strategy.getClassName()); xml.addChild(strategy.getXMLEntity()); } xml.addChild(getLinkProperties().getXMLEntity()); return xml; } /* * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setXMLEntity(com.iver.utiles.XMLEntity) */ public void setXMLEntity(XMLEntity xml) throws XMLException { try { super.setXMLEntity(xml); XMLEntity legendXML = xml.getChild(0); IVectorLegend leg = LegendFactory.createFromXML(legendXML); try { getRecordset().getSelectionSupport().setXMLEntity(xml.getChild(1)); // JMVIVO: Esto sirve para algo???? /* * Jaume: si, para restaurar el selectable datasource cuando se * clona la capa, cuando se carga de un proyecto. Si no esta ya * no se puede ni hacer consultas sql, ni hacer selecciones, * ni usar la mayor parte de las herramientas. * * Lo vuelvo a poner. */ String recordsetName = xml.getStringProperty("recordset-name"); LayerFactory.getDataSourceFactory().changeDataSourceName( getSource().getRecordset().getName(), recordsetName); SelectableDataSource sds = new SelectableDataSource(LayerFactory .getDataSourceFactory().createRandomDataSource( recordsetName, DataSourceFactory.AUTOMATIC_OPENING)); } catch (NoSuchTableException e1) { this.setAvailable(false); throw new XMLException(e1); } catch (ReadDriverException e1) { this.setAvailable(false); throw new XMLException(e1); } // Si tiene una unión, lo marcamos para que no se cree la leyenda hasta // el final // de la lectura del proyecto if (xml.contains("hasJoin")) { setIsJoined(true); PostProcessSupport.addToPostProcess(this, "setLegend", leg, 1); } else { try { setLegend(leg); } catch (LegendLayerException e) { throw new XMLException(e); } } //Por compatibilidad con proyectos anteriores a la 1.0 boolean containsIsLabeled = xml.contains("isLabeled"); if (containsIsLabeled){ isLabeled = xml.getBooleanProperty("isLabeled"); } // set properties for ILabelable XMLEntity labelingXML = xml.firstChild("labelingStrategy", "labelingStrategy"); if (labelingXML!= null) { if(!containsIsLabeled){ isLabeled = true; } try { ILabelingStrategy labeling = LabelingFactory.createStrategyFromXML(labelingXML, this); if (isJoined()) { PostProcessSupport.addToPostProcess(this, "setLabelingStrategy", labeling, 1); } else this.setLabelingStrategy(labeling); } catch (NotExistInXMLEntity neXMLEX) { // no strategy was set, just continue; logger.warn("Reached what should be unreachable code"); } } else if (legendXML.contains("labelFieldName")|| legendXML.contains("labelfield")) { /* (jaume) begin patch; * for backward compatibility purposes. Since gvSIG v1.1 labeling is * no longer managed by the Legend but by the ILabelingStrategy. The * following allows restoring older projects' labelings. */ String labelTextField = null; if (legendXML.contains("labelFieldName")){ labelTextField = legendXML.getStringProperty("labelFieldName"); if (labelTextField != null) { AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy(); labeling.setLayer(this); int unit = 1; boolean useFixedSize = false; String labelFieldHeight = legendXML.getStringProperty("labelHeightFieldName"); labeling.setTextField(labelTextField); if(labelFieldHeight!=null){ labeling.setHeightField(labelFieldHeight); } else { double size = -1; for(int i=0; i<legendXML.getChildrenCount();i++){ XMLEntity xmlChild = legendXML.getChild(i); if(xmlChild.contains("m_FontSize")){ double childFontSize = xmlChild.getDoubleProperty("m_FontSize"); if(size<0){ size = childFontSize; useFixedSize = true; } else { useFixedSize = useFixedSize && (size==childFontSize); } if(xmlChild.contains("m_bUseFontSize")){ if(xmlChild.getBooleanProperty("m_bUseFontSize")){ unit = -1; } else { unit = 1; } } } } labeling.setFixedSize(size/1.4);//Factor de corrección que se aplicaba antes en el etiquetado } labeling.setUsesFixedSize(useFixedSize); labeling.setUnit(unit); labeling.setRotationField(legendXML.getStringProperty("labelRotationFieldName")); if (isJoined()) { PostProcessSupport.addToPostProcess(this, "setLabelingStrategy", labeling, 1); } else this.setLabelingStrategy(labeling); this.setIsLabeled(true); } }else{ labelTextField = legendXML.getStringProperty("labelfield"); if (labelTextField != null) { AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy(); labeling.setLayer(this); int unit = 1; boolean useFixedSize = false; String labelFieldHeight = legendXML.getStringProperty("labelFieldHeight"); labeling.setTextField(labelTextField); if(labelFieldHeight!=null){ labeling.setHeightField(labelFieldHeight); } else { double size = -1; for(int i=0; i<legendXML.getChildrenCount();i++){ XMLEntity xmlChild = legendXML.getChild(i); if(xmlChild.contains("m_FontSize")){ double childFontSize = xmlChild.getDoubleProperty("m_FontSize"); if(size<0){ size = childFontSize; useFixedSize = true; } else { useFixedSize = useFixedSize && (size==childFontSize); } if(xmlChild.contains("m_bUseFontSize")){ if(xmlChild.getBooleanProperty("m_bUseFontSize")){ unit = -1; } else { unit = 1; } } } } labeling.setFixedSize(size/1.4);//Factor de corrección que se aplicaba antes en el etiquetado } labeling.setUsesFixedSize(useFixedSize); labeling.setUnit(unit); labeling.setRotationField(legendXML.getStringProperty("labelFieldRotation")); if (isJoined()) { PostProcessSupport.addToPostProcess(this, "setLabelingStrategy", labeling, 1); } else this.setLabelingStrategy(labeling); this.setIsLabeled(true); } } }else if(!containsIsLabeled){ isLabeled = false; } // compatibility with hyperlink from 1.9 alpha version... do we really need to be compatible with alpha versions?? XMLEntity xmlLinkProperties=xml.firstChild("typeChild", "linkProperties"); if (xmlLinkProperties != null){ try { String fieldName=xmlLinkProperties.getStringProperty("fieldName"); xmlLinkProperties.remove("fieldName"); String extName = xmlLinkProperties.getStringProperty("extName"); xmlLinkProperties.remove("extName"); int typeLink = xmlLinkProperties.getIntProperty("typeLink"); xmlLinkProperties.remove("typeLink"); if (fieldName!=null) { setProperty("legacy.hyperlink.selectedField", fieldName); setProperty("legacy.hyperlink.type", new Integer(typeLink)); if (extName!=null) { setProperty("legacy.hyperlink.extension", extName); } } } catch (NotExistInXMLEntity ex) { logger.warn("Error getting old hyperlink configuration", ex); } } } catch (XMLException e) { this.setAvailable(false); this.orgXMLEntity = xml; } catch (Exception e) { e.printStackTrace(); this.setAvailable(false); this.orgXMLEntity = xml; } } public void setXMLEntityNew(XMLEntity xml) throws XMLException { try { super.setXMLEntity(xml); XMLEntity legendXML = xml.getChild(0); IVectorLegend leg = LegendFactory.createFromXML(legendXML); /* (jaume) begin patch; * for backward compatibility purposes. Since gvSIG v1.1 labeling is * no longer managed by the Legend but by the ILabelingStrategy. The * following allows restoring older projects' labelings. */ if (legendXML.contains("labelFieldHeight")) { AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy(); labeling.setLayer(this); labeling.setTextField(legendXML.getStringProperty("labelFieldHeight")); labeling.setRotationField(legendXML.getStringProperty("labelFieldRotation")); this.setLabelingStrategy(labeling); this.setIsLabeled(true); } /* end patch */ try { getRecordset().getSelectionSupport().setXMLEntity(xml.getChild(1)); this.setLoadSelection(xml.getChild(1)); } catch (ReadDriverException e1) { this.setAvailable(false); throw new XMLException(e1); } // Si tiene una unión, lo marcamos para que no se cree la leyenda hasta // el final // de la lectura del proyecto if (xml.contains("hasJoin")) { setIsJoined(true); PostProcessSupport.addToPostProcess(this, "setLegend", leg, 1); } else { this.setLoadLegend(leg); } } catch (XMLException e) { this.setAvailable(false); this.orgXMLEntity = xml; } catch (Exception e) { this.setAvailable(false); this.orgXMLEntity = xml; } } /** * Sobreimplementación del método toString para que las bases de datos * identifiquen la capa. * * @return DOCUMENT ME! */ public String toString() { /* * Se usa internamente para que la parte de datos identifique de forma * unívoca las tablas */ String ret = super.toString(); return "layer" + ret.substring(ret.indexOf('@') + 1); } public boolean isJoined() { return bHasJoin; } /** * Returns if a layer is spatially indexed * * @return if this layer has the ability to proces spatial queries without * secuential scans. */ public boolean isSpatiallyIndexed() { ReadableVectorial source = getSource(); if (source instanceof ISpatialDB) return true; //FIXME azabala /* * Esto es muy dudoso, y puede cambiar. * Estoy diciendo que las que no son fichero o no son * BoundedShapes estan indexadas. Esto es mentira, pero * así quien pregunte no querrá generar el indice. * Esta por ver si interesa generar el indice para capas * HSQLDB, WFS, etc. */ if(!(source instanceof VectorialFileAdapter)){ return true; } if (!(source.getDriver() instanceof BoundedShapes)) { return true; } if (getISpatialIndex() != null) return true; return false; } public void setIsJoined(boolean hasJoin) { bHasJoin = hasJoin; } /** * @return Returns the spatialIndex. */ public ISpatialIndex getISpatialIndex() { return spatialIndex; } /** * Sets the spatial index. This could be useful if, for some * reasons, you want to work with a distinct spatial index * (for example, a spatial index which could makes nearest * neighbour querys) * @param spatialIndex */ public void setISpatialIndex(ISpatialIndex spatialIndex){ this.spatialIndex = spatialIndex; } public SelectableDataSource getRecordset() throws ReadDriverException { if (!this.isAvailable()) return null; if (sds == null) { SelectableDataSource ds = source.getRecordset(); if (ds == null) { return null; } sds = ds; getSelectionSupport().addSelectionListener(this); } return sds; } public void setEditing(boolean b) throws StartEditionLayerException { super.setEditing(b); try { if (b) { VectorialEditableAdapter vea = null; // TODO: Qué pasa si hay más tipos de adapters? // FJP: Se podría pasar como argumento el // VectorialEditableAdapter // que se quiera usar para evitar meter código aquí de este // estilo. if (getSource() instanceof VectorialDBAdapter) { vea = new VectorialEditableDBAdapter(); } else if (this instanceof FLyrAnnotation) { vea = new AnnotationEditableAdapter( (FLyrAnnotation) this); } else { vea = new VectorialEditableAdapter(); } vea.addEditionListener(this); vea.setOriginalVectorialAdapter(getSource()); // azo: implementations of readablevectorial need //references of projection and spatial index vea.setProjection(getProjection()); vea.setSpatialIndex(spatialIndex); // /vea.setSpatialIndex(getSpatialIndex()); // /vea.setFullExtent(getFullExtent()); vea.setCoordTrans(getCoordTrans()); vea.startEdition(EditionEvent.GRAPHIC); setSource(vea); getRecordset().setSelectionSupport( vea.getOriginalAdapter().getRecordset() .getSelectionSupport()); } else { VectorialEditableAdapter vea = (VectorialEditableAdapter) getSource(); vea.removeEditionListener(this); setSource(vea.getOriginalAdapter()); } // Si tenemos una leyenda, hay que pegarle el cambiazo a su // recordset setRecordset(getSource().getRecordset()); if (getLegend() instanceof IVectorLegend) { IVectorLegend ley = (IVectorLegend) getLegend(); ley.setDataSource(getSource().getRecordset()); // Esto lo pongo para evitar que al dibujar sobre un // dxf, dwg, o dgn no veamos nada. Es debido al checkbox // de la leyenda de textos "dibujar solo textos". //jaume // if (!(getSource().getDriver() instanceof IndexedShpDriver)){ // FSymbol symbol=new FSymbol(getShapeType()); // symbol.setFontSizeInPixels(false); // symbol.setFont(new Font("SansSerif", Font.PLAIN, 9)); // Color color=symbol.getColor(); // int alpha=symbol.getColor().getAlpha(); // if (alpha>250) { // symbol.setColor(new Color(color.getRed(),color.getGreen(),color.getBlue(),100)); // } // ley.setDefaultSymbol(symbol); // } //jaume// ley.useDefaultSymbol(true); } } catch (ReadDriverException e) { throw new StartEditionLayerException(getName(),e); } catch (FieldNotFoundException e) { throw new StartEditionLayerException(getName(),e); } catch (StartWriterVisitorException e) { throw new StartEditionLayerException(getName(),e); } setSpatialCacheEnabled(b); callEditionChanged(LayerEvent .createEditionChangedEvent(this, "edition")); } /** * Para cuando haces una unión, sustituyes el recorset por el nuevo. De esta * forma, podrás poner leyendas basadas en el nuevo recordset * * @param newSds */ public void setRecordset(SelectableDataSource newSds) { // TODO: Deberiamos hacer comprobaciones del cambio sds = newSds; getSelectionSupport().addSelectionListener(this); this.updateDrawVersion(); } public void clearSpatialCache() { spatialCache.clearAll(); } public boolean isSpatialCacheEnabled() { return spatialCacheEnabled; } public void setSpatialCacheEnabled(boolean spatialCacheEnabled) { this.spatialCacheEnabled = spatialCacheEnabled; } public SpatialCache getSpatialCache() { return spatialCache; } /** * Siempre es un numero mayor de 1000 * @param maxFeatures */ public void setMaxFeaturesInEditionCache(int maxFeatures) { if (maxFeatures > spatialCache.maxFeatures) spatialCache.setMaxFeatures(maxFeatures); } /** * This method returns a boolean that is used by the FPopMenu * to make visible the properties menu or not. It is visible by * default, and if a later don't have to show this menu only * has to override this method. * @return * If the properties menu is visible (or not) */ public boolean isPropertiesMenuVisible(){ return true; } public void reload() throws ReloadLayerException { if(this.isEditing()){ throw new ReloadLayerException(getName()); } this.setAvailable(true); super.reload(); this.updateDrawVersion(); try { this.source.getDriver().reload(); if (this.getLegend() == null) { if (this.getRecordset().getDriver() instanceof WithDefaultLegend) { WithDefaultLegend aux = (WithDefaultLegend) this.getRecordset().getDriver(); this.setLegend((IVectorLegend) aux.getDefaultLegend()); this.setLabelingStrategy(aux.getDefaultLabelingStrategy()); } else { this.setLegend(LegendFactory.createSingleSymbolLegend( this.getShapeType())); } } } catch (LegendLayerException e) { this.setAvailable(false); throw new ReloadLayerException(getName(),e); } catch (ReadDriverException e) { this.setAvailable(false); throw new ReloadLayerException(getName(),e); } } protected void setLoadSelection(XMLEntity xml) { this.loadSelection = xml; } protected void setLoadLegend(IVectorLegend legend) { this.loadLegend = legend; } protected void putLoadSelection() throws XMLException { if (this.loadSelection == null) return; try { this.getRecordset().getSelectionSupport().setXMLEntity(this.loadSelection); } catch (ReadDriverException e) { throw new XMLException(e); } this.loadSelection = null; } protected void putLoadLegend() throws LegendLayerException { if (this.loadLegend == null) return; this.setLegend(this.loadLegend); this.loadLegend = null; } protected void cleanLoadOptions() { this.loadLegend = null; this.loadSelection = null; } public boolean isWritable() { VectorialDriver drv = getSource().getDriver(); if (!drv.isWritable()) return false; if (drv instanceof IWriteable) { IWriter writer = ((IWriteable)drv).getWriter(); if (writer != null) { if (writer instanceof ISpatialWriter) return true; } } return false; } public FLayer cloneLayer() throws Exception { FLyrVect clonedLayer = new FLyrVect(); clonedLayer.setSource(getSource()); if (isJoined()) { clonedLayer.setIsJoined(true); clonedLayer.setRecordset(getRecordset()); } clonedLayer.setVisible(isVisible()); clonedLayer.setISpatialIndex(getISpatialIndex()); clonedLayer.setName(getName()); clonedLayer.setCoordTrans(getCoordTrans()); clonedLayer.setLegend((IVectorLegend)getLegend().cloneLegend()); clonedLayer.setIsLabeled(isLabeled()); ILabelingStrategy labelingStrategy=getLabelingStrategy(); if (labelingStrategy!=null) clonedLayer.setLabelingStrategy(labelingStrategy); return clonedLayer; } public SelectionSupport getSelectionSupport() { try { return getRecordset().getSelectionSupport(); } catch (ReadDriverException e) { e.printStackTrace(); } return null; } protected boolean isOnePoint(AffineTransform graphicsTransform, ViewPort viewPort, double dpi, CartographicSupport csSym, IGeometry geom, int[] xyCoords) { return isOnePoint(graphicsTransform, viewPort, geom, xyCoords) && csSym.getCartographicSize(viewPort, dpi, (FShape)geom.getInternalShape()) <= 1; } protected boolean isOnePoint(AffineTransform graphicsTransform, ViewPort viewPort, IGeometry geom, int[] xyCoords) { boolean onePoint = false; int type=geom.getGeometryType() % FShape.Z; if (type!=FShape.POINT && type!=FShape.MULTIPOINT && type!=FShape.NULL) { Rectangle2D geomBounds = geom.getBounds2D(); // ICoordTrans ct = getCoordTrans(); // Se supone que la geometria ya esta // repoyectada y no hay que hacer // ninguna transformacion // if (ct!=null) { //// geomBounds = ct.getInverted().convert(geomBounds); // geomBounds = ct.convert(geomBounds); // } double dist1Pixel = viewPort.getDist1pixel(); onePoint = (geomBounds.getWidth() <= dist1Pixel && geomBounds.getHeight() <= dist1Pixel); if (onePoint) { // avoid out of range exceptions FPoint2D p = new FPoint2D(geomBounds.getMinX(), geomBounds.getMinY()); p.transform(viewPort.getAffineTransform()); p.transform(graphicsTransform); xyCoords[0] = (int) p.getX(); xyCoords[1] = (int) p.getY(); } } return onePoint; } /* * jaume. Stuff from ILabeled. */ private boolean isLabeled; private ILabelingStrategy strategy; public boolean isLabeled() { return isLabeled; } public void setIsLabeled(boolean isLabeled) { this.isLabeled = isLabeled; } public ILabelingStrategy getLabelingStrategy() { return strategy; } public void setLabelingStrategy(ILabelingStrategy strategy) { this.strategy = strategy; try { strategy.setLayer(this); } catch (ReadDriverException e) { e.printStackTrace(); } } public void drawLabels(BufferedImage image, Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, double dpi) throws ReadDriverException { if (strategy!=null && isWithinScale(scale)) { strategy.draw(image, g, viewPort, cancel, dpi); } } public void printLabels(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties) throws ReadDriverException { if (strategy!=null) { strategy.print(g, viewPort, cancel, properties); } } //Métodos para el uso de HyperLinks en capas FLyerVect /** * Return true, because a Vectorial Layer supports HyperLink */ public boolean allowLinks() { return true; } /** * Returns an instance of AbstractLinkProperties that contains the information * of the HyperLink * @return Abstra */ public AbstractLinkProperties getLinkProperties() { return linkProperties; } /** * Provides an array with URIs. Returns one URI by geometry that includes the point * in its own geometry limits with a allowed tolerance. * @param layer, the layer * @param point, the point to check that is contained or not in the geometries in the layer * @param tolerance, the tolerance allowed. Allowed margin of error to detect if the point * is contained in some geometries of the layer * @return */ public URI[] getLink(Point2D point, double tolerance) { //return linkProperties.getLink(this) return linkProperties.getLink(this,point,tolerance); } public void selectionChanged(SelectionEvent e) { this.updateDrawVersion(); } public void afterFieldEditEvent(AfterFieldEditEvent e) { this.updateDrawVersion(); } public void afterRowEditEvent(IRow feat, AfterRowEditEvent e) { this.updateDrawVersion(); } public void beforeFieldEditEvent(BeforeFieldEditEvent e) { } public void beforeRowEditEvent(IRow feat, BeforeRowEditEvent e) { } public void processEvent(EditionEvent e) { if (e.getChangeType()== e.ROW_EDITION){ this.updateDrawVersion(); } } public void legendCleared(LegendClearEvent event) { this.updateDrawVersion(); LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent( legend, legend); this.callLegendChanged(e); } public boolean symbolChanged(SymbolLegendEvent e) { this.updateDrawVersion(); LegendChangedEvent event = LegendChangedEvent.createLegendChangedEvent( legend, legend); this.callLegendChanged(event); return true; } public String getTypeStringVectorLayer() throws ReadDriverException { String typeString=""; int typeShape=this.getShapeType(); if (FShape.MULTI==typeShape){ ReadableVectorial rv=this.getSource(); int i=0; boolean isCorrect=false; while(rv.getShapeCount()>i && !isCorrect){ IGeometry geom=rv.getShape(i); if (geom==null){ i++; continue; } isCorrect=true; if ((geom.getGeometryType() & FShape.Z) == FShape.Z){ typeString="Geometries3D"; }else{ typeString="Geometries2D"; } } }else{ ReadableVectorial rv=this.getSource(); int i=0; boolean isCorrect=false; while(rv.getShapeCount()>i && !isCorrect){ IGeometry geom=rv.getShape(i); if (geom==null){ i++; continue; } isCorrect=true; int type=geom.getGeometryType(); if (FShape.POINT == type){ typeString="Point2D"; } else if (FShape.LINE == type){ typeString="Line2D"; } else if (FShape.POLYGON == type){ typeString="Polygon2D"; } else if (FShape.MULTIPOINT == type){ typeString="MultiPint2D"; } else if ((FShape.POINT | FShape.Z) == type ){ typeString="Point3D"; } else if ((FShape.LINE | FShape.Z) == type ){ typeString="Line3D"; } else if ((FShape.POLYGON | FShape.Z) == type ){ typeString="Polygon3D"; } else if ((FShape.MULTIPOINT | FShape.Z) == type ){ typeString="MultiPoint3D"; } else if ((FShape.POINT | FShape.M) == type ){ typeString="PointM"; } else if ((FShape.LINE | FShape.M) == type ){ typeString="LineM"; } else if ((FShape.POLYGON | FShape.M) == type ){ typeString="PolygonM"; } else if ((FShape.MULTIPOINT | FShape.M) == type ){ typeString="MultiPointM"; } else if ((FShape.MULTI | FShape.M) == type ){ typeString="M"; } } return typeString; } return ""; } public int getTypeIntVectorLayer() throws ReadDriverException { int typeInt=0; int typeShape=this.getShapeType(); if (FShape.MULTI==typeShape){ ReadableVectorial rv=this.getSource(); int i=0; boolean isCorrect=false; while(rv.getShapeCount()>i && !isCorrect){ IGeometry geom=rv.getShape(i); if (geom==null){ i++; continue; } isCorrect=true; if ((geom.getGeometryType() & FShape.Z) == FShape.Z){ typeInt=FShape.MULTI | FShape.Z; }else{ typeInt=FShape.MULTI; } } }else{ ReadableVectorial rv=this.getSource(); int i=0; boolean isCorrect=false; while(rv.getShapeCount()>i && !isCorrect){ IGeometry geom=rv.getShape(i); if (geom==null){ i++; continue; } isCorrect=true; int type=geom.getGeometryType(); typeInt=type; } return typeInt; } return typeInt; } }
iCarto/siga
libFMap/src/com/iver/cit/gvsig/fmap/layers/FLyrVect.java
Java
gpl-3.0
77,323
/* * 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.items.weapon.missiles.darts; import com.shatteredpixel.shatteredpixeldungeon.actors.Char; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Adrenaline; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff; import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet; public class AdrenalineDart extends TippedDart { { image = ItemSpriteSheet.ADRENALINE_DART; } @Override public int proc(Char attacker, Char defender, int damage) { Buff.prolong( defender, Adrenaline.class, Adrenaline.DURATION); if (attacker.alignment == defender.alignment){ return 0; } return super.proc(attacker, defender, damage); } }
00-Evan/shattered-pixel-dungeon-gdx
core/src/com/shatteredpixel/shatteredpixeldungeon/items/weapon/missiles/darts/AdrenalineDart.java
Java
gpl-3.0
1,505
package eu.ehri.project.models.base; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.frames.modules.javahandler.JavaHandler; import com.tinkerpop.frames.modules.javahandler.JavaHandlerContext; import eu.ehri.project.definitions.Ontology; import eu.ehri.project.models.events.SystemEvent; import eu.ehri.project.models.utils.JavaHandlerUtils; public interface Actioner extends NamedEntity { /** * Fetch a list of Actions for this user in newest-first order. * * @return */ @JavaHandler public Iterable<SystemEvent> getActions(); @JavaHandler public Iterable<SystemEvent> getLatestAction(); /** * Implementation of complex methods. */ abstract class Impl implements JavaHandlerContext<Vertex>, Actioner { public Iterable<SystemEvent> getLatestAction() { return frameVertices(gremlin() .out(Ontology.ACTIONER_HAS_LIFECYCLE_ACTION) .out(Ontology.ENTITY_HAS_EVENT)); } public Iterable<SystemEvent> getActions() { return frameVertices(gremlin().as("n").out(Ontology.ACTIONER_HAS_LIFECYCLE_ACTION) .loop("n", JavaHandlerUtils.noopLoopFunc, JavaHandlerUtils.noopLoopFunc) .out(Ontology.ENTITY_HAS_EVENT)); } } }
lindareijnhoudt/neo4j-ehri-plugin
ehri-frames/src/main/java/eu/ehri/project/models/base/Actioner.java
Java
gpl-3.0
1,321
package net.minecraft.src; public class BlockJukeBox extends BlockContainer { protected BlockJukeBox(int par1) { super(par1, Material.wood); this.setCreativeTab(CreativeTabs.tabDecorations); } /** * Called upon block activation (right click on the block.) */ public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { if (par1World.getBlockMetadata(par2, par3, par4) == 0) { return false; } else { this.ejectRecord(par1World, par2, par3, par4); return true; } } /** * Insert the specified music disc in the jukebox at the given coordinates */ public void insertRecord(World par1World, int par2, int par3, int par4, ItemStack par5ItemStack) { if (!par1World.isRemote) { TileEntityRecordPlayer var6 = (TileEntityRecordPlayer)par1World.getBlockTileEntity(par2, par3, par4); if (var6 != null) { var6.func_96098_a(par5ItemStack.copy()); par1World.setBlockMetadata(par2, par3, par4, 1, 2); } } } /** * Ejects the current record inside of the jukebox. */ public void ejectRecord(World par1World, int par2, int par3, int par4) { if (!par1World.isRemote) { TileEntityRecordPlayer var5 = (TileEntityRecordPlayer)par1World.getBlockTileEntity(par2, par3, par4); if (var5 != null) { ItemStack var6 = var5.func_96097_a(); if (var6 != null) { par1World.playAuxSFX(1005, par2, par3, par4, 0); par1World.playRecord((String)null, par2, par3, par4); var5.func_96098_a((ItemStack)null); par1World.setBlockMetadata(par2, par3, par4, 0, 2); float var7 = 0.7F; double var8 = (double)(par1World.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.5D; double var10 = (double)(par1World.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.2D + 0.6D; double var12 = (double)(par1World.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.5D; ItemStack var14 = var6.copy(); EntityItem var15 = new EntityItem(par1World, (double)par2 + var8, (double)par3 + var10, (double)par4 + var12, var14); var15.delayBeforeCanPickup = 10; par1World.spawnEntityInWorld(var15); } } } } /** * ejects contained items into the world, and notifies neighbours of an update, as appropriate */ public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) { this.ejectRecord(par1World, par2, par3, par4); super.breakBlock(par1World, par2, par3, par4, par5, par6); } /** * Drops the block items with a specified chance of dropping the specified items */ public void dropBlockAsItemWithChance(World par1World, int par2, int par3, int par4, int par5, float par6, int par7) { if (!par1World.isRemote) { super.dropBlockAsItemWithChance(par1World, par2, par3, par4, par5, par6, 0); } } /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ public TileEntity createNewTileEntity(World par1World) { return new TileEntityRecordPlayer(); } /** * If this returns true, then comparators facing away from this block will use the value from * getComparatorInputOverride instead of the actual redstone signal strength. */ public boolean hasComparatorInputOverride() { return true; } /** * If hasComparatorInputOverride returns true, the return value from this is used instead of the redstone signal * strength when this block inputs to a comparator. */ public int getComparatorInputOverride(World par1World, int par2, int par3, int par4, int par5) { ItemStack var6 = ((TileEntityRecordPlayer)par1World.getBlockTileEntity(par2, par3, par4)).func_96097_a(); return var6 == null ? 0 : var6.itemID + 1 - Item.record13.itemID; } }
herpingdo/Hakkit
net/minecraft/src/BlockJukeBox.java
Java
gpl-3.0
4,434
import com.jogamp.opengl.*; import com.jogamp.opengl.awt.GLJPanel; import com.jogamp.opengl.fixedfunc.GLMatrixFunc; import com.jogamp.opengl.glu.GLU; import javax.swing.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import static com.jogamp.opengl.GL.GL_COLOR_BUFFER_BIT; import static com.jogamp.opengl.GL.GL_DEPTH_BUFFER_BIT; /** * This program demonstrates geometric primitives and their attributes. * * @author Kiet Le (Java port) Ported to JOGL 2.x by Claudio Eduardo Goes */ public class LinesDemo// // extends GLSkeleton<GLJPanel> implements GLEventListener, KeyListener { private GLU glu; // public static void main(String[] args) { // final GLCanvas glcanvas = createCanvas(); // // final JFrame frame = new JFrame("Basic Frame"); // // frame.getContentPane().add(glcanvas); // frame.setSize(frame.getContentPane().getPreferredSize()); // frame.setVisible(true); // // frame.repaint(); // } // public static GLCanvas createCanvas() { // final GLProfile profile = GLProfile.get(GLProfile.GL2); // GLCapabilities capabilities = new GLCapabilities(profile); // // final GLCanvas glcanvas = new GLCanvas(capabilities); // LinesDemo b = new LinesDemo(); // glcanvas.addGLEventListener(b); //// glcanvas.setSize(screenSize, screenSize); // // return glcanvas; // } // @Override protected GLJPanel createDrawable() { GLCapabilities caps = new GLCapabilities(null); // GLJPanel panel = new GLJPanel(caps); panel.addGLEventListener(this); panel.addKeyListener(this); return panel; } public void run() { GLJPanel demo = createDrawable(); JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("LinesDemo"); frame.setSize(400, 150); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(demo); frame.setVisible(true); demo.requestFocusInWindow(); } public static void main(String[] args) { new LinesDemo().run(); } public void init(GLAutoDrawable drawable) { GL2 gl = drawable.getGL().getGL2(); glu = new GLU(); // gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); gl.glShadeModel(GL2.GL_FLAT); } public void display(GLAutoDrawable drawable) { GL2 gl = drawable.getGL().getGL2(); // int i; float coordinateSize = 300; // gl.glClear(GL.GL_COLOR_BUFFER_BIT); gl.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // gl.glClearColor(1f, 1f, 1f, 1f); // gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION); // gl.glLoadIdentity(); // gl.glOrtho(-coordinateSize, coordinateSize, -coordinateSize, coordinateSize, -1, 1); /* select white for all LinesDemo */ gl.glColor3f(1.0f, 1.0f, 1.0f); /* in 1st row, 3 LinesDemo, each with a different stipple */ gl.glEnable(GL2.GL_LINE_STIPPLE); gl.glEnable(GL2.GL_POINT_SMOOTH); gl.glBegin(GL2.GL_POINTS); gl.glPointSize(10e5f); gl.glVertex2i(200, 200); gl.glEnd(); gl.glDisable(GL2.GL_POINT_SMOOTH); gl.glLineStipple(1, (short) 0x0101); /* dotted */ drawOneLine(gl, 50.0f, 125.0f, 150.0f, 125.0f); gl.glLineStipple(1, (short) 0x00FF); /* dashed */ drawOneLine(gl, 150.0f, 125.0f, 250.0f, 125.0f); drawOneLine(gl, 150.0f, 125.0f, 250.0f, 200f); gl.glLineStipple(1, (short) 0x1C47); /* dash/dot/dash */ drawOneLine(gl, 250.0f, 125.0f, 350.0f, 125.0f); /* in 2nd row, 3 wide LinesDemo, each with different stipple */ gl.glLineWidth(5.0f); gl.glLineStipple(1, (short) 0x0101); /* dotted */ drawOneLine(gl, 50.0f, 100.0f, 150.0f, 100.f); gl.glLineStipple(1, (short) 0x00FF); /* dashed */ drawOneLine(gl, 150.0f, 100.0f, 250.0f, 100.0f); gl.glLineStipple(1, (short) 0x1C47); /* dash/dot/dash */ drawOneLine(gl, 250.0f, 100.0f, 350.0f, 100.0f); gl.glLineWidth(1.0f); /* in 3rd row, 6 LinesDemo, with dash/dot/dash stipple */ /* as part of a single connected line strip */ gl.glLineStipple(1, (short) 0x1C47); /* dash/dot/dash */ gl.glBegin(GL.GL_LINE_STRIP); for (i = 0; i < 7; i++) gl.glVertex2f(50.0f + ((float) i * 50.0f), 75.0f); gl.glEnd(); /* in 4th row, 6 independent LinesDemo with same stipple */ for (i = 0; i < 6; i++) { drawOneLine(gl, 50.0f + ((float) i * 50.0f), 50.0f, 50.0f + ((float) (i + 1) * 50.0f), 50.0f); } /* in 5th row, 1 line, with dash/dot/dash stipple */ /* and a stipple repeat factor of 5 */ gl.glLineStipple(5, (short) 0x1C47); /* dash/dot/dash */ drawOneLine(gl, 50.0f, 25.0f, 350.0f, 25.0f); gl.glDisable(GL2.GL_LINE_STIPPLE); gl.glFlush(); } public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) { GL2 gl = drawable.getGL().getGL2(); // gl.glViewport(0, 0, w, h); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); glu.gluOrtho2D(0.0, (double) w, 0.0, (double) h); } public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { } private void drawOneLine(GL2 gl, float x1, float y1, float x2, float y2) { // gl.glBegin(GL.GL_LINES); gl.glVertex2f((x1), (y1)); gl.glVertex2f((x2), (y2)); // gl.glEnd(); } public void keyTyped(KeyEvent key) { } public void keyPressed(KeyEvent key) { switch (key.getKeyCode()) { case KeyEvent.VK_ESCAPE: System.exit(0); break; default: break; } } public void keyReleased(KeyEvent key) { } public void dispose(GLAutoDrawable arg0) { } }
Tiofx/semester_6
CG/src/LinesDemo.java
Java
gpl-3.0
6,151
import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; 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 com.ofte.services.MetaDataCreations; /** * Servlet implementation class ScheduledTransferRemoteasDestination */ @SuppressWarnings("serial") @WebServlet("/ScheduledTransferRemoteasDestination") public class ScheduledTransferRemoteasDestination extends HttpServlet { // private static final long serialVersionUID = 1L; HashMap<String, String> hashMap = new HashMap<String, String>(); // com.ofte.services.MetaDataCreations metaDataCreations = new // MetaDataCreations(); MetaDataCreations metaDataCreations = new MetaDataCreations(); /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // read form fields String schedulername = request.getParameter("schedulername"); // String jobName = request.getParameter("jname"); String sourceDirectory = request.getParameter("sd"); String sourceTriggerPattern = request.getParameter("stp"); String sourceFilePattern = request.getParameter("sfp"); String destinationDirectory = request.getParameter("dd"); String destinationFilePattern = request.getParameter("dfp"); String destinationTriggerPattern = request.getParameter("dtp"); String hostIp = request.getParameter("hostip"); String userName = request.getParameter("username"); String password = request.getParameter("password"); String port = request.getParameter("port"); String pollUnits = request.getParameter("pu"); String pollInterval = request.getParameter("pi"); // String XMLFilePath = request.getParameter("xmlfilename"); HashMap<String, String> hashMap = new HashMap<>(); hashMap.put("-sn", schedulername); // hashMap.put("-jn", jobName); hashMap.put("-sd", sourceDirectory); hashMap.put("-tr", sourceTriggerPattern); hashMap.put("-sfp", sourceFilePattern); hashMap.put("-sftp-d", destinationDirectory); hashMap.put("-trd", destinationTriggerPattern); hashMap.put("-hi", hostIp); hashMap.put("-un", userName); hashMap.put("-pw", password); hashMap.put("-po", port); hashMap.put("-pu", pollUnits); hashMap.put("-pi", pollInterval); hashMap.put("-dfp", destinationFilePattern); // hashMap.put("-gt", XMLFilePath); // System.out.println(hashMap); // System.out.println("username: " + username); // System.out.println("password: " + password); // String str[] = {"-mn "+monitorName,"-jn "+jobName,"-sd // "+sourceDirectory,"-tr "+sourceTriggerPattern,"-sfp // "+sourceFilePattern,"-dd // "+destinationDirectory,destinationFilePattern,"-trd // "+destinationTriggerPattern,"-pu "+pollUnits,"-pi "+pollInterval,"-gt // "+XMLFilePath}; // for(int i=0;i<str.length;i++) { // System.out.println(str[i]); // } try { // metaDataCreations.fetchingUIDetails(hashMap); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // String string = "-mn "+monitorName+",-jn "+jobName+",-pi // "+pollInterval+",-pu "+pollUnits+",-dd "+destinationDirectory+" "+ // sourceDirectory+",-tr "+sourceTriggerPattern+",-trd // "+destinationTriggerPattern+",-gt "+XMLFilePath+",-sfp // "+sourceFilePattern; // FileWriter fileWriter = new FileWriter("D:\\UIDetails.txt"); // fileWriter.write(string); // fileWriter.close(); Runnable r = new Runnable() { public void run() { // runYourBackgroundTaskHere(); try { metaDataCreations.fetchingUIDetails(hashMap); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; new Thread(r).start(); // Example example = new Example(); // hashMap.put("monitorName", monitorName); // example.result("-mn "+monitorName+" -jn "+jobName+" -pi // "+pollInterval+" -pu "+pollUnits+" -dd "+destinationDirectory+" "+ // sourceDirectory+" -tr "+sourceTriggerPattern+" -trd // "+destinationTriggerPattern+" -gt "+XMLFilePath+" -sfp // "+sourceFilePattern); // do some processing here... // get response writer // PrintWriter writer = response.getWriter(); // build HTML code // String htmlRespone = "<html>"; // htmlRespone += "<h2>Your username is: " + username + "<br/>"; // htmlRespone += "Your password is: " + password + "</h2>"; // htmlRespone += "</html>"; // return response // writer.println(htmlRespone); PrintWriter out = response.getWriter(); response.setContentType("text/html"); out.println("<script type=\"text/javascript\">"); out.println("alert('successfully submited');"); out.println( "window.open('http://localhost:8080/TestingUI/Open_OFTE_Scheduled_Transfers_Page.html','_self')"); out.println("</script>"); } }
MithunThadi/OFTE
SourceCode/new ofte with del monitor/servlet/ScheduledTransferRemoteasDestination.java
Java
gpl-3.0
5,035
package xde.lincore.mcscript.math; public enum RoundingMethod { Round, Floor, Ceil, CastInt; public int round(final double value) { switch (this) { case Round: return (int) Math.round(value); case Floor: return (int) Math.floor(value); case Ceil: return (int) Math.ceil(value); case CastInt: return (int) value; default: throw new UnsupportedOperationException(); } } public long roundToLong(final double value) { switch (this) { case Round: return Math.round(value); case Floor: return (long) Math.floor(value); case Ceil: return (long) Math.ceil(value); case CastInt: return (long) value; default: throw new UnsupportedOperationException(); } } }
lincore81/mcscript
ScriptMod/src/xde/lincore/mcscript/math/RoundingMethod.java
Java
gpl-3.0
741
package com.baselet.gwt.client.view; import java.util.List; import com.baselet.control.basics.geom.Rectangle; import com.baselet.control.config.SharedConfig; import com.baselet.control.enums.ElementId; import com.baselet.element.Selector; import com.baselet.element.interfaces.GridElement; import com.baselet.gwt.client.element.ComponentGwt; import com.baselet.gwt.client.element.ElementFactoryGwt; import com.baselet.gwt.client.resources.HelptextFactory; import com.baselet.gwt.client.resources.HelptextResources; import com.google.gwt.canvas.client.Canvas; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.CanvasElement; import com.google.gwt.user.client.ui.FocusWidget; public class DrawCanvas { private final Canvas canvas = Canvas.createIfSupported(); /* setScaling can be used to set the size the canvas for the next time draw() is used DISCLAIMER: if scaling is set to anything other than 1, this WILL break the way selected elements are viewed, furthermore the dragging will still remain the same and will not update to the new scale. This function is solely meant to be used for high-res exporting of the diagram */ private double scaling = 1.0d; private boolean scaleHasChangedSinceLastDraw = false; public void setScaling(double scaling) { this.scaling = scaling; scaleHasChangedSinceLastDraw = true; } void draw(boolean drawEmptyInfo, List<GridElement> gridElements, Selector selector, boolean forceRedraw) { if (SharedConfig.getInstance().isDev_mode()) { CanvasUtils.drawGridOn(getContext2d()); } if (drawEmptyInfo && gridElements.isEmpty()) { drawEmptyInfoText(getScaling()); } else { // if (tryOptimizedDrawing()) return; for (GridElement ge : gridElements) { if (forceRedraw) { ((ComponentGwt) ge.getComponent()).afterModelUpdate(); } ((ComponentGwt) ge.getComponent()).drawOn(getContext2d(), selector.isSelected(ge), getScaling()); } } if (selector instanceof SelectorNew && ((SelectorNew) selector).isLassoActive()) { ((SelectorNew) selector).drawLasso(getContext2d()); } } public void draw(boolean drawEmptyInfo, List<GridElement> gridElements, Selector selector) { if (isScaleHasChangedSinceLastDraw()) { draw(drawEmptyInfo, gridElements, selector, true); setScaleHasChangedSinceLastDraw(false); } else { draw(drawEmptyInfo, gridElements, selector, false); } } public double getScaling() { return scaling; } public boolean isScaleHasChangedSinceLastDraw() { return scaleHasChangedSinceLastDraw; } public void setScaleHasChangedSinceLastDraw(boolean scaleHasChangedSinceLastDraw) { this.scaleHasChangedSinceLastDraw = scaleHasChangedSinceLastDraw; } public Context2dWrapper getContext2d() { return new Context2dGwtWrapper(canvas.getContext2d()); } public void clearAndSetSize(int width, int height) { // setCoordinateSpace always clears the canvas. To avoid that see https://groups.google.com/d/msg/google-web-toolkit/dpc84mHeKkA/3EKxrlyFCEAJ canvas.setCoordinateSpaceWidth(width); canvas.setCoordinateSpaceHeight(height); } public String toDataUrl(String type) { return canvas.toDataUrl(type); } public void drawEmptyInfoText(double scaling) { double elWidth = 440; double elHeight = 246; double elXPos = getWidth() / 2.0 - elWidth / 2; double elYPos = getHeight() / 2.0 - elHeight / 2; HelptextFactory factory = GWT.create(HelptextFactory.class); HelptextResources resources = factory.getInstance(); String helptext = resources.helpText().getText(); GridElement emptyElement = ElementFactoryGwt.create(ElementId.Text, new Rectangle(elXPos, elYPos, elWidth, elHeight), helptext, "", null); ((ComponentGwt) emptyElement.getComponent()).drawOn(getContext2d(), false, scaling); } /* used to display temporal invalid if vs code passes a wrong uxf */ void drawInvalidDiagramInfo() { double elWidth = 440; double elHeight = 246; double elXPos = getWidth() / 2.0 - elWidth / 2; double elYPos = getHeight() / 2.0 - elHeight / 2; String invalidDiagramText = "valign=center\n" + "halign=center\n" + ".uxf file is currently invalid and can't be displayed.\n" + "Please revert changes or load a valid file"; GridElement emptyElement = ElementFactoryGwt.create(ElementId.Text, new Rectangle(elXPos, elYPos, elWidth, elHeight), invalidDiagramText, "", null); ((ComponentGwt) emptyElement.getComponent()).drawOn(getContext2d(), false, getScaling()); } public int getWidth() { return canvas.getCoordinateSpaceWidth(); } public int getHeight() { return canvas.getCoordinateSpaceHeight(); } public CanvasElement getCanvasElement() { return canvas.getCanvasElement(); } public FocusWidget getWidget() { return canvas; } // TODO would not work because canvas gets always resized and therefore cleaned -> so everything must be redrawn // private boolean tryOptimizedDrawing() { // List<GridElement> geToRedraw = new ArrayList<GridElement>(); // for (GridElement ge : gridElements) { // if(((GwtComponent) ge.getComponent()).isRedrawNecessary()) { // for (GridElement geRedraw : geToRedraw) { // if (geRedraw.getRectangle().intersects(ge.getRectangle())) { // return false; // } // } // geToRedraw.add(ge); // } // } // // for (GridElement ge : gridElements) { // elementCanvas.getContext2d().clearRect(0, 0, ge.getRectangle().getWidth(), ge.getRectangle().getHeight()); // ((GwtComponent) ge.getComponent()).drawOn(elementCanvas.getContext2d()); // } // return true; // } }
umlet/umlet
umlet-gwt/src/main/java/com/baselet/gwt/client/view/DrawCanvas.java
Java
gpl-3.0
5,538
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.sk89q.worldedit.internal.registry; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.input.NoMatchException; import java.util.ArrayList; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; /** * An abstract implementation of a factory for internal usage. * * @param <E> the element that the factory returns */ public abstract class AbstractFactory<E> { protected final WorldEdit worldEdit; protected final List<InputParser<E>> parsers = new ArrayList<InputParser<E>>(); /** * Create a new factory. * * @param worldEdit the WorldEdit instance */ protected AbstractFactory(WorldEdit worldEdit) { checkNotNull(worldEdit); this.worldEdit = worldEdit; } public E parseFromInput(String input, ParserContext context) throws InputParseException { E match; for (InputParser<E> parser : parsers) { match = parser.parseFromInput(input, context); if (match != null) { return match; } } throw new NoMatchException("No match for '" + input + "'"); } }
UnlimitedFreedom/UF-WorldEdit
worldedit-core/src/main/java/com/sk89q/worldedit/internal/registry/AbstractFactory.java
Java
gpl-3.0
2,120
package com.derpgroup.livefinder.manager; import java.util.Arrays; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class TwitchFollowedStreamsResponse { private TwitchStream[] streams; public TwitchStream[] getStreams() { return streams.clone(); } public void setStreams(TwitchStream[] streams) { this.streams = streams.clone(); } @Override public String toString() { return "TwitchFollowedStreamsResponse [streams=" + Arrays.toString(streams) + "]"; } }
DERP-Group/LiveFinder
service/src/main/java/com/derpgroup/livefinder/manager/TwitchFollowedStreamsResponse.java
Java
gpl-3.0
563
package osberbot.bo; /** * TODO: Description * * @author Tititesouris * @since 2016/03/20 */ public class ViewerBO { private Integer id; private String name; private Boolean moderator; private RankBO rank; public ViewerBO(Integer id, String name, RankBO rank) { this.id = id; this.name = name; this.rank = rank; } public boolean hasPower(PowerBO power) { if (rank != null) return rank.hasPower(power); return moderator; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public RankBO getRank() { return rank; } public void setRank(RankBO rank) { this.rank = rank; } }
Tititesouris/OsberBot
src/osberbot/bo/ViewerBO.java
Java
gpl-3.0
900
package miscellaneous; import java.util.Arrays; public class Gen { private static int greyCode(int n1){ return n1 ^ (n1 >> 1); } /* * Advances l1 to next lexicographical higher combination. * cap is the largest value allowed for one index. * return false */ public static boolean nextComb(int[] l1, int cap){ for (int ptr = l1.length-1;;){ if (ptr < 0) return false; if (l1[ptr] == cap - 1){ l1[ptr] = 0; ptr--; } else { l1[ptr]++; break; } } return true; } /* * Advances l1 to next lexicographical higher permutation. * 1 * Find the highest index i such that s[i] < s[i+1]. * If no such index exists, the permutation is the last permutation. * 2 * Find the highest index j > i such that s[j] > s[i]. * Such a j must exist, since i+1 is such an index. * 3 * Swap s[i] with s[j]. * 4 * Reverse all the order of all of the elements after index i */ public static void swap(int[] l1, int a, int b){ int k1 = l1[a];l1[a]=l1[b];l1[b]=k1; } public static void rev(int[] l1, int a, int b){ for (int i = 0; i < (b-a+1)/2;i++) swap(l1,a+i,b-i); } public static boolean nextPerm(int[] l1) { for (int i = l1.length- 2; i >=0; i--) { if (l1[i] < l1[i + 1]){ for (int k = l1.length - 1; k>=0;k--){ if (l1[k]>=l1[i]){ swap(l1,i,k); rev(l1,i+1,l1.length-1); return true; } } } } rev(l1,0,l1.length-1); return false; } public static int[] permInv(int[] l1){ int[] fin = new int[l1.length]; for (int i = 0; i< l1.length;i++){ fin[l1[i]]=i; } return fin; } }
cs6096/contest-library
src/miscellaneous/Gen.java
Java
gpl-3.0
1,729
package com.xcode.bean; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; @ManagedBean @SessionScoped public class UserAuth implements Serializable { /** * */ private static final long serialVersionUID = 4027678448802658446L; private String email; public UserAuth() { SecurityContext context = SecurityContextHolder.getContext(); Authentication auth = context.getAuthentication(); email = auth.getName(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
georgematos/ocaert
src/com/xcode/bean/UserAuth.java
Java
gpl-3.0
838
package Yogibear617.mods.FuturisticCraft.CreativeTabs; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; public class FCSBModCreativeTab extends CreativeTabs { public FCSBModCreativeTab(int par1, String par2Str) { super(par1, par2Str); } @SideOnly(Side.CLIENT) public int getTabIconItemIndex() { return Block.stoneBrick.blockID; } }
Yogibear617/Futuristic_Craft
fc_common/Yogibear617/mods/FuturisticCraft/CreativeTabs/FCSBModCreativeTab.java
Java
gpl-3.0
455
package com.eveningoutpost.dexdrip.Models; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; // from package info.nightscout.client.utils; /** * Created by mike on 30.12.2015. */ /** * The Class DateUtil. A simple wrapper around SimpleDateFormat to ease the handling of iso date string &lt;-&gt; date obj * with TZ */ public class DateUtil { private static final String FORMAT_DATE_ISO = "yyyy-MM-dd'T'HH:mm:ss'Z'"; // eg 2017-03-24T22:03:27Z private static final String FORMAT_DATE_ISO2 = "yyyy-MM-dd'T'HH:mm:ssZ"; // eg 2017-03-27T17:38:14+0300 private static final String FORMAT_DATE_ISO3 = "yyyy-MM-dd'T'HH:mmZ"; // eg 2017-05-12T08:16-0400 /** * Takes in an ISO date string of the following format: * yyyy-mm-ddThh:mm:ss.ms+HoMo * * @param isoDateString the iso date string * @return the date * @throws Exception the exception */ private static Date fromISODateString(String isoDateString) throws Exception { SimpleDateFormat f = new SimpleDateFormat(FORMAT_DATE_ISO); f.setTimeZone(TimeZone.getTimeZone("UTC")); return f.parse(isoDateString); } private static Date fromISODateString3(String isoDateString) throws Exception { SimpleDateFormat f = new SimpleDateFormat(FORMAT_DATE_ISO3); f.setTimeZone(TimeZone.getTimeZone("UTC")); return f.parse(isoDateString); } private static Date fromISODateString2(String isoDateString) throws Exception { try { SimpleDateFormat f = new SimpleDateFormat(FORMAT_DATE_ISO2); f.setTimeZone(TimeZone.getTimeZone("UTC")); return f.parse(isoDateString); } catch (java.text.ParseException e) { return fromISODateString3(isoDateString); } } public static Date tolerantFromISODateString(String isoDateString) throws Exception { try { return fromISODateString(isoDateString.replaceFirst("\\.[0-9][0-9][0-9]Z$", "Z")); } catch (java.text.ParseException e) { return fromISODateString2(isoDateString); } } /** * Render date * * @param date the date obj * @param format - if not specified, will use FORMAT_DATE_ISO * @param tz - tz to set to, if not specified uses local timezone * @return the iso-formatted date string */ public static String toISOString(Date date, String format, TimeZone tz) { if (format == null) format = FORMAT_DATE_ISO; if (tz == null) tz = TimeZone.getDefault(); DateFormat f = new SimpleDateFormat(format); f.setTimeZone(tz); return f.format(date); } public static String toISOString(Date date) { return toISOString(date, FORMAT_DATE_ISO, TimeZone.getTimeZone("UTC")); } public static String toISOString(long date) { return toISOString(new Date(date), FORMAT_DATE_ISO, TimeZone.getTimeZone("UTC")); } public static String toNightscoutFormat(long date) { final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US); format.setTimeZone(TimeZone.getDefault()); return format.format(date); } }
TecMunky/xDrip
app/src/main/java/com/eveningoutpost/dexdrip/Models/DateUtil.java
Java
gpl-3.0
3,340
/* * Copyright (C) 2017 GedMarc * * 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.jwebmp.core.htmlbuilder.css.displays; import com.jwebmp.core.base.client.CSSVersions; import com.jwebmp.core.htmlbuilder.css.CSSEnumeration; import com.jwebmp.core.htmlbuilder.css.annotations.CSSAnnotationType; /** * Definition and Usage * <p> * The display property defines how a certain HTML element should be displayed. * Default value: inline Inherited: no Version: * CSS1 JavaScript syntax: object.style.display="inline" * * @author GedMarc * @version 1.0 * @since 2013/01/22 */ @CSSAnnotationType public enum Displays implements CSSEnumeration<Displays> { /** * Default value. Displays an element as an inline element (like &lt;span&gt;) */ Inline, /** * Displays an element as a block element (like * &lt;p&gt; * ) */ Block, /** * Displays an element as an block_level flex container. New in CSS3 */ Flex, /** * Displays an element as an inline_level flex container. New in CSS3 */ Inline_flex, /** * The element is displayed as an inline_level table */ Inline_table, /** * Let the element behave like a &lt;li&gt; element */ List_item, /** * Displays an element as either block or inline, depending on context */ Run_in, /** * Let the element behave like a &lt;table&gt; element */ Table, /** * Let the element behave like a &lt;caption&gt; element */ Table_caption, /** * Let the element behave like a &lt;colgroup&gt; element */ Table_column_group, /** * Let the element behave like a &lt;thead&gt; element */ Table_header_group, /** * Let the element behave like a &lt;tfoot&gt; element */ Table_footer_group, /** * Let the element behave like a &lt;tbody&gt; element */ Table_row_group, /** * Let the element behave like a &lt;td&gt; element */ Table_cell, /** * Let the element behave like a &lt;col&gt; element */ Table_column, /** * Let the element behave like a &lt;tr&gt; element */ Table_row, /** * The element will not be displayed at all (has no effect on layout) */ None, /** * Sets this property to its default value. Read about initial */ Initial, /** * Inherits this property from its parent element. Read about inherit; */ Inherit, /** * Sets this field as not set */ Unset; @Override public String getJavascriptSyntax() { return "style.display"; } @Override public CSSVersions getCSSVersion() { return CSSVersions.CSS1; } @Override public String getValue() { return name(); } @Override public Displays getDefault() { return Unset; } @Override public String toString() { return super.toString() .toLowerCase() .replaceAll("_", "-"); } }
GedMarc/JWebSwing
src/main/java/com/jwebmp/core/htmlbuilder/css/displays/Displays.java
Java
gpl-3.0
3,363
package com.projectreddog.machinemod.container; import com.projectreddog.machinemod.inventory.SlotBlazePowder; import com.projectreddog.machinemod.inventory.SlotNotBlazePowder; import com.projectreddog.machinemod.inventory.SlotOutputOnlyTurobFurnace; import com.projectreddog.machinemod.tileentities.TileEntityTurboFurnace; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IContainerListener; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; ; public class ContainerTurboFurnace extends Container { protected TileEntityTurboFurnace turbofurnace; protected int lastFuleBurnTimeRemaining = 0; protected int lastProcessingTimeRemaining = 0; public ContainerTurboFurnace(InventoryPlayer inventoryPlayer, TileEntityTurboFurnace turbofurnace) { this.turbofurnace = turbofurnace; lastFuleBurnTimeRemaining = -1; lastProcessingTimeRemaining = -1; // for (int i = 0; i < 1; i++) { // for (int j = 0; j < 3; j++) { addSlotToContainer(new SlotNotBlazePowder(turbofurnace, 0, 47, 34)); addSlotToContainer(new SlotOutputOnlyTurobFurnace(inventoryPlayer.player, turbofurnace, 1, 110, 53)); addSlotToContainer(new SlotBlazePowder(turbofurnace, 2, 47, 74)); // } // } // commonly used vanilla code that adds the player's inventory bindPlayerInventory(inventoryPlayer); } @Override public boolean canInteractWith(EntityPlayer player) { return turbofurnace.isUsableByPlayer(player); } protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, 139 + i * 18)); } } for (int i = 0; i < 9; i++) { addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 197)); } } @Override public ItemStack transferStackInSlot(EntityPlayer player, int slot) { ItemStack stack = ItemStack.EMPTY; Slot slotObject = (Slot) inventorySlots.get(slot); // null checks and checks if the item can be stacked (maxStackSize > 1) if (slotObject != null && slotObject.getHasStack()) { ItemStack stackInSlot = slotObject.getStack(); stack = stackInSlot.copy(); // merges the item into player inventory since its in the Entity if (slot < 3) { if (!this.mergeItemStack(stackInSlot, 3, this.inventorySlots.size(), true)) { return ItemStack.EMPTY; } slotObject.onSlotChange(stackInSlot, stack); } // places it into the tileEntity is possible since its in the player // inventory else if (!this.mergeItemStack(stackInSlot, 0, 3, false)) { return ItemStack.EMPTY; } if (stackInSlot.getCount() == 0) { slotObject.putStack(ItemStack.EMPTY); } else { slotObject.onSlotChanged(); } if (stackInSlot.getCount() == stack.getCount()) { return ItemStack.EMPTY; } slotObject.onTake(player, stackInSlot); } return stack; } /** * Looks for changes made in the container, sends them to every listener. */ public void detectAndSendChanges() { super.detectAndSendChanges(); for (int i = 0; i < this.listeners.size(); ++i) { IContainerListener icrafting = (IContainerListener) this.listeners.get(i); if (this.lastFuleBurnTimeRemaining != this.turbofurnace.getField(0)) { icrafting.sendWindowProperty(this, 0, this.turbofurnace.getField(0)); } if (this.lastProcessingTimeRemaining != this.turbofurnace.getField(1)) { icrafting.sendWindowProperty(this, 1, this.turbofurnace.getField(1)); } } this.lastFuleBurnTimeRemaining = this.turbofurnace.getField(0); this.lastProcessingTimeRemaining = this.turbofurnace.getField(1); } @SideOnly(Side.CLIENT) public void updateProgressBar(int id, int data) { this.turbofurnace.setField(id, data); } }
TechStack/TechStack-s-HeavyMachineryMod
src/main/java/com/projectreddog/machinemod/container/ContainerTurboFurnace.java
Java
gpl-3.0
3,980
/* * Copyright (C) 2004 NNL Technology AB * Visit www.infonode.net for information about InfoNode(R) * products and how to contact NNL Technology AB. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ // $Id: Info.java,v 1.6 2004/09/22 14:31:39 jesper Exp $ package com.supermap.desktop.ui.docking.info; import com.supermap.desktop.ui.docking.DockingWindowsReleaseInfo; import net.infonode.gui.ReleaseInfoDialog; import net.infonode.gui.laf.InfoNodeLookAndFeelReleaseInfo; import net.infonode.tabbedpanel.TabbedPanelReleaseInfo; import net.infonode.util.ReleaseInfo; /** * Program that shows InfoNode Docking Windows release information in a dialog. * * @author $Author: jesper $ * @version $Revision: 1.6 $ */ public class Info { private Info() { } public static final void main(String[] args) { ReleaseInfoDialog.showDialog(new ReleaseInfo[]{DockingWindowsReleaseInfo.getReleaseInfo(), TabbedPanelReleaseInfo.getReleaseInfo(), InfoNodeLookAndFeelReleaseInfo.getReleaseInfo()}, null); System.exit(0); } }
highsad/iDesktop-Cross
Controls/src/com/supermap/desktop/ui/docking/info/Info.java
Java
gpl-3.0
1,846
package net.seabears.game.entities.normalmap; import static java.util.stream.IntStream.range; import java.io.IOException; import java.util.List; import org.joml.Matrix4f; import org.joml.Vector3f; import org.joml.Vector4f; import net.seabears.game.entities.Entity; import net.seabears.game.entities.Light; import net.seabears.game.shadows.ShadowShader; import net.seabears.game.textures.ModelTexture; import net.seabears.game.util.TransformationMatrix; public class NormalMappingShader extends ShadowShader { public static final int TEXTURE_SHADOW = 2; private final int lights; private int locationClippingPlane; private int locationModelTexture; private int locationNormalMap; private int[] locationLightAttenuation; private int[] locationLightColor; private int[] locationLightPosition; private int locationProjectionMatrix; private int locationReflectivity; private int locationShineDamper; private int locationSkyColor; private int locationTextureRows; private int locationTextureOffset; private int locationTransformationMatrix; private int locationViewMatrix; public NormalMappingShader(int lights) throws IOException { super(SHADER_ROOT + "normalmap/", TEXTURE_SHADOW); this.lights = lights; } @Override protected void bindAttributes() { super.bindAttribute(ATTR_POSITION, "position"); super.bindAttribute(ATTR_TEXTURE, "textureCoords"); super.bindAttribute(ATTR_NORMAL, "normal"); super.bindAttribute(ATTR_TANGENT, "tangent"); } @Override protected void getAllUniformLocations() { super.getAllUniformLocations(); locationClippingPlane = super.getUniformLocation("clippingPlane"); locationModelTexture = super.getUniformLocation("modelTexture"); locationNormalMap = super.getUniformLocation("normalMap"); locationLightAttenuation = super.getUniformLocations("attenuation", lights); locationLightColor = super.getUniformLocations("lightColor", lights); locationLightPosition = super.getUniformLocations("lightPosition", lights); locationProjectionMatrix = super.getUniformLocation("projectionMatrix"); locationReflectivity = super.getUniformLocation("reflectivity"); locationShineDamper = super.getUniformLocation("shineDamper"); locationSkyColor = super.getUniformLocation("skyColor"); locationTextureRows = super.getUniformLocation("textureRows"); locationTextureOffset = super.getUniformLocation("textureOffset"); locationTransformationMatrix = super.getUniformLocation("transformationMatrix"); locationViewMatrix = super.getUniformLocation("viewMatrix"); } public void loadClippingPlane(Vector4f plane) { this.loadFloat(locationClippingPlane, plane); } public void loadLights(final List<Light> lights, Matrix4f viewMatrix) { range(0, this.lights) .forEach(i -> loadLight(i < lights.size() ? lights.get(i) : OFF_LIGHT, i, viewMatrix)); } private void loadLight(Light light, int index, Matrix4f viewMatrix) { super.loadFloat(locationLightAttenuation[index], light.getAttenuation()); super.loadFloat(locationLightColor[index], light.getColor()); super.loadFloat(locationLightPosition[index], getEyeSpacePosition(light.getPosition(), viewMatrix)); } public void loadProjectionMatrix(Matrix4f matrix) { super.loadMatrix(locationProjectionMatrix, matrix); } public void loadSky(Vector3f color) { super.loadFloat(locationSkyColor, color); } public void loadNormalMap() { // refers to texture units // TEXTURE_SHADOW occupies one unit super.loadInt(locationModelTexture, 0); super.loadInt(locationNormalMap, 1); } public void loadTexture(ModelTexture texture) { super.loadFloat(locationReflectivity, texture.getReflectivity()); super.loadFloat(locationShineDamper, texture.getShineDamper()); super.loadFloat(locationTextureRows, texture.getRows()); } public void loadEntity(Entity entity) { loadTransformationMatrix( new TransformationMatrix(entity.getPosition(), entity.getRotation(), entity.getScale()) .toMatrix()); super.loadFloat(locationTextureOffset, entity.getTextureOffset()); } public void loadTransformationMatrix(Matrix4f matrix) { super.loadMatrix(locationTransformationMatrix, matrix); } public void loadViewMatrix(Matrix4f matrix) { super.loadMatrix(locationViewMatrix, matrix); } private static Vector3f getEyeSpacePosition(Vector3f position, Matrix4f viewMatrix) { final Vector4f eyeSpacePos = new Vector4f(position.x, position.y, position.z, 1.0f); viewMatrix.transform(eyeSpacePos); return new Vector3f(eyeSpacePos.x, eyeSpacePos.y, eyeSpacePos.z); } }
cberes/game
engine/src/main/java/net/seabears/game/entities/normalmap/NormalMappingShader.java
Java
gpl-3.0
4,691
/* * Copyright (C) 2010-2021 JPEXS * * 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.jpexs.decompiler.flash.gui.timeline; import com.jpexs.decompiler.flash.configuration.Configuration; import com.jpexs.decompiler.flash.tags.base.CharacterTag; import com.jpexs.decompiler.flash.tags.base.MorphShapeTag; import com.jpexs.decompiler.flash.timeline.DepthState; import com.jpexs.decompiler.flash.timeline.Timeline; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.SystemColor; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.swing.JPanel; import org.pushingpixels.substance.api.ColorSchemeAssociationKind; import org.pushingpixels.substance.api.ComponentState; import org.pushingpixels.substance.api.DecorationAreaType; import org.pushingpixels.substance.api.SubstanceLookAndFeel; import org.pushingpixels.substance.internal.utils.SubstanceColorUtilities; /** * * @author JPEXS */ public class TimelineBodyPanel extends JPanel implements MouseListener, KeyListener { private final Timeline timeline; public static final Color shapeTweenColor = new Color(0x59, 0xfe, 0x7c); public static final Color motionTweenColor = new Color(0xd1, 0xac, 0xf1); //public static final Color frameColor = new Color(0xbd, 0xd8, 0xfc); public static final Color borderColor = Color.black; public static final Color emptyBorderColor = new Color(0xbd, 0xd8, 0xfc); public static final Color keyColor = Color.black; public static final Color aColor = Color.black; public static final Color stopColor = Color.white; public static final Color stopBorderColor = Color.black; public static final Color borderLinesColor = new Color(0xde, 0xde, 0xde); //public static final Color selectedColor = new Color(113, 174, 235); public static final int borderLinesLength = 2; public static final float fontSize = 10.0f; private final List<FrameSelectionListener> listeners = new ArrayList<>(); public Point cursor = null; private enum BlockType { EMPTY, NORMAL, MOTION_TWEEN, SHAPE_TWEEN } public static Color getEmptyFrameColor() { return SubstanceColorUtilities.getLighterColor(getControlColor(), 0.7); } public static Color getEmptyFrameSecondColor() { return SubstanceColorUtilities.getLighterColor(getControlColor(), 0.9); } public static Color getSelectedColor() { if (Configuration.useRibbonInterface.get()) { return SubstanceLookAndFeel.getCurrentSkin().getColorScheme(DecorationAreaType.GENERAL, ColorSchemeAssociationKind.FILL, ComponentState.ROLLOVER_SELECTED).getBackgroundFillColor(); } else { return SystemColor.textHighlight; } } private static Color getControlColor() { if (Configuration.useRibbonInterface.get()) { return SubstanceLookAndFeel.getCurrentSkin().getColorScheme(DecorationAreaType.GENERAL, ColorSchemeAssociationKind.FILL, ComponentState.ENABLED).getBackgroundFillColor(); } else { return SystemColor.control; } } public static Color getFrameColor() { return SubstanceColorUtilities.getDarkerColor(getControlColor(), 0.1); } public void addFrameSelectionListener(FrameSelectionListener l) { listeners.add(l); } public void removeFrameSelectionListener(FrameSelectionListener l) { listeners.remove(l); } public TimelineBodyPanel(Timeline timeline) { this.timeline = timeline; Dimension dim = new Dimension(TimelinePanel.FRAME_WIDTH * timeline.getFrameCount() + 1, TimelinePanel.FRAME_HEIGHT * timeline.getMaxDepth()); setSize(dim); setPreferredSize(dim); addMouseListener(this); addKeyListener(this); setFocusable(true); } @Override protected void paintComponent(Graphics g1) { Graphics2D g = (Graphics2D) g1; g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(TimelinePanel.getBackgroundColor()); g.fillRect(0, 0, getWidth(), getHeight()); Rectangle clip = g.getClipBounds(); int frameWidth = TimelinePanel.FRAME_WIDTH; int frameHeight = TimelinePanel.FRAME_HEIGHT; int start_f = clip.x / frameWidth; int start_d = clip.y / frameHeight; int end_f = (clip.x + clip.width) / frameWidth; int end_d = (clip.y + clip.height) / frameHeight; int max_d = timeline.getMaxDepth(); if (max_d < end_d) { end_d = max_d; } int max_f = timeline.getFrameCount() - 1; if (max_f < end_f) { end_f = max_f; } if (end_d - start_d + 1 < 0) { return; } // draw background for (int f = start_f; f <= end_f; f++) { g.setColor((f + 1) % 5 == 0 ? getEmptyFrameSecondColor() : getEmptyFrameColor()); g.fillRect(f * frameWidth, start_d * frameHeight, frameWidth, (end_d - start_d + 1) * frameHeight); g.setColor(emptyBorderColor); for (int d = start_d; d <= end_d; d++) { g.drawRect(f * frameWidth, d * frameHeight, frameWidth, frameHeight); } } // draw selected cell if (cursor != null) { g.setColor(getSelectedColor()); g.fillRect(cursor.x * frameWidth + 1, cursor.y * frameHeight + 1, frameWidth - 1, frameHeight - 1); } g.setColor(aColor); g.setFont(getFont().deriveFont(fontSize)); int awidth = g.getFontMetrics().stringWidth("a"); for (int f = start_f; f <= end_f; f++) { if (!timeline.getFrame(f).actions.isEmpty()) { g.drawString("a", f * frameWidth + frameWidth / 2 - awidth / 2, frameHeight / 2 + fontSize / 2); } } Map<Integer, Integer> depthMaxFrames = timeline.getDepthMaxFrame(); for (int d = start_d; d <= end_d; d++) { int maxFrame = depthMaxFrames.containsKey(d) ? depthMaxFrames.get(d) : -1; if (maxFrame < 0) { continue; } int end_f2 = Math.min(end_f, maxFrame); int start_f2 = Math.min(start_f, end_f2); // find the start frame number of the current block DepthState dsStart = timeline.getFrame(start_f2).layers.get(d); for (; start_f2 >= 1; start_f2--) { DepthState ds = timeline.getFrame(start_f2 - 1).layers.get(d); if (((dsStart == null) != (ds == null)) || (ds != null && dsStart.characterId != ds.characterId)) { break; } } for (int f = start_f2; f <= end_f2; f++) { DepthState fl = timeline.getFrame(f).layers.get(d); boolean motionTween = fl == null ? false : fl.motionTween; DepthState flNext = f < max_f ? timeline.getFrame(f + 1).layers.get(d) : null; DepthState flPrev = f > 0 ? timeline.getFrame(f - 1).layers.get(d) : null; CharacterTag cht = fl == null ? null : timeline.swf.getCharacter(fl.characterId); boolean shapeTween = cht != null && (cht instanceof MorphShapeTag); boolean motionTweenStart = !motionTween && (flNext != null && flNext.motionTween); boolean motionTweenEnd = !motionTween && (flPrev != null && flPrev.motionTween); //boolean shapeTweenStart = shapeTween && (flPrev == null || flPrev.characterId != fl.characterId); //boolean shapeTweenEnd = shapeTween && (flNext == null || flNext.characterId != fl.characterId); /*if (motionTweenStart || motionTweenEnd) { motionTween = true; }*/ int draw_f = f; int num_frames = 1; Color backColor; BlockType blockType; if (fl == null) { for (; f + 1 < timeline.getFrameCount(); f++) { fl = timeline.getFrame(f + 1).layers.get(d); if (fl != null && fl.characterId != -1) { break; } num_frames++; } backColor = getEmptyFrameColor(); blockType = BlockType.EMPTY; } else { for (; f + 1 < timeline.getFrameCount(); f++) { fl = timeline.getFrame(f + 1).layers.get(d); if (fl == null || fl.key) { break; } num_frames++; } backColor = shapeTween ? shapeTweenColor : motionTween ? motionTweenColor : getFrameColor(); blockType = shapeTween ? BlockType.SHAPE_TWEEN : motionTween ? BlockType.MOTION_TWEEN : BlockType.NORMAL; } drawBlock(g, backColor, d, draw_f, num_frames, blockType); } } if (cursor != null && cursor.x >= start_f && cursor.x <= end_f) { g.setColor(TimelinePanel.selectedBorderColor); g.drawLine(cursor.x * frameWidth + frameWidth / 2, 0, cursor.x * frameWidth + frameWidth / 2, getHeight()); } } private void drawBlock(Graphics2D g, Color backColor, int depth, int frame, int num_frames, BlockType blockType) { int frameWidth = TimelinePanel.FRAME_WIDTH; int frameHeight = TimelinePanel.FRAME_HEIGHT; g.setColor(backColor); g.fillRect(frame * frameWidth, depth * frameHeight, num_frames * frameWidth, frameHeight); g.setColor(borderColor); g.drawRect(frame * frameWidth, depth * frameHeight, num_frames * frameWidth, frameHeight); boolean selected = false; if (cursor != null && frame <= cursor.x && (frame + num_frames) > cursor.x && depth == cursor.y) { selected = true; } if (selected) { g.setColor(getSelectedColor()); g.fillRect(cursor.x * frameWidth + 1, depth * frameHeight + 1, frameWidth - 1, frameHeight - 1); } boolean isTween = blockType == BlockType.MOTION_TWEEN || blockType == BlockType.SHAPE_TWEEN; g.setColor(keyColor); if (isTween) { g.drawLine(frame * frameWidth, depth * frameHeight + frameHeight * 3 / 4, frame * frameWidth + num_frames * frameWidth - frameWidth / 2, depth * frameHeight + frameHeight * 3 / 4 ); } if (blockType == BlockType.EMPTY) { g.drawOval(frame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight * 3 / 4 - frameWidth / 2 / 2, frameWidth / 2, frameWidth / 2); } else { g.fillOval(frame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight * 3 / 4 - frameWidth / 2 / 2, frameWidth / 2, frameWidth / 2); } if (num_frames > 1) { int endFrame = frame + num_frames - 1; if (isTween) { g.fillOval(endFrame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight * 3 / 4 - frameWidth / 2 / 2, frameWidth / 2, frameWidth / 2); } else { g.setColor(stopColor); g.fillRect(endFrame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight / 2 - 2, frameWidth / 2, frameHeight / 2); g.setColor(stopBorderColor); g.drawRect(endFrame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight / 2 - 2, frameWidth / 2, frameHeight / 2); } g.setColor(borderLinesColor); for (int n = frame + 1; n < frame + num_frames; n++) { g.drawLine(n * frameWidth, depth * frameHeight + 1, n * frameWidth, depth * frameHeight + borderLinesLength); g.drawLine(n * frameWidth, depth * frameHeight + frameHeight - 1, n * frameWidth, depth * frameHeight + frameHeight - borderLinesLength); } } } @Override public void mouseClicked(MouseEvent e) { } public void frameSelect(int frame, int depth) { if (cursor != null && cursor.x == frame && (cursor.y == depth || depth == -1)) { return; } if (depth == -1 && cursor != null) { depth = cursor.y; } cursor = new Point(frame, depth); for (FrameSelectionListener l : listeners) { l.frameSelected(frame, depth); } repaint(); } @Override public void mousePressed(MouseEvent e) { Point p = e.getPoint(); p.x = p.x / TimelinePanel.FRAME_WIDTH; p.y = p.y / TimelinePanel.FRAME_HEIGHT; if (p.x >= timeline.getFrameCount()) { p.x = timeline.getFrameCount() - 1; } int maxDepth = timeline.getMaxDepth(); if (p.y > maxDepth) { p.y = maxDepth; } frameSelect(p.x, p.y); } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case 37: //left if (cursor.x > 0) { frameSelect(cursor.x - 1, cursor.y); } break; case 39: //right if (cursor.x < timeline.getFrameCount() - 1) { frameSelect(cursor.x + 1, cursor.y); } break; case 38: //up if (cursor.y > 0) { frameSelect(cursor.x, cursor.y - 1); } break; case 40: //down if (cursor.y < timeline.getMaxDepth()) { frameSelect(cursor.x, cursor.y + 1); } break; } } @Override public void keyReleased(KeyEvent e) { } }
jindrapetrik/jpexs-decompiler
src/com/jpexs/decompiler/flash/gui/timeline/TimelineBodyPanel.java
Java
gpl-3.0
15,335
/* * Orbit, a versatile image analysis software for biological image-based quantification. * Copyright (C) 2009 - 2017 Idorsia Pharmaceuticals Ltd., Hegenheimermattweg 91, CH-4123 Allschwil, Switzerland. * * 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.actelion.research.orbit.imageprovider.tree; import com.actelion.research.orbit.beans.RawData; import com.actelion.research.orbit.imageprovider.ImageProviderOmero; import com.actelion.research.orbit.utils.Logger; import java.util.ArrayList; import java.util.List; public class TreeNodeProject extends AbstractOrbitTreeNode { private static Logger logger = Logger.getLogger(TreeNodeProject.class); private RawData project = null; private ImageProviderOmero imageProviderOmero; public TreeNodeProject(ImageProviderOmero imageProviderOmero, RawData project) { this.imageProviderOmero = imageProviderOmero; this.project = project; } @Override public synchronized List<TreeNodeProject> getNodes(AbstractOrbitTreeNode parent) { List<TreeNodeProject> nodeList = new ArrayList<>(); int group = -1; if (parent!=null && parent instanceof TreeNodeGroup) { TreeNodeGroup groupNode = (TreeNodeGroup) parent; RawData rdGroup = (RawData) groupNode.getIdentifier(); group = rdGroup.getRawDataId(); } List<RawData> rdList = loadProjects(group); for (RawData rd : rdList) { nodeList.add(new TreeNodeProject(imageProviderOmero, rd)); } return nodeList; } @Override public boolean isChildOf(Object parent) { return parent instanceof TreeNodeGroup; } @Override public Object getIdentifier() { return project; } @Override public String toString() { return project != null ? project.getBioLabJournal() : ""; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TreeNodeProject that = (TreeNodeProject) o; return project != null ? project.equals(that.project) : that.project == null; } @Override public int hashCode() { return project != null ? project.hashCode() : 0; } private List<RawData> loadProjects(int group) { return imageProviderOmero.loadProjects(group); } }
mstritt/image-provider-omero
src/main/java/com/actelion/research/orbit/imageprovider/tree/TreeNodeProject.java
Java
gpl-3.0
3,070
/** * * Copyright 2014 Martijn Brekhof * * This file is part of Catch Da Stars. * * Catch Da Stars 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. * * Catch Da Stars 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 Catch Da Stars. If not, see <http://www.gnu.org/licenses/>. * */ package com.strategames.engine.gameobject.types; import java.util.ArrayList; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.ChainShape; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonValue; import com.strategames.engine.gameobject.GameObject; import com.strategames.engine.gameobject.StaticBody; import com.strategames.engine.utils.ConfigurationItem; import com.strategames.engine.utils.Textures; public class Door extends StaticBody { public final static float WIDTH = 0.35f; public final static float HEIGHT = 0.35f; private Wall wall; private boolean open; private int[] entryLevel = new int[2]; // level this door provides access too private int[] exitLevel = new int[2]; // level this door can be accessed from public Door() { super(new Vector2(WIDTH, HEIGHT)); } @Override protected TextureRegion createImage() { return Textures.getInstance().passageToNextLevel; } @Override protected void setupBody(Body body) { Vector2 leftBottom = new Vector2(0, 0); Vector2 rightBottom = new Vector2(WIDTH, 0); Vector2 rightTop = new Vector2(WIDTH, HEIGHT); Vector2 leftTop = new Vector2(0, HEIGHT); ChainShape chain = new ChainShape(); chain.createLoop(new Vector2[] {leftBottom, rightBottom, rightTop, leftTop}); Fixture fixture = body.createFixture(chain, 0.0f); fixture.setSensor(true); } @Override protected void writeValues(Json json) { json.writeArrayStart("nextLevelPosition"); json.writeValue(entryLevel[0]); json.writeValue(entryLevel[1]); json.writeArrayEnd(); } @Override protected void readValue(JsonValue jsonData) { String name = jsonData.name(); if( name.contentEquals("nextLevelPosition")) { this.entryLevel = jsonData.asIntArray(); } } @Override public GameObject copy() { Door door = (Door) newInstance(); door.setPosition(getX(), getY()); int[] pos = getAccessToPosition(); door.setAccessTo(pos[0], pos[1]); return door; } @Override protected GameObject newInstance() { return new Door(); } @Override protected ArrayList<ConfigurationItem> createConfigurationItems() { return null; } @Override public void increaseSize() { } @Override public void decreaseSize() { } @Override protected void destroyAction() { } @Override public void handleCollision(Contact contact, ContactImpulse impulse, GameObject gameObject) { } @Override public void loadSounds() { } public Wall getWall() { return wall; } public void setWall(Wall wall) { this.wall = wall; } public boolean isOpen() { return open; } /** * Sets the level position this door provides access too * @param x * @param y */ public void setAccessTo(int x, int y) { this.entryLevel[0] = x; this.entryLevel[1] = y; } /** * Returns the level position this door provides access too * @return */ public int[] getAccessToPosition() { return entryLevel; } /** * Sets the level position from which this door is accessible * @param exitLevel */ public void setExitLevel(int[] exitLevel) { this.exitLevel = exitLevel; } /** * Returns the level position this door is accessible from * @return */ public int[] getAccessFromPosition() { return exitLevel; } @Override public String toString() { return super.toString() + ", nextLevelPosition="+entryLevel[0]+","+entryLevel[1]; } @Override public boolean equals(Object obj) { Door door; if( obj instanceof Door ) { door = (Door) obj; } else { return false; } int[] pos = door.getAccessToPosition(); return pos[0] == entryLevel[0] && pos[1] == entryLevel[1] && super.equals(obj); } public void open() { Gdx.app.log("Door", "open"); this.open = true; } public void close(){ this.open = false; } }
poisdeux/catchdastars
core/src/com/strategames/engine/gameobject/types/Door.java
Java
gpl-3.0
4,823
/* * Decompiled with CFR 0_115. * * Could not load the following classes: * android.content.BroadcastReceiver * android.content.Context * android.content.Intent * android.content.IntentFilter */ package com.buzzfeed.android.vcr.util; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.annotation.NonNull; import com.buzzfeed.android.vcr.VCRConfig; import com.buzzfeed.toolkit.util.EZUtil; public final class VCRBitrateLimitingReceiver { private final Context mContext; private final BroadcastReceiver mReceiver; public VCRBitrateLimitingReceiver(@NonNull Context context) { this.mContext = EZUtil.checkNotNull(context, "Context must not be null."); this.mReceiver = new ConnectivityReceiver(); } public void register() { this.mContext.registerReceiver(this.mReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")); } public void unregister() { this.mContext.unregisterReceiver(this.mReceiver); } private final class ConnectivityReceiver extends BroadcastReceiver { private ConnectivityReceiver() { } public void onReceive(Context context, Intent intent) { VCRConfig.getInstance().setAdaptiveBitrateLimitForConnection(context); } } }
SPACEDAC7/TrabajoFinalGrado
uploads/34f7f021ecaf167f6e9669e45c4483ec/java_source/com/buzzfeed/android/vcr/util/VCRBitrateLimitingReceiver.java
Java
gpl-3.0
1,401
/* * 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. */ /** * * @author dh2744 */ import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.util.Vector; /* * 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. */ /** * * @author dh2744 */ public class CheckField { //check that spike list and exp log exists, are correct and match public static int checkSpkListExpLog(javax.swing.JTextField spikeListField, javax.swing.JTextField expLogFileField, javax.swing.JButton runButton, javax.swing.JTextArea outputTextArea) { int exitValue = 0; runButton.setEnabled(false); Boolean errorLog = false; //Vector<String> logResult = new Vector<>(); // to do java 1.6 compatibility Vector<String> logResult = new Vector<String>(); //experimental log try { //read in Experimental log String csvFile = expLogFileField.getText(); String[] csvCheck1 = csvFile.split("\\."); String csvText1 = "csv"; System.out.println("end of Exp log"+ csvCheck1[csvCheck1.length - 1] + " equals csv:" ); System.out.println(csvCheck1[csvCheck1.length - 1].equals("csv")); //two ifs for whether string ends in "]" or not if ( !csvCheck1[csvCheck1.length - 1].equals("csv") ){ if (!(csvCheck1[csvCheck1.length].equals("csv"))) { logResult.add( "Exp log file chosen is not a csv file" ); ErrorHandler.errorPanel("Exp log file chosen " + '\n' + csvFile + '\n' + "Is not a csv file."); exitValue = -1; errorLog = true; } } // This will reference one line at a time String line = null; Boolean expLogGood = true; try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(csvFile); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); line = bufferedReader.readLine(); String[] expLogParts = line.split(","); if (!expLogParts[0].toUpperCase().equals("PROJECT")) { logResult.add( "Error reading in expLog File" ); logResult.add("Exp log file lacks Project column." ); ErrorHandler.errorPanel("Exp log file lacks Project column " + '\n' + "Please re-enter exp log file"); errorLog = true; expLogGood = false; exitValue = -1; } else if (!expLogParts[1].toUpperCase().equals("EXPERIMENT DATE")) { logResult.add( "Error reading in expLog File" ); logResult.add("Exp log file lacks Experiment column." ); ErrorHandler.errorPanel("Exp log file lacks Experiment column " + '\n' + "Please re-enter exp log file"); errorLog = true; expLogGood = false; exitValue = -1; } else { LineNumberReader lnr = null; line = bufferedReader.readLine(); Integer i = 1; line = bufferedReader.readLine(); String[] country = line.split(","); System.out.println("Start while loop"); while (line != null) { System.out.println(line); System.out.println(country[0]); System.out.println("Current line num " + i); i++; line = bufferedReader.readLine(); System.out.println(line); System.out.println("line = null? " + (line == null)); //System.out.println("line.isEmpty ? " + (line.isEmpty()) ); if (line != null) { System.out.println("line : " + line); System.out.println("country : " + country[0]); country = line.split(","); } } System.out.println("Current line num " + i); System.out.println("done with while loop"); // Always close files. bufferedReader.close(); } //end of if-else } catch (FileNotFoundException ex) { logResult.add( "ExpLog File not found" ); System.out.println( "Unable to open file '" + csvFile + "'"); errorLog = true; exitValue = -1; expLogGood = false; } catch (IOException ex) { logResult.add( "Error reading in expLog File" ); logResult.add("IOException." ); System.out.println( "Error reading file '" + csvFile + "'"); errorLog = true; expLogGood = false; exitValue = -1; } System.out.println("expLogGood : " + expLogGood); //++++++++++++++++++++++++++++++++++++read in Spk list file String check = spikeListField.getText(); String[] temp = check.split(","); System.out.println("spk list chooser: " + temp[0]); String[] spkCsvFile = temp; if (temp.length > 1) { System.out.println("spkCsvFile.length = " + temp.length); for (int ind = 0; ind < temp.length; ind++) { if (0 == ind) { spkCsvFile[ind] = temp[ind].substring(1, temp[ind].length()).trim(); System.out.println("spkCsvFile[ind] " + spkCsvFile[ind]); File fileCheck = new File(spkCsvFile[ind]); System.out.println("exists? spkCsvFile[" + ind + "] " + fileCheck.exists()); } else if (ind == (temp.length - 1)) { spkCsvFile[ind] = temp[ind].substring(0, temp[ind].length() - 1).trim(); System.out.println("spkCsvFile[ind] " + spkCsvFile[ind]); File fileCheck = new File(spkCsvFile[ind]); System.out.println("exists? spkCsvFile[" + ind + "] " + fileCheck.exists()); } else { spkCsvFile[ind] = temp[ind]; System.out.println("spkCsvFile[ind] " + spkCsvFile[ind].trim()); System.out.println("MMMMM" + spkCsvFile[ind].trim() + "MMMMMMM"); File fileCheck = new File(spkCsvFile[ind].trim()); System.out.println("exists? spkCsvFile[" + ind + "] " + fileCheck.exists()); } } } else if (temp.length == 1) { System.out.println("temp.length = " + temp.length); System.out.println("temp[0].length = " + temp.length); System.out.println("temp[0].toString().endsWith(]) = " + temp.toString().endsWith("]") ); System.out.println("temp[0].toString().length() "+temp[0].toString().length()); System.out.println("temp[0].substring(temp[0].toString().length()-1 ) = " + temp[0].substring(temp[0].toString().length()-1 ).toString() ); System.out.println("temp[0].substring(temp[0].toString().length()-1 ).equals(]) "+ temp[0].substring(temp[0].toString().length()-1 ).equals("]") ); if ( temp[0].substring(temp[0].toString().length()-1 ).equals("]") ){ int len = temp[0].length(); len--; System.out.println("temp[0].toString().substring(2,3 ) = "+ temp[0].substring(2,3) ); System.out.println("temp[0].toString().substring(1,2 ) = "+ temp[0].toString().substring(1,2 ) ); System.out.println("temp[0].toString().substring(0,1 ) = "+ temp[0].substring(0,1 ) ); if (temp[0].substring(2,3 ).equals("[")){ spkCsvFile[0] = temp[0].substring(3, len).trim(); } else if (temp[0].toString().substring(1,2 ).equals("[")){ spkCsvFile[0] = temp[0].toString().substring(2, len).trim(); } else if (temp[0].toString().substring(0,1 ).equals("[")){ spkCsvFile[0] = temp[0].toString().substring(1, len).trim(); } System.out.println("spkCsvFile[ind] " + spkCsvFile[0]); } File fileCheck = new File(spkCsvFile[0]); System.out.println("exists? spkCsvFile[" + 0 + "] " + fileCheck.exists()); } System.out.println("Done with reading in spike-list file names "); // check that it's csv for (int j = 0; j < spkCsvFile.length; j++) { String[] csvCheck = spkCsvFile[j].split("\\."); String csvText = "csv"; System.out.println(csvCheck[csvCheck.length - 1]); System.out.println(csvCheck[csvCheck.length - 1].equals("csv")); if (!(csvCheck[csvCheck.length - 1].equals("csv")|| csvCheck[csvCheck.length].equals("csv")) ) { logResult.add( "Spike-list csv file chosen " + spkCsvFile[j] ); logResult.add("Is not a csv file." ); ErrorHandler.errorPanel("Spike-list csv file chosen " + spkCsvFile[j] + '\n' + "Is not a csv file."); errorLog = true; exitValue = -1; } // spike list file try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(spkCsvFile[j].trim()); System.out.println("file reader " + spkCsvFile[j]); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); line = bufferedReader.readLine(); System.out.println(line); String[] spkListHeader = line.split(","); String third = "Time (s)"; System.out.println(spkListHeader[2]); // check for spike list file System.out.println(spkListHeader[2]); if (!(spkListHeader[2].equals("Time (s)") || spkListHeader[2].equals("Time (s) ") || spkListHeader[2].equals("\"Time (s)\"") || spkListHeader[2].equals("\"Time (s) \""))) { logResult.add( "Spike-list csv file chosen " + spkCsvFile[j] ); logResult.add("Is not a proper spike-list file" ); logResult.add( "'Time (s)' should be third column header " ); logResult.add("Instead 3rd column is "+ spkListHeader[2].toString() ); ErrorHandler.errorPanel("Spike-list csv file chosen '" + spkCsvFile[j]+"'" + '\n' + "Is not a proper spike-list file" + '\n' + "'Time (s)' should be third column header"); exitValue = -1; errorLog=true; } for (int counter2 = 1; counter2 < 5; counter2++) { // content check line = bufferedReader.readLine(); if (counter2 == 2) { System.out.println(line); String[] spkListContents = line.split(","); //Project,Experiment Date,Plate SN,DIV,Well,Treatment,Size,Dose,Units System.out.println("Time(s) " + spkListContents[2] + " , Electrode =" + spkListContents[3]); } } // Always close files. bufferedReader.close(); } catch (FileNotFoundException ex) { logResult.add( " Unable to open file " + spkCsvFile[j] ); logResult.add(" Please select another spike list file " ); ErrorHandler.errorPanel("Unable to open file " + j + " " + spkCsvFile[j] + '\n' + "Please select another spike list file"); exitValue = -1; errorLog = true; } catch (IOException ex) { logResult.add( "Error reading file " + spkCsvFile[j] ); logResult.add(" IOException " ); ErrorHandler.errorPanel( "Error reading file '" + j + " " + spkCsvFile[j] + "'" + '\n' + "Please select another spike list file"); errorLog = true; exitValue = -1; } } //end of loop through spike List Files // +++++++++need to compare files System.out.println("Starting match"); for (int j = 0; j < spkCsvFile.length; j++) { if (expLogGood && !errorLog) { try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(csvFile); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); line = bufferedReader.readLine(); line = bufferedReader.readLine(); System.out.println(line); String[] country = line.split(","); //Project,Experiment Date,Plate SN,DIV,Well,Treatment,Size,Dose,Units if (country.length>5 ){ System.out.println("Project " + country[0] + " , Exp Date=" + country[1] + " , Plate SN=" + country[2] + " , DIV= " + country[3] + " , Well=" + country[4] + " , trt=" + country[5]); } else{ System.out.println("Project " + country[0] + " , Exp Date=" + country[1] + " , Plate SN=" + country[2] + " , DIV= " + country[3] + " , Well=" + country[4] ); } // now compare to name of spk-list file File spkListFile = new File(spkCsvFile[j]); System.out.println("spkCsvFile "+spkCsvFile[j]); System.out.println( "File.separator" + File.separator ); String name1 = spkListFile.getName().toString(); String[] partsName1 = name1.split("_"); System.out.println(partsName1[0]); System.out.println(partsName1[1]); System.out.println(partsName1[2]); if (!(partsName1[0].equals(country[0].trim() ))) { System.out.println("spkListFileNameParts " + partsName1[0].toString()); System.out.println("country " + country[0]); logResult.add( "project in spk-list file name: " + partsName1[0] ); logResult.add("& experimental log file project: " + country[0]); logResult.add("Do not match"); ErrorHandler.errorPanel( "project in spk-list file name: " + partsName1[0] + '\n' + "& experimental log file project: " + country[0] + '\n' + "Do not match"); exitValue = -1; errorLog = true; } else if (!(partsName1[1].equals(country[1].trim() ))) { logResult.add( "Experiment date does not match between" + '\n' + spkCsvFile[j] ); logResult.add("and experimental log file. "); logResult.add("Please re-enter file"); ErrorHandler.errorPanel( "Experiment date does not match between" + '\n' + spkCsvFile[j] + " name and experimental log file. '"); exitValue = -1; errorLog = true; } else if (!(partsName1[2].equals(country[2].trim() ))) { logResult.add("No match between spk list" + spkCsvFile[j]); logResult.add("and experimental log file. "); ErrorHandler.errorPanel( "No match between spk list" + spkCsvFile[j] + '\n' + "and experimental log file. '" + '\n' + "Project name do not match"); exitValue = -1; errorLog = true; } // Always close files. bufferedReader.close(); } catch (FileNotFoundException ex) { System.out.println( "Unable to open file '" + csvFile + "'"); logResult.add(" Unable to open file "); logResult.add("'" + csvFile + "'"); ErrorHandler.errorPanel( "Unable to open file " + '\n' + "'" + csvFile + "'" + '\n' ); exitValue = -1; errorLog = true; } catch (IOException ex) { System.out.println( "Error reading file '" + csvFile + "'"); ErrorHandler.errorPanel( "Error reading file " + "'" + csvFile + "'" + '\n' ); logResult.add("Error reading file "); logResult.add("'" + csvFile + "'"); errorLog = true; exitValue = -1; } System.out.println("expLogGood : " + expLogGood); System.out.println(" "); } System.out.println("done with match "); System.out.println("NUMER OF TIMES THROUGH LOOP : " + j + 1); } //end of loop through spike list files if (!errorLog) { runButton.setEnabled(true); logResult.add("Files chosen are without errors"); logResult.add("They match one another"); logResult.add("proceeeding to Analysis"); } PrintToTextArea.printToTextArea(logResult , outputTextArea); } catch (Exception e) { logResult.add("Try at reading the csv file failed"); logResult.add(" "); logResult.add(" "); e.printStackTrace(); exitValue = -1; PrintToTextArea.printToTextArea(logResult , outputTextArea); } return(exitValue); } public static int checkRObject(javax.swing.JTextField rasterFileChooserField, javax.swing.JButton makeRasterButton, javax.swing.JTextArea toolsTextArea) { int exitValue = 0; makeRasterButton.setEnabled(false); Boolean errorLog = false; //Vector<String> logResult = new Vector<>(); // to do java 1.6 compatibility Vector<String> logResult = new Vector<String>(); //check Robject try { //check extension String rObject = rasterFileChooserField.getText(); String[] rObjectCheck1 = rObject.split("\\."); String rObjectText1 = "RData"; System.out.println( rObject + " (-1) end in .RData? : " ); System.out.println(rObjectCheck1[rObjectCheck1.length-1 ].equals("RData")); System.out.println( rObject + " end in .RData? : " ); //System.out.println(rObjectCheck1[rObjectCheck1.length ].equals("RData")); //two ifs for whether string ends in "]" or not if ( !rObjectCheck1[rObjectCheck1.length-1 ].equals("RData") ) { System.out.println("in if statement"); ErrorHandler.errorPanel("Robject file chosen " + '\n' + rObject + '\n' + "Is not a Robject of .RData extension"); exitValue = -1; errorLog = true; return exitValue; } // This will reference one line at a time String line = null; Boolean expLogGood = true; try { // Query R for what's in the Robject System.out.println(" right before SystemCall.systemCall(cmd0, outputTextArea) " ); Vector<String> envVars = new Vector<String>(); File fileWD = new File(System.getProperty("java.class.path")); File dashDir = fileWD.getAbsoluteFile().getParentFile(); System.out.println("Dash dir " + dashDir.toString()); File systemPaths = new File( dashDir.toString() +File.separator+"Code" + File.separator+"systemPaths.txt"); File javaClassPath = new File(System.getProperty("java.class.path")); File rootPath1 = javaClassPath.getAbsoluteFile().getParentFile(); String rootPath2Slash = rootPath1.toString(); rootPath2Slash = rootPath2Slash.replace("\\", "\\\\"); envVars=GetEnvVars.getEnvVars( systemPaths, toolsTextArea ); String cmd0 = envVars.get(0).toString() + " " + rootPath2Slash + File.separator +"Code"+ File.separator + "RobjectInfoScript.R "+ "RobjectPath="+rObject.toString(); System.out.println( "cmd0 " + cmd0 ); SystemCall.systemCall(cmd0, toolsTextArea ); System.out.println("After SystemCall in Raster " ); /// here we need code to populate raster parameter object } catch (Exception i){ logResult.add("Try at running RobjectInfoScript.R"); logResult.add(" "); logResult.add(" "); i.printStackTrace(); exitValue = -1; PrintToTextArea.printToTextArea(logResult , toolsTextArea); } } catch (Exception e) { logResult.add("Try at reading the Robject file failed"); logResult.add(" "); logResult.add(" "); e.printStackTrace(); exitValue = -1; PrintToTextArea.printToTextArea(logResult , toolsTextArea); } return(exitValue); } public static int checkDistFile( javax.swing.JTextField distPlotFileField, javax.swing.JButton plotDistrButton, javax.swing.JTextArea distPlotTextArea) { int exitValue = 0; plotDistrButton.setEnabled(false); Boolean errorLog = false; //Vector<String> logResult = new Vector<>(); // to do java 1.6 compatibility Vector<String> logResult = new Vector<String>(); //check Robject try { //check extension String[] distPlotFile1=RemoveSqBrackets.removeSqBrackets( distPlotFileField ); String[] distPlotFileCheck1 = distPlotFile1[0].split("\\."); String distPlotFileText1 = "csv"; System.out.println( distPlotFile1[0] + " (-1) end in .csv? : " ); System.out.println(distPlotFileCheck1[distPlotFileCheck1.length-1 ].equals("csv")); System.out.println(distPlotFileCheck1[distPlotFileCheck1.length-1 ] + " =distPlotFileCheck1[distPlotFileCheck1.length-1 ]" ); //System.out.println(rObjectCheck1[rObjectCheck1.length ].equals("RData")); //two ifs for whether string ends in "]" or not if ( !distPlotFileCheck1[distPlotFileCheck1.length-1 ].equals("csv") ) { System.out.println("in if statement"); ErrorHandler.errorPanel("Distribution file chosen " + '\n' + distPlotFile1[0] + '\n' + "Is not a distribution file of .csv extension"); exitValue = -1; errorLog = true; return exitValue; } // This will reference one line at a time String line = null; Boolean expLogGood = true; try { // Query R for what's in the Robject System.out.println(" right before SystemCall.systemCall(cmd0, distPlotTextArea) " ); Vector<String> envVars = new Vector<String>(); File fileWD = new File(System.getProperty("java.class.path")); File dashDir = fileWD.getAbsoluteFile().getParentFile(); System.out.println("Dash dir " + dashDir.toString()); File systemPaths = new File( dashDir.toString() +File.separator+"Code" + File.separator+"systemPaths.txt"); File javaClassPath = new File(System.getProperty("java.class.path")); File rootPath1 = javaClassPath.getAbsoluteFile().getParentFile(); String rootPath2Slash = rootPath1.toString(); rootPath2Slash = rootPath2Slash.replace("\\", "\\\\"); envVars=GetEnvVars.getEnvVars( systemPaths, distPlotTextArea ); String cmd0 = envVars.get(0).toString() + " " + rootPath2Slash + File.separator +"Code"+ File.separator + "distFileInfoScript.R "+ "distFilePath="+distPlotFile1[0].toString(); System.out.println( "cmd0 " + cmd0 ); SystemCall.systemCall(cmd0, distPlotTextArea ); System.out.println("After SystemCall in distPlot " ); /// here we need code to populate raster parameter object } catch (Exception i){ logResult.add("Try at running distFileInfoScript.R"); logResult.add(" "); logResult.add(" "); i.printStackTrace(); exitValue = -1; PrintToTextArea.printToTextArea(logResult , distPlotTextArea); } } catch (Exception e) { logResult.add("Try at reading the Robject file failed"); logResult.add(" "); logResult.add(" "); e.printStackTrace(); exitValue = -1; PrintToTextArea.printToTextArea(logResult ,distPlotTextArea); } return(exitValue); } }
igm-team/meaRtools
Java_IGMDash-master/src/CheckField.java
Java
gpl-3.0
29,621
package org.emdev.ui.uimanager; import android.annotation.TargetApi; import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.content.ComponentName; import android.content.Context; import android.view.View; import android.view.Window; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.emdev.BaseDroidApp; @TargetApi(11) public class UIManager3x implements IUIManager { private static final String SYS_UI_CLS = "com.android.systemui.SystemUIService"; private static final String SYS_UI_PKG = "com.android.systemui"; private static final ComponentName SYS_UI = new ComponentName(SYS_UI_PKG, SYS_UI_CLS); private static final String SU_PATH1 = "/system/bin/su"; private static final String SU_PATH2 = "/system/xbin/su"; private static final String AM_PATH = "/system/bin/am"; private static final Map<ComponentName, Data> data = new HashMap<ComponentName, Data>() { /** * */ private static final long serialVersionUID = -6627308913610357179L; @Override public Data get(final Object key) { Data existing = super.get(key); if (existing == null) { existing = new Data(); put((ComponentName) key, existing); } return existing; } }; @Override public void setTitleVisible(final Activity activity, final boolean visible, final boolean firstTime) { if (firstTime) { try { final Window window = activity.getWindow(); window.requestFeature(Window.FEATURE_ACTION_BAR); window.requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS); activity.setProgressBarIndeterminate(true); activity.setProgressBarIndeterminateVisibility(true); window.setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, 1); } catch (final Throwable th) { LCTX.e("Error on requestFeature call: " + th.getMessage()); } } try { if (visible) { activity.getActionBar().show(); } else { activity.getActionBar().hide(); } data.get(activity.getComponentName()).titleVisible = visible; } catch (final Throwable th) { LCTX.e("Error on requestFeature call: " + th.getMessage()); } } @Override public boolean isTitleVisible(final Activity activity) { return data.get(activity.getComponentName()).titleVisible; } @Override public void setProgressSpinnerVisible(Activity activity, boolean visible) { activity.setProgressBarIndeterminateVisibility(visible); activity.getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, visible ? 1 : 0); } @Override public void setFullScreenMode(final Activity activity, final View view, final boolean fullScreen) { data.get(activity.getComponentName()).fullScreen = fullScreen; if (fullScreen) { stopSystemUI(activity); } else { startSystemUI(activity); } } @Override public void openOptionsMenu(final Activity activity, final View view) { activity.openOptionsMenu(); } @Override public void invalidateOptionsMenu(final Activity activity) { activity.invalidateOptionsMenu(); } @Override public void onMenuOpened(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && data.get(activity.getComponentName()).fullScreenState.get()) { startSystemUI(activity); } } @Override public void onMenuClosed(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && !data.get(activity.getComponentName()).fullScreenState.get()) { stopSystemUI(activity); } } @Override public void onPause(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && data.get(activity.getComponentName()).fullScreenState.get()) { startSystemUI(activity); } } @Override public void onResume(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && !data.get(activity.getComponentName()).fullScreenState.get()) { stopSystemUI(activity); } } @Override public void onDestroy(final Activity activity) { if (data.get(activity.getComponentName()).fullScreen && data.get(activity.getComponentName()).fullScreenState.get()) { startSystemUI(activity); } } @Override public boolean isTabletUi(final Activity activity) { return true; } protected void startSystemUI(final Activity activity) { if (isSystemUIRunning()) { data.get(activity.getComponentName()).fullScreenState.set(false); return; } exec(false, activity, AM_PATH, "startservice", "-n", SYS_UI.flattenToString()); } protected void stopSystemUI(final Activity activity) { if (!isSystemUIRunning()) { data.get(activity.getComponentName()).fullScreenState.set(true); return; } final String su = getSuPath(); if (su == null) { data.get(activity.getComponentName()).fullScreenState.set(false); return; } exec(true, activity, su, "-c", "service call activity 79 s16 " + SYS_UI_PKG); } protected boolean isSystemUIRunning() { final Context ctx = BaseDroidApp.context; final ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE); final List<RunningServiceInfo> rsiList = am.getRunningServices(1000); for (final RunningServiceInfo rsi : rsiList) { LCTX.d("Service: " + rsi.service); if (SYS_UI.equals(rsi.service)) { LCTX.e("System UI service found"); return true; } } return false; } protected void exec(final boolean expected, final Activity activity, final String... as) { (new Thread(new Runnable() { @Override public void run() { try { final boolean result = execImpl(as); data.get(activity.getComponentName()).fullScreenState.set(result ? expected : !expected); } catch (final Throwable th) { LCTX.e("Changing full screen mode failed: " + th.getCause()); data.get(activity.getComponentName()).fullScreenState.set(!expected); } } })).start(); } private boolean execImpl(final String... as) { try { LCTX.d("Execute: " + Arrays.toString(as)); final Process process = Runtime.getRuntime().exec(as); final InputStreamReader r = new InputStreamReader(process.getInputStream()); final StringWriter w = new StringWriter(); final char ac[] = new char[8192]; int i = 0; do { i = r.read(ac); if (i > 0) { w.write(ac, 0, i); } } while (i != -1); r.close(); process.waitFor(); final int exitValue = process.exitValue(); final String text = w.toString(); LCTX.d("Result code: " + exitValue); LCTX.d("Output:\n" + text); return 0 == exitValue; } catch (final IOException e) { throw new IllegalStateException(e); } catch (final InterruptedException e) { throw new IllegalStateException(e); } } private static String getSuPath() { final File su1 = new File(SU_PATH1); if (su1.exists() && su1.isFile() && su1.canExecute()) { return SU_PATH1; } final File su2 = new File(SU_PATH2); if (su2.exists() && su2.isFile() && su2.canExecute()) { return SU_PATH2; } return null; } private static class Data { boolean fullScreen = false; boolean titleVisible = true; final AtomicBoolean fullScreenState = new AtomicBoolean(); } }
bonisamber/bookreader
Application/src/main/java/org/emdev/ui/uimanager/UIManager3x.java
Java
gpl-3.0
8,692
/** Copyright 2012 John Cummens (aka Shadowmage, Shadowmage4513) This software is distributed under the terms of the GNU General Public License. Please see COPYING for precise license information. This file is part of Ancient Warfare. Ancient Warfare 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. Ancient Warfare 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 Ancient Warfare. If not, see <http://www.gnu.org/licenses/>. */ package shadowmage.ancient_warfare.common.vehicles.types; import net.minecraft.block.Block; import net.minecraft.item.Item; import shadowmage.ancient_warfare.common.config.Config; import shadowmage.ancient_warfare.common.item.ItemLoader; import shadowmage.ancient_warfare.common.registry.ArmorRegistry; import shadowmage.ancient_warfare.common.registry.VehicleUpgradeRegistry; import shadowmage.ancient_warfare.common.research.ResearchGoal; import shadowmage.ancient_warfare.common.utils.ItemStackWrapperCrafting; import shadowmage.ancient_warfare.common.vehicles.VehicleBase; import shadowmage.ancient_warfare.common.vehicles.VehicleMovementType; import shadowmage.ancient_warfare.common.vehicles.VehicleVarHelpers.BallistaVarHelper; import shadowmage.ancient_warfare.common.vehicles.helpers.VehicleFiringVarsHelper; import shadowmage.ancient_warfare.common.vehicles.materials.VehicleMaterial; import shadowmage.ancient_warfare.common.vehicles.missiles.Ammo; public class VehicleTypeBoatBallista extends VehicleType { /** * @param typeNum */ public VehicleTypeBoatBallista(int typeNum) { super(typeNum); this.configName = "boat_ballista"; this.vehicleMaterial = VehicleMaterial.materialWood; this.materialCount = 5; this.movementType = VehicleMovementType.WATER; this.maxMissileWeight = 2.f; this.validAmmoTypes.add(Ammo.ammoBallistaBolt); this.validAmmoTypes.add(Ammo.ammoBallistaBoltFlame); this.validAmmoTypes.add(Ammo.ammoBallistaBoltExplosive); this.validAmmoTypes.add(Ammo.ammoBallistaBoltIron); this.ammoBySoldierRank.put(0, Ammo.ammoBallistaBolt); this.ammoBySoldierRank.put(1, Ammo.ammoBallistaBolt); this.ammoBySoldierRank.put(2, Ammo.ammoBallistaBoltFlame); this.validUpgrades.add(VehicleUpgradeRegistry.speedUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.pitchDownUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.pitchUpUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.pitchExtUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.powerUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.reloadUpgrade); this.validUpgrades.add(VehicleUpgradeRegistry.aimUpgrade); this.validArmors.add(ArmorRegistry.armorStone); this.validArmors.add(ArmorRegistry.armorObsidian); this.validArmors.add(ArmorRegistry.armorIron); this.armorBaySize = 3; this.upgradeBaySize = 3; this.ammoBaySize = 6; this.storageBaySize = 0; this.addNeededResearchForMaterials(); this.addNeededResearch(0, ResearchGoal.vehicleTorsion1); this.addNeededResearch(1, ResearchGoal.vehicleTorsion2); this.addNeededResearch(2, ResearchGoal.vehicleTorsion3); this.addNeededResearch(3, ResearchGoal.vehicleTorsion4); this.addNeededResearch(4, ResearchGoal.vehicleTorsion5); this.addNeededResearch(0, ResearchGoal.vehicleMobility1); this.addNeededResearch(1, ResearchGoal.vehicleMobility2); this.addNeededResearch(2, ResearchGoal.vehicleMobility3); this.addNeededResearch(3, ResearchGoal.vehicleMobility4); this.addNeededResearch(4, ResearchGoal.vehicleMobility5); this.addNeededResearch(0, ResearchGoal.upgradeMechanics1); this.addNeededResearch(1, ResearchGoal.upgradeMechanics2); this.addNeededResearch(2, ResearchGoal.upgradeMechanics3); this.addNeededResearch(3, ResearchGoal.upgradeMechanics4); this.addNeededResearch(4, ResearchGoal.upgradeMechanics5); this.additionalMaterials.add(new ItemStackWrapperCrafting(Item.silk, 8, false, false)); this.additionalMaterials.add(new ItemStackWrapperCrafting(ItemLoader.torsionUnit, 2, false, false)); this.additionalMaterials.add(new ItemStackWrapperCrafting(ItemLoader.equipmentBay, 1, false, false)); this.additionalMaterials.add(new ItemStackWrapperCrafting(ItemLoader.mobilityUnit, 1, false, false)); this.additionalMaterials.add(new ItemStackWrapperCrafting(Block.cactus, 2, false, false)); this.width = 2.7f; this.height = 1.4f; this.baseStrafeSpeed = 2.f; this.baseForwardSpeed = 6.2f*0.05f; this.turretForwardsOffset = 23*0.0625f; this.turretVerticalOffset = 1.325f; this.accuracy = 0.98f; this.basePitchMax = 15; this.basePitchMin = -15; this.baseMissileVelocityMax = 42.f;//stand versions should have higher velocity, as should fixed version--i.e. mobile turret should have the worst of all versions this.riderForwardsOffset = -1.0f ; this.riderVerticalOffset = 0.7f; this.shouldRiderSit = true; this.isMountable = true; this.isDrivable = true;//adjust based on isMobile or not this.isCombatEngine = true; this.canAdjustPitch = true; this.canAdjustPower = false; this.canAdjustYaw = true; this.turretRotationMax=360.f;//adjust based on mobile/stand fixed (0), stand fixed(90'), or mobile or stand turret (360) this.displayName = "item.vehicleSpawner.18"; this.displayTooltip.add("item.vehicleSpawner.tooltip.torsion"); this.displayTooltip.add("item.vehicleSpawner.tooltip.boat"); this.displayTooltip.add("item.vehicleSpawner.tooltip.fullturret"); } @Override public String getTextureForMaterialLevel(int level) { switch(level) { case 0: return Config.texturePath + "models/boatBallista1.png"; case 1: return Config.texturePath + "models/boatBallista2.png"; case 2: return Config.texturePath + "models/boatBallista3.png"; case 3: return Config.texturePath + "models/boatBallista4.png"; case 4: return Config.texturePath + "models/boatBallista5.png"; default: return Config.texturePath + "models/boatBallista1.png"; } } @Override public VehicleFiringVarsHelper getFiringVarsHelper(VehicleBase veh) { return new BallistaVarHelper(veh); } }
shadowmage45/AncientWarfare
AncientWarfare/src/shadowmage/ancient_warfare/common/vehicles/types/VehicleTypeBoatBallista.java
Java
gpl-3.0
6,768
package com.andyadc.concurrency.latch; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.*; /** * @author andaicheng * @version 2017/3/10 */ public class LatchDemo_1 { public static void main(String[] args) throws Exception { int num = 10; //发令枪只只响一次 CountDownLatch begin = new CountDownLatch(1); //参与跑步人数 CountDownLatch end = new CountDownLatch(num); ExecutorService es = Executors.newFixedThreadPool(num); //记录跑步成绩 List<Future<Integer>> futures = new ArrayList<>(); for (int i = 0; i < num; i++) { futures.add(es.submit(new Runner(begin, end))); } //预备 TimeUnit.SECONDS.sleep(10); //发令枪响 begin.countDown(); //等待跑者跑完 end.await(); int sum = 0; for (Future<Integer> f : futures) { sum += f.get(); } System.out.println("平均分数: " + (float) (sum / num)); } } class Runner implements Callable<Integer> { //开始信号 private CountDownLatch begin; //结束信号 private CountDownLatch end; public Runner(CountDownLatch begin, CountDownLatch end) { this.begin = begin; this.end = end; } @Override public Integer call() throws Exception { //跑步成绩 int score = new Random().nextInt(10); //等待发令枪响 begin.await(); TimeUnit.SECONDS.sleep(score); //跑步结束 end.countDown(); System.out.println("score:" + score); return score; } }
andyadc/java-study
concurrency-study/src/main/java/com/andyadc/concurrency/latch/LatchDemo_1.java
Java
gpl-3.0
1,769
package com.infamous.performance.activities; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.os.SystemClock; import android.preference.PreferenceManager; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.infamous.performance.R; import com.infamous.performance.util.ActivityThemeChangeInterface; import com.infamous.performance.util.Constants; import com.infamous.performance.util.Helpers; /** * Created by h0rn3t on 09.02.2014. * http://forum.xda-developers.com/member.php?u=4674443 */ public class checkSU extends Activity implements Constants, ActivityThemeChangeInterface { private boolean mIsLightTheme; private ProgressBar wait; private TextView info; private ImageView attn; SharedPreferences mPreferences; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); setTheme(); setContentView(R.layout.check_su); wait=(ProgressBar) findViewById(R.id.wait); info=(TextView) findViewById(R.id.info); attn=(ImageView) findViewById(R.id.attn); if(mPreferences.getBoolean("booting",false)) { info.setText(getString(R.string.boot_wait)); wait.setVisibility(View.GONE); attn.setVisibility(View.VISIBLE); } else { new TestSU().execute(); } } private class TestSU extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { SystemClock.sleep(1000); final Boolean canSu = Helpers.checkSu(); final Boolean canBb = Helpers.binExist("busybox")!=null; if (canSu && canBb) return "ok"; else return "nok"; } @Override protected void onPostExecute(String result) { if(result.equals("nok")){ //mPreferences.edit().putBoolean("firstrun", true).commit(); info.setText(getString(R.string.su_failed_su_or_busybox)); wait.setVisibility(View.GONE); attn.setVisibility(View.VISIBLE); } else{ //mPreferences.edit().putBoolean("firstrun", false).commit(); Intent returnIntent = new Intent(); returnIntent.putExtra("r",result); setResult(RESULT_OK,returnIntent); finish(); } } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Void... values) { } } @Override public boolean isThemeChanged() { final boolean is_light_theme = mPreferences.getBoolean(PREF_USE_LIGHT_THEME, false); return is_light_theme != mIsLightTheme; } @Override public void setTheme() { final boolean is_light_theme = mPreferences.getBoolean(PREF_USE_LIGHT_THEME, false); mIsLightTheme = is_light_theme; setTheme(is_light_theme ? R.style.Theme_Light : R.style.Theme_Dark); } @Override public void onResume() { super.onResume(); } }
InfamousProductions/Infamous_Performance
src/com/infamous/performance/activities/checkSU.java
Java
gpl-3.0
3,396
// Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) package MJDecompiler; import java.io.IOException; // Referenced classes of package MJDecompiler: // bm, bf, bh, bj, // bc final class as extends CpField { as(ClazzInputStream bc, ClassFile bj1) throws IOException { super(bc, bj1); } final void writeBytecode(ByteCodeOutput bf1) throws IOException { bf1.writeByte(9); bf1.writeUshort(super.b); bf1.writeUshort(super.o); } final String type() { return super.a.getConstant(super.o).type(); } final String a(ClassFile bj1) { return "FieldRef(" + super.b + ":" + bj1.getConstant(super.b).a(bj1) + ", " + super.o + ":" + bj1.getConstant(super.o).a(bj1) + ")"; } }
ghostgzt/STX
src/MJDecompiler/as.java
Java
gpl-3.0
839
package com.zalthrion.zylroth.handler; import net.minecraft.client.settings.KeyBinding; import org.lwjgl.input.Keyboard; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class KeyHandler { @SideOnly(Side.CLIENT) public static KeyBinding openSummonGui; public static void init() { openSummonGui = new KeyBinding("key.zylroth:summongui", Keyboard.KEY_Z, "key.categories.zylroth"); ClientRegistry.registerKeyBinding(openSummonGui); } }
Zalthrion/Zyl-Roth
src/main/java/com/zalthrion/zylroth/handler/KeyHandler.java
Java
gpl-3.0
533
/* * Copyright (c) 2014 Ian Bondoc * * This file is part of Jen8583 * * Jen8583 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. * * Jen8583 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.chiknrice.iso.codec; import org.chiknrice.iso.config.ComponentDef.Encoding; import java.nio.ByteBuffer; /** * The main contract for a codec used across encoding and decoding of message components. Each field/component of the * ISO message would have its own instance of codec which contains the definition of how the value should be * encoded/decoded. The codec should be designed to be thread safe as the instance would live throughout the life of the * IsoMessageDef. Any issues encountered during encoding/decoding should be throwing a CodecException. Any issues * encountered during codec configuration/construction the constructor should throw a ConfigException. A ConfigException * should generally happen during startup while CodecException happens when the Codec is being used. * * @author <a href="mailto:chiknrice@gmail.com">Ian Bondoc</a> */ public interface Codec<T> { /** * The implementation should define how the value T should be decoded from the ByteBuffer provided. The * implementation could either decode the value from a certain number of bytes or consume the whole ByteBuffer. * * @param buf * @return the decoded value */ T decode(ByteBuffer buf); /** * The implementation should define how the value T should be encoded to the ByteBuffer provided. The ByteBuffer * assumes the value would be encoded from the current position. * * @param buf * @param value the value to be encoded */ void encode(ByteBuffer buf, T value); /** * Defines how the value should be encoded/decoded. * * @return the encoding defined for the value. */ Encoding getEncoding(); }
chiknrice/jen8583
src/main/java/org/chiknrice/iso/codec/Codec.java
Java
gpl-3.0
2,477
package ru.trolsoft.utils.files; import ru.trolsoft.utils.StrUtils; import java.io.*; import java.util.Random; /** * Created on 07/02/17. */ public class IntelHexWriter { private final Writer writer; /** * */ private int segmentAddress = 0; public IntelHexWriter(Writer writer) { if (writer instanceof BufferedWriter) { this.writer = writer; } else { this.writer = new BufferedWriter(writer); } } // public IntelHexWriter(String fileName) throws IOException { // this(new FileWriter(fileName)); // } public void addData(int offset, byte data[], int bytesPerLine) throws IOException { if (data.length == 0) { return; } //System.out.println("::" + data.length); byte buf[] = new byte[bytesPerLine]; int pos = 0; int bytesToAdd = data.length; while (bytesToAdd > 0) { if (offset % bytesPerLine != 0) { // can be true for first line if offset doesn't aligned buf = new byte[bytesPerLine - offset % bytesPerLine]; } else if (bytesToAdd < bytesPerLine) { // last line buf = new byte[bytesToAdd]; } else if (buf.length != bytesPerLine) { buf = new byte[bytesPerLine]; } System.arraycopy(data, pos, buf, 0, buf.length); // Goto next segment if no more space available in current if (offset + buf.length - 1 > segmentAddress + 0xffff) { int nextSegment = ((offset + bytesPerLine) >> 4) << 4; addSegmentRecord(nextSegment); segmentAddress = nextSegment; } addDataRecord(offset & 0xffff, buf); bytesToAdd -= buf.length; offset += buf.length; pos += buf.length; } } private void addSegmentRecord(int offset) throws IOException { int paragraph = offset >> 4; int hi = (paragraph >> 8) & 0xff; int lo = paragraph & 0xff; int crc = 2 + 2 + hi + lo; crc = (-crc) & 0xff; String rec = ":02000002" + hex(hi) + hex(lo) + hex(crc); write(rec); // 02 0000 02 10 00 EC //:02 0000 04 00 01 F9 } private void addEofRecord() throws IOException { write(":00000001FF"); } private void write(String s) throws IOException { writer.write(s); //writer.write(0x0d); writer.write(0x0a); } private void addDataRecord(int offset, byte[] data) throws IOException { int hi = (offset >> 8) & 0xff; int lo = offset & 0xff; int crc = data.length + hi + lo; String rec = ":" + hex(data.length) + hex(hi) + hex(lo) + "00"; for (byte d : data) { rec += hex(d); crc += d; } crc = (-crc) & 0xff; rec += hex(crc); write(rec); } private static String hex(int b) { return StrUtils.byteToHexStr((byte)b); } public void done() throws IOException { addEofRecord(); writer.flush(); } public static void main(String ... args) throws IOException { IntelHexWriter w = new IntelHexWriter(new OutputStreamWriter(System.out)); // w.addDataRecord(0x0190, new byte[] {0x56, 0x45, 0x52, 0x53, 0x49, 0x4F, 0x4E, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x41, // 0x54, 0x0D, 0x0A}); byte[] data = new byte[Math.abs(new Random().nextInt() % 1024)]; for (int i = 0; i < data.length; i++) { data[i] = (byte) (i % 0xff); } w.addData(0x10000 - 0x100, data, 16); w.done(); } }
trol73/avr-bootloader
software/java/src/ru/trolsoft/utils/files/IntelHexWriter.java
Java
gpl-3.0
3,697
/* * Copyright (c) 2010 The University of Reading * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 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. Neither the name of the University of Reading, nor the names of the * authors or contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 uk.ac.rdg.resc.edal.coverage.domain; import java.util.List; import org.opengis.referencing.crs.CoordinateReferenceSystem; /** * A geospatial/temporal domain: defines the set of points for which a {@link DiscreteCoverage} * is defined. The domain is comprised of a set of unique domain objects in a * defined order. The domain therefore has the semantics of both a {@link Set} * and a {@link List} of domain objects. * @param <DO> The type of the domain object * @author Jon */ public interface Domain<DO> { /** * Gets the coordinate reference system to which objects in this domain are * referenced. Returns null if the domain objects cannot be referenced * to an external coordinate reference system. * @return the coordinate reference system to which objects in this domain are * referenced, or null if the domain objects are not externally referenced. */ public CoordinateReferenceSystem getCoordinateReferenceSystem(); /** * Returns the {@link List} of domain objects that comprise this domain. * @todo There may be issues for large grids if the number of domain objects * is greater than Integer.MAX_VALUE, as the size of this list will be recorded * incorrectly. This will only happen for very large domains (e.g. large grids). */ public List<DO> getDomainObjects(); /** * <p>Returns the number of domain objects in the domain.</p> * <p>This is a long integer because grids can grow very large, beyond the * range of a 4-byte integer.</p> */ public long size(); }
nansencenter/GreenSeasADC-portlet
docroot/WEB-INF/src/uk/ac/rdg/resc/edal/coverage/domain/Domain.java
Java
gpl-3.0
3,145
/***************************************************************** * This file is part of Managing Agricultural Research for Learning & * Outcomes Platform (MARLO). * MARLO 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. * MARLO 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 MARLO. If not, see <http://www.gnu.org/licenses/>. *****************************************************************/ package org.cgiar.ccafs.marlo.data.manager.impl; import org.cgiar.ccafs.marlo.data.dao.ReportSynthesisGovernanceDAO; import org.cgiar.ccafs.marlo.data.manager.ReportSynthesisGovernanceManager; import org.cgiar.ccafs.marlo.data.model.ReportSynthesisGovernance; import java.util.List; import javax.inject.Inject; import javax.inject.Named; /** * @author CCAFS */ @Named public class ReportSynthesisGovernanceManagerImpl implements ReportSynthesisGovernanceManager { private ReportSynthesisGovernanceDAO reportSynthesisGovernanceDAO; // Managers @Inject public ReportSynthesisGovernanceManagerImpl(ReportSynthesisGovernanceDAO reportSynthesisGovernanceDAO) { this.reportSynthesisGovernanceDAO = reportSynthesisGovernanceDAO; } @Override public void deleteReportSynthesisGovernance(long reportSynthesisGovernanceId) { reportSynthesisGovernanceDAO.deleteReportSynthesisGovernance(reportSynthesisGovernanceId); } @Override public boolean existReportSynthesisGovernance(long reportSynthesisGovernanceID) { return reportSynthesisGovernanceDAO.existReportSynthesisGovernance(reportSynthesisGovernanceID); } @Override public List<ReportSynthesisGovernance> findAll() { return reportSynthesisGovernanceDAO.findAll(); } @Override public ReportSynthesisGovernance getReportSynthesisGovernanceById(long reportSynthesisGovernanceID) { return reportSynthesisGovernanceDAO.find(reportSynthesisGovernanceID); } @Override public ReportSynthesisGovernance saveReportSynthesisGovernance(ReportSynthesisGovernance reportSynthesisGovernance) { return reportSynthesisGovernanceDAO.save(reportSynthesisGovernance); } }
CCAFS/MARLO
marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/ReportSynthesisGovernanceManagerImpl.java
Java
gpl-3.0
2,612
package com.entrepidea.jvm; import java.util.ArrayList; import java.util.List; /** * @Desc: * @Source: 深入理解Java虚拟机:JVM高级特性与最佳实践(第2版) * Created by jonat on 10/18/2019. * TODO need revisit - the code seem just running - supposedly it should end soon with exceptions. */ public class RuntimeConstantPoolOOM { public static void main(String[] args){ List<String> l = new ArrayList<>(); int i=0; while(true){ l.add(String.valueOf(i++).intern()); } } }
entrepidea/projects
java/java.core/src/main/java/com/entrepidea/jvm/RuntimeConstantPoolOOM.java
Java
gpl-3.0
551
package com.kimkha.finanvita.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.util.SparseBooleanArray; import android.view.*; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; import com.kimkha.finanvita.R; import com.kimkha.finanvita.adapters.AbstractCursorAdapter; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public abstract class ItemListFragment extends BaseFragment implements AdapterView.OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> { public static final String RESULT_EXTRA_ITEM_ID = ItemListFragment.class.getName() + ".RESULT_EXTRA_ITEM_ID"; public static final String RESULT_EXTRA_ITEM_IDS = ItemListFragment.class.getName() + ".RESULT_EXTRA_ITEM_IDS"; // ----------------------------------------------------------------------------------------------------------------- public static final int SELECTION_TYPE_NONE = 0; public static final int SELECTION_TYPE_SINGLE = 1; public static final int SELECTION_TYPE_MULTI = 2; // ----------------------------------------------------------------------------------------------------------------- protected static final String ARG_SELECTION_TYPE = "ARG_SELECTION_TYPE"; protected static final String ARG_ITEM_IDS = "ARG_ITEM_IDS"; protected static final String ARG_IS_OPEN_DRAWER_LAYOUT = "ARG_IS_OPEN_DRAWER_LAYOUT"; // ----------------------------------------------------------------------------------------------------------------- protected static final String STATE_SELECTED_POSITIONS = "STATE_SELECTED_POSITIONS"; // ----------------------------------------------------------------------------------------------------------------- protected static final int LOADER_ITEMS = 1468; // ----------------------------------------------------------------------------------------------------------------- protected ListView list_V; protected View create_V; // ----------------------------------------------------------------------------------------------------------------- protected AbstractCursorAdapter adapter; protected int selectionType; public static Bundle makeArgs(int selectionType, long[] itemIDs) { return makeArgs(selectionType, itemIDs, false); } public static Bundle makeArgs(int selectionType, long[] itemIDs, boolean isOpenDrawerLayout) { final Bundle args = new Bundle(); args.putInt(ARG_SELECTION_TYPE, selectionType); args.putLongArray(ARG_ITEM_IDS, itemIDs); args.putBoolean(ARG_IS_OPEN_DRAWER_LAYOUT, isOpenDrawerLayout); return args; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); // Get arguments final Bundle args = getArguments(); selectionType = args != null ? args.getInt(ARG_SELECTION_TYPE, SELECTION_TYPE_NONE) : SELECTION_TYPE_NONE; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_items_list, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Get views list_V = (ListView) view.findViewById(R.id.list_V); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Setup if (selectionType == SELECTION_TYPE_NONE) { create_V = LayoutInflater.from(getActivity()).inflate(R.layout.li_create_new, list_V, false); list_V.addFooterView(create_V); } adapter = createAdapter(getActivity()); list_V.setAdapter(adapter); list_V.setOnItemClickListener(this); if (getArguments().getBoolean(ARG_IS_OPEN_DRAWER_LAYOUT, false)) { final int paddingHorizontal = getResources().getDimensionPixelSize(R.dimen.dynamic_margin_drawer_narrow_horizontal); list_V.setPadding(paddingHorizontal, list_V.getPaddingTop(), paddingHorizontal, list_V.getPaddingBottom()); } if (selectionType == SELECTION_TYPE_MULTI) { list_V.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); if (savedInstanceState != null) { final ArrayList<Integer> selectedPositions = savedInstanceState.getIntegerArrayList(STATE_SELECTED_POSITIONS); list_V.setTag(selectedPositions); } else { final long[] selectedIDs = getArguments().getLongArray(ARG_ITEM_IDS); list_V.setTag(selectedIDs); } } // Loader getLoaderManager().initLoader(LOADER_ITEMS, null, this); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (selectionType == SELECTION_TYPE_MULTI) { final ArrayList<Integer> selectedPositions = new ArrayList<Integer>(); final SparseBooleanArray listPositions = list_V.getCheckedItemPositions(); if (listPositions != null) { for (int i = 0; i < listPositions.size(); i++) { if (listPositions.get(listPositions.keyAt(i))) selectedPositions.add(listPositions.keyAt(i)); } } outState.putIntegerArrayList(STATE_SELECTED_POSITIONS, selectedPositions); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.items_list, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_create: startItemCreate(getActivity(), item.getActionView()); return true; } return super.onOptionsItemSelected(item); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle bundle) { switch (id) { case LOADER_ITEMS: return createItemsLoader(); } return null; } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { switch (cursorLoader.getId()) { case LOADER_ITEMS: bindItems(cursor); break; } } @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { switch (cursorLoader.getId()) { case LOADER_ITEMS: bindItems(null); break; } } @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { switch (selectionType) { case SELECTION_TYPE_NONE: if (position == adapter.getCount()) startItemCreate(getActivity(), view); else startItemDetails(getActivity(), id, position, adapter, adapter.getCursor(), view); break; case SELECTION_TYPE_SINGLE: // Prepare extras final Bundle extras = new Bundle(); onItemSelected(id, adapter, adapter.getCursor(), extras); Intent data = new Intent(); data.putExtra(RESULT_EXTRA_ITEM_ID, id); data.putExtras(extras); getActivity().setResult(Activity.RESULT_OK, data); getActivity().finish(); break; case SELECTION_TYPE_MULTI: adapter.setSelectedIDs(list_V.getCheckedItemIds()); break; } } protected abstract AbstractCursorAdapter createAdapter(Context context); protected abstract Loader<Cursor> createItemsLoader(); /** * Called when item id along with extras should be returned to another activity. If only item id is necessary, you don't need to do anything. Just extra values should be put in outExtras. * * @param itemId Id of selected item. You don't need to put it to extras. This will be done automatically. * @param adapter Adapter for convenience. * @param c Cursor. * @param outExtras Put all additional data in here. */ protected abstract void onItemSelected(long itemId, AbstractCursorAdapter adapter, Cursor c, Bundle outExtras); /** * Called when you should start item detail activity * * @param context Context. * @param itemId Id of selected item. * @param position Selected position. * @param adapter Adapter for convenience. * @param c Cursor. * @param view */ protected abstract void startItemDetails(Context context, long itemId, int position, AbstractCursorAdapter adapter, Cursor c, View view); /** * Start item create activity here. */ protected abstract void startItemCreate(Context context, View view); public long[] getSelectedItemIDs() { return list_V.getCheckedItemIds(); } protected void bindItems(Cursor c) { boolean needUpdateSelectedIDs = adapter.getCount() == 0 && selectionType == SELECTION_TYPE_MULTI; adapter.swapCursor(c); if (needUpdateSelectedIDs && list_V.getTag() != null) { final Object tag = list_V.getTag(); if (tag instanceof ArrayList) { //noinspection unchecked final ArrayList<Integer> selectedPositions = (ArrayList<Integer>) tag; list_V.setTag(selectedPositions); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < selectedPositions.size(); i++) list_V.setItemChecked(selectedPositions.get(i), true); } else if (tag instanceof long[]) { final long[] selectedIDs = (long[]) tag; final Set<Long> selectedIDsSet = new HashSet<Long>(); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < selectedIDs.length; i++) selectedIDsSet.add(selectedIDs[i]); long itemId; for (int i = 0; i < adapter.getCount(); i++) { itemId = list_V.getItemIdAtPosition(i); if (selectedIDsSet.contains(itemId)) { selectedIDsSet.remove(itemId); list_V.setItemChecked(i, true); if (selectedIDsSet.size() == 0) break; } } } adapter.setSelectedIDs(list_V.getCheckedItemIds()); } } }
kimkha/Finanvita
Finanvita/src/main/java/com/kimkha/finanvita/ui/ItemListFragment.java
Java
gpl-3.0
11,290
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.content; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.Resources; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.UserHandle; import android.view.DisplayAdjustments; import android.view.Display; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * Proxying implementation of Context that simply delegates all of its calls to * another Context. Can be subclassed to modify behavior without changing * the original Context. */ public class ContextWrapper extends Context { Context mBase; public ContextWrapper(Context base) { mBase = base; } /** * Set the base context for this ContextWrapper. All calls will then be * delegated to the base context. Throws * IllegalStateException if a base context has already been set. * * @param base The new base context for this wrapper. */ protected void attachBaseContext(Context base) { if (mBase != null) { throw new IllegalStateException("Base context already set"); } mBase = base; } /** * @return the base context as set by the constructor or setBaseContext */ public Context getBaseContext() { return mBase; } @Override public AssetManager getAssets() { return mBase.getAssets(); } @Override public Resources getResources() { return mBase.getResources(); } @Override public PackageManager getPackageManager() { return mBase.getPackageManager(); } @Override public ContentResolver getContentResolver() { return mBase.getContentResolver(); } @Override public Looper getMainLooper() { return mBase.getMainLooper(); } @Override public Context getApplicationContext() { return mBase.getApplicationContext(); } @Override public void setTheme(int resid) { mBase.setTheme(resid); } /** @hide */ @Override public int getThemeResId() { return mBase.getThemeResId(); } @Override public Resources.Theme getTheme() { return mBase.getTheme(); } @Override public ClassLoader getClassLoader() { return mBase.getClassLoader(); } @Override public String getPackageName() { return mBase.getPackageName(); } /** @hide */ @Override public String getBasePackageName() { return mBase.getBasePackageName(); } /** @hide */ @Override public String getOpPackageName() { return mBase.getOpPackageName(); } @Override public ApplicationInfo getApplicationInfo() { return mBase.getApplicationInfo(); } @Override public String getPackageResourcePath() { return mBase.getPackageResourcePath(); } @Override public String getPackageCodePath() { return mBase.getPackageCodePath(); } /** @hide */ @Override public File getSharedPrefsFile(String name) { return mBase.getSharedPrefsFile(name); } @Override public SharedPreferences getSharedPreferences(String name, int mode) { return mBase.getSharedPreferences(name, mode); } @Override public FileInputStream openFileInput(String name) throws FileNotFoundException { return mBase.openFileInput(name); } @Override public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException { return mBase.openFileOutput(name, mode); } @Override public boolean deleteFile(String name) { return mBase.deleteFile(name); } @Override public File getFileStreamPath(String name) { return mBase.getFileStreamPath(name); } @Override public String[] fileList() { return mBase.fileList(); } @Override public File getFilesDir() { return mBase.getFilesDir(); } @Override public File getNoBackupFilesDir() { return mBase.getNoBackupFilesDir(); } @Override public File getExternalFilesDir(String type) { return mBase.getExternalFilesDir(type); } @Override public File[] getExternalFilesDirs(String type) { return mBase.getExternalFilesDirs(type); } @Override public File getObbDir() { return mBase.getObbDir(); } @Override public File[] getObbDirs() { return mBase.getObbDirs(); } @Override public File getCacheDir() { return mBase.getCacheDir(); } @Override public File getCodeCacheDir() { return mBase.getCodeCacheDir(); } @Override public File getExternalCacheDir() { return mBase.getExternalCacheDir(); } @Override public File[] getExternalCacheDirs() { return mBase.getExternalCacheDirs(); } @Override public File[] getExternalMediaDirs() { return mBase.getExternalMediaDirs(); } @Override public File getDir(String name, int mode) { return mBase.getDir(name, mode); } @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) { return mBase.openOrCreateDatabase(name, mode, factory); } @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory, DatabaseErrorHandler errorHandler) { return mBase.openOrCreateDatabase(name, mode, factory, errorHandler); } @Override public boolean deleteDatabase(String name) { return mBase.deleteDatabase(name); } @Override public File getDatabasePath(String name) { return mBase.getDatabasePath(name); } @Override public String[] databaseList() { return mBase.databaseList(); } @Override public Drawable getWallpaper() { return mBase.getWallpaper(); } @Override public Drawable peekWallpaper() { return mBase.peekWallpaper(); } @Override public int getWallpaperDesiredMinimumWidth() { return mBase.getWallpaperDesiredMinimumWidth(); } @Override public int getWallpaperDesiredMinimumHeight() { return mBase.getWallpaperDesiredMinimumHeight(); } @Override public void setWallpaper(Bitmap bitmap) throws IOException { mBase.setWallpaper(bitmap); } @Override public void setWallpaper(InputStream data) throws IOException { mBase.setWallpaper(data); } @Override public void clearWallpaper() throws IOException { mBase.clearWallpaper(); } @Override public void startActivity(Intent intent) { mBase.startActivity(intent); } /** @hide */ @Override public void startActivityAsUser(Intent intent, UserHandle user) { mBase.startActivityAsUser(intent, user); } @Override public void startActivity(Intent intent, Bundle options) { mBase.startActivity(intent, options); } /** @hide */ @Override public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) { mBase.startActivityAsUser(intent, options, user); } @Override public void startActivities(Intent[] intents) { mBase.startActivities(intents); } @Override public void startActivities(Intent[] intents, Bundle options) { mBase.startActivities(intents, options); } /** @hide */ @Override public void startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) { mBase.startActivitiesAsUser(intents, options, userHandle); } @Override public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException { mBase.startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags); } @Override public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException { mBase.startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, options); } @Override public void sendBroadcast(Intent intent) { mBase.sendBroadcast(intent); } @Override public void sendBroadcast(Intent intent, String receiverPermission) { mBase.sendBroadcast(intent, receiverPermission); } /** @hide */ @Override public void sendBroadcast(Intent intent, String receiverPermission, int appOp) { mBase.sendBroadcast(intent, receiverPermission, appOp); } @Override public void sendOrderedBroadcast(Intent intent, String receiverPermission) { mBase.sendOrderedBroadcast(intent, receiverPermission); } @Override public void sendOrderedBroadcast( Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras); } /** @hide */ @Override public void sendOrderedBroadcast( Intent intent, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcast(intent, receiverPermission, appOp, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void sendBroadcastAsUser(Intent intent, UserHandle user) { mBase.sendBroadcastAsUser(intent, user); } @Override public void sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission) { mBase.sendBroadcastAsUser(intent, user, receiverPermission); } @Override public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcastAsUser(intent, user, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras); } /** @hide */ @Override public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendOrderedBroadcastAsUser(intent, user, receiverPermission, appOp, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void sendStickyBroadcast(Intent intent) { mBase.sendStickyBroadcast(intent); } @Override public void sendStickyOrderedBroadcast( Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendStickyOrderedBroadcast(intent, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void removeStickyBroadcast(Intent intent) { mBase.removeStickyBroadcast(intent); } @Override public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) { mBase.sendStickyBroadcastAsUser(intent, user); } @Override public void sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle user, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { mBase.sendStickyOrderedBroadcastAsUser(intent, user, resultReceiver, scheduler, initialCode, initialData, initialExtras); } @Override public void removeStickyBroadcastAsUser(Intent intent, UserHandle user) { mBase.removeStickyBroadcastAsUser(intent, user); } @Override public Intent registerReceiver( BroadcastReceiver receiver, IntentFilter filter) { return mBase.registerReceiver(receiver, filter); } @Override public Intent registerReceiver( BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) { return mBase.registerReceiver(receiver, filter, broadcastPermission, scheduler); } /** @hide */ @Override public Intent registerReceiverAsUser( BroadcastReceiver receiver, UserHandle user, IntentFilter filter, String broadcastPermission, Handler scheduler) { return mBase.registerReceiverAsUser(receiver, user, filter, broadcastPermission, scheduler); } @Override public void unregisterReceiver(BroadcastReceiver receiver) { mBase.unregisterReceiver(receiver); } @Override public ComponentName startService(Intent service) { return mBase.startService(service); } @Override public boolean stopService(Intent name) { return mBase.stopService(name); } /** @hide */ @Override public ComponentName startServiceAsUser(Intent service, UserHandle user) { return mBase.startServiceAsUser(service, user); } /** @hide */ @Override public boolean stopServiceAsUser(Intent name, UserHandle user) { return mBase.stopServiceAsUser(name, user); } @Override public boolean bindService(Intent service, ServiceConnection conn, int flags) { return mBase.bindService(service, conn, flags); } /** @hide */ @Override public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags, UserHandle user) { return mBase.bindServiceAsUser(service, conn, flags, user); } @Override public void unbindService(ServiceConnection conn) { mBase.unbindService(conn); } @Override public boolean startInstrumentation(ComponentName className, String profileFile, Bundle arguments) { return mBase.startInstrumentation(className, profileFile, arguments); } @Override public Object getSystemService(String name) { return mBase.getSystemService(name); } @Override public int checkPermission(String permission, int pid, int uid) { return mBase.checkPermission(permission, pid, uid); } /** @hide */ @Override public int checkPermission(String permission, int pid, int uid, IBinder callerToken) { return mBase.checkPermission(permission, pid, uid, callerToken); } @Override public int checkCallingPermission(String permission) { return mBase.checkCallingPermission(permission); } @Override public int checkCallingOrSelfPermission(String permission) { return mBase.checkCallingOrSelfPermission(permission); } @Override public void enforcePermission( String permission, int pid, int uid, String message) { mBase.enforcePermission(permission, pid, uid, message); } @Override public void enforceCallingPermission(String permission, String message) { mBase.enforceCallingPermission(permission, message); } @Override public void enforceCallingOrSelfPermission( String permission, String message) { mBase.enforceCallingOrSelfPermission(permission, message); } @Override public void grantUriPermission(String toPackage, Uri uri, int modeFlags) { mBase.grantUriPermission(toPackage, uri, modeFlags); } @Override public void revokeUriPermission(Uri uri, int modeFlags) { mBase.revokeUriPermission(uri, modeFlags); } @Override public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) { return mBase.checkUriPermission(uri, pid, uid, modeFlags); } /** @hide */ @Override public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags, IBinder callerToken) { return mBase.checkUriPermission(uri, pid, uid, modeFlags, callerToken); } @Override public int checkCallingUriPermission(Uri uri, int modeFlags) { return mBase.checkCallingUriPermission(uri, modeFlags); } @Override public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) { return mBase.checkCallingOrSelfUriPermission(uri, modeFlags); } @Override public int checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags) { return mBase.checkUriPermission(uri, readPermission, writePermission, pid, uid, modeFlags); } @Override public void enforceUriPermission( Uri uri, int pid, int uid, int modeFlags, String message) { mBase.enforceUriPermission(uri, pid, uid, modeFlags, message); } @Override public void enforceCallingUriPermission( Uri uri, int modeFlags, String message) { mBase.enforceCallingUriPermission(uri, modeFlags, message); } @Override public void enforceCallingOrSelfUriPermission( Uri uri, int modeFlags, String message) { mBase.enforceCallingOrSelfUriPermission(uri, modeFlags, message); } @Override public void enforceUriPermission( Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags, String message) { mBase.enforceUriPermission( uri, readPermission, writePermission, pid, uid, modeFlags, message); } @Override public Context createPackageContext(String packageName, int flags) throws PackageManager.NameNotFoundException { return mBase.createPackageContext(packageName, flags); } /** @hide */ @Override public Context createPackageContextAsUser(String packageName, int flags, UserHandle user) throws PackageManager.NameNotFoundException { return mBase.createPackageContextAsUser(packageName, flags, user); } /** @hide */ public Context createApplicationContext(ApplicationInfo application, int flags) throws PackageManager.NameNotFoundException { return mBase.createApplicationContext(application, flags); } /** @hide */ @Override public int getUserId() { return mBase.getUserId(); } @Override public Context createConfigurationContext(Configuration overrideConfiguration) { return mBase.createConfigurationContext(overrideConfiguration); } @Override public Context createDisplayContext(Display display) { return mBase.createDisplayContext(display); } @Override public boolean isRestricted() { return mBase.isRestricted(); } /** @hide */ @Override public DisplayAdjustments getDisplayAdjustments(int displayId) { return mBase.getDisplayAdjustments(displayId); } }
s20121035/rk3288_android5.1_repo
frameworks/base/core/java/android/content/ContextWrapper.java
Java
gpl-3.0
20,584
package com.thomasjensen.checkstyle.addons.checks; /* * Checkstyle-Addons - Additional Checkstyle checks * Copyright (c) 2015-2020, the Checkstyle Addons contributors * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License, version 3, as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this * program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.jcip.annotations.Immutable; /** * Represents a Java binary class name for reference types, in the form of its fragments. This is the only way to tell * the difference between a class called <code>A$B</code> and a class called <code>A</code> that has an inner class * <code>B</code>. */ @Immutable public final class BinaryName { private final String pkg; private final List<String> cls; /** * Constructor. * * @param pPkg package name * @param pOuterCls outer class simple name * @param pInnerCls inner class simple names in descending order of their nesting */ public BinaryName(@Nullable final String pPkg, @Nonnull final String pOuterCls, @Nullable final String... pInnerCls) { pkg = pPkg; List<String> nameList = new ArrayList<>(); if (pOuterCls != null) { nameList.add(pOuterCls); } else { throw new IllegalArgumentException("pOuterCls was null"); } if (pInnerCls != null) { for (final String inner : pInnerCls) { nameList.add(inner); } } cls = Collections.unmodifiableList(nameList); } /** * Constructor. * * @param pPkg package name * @param pClsNames class simple names in descending order of their nesting */ public BinaryName(@Nullable final String pPkg, @Nonnull final Collection<String> pClsNames) { pkg = pPkg; if (pClsNames.size() == 0) { throw new IllegalArgumentException("pClsNames is empty"); } cls = Collections.unmodifiableList(new ArrayList<>(pClsNames)); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (pkg != null) { sb.append(pkg); sb.append('.'); } for (final Iterator<String> iter = cls.iterator(); iter.hasNext();) { sb.append(iter.next()); if (iter.hasNext()) { sb.append('$'); } } return sb.toString(); } @Override public boolean equals(final Object pOther) { if (this == pOther) { return true; } if (pOther == null || getClass() != pOther.getClass()) { return false; } BinaryName other = (BinaryName) pOther; if (pkg != null ? !pkg.equals(other.pkg) : other.pkg != null) { return false; } if (!cls.equals(other.cls)) { return false; } return true; } @Override public int hashCode() { int result = pkg != null ? pkg.hashCode() : 0; result = 31 * result + cls.hashCode(); return result; } public String getPackage() { return pkg; } /** * Getter. * * @return the simple name of the outer class (even if this binary name represents an inner class) */ public String getOuterSimpleName() { return cls.get(0); } /** * Getter. * * @return the simple name of the inner class represented by this binary name. <code>null</code> if this binary name * does not represent an inner class */ public String getInnerSimpleName() { return cls.size() > 1 ? cls.get(cls.size() - 1) : null; } /** * The fully qualified name of the outer class. * * @return that, or <code>null</code> if the simple name of the outer class is unknown */ @CheckForNull public String getOuterFqcn() { return (pkg != null ? (pkg + ".") : "") + getOuterSimpleName(); } }
checkstyle-addons/checkstyle-addons
src/main/java/com/thomasjensen/checkstyle/addons/checks/BinaryName.java
Java
gpl-3.0
4,699
/* * $Id: LeftJoin.java,v 1.2 2006/04/09 12:13:12 laddi Exp $ * Created on 5.10.2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.data.query; import java.util.HashSet; import java.util.Set; import com.idega.data.query.output.Output; import com.idega.data.query.output.Outputable; import com.idega.data.query.output.ToStringer; /** * * Last modified: $Date: 2006/04/09 12:13:12 $ by $Author: laddi $ * * @author <a href="mailto:gummi@idega.com">Gudmundur Agust Saemundsson</a> * @version $Revision: 1.2 $ */ public class LeftJoin implements Outputable { private Column left, right; public LeftJoin(Column left, Column right) { this.left = left; this.right = right; } public Column getLeftColumn() { return this.left; } public Column getRightColumn() { return this.right; } @Override public void write(Output out) { out.print(this.left.getTable()) .print(" left join ") .print(this.right.getTable()) .print(" on ") .print(this.left) .print(" = ") .print(this.right); } public Set<Table> getTables(){ Set<Table> s = new HashSet<Table>(); s.add(this.left.getTable()); s.add(this.right.getTable()); return s; } @Override public String toString() { return ToStringer.toString(this); } }
idega/com.idega.core
src/java/com/idega/data/query/LeftJoin.java
Java
gpl-3.0
1,467
package it.emarolab.owloop.descriptor.utility.classDescriptor; import it.emarolab.amor.owlInterface.OWLReferences; import it.emarolab.owloop.descriptor.construction.descriptorEntitySet.Individuals; import it.emarolab.owloop.descriptor.construction.descriptorExpression.ClassExpression; import it.emarolab.owloop.descriptor.construction.descriptorGround.ClassGround; import it.emarolab.owloop.descriptor.utility.individualDescriptor.LinkIndividualDesc; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLNamedIndividual; import java.util.List; /** * This is an example of a 'simple' Class Descriptor that implements 1 ClassExpression (aka {@link ClassExpression}) interface: * <ul> * <li><b>{@link ClassExpression.Instance}</b>: to describe an Individual of a Class.</li> * </ul> * * See {@link FullClassDesc} for an example of a 'compound' Class Descriptor that implements all ClassExpressions (aka {@link ClassExpression}). * <p> * <div style="text-align:center;"><small> * <b>File</b>: it.emarolab.owloop.core.Axiom <br> * <b>Licence</b>: GNU GENERAL PUBLIC LICENSE. Version 3, 29 June 2007 <br> * <b>Authors</b>: Buoncompagni Luca (luca.buoncompagni@edu.unige.it), Syed Yusha Kareem (kareem.syed.yusha@dibris.unige.it) <br> * <b>affiliation</b>: EMAROLab, DIBRIS, University of Genoa. <br> * <b>date</b>: 01/05/19 <br> * </small></div> */ public class InstanceClassDesc extends ClassGround implements ClassExpression.Instance<LinkIndividualDesc> { private Individuals individuals = new Individuals(); /* Constructors from class: ClassGround */ public InstanceClassDesc(OWLClass instance, OWLReferences onto) { super(instance, onto); } public InstanceClassDesc(String instanceName, OWLReferences onto) { super(instanceName, onto); } public InstanceClassDesc(OWLClass instance, String ontoName) { super(instance, ontoName); } public InstanceClassDesc(OWLClass instance, String ontoName, String filePath, String iriPath) { super(instance, ontoName, filePath, iriPath); } public InstanceClassDesc(OWLClass instance, String ontoName, String filePath, String iriPath, boolean bufferingChanges) { super(instance, ontoName, filePath, iriPath, bufferingChanges); } public InstanceClassDesc(String instanceName, String ontoName) { super(instanceName, ontoName); } public InstanceClassDesc(String instanceName, String ontoName, String filePath, String iriPath) { super(instanceName, ontoName, filePath, iriPath); } public InstanceClassDesc(String instanceName, String ontoName, String filePath, String iriPath, boolean bufferingChanges) { super(instanceName, ontoName, filePath, iriPath, bufferingChanges); } /* Overriding methods in class: ClassGround */ // To read axioms from an ontology @Override public List<MappingIntent> readAxioms() { return Instance.super.readAxioms(); } // To write axioms to an ontology @Override public List<MappingIntent> writeAxioms() { return Instance.super.writeAxioms(); } /* Overriding methods in classes: Class and ClassExpression */ // Is used by the descriptors's build() method. It's possible to change the return type based on need. @Override public LinkIndividualDesc getIndividualDescriptor(OWLNamedIndividual instance, OWLReferences ontology) { return new LinkIndividualDesc( instance, ontology); } // It returns Individuals from the EntitySet (after being read from the ontology) @Override public Individuals getIndividuals() { return individuals; } /* Overriding method in class: Object */ // To show internal state of the Descriptor @Override public String toString() { return getClass().getSimpleName() + "{" + "\n" + "\n" + "\t" + getGround() + ":" + "\n" + "\n" + "\t\t⇐ " + individuals + "\n" + "}" + "\n"; } }
EmaroLab/owloop
src/main/java/it/emarolab/owloop/descriptor/utility/classDescriptor/InstanceClassDesc.java
Java
gpl-3.0
4,115
package com.example.habitup.View; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.habitup.Model.Attributes; import com.example.habitup.Model.Habit; import com.example.habitup.R; import java.util.ArrayList; /** * This is the adapter for creating the habit list, which displays the habit name, and * it's schedule. * * @author Shari Barboza */ public class HabitListAdapter extends ArrayAdapter<Habit> { // The habits array private ArrayList<Habit> habits; public HabitListAdapter(Context context, int resource, ArrayList<Habit> habits) { super(context, resource, habits); this.habits = habits; } @Override public View getView(int position, View view, ViewGroup viewGroup) { View v = view; // Inflate a new view if (v == null) { LayoutInflater inflater = LayoutInflater.from(getContext()); v = inflater.inflate(R.layout.habit_list_item, null); } // Get the habit Habit habit = habits.get(position); String attributeName = habit.getHabitAttribute(); String attributeColour = Attributes.getColour(attributeName); // Set the name of the habit TextView habitNameView = v.findViewById(R.id.habit_name); habitNameView.setText(habit.getHabitName()); habitNameView.setTextColor(Color.parseColor(attributeColour)); // Get habit schedule boolean[] schedule = habit.getHabitSchedule(); View monView = v.findViewById(R.id.mon_box); View tueView = v.findViewById(R.id.tue_box); View wedView = v.findViewById(R.id.wed_box); View thuView = v.findViewById(R.id.thu_box); View friView = v.findViewById(R.id.fri_box); View satView = v.findViewById(R.id.sat_box); View sunView = v.findViewById(R.id.sun_box); View[] textViews = {monView, tueView, wedView, thuView, friView, satView, sunView}; // Display days of the month for the habit's schedule for (int i = 1; i < schedule.length; i++) { if (schedule[i]) { textViews[i-1].setVisibility(View.VISIBLE); } else { textViews[i-1].setVisibility(View.GONE); } } return v; } }
CMPUT301F17T29/HabitUp
app/src/main/java/com/example/habitup/View/HabitListAdapter.java
Java
gpl-3.0
2,677
package org.elsys.InternetProgramming; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; public class ServerHandler { private Socket socket; public ServerHandler(String serverHost, int serverPort) { try { this.socket = new Socket(serverHost, serverPort); } catch (IOException e) { e.printStackTrace(); } } public void sendDateToServer(String date) { try { final OutputStream outputStream = this.socket.getOutputStream(); final PrintWriter out = new PrintWriter(outputStream); out.println(date); out.flush(); } catch (IOException e) { e.printStackTrace(); } } public int getCountFromServer() { try { final InputStream inputStream = this.socket.getInputStream(); final InputStreamReader inputStreamReader = new InputStreamReader(inputStream); final BufferedReader reader = new BufferedReader(inputStreamReader); final String line = reader.readLine(); final int result = Integer.parseInt(line); return result; } catch (IOException e) { e.printStackTrace(); } return 0; } public void closeConnection() { try { this.socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
edudev/internet_programming
Homework2/workspace/DateFormatterClient/src/org/elsys/InternetProgramming/ServerHandler.java
Java
gpl-3.0
1,328
/* * 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.engine.virtualization; import java.io.IOException; /** * @author Lucian Chirita (lucianc@users.sourceforge.net) */ public class FloatSerializer implements ObjectSerializer<Float> { @Override public int typeValue() { return SerializationConstants.OBJECT_TYPE_FLOAT; } @Override public ReferenceType defaultReferenceType() { return ReferenceType.OBJECT; } @Override public boolean defaultStoreReference() { return true; } @Override public void write(Float value, VirtualizationOutput out) throws IOException { out.writeFloat(value); } @Override public Float read(VirtualizationInput in) throws IOException { return in.readFloat(); } }
aleatorio12/ProVentasConnector
jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/engine/virtualization/FloatSerializer.java
Java
gpl-3.0
1,687
package com.ouser.module; import java.util.HashMap; import java.util.Map; import com.ouser.util.StringUtil; import android.os.Bundle; /** * 照片 * @author hanlixin * */ public class Photo { public enum Size { Small(80, 0), /** 小列表,菜单 */ Normal(100, 1), /** profile */ Large(134, 2), /** 大列表 */ XLarge(640, 3); /** 大图 */ private int size = 0; private int key = 0; Size(int size, int key) { this.size = size; this.key = key; } public int getSize() { return size; } int getKey() { return key; } static Size fromKey(int key) { for(Size s : Size.values()) { if(s.getKey() == key) { return s; } } return null; } } private String url = ""; private int resId = 0; private Map<Size, String> paths = new HashMap<Size, String>(); private Map<Size, Integer> tryTimes = new HashMap<Size, Integer>(); public String getUrl() { return url; } public void setUrl(String url) { this.url = url; this.tryTimes.clear(); } public int getResId() { return resId; } public void setResId(int res) { this.resId = res; } public void setPath(String path, Size size) { paths.put(size, path); } public String getPath(Size size) { if(paths.containsKey(size)) { return paths.get(size); } return ""; } public void setTryTime(int value, Size size) { tryTimes.put(size, value); } public int getTryTime(Size size) { if(tryTimes.containsKey(size)) { return tryTimes.get(size); } return 0; } public boolean isEmpty() { return StringUtil.isEmpty(url) && resId == 0; } public boolean isSame(Photo p) { return p.url.equals(this.url) || ( this.resId != 0 && p.resId == this.resId); } public Bundle toBundle() { StringBuilder sbPath = new StringBuilder(); for(Map.Entry<Size, String> entry : paths.entrySet()) { sbPath.append(entry.getKey().getKey()).append(":").append(entry.getValue()).append(";"); } StringBuilder sbTryTime = new StringBuilder(); for(Map.Entry<Size, Integer> entry : tryTimes.entrySet()) { sbPath.append(entry.getKey().getKey()).append(":").append(entry.getValue()).append(";"); } Bundle bundle = new Bundle(); bundle.putString("url", url); bundle.putInt("resid", resId); bundle.putString("path", sbPath.toString()); bundle.putString("trytime", sbTryTime.toString()); return bundle; } public void fromBundle(Bundle bundle) { url = bundle.getString("url"); resId = bundle.getInt("resid"); String strPath = bundle.getString("path"); String strTryTime = bundle.getString("trytime"); this.paths.clear(); for(String str : strPath.split(";")) { if("".equals(str)) { continue; } String[] values = str.split(":"); this.paths.put(Size.fromKey(Integer.parseInt(values[0])), values[1]); } this.tryTimes.clear(); for(String str : strTryTime.split(";")) { if("".equals(str)) { continue; } String[] values = str.split(":"); this.tryTimes.put(Size.fromKey(Integer.parseInt(values[0])), Integer.parseInt(values[1])); } } }
tassadar2002/ouser
src/com/ouser/module/Photo.java
Java
gpl-3.0
3,179
package bdv.server; import bdv.db.UserController; import bdv.model.DataSet; import bdv.util.Render; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.util.log.Log; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STGroup; import org.stringtemplate.v4.STRawGroupDir; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.net.URISyntaxException; import java.security.Principal; import java.util.List; import java.util.stream.Collectors; /** * Author: HongKee Moon (moon@mpi-cbg.de), Scientific Computing Facility * Organization: MPI-CBG Dresden * Date: December 2016 */ public class UserPageHandler extends BaseContextHandler { private static final org.eclipse.jetty.util.log.Logger LOG = Log.getLogger( UserPageHandler.class ); UserPageHandler( final Server server, final ContextHandlerCollection publicDatasetHandlers, final ContextHandlerCollection privateDatasetHandlers, final String thumbnailsDirectoryName ) throws IOException, URISyntaxException { super( server, publicDatasetHandlers, privateDatasetHandlers, thumbnailsDirectoryName ); setContextPath( "/private/user/*" ); } @Override public void doHandle( final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response ) throws IOException, ServletException { // System.out.println(target); Principal principal = request.getUserPrincipal(); // System.out.println( principal.getName() ); if ( null == request.getQueryString() ) { list( baseRequest, response, principal.getName() ); } else { // System.out.println(request.getQueryString()); updateDataSet( baseRequest, request, response, principal.getName() ); } } private void updateDataSet( Request baseRequest, HttpServletRequest request, HttpServletResponse response, String userId ) throws IOException { final String op = request.getParameter( "op" ); if ( null != op ) { if ( op.equals( "addDS" ) ) { final String dataSetName = request.getParameter( "name" ); final String tags = request.getParameter( "tags" ); final String description = request.getParameter( "description" ); final String file = request.getParameter( "file" ); final boolean isPublic = Boolean.parseBoolean( request.getParameter( "public" ) ); // System.out.println( "name: " + dataSetName ); // System.out.println( "tags: " + tags ); // System.out.println( "description: " + description ); // System.out.println( "file: " + file ); // System.out.println( "isPublic: " + isPublic ); final DataSet ds = new DataSet( dataSetName, file, tags, description, isPublic ); // Add it the database UserController.addDataSet( userId, ds ); // Add new CellHandler depending on public property addDataSet( ds, baseRequest, response ); } else if ( op.equals( "removeDS" ) ) { final long dsId = Long.parseLong( request.getParameter( "dataset" ) ); // Remove it from the database UserController.removeDataSet( userId, dsId ); // Remove the CellHandler removeDataSet( dsId, baseRequest, response ); } else if ( op.equals( "updateDS" ) ) { // UpdateDS uses x-editable // Please, refer http://vitalets.github.io/x-editable/docs.html final String field = request.getParameter( "name" ); final long dataSetId = Long.parseLong( request.getParameter( "pk" ) ); final String value = request.getParameter( "value" ); // Update the database final DataSet ds = UserController.getDataSet( userId, dataSetId ); if ( field.equals( "dataSetName" ) ) { ds.setName( value ); } else if ( field.equals( "dataSetDescription" ) ) { ds.setDescription( value ); } // Update DataBase UserController.updateDataSet( userId, ds ); // Update the CellHandler updateHandler( ds, baseRequest, response ); // System.out.println( field + ":" + value ); } else if ( op.equals( "addTag" ) || op.equals( "removeTag" ) ) { processTag( op, baseRequest, request, response ); } else if ( op.equals( "setPublic" ) ) { final long dataSetId = Long.parseLong( request.getParameter( "dataset" ) ); final boolean checked = Boolean.parseBoolean( request.getParameter( "checked" ) ); final DataSet ds = UserController.getDataSet( userId, dataSetId ); ds.setPublic( checked ); UserController.updateDataSet( userId, ds ); ds.setPublic( !checked ); updateHandlerVisibility( ds, checked, baseRequest, response ); } else if ( op.equals( "addSharedUser" ) || op.equals( "removeSharedUser" ) ) { final long dataSetId = Long.parseLong( request.getParameter( "dataset" ) ); final String sharedUserId = request.getParameter( "userId" ); if ( op.equals( "addSharedUser" ) ) { // System.out.println("Add a shared user"); UserController.addReadableSharedUser( userId, dataSetId, sharedUserId ); } else if ( op.equals( "removeSharedUser" ) ) { // System.out.println("Remove the shared user"); UserController.removeReadableSharedUser( userId, dataSetId, sharedUserId ); } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); ow.write( "Success: " ); ow.close(); } } } private void updateHandlerVisibility( DataSet ds, boolean newVisibility, Request baseRequest, HttpServletResponse response ) throws IOException { String dsName = ds.getName(); boolean ret = removeCellHandler( ds.getIndex() ); if ( ret ) { ds.setPublic( newVisibility ); final boolean isPublic = newVisibility; final String context = "/" + ( isPublic ? Constants.PUBLIC_DATASET_CONTEXT_NAME : Constants.PRIVATE_DATASET_CONTEXT_NAME ) + "/id/" + ds.getIndex(); LOG.info( "Add new context: " + ds.getName() + " on " + context ); CellHandler ctx = getCellHandler( ds, isPublic, context ); ctx.setContextPath( context ); try { ctx.start(); } catch ( Exception e ) { LOG.warn( "Failed to start CellHandler", e ); e.printStackTrace(); ret = false; } } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsName + " is removed." ); } else { ow.write( "Error: " + dsName + " cannot be removed." ); } ow.close(); } private void updateHandler( DataSet ds, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = false; String dsName = ""; for ( final Handler handler : server.getChildHandlersByClass( CellHandler.class ) ) { final CellHandler contextHandler = ( CellHandler ) handler; if ( contextHandler.getDataSet().getIndex() == ds.getIndex() ) { final DataSet dataSet = contextHandler.getDataSet(); dataSet.setName( ds.getName() ); dataSet.setDescription( ds.getDescription() ); ret = true; dsName = ds.getName(); break; } } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsName + " is updated." ); } else { ow.write( "Error: " + dsName + " cannot be updated." ); } ow.close(); } private void removeDataSet( long dsId, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = removeCellHandler( dsId ); response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsId + " is removed." ); } else { ow.write( "Error: " + dsId + " cannot be removed." ); } ow.close(); } private void addDataSet( DataSet ds, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = false; if ( !ds.getXmlPath().isEmpty() && !ds.getName().isEmpty() ) { final boolean isPublic = ds.isPublic(); final String context = "/" + ( isPublic ? Constants.PUBLIC_DATASET_CONTEXT_NAME : Constants.PRIVATE_DATASET_CONTEXT_NAME ) + "/id/" + ds.getIndex(); LOG.info( "Add new context: " + ds.getName() + " on " + context ); CellHandler ctx = getCellHandler( ds, isPublic, context ); ctx.setContextPath( context ); try { ctx.start(); } catch ( Exception e ) { LOG.warn( "Failed to start CellHandler", e ); e.printStackTrace(); } ret = true; } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) ow.write( "Success: " + ds.getName() + " is added." ); else ow.write( "Error: " + ds.getName() + " cannot be added." ); ow.close(); } private void list( final Request baseRequest, final HttpServletResponse response, final String userId ) throws IOException { response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); getHtmlDatasetList( ow, userId ); ow.close(); } private void getHtmlDatasetList( final PrintWriter out, final String userId ) throws IOException { final List< DataSet >[] dataSets = UserController.getDataSets( userId ); final List< DataSet > myDataSetList = dataSets[ 0 ]; final List< DataSet > sharedDataSetList = dataSets[ 1 ]; final STGroup g = new STRawGroupDir( "templates", '$', '$' ); final ST userPage = g.getInstanceOf( "userPage" ); final STGroup g2 = new STRawGroupDir( "templates", '~', '~' ); final ST userPageJS = g2.getInstanceOf( "userPageJS" ); final StringBuilder dsString = new StringBuilder(); for ( DataSet ds : myDataSetList ) { StringBuilder sharedUserString = new StringBuilder(); final ST dataSetTr = g.getInstanceOf( "privateDataSetTr" ); for ( String sharedUser : ds.getSharedUsers() ) { final ST userToBeRemoved = g.getInstanceOf( "userToBeRemoved" ); userToBeRemoved.add( "dataSetId", ds.getIndex() ); userToBeRemoved.add( "sharedUserId", sharedUser ); sharedUserString.append( userToBeRemoved.render() ); } if ( ds.getDatasetUrl() == null ) { // Setup the dataset url if ( ds.isPublic() ) { ds.setDatasetUrl( "/" + Constants.PUBLIC_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } else { ds.setDatasetUrl( "/" + Constants.PRIVATE_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } } dataSetTr.add( "thumbnailUrl", ds.getThumbnailUrl() ); dataSetTr.add( "dataSetId", ds.getIndex() ); dataSetTr.add( "dataSetTags", ds.getTags().stream().collect( Collectors.joining( "," ) ) ); dataSetTr.add( "dataSetName", ds.getName() ); dataSetTr.add( "dataSetDescription", ds.getDescription() ); dataSetTr.add( "dataSetLocation", ds.getXmlPath() ); String url = ds.getDatasetUrl(); if ( url.endsWith( "/" ) ) url = url.substring( 0, url.lastIndexOf( "/" ) ); dataSetTr.add( "dataSetUrl", url ); dataSetTr.add( "dataSetIsPublic", ds.isPublic() ); dataSetTr.add( "sharedUsers", sharedUserString.toString() ); dsString.append( dataSetTr.render() ); } if ( sharedDataSetList != null ) { for ( DataSet ds : sharedDataSetList ) { final ST dataSetTr = g.getInstanceOf( "sharedDataSetTr" ); if ( ds.getDatasetUrl() == null ) { // Setup the dataset url if ( ds.isPublic() ) { ds.setDatasetUrl( "/" + Constants.PUBLIC_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } else { ds.setDatasetUrl( "/" + Constants.PRIVATE_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } } dataSetTr.add( "thumbnailUrl", ds.getThumbnailUrl() ); dataSetTr.add( "dataSetId", ds.getIndex() ); dataSetTr.add( "dataSetTags", Render.createTagsLabel( ds ) ); dataSetTr.add( "dataSetName", ds.getName() ); dataSetTr.add( "dataSetDescription", ds.getDescription() ); dataSetTr.add( "dataSetLocation", ds.getXmlPath() ); String url = ds.getDatasetUrl(); if ( url.endsWith( "/" ) ) url = url.substring( 0, url.lastIndexOf( "/" ) ); dataSetTr.add( "dataSetUrl", url ); dataSetTr.add( "dataSetIsPublic", ds.isPublic() ); dataSetTr.add( "sharedUsers", ds.getOwner() ); dsString.append( dataSetTr.render() ); } } userPage.add( "userId", userId ); userPage.add( "dataSetTr", dsString.toString() ); userPage.add( "JS", userPageJS.render() ); out.write( userPage.render() ); out.close(); } }
hkmoon/bigdataviewer-server
src/main/java/bdv/server/UserPageHandler.java
Java
gpl-3.0
13,172
/* * Copyright 2006, 2007 Alessandro Chiari. * * This file is part of BrewPlus. * * BrewPlus is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * BrewPlus 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 BrewPlus; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package jmash; import jmash.interfaces.XmlAble; import org.apache.log4j.Logger; import org.jdom.Element; /** * * @author Alessandro */ public class YeastType implements XmlAble { private static Logger LOGGER = Logger.getLogger(YeastType.class); /** Creates a new instance of YeastType */ public YeastType() { } private String nome; private String codice; private String produttore; private String forma; private String categoria; private String descrizione; private String attenuazioneMed; private String attenuazioneMin; private String attenuazioneMax; private String temperaturaMin; private String temperaturaMax; private String temperaturaMaxFerm; private static String campiXml[] = { "nome", "codice", "produttore", "forma", "categoria", "attenuazioneMed", "attenuazioneMin", "attenuazioneMax", "temperaturaMin", "temperaturaMax", "descrizione"}; public String getNome() { return this.nome; } public void setNome(String nome) { this.nome = nome; } public String getCodice() { return this.codice; } public void setCodice(String codice) { this.codice = codice; } public String getProduttore() { return this.produttore; } public void setProduttore(String produttore) { this.produttore = produttore; } public String getForma() { return this.forma; } public void setForma(String forma) { this.forma = forma; } public String getCategoria() { return this.categoria; } public void setCategoria(String categoria) { this.categoria = categoria; } public String getDescrizione() { return this.descrizione; } public void setDescrizione(String descrizione) { this.descrizione = descrizione; } public String getAttenuazioneMin() { return this.attenuazioneMin; } public void setAttenuazioneMin(String attenuazioneMin) { this.attenuazioneMin = attenuazioneMin; } public String getAttenuazioneMax() { return this.attenuazioneMax; } public void setAttenuazioneMax(String attenuazioneMax) { this.attenuazioneMax = attenuazioneMax; } public String getTemperaturaMin() { return this.temperaturaMin; } public void setTemperaturaMin(String temperaturaMin) { this.temperaturaMin = temperaturaMin; } public String getTemperaturaMax() { return this.temperaturaMax; } public void setTemperaturaMax(String temperaturaMax) { this.temperaturaMax = temperaturaMax; } public String getAttenuazioneMed() { if (attenuazioneMed != null && !"".equals(attenuazioneMed)) { return this.attenuazioneMed; } else if (getAttenuazioneMin() != null && !"".equals(getAttenuazioneMin()) && getAttenuazioneMax() != null && !"".equals(getAttenuazioneMax())) { return (String.valueOf((Integer.valueOf(getAttenuazioneMin())+Integer.valueOf(getAttenuazioneMax()))/2)); } return this.attenuazioneMed; } public void setAttenuazioneMed(String attenuazioneMed) { this.attenuazioneMed = attenuazioneMed; } public String getTemperaturaMaxFerm() { return temperaturaMaxFerm; } public void setTemperaturaMaxFerm(String temperaturaMaxFerm) { this.temperaturaMaxFerm = temperaturaMaxFerm; } public static String[] getCampiXml() { return campiXml; } public static void setCampiXml(String[] aCampiXml) { campiXml = aCampiXml; } @Override public Element toXml() { try { return Utils.toXml(this, campiXml); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } return null; } @Override public String getTag() { return "yeasts"; } @Override public String[] getXmlFields() { return campiXml; } }
rekhyt75/BrewPlus-IFDB
brewplus/brewplus-ifdb/src/main/java/jmash/YeastType.java
Java
gpl-3.0
4,355
package edu.stanford.nlp.mt.lm; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import edu.stanford.nlp.mt.util.IString; import edu.stanford.nlp.mt.util.Sequence; import edu.stanford.nlp.mt.util.TokenUtils; import edu.stanford.nlp.mt.util.Vocabulary; /** * KenLM language model support via JNI. * * @author daniel cer * @author Spence Green * @author Kenneth Heafield * */ public class KenLanguageModel implements LanguageModel<IString> { private static final Logger logger = LogManager.getLogger(KenLanguageModel.class.getName()); private static final int[] EMPTY_INT_ARRAY = new int[0]; private static final KenLMState ZERO_LENGTH_STATE = new KenLMState(0.0f, EMPTY_INT_ARRAY, 0); public static final String KENLM_LIBRARY_NAME = "PhrasalKenLM"; static { try { System.loadLibrary(KENLM_LIBRARY_NAME); logger.info("Loaded KenLM JNI library."); } catch (java.lang.UnsatisfiedLinkError e) { logger.fatal("KenLM has not been compiled!", e); System.exit(-1); } } private final KenLM model; private final String name; private AtomicReference<int[]> istringIdToKenLMId; private final ReentrantLock preventDuplicateWork = new ReentrantLock(); /** * Constructor for multi-threaded queries. * * @param filename */ public KenLanguageModel(String filename) { model = new KenLM(filename); name = String.format("KenLM(%s)", filename); initializeIdTable(); } /** * Create the mapping between IString word ids and KenLM word ids. */ private void initializeIdTable() { // Don't remove this line!! Sanity check to make sure that start and end load before // building the index. logger.info("Special tokens: start: {} end: {}", TokenUtils.START_TOKEN, TokenUtils.END_TOKEN); int[] table = new int[Vocabulary.systemSize()]; for (int i = 0; i < table.length; ++i) { table[i] = model.index(Vocabulary.systemGet(i)); } istringIdToKenLMId = new AtomicReference<int[]>(table); } /** * Maps the IString id to a kenLM id. If the IString * id is out of range, update the vocab mapping. * @param token * @return kenlm id of the string */ private int toKenLMId(IString token) { { int[] map = istringIdToKenLMId.get(); if (token.id < map.length) { return map[token.id]; } } // Rare event: we have to expand the vocabulary. // In principle, this doesn't need to be a lock, but it does // prevent unnecessary work duplication. if (preventDuplicateWork.tryLock()) { // This thread is responsible for updating the mapping. try { // Maybe another thread did the work for us? int[] oldTable = istringIdToKenLMId.get(); if (token.id < oldTable.length) { return oldTable[token.id]; } int[] newTable = new int[Vocabulary.systemSize()]; System.arraycopy(oldTable, 0, newTable, 0, oldTable.length); for (int i = oldTable.length; i < newTable.length; ++i) { newTable[i] = model.index(Vocabulary.systemGet(i)); } istringIdToKenLMId.set(newTable); return newTable[token.id]; } finally { preventDuplicateWork.unlock(); } } // Another thread is working. Lookup directly. return model.index(token.toString()); } @Override public IString getStartToken() { return TokenUtils.START_TOKEN; } @Override public IString getEndToken() { return TokenUtils.END_TOKEN; } @Override public String getName() { return name; } @Override public int order() { return model.order(); } @Override public LMState score(Sequence<IString> sequence, int startIndex, LMState priorState) { if (sequence.size() == 0) { // Source deletion rule return priorState == null ? ZERO_LENGTH_STATE : priorState; } // Extract prior state final int[] state = priorState == null ? EMPTY_INT_ARRAY : ((KenLMState) priorState).getState(); final int[] ngramIds = makeKenLMInput(sequence, state); if (sequence.size() == 1 && priorState == null && sequence.get(0).equals(TokenUtils.START_TOKEN)) { // Special case: Source deletion rule (e.g., from the OOV model) at the start of a string assert ngramIds.length == 1; return new KenLMState(0.0f, ngramIds, ngramIds.length); } // Reverse the start index for KenLM final int kenLMStartIndex = ngramIds.length - state.length - startIndex - 1; assert kenLMStartIndex >= 0; // Execute the query (via JNI) and construct the return state final long got = model.scoreSeqMarshalled(ngramIds, kenLMStartIndex); return new KenLMState(KenLM.scoreFromMarshalled(got), ngramIds, KenLM.rightStateFromMarshalled(got)); } /** * Convert a Sequence and an optional state to an input for KenLM. * * @param sequence * @param priorState * @return */ private int[] makeKenLMInput(Sequence<IString> sequence, int[] priorState) { final int sequenceSize = sequence.size(); int[] ngramIds = new int[sequenceSize + priorState.length]; if (priorState.length > 0) { System.arraycopy(priorState, 0, ngramIds, sequenceSize, priorState.length); } for (int i = 0; i < sequenceSize; i++) { // Notice: ngramids are in reverse order vv. the Sequence ngramIds[sequenceSize-1-i] = toKenLMId(sequence.get(i)); } return ngramIds; } // TODO(spenceg) This never yielded an improvement.... // private static final int DEFAULT_CACHE_SIZE = 10000; // private static final ThreadLocal<KenLMCache> threadLocalCache = // new ThreadLocal<KenLMCache>(); // // private static class KenLMCache { // private final long[] keys; // private final long[] values; // private final int mask; // public KenLMCache(int size) { // this.keys = new long[size]; // this.values = new long[size]; // this.mask = size - 1; // } // // public Long get(int[] kenLMInput, int startIndex) { // long hashValue = MurmurHash2.hash64(kenLMInput, kenLMInput.length, startIndex); // int k = ideal(hashValue); // return keys[k] == hashValue ? values[k] : null; // } // private int ideal(long hashed) { // return ((int)hashed) & mask; // } // public void insert(int[] kenLMInput, int startIndex, long value) { // long hashValue = MurmurHash2.hash64(kenLMInput, kenLMInput.length, startIndex); // int k = ideal(hashValue); // keys[k] = hashValue; // values[k] = value; // } // } }
Andy-Peng/phrasal
src/edu/stanford/nlp/mt/lm/KenLanguageModel.java
Java
gpl-3.0
6,706
package appalachia.rtg.world.biome.realistic.appalachia.adirondack; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.ChunkPrimer; import appalachia.api.AppalachiaBiomes; import rtg.api.config.BiomeConfig; import rtg.api.util.BlockUtil; import rtg.api.util.CliffCalculator; import rtg.api.util.noise.OpenSimplexNoise; import rtg.api.world.IRTGWorld; import rtg.api.world.surface.SurfaceBase; import rtg.api.world.terrain.TerrainBase; public class RealisticBiomeAPLAdirondackBeach extends RealisticBiomeAPLAdirondackBase { public static Biome biome = AppalachiaBiomes.adirondackBeach; public static Biome river = AppalachiaBiomes.adirondackRiver; public RealisticBiomeAPLAdirondackBeach() { super(biome, river); } @Override public void initConfig() { this.getConfig().addProperty(this.getConfig().SURFACE_MIX_BLOCK).set(""); this.getConfig().addProperty(this.getConfig().SURFACE_MIX_BLOCK_META).set(0); } @Override public TerrainBase initTerrain() { return new TerrainAPLAdirondackBeach(); } @Override public SurfaceBase initSurface() { return new SurfaceAPLAdirondackBeach(config, biome.topBlock, biome.fillerBlock, BlockUtil.getStateDirt(2), 12f, 0.27f); } public class SurfaceAPLAdirondackBeach extends SurfaceBase { protected IBlockState mixBlock; protected float width; protected float height; public SurfaceAPLAdirondackBeach(BiomeConfig config, IBlockState top, IBlockState filler, IBlockState mix, float mixWidth, float mixHeight) { super(config, top, filler); mixBlock = this.getConfigBlock(config.SURFACE_MIX_BLOCK.get(), config.SURFACE_MIX_BLOCK_META.get(), mix); width = mixWidth; height = mixHeight; } @Override public void paintTerrain(ChunkPrimer primer, int i, int j, int x, int z, int depth, IRTGWorld rtgWorld, float[] noise, float river, Biome[] base) { Random rand = rtgWorld.rand(); OpenSimplexNoise simplex = rtgWorld.simplex(); float c = CliffCalculator.calc(x, z, noise); boolean cliff = c > 2.3f ? true : false; // 2.3f because higher thresholds result in fewer stone cliffs (more grassy cliffs) for (int k = 255; k > -1; k--) { Block b = primer.getBlockState(x, k, z).getBlock(); if (b == Blocks.AIR) { depth = -1; } else if (b == Blocks.STONE) { depth++; if (cliff) { if (depth > -1 && depth < 2) { if (rand.nextInt(3) == 0) { primer.setBlockState(x, k, z, hcCobble(rtgWorld, i, j, x, z, k)); } else { primer.setBlockState(x, k, z, hcStone(rtgWorld, i, j, x, z, k)); } } else if (depth < 10) { primer.setBlockState(x, k, z, hcStone(rtgWorld, i, j, x, z, k)); } } else { if (depth == 0 && k > 61) { if (simplex.noise2(i / width, j / width) > height) // > 0.27f, i / 12f { primer.setBlockState(x, k, z, mixBlock); } else { primer.setBlockState(x, k, z, topBlock); } } else if (depth < 4) { primer.setBlockState(x, k, z, fillerBlock); } } } } } } @Override public void initDecos() { } public class TerrainAPLAdirondackBeach extends TerrainBase { public TerrainAPLAdirondackBeach() { } @Override public float generateNoise(IRTGWorld rtgWorld, int x, int y, float border, float river) { return terrainBeach(x, y, rtgWorld.simplex(), river, 180f, 35f, 63f); } } }
Team-RTG/Appalachia
src/main/java/appalachia/rtg/world/biome/realistic/appalachia/adirondack/RealisticBiomeAPLAdirondackBeach.java
Java
gpl-3.0
4,464
/* * 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; import hsa.awp.event.model.Event; import hsa.awp.event.model.Occurrence; import hsa.awp.user.model.SingleUser; import hsa.awp.user.model.User; import hsa.awp.usergui.controller.IUserGuiController; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; import org.apache.wicket.spring.injection.annot.SpringBean; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** * Panel showing detailed information about an {@link Event}. * * @author klassm */ public class EventDetailPanel extends Panel { /** * unique serialization id. */ private static final long serialVersionUID = 9180564827437598145L; /** * GuiController which feeds the Gui with Data. */ @SpringBean(name = "usergui.controller") private transient IUserGuiController controller; /** * Constructor. * * @param id wicket:id. * @param event event to show. */ public EventDetailPanel(String id, Event event) { super(id); List<SingleUser> teachers = new LinkedList<SingleUser>(); event = controller.getEventById(event.getId()); for (Long teacherId : event.getTeachers()) { User user = controller.getUserById(teacherId); if (user != null && user instanceof SingleUser) { teachers.add((SingleUser) user); } } Collections.sort(teachers, new Comparator<SingleUser>() { @Override public int compare(SingleUser o1, SingleUser o2) { return o1.getName().compareTo(o2.getName()); } }); StringBuffer teachersList = new StringBuffer(); if (teachers.size() == 0) { teachersList.append("keine"); } else { boolean first = true; for (SingleUser teacher : teachers) { if (first) { first = false; } else { teachersList.append(", "); } teachersList.append(teacher.getName()); } } WebMarkupContainer eventGeneral = new WebMarkupContainer("event.general"); add(eventGeneral); eventGeneral.add(new Label("event.general.caption", "Allgemeines")); eventGeneral.add(new Label("event.general.eventId", new Model<Integer>(event.getEventId()))); eventGeneral.add(new Label("event.general.subjectName", new Model<String>(event.getSubject().getName()))); eventGeneral.add(new Label("event.general.maxParticipants", new Model<Integer>(event.getMaxParticipants()))); Label teacherLabel = new Label("event.general.teachers", new Model<String>(teachersList.toString())); eventGeneral.add(teacherLabel); eventGeneral.add(new Label("event.general.eventDescription", new Model<String>(event.getDetailInformation()))); ExternalLink detailLink = new ExternalLink("event.general.link", event.getSubject().getLink()); eventGeneral.add(detailLink); detailLink.add(new Label("event.general.linkDesc", event.getSubject().getLink())); String description = event.getSubject().getDescription(); if (description == null || ((description = description.trim().replace("\n", "<br>")).equals(""))) { description = "keine"; } Label subjectDescription = new Label("event.general.subjectDescription", new Model<String>(description)); subjectDescription.setEscapeModelStrings(false); eventGeneral.add(subjectDescription); WebMarkupContainer eventTimetable = new WebMarkupContainer("event.timetable"); add(eventTimetable); eventTimetable.add(new Label("event.timetable.caption", "Stundenplan")); List<Occurrence> occurences; if (event.getTimetable() == null) { occurences = new LinkedList<Occurrence>(); } else { occurences = new LinkedList<Occurrence>(event.getTimetable().getOccurrences()); } eventTimetable.add(new ListView<Occurrence>("event.timetable.list", occurences) { /** * unique serialization id. */ private static final long serialVersionUID = -1041971433878928045L; @Override protected void populateItem(ListItem<Occurrence> item) { DateFormat singleFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm"); DateFormat dayFormat = new SimpleDateFormat("EEEE"); DateFormat timeFormat = new SimpleDateFormat("HH:mm"); String s; switch (item.getModelObject().getType()) { case SINGLE: s = "Einzeltermin vom " + singleFormat.format(item.getModelObject().getStartDate().getTime()); s += " bis " + singleFormat.format(item.getModelObject().getEndDate().getTime()); break; case PERIODICAL: s = "Wöchentlich am " + dayFormat.format(item.getModelObject().getStartDate().getTime()); s += " von " + timeFormat.format(item.getModelObject().getStartDate().getTime()) + " bis " + timeFormat.format(item.getModelObject().getEndDate().getTime()); break; default: s = ""; } item.add(new Label("event.timetable.list.occurrence", s)); } }); if (occurences.size() == 0) { eventTimetable.setVisible(false); } } }
physalix-enrollment/physalix
UserGui/src/main/java/hsa/awp/usergui/EventDetailPanel.java
Java
gpl-3.0
6,335
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.dialer.calllog; import android.content.Context; import android.content.res.Resources; import android.provider.CallLog.Calls; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.util.Log; import com.android.contacts.common.CallUtil; import com.android.dialer.PhoneCallDetails; import com.android.dialer.PhoneCallDetailsHelper; import com.android.dialer.R; /** * Helper class to fill in the views of a call log entry. */ /* package */class CallLogListItemHelper { private static final String TAG = "CallLogListItemHelper"; /** Helper for populating the details of a phone call. */ private final PhoneCallDetailsHelper mPhoneCallDetailsHelper; /** Helper for handling phone numbers. */ private final PhoneNumberDisplayHelper mPhoneNumberHelper; /** Resources to look up strings. */ private final Resources mResources; /** * Creates a new helper instance. * * @param phoneCallDetailsHelper used to set the details of a phone call * @param phoneNumberHelper used to process phone number */ public CallLogListItemHelper(PhoneCallDetailsHelper phoneCallDetailsHelper, PhoneNumberDisplayHelper phoneNumberHelper, Resources resources) { mPhoneCallDetailsHelper = phoneCallDetailsHelper; mPhoneNumberHelper = phoneNumberHelper; mResources = resources; } /** * Sets the name, label, and number for a contact. * * @param context The application context. * @param views the views to populate * @param details the details of a phone call needed to fill in the data */ public void setPhoneCallDetails( Context context, CallLogListItemViews views, PhoneCallDetails details) { mPhoneCallDetailsHelper.setPhoneCallDetails(views.phoneCallDetailsViews, details); // Set the accessibility text for the contact badge views.quickContactView.setContentDescription(getContactBadgeDescription(details)); // Set the primary action accessibility description views.primaryActionView.setContentDescription(getCallDescription(context, details)); // Cache name or number of caller. Used when setting the content descriptions of buttons // when the actions ViewStub is inflated. views.nameOrNumber = this.getNameOrNumber(details); } /** * Sets the accessibility descriptions for the action buttons in the action button ViewStub. * * @param views The views associated with the current call log entry. */ public void setActionContentDescriptions(CallLogListItemViews views) { if (views.nameOrNumber == null) { Log.e(TAG, "setActionContentDescriptions; name or number is null."); } // Calling expandTemplate with a null parameter will cause a NullPointerException. // Although we don't expect a null name or number, it is best to protect against it. CharSequence nameOrNumber = views.nameOrNumber == null ? "" : views.nameOrNumber; views.callBackButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_call_back_action), nameOrNumber)); views.videoCallButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_video_call_action), nameOrNumber)); views.voicemailButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_voicemail_action), nameOrNumber)); views.detailsButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_details_action), nameOrNumber)); } /** * Returns the accessibility description for the contact badge for a call log entry. * * @param details Details of call. * @return Accessibility description. */ private CharSequence getContactBadgeDescription(PhoneCallDetails details) { return mResources.getString(R.string.description_contact_details, getNameOrNumber(details)); } /** * Returns the accessibility description of the "return call/call" action for a call log * entry. * Accessibility text is a combination of: * {Voicemail Prefix}. {Number of Calls}. {Caller information} {Phone Account}. * If most recent call is a voicemail, {Voicemail Prefix} is "New Voicemail.", otherwise "". * * If more than one call for the caller, {Number of Calls} is: * "{number of calls} calls.", otherwise "". * * The {Caller Information} references the most recent call associated with the caller. * For incoming calls: * If missed call: Missed call from {Name/Number} {Call Type} {Call Time}. * If answered call: Answered call from {Name/Number} {Call Type} {Call Time}. * * For outgoing calls: * If outgoing: Call to {Name/Number] {Call Type} {Call Time}. * * Where: * {Name/Number} is the name or number of the caller (as shown in call log). * {Call type} is the contact phone number type (eg mobile) or location. * {Call Time} is the time since the last call for the contact occurred. * * The {Phone Account} refers to the account/SIM through which the call was placed or received * in multi-SIM devices. * * Examples: * 3 calls. New Voicemail. Missed call from Joe Smith mobile 2 hours ago on SIM 1. * * 2 calls. Answered call from John Doe mobile 1 hour ago. * * @param context The application context. * @param details Details of call. * @return Return call action description. */ public CharSequence getCallDescription(Context context, PhoneCallDetails details) { int lastCallType = getLastCallType(details.callTypes); boolean isVoiceMail = lastCallType == Calls.VOICEMAIL_TYPE; // Get the name or number of the caller. final CharSequence nameOrNumber = getNameOrNumber(details); // Get the call type or location of the caller; null if not applicable final CharSequence typeOrLocation = mPhoneCallDetailsHelper.getCallTypeOrLocation(details); // Get the time/date of the call final CharSequence timeOfCall = mPhoneCallDetailsHelper.getCallDate(details); SpannableStringBuilder callDescription = new SpannableStringBuilder(); // Prepend the voicemail indication. if (isVoiceMail) { callDescription.append(mResources.getString(R.string.description_new_voicemail)); } // Add number of calls if more than one. if (details.callTypes.length > 1) { callDescription.append(mResources.getString(R.string.description_num_calls, details.callTypes.length)); } // If call had video capabilities, add the "Video Call" string. if ((details.features & Calls.FEATURES_VIDEO) == Calls.FEATURES_VIDEO && CallUtil.isVideoEnabled(context)) { callDescription.append(mResources.getString(R.string.description_video_call)); } int stringID = getCallDescriptionStringID(details); String accountLabel = PhoneAccountUtils.getAccountLabel(context, details.accountHandle); // Use chosen string resource to build up the message. CharSequence onAccountLabel = accountLabel == null ? "" : TextUtils.expandTemplate( mResources.getString(R.string.description_phone_account), accountLabel); callDescription.append( TextUtils.expandTemplate( mResources.getString(stringID), nameOrNumber, // If no type or location can be determined, sub in empty string. typeOrLocation == null ? "" : typeOrLocation, timeOfCall, onAccountLabel)); return callDescription; } /** * Determine the appropriate string ID to describe a call for accessibility purposes. * * @param details Call details. * @return String resource ID to use. */ public int getCallDescriptionStringID(PhoneCallDetails details) { int lastCallType = getLastCallType(details.callTypes); int stringID; if (lastCallType == Calls.VOICEMAIL_TYPE || lastCallType == Calls.MISSED_TYPE) { //Message: Missed call from <NameOrNumber>, <TypeOrLocation>, <TimeOfCall>, //<PhoneAccount>. stringID = R.string.description_incoming_missed_call; } else if (lastCallType == Calls.INCOMING_TYPE) { //Message: Answered call from <NameOrNumber>, <TypeOrLocation>, <TimeOfCall>, //<PhoneAccount>. stringID = R.string.description_incoming_answered_call; } else { //Message: Call to <NameOrNumber>, <TypeOrLocation>, <TimeOfCall>, <PhoneAccount>. stringID = R.string.description_outgoing_call; } return stringID; } /** * Determine the call type for the most recent call. * @param callTypes Call types to check. * @return Call type. */ private int getLastCallType(int[] callTypes) { if (callTypes.length > 0) { return callTypes[0]; } else { return Calls.MISSED_TYPE; } } /** * Return the name or number of the caller specified by the details. * @param details Call details * @return the name (if known) of the caller, otherwise the formatted number. */ private CharSequence getNameOrNumber(PhoneCallDetails details) { final CharSequence recipient; if (!TextUtils.isEmpty(details.name)) { recipient = details.name; } else { recipient = mPhoneNumberHelper.getDisplayNumber(details.accountHandle, details.number, details.numberPresentation, details.formattedNumber); } return recipient; } }
s20121035/rk3288_android5.1_repo
packages/apps/Dialer/src/com/android/dialer/calllog/CallLogListItemHelper.java
Java
gpl-3.0
10,890
/* * IIIFProducer * Copyright (C) 2017 Leipzig University Library <info@ub.uni-leipzig.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 de.ubleipzig.iiifproducer.template; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import de.ubleipzig.iiif.vocabulary.IIIFEnum; /** * TemplateService. * * @author christopher-johnson */ @JsonPropertyOrder({"@context", "@id", "profile"}) public class TemplateService { @JsonProperty("@context") private String context = IIIFEnum.IMAGE_CONTEXT.IRIString(); @JsonProperty("@id") private String id; @JsonProperty private String profile = IIIFEnum.SERVICE_PROFILE.IRIString(); /** * @param id String */ public TemplateService(final String id) { this.id = id; } }
ubleipzig/iiif-producer
templates/src/main/java/de/ubleipzig/iiifproducer/template/TemplateService.java
Java
gpl-3.0
1,444
package com.pix.mind.controllers; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.pix.mind.PixMindGame; import com.pix.mind.box2d.bodies.PixGuy; public class KeyboardController extends PixGuyController { boolean movingLeft = false; boolean movingRight = false; public KeyboardController(PixGuy pixGuy, Stage stage) { super(pixGuy); stage.addListener(new InputListener(){ @Override public boolean keyDown(InputEvent event, int keycode) { // TODO Auto-generated method stub if (keycode == Keys.LEFT) { movingLeft = true; movingRight = false; } if (keycode == Keys.RIGHT) { movingRight = true; movingLeft = false; } return true; } @Override public boolean keyUp(InputEvent event, int keycode) { // TODO Auto-generated method stub if (keycode == Keys.LEFT) { movingRight = true; movingLeft = false; } if (keycode == Keys.RIGHT) { movingLeft = true; movingRight = false; } if (!Gdx.input.isKeyPressed(Keys.RIGHT)&& !Gdx.input.isKeyPressed(Keys.LEFT)) { movingRight = false; movingLeft = false; } return true; } }); } public void movements() { if (movingLeft) { pixGuy.moveLeft(Gdx.graphics.getDeltaTime()); } if (movingRight) { pixGuy.moveRight(Gdx.graphics.getDeltaTime()); } if(!movingLeft&&!movingRight){ // if it is not touched, set horizontal velocity to 0 to // eliminate inercy. pixGuy.body.setLinearVelocity(0, pixGuy.body.getLinearVelocity().y); } } }
tuxskar/pixmind
pixmind/src/com/pix/mind/controllers/KeyboardController.java
Java
gpl-3.0
1,788
package com.wongsir.newsgathering.model.commons; import com.google.common.base.MoreObjects; import com.google.gson.annotations.SerializedName; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; /** * @Description: TODO * @author Wongsir * @date 2017年1月4日 * */ public class Webpage { /** * 附件id列表 */ public List<String> attachmentList; /** * 图片ID列表 */ public List<String> imageList; /** * 正文 */ private String content; /** * 标题 */ private String title; /** * 链接 */ private String url; /** * 域名 */ private String domain; /** * 爬虫id,可以认为是taskid */ private String spiderUUID; /** * 模板id */ @SerializedName("spiderInfoId") private String spiderInfoId; /** * 分类 */ private String category; /** * 网页快照 */ private String rawHTML; /** * 关键词 */ private List<String> keywords; /** * 摘要 */ private List<String> summary; /** * 抓取时间 */ @SerializedName("gatherTime") private Date gathertime; /** * 网页id,es自动分配的 */ private String id; /** * 文章的发布时间 */ private Date publishTime; /** * 命名实体 */ private Map<String, Set<String>> namedEntity; /** * 动态字段 */ private Map<String, Object> dynamicFields; /** * 静态字段 */ private Map<String, Object> staticFields; /** * 本网页处理时长 */ private long processTime; public Map<String, Object> getStaticFields() { return staticFields; } public Webpage setStaticFields(Map<String, Object> staticFields) { this.staticFields = staticFields; return this; } public Map<String, Set<String>> getNamedEntity() { return namedEntity; } public Webpage setNamedEntity(Map<String, Set<String>> namedEntity) { this.namedEntity = namedEntity; return this; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public String getSpiderInfoId() { return spiderInfoId; } public void setSpiderInfoId(String spiderInfoId) { this.spiderInfoId = spiderInfoId; } public Date getGathertime() { return gathertime; } public void setGathertime(Date gathertime) { this.gathertime = gathertime; } public String getSpiderUUID() { return spiderUUID; } public void setSpiderUUID(String spiderUUID) { this.spiderUUID = spiderUUID; } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<String> getKeywords() { return keywords; } public Webpage setKeywords(List<String> keywords) { this.keywords = keywords; return this; } public List<String> getSummary() { return summary; } public Webpage setSummary(List<String> summary) { this.summary = summary; return this; } public Date getPublishTime() { return publishTime; } public Webpage setPublishTime(Date publishTime) { this.publishTime = publishTime; return this; } public String getCategory() { return category; } public Webpage setCategory(String category) { this.category = category; return this; } public String getRawHTML() { return rawHTML; } public Webpage setRawHTML(String rawHTML) { this.rawHTML = rawHTML; return this; } public Map<String, Object> getDynamicFields() { return dynamicFields; } public Webpage setDynamicFields(Map<String, Object> dynamicFields) { this.dynamicFields = dynamicFields; return this; } public List<String> getAttachmentList() { return attachmentList; } public Webpage setAttachmentList(List<String> attachmentList) { this.attachmentList = attachmentList; return this; } public List<String> getImageList() { return imageList; } public Webpage setImageList(List<String> imageList) { this.imageList = imageList; return this; } public long getProcessTime() { return processTime; } public Webpage setProcessTime(long processTime) { this.processTime = processTime; return this; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("content", content) .add("title", title) .add("url", url) .add("domain", domain) .add("spiderUUID", spiderUUID) .add("spiderInfoId", spiderInfoId) .add("category", category) .add("rawHTML", rawHTML) .add("keywords", keywords) .add("summary", summary) .add("gathertime", gathertime) .add("id", id) .add("publishTime", publishTime) .add("namedEntity", namedEntity) .add("dynamicFields", dynamicFields) .add("staticFields", staticFields) .add("attachmentList", attachmentList) .add("imageList", imageList) .toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Webpage webpage = (Webpage) o; return new EqualsBuilder() .append(getContent(), webpage.getContent()) .append(getTitle(), webpage.getTitle()) .append(getUrl(), webpage.getUrl()) .append(getDomain(), webpage.getDomain()) .append(getSpiderUUID(), webpage.getSpiderUUID()) .append(getSpiderInfoId(), webpage.getSpiderInfoId()) .append(getCategory(), webpage.getCategory()) .append(getRawHTML(), webpage.getRawHTML()) .append(getKeywords(), webpage.getKeywords()) .append(getSummary(), webpage.getSummary()) .append(getGathertime(), webpage.getGathertime()) .append(getId(), webpage.getId()) .append(getPublishTime(), webpage.getPublishTime()) .append(getNamedEntity(), webpage.getNamedEntity()) .append(getDynamicFields(), webpage.getDynamicFields()) .append(getStaticFields(), webpage.getStaticFields()) .append(getAttachmentList(), webpage.getAttachmentList()) .append(getImageList(), webpage.getImageList()) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(getContent()) .append(getTitle()) .append(getUrl()) .append(getDomain()) .append(getSpiderUUID()) .append(getSpiderInfoId()) .append(getCategory()) .append(getRawHTML()) .append(getKeywords()) .append(getSummary()) .append(getGathertime()) .append(getId()) .append(getPublishTime()) .append(getNamedEntity()) .append(getDynamicFields()) .append(getStaticFields()) .append(getAttachmentList()) .append(getImageList()) .toHashCode(); } }
WongSir/JustGo
src/main/java/com/wongsir/newsgathering/model/commons/Webpage.java
Java
gpl-3.0
8,742
package fr.hnit.babyname; /* The babyname app is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. The babyname app 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 the TXM platform. If not, see http://www.gnu.org/licenses */ import android.app.AlertDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { public static final String UPDATE_EXTRA = "update"; ListView namesListView; BabyNameAdapter adapter; public static BabyNameDatabase database = new BabyNameDatabase(); public static ArrayList<BabyNameProject> projects = new ArrayList<>(); Intent editIntent; Intent findIntent; Intent settingsIntent; Intent aboutIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (database.size() == 0) database.initialize(); namesListView = (ListView) findViewById(R.id.listView); registerForContextMenu(namesListView); namesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { BabyNameProject project = projects.get(i); if (project != null) { doFindName(project); } } }); adapter = new BabyNameAdapter(this, projects); namesListView.setAdapter(adapter); if (projects.size() == 0) { initializeProjects(); } editIntent = new Intent(MainActivity.this, EditActivity.class); findIntent = new Intent(MainActivity.this, FindActivity.class); settingsIntent = new Intent(MainActivity.this, SettingsActivity.class); aboutIntent = new Intent(MainActivity.this, AboutActivity.class); } @Override public void onResume() { super.onResume(); // Always call the superclass method first adapter.notifyDataSetChanged(); for (BabyNameProject project : projects) { if (project.needSaving) { //Toast.makeText(this, "Saving changes of "+project+"... "+project, Toast.LENGTH_SHORT).show(); if (!BabyNameProject.storeProject(project, this)) { Toast.makeText(this, "Error: could not save changes to babyname project: "+project, Toast.LENGTH_LONG).show(); } } } } private void initializeProjects() { //AppLogger.info("Initializing projects..."); for (String filename : this.fileList()) { if (filename.endsWith(".baby")) { //AppLogger.info("Restoring... "+filename); try { BabyNameProject project = BabyNameProject.readProject(filename, this); if (project != null) projects.add(project); else Toast.makeText(MainActivity.this, "Error: could not read baby name project from "+filename, Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } } } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_list, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); if (adapter.getCount() <= info.position) return false; BabyNameProject project = adapter.getItem(info.position); if (project == null) return false; switch (item.getItemId()) { case R.id.action_reset_baby: doResetBaby(project); return true; case R.id.action_top_baby: doShowTop10(project); return true; case R.id.action_delete_baby: doDeleteBaby(project); return true; default: return super.onContextItemSelected(item); } } public void doResetBaby(final BabyNameProject project) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.reset_question_title); builder.setMessage(R.string.reset_question_content); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { project.reset(); adapter.notifyDataSetChanged(); if (!BabyNameProject.storeProject(project, MainActivity.this)) { Toast.makeText(MainActivity.this, "Error: could not save reset changes to babyname project: "+project, Toast.LENGTH_LONG).show(); } dialog.dismiss(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // I do not need any action here you might dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } public void doDeleteBaby(final BabyNameProject project) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.delete_question_title); builder.setMessage(R.string.delete_question_content); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { projects.remove(project); MainActivity.this.deleteFile(project.getID()+".baby"); adapter.notifyDataSetChanged(); dialog.dismiss(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } public String projectToString(BabyNameProject p) { String l1 = ""; if (p.genders.contains(NameData.F) && p.genders.contains(NameData.M)) { l1 += getString(R.string.boy_or_girl_name); } else if (p.genders.contains(NameData.M)) { l1 += getString(R.string.boy_name); } else { l1 +=getString( R.string.girl_name); } if (p.origins.size() == 1) { l1 += "\n\t "+String.format(getString(R.string.origin_is), p.origins.toArray()[0]); } else if (p.origins.size() > 1) { l1 += "\n\t "+String.format(getString(R.string.origin_are), p.origins); } else { l1 += "\n\t "+getString(R.string.no_origin); } if (p.pattern != null) { if (".*".equals(p.pattern.toString())) { l1 += "\n\t "+getString(R.string.no_pattern); } else { l1 += "\n\t "+String.format(getString(R.string.matches_with), p.pattern); } } if (p.nexts.size() == 1) { l1 += "\n\t"+getString(R.string.one_remaining_name); } else if (p.nexts.size() == 0) { int n = p.scores.size(); if (n > 11) n = n - 10; l1 += "\n\t"+String.format(getString(R.string.no_remaining_loop), p.loop, n); } else { l1 += "\n\t"+String.format(getString(R.string.remaining_names), p.nexts.size()); } if (p.scores.size() > 0 && p.getBest() != null) { l1 += "\n\n\t"+String.format(getString(R.string.bact_match_is), p.getBest()); } return l1; } public void doShowTop10(final BabyNameProject project) { List<Integer> names = project.getTop10(); final StringBuffer buffer = new StringBuffer(); int n = 0; for (Integer name : names) { buffer.append("\n"+MainActivity.database.get(name)+": "+project.scores.get(name)); } if (names.size() == 0) buffer.append(getString(R.string.no_name_rated)); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.top_title); builder.setMessage(buffer.toString()); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); if (names.size() > 0) builder.setNegativeButton(R.string.copy, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("baby top10", buffer.toString()); clipboard.setPrimaryClip(clip); Toast.makeText(MainActivity.this, R.string.text_copied, Toast.LENGTH_LONG).show(); } }); AlertDialog alert = builder.create(); alert.show(); //Toast.makeText(this, buffer.toString(), Toast.LENGTH_LONG).show(); } public void doFindName(BabyNameProject project) { //AppLogger.info("Open FindActivity with "+project+" index="+projects.indexOf(project)); findIntent.putExtra(FindActivity.PROJECT_EXTRA, projects.indexOf(project)); this.startActivityForResult(findIntent, 0); } private void openEditActivity(BabyNameProject project) { //AppLogger.info("Open EditActivity with "+project+" index="+projects.indexOf(project)); editIntent.putExtra(EditActivity.PROJECT_EXTRA, projects.indexOf(project)); this.startActivityForResult(editIntent, 0); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: this.startActivityForResult(settingsIntent, 0); return true; case R.id.action_about: this.startActivityForResult(aboutIntent, 0); return true; case R.id.action_new_baby: doNewBaby(); return true; default: return super.onOptionsItemSelected(item); } } public void doNewBaby() { Toast.makeText(this, R.string.new_baby, Toast.LENGTH_LONG).show(); BabyNameProject project = new BabyNameProject(); projects.add(project); openEditActivity(project); } }
mdecorde/BABYNAME
app/src/main/java/fr/hnit/babyname/MainActivity.java
Java
gpl-3.0
12,172
package com.weatherapp.model.entities; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Location implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String name; public Location(String name) { this.name = name; } public Location() {} public String getName() { return name; } public void setName(String name) { this.name = name; } }
VoidDragonOfMars/pixelware
instantweatherapplication/src/main/java/com/weatherapp/model/entities/Location.java
Java
gpl-3.0
552
package units.interfaces; public abstract interface Value<T> extends MyComparable<T> { // OPERATIONS default boolean invariant() { return true; } default void checkInvariant() { if(!invariant()) { System.exit(-1); } } public abstract T newInstance(double value); public abstract T abs(); public abstract T min(T value); public abstract T max(T value); public abstract T add(T value); public abstract T sub(T value); public abstract T mul(double value); public abstract T div(double value); public abstract double div(T value); }
MesutKoc/uni-haw
2. Semester/PR2/Aufgabe_2a_Igor/src/units/interfaces/Value.java
Java
gpl-3.0
686
/* * This file is part of JGCGen. * * JGCGen 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. * * JGCGen 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 JGCGen. If not, see <http://www.gnu.org/licenses/>. */ package org.luolamies.jgcgen.text; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.luolamies.jgcgen.RenderException; public class Fonts { private final File workdir; public Fonts(File workdir) { this.workdir = workdir; } public Font get(String name) { String type; if(name.endsWith(".jhf")) type = "Hershey"; else throw new RenderException("Can't figure out font type from filename! Use $fonts.get(\"file\", \"type\")"); return get(name, type); } @SuppressWarnings("unchecked") public Font get(String name, String type) { Class<? extends Font> fclass; try { fclass = (Class<? extends Font>) Class.forName(getClass().getPackage().getName() + "." + type + "Font"); } catch (ClassNotFoundException e1) { throw new RenderException("Font type \"" + type + "\" not supported!"); } InputStream in; File file = new File(workdir, name); if(file.isFile()) { try { in = new FileInputStream(file); } catch (FileNotFoundException e) { in = null; } } else in = getClass().getResourceAsStream("/fonts/" + name); if(in==null) throw new RenderException("Can't find font: " + name); try { return fclass.getConstructor(InputStream.class).newInstance(in); } catch(Exception e) { throw new RenderException("Error while trying to construct handler for font \"" + type + "\": " + e.getMessage(), e); } finally { try { in.close(); } catch (IOException e) { } } } }
callaa/JGCGen
src/org/luolamies/jgcgen/text/Fonts.java
Java
gpl-3.0
2,230
package bartburg.nl.backbaseweather.provision.remote.controller; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.annotation.Annotation; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import bartburg.nl.backbaseweather.AppConstants; import bartburg.nl.backbaseweather.provision.remote.annotation.ApiController; import bartburg.nl.backbaseweather.provision.remote.util.QueryStringUtil; import static bartburg.nl.backbaseweather.AppConstants.OPEN_WEATHER_MAP_BASE_URL; import static bartburg.nl.backbaseweather.AppConstants.OPEN_WEATHER_PROTOCOL; /** * Created by Bart on 6/3/2017. */ public abstract class BaseApiController { /** * Do the actual work of requesting data from the server. Note, should not run on main thread. * * @param parameters Parameters that will be added to the query string. * @param onErrorListener Listener that will get called when status code is not 200 * @return The result string or *null* when failed. */ @Nullable public String get(HashMap<String, String> parameters, @Nullable OnErrorListener onErrorListener) { return get(parameters, onErrorListener, null); } /** * Do the actual work of requesting data from the server. Note, should not run on main thread. * * @param parameters Parameters that will be added to the query string. * @param onErrorListener Listener that will get called when status code is not 200 * @param customRelativePath Use this if you want to provide a custom relative path (not the one from the annotation). * @return The result string or *null* when failed. */ @Nullable public String get(HashMap<String, String> parameters, @Nullable OnErrorListener onErrorListener, @Nullable String customRelativePath) { try { parameters.put("appid", AppConstants.OPEN_WEATHER_MAP_KEY); URL url = new URL(OPEN_WEATHER_PROTOCOL + OPEN_WEATHER_MAP_BASE_URL + getRelativePath(customRelativePath) + QueryStringUtil.mapToQueryString(parameters)); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); String responseMessage = urlConnection.getResponseMessage(); if (responseCode != 200 && onErrorListener != null) { onErrorListener.onError(responseCode, responseMessage); } else { return readInputStream(urlConnection); } } catch (IOException e) { e.printStackTrace(); } return null; } @NonNull private String readInputStream(HttpURLConnection urlConnection) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); return sb.toString(); } public interface OnErrorListener { void onError(int responseCode, String responseMessage); } private String getRelativePath(String customRelativePath) { if (customRelativePath != null) { return customRelativePath; } Class<? extends BaseApiController> aClass = getClass(); if (aClass.isAnnotationPresent(ApiController.class)) { Annotation annotation = aClass.getAnnotation(ApiController.class); ApiController apiController = (ApiController) annotation; return apiController.relativePath(); } return ""; } }
bartburg/backbaseweatherapp
app/src/main/java/bartburg/nl/backbaseweather/provision/remote/controller/BaseApiController.java
Java
gpl-3.0
3,934
/***************************************************************** * This file is part of CCAFS Planning and Reporting Platform. * CCAFS P&R 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. * CCAFS P&R 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 CCAFS P&R. If not, see <http://www.gnu.org/licenses/>. * *************************************************************** */ package org.cgiar.ccafs.ap.data.dao.mysql; import org.cgiar.ccafs.ap.data.dao.ProjectOtherContributionDAO; import org.cgiar.ccafs.utils.db.DAOManager; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import com.google.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Javier Andrés Gallego B. */ public class MySQLProjectOtherContributionDAO implements ProjectOtherContributionDAO { // Logger private static Logger LOG = LoggerFactory.getLogger(MySQLProjectOtherContributionDAO.class); private DAOManager databaseManager; @Inject public MySQLProjectOtherContributionDAO(DAOManager databaseManager) { this.databaseManager = databaseManager; } @Override public Map<String, String> getIPOtherContributionById(int ipOtherContributionId) { Map<String, String> ipOtherContributionData = new HashMap<String, String>(); LOG.debug(">> getIPOtherContributionById( ipOtherContributionId = {} )", ipOtherContributionId); StringBuilder query = new StringBuilder(); query.append("SELECT ipo.* "); query.append("FROM project_other_contributions as ipo "); query.append("WHERE ipo.id= "); query.append(ipOtherContributionId); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); if (rs.next()) { ipOtherContributionData.put("id", rs.getString("id")); ipOtherContributionData.put("project_id", rs.getString("project_id")); ipOtherContributionData.put("contribution", rs.getString("contribution")); ipOtherContributionData.put("additional_contribution", rs.getString("additional_contribution")); ipOtherContributionData.put("crp_contributions_nature", rs.getString("crp_contributions_nature")); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the IP Other Contribution {}.", ipOtherContributionId, e); } LOG.debug("-- getIPOtherContributionById() > Calling method executeQuery to get the results"); return ipOtherContributionData; } @Override public Map<String, String> getIPOtherContributionByProjectId(int projectID) { LOG.debug(">> getIPOtherContributionByProjectId (projectID = {} )", projectID); Map<String, String> ipOtherContributionData = new HashMap<String, String>(); StringBuilder query = new StringBuilder(); query.append("SELECT ipo.* "); query.append("FROM project_other_contributions as ipo "); query.append("INNER JOIN projects p ON ipo.project_id = p.id "); query.append("WHERE ipo.project_id= "); query.append(projectID); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); if (rs.next()) { ipOtherContributionData.put("id", rs.getString("id")); ipOtherContributionData.put("project_id", rs.getString("project_id")); ipOtherContributionData.put("contribution", rs.getString("contribution")); ipOtherContributionData.put("additional_contribution", rs.getString("additional_contribution")); ipOtherContributionData.put("crp_contributions_nature", rs.getString("crp_contributions_nature")); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the IP Other Contribution by the projectID {}.", projectID, e); } LOG.debug("-- getIPOtherContributionByProjectId() : {}", ipOtherContributionData); return ipOtherContributionData; } @Override public int saveIPOtherContribution(int projectID, Map<String, Object> ipOtherContributionData) { LOG.debug(">> saveIPOtherContribution(ipOtherContributionDataData={})", ipOtherContributionData); StringBuilder query = new StringBuilder(); int result = -1; Object[] values; if (ipOtherContributionData.get("id") == null) { // Insert new IP Other Contribution record query.append("INSERT INTO project_other_contributions (project_id, contribution, additional_contribution, "); query.append("crp_contributions_nature, created_by, modified_by, modification_justification) "); query.append("VALUES (?,?,?,?,?,?,?) "); values = new Object[7]; values[0] = projectID; values[1] = ipOtherContributionData.get("contribution"); values[2] = ipOtherContributionData.get("additional_contribution"); values[3] = ipOtherContributionData.get("crp_contributions_nature"); values[4] = ipOtherContributionData.get("user_id"); values[5] = ipOtherContributionData.get("user_id"); values[6] = ipOtherContributionData.get("justification"); result = databaseManager.saveData(query.toString(), values); if (result <= 0) { LOG.error("A problem happened trying to add a new IP Other Contribution with project id={}", projectID); return -1; } } else { // update IP Other Contribution record query.append("UPDATE project_other_contributions SET project_id = ?, contribution = ?, "); query.append("additional_contribution = ?, crp_contributions_nature = ?, modified_by = ?, "); query.append("modification_justification = ? WHERE id = ? "); values = new Object[7]; values[0] = projectID; values[1] = ipOtherContributionData.get("contribution"); values[2] = ipOtherContributionData.get("additional_contribution"); values[3] = ipOtherContributionData.get("crp_contributions_nature"); values[4] = ipOtherContributionData.get("user_id"); values[5] = ipOtherContributionData.get("justification"); values[6] = ipOtherContributionData.get("id"); result = databaseManager.saveData(query.toString(), values); if (result == -1) { LOG.error("A problem happened trying to update the IP Other Contribution identified with the id = {}", ipOtherContributionData.get("id")); return -1; } } LOG.debug("<< saveIPOtherContribution():{}", result); return result; } }
CCAFS/ccafs-ap
impactPathways/src/main/java/org/cgiar/ccafs/ap/data/dao/mysql/MySQLProjectOtherContributionDAO.java
Java
gpl-3.0
6,952
package com.ocams.andre; import javax.swing.table.DefaultTableModel; public class MasterJurnal extends javax.swing.JFrame { public MasterJurnal() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTable2 = new javax.swing.JTable(); jTextField4 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Kode:"); jLabel2.setText("Perkiraan:"); jLabel3.setText("Nomor Referensi:"); jLabel4.setText("Posisi:"); jLabel5.setText("Harga:"); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); buttonGroup1.add(jRadioButton1); jRadioButton1.setText("Debit"); buttonGroup1.add(jRadioButton2); jRadioButton2.setText("Kredit"); jLabel6.setText("User:"); jLabel7.setText("NamaUser"); jButton1.setText("Logout"); jButton2.setText("Insert"); jButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton2MouseClicked(evt); } }); jButton3.setText("Update"); jButton3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton3MouseClicked(evt); } }); jButton4.setText("Delete"); jButton4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton4MouseClicked(evt); } }); jTable2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Kode", "Perkiraan", "No. Ref.", "Posisi", "Harga" } )); jTable2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTable2MouseClicked(evt); } }); jScrollPane2.setViewportView(jTable2); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel2) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel7)) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton4)) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRadioButton2)) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jRadioButton1) .addComponent(jRadioButton2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jButton3) .addComponent(jButton4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked String kode = jTextField1.getText(); String perkiraan = jTextField2.getText(); String noref = jTextField3.getText(); String posisi = ""; if (jRadioButton1.isSelected() == true){ posisi = "Debit"; }else if (jRadioButton2.isSelected() == true){ posisi = "Kredit"; } String harga = jTextField4.getText(); Object[] row = {kode,perkiraan,noref,posisi,harga}; DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); model.addRow(row); }//GEN-LAST:event_jButton2MouseClicked private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked int baris = jTable2.rowAtPoint(evt.getPoint()); String kode = jTextField1.getText(); String perkiraan = jTextField2.getText(); String noref = jTextField3.getText(); String posisi = ""; if (jRadioButton1.isSelected() == true){ posisi = "Debit"; }else if (jRadioButton2.isSelected() == true){ posisi = "Kredit"; } String harga = jTextField4.getText(); DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); model.setValueAt(kode, baris, 0); model.setValueAt(perkiraan, baris, 1); model.setValueAt(noref, baris, 2); model.setValueAt(posisi, baris, 3); model.setValueAt(harga, baris, 4); }//GEN-LAST:event_jButton3MouseClicked private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseClicked DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); model.removeRow(jTable2.rowAtPoint(evt.getPoint())); }//GEN-LAST:event_jButton4MouseClicked private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked int baris = jTable2.rowAtPoint(evt.getPoint()); jTextField1.setText(String.valueOf(jTable2.getValueAt(baris, 0))); jTextField2.setText(String.valueOf(jTable2.getValueAt(baris, 1))); jTextField3.setText(String.valueOf(jTable2.getValueAt(baris,2))); String posisi = String.valueOf(jTable2.getValueAt(baris, 3)); if ("debit".equalsIgnoreCase(posisi)){ jRadioButton1.setSelected(true); }else if ("kredit".equalsIgnoreCase(posisi)){ jRadioButton2.setSelected(true); } jTextField4.setText(String.valueOf(jTable2.getValueAt(baris, 4))); }//GEN-LAST:event_jTable2MouseClicked private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MasterJurnal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; // End of variables declaration//GEN-END:variables }
benyaminl/OCAMS
src/com/ocams/andre/MasterJurnal.java
Java
gpl-3.0
15,559
/* * generated by Xtext */ package org.eclectic.frontend.parser.antlr; import com.google.inject.Inject; import org.eclipse.xtext.parser.antlr.XtextTokenStream; import org.eclectic.frontend.services.TaoGrammarAccess; public class TaoParser extends org.eclipse.xtext.parser.antlr.AbstractAntlrParser { @Inject private TaoGrammarAccess grammarAccess; @Override protected void setInitialHiddenTokens(XtextTokenStream tokenStream) { tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT"); } @Override protected org.eclectic.frontend.parser.antlr.internal.InternalTaoParser createParser(XtextTokenStream stream) { return new org.eclectic.frontend.parser.antlr.internal.InternalTaoParser(stream, getGrammarAccess()); } @Override protected String getDefaultRuleName() { return "TaoTransformation"; } public TaoGrammarAccess getGrammarAccess() { return this.grammarAccess; } public void setGrammarAccess(TaoGrammarAccess grammarAccess) { this.grammarAccess = grammarAccess; } }
jesusc/eclectic
plugins/org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/TaoParser.java
Java
gpl-3.0
1,041
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.github.mdsimmo.pixeldungeon.levels.painters; import com.github.mdsimmo.pixeldungeon.items.Gold; import com.github.mdsimmo.pixeldungeon.items.Heap; import com.github.mdsimmo.pixeldungeon.items.keys.IronKey; import com.github.mdsimmo.pixeldungeon.levels.Level; import com.github.mdsimmo.pixeldungeon.levels.Room; import com.github.mdsimmo.pixeldungeon.levels.Terrain; import com.github.mdsimmo.utils.Random; public class TreasuryPainter extends Painter { public static void paint( Level level, Room room ) { fill( level, room, Terrain.WALL ); fill( level, room, 1, Terrain.EMPTY ); set( level, room.center(), Terrain.STATUE ); Heap.Type heapType = Random.Int( 2 ) == 0 ? Heap.Type.CHEST : Heap.Type.HEAP; int n = Random.IntRange( 2, 3 ); for ( int i = 0; i < n; i++ ) { int pos; do { pos = room.random(); } while ( level.map[pos] != Terrain.EMPTY || level.heaps.get( pos ) != null ); level.drop( new Gold().random(), pos ).type = (i == 0 && heapType == Heap.Type.CHEST ? Heap.Type.MIMIC : heapType); } if ( heapType == Heap.Type.HEAP ) { for ( int i = 0; i < 6; i++ ) { int pos; do { pos = room.random(); } while ( level.map[pos] != Terrain.EMPTY ); level.drop( new Gold( Random.IntRange( 1, 3 ) ), pos ); } } room.entrance().set( Room.Door.Type.LOCKED ); level.addItemToSpawn( new IronKey() ); } }
mdsimmo/cake-dungeon
java/com/github/mdsimmo/pixeldungeon/levels/painters/TreasuryPainter.java
Java
gpl-3.0
2,296
/** * This file is part of JsonFL. * * JsonFL is free software: you can redistribute it and/or modify it under the * terms of the Lesser GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * JsonFL is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the Lesser GNU General Public License for more * details. * * You should have received a copy of the Lesser GNU General Public License * along with JsonFL. If not, see <http://www.gnu.org/licenses/>. */ package au.com.houliston.jsonfl; /** * Is thrown when the creation string for the JsonFL is invalid * * @author Trent Houliston * @version 1.0 */ public class InvalidJsonFLException extends Exception { /** * Creates a new InvalidJsonFLException with the passed message * * @param message The message to set */ public InvalidJsonFLException(String message) { super(message); } /** * Creates a new InvalidJsonFLException along with a message and a cause * * @param message The message to set * @param cause The root cause which made this exception */ public InvalidJsonFLException(String message, Throwable cause) { super(message, cause); } }
TrentHouliston/JsonFL
src/main/java/au/com/houliston/jsonfl/InvalidJsonFLException.java
Java
gpl-3.0
1,371
package edu.kit.iti.formal.mandatsverteilung.generierer; import edu.kit.iti.formal.mandatsverteilung.datenhaltung.Bundestagswahl; /** * Modelliert eine Einschränkung an das Ergebnis des Generierers, dass der * Bundestag eine bestimmte Größe haben soll. * * @author Jan * */ public class SitzzahlEinschraenkung extends Einschraenkung { public SitzzahlEinschraenkung(int wert, int abweichung) { assert wert > 0; assert abweichung > 0; this.wert = wert; this.abweichung = abweichung; gewichtung = 1.0; } @Override int ueberpruefeErgebnis(Bundestagswahl b) { int tatsaechlicheSitzzahl = b.getSitzzahl(); int genauigkeit = RandomisierterGenerierer.getGenauigkeit(); double minD = (minDistance(genauigkeit * tatsaechlicheSitzzahl, genauigkeit * wert, genauigkeit * abweichung)); return (int) (gewichtung * minD); } }
Bundeswahlrechner/Bundeswahlrechner
mandatsverteilung/src/main/java/edu/kit/iti/formal/mandatsverteilung/generierer/SitzzahlEinschraenkung.java
Java
gpl-3.0
934
package name.parsak.controller; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import name.parsak.api.Tcpip; import name.parsak.dto.UsrDptRole; import name.parsak.model.Department; import name.parsak.model.Menu; import name.parsak.model.Role; import name.parsak.model.User; import name.parsak.service.UserDBService; @Controller public class WebController { final private String project_name = "JWC"; final private String user_cookie_name = "user"; final private String blank = ""; final private int max_login_time = 7200; private UserDBService userDBService; @Autowired(required=true) @Qualifier(value="UserDBService") public void setUserDBService(UserDBService us){ this.userDBService = us; } // Create Admin User, if it doesn't exist @RequestMapping(value="setup") public String setup() { this.userDBService.setup(); return "redirect:/"; } // Default page @RequestMapping({"/", "index"}) public String index( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid, @ModelAttribute(project_name)Menu menu) { if (! userid.equals(blank)) { int id = Integer.parseInt(userid); User user = this.userDBService.getUserById(id); if (user != null) { model.addAttribute("id", userid); model.addAttribute("name", user.getName()); model.addAttribute("lastname", user.getLastname()); model.addAttribute("email", user.getEmail()); if (this.userDBService.isUserAdmin(user)) { model.addAttribute("admin", "true"); } try { String name = menu.getName(); if (name != null) { this.userDBService.AddMenu(menu); } } catch (NullPointerException e) {} // menu.id is used to browse long menuid = menu.getId(); model.addAttribute("menu", this.userDBService.getMenuDtoById(menuid)); model.addAttribute("parent", menuid); model.addAttribute("menulist", this.userDBService.getMenuByParent(menuid)); } } return "index"; } // Login User @RequestMapping(value="login") public String login( Model model, @ModelAttribute(project_name)User u, HttpServletResponse response) { Long userid = u.getId(); // In case user enters /login without submitting a login form if (userid != 0) { User user = this.userDBService.getUser(u.getId(), u.getPassword()); if (user != null) { Cookie cookie = new Cookie(user_cookie_name, String.valueOf(user.getId())); cookie.setMaxAge(max_login_time); response.addCookie(cookie); } } return "redirect:/"; } // Logout User @RequestMapping(value="logout") public String logout( HttpServletResponse response) { Cookie cookie = new Cookie(user_cookie_name,blank); cookie.setMaxAge(0); response.addCookie(cookie); return "redirect:/"; } // Display All Users @RequestMapping(value="users") public String users( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid) { if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); model.addAttribute("userslist", this.userDBService.listUsers()); return "users"; } } } return "redirect:/"; } // Display All Departments @RequestMapping(value="departments") public String departments( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid) { if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); model.addAttribute("deptlist", this.userDBService.listDepartments()); model.addAttribute("rolelist", this.userDBService.listRoles()); return "departments"; } } } return "redirect:/"; } @RequestMapping(value="department") public String department( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid, @ModelAttribute(project_name)UsrDptRole usrdptrole){ if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); String DeptName = usrdptrole.getDeptname(); System.out.println(">> Displaying "+DeptName); Department department = this.userDBService.getDepartmentByName(DeptName); model.addAttribute("department", department.getDepartment_name()); // model.addAttribute("deptrolelist", this.userDBService.getDepartmentUsers(department)); return "department"; } } } return "redirect:/"; } @RequestMapping(value="add_user") public String add_user( Model model, @ModelAttribute(project_name)User user, HttpServletResponse response) { String user_name = null; String user_lastname = null; String user_email = null; String user_password = null; try { user_name = user.getName(); user_lastname = user.getLastname(); user_email = user.getEmail(); user_password = user.getPassword(); } catch (NullPointerException e) {} if (user_name != null && user_lastname != null && user_email != null && user_password != null) { this.userDBService.addUser(user); } return "redirect:/users"; } @RequestMapping(value="update_user") public String update_user( Model model, @ModelAttribute(project_name)User user, HttpServletResponse response) { String user_name = null; String user_lastname = null; String user_email = null; String user_password = null; try { user_name = user.getName(); user_lastname = user.getLastname(); user_email = user.getEmail(); user_password = user.getPassword(); } catch (NullPointerException e) {} if (user_name != null && user_lastname != null && user_email != null && user_password != null) { this.userDBService.updateUser(user); } return "redirect:/user"+user.getId(); } // Assign UserRole to a user @RequestMapping(value="add_user_role") public String AddUserRole(@ModelAttribute(project_name)UsrDptRole usrdptrole) { String deptname = usrdptrole.getDeptname(); String rolename = usrdptrole.getRolename(); long userid = usrdptrole.getUserid(); if (userid != 0 && !deptname.equals(blank) && !rolename.equals(blank)) { User user = this.userDBService.getUserById((int) userid); Department department = this.userDBService.getDepartmentByName(deptname); Role role = this.userDBService.getRoleByName(rolename); this.userDBService.AddUserRole(user, department, role); } return "redirect:/user"+userid; } @RequestMapping(value="remove_userrole") public String RemoveUserRole(@ModelAttribute(project_name) UsrDptRole deptrole) { this.userDBService.removeUserRoleById(deptrole.getId()); return "redirect:/user"+deptrole.getUserid(); } // Display User{id} @RequestMapping(value="/user{id}") public String user( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid, @PathVariable("id") int id) { if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); User user = this.userDBService.getUserById(id); model.addAttribute("userid",user.getId()); model.addAttribute("name",user.getName()); model.addAttribute("lastname",user.getLastname()); model.addAttribute("email",user.getEmail()); model.addAttribute("User", user); // To populate Edit Form model.addAttribute("deptrolelist",this.userDBService.getUsrDptRoles(user)); model.addAttribute("deptlist", this.userDBService.listDepartments()); model.addAttribute("rolelist", this.userDBService.listRoles()); return "user"; } } } return "redirect:/"; } // Remove User{id} @RequestMapping(value="/removeuser{id}") public String removeuser( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid, @PathVariable("id") int id) { if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); User user = this.userDBService.getUserById(id); this.userDBService.RemoveUserRoleByUser(user); this.userDBService.removeUser(user); return "redirect:/users"; } } } return "redirect:/"; } @RequestMapping(value="/add_department") public String addNewDepartment(@ModelAttribute(project_name) UsrDptRole deptrole) { this.userDBService.AddDepartment(deptrole.getDeptname()); return "redirect:/departments"; } @RequestMapping(value="/add_role") public String addNewRole(@ModelAttribute(project_name) UsrDptRole deptrole) { this.userDBService.AddRole(deptrole.getRolename()); return "redirect:/departments"; } @RequestMapping(value="/api_test") public String test_api(Model model) { Tcpip tcpip = new Tcpip(); String response = tcpip.get("http://www.google.com"); model.addAttribute("response", response); return "api_test"; } }
yparsak/JWC
src/main/java/name/parsak/controller/WebController.java
Java
gpl-3.0
10,545
package ua.pp.shurgent.tfctech.integration.bc.blocks.pipes.transport; import net.minecraft.item.Item; import net.minecraftforge.common.util.ForgeDirection; import ua.pp.shurgent.tfctech.integration.bc.BCStuff; import ua.pp.shurgent.tfctech.integration.bc.ModPipeIconProvider; import ua.pp.shurgent.tfctech.integration.bc.blocks.pipes.handlers.PipeItemsInsertionHandler; import buildcraft.api.core.IIconProvider; import buildcraft.transport.pipes.PipeItemsQuartz; import buildcraft.transport.pipes.events.PipeEventItem; public class PipeItemsSterlingSilver extends PipeItemsQuartz { public PipeItemsSterlingSilver(Item item) { super(item); } @Override public IIconProvider getIconProvider() { return BCStuff.pipeIconProvider; } @Override public int getIconIndex(ForgeDirection direction) { return ModPipeIconProvider.TYPE.PipeItemsSterlingSilver.ordinal(); } public void eventHandler(PipeEventItem.AdjustSpeed event) { super.eventHandler(event); } public void eventHandler(PipeEventItem.Entered event) { event.item.setInsertionHandler(PipeItemsInsertionHandler.INSTANCE); } }
Shurgent/TFCTech
src/main/java/ua/pp/shurgent/tfctech/integration/bc/blocks/pipes/transport/PipeItemsSterlingSilver.java
Java
gpl-3.0
1,104
package org.crazyit.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; /** * Description: * <br/>site: <a href="http://www.crazyit.org">crazyit.org</a> * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class StartActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //»ñȡӦÓóÌÐòÖеÄbn°´Å¥ Button bn = (Button)findViewById(R.id.bn); //Ϊbn°´Å¥°ó¶¨Ê¼þ¼àÌýÆ÷ bn.setOnClickListener(new OnClickListener() { @Override public void onClick(View source) { //´´½¨ÐèÒªÆô¶¯µÄActivity¶ÔÓ¦µÄIntent Intent intent = new Intent(StartActivity.this , SecondActivity.class); //Æô¶¯intent¶ÔÓ¦µÄActivity startActivity(intent); } }); } }
footoflove/android
crazy_android/04/4.1/StartActivity/src/org/crazyit/activity/StartActivity.java
Java
gpl-3.0
1,081
package ru.mos.polls.ourapps.ui.adapter; import java.util.ArrayList; import java.util.List; import ru.mos.polls.base.BaseRecyclerAdapter; import ru.mos.polls.base.RecyclerBaseViewModel; import ru.mos.polls.ourapps.model.OurApplication; import ru.mos.polls.ourapps.vm.item.OurApplicationVM; public class OurAppsAdapter extends BaseRecyclerAdapter<RecyclerBaseViewModel> { public void add(List<OurApplication> list) { List<RecyclerBaseViewModel> rbvm = new ArrayList<>(); for (OurApplication ourApp : list) { rbvm.add(new OurApplicationVM(ourApp)); } addData(rbvm); } }
active-citizen/android.java
app/src/main/java/ru/mos/polls/ourapps/ui/adapter/OurAppsAdapter.java
Java
gpl-3.0
625
/* * SPDX-License-Identifier: GPL-3.0 * * * (J)ava (M)iscellaneous (U)tilities (L)ibrary * * JMUL is a central repository for utilities which are used in my * other public and private repositories. * * Copyright (C) 2013 Kristian Kutin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * e-mail: kristian.kutin@arcor.de */ /* * This section contains meta informations. * * $Id$ */ package jmul.transformation.xml.rules.xml2object; import jmul.misc.id.ID; import jmul.misc.id.IntegerID; import jmul.reflection.classes.ClassDefinition; import jmul.reflection.classes.ClassHelper; import jmul.string.TextHelper; import jmul.transformation.TransformationException; import jmul.transformation.TransformationParameters; import jmul.transformation.TransformationRuleBase; import jmul.transformation.xml.cache.Xml2ObjectCache; import static jmul.transformation.xml.rules.PersistenceMarkups.ID_ATTRIBUTE; import static jmul.transformation.xml.rules.PersistenceMarkups.OBJECT_ELEMENT; import static jmul.transformation.xml.rules.PersistenceMarkups.TYPE_ATTRIBUTE; import static jmul.transformation.xml.rules.PersistenceMarkups.VALUE_ATTRIBUTE; import static jmul.transformation.xml.rules.TransformationConstants.OBJECT_CACHE; import jmul.xml.XmlParserHelper; import org.w3c.dom.Node; /** * An implementation of a transformation rule. * * @author Kristian Kutin */ public class Xml2ClassRule extends TransformationRuleBase { /** * A class name. */ private static final String EXPECTED_TYPE_NAME = Class.class.getName(); /** * Constructs a transformation rule. * * @param anOrigin * a description of the transformation origin * @param aDestination * a description of the transformation destination * @param aPriority * a rule priority */ public Xml2ClassRule(String anOrigin, String aDestination, int aPriority) { super(anOrigin, aDestination, aPriority); } /** * The method determines if this rule can be applied to the specified * object. * * @param someParameters * some transformation parameters, including the object which is to * be transformed * * @return <code>true</code> if the rule is applicable, else * <code>false</code> */ @Override public boolean isApplicable(TransformationParameters someParameters) { return RuleHelper.isApplicable(someParameters, EXPECTED_TYPE_NAME); } /** * The method performs the actual transformation. * * @param someParameters * some transformation parameters, including the object which is to * be transformed * * @return the transformed object */ @Override public Object transform(TransformationParameters someParameters) { // Check some plausibilites first. if (!someParameters.containsPrerequisite(OBJECT_CACHE)) { String message = TextHelper.concatenateStrings("Prerequisites for the transformation are missing (", OBJECT_CACHE, ")!"); throw new TransformationException(message); } Object target = someParameters.getObject(); Node objectElement = (Node) target; XmlParserHelper.assertMatchesXmlElement(objectElement, OBJECT_ELEMENT); XmlParserHelper.assertExistsXmlAttribute(objectElement, ID_ATTRIBUTE); XmlParserHelper.assertExistsXmlAttribute(objectElement, TYPE_ATTRIBUTE); XmlParserHelper.assertExistsXmlAttribute(objectElement, VALUE_ATTRIBUTE); // Get the required informations. Xml2ObjectCache objectCache = (Xml2ObjectCache) someParameters.getPrerequisite(OBJECT_CACHE); String idString = XmlParserHelper.getXmlAttributeValue(objectElement, ID_ATTRIBUTE); String typeString = XmlParserHelper.getXmlAttributeValue(objectElement, TYPE_ATTRIBUTE); String valueString = XmlParserHelper.getXmlAttributeValue(objectElement, VALUE_ATTRIBUTE); ID id = new IntegerID(idString); ClassDefinition type = null; try { type = ClassHelper.getClass(typeString); } catch (ClassNotFoundException e) { String message = TextHelper.concatenateStrings("An unknown class was specified (", typeString, ")!"); throw new TransformationException(message, e); } Class clazz = null; try { ClassDefinition definition = ClassHelper.getClass(valueString); clazz = definition.getType(); } catch (ClassNotFoundException e) { String message = TextHelper.concatenateStrings("An unknown class was specified (", valueString, ")!"); throw new TransformationException(message, e); } // Instantiate and initialize the specified object objectCache.addObject(id, clazz, type.getType()); return clazz; } }
gammalgris/jmul
Utilities/Transformation-XML/src/jmul/transformation/xml/rules/xml2object/Xml2ClassRule.java
Java
gpl-3.0
5,570
package com.baeldung.webflux; import static java.time.LocalDateTime.now; import static java.util.UUID.randomUUID; import java.time.Duration; import org.springframework.stereotype.Component; import org.springframework.web.reactive.socket.WebSocketHandler; import org.springframework.web.reactive.socket.WebSocketSession; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Component("EmployeeWebSocketHandler") public class EmployeeWebSocketHandler implements WebSocketHandler { ObjectMapper om = new ObjectMapper(); @Override public Mono<Void> handle(WebSocketSession webSocketSession) { Flux<String> employeeCreationEvent = Flux.generate(sink -> { EmployeeCreationEvent event = new EmployeeCreationEvent(randomUUID().toString(), now().toString()); try { sink.next(om.writeValueAsString(event)); } catch (JsonProcessingException e) { sink.error(e); } }); return webSocketSession.send(employeeCreationEvent .map(webSocketSession::textMessage) .delayElements(Duration.ofSeconds(1))); } }
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketHandler.java
Java
gpl-3.0
1,272
package org.vaadin.addons.guice.server; import org.vaadin.addons.guice.servlet.VGuiceApplicationServlet; import com.google.inject.servlet.ServletModule; /** * * @author Will Temperley * */ public class ExampleGuiceServletModule extends ServletModule { @Override protected void configureServlets() { serve("/*").with(VGuiceApplicationServlet.class); } }
241180/Oryx
v-guice-example-master/src/main/java/org/vaadin/addons/guice/server/ExampleGuiceServletModule.java
Java
gpl-3.0
383
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.mariotaku.twidere.util.http; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.microedition.io.Connector; import javax.microedition.io.SecurityInfo; import javax.microedition.io.SocketConnection; import javax.microedition.io.StreamConnection; import repackaged.com.sun.midp.pki.X509Certificate; import repackaged.com.sun.midp.ssl.SSLStreamConnection; /** * * @author mariotaku */ public final class UnsafeSSLConnection implements StreamConnection { private final SSLStreamConnection sc; UnsafeSSLConnection(final String host, final int port) throws IOException { final SocketConnection tcp = (SocketConnection) Connector.open("socket://" + host + ":" + port); tcp.setSocketOption(SocketConnection.DELAY, 0); final InputStream tcpIn = tcp.openInputStream(); final OutputStream tcpOut = tcp.openOutputStream(); sc = new SSLStreamConnection(host, port, tcpIn, tcpOut); } public synchronized OutputStream openOutputStream() throws IOException { return sc.openOutputStream(); } public synchronized InputStream openInputStream() throws IOException { return sc.openInputStream(); } public DataOutputStream openDataOutputStream() throws IOException { return sc.openDataOutputStream(); } public DataInputStream openDataInputStream() throws IOException { return sc.openDataInputStream(); } public X509Certificate getServerCertificate() { return sc.getServerCertificate(); } public SecurityInfo getSecurityInfo() throws IOException { return sc.getSecurityInfo(); } public synchronized void close() throws IOException { sc.close(); } public static UnsafeSSLConnection open(final String host, final int port) throws IOException { if (host == null && port < 0) { return new UnsafeSSLConnection("127.0.0.1", 443); } else if (host != null) { return new UnsafeSSLConnection(host, 443); } return new UnsafeSSLConnection(host, port); } }
mariotaku/twidere.j2me
src/org/mariotaku/twidere/util/http/UnsafeSSLConnection.java
Java
gpl-3.0
2,116
/*********************************************************************** This file is part of KEEL-software, the Data Mining tool for regression, classification, clustering, pattern mining and so on. Copyright (C) 2004-2010 F. Herrera (herrera@decsai.ugr.es) L. Sánchez (luciano@uniovi.es) J. Alcalá-Fdez (jalcala@decsai.ugr.es) S. García (sglopez@ujaen.es) A. Fernández (alberto.fernandez@ujaen.es) J. Luengo (julianlm@decsai.ugr.es) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ **********************************************************************/ package keel.Algorithms.RE_SL_Methods.LEL_TSK; import java.io.*; import org.core.*; import java.util.*; import java.lang.Math; class Simplif { public double semilla; public long cont_soluciones; public long Gen, n_genes, n_reglas, n_generaciones; public int n_soluciones; public String fich_datos_chequeo, fich_datos_tst, fich_datos_val; public String fichero_conf, ruta_salida; public String fichero_br, fichero_reglas, fich_tra_obli, fich_tst_obli; public String datos_inter = ""; public String cadenaReglas = ""; public MiDataset tabla, tabla_tst, tabla_val; public BaseR_TSK base_reglas; public BaseR_TSK base_total; public Adap_Sel fun_adap; public AG alg_gen; public Simplif(String f_e) { fichero_conf = f_e; } private String Quita_blancos(String cadena) { StringTokenizer sT = new StringTokenizer(cadena, "\t ", false); return (sT.nextToken()); } /** Reads the data of the configuration file */ public void leer_conf() { int i, j; String cadenaEntrada, valor; double cruce, mutacion, porc_radio_reglas, porc_min_reglas, alfa, tau; int tipo_fitness, long_poblacion; // we read the file in a String cadenaEntrada = Fichero.leeFichero(fichero_conf); StringTokenizer sT = new StringTokenizer(cadenaEntrada, "\n\r=", false); // we read the algorithm's name sT.nextToken(); sT.nextToken(); // we read the name of the training and test files sT.nextToken(); valor = sT.nextToken(); StringTokenizer ficheros = new StringTokenizer(valor, "\t ", false); fich_datos_chequeo = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); fich_datos_val = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); fich_datos_tst = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); // we read the name of the output files sT.nextToken(); valor = sT.nextToken(); ficheros = new StringTokenizer(valor, "\t ", false); fich_tra_obli = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); fich_tst_obli = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); String aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //Br inicial aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BD fichero_br = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de MAN2TSK fichero_reglas = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de Select aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de Tuning ruta_salida = fich_tst_obli.substring(0, fich_tst_obli.lastIndexOf('/') + 1); // we read the seed of the random generator sT.nextToken(); valor = sT.nextToken(); semilla = Double.parseDouble(valor.trim()); Randomize.setSeed( (long) semilla); ; for (i = 0; i < 19; i++) { sT.nextToken(); //variable sT.nextToken(); //valor } // we read the Number of Iterations sT.nextToken(); valor = sT.nextToken(); n_generaciones = Long.parseLong(valor.trim()); // we read the Population Size sT.nextToken(); valor = sT.nextToken(); long_poblacion = Integer.parseInt(valor.trim()); // we read the Tau parameter for the minimun maching degree required to the KB sT.nextToken(); valor = sT.nextToken(); tau = Double.parseDouble(valor.trim()); // we read the Rate of Rules that don't are eliminated sT.nextToken(); valor = sT.nextToken(); porc_min_reglas = Double.parseDouble(valor.trim()); // we read the Rate of rules to estimate the niche radio sT.nextToken(); valor = sT.nextToken(); porc_radio_reglas = Double.parseDouble(valor.trim()); // we read the Alfa parameter for the Power Law sT.nextToken(); valor = sT.nextToken(); alfa = Double.parseDouble(valor.trim()); // we read the Type of Fitness Function sT.nextToken(); valor = sT.nextToken(); tipo_fitness = Integer.parseInt(valor.trim()); // we select the numero de soluciones n_soluciones = 1; // we read the Cross Probability sT.nextToken(); valor = sT.nextToken(); cruce = Double.parseDouble(valor.trim()); // we read the Mutation Probability sT.nextToken(); valor = sT.nextToken(); mutacion = Double.parseDouble(valor.trim()); // we create all the objects tabla = new MiDataset(fich_datos_chequeo, false); if (tabla.salir == false) { tabla_val = new MiDataset(fich_datos_val, false); tabla_tst = new MiDataset(fich_datos_tst, false); base_total = new BaseR_TSK(fichero_br, tabla, true); base_reglas = new BaseR_TSK(base_total.n_reglas, tabla); fun_adap = new Adap_Sel(tabla, tabla_tst, base_reglas, base_total, base_total.n_reglas, porc_radio_reglas, porc_min_reglas, n_soluciones, tau, alfa, tipo_fitness); alg_gen = new AG(long_poblacion, base_total.n_reglas, cruce, mutacion, fun_adap); } } public void run() { int i, j; double ec, el, min_CR, ectst, eltst; /* We read the configutate file and we initialize the structures and variables */ leer_conf(); if (tabla.salir == false) { /* Inicializacion del contador de soluciones ya generadas */ cont_soluciones = 0; System.out.println("Simplif-TSK"); do { /* Generation of the initial population */ alg_gen.Initialize(); Gen = 0; /* Evaluation of the initial population */ alg_gen.Evaluate(); Gen++; /* Main of the genetic algorithm */ do { /* Interchange of the new and old population */ alg_gen.Intercambio(); /* Selection by means of Baker */ alg_gen.Select(); /* Crossover */ alg_gen.Cruce_Multipunto(); /* Mutation */ alg_gen.Mutacion_Uniforme(); /* Elitist selection */ alg_gen.Elitist(); /* Evaluation of the current population */ alg_gen.Evaluate(); /* we increment the counter */ Gen++; } while (Gen <= n_generaciones); /* we store the RB in the Tabu list */ if (Aceptar(alg_gen.solucion()) == 1) { fun_adap.guardar_solucion(alg_gen.solucion()); /* we increment the number of solutions */ cont_soluciones++; fun_adap.Decodifica(alg_gen.solucion()); fun_adap.Cubrimientos_Base(); /* we calcule the MSEs */ fun_adap.Error_tra(); ec = fun_adap.EC; el = fun_adap.EL; fun_adap.tabla_tst = tabla_tst; fun_adap.Error_tst(); ectst = fun_adap.EC; eltst = fun_adap.EL; /* we calculate the minimum and maximum matching */ min_CR = 1.0; for (i = 0; i < tabla.long_tabla; i++) { min_CR = Adap.Minimo(min_CR, tabla.datos[i].maximo_cubrimiento); } /* we write the RB */ cadenaReglas = base_reglas.BRtoString(); cadenaReglas += "\n\nMinimum of C_R: " + min_CR + " Minimum covering degree: " + fun_adap.mincb + "\nAverage covering degree: " + fun_adap.medcb + " MLE: " + el + "\nMSEtra: " + ec + " , MSEtst: " + ectst + "\n"; Fichero.escribeFichero(fichero_reglas, cadenaReglas); /* we write the obligatory output files*/ String salida_tra = tabla.getCabecera(); salida_tra += fun_adap.getSalidaObli(tabla_val); Fichero.escribeFichero(fich_tra_obli, salida_tra); String salida_tst = tabla_tst.getCabecera(); salida_tst += fun_adap.getSalidaObli(tabla_tst); Fichero.escribeFichero(fich_tst_obli, salida_tst); /* we write the MSEs in specific files */ Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunR.txt", "" + base_reglas.n_reglas + "\n"); Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunTRA.txt", "" + ec + "\n"); Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunTST.txt", "" + ectst + "\n"); } /* the multimodal GA finish when the condition is true */ } while (Parada() == 0); } } /** Criterion of stop */ public int Parada() { if (cont_soluciones == n_soluciones) { return (1); } else { return (0); } } /** Criterion to accept the solutions */ int Aceptar(char[] cromosoma) { return (1); } }
SCI2SUGR/KEEL
src/keel/Algorithms/RE_SL_Methods/LEL_TSK/Simplif.java
Java
gpl-3.0
10,008
package com.orcinuss.reinforcedtools.item.tools; import com.google.common.collect.Sets; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.item.EnumRarity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import java.util.Set; public class ItemRTMHarvester extends ItemTool{ private static final Set blocksToBreak = Sets.newHashSet(new Block[]{Blocks.glowstone}); public EnumRarity rarity; public ItemRTMHarvester(Item.ToolMaterial material) { this(material, EnumRarity.common); } public ItemRTMHarvester(Item.ToolMaterial material, EnumRarity rarity ){ super(0.0F, material, blocksToBreak); this.rarity = rarity; this.maxStackSize = 1; } }
Orcinuss/ReinforcedTools
src/main/java/com/orcinuss/reinforcedtools/item/tools/ItemRTMHarvester.java
Java
gpl-3.0
803
package org.hl7.v3; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>AgeDetectedIssueCodeのJavaクラス。 * * <p>次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。 * <p> * <pre> * &lt;simpleType name="AgeDetectedIssueCode"> * &lt;restriction base="{urn:hl7-org:v3}cs"> * &lt;enumeration value="AGE"/> * &lt;enumeration value="DOSEHINDA"/> * &lt;enumeration value="DOSELINDA"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "AgeDetectedIssueCode") @XmlEnum public enum AgeDetectedIssueCode { AGE, DOSEHINDA, DOSELINDA; public String value() { return name(); } public static AgeDetectedIssueCode fromValue(String v) { return valueOf(v); } }
ricecakesoftware/CommunityMedicalLink
ricecakesoftware.communitymedicallink.hl7/src/org/hl7/v3/AgeDetectedIssueCode.java
Java
gpl-3.0
913
package medium_challenges; import java.util.ArrayList; import java.util.List; import java.util.Scanner; class BenderSolution { public static void main(String args[]) { @SuppressWarnings("resource") Scanner in = new Scanner(System.in); int R = in.nextInt(); int C = in.nextInt(); in.nextLine(); List<Node> teleports = new ArrayList<>(); Node start = null; // Create (x,y) map and store starting point char[][] map = new char[C][R]; for (int y = 0; y < R; y++) { String row = in.nextLine(); for (int x = 0; x < C; x++){ char item = row.charAt(x); map[x][y] = item; if (item == '@') { start = new Node(x,y); } if (item == 'T') { teleports.add(new Node(x,y)); } } } // Create new robot with map Bender bender = new Bender(start, map, teleports); // Limit iterations boolean circular = false; final int MAX_ITERATIONS = 200; // Collect all moves. List<String> moves = new ArrayList<>(); while (bender.alive && !circular) { moves.add(bender.move()); circular = moves.size() > MAX_ITERATIONS; } // Output Result if (circular) System.out.println("LOOP"); else { for (String s: moves) System.out.println(s); } } /** Simple object to store coordinate pair */ private static class Node { final int x, y; Node(int x, int y) { this.x = x; this.y = y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Node other = (Node) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } } /** Object to store state and behavior of Bender */ private static class Bender { Node position; char[][] map; boolean directionToggle; boolean alive; Direction facing; boolean beerToggle; List<Node> teleports; /** Direction enum includes the ability to find next node based on direction Bender is facing. */ private enum Direction { SOUTH(0, 1), EAST(1, 0), NORTH(0, -1), WEST(-1, 0); private int dx; private int dy; Direction (int dx, int dy) { this.dx = dx; this.dy = dy; } public Node newNode(Node original) { return new Node(original.x + dx, original.y + dy); } public Direction nextDirection(boolean toggle) { if (toggle) { switch (this) { case SOUTH: return EAST; case EAST: return NORTH; default: return WEST; } } else { switch (this) { case WEST: return NORTH; case NORTH: return EAST; default: return SOUTH; } } } } public Bender(Node start, char[][] map, List<Node> teleports) { this.position = start; this.map = map; this.alive = true; this.facing = Direction.SOUTH; this.directionToggle = true; this.beerToggle = false; this.teleports = teleports; } /** Updates the state of bender. Returns direction of the move. */ public String move() { char currentContent = map[position.x][position.y]; // Check for Teleporters if (currentContent == 'T') { position = (teleports.get(0).equals(position)) ? teleports.get(1) : teleports.get(0); } // Check for immediate move command if ((""+currentContent).matches("[NESW]")) { switch (currentContent) { case 'N': facing = Direction.NORTH; position = facing.newNode(position); return Direction.NORTH.toString(); case 'W': facing = Direction.WEST; position = facing.newNode(position); return Direction.WEST.toString(); case 'S': facing = Direction.SOUTH; position = facing.newNode(position); return Direction.SOUTH.toString(); default: facing = Direction.EAST; position = facing.newNode(position); return Direction.EAST.toString(); } } // Check for inversion if (currentContent == 'I') { directionToggle = !directionToggle; } // Check for beer if (currentContent == 'B') { beerToggle = !beerToggle; } // Trial next possibility Node trial = facing.newNode(position); char content = map[trial.x][trial.y]; // Check if Bender dies if (content == '$') { alive = false; return facing.toString(); } // Check for beer power to remove X barrier if (beerToggle && content == 'X') { content = ' '; map[trial.x][trial.y] = ' '; } // Check for Obstacles boolean initialCheck = true; while (content == 'X' || content == '#') { // Check for obstacles if (content == 'X' || content == '#') { if (initialCheck) { facing = directionToggle ? Direction.SOUTH : Direction.WEST; initialCheck = false; } else { facing = facing.nextDirection(directionToggle); } } // Update position and facing trial = facing.newNode(position); content = map[trial.x][trial.y]; } // If we made it to this point, it's okay to move bender position = facing.newNode(position); if (content == '$') alive = false; return facing.toString(); } } }
workwelldone/bright-eyes
src/medium_challenges/BenderSolution.java
Java
gpl-3.0
5,937
package me.zsj.moment.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; import com.bumptech.glide.load.resource.bitmap.BitmapTransformation; /** * @author zsj */ public class CircleTransform extends BitmapTransformation { public CircleTransform(Context context) { super(context); } @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { return circleCrop(pool, toTransform); } private static Bitmap circleCrop(BitmapPool pool, Bitmap source) { if (source == null) return null; int size = Math.min(source.getWidth(), source.getHeight()); int x = (source.getWidth() - size) / 2; int y = (source.getHeight() - size) / 2; Bitmap squared = Bitmap.createBitmap(source, x, y, size, size); Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888); if (result == null) { result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(result); Paint paint = new Paint(); paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); paint.setAntiAlias(true); float r = size / 2f; canvas.drawCircle(r, r, r, paint); squared.recycle(); return result; } @Override public String getId() { return getClass().getName(); } }
Assassinss/Moment
app/src/main/java/me/zsj/moment/utils/CircleTransform.java
Java
gpl-3.0
1,691
package clientdata.visitors; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.HashMap; import java.util.Map; import org.apache.mina.core.buffer.IoBuffer; import clientdata.VisitorInterface; public class SlotDefinitionVisitor implements VisitorInterface { public static class SlotDefinition { public String slotName; public byte global; public byte canMod; public byte exclusive; public String hardpointName; public int unk1; } public SlotDefinitionVisitor() { definitions = new HashMap<String, SlotDefinition>(); } private Map<String, SlotDefinition> definitions; public Map<String, SlotDefinition> getDefinitions() { return definitions; } @Override public void parseData(String nodename, IoBuffer data, int depth, int size) throws Exception { if(nodename.endsWith("DATA")) { CharsetDecoder cd = Charset.forName("US-ASCII").newDecoder(); while(data.hasRemaining()) { SlotDefinition next = new SlotDefinition(); next.slotName = data.getString(cd); cd.reset(); next.global = data.get(); next.canMod = data.get(); next.exclusive = data.get(); next.hardpointName = data.getString(cd); cd.reset(); next.unk1 = data.getInt(); definitions.put(next.slotName, next); } } } @Override public void notifyFolder(String nodeName, int depth) throws Exception {} }
swgopenge/openge
src/clientdata/visitors/SlotDefinitionVisitor.java
Java
gpl-3.0
1,410
package fr.eurecom.senml.entity; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; import com.google.appengine.api.datastore.Key; @PersistenceCapable public class ContactTest { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Key key; @Persistent private String firstName; @Persistent private String lastName; @Persistent private String email; public ContactTest(String firstName, String lastName, String email) { this.firstName = firstName; this.lastName = lastName; this.email = email; } public String getirstName() {return firstName;} public String getLastName() {return lastName;} public String getEmail() {return email;} public Key getKey() {return key;} }
mspublic/openair4G-mirror
targets/PROJECTS/SPECTRA/DEMO_SPECTRA/spectra_demo_src/CRM/server-gae/restlet/src/fr/eurecom/senml/entity/ContactTest.java
Java
gpl-3.0
917
package me.anthonybruno.soccerSim.team.member; import me.anthonybruno.soccerSim.models.Range; /** * Player is a class that contains information about a player. */ public class Player extends TeamMember { private final Range shotRange; private final int goal; /** * Creates a new player with a name, shot range (how likely a shot will be attributed to the player) and a goal * rating (how likely they are to score a goal). * * @param name The name of the player * @param shotRange Shot range of player. Defines how likely a shot on goal will be attributed to this player (see * rule files for more information. Is the maximum value when lower and upper bounds given by the * rules. * @param goal How likely a shot from the player will go in. When shot is taken, a number from 1-10 is generated. * If the generated number is above or equal to goal rating, the player scores. */ public Player(String name, Range shotRange, int goal, int multiplier) { super(name, multiplier); this.shotRange = shotRange; this.goal = goal; } /** * Returns the shot range of player. * * @return the player's shot range. */ public Range getShotRange() { return shotRange; } /** * Returns the goal rating of the player. * * @return the player's goal range. */ public int getGoal() { return goal; } }
AussieGuy0/soccerSim
src/main/java/me/anthonybruno/soccerSim/team/member/Player.java
Java
gpl-3.0
1,523
package vizardous.delegate.dataFilter; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import vizardous.util.Converter; /** * Filter class that provides filter functionality for data structures with comparable content * * @author Johannes Seiffarth <j.seiffarth@fz-juelich.de> */ public class ComparableFilter { /** * Filters a map. All values (not keys!) that equal kick will be removed * @param map to filter * @param kick Value to kick out */ public static <T extends Comparable<T>, K> void filter(Map<K,T> map, T kick) { Set<Map.Entry<K, T>> entrySet = map.entrySet(); for(Iterator<Map.Entry<K,T>> it = entrySet.iterator(); it.hasNext();) { Map.Entry<K, T> entry = it.next(); if(entry.getValue().equals(kick)) it.remove(); } } /** * Filters a list. All values that equal kick will be removed * @param list to filter * @param kick Value to kick out * @return a reference to list (no new list!) */ public static <T extends Comparable<T>> List<T> filter(List<T> list, T kick) { for(Iterator<T> it = list.iterator(); it.hasNext();) { T val = it.next(); if(val.equals(kick)) it.remove(); } return list; } /** * Filters a double array. All values that equal kick will be removed * @param data array to filter * @param kick Value to kick out * @return a new filtered array */ public static double[] filter(double[] data, double kick) { LinkedList<Double> list = new LinkedList<Double>(); for(double value : data) { if(value != kick) list.add(value); } return Converter.listToArray(list); } }
modsim/vizardous
src/main/java/vizardous/delegate/dataFilter/ComparableFilter.java
Java
gpl-3.0
1,741
package com.albion.common.graph.algorithms; import com.albion.common.graph.core.v1.Edge; import com.albion.common.graph.core.v1.Graph; import com.albion.common.graph.core.v1.Vertex; import java.util.ArrayList; import java.util.List; public class BreathFirstSearch { public static Vertex locate(Graph graph, Integer source, Integer target){ List<Vertex> queue = new ArrayList<>(); Vertex root = graph.getVertex(source); queue.add(root); while(!queue.isEmpty()){ Vertex v = queue.remove(0); if(v.getId() == target.intValue()){ v.setVisited(true); return v; } List<Edge> edgeList = v.getEdgeList(); for(Edge edge : edgeList){ int vertexId = edge.getY(); Vertex w = graph.getVerticesMap().get(vertexId); if(w.isVisited() == false){ w.setVisited(true); queue.add(w); } } } return null; } }
KyleLearnedThis/data-structures
src/main/java/com/albion/common/graph/algorithms/BreathFirstSearch.java
Java
gpl-3.0
868
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package services; import FareCalculator.Calculate; import java.util.ArrayList; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.PathParam; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.logging.Level; import java.util.logging.Logger; import java.lang.ClassNotFoundException; import java.net.URI; import javax.ws.rs.DefaultValue; import javax.ws.rs.QueryParam; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; import localstorage.FaresType; /** * * @author peppa */ @Path("/") public class calculatorService { @Context private UriInfo context; public calculatorService(){ } @GET @Path("/calculate") @Produces({"application/xml"}) public Response fareCalculator(@DefaultValue("TK") @QueryParam("carrier") String carrier, @DefaultValue("2012-01-01") @QueryParam("date") String date, @DefaultValue("ADB") @QueryParam("origCode") String origCode, @DefaultValue("ESB") @QueryParam("destCode") String destCode, @DefaultValue("Economy") @QueryParam("fareClass") String fareClass) { Calculate cal = new Calculate(); FaresType fare = cal.fareCalculate(carrier, date, origCode, destCode, fareClass); return Response.ok(new JAXBElement<FaresType>(new QName("faresType"), FaresType.class, fare)).build(); } }
ecemandirac/FlightTracker
Fare_Module/src/java/services/calculatorService.java
Java
gpl-3.0
1,825
package xyw.ning.juicer.poco.model; import xyw.ning.juicer.base.NoProguard; /** * Created by Ning-win on 2016/7/30. */ public class Size implements NoProguard { public String url; public long width; public long height; }
ningshu/Juicer
app/src/main/java/xyw/ning/juicer/poco/model/Size.java
Java
gpl-3.0
237
/* * Copyright (C) 2014 Matej Kormuth <http://matejkormuth.eu> * * 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 ts3bot.helpers; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Helper for testing method signatures. */ public final class MethodSignatureTester { // Object methods. private static final List<MethodSignature> objectMethodSignatures = new ArrayList<MethodSignatureTester.MethodSignature>(); static { for (Method m : Object.class.getDeclaredMethods()) { objectMethodSignatures.add(new MethodSignature(m.getName(), m.getParameterTypes())); } } /** * Checks whether specified interface declares all of public methods implementation class declares. * * @param impl * implementation class * @param interf * interface class * @throws RuntimeException * When interface does not declare public method implementation class does */ public static final void hasInterfAllImplPublicMethods(final Class<?> impl, final Class<?> interf) { List<MethodSignature> interfMethodSignatures = new ArrayList<MethodSignature>( 100); // Generate interface method signatures. for (Method m : interf.getDeclaredMethods()) { // Interface has only public abstract methods. interfMethodSignatures.add(new MethodSignature(m.getName(), m.getParameterTypes())); } for (Method m : impl.getDeclaredMethods()) { // Checking only public methods. MethodSignature ms; if (Modifier.isPublic(m.getModifiers())) { // Build method signature. ms = new MethodSignature(m.getName(), m.getParameterTypes()); // Don't check methods derived from Object. if (!objectMethodSignatures.contains(ms)) { // Check if interface declares it. if (!interfMethodSignatures.contains(ms)) { throw new RuntimeException( "Interface '" + interf.getName() + "' does not declare method " + ms.toString() + " implemented in class '" + impl.getName() + "'!"); } } } } } /** * Class that specified method signature in Java. */ private static class MethodSignature { private final String name; private final Class<?>[] params; public MethodSignature(final String name, final Class<?>[] params) { this.name = name; this.params = params; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); result = prime * result + ((this.params == null) ? 0 : this.params.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (this.getClass() != obj.getClass()) return false; MethodSignature other = (MethodSignature) obj; if (this.name == null) { if (other.name != null) return false; } else if (!this.name.equals(other.name)) return false; if (this.params == null) { if (other.params != null) return false; } else if (this.params.length != other.params.length) return false; for (int i = 0; i < this.params.length; i++) { if (!this.params[i].equals(other.params[i])) { return false; } } return true; } @Override public String toString() { return "MethodSignature [name=" + this.name + ", params=" + Arrays.toString(this.params) + "]"; } } }
dobrakmato/Sergius
src/test/java/ts3bot/helpers/MethodSignatureTester.java
Java
gpl-3.0
4,969
package org.anddev.amatidev.pvb; import java.util.LinkedList; import org.amatidev.util.AdEnviroment; import org.amatidev.util.AdPrefs; import org.anddev.amatidev.pvb.bug.BugBeetle; import org.anddev.amatidev.pvb.card.Card; import org.anddev.amatidev.pvb.card.CardTomato; import org.anddev.amatidev.pvb.obj.Dialog; import org.anddev.amatidev.pvb.plant.Plant; import org.anddev.amatidev.pvb.singleton.GameData; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.text.Text; public class Tutorial extends MainGame { private Sprite mArrow; private int mTutorialStep = 1; @Override public void createScene() { // sfondo e tabellone Sprite back = new Sprite(0, 0, GameData.getInstance().mBackground); Sprite table = new Sprite(0, 0, GameData.getInstance().mTable); getChild(BACKGROUND_LAYER).attachChild(back); getChild(BACKGROUND_LAYER).attachChild(table); Sprite seed = new Sprite(25, 14, GameData.getInstance().mSeed); table.attachChild(seed); GameData.getInstance().mMySeed.setParent(null); table.attachChild(GameData.getInstance().mMySeed); // field position for (int i = 0; i < FIELDS; i++) { int x = i % 9; int y = (int)(i / 9); Rectangle field = new Rectangle(0, 0, 68, 74); field.setColor(0f, 0f, 0f); if (i % 2 == 0) field.setAlpha(0.05f); else field.setAlpha(0.08f); field.setPosition(42 + x * 71, 96 + y * 77); getChild(GAME_LAYER).attachChild(field); registerTouchArea(field); } } protected void initLevel() { // contatori per individuare se in una riga c'e' un nemico AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "enemy"); AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "enemy_killed"); AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count96.0"); AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count173.0"); AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count250.0"); AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count327.0"); AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count404.0"); GameData.getInstance().mMySeed.resetScore(); LinkedList<Card> cards = GameData.getInstance().mCards; cards.clear(); cards.add(new CardTomato()); // TUTORIAL this.mArrow = new Sprite(106, 95, GameData.getInstance().mArrow); this.mArrow.setColor(1f, 0.4f, 0.4f); this.mArrow.registerEntityModifier( new LoopEntityModifier( null, -1, null, new SequenceEntityModifier( new ScaleModifier(0.5f, 1f, 1.2f), new ScaleModifier(0.5f, 1.2f, 1f) ) ) ); getChild(GUI_LAYER).attachChild(this.mArrow); AdEnviroment.getInstance().showMessage("Select a card to use"); AdEnviroment.getInstance().showMessage("Each card has a recharge time and price"); } @Override public void startScene() { initLevel(); // add card LinkedList<Card> cards = GameData.getInstance().mCards; int start_x = 106; for (int i = 0; i < cards.size(); i++) { Card c = cards.get(i); c.setPosition(start_x + i * 69, 7); getChild(BACKGROUND_LAYER).attachChild(c); } Text skip = new Text(0, 0, GameData.getInstance().mFontTutorial, "Skip"); skip.setColor(1.0f, 0.3f, 0.3f); skip.setPosition(37, 360); getChild(GUI_LAYER).attachChild(skip); registerTouchArea(skip); } public void checkLevelFinish() { if (this.mGameOver == false && this.mLevelFinish == false) { registerUpdateHandler(new TimerHandler(2f, false, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { if (Tutorial.this.mTutorialStep == 4) { final Sprite e = new Sprite(12, 25, GameData.getInstance().mSeed); IEntity field = getChild(GAME_LAYER).getChild(12); if (field.getChildCount() == 0) field.attachChild(e); Tutorial.this.mTutorialStep++; Tutorial.this.mArrow.setPosition(310, 135); Tutorial.this.mArrow.setRotation(-132f); AdEnviroment.getInstance().showMessage("Pick the seeds producing the field to increase the stock"); } } })); } } private void levelFinish() { if (this.mGameOver == false && this.mLevelFinish == false) { Dialog dialog = new Dialog("Tutorial\nComplete"); getChild(GUI2_LAYER).attachChild(dialog); clearScene(); registerUpdateHandler(new TimerHandler(6, false, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { AdEnviroment.getInstance().nextScene(); } })); this.mLevelFinish = true; GameData.getInstance().mMyScore.resetScore(); } } @Override public void manageAreaTouch(ITouchArea pTouchArea) { if (pTouchArea instanceof Card) { GameData.getInstance().mSoundCard.play(); this.mSelect = ((Card) pTouchArea).makeSelect(); // TUTORIAL if (this.mTutorialStep == 1) { this.mTutorialStep++; this.mArrow.setPosition(595, 203); this.mArrow.setRotation(132f); AdEnviroment.getInstance().showMessage("If bugs incoming, try to kill them by planting"); BugBeetle e = new BugBeetle(250f); getChild(GAME_LAYER).attachChild(e); registerUpdateHandler(new TimerHandler(6f, false, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { Tutorial.this.mTutorialStep++; Tutorial.this.mArrow.setPosition(100, 203); Tutorial.this.mArrow.setRotation(-132f); AdEnviroment.getInstance().showMessage("If you have enough seeds you can plant"); } })); } } else { IEntity field = (IEntity) pTouchArea; if (field.getChildCount() == 1 && !(field.getFirstChild() instanceof Plant)) { GameData.getInstance().mSoundSeed.play(); GameData.getInstance().mMySeed.addScore(1); AdEnviroment.getInstance().safeDetachEntity(field.getFirstChild()); if (this.mTutorialStep == 5) { this.mTutorialStep++; this.mArrow.setPosition(17, 95); this.mArrow.setRotation(0f); AdEnviroment.getInstance().showMessage("Seeds stock are increased to +1"); AdEnviroment.getInstance().showMessage("Kill bugs to complete levels and obtain score and new plants"); registerUpdateHandler(new TimerHandler(9f, false, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { AdEnviroment.getInstance().getEngine().runOnUpdateThread(new Runnable() { @Override public void run() { Tutorial.this.levelFinish(); } }); } })); } } else if (field instanceof Text) { GameData.getInstance().mSoundMenu.play(); AdEnviroment.getInstance().nextScene(); } else { if (this.mSelect != null && this.mSelect.isReady() && field.getChildCount() == 0 && this.mTutorialStep >= 3 && field.getY() == 250.0f) { if (GameData.getInstance().mMySeed.getScore() >= this.mSelect.getPrice()) { GameData.getInstance().mMySeed.addScore(-this.mSelect.getPrice()); this.mSelect.startRecharge(); field.attachChild(this.mSelect.getPlant()); // TUTORIAL if (this.mTutorialStep == 3) { this.mTutorialStep++; this.mArrow.setPosition(17, 95); this.mArrow.setRotation(0f); AdEnviroment.getInstance().showMessage("Seeds stock are decreased because you bought a plant"); } } } } } } }
amatig/PlantsVsBugs
src/org/anddev/amatidev/pvb/Tutorial.java
Java
gpl-3.0
7,881