repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
runelite/runelite
runelite-client/src/main/java/net/runelite/client/plugins/devtools/WidgetInspectorOverlay.java
4215
/* * Copyright (c) 2018 Abex * Copyright (c) 2017, Kronos <https://github.com/KronosDesign> * Copyright (c) 2017, Adam <Adam@sigterm.info> * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.plugins.devtools; import java.awt.Color; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import javax.inject.Inject; import javax.inject.Singleton; import net.runelite.api.Client; import net.runelite.api.MenuEntry; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetID; import net.runelite.api.widgets.WidgetItem; import net.runelite.client.ui.overlay.Overlay; import net.runelite.client.ui.overlay.OverlayLayer; import net.runelite.client.ui.overlay.OverlayPosition; import net.runelite.client.ui.overlay.OverlayPriority; @Singleton public class WidgetInspectorOverlay extends Overlay { private final Client client; private final WidgetInspector inspector; @Inject public WidgetInspectorOverlay( Client client, WidgetInspector inspector ) { this.client = client; this.inspector = inspector; setPosition(OverlayPosition.DYNAMIC); setLayer(OverlayLayer.ABOVE_WIDGETS); setPriority(OverlayPriority.HIGHEST); drawAfterInterface(WidgetID.FULLSCREEN_CONTAINER_TLI); } @Override public Dimension render(Graphics2D g) { Widget w = inspector.getSelectedWidget(); if (w != null) { Object wiw = w; if (inspector.getSelectedItem() != -1) { wiw = w.getWidgetItem(inspector.getSelectedItem()); } renderWiw(g, wiw, WidgetInspector.SELECTED_WIDGET_COLOR); } if (inspector.isPickerSelected()) { boolean menuOpen = client.isMenuOpen(); MenuEntry[] entries = client.getMenuEntries(); for (int i = menuOpen ? 0 : entries.length - 1; i < entries.length; i++) { MenuEntry e = entries[i]; Object wiw = inspector.getWidgetOrWidgetItemForMenuOption(e.getType(), e.getParam0(), e.getParam1()); if (wiw == null) { continue; } Color color = inspector.colorForWidget(i, entries.length); renderWiw(g, wiw, color); } } return null; } private void renderWiw(Graphics2D g, Object wiw, Color color) { g.setColor(color); if (wiw instanceof WidgetItem) { WidgetItem wi = (WidgetItem) wiw; Rectangle bounds = wi.getCanvasBounds(); g.draw(bounds); String text = wi.getId() + ""; FontMetrics fm = g.getFontMetrics(); Rectangle2D textBounds = fm.getStringBounds(text, g); int textX = (int) (bounds.getX() + (bounds.getWidth() / 2) - (textBounds.getWidth() / 2)); int textY = (int) (bounds.getY() + (bounds.getHeight() / 2) + (textBounds.getHeight() / 2)); g.setColor(Color.BLACK); g.drawString(text, textX + 1, textY + 1); g.setColor(Color.ORANGE); g.drawString(text, textX, textY); } else { Widget w = (Widget) wiw; g.draw(w.getBounds()); } } }
bsd-2-clause
vilmospapp/jodd
jodd-db/src/test/java/jodd/db/oom/fixtures/BooSqlType.java
1894
// Copyright (c) 2003-present, Jodd Team (http://jodd.org) // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package jodd.db.oom.fixtures; import jodd.db.type.SqlType; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.ResultSet; public class BooSqlType extends SqlType<Boo> { @Override public void set(PreparedStatement st, int index, Boo value, int dbSqlType) throws SQLException { st.setInt(index, value.value); } @Override public Boo get(ResultSet rs, int index, int dbSqlType) throws SQLException { Boo boo = new Boo(); boo.value = rs.getInt(index); return boo; } }
bsd-2-clause
highsource/jsonix-schema-compiler
compiler/src/main/java/org/hisrc/jsonix/configuration/exception/AmbiguousMappingNameException.java
613
package org.hisrc.jsonix.configuration.exception; import java.text.MessageFormat; import org.apache.commons.lang3.Validate; public class AmbiguousMappingNameException extends ConfigurationException { private static final long serialVersionUID = -7107929604268428687L; private final String name; public AmbiguousMappingNameException(String name) { super( MessageFormat .format("There is more than one mapping with the name [{0}], please set and use id attributes for mapping references.", Validate.notNull(name))); this.name = name; } public String getName() { return name; } }
bsd-2-clause
MightyPork/tortuga
src/com/porcupine/time/TimerInterpolating.java
1816
package com.porcupine.time; /** * Timer for interpolated timing * * @author Ondřej Hruška (MightyPork) */ public class TimerInterpolating { private long lastFrame = 0; private long nextFrame = 0; private long skipped = 0; private long lastSkipped = 0; private static final long SECOND = 1000000000; // a million nanoseconds private long FRAME; // a time of one frame in nanoseconds /** * New interpolated timer * * @param fps target FPS */ public TimerInterpolating(long fps) { FRAME = Math.round(SECOND / fps); lastFrame = System.nanoTime(); nextFrame = System.nanoTime() + FRAME; } /** * Sync and calculate dropped frames etc. */ public void sync() { long time = getTime(); if (time >= nextFrame) { long skippedNow = (long) Math.floor((time - nextFrame) / (double) FRAME) + 1; //System.out.println("Skipping: "+skippedNow); skipped += skippedNow; lastFrame = nextFrame + (1 - skippedNow) * FRAME; nextFrame += skippedNow * FRAME; } } /** * Get nanotime * * @return nanotime */ public long getTime() { return System.nanoTime(); } /** * Get fraction of next frame * * @return fraction */ public double getFraction() { if (getSkipped() >= 1) { return 1; } long time = getTime(); if (time <= nextFrame) { return (double) (time - lastFrame) / (double) FRAME; } return 1; } /** * Get number of elapsed ticks * * @return ticks */ public int getSkipped() { long change = skipped - lastSkipped; lastSkipped = skipped; return (int) change; } /** * Clear timer and start counting new tick. */ public void startNewFrame() { //System.out.println("! start new frame !"); long time = getTime(); lastFrame = time; nextFrame = time + FRAME; lastSkipped = skipped; } }
bsd-2-clause
tkmnet/RCRS-ADF
gradle/gradle-2.1/src/language-jvm/org/gradle/api/internal/tasks/compile/CleaningGroovyCompiler.java
1590
/* * Copyright 2010 the original author or authors. * * 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 org.gradle.api.internal.tasks.compile; import org.gradle.api.internal.TaskOutputsInternal; import org.gradle.language.base.internal.compile.Compiler; import org.gradle.language.jvm.internal.SimpleStaleClassCleaner; import org.gradle.language.jvm.internal.StaleClassCleaner; public class CleaningGroovyCompiler extends CleaningJavaCompilerSupport<GroovyJavaJointCompileSpec> { private final Compiler<GroovyJavaJointCompileSpec> compiler; private final TaskOutputsInternal taskOutputs; public CleaningGroovyCompiler(Compiler<GroovyJavaJointCompileSpec> compiler, TaskOutputsInternal taskOutputs) { this.compiler = compiler; this.taskOutputs = taskOutputs; } @Override protected Compiler<GroovyJavaJointCompileSpec> getCompiler() { return compiler; } @Override protected StaleClassCleaner createCleaner(GroovyJavaJointCompileSpec spec) { return new SimpleStaleClassCleaner(taskOutputs); } }
bsd-2-clause
imagejan/imagej-updater
src/main/java/net/imagej/updater/action/Upload.java
5359
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2015 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package net.imagej.updater.action; import java.util.Collection; import java.util.Collections; import net.imagej.updater.FileObject; import net.imagej.updater.FilesCollection; import net.imagej.updater.GroupAction; import net.imagej.updater.UpdateSite; import net.imagej.updater.FileObject.Action; import net.imagej.updater.FileObject.Status; /** * The <i>upload</i> action. * * <p> * This class determines whether a bunch of files can be uploaded to a given * update site (possibly shadowing another update site's versions of the same * files), how to mark them to be uploaded, and what to call this action in the * GUI. * </p> * * @author Johannes Schindelin */ public class Upload implements GroupAction { private String updateSite; public Upload(final String updateSite) { this.updateSite = updateSite; } /** * Determines whether a particular set of files can be uploaded to this * update site. * * <p> * Uploading to a higher-ranked update site is called <i>shadowing</i>. This * table indicates what actions are valid: * <table> * <tr> * <th>&nbsp;</th> * <th>upload</th> * <th>shadow</th> * </tr> * <tr> * <td>INSTALLED</td> * <td>NO</td> * <td>RANK</td> * </tr> * <tr> * <td>LOCAL_ONLY</td> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <td>MODIFIED</td> * <td>YES</td> * <td>RANK</td> * </tr> * <tr> * <td>NEW</td> * <td>NO</td> * <td>NO</td> * </tr> * <tr> * <td>NOT_INSTALLED</td> * <td>NO</td> * <td>NO</td> * </tr> * <tr> * <td>OBSOLETE</td> * <td>YES</td> * <td>RANK</td> * </tr> * <tr> * <td>OBSOLETE_MODIFIED</td> * <td>YES</td> * <td>RANK</td> * </tr> * <tr> * <td>OBSOLETE_UNINSTALLED</td> * <td>NO</td> * <td>NO</td> * </tr> * <tr> * <td>UPDATEABLE</td> * <td>YES</td> * <td>RANK</td> * </tr> * </table> * * where <i>RANK</i> means that the rank of the update site to upload to * must be greater than the rank of the file's current update site. * </p> */ @Override public boolean isValid(FilesCollection files, FileObject file) { final Status status = file.getStatus(); final boolean canUpload = status.isValid(Action.UPLOAD); boolean shadowing = file.updateSite != null && !updateSite.equals(file.updateSite); if (!canUpload && status != Status.INSTALLED) return false; final Collection<String> sites = files.getSiteNamesToUpload(); if (sites.size() > 0 && !sites.contains(updateSite)) return false; if (shadowing) { final UpdateSite shadowingSite = files.getUpdateSite(updateSite, false); final UpdateSite shadowedSite = files.getUpdateSite(file.updateSite, false); if (shadowingSite.getRank() < shadowedSite.getRank()) return false; } return true; } @Override public void setAction(FilesCollection files, FileObject file) { if (file.updateSite != null && !file.updateSite.equals(updateSite) && file.originalUpdateSite == null) { file.originalUpdateSite = file.updateSite; } file.updateSite = updateSite; if (file.getStatus() == Status.INSTALLED) file.setStatus(Status.MODIFIED); // TODO: add to overriding file.setAction(files, Action.UPLOAD); } @Override public String getLabel(FilesCollection files, Iterable<FileObject> selected) { boolean shadowing = false; for (final FileObject file : selected) { final Status status = file.getStatus(); if (status.isValid(Action.UPLOAD) || status == Status.INSTALLED) { if (file.updateSite != null && !file.updateSite.equals(updateSite)) { shadowing = true; } } } return "Upload" + (shadowing ? " (shadowing)" : "") + " to " + updateSite; } @Override public String toString() { return getLabel(null, Collections.<FileObject>emptyList()); } }
bsd-2-clause
Pushjet/Pushjet-Android
gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/src/core-impl/org/gradle/api/internal/externalresource/local/AbstractLocallyAvailableResourceFinder.java
1273
/* * Copyright 2012 the original author or authors. * * 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 org.gradle.api.internal.externalresource.local; import org.gradle.api.Transformer; import org.gradle.internal.Factory; import java.io.File; import java.util.List; public class AbstractLocallyAvailableResourceFinder<C> implements LocallyAvailableResourceFinder<C> { private final Transformer<Factory<List<File>>, C> producer; public AbstractLocallyAvailableResourceFinder(Transformer<Factory<List<File>>, C> producer) { this.producer = producer; } public LocallyAvailableResourceCandidates findCandidates(C criterion) { return new LazyLocallyAvailableResourceCandidates(producer.transform(criterion)); } }
bsd-2-clause
jayantk/jklol
src/com/jayantkrish/jklol/lisp/AmbLispMaxMarginOracle.java
5629
package com.jayantkrish.jklol.lisp; import java.util.Arrays; import java.util.List; import com.google.common.base.Preconditions; import com.jayantkrish.jklol.evaluation.Example; import com.jayantkrish.jklol.inference.MarginalCalculator; import com.jayantkrish.jklol.inference.MaxMarginalSet; import com.jayantkrish.jklol.lisp.AmbEval.AmbFunctionValue; import com.jayantkrish.jklol.lisp.ParametricBfgBuilder.MarkedVars; import com.jayantkrish.jklol.models.FactorGraph; import com.jayantkrish.jklol.models.VariableNumMap; import com.jayantkrish.jklol.models.VariableNumMap.VariableRelabeling; import com.jayantkrish.jklol.models.parametric.ParametricFactor; import com.jayantkrish.jklol.models.parametric.SufficientStatistics; import com.jayantkrish.jklol.training.GradientOracle; import com.jayantkrish.jklol.training.LogFunction; import com.jayantkrish.jklol.util.Assignment; public class AmbLispMaxMarginOracle implements GradientOracle<AmbFunctionValue, Example<List<Object>, Example<AmbFunctionValue,AmbFunctionValue>>> { private final AmbFunctionValue family; private final EvalContext context; private final ParameterSpec parameterSpec; private final MarginalCalculator marginalCalculator; public AmbLispMaxMarginOracle(AmbFunctionValue family, EvalContext context, ParameterSpec parameterSpec, MarginalCalculator marginalCalculator) { this.family = Preconditions.checkNotNull(family); this.context = Preconditions.checkNotNull(context); this.parameterSpec = Preconditions.checkNotNull(parameterSpec); this.marginalCalculator = Preconditions.checkNotNull(marginalCalculator); } @Override public AmbFunctionValue instantiateModel(SufficientStatistics parameters) { ParametricBfgBuilder newBuilder = new ParametricBfgBuilder(true); Object value = family.apply(Arrays.<Object>asList(new SpecAndParameters(parameterSpec, parameters)), context, newBuilder); Preconditions.checkState(value instanceof AmbFunctionValue); return (AmbFunctionValue) value; } @Override public SufficientStatistics initializeGradient() { return parameterSpec.getNewParameters(); } @Override public double accumulateGradient(SufficientStatistics gradient, SufficientStatistics currentParameters, AmbFunctionValue instantiatedModel, Example<List<Object>, Example<AmbFunctionValue, AmbFunctionValue>> example, LogFunction log) { List<Object> input = example.getInput(); AmbFunctionValue costFunction = example.getOutput().getInput(); AmbFunctionValue outputFunction = example.getOutput().getOutput(); // Evaluate the nondeterministic function on the input value // then augment the distribution with the costs. ParametricBfgBuilder inputBuilder = new ParametricBfgBuilder(true); Object inputApplicationResult = instantiatedModel.apply(input, context, inputBuilder); costFunction.apply(Arrays.asList(inputApplicationResult), context, inputBuilder); FactorGraph inputFactorGraph = inputBuilder.buildNoBranching(); MaxMarginalSet inputMaxMarginals = marginalCalculator.computeMaxMarginals(inputFactorGraph); Assignment costConditionalAssignment = inputMaxMarginals.getNthBestAssignment(0); double costConditionalScore = inputFactorGraph.getUnnormalizedLogProbability( costConditionalAssignment); // Evaluate the nondeterministic function on the input value // then condition the distribution on the true output. ParametricBfgBuilder outputBuilder = new ParametricBfgBuilder(true); inputApplicationResult = instantiatedModel.apply(input, context, outputBuilder); outputFunction.apply(Arrays.asList(inputApplicationResult), context, outputBuilder); FactorGraph outputFactorGraph = outputBuilder.buildNoBranching(); MaxMarginalSet outputMaxMarginals = marginalCalculator.computeMaxMarginals(outputFactorGraph); Assignment outputConditionalAssignment = outputMaxMarginals.getNthBestAssignment(0); double outputConditionalScore = outputFactorGraph.getUnnormalizedLogProbability( outputConditionalAssignment); // Compute the gradient as a function of the two assignments. incrementSufficientStatistics(inputBuilder, parameterSpec, gradient, currentParameters, costConditionalAssignment, -1.0); incrementSufficientStatistics(outputBuilder, parameterSpec, gradient, currentParameters, outputConditionalAssignment, 1.0); return Math.min(0.0, outputConditionalScore - costConditionalScore); } private static void incrementSufficientStatistics(ParametricBfgBuilder builder, ParameterSpec spec, SufficientStatistics gradient, SufficientStatistics currentParameters, Assignment assignment, double multiplier) { for (MarkedVars mark : builder.getMarkedVars()) { VariableNumMap vars = mark.getVars(); ParametricFactor pf = mark.getFactor(); SufficientStatistics factorGradient = spec.getParametersByIds( mark.getParameterIds(), gradient); SufficientStatistics factorCurrentParameters = spec.getParametersByIds( mark.getParameterIds(), currentParameters); VariableRelabeling relabeling = mark.getVarsToFactorRelabeling(); // Figure out which variables have been conditioned on. Assignment factorAssignment = assignment.intersection(vars.getVariableNumsArray()); Assignment relabeledAssignment = factorAssignment.mapVariables( relabeling.getVariableIndexReplacementMap()); pf.incrementSufficientStatisticsFromAssignment(factorGradient, factorCurrentParameters, relabeledAssignment, multiplier); } } }
bsd-2-clause
petr-panteleyev/money-manager
src/main/java/org/panteleyev/money/app/cells/StatementSumCell.java
999
/* Copyright (c) Petr Panteleyev. All rights reserved. Licensed under the BSD license. See LICENSE file in the project root for full license information. */ package org.panteleyev.money.app.cells; import javafx.geometry.Pos; import javafx.scene.control.TableCell; import org.panteleyev.money.app.Styles; import org.panteleyev.money.statements.StatementRecord; import java.math.BigDecimal; public class StatementSumCell extends TableCell<StatementRecord, StatementRecord> { @Override public void updateItem(StatementRecord item, boolean empty) { super.updateItem(item, empty); setAlignment(Pos.CENTER_RIGHT); getStyleClass().removeAll(Styles.CREDIT, Styles.DEBIT); if (empty || item == null) { setText(""); } else { var amount = item.getAmountDecimal().orElse(BigDecimal.ZERO); getStyleClass().add(amount.signum() < 0 ? Styles.DEBIT : Styles.CREDIT); setText(amount.toString()); } } }
bsd-2-clause
kaaveland/tryagain
src/test/java/com/github/kaaveland/tryagain/impl/ExceptionInTest.java
831
package com.github.kaaveland.tryagain.impl; import com.github.kaaveland.tryagain.api.ExceptionMatcher; import org.junit.Test; import java.io.IOException; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class ExceptionInTest { private final ExceptionMatcher runtimeAndIOException = new ExceptionIn(RuntimeException.class, IOException.class); @Test public void that_exception_in_matches_given_exceptions() { assertThat(runtimeAndIOException.retry(new RuntimeException()), is(true)); assertThat(runtimeAndIOException.retry(new IOException()), is(true)); } @Test public void that_exception_in_matches_exactly_and_not_subclasses() { assertThat(runtimeAndIOException.retry(new IllegalArgumentException()), is(false)); } }
bsd-2-clause
deepinniagafalls/ScrabbleStage3
part2/src/tests/TileSpaceTest.java
1256
package tests; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.ArrayList; import org.junit.Test; import code.TileSpace_047; import code.base.Board_024; import code.base.Inventory_024; import code.base.Scrabble_024_047; import code.base.TileRack_024; import code.client.BoardFrame_047; import code.client.Game_047; import code.client.PlayerFrame_047; public class TileSpaceTest { @Test public void test() { TileSpace_047 ts = new TileSpace_047(0, 0, null, null, 0, 0); } @Test public void isAdjactentTest() throws IOException{ int row=0;int colm1=0; int colm2 =0; Game_047 g = new Game_047("", true , "", "", row, null); Scrabble_024_047 s= new Scrabble_024_047(0, g); Inventory_024 i = new Inventory_024(); Board_024 b = new Board_024(); ArrayList<PlayerFrame_047> pf = new ArrayList<PlayerFrame_047>(); BoardFrame_047 bf = new BoardFrame_047(s, b, i, pf, g, s, null); TileSpace_047 ts = new TileSpace_047(row, colm1, s, bf, 0, 0); b.getTile(row, colm1); b.getTile(row, colm2); boolean expected = true; boolean actual = ts.isAdjacent(); assertTrue("The boolean we want is " + actual, actual == expected); } }
bsd-2-clause
jcodec/jcodec
src/main/java/org/jcodec/containers/mp4/boxes/VideoSampleEntry.java
4234
package org.jcodec.containers.mp4.boxes; import org.jcodec.common.JCodecUtil2; import org.jcodec.common.io.NIOUtils; import org.jcodec.common.model.Size; import java.nio.ByteBuffer; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License * * Describes video payload sample * * @author The JCodec project * */ public class VideoSampleEntry extends SampleEntry { public static VideoSampleEntry videoSampleEntry(String fourcc, Size size, String encoderName) { return createVideoSampleEntry(new Header(fourcc), (short) 0, (short) 0, "jcod", 0, 768, (short) size.getWidth(), (short) size.getHeight(), 72, 72, (short) 1, encoderName != null ? encoderName : "jcodec", (short) 24, (short) 1, (short) -1); } public static VideoSampleEntry createVideoSampleEntry(Header atom, short version, short revision, String vendor, int temporalQual, int spacialQual, short width, short height, long hRes, long vRes, short frameCount, String compressorName, short depth, short drefInd, short clrTbl) { VideoSampleEntry e = new VideoSampleEntry(atom); e.drefInd = drefInd; e.version = version; e.revision = revision; e.vendor = vendor; e.temporalQual = temporalQual; e.spacialQual = spacialQual; e.width = width; e.height = height; e.hRes = hRes; e.vRes = vRes; e.frameCount = frameCount; e.compressorName = compressorName; e.depth = depth; e.clrTbl = clrTbl; return e; } private short version; private short revision; private String vendor; private int temporalQual; private int spacialQual; private short width; private short height; private float hRes; private float vRes; private short frameCount; private String compressorName; private short depth; private short clrTbl; public VideoSampleEntry(Header atom) { super(atom); } public void parse(ByteBuffer input) { super.parse(input); version = input.getShort(); revision = input.getShort(); vendor = NIOUtils.readString(input, 4); temporalQual = input.getInt(); spacialQual = input.getInt(); width = input.getShort(); height = input.getShort(); hRes = (float) input.getInt() / 65536f; vRes = (float) input.getInt() / 65536f; input.getInt(); // Reserved frameCount = input.getShort(); compressorName = NIOUtils.readPascalStringL(input, 31); depth = input.getShort(); clrTbl = input.getShort(); parseExtensions(input); } @Override public void doWrite(ByteBuffer out) { super.doWrite(out); out.putShort(version); out.putShort(revision); out.put(JCodecUtil2.asciiString(vendor), 0, 4); out.putInt(temporalQual); out.putInt(spacialQual); out.putShort((short) width); out.putShort((short) height); out.putInt((int) (hRes * 65536)); out.putInt((int) (vRes * 65536)); out.putInt(0); // data size out.putShort(frameCount); NIOUtils.writePascalStringL(out, compressorName, 31); out.putShort(depth); out.putShort(clrTbl); writeExtensions(out); } public int getWidth() { return width; } public int getHeight() { return height; } public float gethRes() { return hRes; } public float getvRes() { return vRes; } public long getFrameCount() { return frameCount; } public String getCompressorName() { return compressorName; } public long getDepth() { return depth; } public String getVendor() { return vendor; } public short getVersion() { return version; } public short getRevision() { return revision; } public int getTemporalQual() { return temporalQual; } public int getSpacialQual() { return spacialQual; } public short getClrTbl() { return clrTbl; } }
bsd-2-clause
geronimo-iia/ferox
ferox-math/src/main/java/com/ferox/math/ColorRGB.java
22572
/* * Ferox, a graphics and game library in Java * * Copyright (c) 2012, Michael Ludwig * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ferox.math; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; /** * <p/> * ColorRGB is a 3-tuple that stores red, green, and blue color components to represent a color in the * classical RGB scheme. It does not support sRGB, although there is nothing stopping you from storing sRGB * within the color and performing the math manually. * <p/> * Color component values are normally defined in the range from 0 to 1, where 1 represents full saturation of * the component. So (0, 0, 0) is black and (1, 1, 1) would be white. ColorRGB stores color values past 1 so * that high-dynamic range colors can be used. However, ReadOnlyColor3f does not perform any tone-mapping so * (2, 2, 2) and (3, 1, 5) would both be considered as (1, 1, 1) when asking for LDR values. * <p/> * <p/> * It is assumed that systems supporting HDR will use the HDR values and perform tone-mapping manually. The * clamping is provided as a convenience for colors where HDR values are meaningless, such as with materials * (where a value of 1 is the highest physically correct value). * <p/> * It is a common practice to use a {@link Vector4} when an RGBA color is needed, such as in the lower-level * rendering APIs in com.ferox.renderer. * * @author Michael Ludwig */ public final class ColorRGB implements Cloneable { private static final double DEFAULT_FACTOR = 0.7; private static final int RED = 0; private static final int GREEN = 1; private static final int BLUE = 2; private final double[] rgb; private final double[] rgbHDR; /** * Create a new ColorRGB with red, green, and blue values equal to 0. */ public ColorRGB() { rgb = new double[] { 0, 0, 0 }; rgbHDR = new double[] { 0, 0, 0 }; } /** * Create a new ColorRGB that copies the color values from <var>color</var> initially. * * @param color The color to copy * * @throws NullPointerException if color is null * @see #set(ColorRGB) */ public ColorRGB(@Const ColorRGB color) { this(); set(color); } /** * Create a new ColorRGB that uses the given red, green and blue color values initially. * * @param red The red value * @param green The green value * @param blue The blue value * * @see #set(double, double, double) */ public ColorRGB(double red, double green, double blue) { this(); set(red, green, blue); } @Override public ColorRGB clone() { return new ColorRGB(this); } /** * Get the approximate luminance of this color, clamping the component values to non-HDR values. * * @return The luminance */ public double luminance() { return .3 * red() + .59 * green() + .11 * blue(); } /** * Get the approximate luminance of this color, using its HDR component values. * * @return The HDR luminance */ public double luminanceHDR() { return .3 * redHDR() + .59 * greenHDR() + .11 * blueHDR(); } /** * Convenience function to brighten this color. This is equivalent to <code>brighter(this, 1.43);</code> * * @return This color */ public ColorRGB brighter() { return brighter(this, 1.0 / DEFAULT_FACTOR); } /** * Compute a brighter version of <var>color</var>, adjusted by the given brightness <var>factor</var> and * store it in this color. The <var>factor</var> represents the fraction to scale each component by. This * uses the HDR color values, so the brighter color might extend into high dynamic range values (i.e. if * you brightened white). * * @param color The base color being brightened. * @param factor The factor to scale by, must be at least 1 * * @return This color * * @throws IllegalArgumentException if factor is less than 1 * @throws NullPointerException if color is null */ public ColorRGB brighter(@Const ColorRGB color, double factor) { if (factor < 1.0) { throw new IllegalArgumentException("Brightening factor must be at least 1, not: " + factor); } double minBrightness = factor / (255 * factor - 255); double r = color.redHDR(); double g = color.greenHDR(); double b = color.blueHDR(); // if the color is black, then the brighter color must be a gray if (r == 0 && g == 0 && b == 0) { return set(minBrightness, minBrightness, minBrightness); } // check for > 0 here so that non-black colors don't have component creep, // this is so that dark blue brightens into a brighter blue, without adding // any red or green if (r > 0 && r < minBrightness) { r = minBrightness; } if (g > 0 && g < minBrightness) { g = minBrightness; } if (b > 0 && b < minBrightness) { b = minBrightness; } return set(r * factor, g * factor, b * factor); } /** * Convenience function to darken this color. This is equivalent to <code>darker(this, 0.7);</code> * * @return This color */ public ColorRGB darker() { return darker(this, DEFAULT_FACTOR); } /** * Compute a darker version of <var>color</var>. The <var>factor</var> represents the fraction to scale * each component by. This uses the HDR color values, so it might be possible for the darkened color to be * equal in the low dynamic range. * * @param color The color to darken * @param factor The factor to scale by, in the range (0, 1] * * @return This color * * @throws IllegalArgumentException if factor is not in (0, 1] * @throws NullPointerException if color is null */ public ColorRGB darker(@Const ColorRGB color, double factor) { if (factor <= 0.0 || factor > 1.0) { throw new IllegalArgumentException("Darkening factor must be in the range (0, 1], not: " + factor); } return set(Math.max(0, factor * color.redHDR()), Math.max(0, factor * color.greenHDR()), Math.max(0, factor * color.blueHDR())); } /** * Copy the color values from <var>color</var> into this color. * * @param color The color to copy * * @return This color * * @throws NullPointerException if color is null */ public ColorRGB set(@Const ColorRGB color) { return set(color.redHDR(), color.greenHDR(), color.blueHDR()); } /** * Set this color to use the given red, green and blue values. This is equivalent to calling {@link * #red(double)}, {@link #green(double)}, and {@link #blue(double)} with their appropriate values. * * @param red The new red value * @param green The new green value * @param blue The new blue value * * @return This color */ public ColorRGB set(double red, double green, double blue) { return red(red).green(green).blue(blue); } /** * Set the red component value to <var>blue</var>. This value can be greater than 1 and will be unclamped * for {@link #redHDR()}, but will be clamped to below 1 for {@link #red()}. Values below 0 will always be * clamped to 0, regardless of dynamic range. * * @param red The new red color value * * @return This color */ public ColorRGB red(double red) { return setValue(red, RED); } /** * Set the green component value to <var>blue</var>. This value can be greater than 1 and will be * unclamped for {@link #greenHDR()}, but will be clamped to below 1 for {@link #green()}. Values below 0 * will always be clamped to 0, regardless of dynamic range. * * @param green The new green color value * * @return This color */ public ColorRGB green(double green) { return setValue(green, GREEN); } /** * Set the blue component value to <var>blue</var>. This value can be greater than 1 and will be unclamped * for {@link #blueHDR()}, but will be clamped to below 1 for {@link #blue()}. Values below 0 will always * be clamped to 0, regardless of dynamic range. * * @param blue The new blue color value * * @return This color */ public ColorRGB blue(double blue) { return setValue(blue, BLUE); } private ColorRGB setValue(double v, int i) { rgbHDR[i] = Math.max(0, v); rgb[i] = Math.min(rgbHDR[i], 1f); return this; } /** * Set the component at <var>index</var> to the given value. This value can be greater than 1 and will be * returned unclamped the HDR functions, but will be clamped to below 1 for LDR values. Values below 0 * will always be clamped to 0, regardless of dynamic range. * * @param index The component index to set * @param value The color value for the component * * @return This color * * @throws IndexOutOfBoundsException if index isn't 0, 1, or 2 */ public ColorRGB set(int index, double value) { if (index >= 0 && index < 3) { return setValue(value, index); } else { throw new IndexOutOfBoundsException("Illegal index, must be in [0, 2], not: " + index); } } /** * Set this color to the red, green, and blue color values taken from the given array, starting at * <var>offset</var>. The values can be LDR or HDR, just as in {@link #set(double, double, double)}. This * assumes that there are at least three elements left in the array, starting at offset. * * @param values The array to take color values from * @param offset The offset into values to take the first component from * * @return This color * * @throws ArrayIndexOutOfBoundsException if values does not have enough elements to take 3 color values * from */ public ColorRGB set(double[] values, int offset) { return set(values[offset], values[offset + 1], values[offset + 2]); } /** * As {@link #set(double[], int)} but the values are taken from the float[]. * * @param values The array to take color values from * @param offset The offset into values to take the first component from * * @return This color * * @throws ArrayIndexOutOfBoundsException if values does not have enough elements to take 3 color values * from */ public ColorRGB set(float[] values, int offset) { return set(values[offset], values[offset + 1], values[offset + 2]); } /** * As {@link #set(double[], int)} but a DoubleBuffer is used as a source for float values. * * @param values The DoubleBuffer to take color values from * @param offset The offset into values to take the first component * * @return This color * * @throws ArrayIndexOutOfBoundsException if values does not have enough elements to take 3 color values * from */ public ColorRGB set(DoubleBuffer values, int offset) { return set(values.get(offset), values.get(offset + 1), values.get(offset + 2)); } /** * As {@link #set(double[], int)} but a FloatBuffer is used as a source for float values. * * @param values The FloatBuffer to take color values from * @param offset The offset into values to take the first component * * @return This color * * @throws ArrayIndexOutOfBoundsException if values does not have enough elements to take 3 color values * from */ public ColorRGB set(FloatBuffer values, int offset) { return set(values.get(offset), values.get(offset + 1), values.get(offset + 2)); } /** * Return the clamped color value for the red component. This value will be between 0 and 1, where 1 * represents full saturation for the component. This will return 1 if {@link #redHDR()} returns a value * greater than 1. Only clamping is performed to get this to [0, 1], tone-mapping is not performed. * * @return The clamped red value */ public double red() { return rgb[RED]; } /** * Return the clamped color value for the green component. This value will be between 0 and 1, where 1 * represents full saturation for the component. This will return 1 if {@link #greenHDR()} returns a value * greater than 1. Only clamping is performed to get this to [0, 1], tone-mapping is not performed. * * @return The clamped green value */ public double green() { return rgb[GREEN]; } /** * Return the clamped color value for the blue component. This value will be between 0 and 1, where 1 * represents full saturation for the component. This will return 1 if {@link #blueHDR()} returns a value * greater than 1. Only clamping is performed to get this to [0, 1], tone-mapping is not performed. * * @return The clamped blue value */ public double blue() { return rgb[BLUE]; } /** * Return the unclamped color value for the red component. This value will be at least 0 and has no * maximum. Any value higher than 1 represents a high dynamic range value. * * @return The unclamped red */ public double redHDR() { return rgbHDR[RED]; } /** * Return the unclamped color value for the green component. This value will be at least 0 and has no * maximum. Any value higher than 1 represents a high dynamic range value. * * @return The unclamped green */ public double greenHDR() { return rgbHDR[GREEN]; } /** * Return the unclamped color value for the blue component. This value will be at least 0 and has no * maximum. Any value higher than 1 represents a high dynamic range value. * * @return The unclamped blue */ public double blueHDR() { return rgbHDR[BLUE]; } /** * Get the clamped color value for <var>component</var>. Red is 0, green is 1 and blue is 2. The value * will be in [0, 1]. * * @param component The color component to look up * * @return The clamped color for the given component */ public double get(int component) { switch (component) { case 0: return red(); case 1: return green(); case 2: return blue(); default: throw new IndexOutOfBoundsException("Component must be between 0 and 2, not: " + component); } } /** * Get the unclamped color value for <var>component</var>. Red is 0, green is 1 and blue is 2. * * @param component The color component to look up * * @return The unclamped, HDR color for the given component */ public double getHDR(int component) { switch (component) { case 0: return redHDR(); case 1: return greenHDR(); case 2: return blueHDR(); default: throw new IndexOutOfBoundsException("Component must be between 0 and 2, not: " + component); } } /** * Copy the clamped color values of this color into <var>vals</var> starting at <var>offset</var>. It is * assumed that vals has 3 indices starting at offset. The color values will be in [0, 1]. * * @param vals The destination array * @param offset The offset into vals * * @throws ArrayIndexOutOfBoundsException if vals does not have enough space to store the color */ public void get(double[] vals, int offset) { vals[offset] = red(); vals[offset + 1] = green(); vals[offset + 2] = blue(); } /** * As {@link #get(double[], int)} but the values are cast into floats. * * @param vals The destination array * @param offset The offset into vals */ public void get(float[] vals, int offset) { vals[offset] = (float) red(); vals[offset + 1] = (float) green(); vals[offset + 2] = (float) blue(); } /** * As {@link #get(double[], int)}, but with a DoubleBuffer. <var>offset</var> is measured from 0, not the * buffer's position. * * @param store The DoubleBuffer to hold the row values * @param offset The first index to use in the store * * @throws ArrayIndexOutOfBoundsException if store doesn't have enough space for the color */ public void get(DoubleBuffer store, int offset) { store.put(offset, red()); store.put(offset + 1, green()); store.put(offset + 2, blue()); } /** * As {@link #getHDR(double[], int)}, but with a DoubleBuffer. <var>offset</var> is measured from 0, not * the buffer's position. * * @param store The DoubleBuffer to hold the row values * @param offset The first index to use in the store * * @throws ArrayIndexOutOfBoundsException if store doesn't have enough space for the color */ public void getHDR(DoubleBuffer store, int offset) { store.put(offset, redHDR()); store.put(offset + 1, greenHDR()); store.put(offset + 2, blueHDR()); } /** * As {@link #get(double[], int)}, but with a FloatBuffer. <var>offset</var> is measured from 0, not the * buffer's position. * * @param store The FloatBuffer to hold the row values * @param offset The first index to use in the store * * @throws ArrayIndexOutOfBoundsException if store doesn't have enough space for the color */ public void get(FloatBuffer store, int offset) { store.put(offset, (float) red()); store.put(offset + 1, (float) green()); store.put(offset + 2, (float) blue()); } /** * As {@link #getHDR(double[], int)}, but with a FloatBuffer. <var>offset</var> is measured from 0, not * the buffer's position. * * @param store The FloatBuffer to hold the row values * @param offset The first index to use in the store * * @throws ArrayIndexOutOfBoundsException if store doesn't have enough space for the color */ public void getHDR(FloatBuffer store, int offset) { store.put(offset, (float) redHDR()); store.put(offset + 1, (float) greenHDR()); store.put(offset + 2, (float) blueHDR()); } /** * Copy the HDR color values of this color into <var>vals</var> starting at <var>offset</var>. It is * assumed that vals has 3 indices starting at offset. * * @param vals The destination array * @param offset The offset into vals * * @throws ArrayIndexOutOfBoundsException if vals does not have enough space to store the color */ public void getHDR(double[] vals, int offset) { vals[offset] = redHDR(); vals[offset + 1] = greenHDR(); vals[offset + 2] = blueHDR(); } /** * As {@link #getHDR(double[], int)} except the values are cast to floats to store in the array. * * @param vals The destination array * @param offset THe offset into vals */ public void getHDR(float[] vals, int offset) { vals[offset] = (float) redHDR(); vals[offset + 1] = (float) greenHDR(); vals[offset + 2] = (float) blueHDR(); } /** * Determine if the two colors are equal. If <var>asHDR</var> is true, the HDR color values are compared. * If it is false, the color values are first clamped to [0, 1] and then compared. * * @param color The other color to compare to * @param asHDR True if HDR color ranges are used * * @return True if they are equal */ public boolean equals(@Const ColorRGB color, boolean asHDR) { if (color == null) { return false; } if (asHDR) { return Double.compare(redHDR(), color.redHDR()) == 0 && Double.compare(greenHDR(), color.greenHDR()) == 0 && Double.compare(blueHDR(), color.blueHDR()) == 0; } else { return Double.compare(red(), color.red()) == 0 && Double.compare(green(), color.green()) == 0 && Double.compare(blue(), color.blue()) == 0; } } @Override public boolean equals(Object o) { return o instanceof ColorRGB && equals((ColorRGB) o, true); } @Override public int hashCode() { long result = 17; result += 31 * result + Double.doubleToLongBits(redHDR()); result += 31 * result + Double.doubleToLongBits(greenHDR()); result += 31 * result + Double.doubleToLongBits(blueHDR()); return (int) (((result & 0xffffffff00000000L) >> 32) ^ (result & 0x00000000ffffffffL)); } }
bsd-2-clause
milot-mirdita/GeMuDB
Vendor/NCBI eutils/src/gov/nih/nlm/ncbi/www/soap/eutils/efetch_gene/DenseSeg_starts_type0.java
24974
/** * DenseSeg_starts_type0.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.6.2 Built on : Apr 17, 2012 (05:34:40 IST) */ package gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene; /** * DenseSeg_starts_type0 bean class */ @SuppressWarnings({"unchecked","unused"}) public class DenseSeg_starts_type0 implements org.apache.axis2.databinding.ADBBean{ /* This type was generated from the piece of schema that had name = Dense-seg_starts_type0 Namespace URI = http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene Namespace Prefix = ns1 */ /** * field for DenseSeg_startsSequence * This was an Array! */ protected gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.DenseSeg_startsSequence[] localDenseSeg_startsSequence ; /* This tracker boolean wil be used to detect whether the user called the set method * for this attribute. It will be used to determine whether to include this field * in the serialized XML */ protected boolean localDenseSeg_startsSequenceTracker = false ; public boolean isDenseSeg_startsSequenceSpecified(){ return localDenseSeg_startsSequenceTracker; } /** * Auto generated getter method * @return gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.DenseSeg_startsSequence[] */ public gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.DenseSeg_startsSequence[] getDenseSeg_startsSequence(){ return localDenseSeg_startsSequence; } /** * validate the array for DenseSeg_startsSequence */ protected void validateDenseSeg_startsSequence(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.DenseSeg_startsSequence[] param){ } /** * Auto generated setter method * @param param DenseSeg_startsSequence */ public void setDenseSeg_startsSequence(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.DenseSeg_startsSequence[] param){ validateDenseSeg_startsSequence(param); localDenseSeg_startsSequenceTracker = param != null; this.localDenseSeg_startsSequence=param; } /** * Auto generated add method for the array for convenience * @param param gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.DenseSeg_startsSequence */ public void addDenseSeg_startsSequence(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.DenseSeg_startsSequence param){ if (localDenseSeg_startsSequence == null){ localDenseSeg_startsSequence = new gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.DenseSeg_startsSequence[]{}; } //update the setting tracker localDenseSeg_startsSequenceTracker = true; java.util.List list = org.apache.axis2.databinding.utils.ConverterUtil.toList(localDenseSeg_startsSequence); list.add(param); this.localDenseSeg_startsSequence = (gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.DenseSeg_startsSequence[])list.toArray( new gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.DenseSeg_startsSequence[list.size()]); } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,parentQName); return factory.createOMElement(dataSource,parentQName); } public void serialize(final javax.xml.namespace.QName parentQName, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, javax.xml.stream.XMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter); if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":Dense-seg_starts_type0", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "Dense-seg_starts_type0", xmlWriter); } } if (localDenseSeg_startsSequenceTracker){ if (localDenseSeg_startsSequence!=null){ for (int i = 0;i < localDenseSeg_startsSequence.length;i++){ if (localDenseSeg_startsSequence[i] != null){ localDenseSeg_startsSequence[i].serialize(null,xmlWriter); } else { // we don't have to do any thing since minOccures is zero } } } else { throw new org.apache.axis2.databinding.ADBException("Dense-seg_startsSequence cannot be null!!"); } } xmlWriter.writeEndElement(); } private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * Utility method to write an element start tag. */ private void writeStartElement(java.lang.String prefix, java.lang.String namespace, java.lang.String localPart, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, localPart); } else { if (namespace.length() == 0) { prefix = ""; } else if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, localPart, namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext(); while (true) { java.lang.String uri = nsContext.getNamespaceURI(prefix); if (uri == null || uri.length() == 0) { break; } prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); if (localDenseSeg_startsSequenceTracker){ if (localDenseSeg_startsSequence!=null) { for (int i = 0;i < localDenseSeg_startsSequence.length;i++){ if (localDenseSeg_startsSequence[i] != null){ elementList.add(new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene", "Dense-seg_startsSequence")); elementList.add(localDenseSeg_startsSequence[i]); } else { // nothing to do } } } else { throw new org.apache.axis2.databinding.ADBException("Dense-seg_startsSequence cannot be null!!"); } } return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static DenseSeg_starts_type0 parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ DenseSeg_starts_type0 object = new DenseSeg_starts_type0(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){ java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName!=null){ java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1){ nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":")); } nsPrefix = nsPrefix==null?"":nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1); if (!"Dense-seg_starts_type0".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (DenseSeg_starts_type0)gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.ExtensionMapper.getTypeObject( nsUri,type,reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); reader.next(); java.util.ArrayList list1 = new java.util.ArrayList(); while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); try{ if (reader.isStartElement() ){ // Process the array and step past its final element's end. list1.add(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.DenseSeg_startsSequence.Factory.parse(reader)); //loop until we find a start element that is not part of this array boolean loopDone1 = false; while(!loopDone1){ // Step to next element event. while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isEndElement()){ //two continuous end elements means we are exiting the xml structure loopDone1 = true; } else { list1.add(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.DenseSeg_startsSequence.Factory.parse(reader)); } } // call the converter utility to convert and set the array object.setDenseSeg_startsSequence((gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.DenseSeg_startsSequence[]) org.apache.axis2.databinding.utils.ConverterUtil.convertToArray( gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.DenseSeg_startsSequence.class, list1)); } // End of if for expected property start element else { } } catch (java.lang.Exception e) {} while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement()) // A start element we are not expecting indicates a trailing invalid property throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName()); } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
bsd-2-clause
alameluchidambaram/CONNECT
Product/Production/Services/PatientDiscoveryCore/src/main/java/gov/hhs/fha/nhinc/patientdiscovery/nhin/deferred/response/proxy/service/RespondingGatewayDeferredResponseServicePortDescriptor.java
7375
/** * The software subject to this notice and license includes both human readable * source code form and machine readable, binary, object code form. The CONNECT_git * Software was developed in conjunction with the National Cancer Institute * (NCI) by NCI employees and 5AM Solutions, Inc. (5AM). To the extent * government employees are authors, any rights in such works shall be subject * to Title 17 of the United States Code, section 105. * * This CONNECT_git Software License (the License) is between NCI and You. You (or * Your) shall mean a person or an entity, and all other entities that control, * are controlled by, or are under common control with the entity. Control for * purposes of this definition means (i) the direct or indirect power to cause * the direction or management of such entity, whether by contract or otherwise, * or (ii) ownership of fifty percent (50%) or more of the outstanding shares, * or (iii) beneficial ownership of such entity. * * This License is granted provided that You agree to the conditions described * below. NCI grants You a non-exclusive, worldwide, perpetual, fully-paid-up, * no-charge, irrevocable, transferable and royalty-free right and license in * its rights in the CONNECT_git Software to (i) use, install, access, operate, * execute, copy, modify, translate, market, publicly display, publicly perform, * and prepare derivative works of the CONNECT_git Software; (ii) distribute and * have distributed to and by third parties the CONNECT_git Software and any * modifications and derivative works thereof; and (iii) sublicense the * foregoing rights set out in (i) and (ii) to third parties, including the * right to license such rights to further third parties. For sake of clarity, * and not by way of limitation, NCI shall have no right of accounting or right * of payment from You or Your sub-licensees for the rights granted under this * License. This License is granted at no charge to You. * * Your redistributions of the source code for the Software must retain the * above copyright notice, this list of conditions and the disclaimer and * limitation of liability of Article 6, below. Your redistributions in object * code form must reproduce the above copyright notice, this list of conditions * and the disclaimer of Article 6 in the documentation and/or other materials * provided with the distribution, if any. * * Your end-user documentation included with the redistribution, if any, must * include the following acknowledgment: This product includes software * developed by 5AM and the National Cancer Institute. If You do not include * such end-user documentation, You shall include this acknowledgment in the * Software itself, wherever such third-party acknowledgments normally appear. * * You may not use the names "The National Cancer Institute", "NCI", or "5AM" * to endorse or promote products derived from this Software. This License does * not authorize You to use any trademarks, service marks, trade names, logos or * product names of either NCI or 5AM, except as required to comply with the * terms of this License. * * For sake of clarity, and not by way of limitation, You may incorporate this * Software into Your proprietary programs and into any third party proprietary * programs. However, if You incorporate the Software into third party * proprietary programs, You agree that You are solely responsible for obtaining * any permission from such third parties required to incorporate the Software * into such third party proprietary programs and for informing Your * sub-licensees, including without limitation Your end-users, of their * obligation to secure any required permissions from such third parties before * incorporating the Software into such third party proprietary software * programs. In the event that You fail to obtain such permissions, You agree * to indemnify NCI for any claims against NCI by such third parties, except to * the extent prohibited by law, resulting from Your failure to obtain such * permissions. * * For sake of clarity, and not by way of limitation, You may add Your own * copyright statement to Your modifications and to the derivative works, and * You may provide additional or different license terms and conditions in Your * sublicenses of modifications of the Software, or any derivative works of the * Software as a whole, provided Your use, reproduction, and distribution of the * Work otherwise complies with the conditions stated in this License. * * THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, * (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO * EVENT SHALL THE NATIONAL CANCER INSTITUTE, 5AM SOLUTIONS, INC. OR THEIR * AFFILIATES 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 gov.hhs.fha.nhinc.patientdiscovery.nhin.deferred.response.proxy.service; import gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor; import ihe.iti.xcpd._2009.RespondingGatewayDeferredResponsePortType; /** * @author dharley * */ public class RespondingGatewayDeferredResponseServicePortDescriptor implements ServicePortDescriptor<RespondingGatewayDeferredResponsePortType> { /* * (non-Javadoc) * * @see gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor#getNamespaceUri() */ @Override public String getNamespaceUri() { return "urn:ihe:iti:xcpd:2009"; } /* * (non-Javadoc) * * @see gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor#getServiceLocalPart() */ @Override public String getServiceLocalPart() { return "RespondingGatewayDeferredResp_Service"; } /* * (non-Javadoc) * * @see gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor#getPortLocalPart() */ @Override public String getPortLocalPart() { return "RespondingGatewayDeferredResponse_Port"; } /* * (non-Javadoc) * * @see gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor#getWSDLFileName() */ @Override public String getWSDLFileName() { return "NhinPatientDiscoveryDeferredResponse.wsdl"; } /* * (non-Javadoc) * * @see gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor#getWSAddressingAction() */ @Override public String getWSAddressingAction() { return "urn:hl7-org:v3:PRPA_IN201306UV02:Deferred:CrossGatewayPatientDiscovery"; } /* * (non-Javadoc) * * @see gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor#getPortClass() */ @Override public Class<RespondingGatewayDeferredResponsePortType> getPortClass() { return RespondingGatewayDeferredResponsePortType.class; } }
bsd-3-clause
NCIP/caarray
software/grid/v1_0/src/gov/nih/nci/caarray/services/external/v1_0/grid/service/CaArraySvc_v1_0Configuration.java
2395
//====================================================================================== // Copyright 5AM Solutions Inc, Yale University // // Distributed under the OSI-approved BSD 3-Clause License. // See http://ncip.github.com/caarray/LICENSE.txt for details. //====================================================================================== package gov.nih.nci.caarray.services.external.v1_0.grid.service; import gov.nih.nci.cagrid.introduce.servicetools.ServiceConfiguration; import org.globus.wsrf.config.ContainerConfig; import java.io.File; import javax.naming.InitialContext; import org.apache.axis.MessageContext; import org.globus.wsrf.Constants; /** * DO NOT EDIT: This class is autogenerated! * * This class holds all service properties which were defined for the service to have * access to. * * @created by Introduce Toolkit version 1.5 * */ public class CaArraySvc_v1_0Configuration implements ServiceConfiguration { public static CaArraySvc_v1_0Configuration configuration = null; public String etcDirectoryPath; public static CaArraySvc_v1_0Configuration getConfiguration() throws Exception { if (CaArraySvc_v1_0Configuration.configuration != null) { return CaArraySvc_v1_0Configuration.configuration; } MessageContext ctx = MessageContext.getCurrentContext(); String servicePath = ctx.getTargetService(); String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/serviceconfiguration"; try { javax.naming.Context initialContext = new InitialContext(); CaArraySvc_v1_0Configuration.configuration = (CaArraySvc_v1_0Configuration) initialContext.lookup(jndiName); } catch (Exception e) { throw new Exception("Unable to instantiate service configuration.", e); } return CaArraySvc_v1_0Configuration.configuration; } private String caGridWsEnumeration_iterImplType; public String getEtcDirectoryPath() { return ContainerConfig.getBaseDirectory() + File.separator + etcDirectoryPath; } public void setEtcDirectoryPath(String etcDirectoryPath) { this.etcDirectoryPath = etcDirectoryPath; } public String getCaGridWsEnumeration_iterImplType() { return caGridWsEnumeration_iterImplType; } public void setCaGridWsEnumeration_iterImplType(String caGridWsEnumeration_iterImplType) { this.caGridWsEnumeration_iterImplType = caGridWsEnumeration_iterImplType; } }
bsd-3-clause
FauxFaux/dmnp
doccrap/src/main/java/com/goeswhere/dmnp/doccrap/DocCrap.java
6175
package com.goeswhere.dmnp.doccrap; import com.goeswhere.dmnp.util.ASTContainers; import com.goeswhere.dmnp.util.ASTWrapper; import com.goeswhere.dmnp.util.FileUtils; import com.goeswhere.dmnp.util.TerribleImplementation; import org.eclipse.jdt.core.dom.*; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.TextEdit; import java.io.*; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; class DocCrap { static String cleanCU(final String cus) { final CompilationUnit cu = ASTWrapper.compile(cus); cu.recordModifications(); final Document doc = new Document(cus); cu.accept(new ASTVisitor() { @Override public boolean visit(final MethodDeclaration meth) { final Javadoc javadoc = meth.getJavadoc(); if (null == javadoc) return super.visit(meth); final List<TagElement> tags = ASTContainers.tags(javadoc); final Map<String, String> args = methodArgs(meth); for (final Iterator<TagElement> it = tags.iterator(); it.hasNext(); ) { final TagElement te = it.next(); final String tagName = te.getTagName(); final List<ASTNode> frags = ASTContainers.fragments(te); if ("@param".equals(tagName)) { // param with no name?! if (frags.isEmpty()) { continue; } // name that's no name final ASTNode nameNode = frags.get(0); if (!(nameNode instanceof SimpleName)) continue; // arg doesn't even exist final String ident = ((SimpleName) nameNode).getIdentifier(); if (!args.containsKey(ident)) { it.remove(); continue; } // contains only the name if (1 == frags.size()) { it.remove(); continue; } final ASTNode a = frags.get(1); if (a instanceof TextElement) { final String text = ((TextElement) a).getText().trim(); if ("".equals(text) || "-".equals(text) || (args.get(ident) + " -").equals(text)) { it.remove(); continue; } } } else if ("@return".equals(tagName)) { if (frags.isEmpty()) it.remove(); else if (1 == frags.size()) { ASTNode a = frags.get(0); if (a instanceof TextElement) { final String text = ((TextElement) a).getText(); final String methodAbout = meth.getName().getIdentifier().replaceFirst("get|is", ""); final String regex = "(?i)\\s*(?:returns? )?(?:the )?(?:value of )?" + Pattern.quote(methodAbout) + "\\.?"; final String trimmed = text.trim(); final String rettype = stringize(meth.getReturnType2()); if ("".equals(trimmed) || "-".equals(trimmed) || (rettype + " -").equals(trimmed) || trimmed.equals(rettype) || text.matches(regex)) it.remove(); } } } } if (tags.isEmpty()) javadoc.delete(); else if (1 == tags.size()) { if ("@".equals(tags.get(0).getTagName())) javadoc.delete(); } return super.visit(meth); } }); try { cu.rewrite(doc, null).apply(doc, TextEdit.UPDATE_REGIONS); } catch (MalformedTreeException | BadLocationException e) { throw new RuntimeException(e); } return doc.get(); } private static Map<String, String> methodArgs(MethodDeclaration node) { Map<String, String> args = new HashMap<>(); for (SingleVariableDeclaration a : ASTContainers.parameters(node)) args.put(a.getName().getIdentifier(), stringize(a.getType())); return args; } @TerribleImplementation private static String stringize(Type t) { return String.valueOf(t); } public static void main(String[] args) throws IOException { long start = System.nanoTime(); for (String s : args) processDir(new File(s)); System.out.println((System.nanoTime() - start) / 1e9); } private static void processDir(File file) throws IOException { for (File child : file.listFiles()) if (!child.getName().equals(".") && !child.getName().equals("..")) if (child.isDirectory()) processDir(child); else if (child.getName().endsWith(".java")) processFile(child); } private static void processFile(File child) throws IOException { final String res = cleanCU(FileUtils.consumeFile(new FileReader(child))); FileWriter fw = new FileWriter(child); try { fw.write(res); } finally { fw.flush(); fw.close(); } } }
bsd-3-clause
fraunhoferfokus/govapps
data-portlet/src/main/java/de/fraunhofer/fokus/movepla/model/RelatedApplicationsClp.java
11561
package de.fraunhofer.fokus.movepla.model; /* * #%L * govapps_data * $Id: RelatedApplicationsClp.java 566 2014-11-13 15:22:01Z sma $ * %% * Copyright (C) 2013 - 2014 Fraunhofer FOKUS / CC ÖFIT * %% * Copyright (c) 2,013, Fraunhofer FOKUS, Kompetenzzentrum Oeffentliche IT * 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) All advertising materials mentioning features or use of this software must * display the following acknowledgement: * This product includes software developed by Fraunhofer FOKUS, Kompetenzzentrum Oeffentliche IT. * * 4) Neither the name of the organization nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDER ''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 * Fraunhofer FOKUS, Kompetenzzentrum Oeffentliche IT * 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. * #L% */ import com.liferay.portal.kernel.bean.AutoEscapeBeanHandler; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.model.BaseModel; import com.liferay.portal.model.impl.BaseModelImpl; import com.liferay.portal.util.PortalUtil; import de.fraunhofer.fokus.movepla.service.RelatedApplicationsLocalServiceUtil; import java.io.Serializable; import java.lang.reflect.Proxy; import java.util.Date; import java.util.HashMap; import java.util.Map; public class RelatedApplicationsClp extends BaseModelImpl<RelatedApplications> implements RelatedApplications { private long _RelatedApplicationsID; private long _companyId; private long _userId; private String _userUuid; private Date _createDate; private Date _modifiedDate; private long _applicationId; private long _applicationId2; private BaseModel<?> _relatedApplicationsRemoteModel; public RelatedApplicationsClp() { } public Class<?> getModelClass() { return RelatedApplications.class; } public String getModelClassName() { return RelatedApplications.class.getName(); } public long getPrimaryKey() { return _RelatedApplicationsID; } public void setPrimaryKey(long primaryKey) { setRelatedApplicationsID(primaryKey); } public Serializable getPrimaryKeyObj() { return new Long(_RelatedApplicationsID); } public void setPrimaryKeyObj(Serializable primaryKeyObj) { setPrimaryKey(((Long) primaryKeyObj).longValue()); } @Override public Map<String, Object> getModelAttributes() { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("RelatedApplicationsID", getRelatedApplicationsID()); attributes.put("companyId", getCompanyId()); attributes.put("userId", getUserId()); attributes.put("createDate", getCreateDate()); attributes.put("modifiedDate", getModifiedDate()); attributes.put("applicationId", getApplicationId()); attributes.put("applicationId2", getApplicationId2()); return attributes; } @Override public void setModelAttributes(Map<String, Object> attributes) { Long RelatedApplicationsID = (Long) attributes.get( "RelatedApplicationsID"); if (RelatedApplicationsID != null) { setRelatedApplicationsID(RelatedApplicationsID); } Long companyId = (Long) attributes.get("companyId"); if (companyId != null) { setCompanyId(companyId); } Long userId = (Long) attributes.get("userId"); if (userId != null) { setUserId(userId); } Date createDate = (Date) attributes.get("createDate"); if (createDate != null) { setCreateDate(createDate); } Date modifiedDate = (Date) attributes.get("modifiedDate"); if (modifiedDate != null) { setModifiedDate(modifiedDate); } Long applicationId = (Long) attributes.get("applicationId"); if (applicationId != null) { setApplicationId(applicationId); } Long applicationId2 = (Long) attributes.get("applicationId2"); if (applicationId2 != null) { setApplicationId2(applicationId2); } } public long getRelatedApplicationsID() { return _RelatedApplicationsID; } public void setRelatedApplicationsID(long RelatedApplicationsID) { _RelatedApplicationsID = RelatedApplicationsID; } public long getCompanyId() { return _companyId; } public void setCompanyId(long companyId) { _companyId = companyId; } public long getUserId() { return _userId; } public void setUserId(long userId) { _userId = userId; } public String getUserUuid() throws SystemException { return PortalUtil.getUserValue(getUserId(), "uuid", _userUuid); } public void setUserUuid(String userUuid) { _userUuid = userUuid; } public Date getCreateDate() { return _createDate; } public void setCreateDate(Date createDate) { _createDate = createDate; } public Date getModifiedDate() { return _modifiedDate; } public void setModifiedDate(Date modifiedDate) { _modifiedDate = modifiedDate; } public long getApplicationId() { return _applicationId; } public void setApplicationId(long applicationId) { _applicationId = applicationId; } public long getApplicationId2() { return _applicationId2; } public void setApplicationId2(long applicationId2) { _applicationId2 = applicationId2; } public BaseModel<?> getRelatedApplicationsRemoteModel() { return _relatedApplicationsRemoteModel; } public void setRelatedApplicationsRemoteModel( BaseModel<?> relatedApplicationsRemoteModel) { _relatedApplicationsRemoteModel = relatedApplicationsRemoteModel; } public void persist() throws SystemException { if (this.isNew()) { RelatedApplicationsLocalServiceUtil.addRelatedApplications(this); } else { RelatedApplicationsLocalServiceUtil.updateRelatedApplications(this); } } @Override public RelatedApplications toEscapedModel() { return (RelatedApplications) Proxy.newProxyInstance(RelatedApplications.class.getClassLoader(), new Class[] { RelatedApplications.class }, new AutoEscapeBeanHandler(this)); } @Override public Object clone() { RelatedApplicationsClp clone = new RelatedApplicationsClp(); clone.setRelatedApplicationsID(getRelatedApplicationsID()); clone.setCompanyId(getCompanyId()); clone.setUserId(getUserId()); clone.setCreateDate(getCreateDate()); clone.setModifiedDate(getModifiedDate()); clone.setApplicationId(getApplicationId()); clone.setApplicationId2(getApplicationId2()); return clone; } public int compareTo(RelatedApplications relatedApplications) { long primaryKey = relatedApplications.getPrimaryKey(); if (getPrimaryKey() < primaryKey) { return -1; } else if (getPrimaryKey() > primaryKey) { return 1; } else { return 0; } } @Override public boolean equals(Object obj) { if (obj == null) { return false; } RelatedApplicationsClp relatedApplications = null; try { relatedApplications = (RelatedApplicationsClp) obj; } catch (ClassCastException cce) { return false; } long primaryKey = relatedApplications.getPrimaryKey(); if (getPrimaryKey() == primaryKey) { return true; } else { return false; } } @Override public int hashCode() { return (int) getPrimaryKey(); } @Override public String toString() { StringBundler sb = new StringBundler(15); sb.append("{RelatedApplicationsID="); sb.append(getRelatedApplicationsID()); sb.append(", companyId="); sb.append(getCompanyId()); sb.append(", userId="); sb.append(getUserId()); sb.append(", createDate="); sb.append(getCreateDate()); sb.append(", modifiedDate="); sb.append(getModifiedDate()); sb.append(", applicationId="); sb.append(getApplicationId()); sb.append(", applicationId2="); sb.append(getApplicationId2()); sb.append("}"); return sb.toString(); } public String toXmlString() { StringBundler sb = new StringBundler(25); sb.append("<model><model-name>"); sb.append("de.fraunhofer.fokus.movepla.model.RelatedApplications"); sb.append("</model-name>"); sb.append( "<column><column-name>RelatedApplicationsID</column-name><column-value><![CDATA["); sb.append(getRelatedApplicationsID()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>companyId</column-name><column-value><![CDATA["); sb.append(getCompanyId()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>userId</column-name><column-value><![CDATA["); sb.append(getUserId()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>createDate</column-name><column-value><![CDATA["); sb.append(getCreateDate()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>modifiedDate</column-name><column-value><![CDATA["); sb.append(getModifiedDate()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>applicationId</column-name><column-value><![CDATA["); sb.append(getApplicationId()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>applicationId2</column-name><column-value><![CDATA["); sb.append(getApplicationId2()); sb.append("]]></column-value></column>"); sb.append("</model>"); return sb.toString(); } }
bsd-3-clause
NCIP/cagrid
cagrid/Software/core/caGrid/projects/sdkQuery41/src/java/style/org/cagrid/data/sdkquery41/style/wizard/SDK41InitializationPanel.java
1745
package org.cagrid.data.sdkquery41.style.wizard; import gov.nih.nci.cagrid.data.style.sdkstyle.wizard.CoreDsIntroPanel; import gov.nih.nci.cagrid.introduce.beans.extension.ServiceExtensionDescriptionType; import gov.nih.nci.cagrid.introduce.common.ServiceInformation; import java.io.File; import org.cagrid.data.sdkquery41.style.common.SDK41StyleConstants; import org.cagrid.data.sdkquery41.style.wizard.config.SDK41InitialConfigurationStep; import org.cagrid.grape.utils.CompositeErrorDialog; /** * SDK41InitializationPanel * First wizard panel to create a caGrid data service * backed by caCORE SDK 4.1 * * @author David */ public class SDK41InitializationPanel extends CoreDsIntroPanel { private SDK41InitialConfigurationStep configuration = null; public SDK41InitializationPanel(ServiceExtensionDescriptionType extensionDescription, ServiceInformation info) { super(extensionDescription, info); configuration = new SDK41InitialConfigurationStep(info); } protected void setLibrariesAndProcessor() { // set the query processors and style lib dir on the configuration // this.configuration.setCql1ProcessorClassName(SDK41QueryProcessor.class.getName()); // this.configuration.setCql2ProcessorClassName(SDK41CQL2QueryProcessor.class.getName()); File styleLibDir = new File(SDK41StyleConstants.STYLE_DIR, "lib"); this.configuration.setStyleLibDirectory(styleLibDir); } public void movingNext() { try { configuration.applyConfiguration(); } catch (Exception ex) { ex.printStackTrace(); CompositeErrorDialog.showErrorDialog("Error applying configuration", ex.getMessage(), ex); } } }
bsd-3-clause
shingoOKAWA/trie-dictionary-java
src/main/java/org/okawa/util/nlang/trie/impl/DoubleArrayBuilder.java
6104
package org.okawa.util.nlang.trie.impl; import java.util.ArrayList; import java.util.List; import org.okawa.util.nlang.trie.Trie; import org.okawa.util.nlang.trie.TrieBuilder; /** * Double-Arrayビルダー */ public final class DoubleArrayBuilder implements TrieBuilder { /** キーワード一覧 */ private final List<StringStream> keys; /** BASE配列 */ private final DynamicArrayList<Integer> base = new DynamicArrayList<Integer>(); /** CHECK配列 */ private final DynamicArrayList<Character> check = new DynamicArrayList<Character>(); /** TAIL配列 接尾辞開始位置配列 */ private final ArrayList<Integer> begins = new ArrayList<Integer>(); /** TAIL配列 接尾辞長 */ private final ArrayList<Integer> lengths = new ArrayList<Integer>(); /** TAIL配列 */ private final StringBuilder tail = new StringBuilder(); /** * キーワード一覧からビルダーをインスタンス化 * * @param keys キーワード一覧 * @param sorted trueの場合はソートされたキーワードを使用するものとして処理 */ private DoubleArrayBuilder(List<? extends Trie.Entry> keys, boolean sorted) { this.keys = new ArrayList<StringStream>(keys.size()); // ソート & ユニーク // 本来であればRaddixSort使用したい if (!sorted) { java.util.Collections.sort(keys); } String prev = null; String keyString = null; for (Trie.Entry key : keys) { keyString = key.getKey(); if (!keyString.equals(prev)) { this.keys.add(new StringStream(prev = keyString)); } } } /** * ビルダーからTrieをインスタンス化 * * @param keys キーワード一覧 * @param sorted trueの場合はソートされたキーワードを使用するものとして処理 */ public static DoubleArray build(List<? extends Trie.Entry> keys, boolean sorted, Callback func) { DoubleArrayBuilder builder = new DoubleArrayBuilder(keys, sorted); // 0 : begin // builder.keys.size() : end // 0 : rootIndex builder.build(new DoubleArrayAllocator(), 0, builder.keys.size(), 0, func); return new DoubleArray(builder); } /** * 構築実処理 * * @param allocator 使用する仮想メモリアロケータ * @param begin 使用キーワード開始インデックス * @param end 使用キーワード終了インデックス * @param 根ノードに割り振られた番地 */ private void build(DoubleArrayAllocator allocator, int begin, int end, int rootIndex, Callback func) { // 残るは接尾辞のみ // endとbeginの差が1の場合は共通の接頭辞を持つキーが存在しない、すなわちTAIL配列に格納 if (end - begin == 1) { this.insertTail(keys.get(begin), rootIndex, func); return; } // 各接頭文字に対する終了位置 final List<Integer> ends = new ArrayList<Integer>(); // 文字コードリスト final List<Character> codes = new ArrayList<Character>(); // 前回処理した文字コード char prev = Constants.DACheck.EMPTY_CODE; // 根ノードから伸びるエッジ(文字)を収集 for (int i = begin; i < end; i++) { char curr = keys.get(i).read(); if (prev != curr) { codes.add(prev = curr); ends.add(i); } } ends.add(end); // 根ノードから派生するノードに対して再帰的に構築 final int xNode = allocator.xCheck(codes); for (int i = 0; i< codes.size(); i++) { this.build(allocator, ends.get(i), ends.get(i + 1), this.setNode(codes.get(i), rootIndex, xNode), func); } } /** * ノードをセット * * @param code 文字コード * @param parentIndex 親ノードインデックス * @param xNode xCheckで付与される番地 * @return 新たに付与されたノード番地 */ private int setNode(char code, int parentIndex, int xNode) { // アサインされた文字コードに対応した子ノード final int childNode = xNode + code; // 親ノードにはxCheckで付与される番地を振る this.base.set(parentIndex, xNode, Constants.DABase.INIT_VALUE); // 子ノードとの接続情報をセット this.check.set(childNode, code, Constants.DACheck.EMPTY_CODE); // 子ノードを返り値とする return childNode; } /** * TAIL配列に接尾辞を格納 * * @param key 格納する接尾辞を持つキーワード * @param nodeIndex 付随するノードインデックス * @param func キー登録時のコールバック関数 */ private void insertTail(StringStream key, int nodeIndex, Callback func) { String suffix = key.rest(-1); // 0-startのインデックスなので、以下のようなIDの割り振りはAllocationに相当することに注意 int id = Constants.DABase.ID(this.begins.size()); // 処理時のBASE配列のサイズをIDとして使用 this.base.set(nodeIndex, id, Constants.DABase.INIT_VALUE); // TAILオフセット (開始位置) this.begins.add(this.tail.length()); // TAILオフセット (終了位置) this.lengths.add(suffix.length()); // TAIL配列 this.tail.append(suffix); // コールバック関数実行 func.apply(Constants.DABase.ID(id)); } /** DoubleArray構築時に使用 */ public int getKeySetSize() { return this.keys.size(); } /** DoubleArray構築時に使用 */ public DynamicArrayList<Integer> getBase() { return this.base; } /** DoubleArray構築時に使用 */ public DynamicArrayList<Character> getCheck() { return this.check; } /** DoubleArray構築時に使用 */ public List<Integer> getBegins() { return this.begins; } /** DoubleArray構築時に使用 */ public List<Integer> getLengths() { return this.lengths; } /** DoubleArray構築時に使用 */ public StringBuilder getTail() { return this.tail; } }
bsd-3-clause
cs-au-dk/JWIG
examples/src/guessinggame/GameState.java
1578
package guessinggame; import dk.brics.jwig.persistence.AbstractPersistable; import dk.brics.jwig.persistence.HibernateQuerier; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Transaction; public class GameState extends AbstractPersistable { private int plays = 0; private String holder = null; private int record = Integer.MAX_VALUE; int getRecord() { return record; } int getPlays() { return plays; } String getHolder() { return holder; } private void changed() { save(); } void incrementPlays() { plays++; changed(); } synchronized void setRecord(int guesses, String name) { if ((guesses < getRecord())) { setHolder(name); setRecord(guesses); changed(); } } public static GameState load() { org.hibernate.classic.Session session = HibernateQuerier.getFactory().getCurrentSession(); Criteria c = session.createCriteria(GameState.class); List<?> list = c.list(); GameState game = null; if ((list.size() > 0)) game = (GameState) list.get(0); if ((game == null)) game = new GameState(); return game; } public void save() { org.hibernate.classic.Session session = HibernateQuerier.getFactory().getCurrentSession(); Transaction transaction = session.beginTransaction(); session.saveOrUpdate(this); transaction.commit(); } void setPlays(int plays) { this.plays = plays; } void setHolder(String holder) { this.holder = holder; } void setRecord(int record) { this.record = record; } }
bsd-3-clause
scaladyno/ductilej
docs/wasp-2010-2-22-src/unop.java
154
int foo = 0, bar = 0; // non-side-effecting op foo = -foo; // prefix increment foo = ++bar; // postfix increment foo = bar++; // same for decrement
bsd-3-clause
krzyk/rexsl
src/test/java/com/rexsl/page/inset/package-info.java
1699
/** * Copyright (c) 2011-2014, ReXSL.com * 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 ReXSL.com nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Insets, tests. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 0.4.7 */ package com.rexsl.page.inset;
bsd-3-clause
NCIP/cagrid2-wsrf
wsrf-servicegroup-api/src/main/java/org/oasis_open/docs/wsrf/_2004/_06/wsrf_ws_servicegroup_1_2_draft_01/ObjectFactory.java
10065
package org.oasis_open.docs.wsrf._2004._06.wsrf_ws_servicegroup_1_2_draft_01; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; import org.xmlsoap.schemas.ws._2004._03.addressing.EndpointReferenceType; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the org.oasis_open.docs.wsrf._2004._06.wsrf_ws_servicegroup_1_2_draft_01 package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _EntryRemovalNotification_QNAME = new QName("http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", "EntryRemovalNotification"); private final static QName _ServiceGroupEPR_QNAME = new QName("http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", "ServiceGroupEPR"); private final static QName _UnsupportedMemberInterfaceFault_QNAME = new QName("http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", "UnsupportedMemberInterfaceFault"); private final static QName _AddRefusedFault_QNAME = new QName("http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", "AddRefusedFault"); private final static QName _Entry_QNAME = new QName("http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", "Entry"); private final static QName _Content_QNAME = new QName("http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", "Content"); private final static QName _AddResponse_QNAME = new QName("http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", "AddResponse"); private final static QName _EntryAdditionNotification_QNAME = new QName("http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", "EntryAdditionNotification"); private final static QName _MemberEPR_QNAME = new QName("http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", "MemberEPR"); private final static QName _ContentCreationFailedFault_QNAME = new QName("http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", "ContentCreationFailedFault"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.oasis_open.docs.wsrf._2004._06.wsrf_ws_servicegroup_1_2_draft_01 * */ public ObjectFactory() { } /** * Create an instance of {@link ContentCreationFailedFaultType } * */ public ContentCreationFailedFaultType createContentCreationFailedFaultType() { return new ContentCreationFailedFaultType(); } /** * Create an instance of {@link ServiceGroupModificationNotificationType } * */ public ServiceGroupModificationNotificationType createServiceGroupModificationNotificationType() { return new ServiceGroupModificationNotificationType(); } /** * Create an instance of {@link ServiceGroupEntryRP } * */ public ServiceGroupEntryRP createServiceGroupEntryRP() { return new ServiceGroupEntryRP(); } /** * Create an instance of {@link MembershipContentRule } * */ public MembershipContentRule createMembershipContentRule() { return new MembershipContentRule(); } /** * Create an instance of {@link EntryType } * */ public EntryType createEntryType() { return new EntryType(); } /** * Create an instance of {@link AddRefusedFaultType } * */ public AddRefusedFaultType createAddRefusedFaultType() { return new AddRefusedFaultType(); } /** * Create an instance of {@link ServiceGroupRemovalNotificationType } * */ public ServiceGroupRemovalNotificationType createServiceGroupRemovalNotificationType() { return new ServiceGroupRemovalNotificationType(); } /** * Create an instance of {@link UnsupportedMemberInterfaceFaultType } * */ public UnsupportedMemberInterfaceFaultType createUnsupportedMemberInterfaceFaultType() { return new UnsupportedMemberInterfaceFaultType(); } /** * Create an instance of {@link ServiceGroupRP } * */ public ServiceGroupRP createServiceGroupRP() { return new ServiceGroupRP(); } /** * Create an instance of {@link Add } * */ public Add createAdd() { return new Add(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ServiceGroupRemovalNotificationType }{@code >}} * */ @XmlElementDecl(namespace = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", name = "EntryRemovalNotification") public JAXBElement<ServiceGroupRemovalNotificationType> createEntryRemovalNotification(ServiceGroupRemovalNotificationType value) { return new JAXBElement<ServiceGroupRemovalNotificationType>(_EntryRemovalNotification_QNAME, ServiceGroupRemovalNotificationType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EndpointReferenceType }{@code >}} * */ @XmlElementDecl(namespace = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", name = "ServiceGroupEPR") public JAXBElement<EndpointReferenceType> createServiceGroupEPR(EndpointReferenceType value) { return new JAXBElement<EndpointReferenceType>(_ServiceGroupEPR_QNAME, EndpointReferenceType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link UnsupportedMemberInterfaceFaultType }{@code >}} * */ @XmlElementDecl(namespace = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", name = "UnsupportedMemberInterfaceFault") public JAXBElement<UnsupportedMemberInterfaceFaultType> createUnsupportedMemberInterfaceFault(UnsupportedMemberInterfaceFaultType value) { return new JAXBElement<UnsupportedMemberInterfaceFaultType>(_UnsupportedMemberInterfaceFault_QNAME, UnsupportedMemberInterfaceFaultType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AddRefusedFaultType }{@code >}} * */ @XmlElementDecl(namespace = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", name = "AddRefusedFault") public JAXBElement<AddRefusedFaultType> createAddRefusedFault(AddRefusedFaultType value) { return new JAXBElement<AddRefusedFaultType>(_AddRefusedFault_QNAME, AddRefusedFaultType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EntryType }{@code >}} * */ @XmlElementDecl(namespace = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", name = "Entry") public JAXBElement<EntryType> createEntry(EntryType value) { return new JAXBElement<EntryType>(_Entry_QNAME, EntryType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Object }{@code >}} * */ @XmlElementDecl(namespace = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", name = "Content") public JAXBElement<Object> createContent(Object value) { return new JAXBElement<Object>(_Content_QNAME, Object.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EndpointReferenceType }{@code >}} * */ @XmlElementDecl(namespace = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", name = "AddResponse") public JAXBElement<EndpointReferenceType> createAddResponse(EndpointReferenceType value) { return new JAXBElement<EndpointReferenceType>(_AddResponse_QNAME, EndpointReferenceType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ServiceGroupModificationNotificationType }{@code >}} * */ @XmlElementDecl(namespace = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", name = "EntryAdditionNotification") public JAXBElement<ServiceGroupModificationNotificationType> createEntryAdditionNotification(ServiceGroupModificationNotificationType value) { return new JAXBElement<ServiceGroupModificationNotificationType>(_EntryAdditionNotification_QNAME, ServiceGroupModificationNotificationType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EndpointReferenceType }{@code >}} * */ @XmlElementDecl(namespace = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", name = "MemberEPR") public JAXBElement<EndpointReferenceType> createMemberEPR(EndpointReferenceType value) { return new JAXBElement<EndpointReferenceType>(_MemberEPR_QNAME, EndpointReferenceType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ContentCreationFailedFaultType }{@code >}} * */ @XmlElementDecl(namespace = "http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ServiceGroup-1.2-draft-01.xsd", name = "ContentCreationFailedFault") public JAXBElement<ContentCreationFailedFaultType> createContentCreationFailedFault(ContentCreationFailedFaultType value) { return new JAXBElement<ContentCreationFailedFaultType>(_ContentCreationFailedFault_QNAME, ContentCreationFailedFaultType.class, null, value); } }
bsd-3-clause
delivered/BulkScanDownloader
src/main/java/iris/RecycleDownloadedItemRequest.java
6482
/** * RecycleDownloadedItemRequest.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package iris; public class RecycleDownloadedItemRequest implements java.io.Serializable { private java.lang.Boolean keepScans; private iris.MailboxID mailboxID; private iris.VItemID[] VItemIDs; public RecycleDownloadedItemRequest() { } public RecycleDownloadedItemRequest( java.lang.Boolean keepScans, iris.MailboxID mailboxID, iris.VItemID[] VItemIDs) { this.keepScans = keepScans; this.mailboxID = mailboxID; this.VItemIDs = VItemIDs; } /** * Gets the keepScans value for this RecycleDownloadedItemRequest. * * @return keepScans */ public java.lang.Boolean getKeepScans() { return keepScans; } /** * Sets the keepScans value for this RecycleDownloadedItemRequest. * * @param keepScans */ public void setKeepScans(java.lang.Boolean keepScans) { this.keepScans = keepScans; } /** * Gets the mailboxID value for this RecycleDownloadedItemRequest. * * @return mailboxID */ public iris.MailboxID getMailboxID() { return mailboxID; } /** * Sets the mailboxID value for this RecycleDownloadedItemRequest. * * @param mailboxID */ public void setMailboxID(iris.MailboxID mailboxID) { this.mailboxID = mailboxID; } /** * Gets the VItemIDs value for this RecycleDownloadedItemRequest. * * @return VItemIDs */ public iris.VItemID[] getVItemIDs() { return VItemIDs; } /** * Sets the VItemIDs value for this RecycleDownloadedItemRequest. * * @param VItemIDs */ public void setVItemIDs(iris.VItemID[] VItemIDs) { this.VItemIDs = VItemIDs; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof RecycleDownloadedItemRequest)) return false; RecycleDownloadedItemRequest other = (RecycleDownloadedItemRequest) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.keepScans==null && other.getKeepScans()==null) || (this.keepScans!=null && this.keepScans.equals(other.getKeepScans()))) && ((this.mailboxID==null && other.getMailboxID()==null) || (this.mailboxID!=null && this.mailboxID.equals(other.getMailboxID()))) && ((this.VItemIDs==null && other.getVItemIDs()==null) || (this.VItemIDs!=null && java.util.Arrays.equals(this.VItemIDs, other.getVItemIDs()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getKeepScans() != null) { _hashCode += getKeepScans().hashCode(); } if (getMailboxID() != null) { _hashCode += getMailboxID().hashCode(); } if (getVItemIDs() != null) { for (int i=0; i<java.lang.reflect.Array.getLength(getVItemIDs()); i++) { java.lang.Object obj = java.lang.reflect.Array.get(getVItemIDs(), i); if (obj != null && !obj.getClass().isArray()) { _hashCode += obj.hashCode(); } } } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(RecycleDownloadedItemRequest.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("uri:iris", ">RecycleDownloadedItemRequest")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("keepScans"); elemField.setXmlName(new javax.xml.namespace.QName("uri:iris", "KeepScans")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("mailboxID"); elemField.setXmlName(new javax.xml.namespace.QName("uri:iris", "MailboxID")); elemField.setXmlType(new javax.xml.namespace.QName("uri:iris", "MailboxID")); elemField.setMinOccurs(0); elemField.setNillable(true); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("VItemIDs"); elemField.setXmlName(new javax.xml.namespace.QName("uri:iris", "VItemIDs")); elemField.setXmlType(new javax.xml.namespace.QName("uri:iris", "VItemID")); elemField.setMinOccurs(0); elemField.setNillable(true); elemField.setItemQName(new javax.xml.namespace.QName("uri:iris", "VItemID")); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
bsd-3-clause
CERN/JAMH
jamh/base_rule_set/src/test/java/cern/enice/jira/amh/baseruleset/rulesets/MultivalueFieldsRuleSetTest.java
2164
package cern.enice.jira.amh.baseruleset.rulesets; import static org.junit.Assert.*; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.mockito.Mock; import cern.enice.jira.amh.api.JiraCommunicator; import cern.enice.jira.amh.baseruleset.Tokens; import cern.enice.jira.amh.dto.EMail; import cern.enice.jira.amh.dto.EMailAddress; import cern.enice.jira.amh.dto.IssueDescriptor; import cern.enice.jira.amh.jira_rest_communicator.JiraRestCommunicator; import cern.enice.jira.amh.logback.LogbackLogProvider; import cern.enice.jira.amh.utils.EmailHandlingException; public class MultivalueFieldsRuleSetTest { MultivalueFieldsRuleSet multivalueFieldsRuleSet = new MultivalueFieldsRuleSet(); public JiraRestCommunicator getMockedJiraCommunicator() { Map<String, Map<String, Object>> userDataMap = new HashMap<String, Map<String, Object>>(); JiraRestCommunicator jiraCommunicator = mock(JiraRestCommunicator.class); doReturn("support - labview").when(jiraCommunicator).getComponentRegisteredName(null, null, "support - labview"); doReturn(true).when(jiraCommunicator).isValidProject("ens"); return jiraCommunicator; } @Test public void test() throws EmailHandlingException { multivalueFieldsRuleSet.setLogger(new LogbackLogProvider()); Map<String, String > token = new HashMap<String, String>(); token.put(Tokens.COMPONENTS, "Support__-__LabVIEW"); EMail email = new EMail(); email.setFrom(new EMailAddress("Brice Copy", "brice.copy", "cern.ch")); email.setTo(Arrays.asList(new EMailAddress[]{new EMailAddress("ICE Control Support", "IceControls.support", "cern.ch")})); multivalueFieldsRuleSet.setJiraCommunicator(getMockedJiraCommunicator()); IssueDescriptor issueDescriptor = new IssueDescriptor(); issueDescriptor.setOriginalState(new IssueDescriptor()); multivalueFieldsRuleSet.process(email, token, issueDescriptor); assertNotNull(issueDescriptor.getComponents()); assertTrue(issueDescriptor.getComponents().contains("support - labview")); } }
bsd-3-clause
ltilve/chromium
mojo/android/javatests/src/org/chromium/mojo/bindings/RouterTest.java
5697
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.mojo.bindings; import android.test.suitebuilder.annotation.SmallTest; import org.chromium.mojo.MojoTestCase; import org.chromium.mojo.bindings.BindingsTestUtils.CapturingErrorHandler; import org.chromium.mojo.bindings.BindingsTestUtils.RecordingMessageReceiverWithResponder; import org.chromium.mojo.system.Core; import org.chromium.mojo.system.Handle; import org.chromium.mojo.system.MessagePipeHandle; import org.chromium.mojo.system.MojoResult; import org.chromium.mojo.system.Pair; import org.chromium.mojo.system.ResultAnd; import org.chromium.mojo.system.impl.CoreImpl; import java.nio.ByteBuffer; import java.util.ArrayList; /** * Testing {@link Router} */ public class RouterTest extends MojoTestCase { private MessagePipeHandle mHandle; private Router mRouter; private RecordingMessageReceiverWithResponder mReceiver; private CapturingErrorHandler mErrorHandler; /** * @see MojoTestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); Core core = CoreImpl.getInstance(); Pair<MessagePipeHandle, MessagePipeHandle> handles = core.createMessagePipe(null); mHandle = handles.first; mRouter = new RouterImpl(handles.second); mReceiver = new RecordingMessageReceiverWithResponder(); mRouter.setIncomingMessageReceiver(mReceiver); mErrorHandler = new CapturingErrorHandler(); mRouter.setErrorHandler(mErrorHandler); mRouter.start(); } /** * Testing sending a message via the router that expected a response. */ @SmallTest public void testSendingToRouterWithResponse() { final int requestMessageType = 0xdead; final int responseMessageType = 0xbeaf; // Sending a message expecting a response. MessageHeader header = new MessageHeader(requestMessageType, MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG, 0); Encoder encoder = new Encoder(CoreImpl.getInstance(), header.getSize()); header.encode(encoder); mRouter.acceptWithResponder(encoder.getMessage(), mReceiver); ByteBuffer receiveBuffer = ByteBuffer.allocateDirect(header.getSize()); ResultAnd<MessagePipeHandle.ReadMessageResult> result = mHandle.readMessage(receiveBuffer, 0, MessagePipeHandle.ReadFlags.NONE); assertEquals(MojoResult.OK, result.getMojoResult()); MessageHeader receivedHeader = new Message( receiveBuffer, new ArrayList<Handle>()).asServiceMessage().getHeader(); assertEquals(header.getType(), receivedHeader.getType()); assertEquals(header.getFlags(), receivedHeader.getFlags()); assertTrue(receivedHeader.getRequestId() != 0); // Sending the response. MessageHeader responseHeader = new MessageHeader(responseMessageType, MessageHeader.MESSAGE_IS_RESPONSE_FLAG, receivedHeader.getRequestId()); encoder = new Encoder(CoreImpl.getInstance(), header.getSize()); responseHeader.encode(encoder); Message responseMessage = encoder.getMessage(); mHandle.writeMessage(responseMessage.getData(), new ArrayList<Handle>(), MessagePipeHandle.WriteFlags.NONE); runLoopUntilIdle(); assertEquals(1, mReceiver.messages.size()); ServiceMessage receivedResponseMessage = mReceiver.messages.get(0).asServiceMessage(); assertEquals(MessageHeader.MESSAGE_IS_RESPONSE_FLAG, receivedResponseMessage.getHeader().getFlags()); assertEquals(responseMessage.getData(), receivedResponseMessage.getData()); } /** * Testing receiving a message via the router that expected a response. */ @SmallTest public void testReceivingViaRouterWithResponse() { final int requestMessageType = 0xdead; final int responseMessageType = 0xbeef; final int requestId = 0xdeadbeaf; // Sending a message expecting a response. MessageHeader header = new MessageHeader(requestMessageType, MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG, requestId); Encoder encoder = new Encoder(CoreImpl.getInstance(), header.getSize()); header.encode(encoder); Message headerMessage = encoder.getMessage(); mHandle.writeMessage(headerMessage.getData(), new ArrayList<Handle>(), MessagePipeHandle.WriteFlags.NONE); runLoopUntilIdle(); assertEquals(1, mReceiver.messagesWithReceivers.size()); Pair<Message, MessageReceiver> receivedMessage = mReceiver.messagesWithReceivers.get(0); assertEquals(headerMessage.getData(), receivedMessage.first.getData()); // Sending the response. MessageHeader responseHeader = new MessageHeader(responseMessageType, MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG, requestId); encoder = new Encoder(CoreImpl.getInstance(), header.getSize()); responseHeader.encode(encoder); Message message = encoder.getMessage(); receivedMessage.second.accept(message); ByteBuffer receivedResponseMessage = ByteBuffer.allocateDirect(responseHeader.getSize()); ResultAnd<MessagePipeHandle.ReadMessageResult> result = mHandle.readMessage(receivedResponseMessage, 0, MessagePipeHandle.ReadFlags.NONE); assertEquals(MojoResult.OK, result.getMojoResult()); assertEquals(message.getData(), receivedResponseMessage); } }
bsd-3-clause
mbordas/qualify
src/test/java/qualify/test/unit/UT_TestToolStrings.java
2721
/*Copyright (c) 2011, Mathieu Bordas 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 copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package qualify.test.unit; import qualify.TestCase; import qualify.tools.TestToolStrings; public class UT_TestToolStrings extends TestCase { TestToolStrings strings = new TestToolStrings(this); @Override public void run() { setRequirementTarget("TestToolStrings"); String[] a = new String[]{"a", "b", "c", "d"}; String[] b = new String[]{"1", "2", "3", "4"}; strings.checkSameValues(new String[]{"a", "b", "c", "d", "1", "2", "3", "4"}, TestToolStrings.concat(a, b), true); strings.checkSameValues(new String[]{"a", "b", "c", "d", "2", "3", "4"}, TestToolStrings.concat(a, b, 1, 3), true); strings.checkSameValues(new String[]{"a", "b", "c", "d", "1", "2", "3"}, TestToolStrings.concat(a, b, 0, 2), true); strings.checkSameValues(new String[]{"a", "b", "c", "d"}, TestToolStrings.concat(a, null), true); strings.checkSameValues(new String[]{"a", "b", "c", "d"}, TestToolStrings.concat(a, null, 0, 2), true); strings.checkSameValues(new String[]{}, TestToolStrings.concat(null, null), true); strings.checkSameValues(new String[]{"1", "2", "3", "4"}, TestToolStrings.concat(null, b), true); strings.checkSameValues(new String[]{"1", "2", "3"}, TestToolStrings.concat(null, b, 0, 2), true); } }
bsd-3-clause
8v060htwyc/whois
whois-nrtm/src/main/java/net/ripe/db/whois/nrtm/client/SocketChannelFactory.java
3091
package net.ripe.db.whois.nrtm.client; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class SocketChannelFactory { private SocketChannelFactory() {} public static SocketChannel createSocketChannel(final String host, final int port) throws IOException { final SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(true); socketChannel.connect(new InetSocketAddress(host, port)); return socketChannel; } public static Reader createReader(final SocketChannel socketChannel) { return new Reader(socketChannel); } public static Writer createWriter(final SocketChannel socketChannel) { return new Writer(socketChannel); } public static class Reader { private final SocketChannel socketChannel; final ByteBuffer buffer = ByteBuffer.allocate(1024); public Reader(final SocketChannel socketChannel) { this.socketChannel = socketChannel; } public String readLine() throws IOException { final StringBuilder builder = new StringBuilder(); if (buffer.position() > 0) { if (readLineFromBuffer(builder)) { return builder.toString(); } } for (;;) { final int length = socketChannel.read(buffer); if (length == 0) { continue; } if (length == -1) { throw new IOException("End of stream"); } buffer.flip(); if (readLineFromBuffer(builder)) { return builder.toString(); } } } private boolean readLineFromBuffer(final StringBuilder builder) { while (buffer.hasRemaining()) { byte next = buffer.get(); if (next == '\n') { if (buffer.position() == buffer.limit()) { // no more bytes in buffer buffer.clear(); } return true; } builder.append((char)next); } // no more bytes in buffer buffer.clear(); return false; } } public static class Writer { private static final byte[] NEWLINE = new byte[]{'\n'}; private final SocketChannel socketChannel; public Writer(SocketChannel socketChannel) { this.socketChannel = socketChannel; } public void writeLine(final String line) throws IOException { final ByteBuffer byteBuffer = ByteBuffer.allocate(line.length() + 1); byteBuffer.put(line.getBytes()); byteBuffer.put(NEWLINE, 0, 1); byteBuffer.flip(); while (byteBuffer.hasRemaining()) { socketChannel.write(byteBuffer); } } } }
bsd-3-clause
Sensirion/SmartGadget-Android
app/src/main/java/com/sensirion/smartgadget/peripheral/rht_sensor/external/GadgetModel.java
3192
/* * Copyright (c) 2017, Sensirion AG * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Sensirion AG nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.sensirion.smartgadget.peripheral.rht_sensor.external; import android.support.annotation.NonNull; import android.support.annotation.Nullable; public class GadgetModel { public static final String UNKNOWN_DEVICE_NAME = "UNKNOWN"; @NonNull private final String mDeviceAddress; private String mUserDeviceName; private int rssi; private boolean mConnected; public GadgetModel(@NonNull final String deviceAddress, final boolean connected, @Nullable final String userDeviceName) { mDeviceAddress = deviceAddress; mConnected = connected; mUserDeviceName = (userDeviceName != null) ? userDeviceName : UNKNOWN_DEVICE_NAME; } @NonNull public String getAddress() { return mDeviceAddress; } public boolean isConnected() { return mConnected; } public void setConnected(boolean connected) { mConnected = connected; } @NonNull public String getName() { return mUserDeviceName; } public void setUserDeviceName(@NonNull String userDeviceName) { mUserDeviceName = userDeviceName; } public int getRssi() { return rssi; } public void setRssi(int rssi) { this.rssi = rssi; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof GadgetModel)) return false; GadgetModel that = (GadgetModel) o; return mDeviceAddress.equals(that.mDeviceAddress); } @Override public int hashCode() { return mDeviceAddress.hashCode(); } }
bsd-3-clause
GCRC/nunaliit
nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/CommandRestore.java
3360
package ca.carleton.gcrc.couch.command; import java.io.File; import java.io.PrintStream; import java.util.Set; import ca.carleton.gcrc.couch.app.DbRestoreListener; import ca.carleton.gcrc.couch.app.DbRestoreProcess; import ca.carleton.gcrc.couch.client.CouchDb; import ca.carleton.gcrc.couch.command.impl.CommandSupport; import ca.carleton.gcrc.couch.command.impl.RestoreListener; public class CommandRestore implements Command { @Override public String getCommandString() { return "restore"; } @Override public boolean matchesKeyword(String keyword) { if( getCommandString().equalsIgnoreCase(keyword) ) { return true; } return false; } @Override public boolean isDeprecated() { return false; } @Override public String[] getExpectedOptions() { return new String[]{ Options.OPTION_ATLAS_DIR ,Options.OPTION_DUMP_DIR ,Options.OPTION_DOC_ID }; } @Override public boolean requiresAtlasDir() { return true; } @Override public void reportHelp(PrintStream ps) { ps.println("Nunaliit2 Atlas Framework - Restore Command"); ps.println(); ps.println("The restore command allows a user to restore a snapshot, previously"); ps.println("obtained using the dump command, to the database associated with the"); ps.println("atlas."); ps.println(); ps.println("Command Syntax:"); ps.println(" nunaliit restore <options>"); ps.println(); ps.println("options:"); ps.println(" "+Options.OPTION_DUMP_DIR+" <dir>"); ps.println(" --dump-dir <dir> Directory where snapshot is stored"); ps.println(); ps.println(" "+Options.OPTION_DOC_ID+" <docId>"); ps.println(" Specifies which document(s) should be restored by selecting the "); ps.println(" document identifier. This option can be used multiple times to include"); ps.println(" multiple documents in the restore process. If this option is not "); ps.println(" used, all documents are restored."); ps.println(); CommandHelp.reportGlobalOptions(ps,getExpectedOptions()); } @Override public void runCommand( GlobalSettings gs ,Options options ) throws Exception { if( options.getArguments().size() > 1 ){ throw new Exception("Unexpected argument: "+options.getArguments().get(1)); } File atlasDir = gs.getAtlasDir(); // Pick up options String dumpDirStr = options.getDumpDir(); Set<String> docIds = options.getDocIds(); File dumpDir = null; if( null != dumpDirStr ){ dumpDir = new File(dumpDirStr); } if( null == dumpDir ) { throw new Exception("During a restore, the --dump-dir option must be provided"); } if( false == dumpDir.exists() ) { throw new Exception("Can not find restore directory: "+dumpDir.getAbsolutePath()); } gs.getOutStream().println("Restoring from "+dumpDir.getAbsolutePath()); // Load properties for atlas AtlasProperties atlasProperties = AtlasProperties.fromAtlasDir(atlasDir); CouchDb couchDb = CommandSupport.createCouchDb(gs, atlasProperties); DbRestoreListener listener = new RestoreListener(gs.getOutStream()); DbRestoreProcess restoreProcess = new DbRestoreProcess(couchDb, dumpDir); restoreProcess.setListener(listener); if( docIds.size() < 1 ) { restoreProcess.setAllDocs(true); } else { for(String docId : docIds) { restoreProcess.addDocId(docId); } } restoreProcess.restore(); } }
bsd-3-clause
Team319/SteamworksBob319
src/org/usfirst/frc319/SteamworksBob319/commands/DriveTrain/RightDrivetrainPIDTest.java
1439
// RobotBuilder Version: 2.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc319.SteamworksBob319.commands.DriveTrain; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc319.SteamworksBob319.Robot; /** * */ public class RightDrivetrainPIDTest extends Command { public RightDrivetrainPIDTest() { requires(Robot.driveTrain); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { Robot.driveTrain.rightDrivetrainPIDTestMode(); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
bsd-3-clause
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/telephony/OvhDirectoryInfo.java
2672
package net.minidev.ovh.api.telephony; import java.util.Date; import net.minidev.ovh.api.nichandle.OvhGenderEnum; /** * Directory Informations */ public class OvhDirectoryInfo { /** * canBeNull && readOnly */ public String directoryServiceCode; /** * canBeNull && readOnly */ public String country; /** * canBeNull && readOnly */ public String PJSocialNomination; /** * canBeNull && readOnly */ public String wayName; /** * canBeNull && readOnly */ public String occupation; /** * canBeNull && readOnly */ public OvhGenderEnum gender; /** * canBeNull && readOnly */ public String city; /** * canBeNull && readOnly */ public String siret; /** * canBeNull && readOnly */ public String number; /** * canBeNull && readOnly */ public Long inseeCode; /** * canBeNull && readOnly */ public String wayType; /** * canBeNull && readOnly */ public String cedex; /** * canBeNull && readOnly */ public String ape; /** * canBeNull && readOnly */ public String urbanDistrict; /** * canBeNull && readOnly */ public String email; /** * canBeNull && readOnly */ public String lineDescription; /** * canBeNull && readOnly */ public Boolean displaySearchReverse; /** * canBeNull && readOnly */ public Boolean displayFirstName; /** * canBeNull && readOnly */ public String address; /** * canBeNull && readOnly */ public String socialNomination; /** * canBeNull && readOnly */ public String postBox; /** * canBeNull && readOnly */ public String addressExtra; /** * canBeNull && readOnly */ public String wayNumber; /** * canBeNull && readOnly */ public String modificationType; /** * canBeNull && readOnly */ public Boolean displayUniversalDirectory; /** * canBeNull && readOnly */ public String legalForm; /** * canBeNull && readOnly */ public Date birthDate; /** * canBeNull && readOnly */ public String socialNominationExtra; /** * canBeNull && readOnly */ public String firstName; /** * canBeNull && readOnly */ public Boolean displayOnlyCity; /** * canBeNull && readOnly */ public String modificationDate; /** * canBeNull && readOnly */ public Long areaCode; /** * canBeNull && readOnly */ public String wayNumberExtra; /** * canBeNull && readOnly */ public String name; /** * canBeNull && readOnly */ public String postCode; /** * canBeNull && readOnly */ public Boolean receivePJDirectory; /** * canBeNull && readOnly */ public Boolean displayMarketingDirectory; /** * canBeNull && readOnly */ public String status; }
bsd-3-clause
inepex/ineform
ineframe/src/main/java/com/inepex/ineFrame/server/util/ArrayListConcurrentHashMap.java
2455
package com.inepex.ineFrame.server.util; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.ConcurrentHashMap; /** * @author balint.steinbach@inepex.com, istvan.szoboszlai@inepex.com * * ConcurrentHashMap of a {@link List} of Items. Ensures creation of the * list, and provides convenience functions. * * @param <T> * Type of the Key * @param <K> * Generic type of the List */ public class ArrayListConcurrentHashMap<T, K> { private final ConcurrentHashMap<T, List<K>> map = new ConcurrentHashMap<>(); public List<K> getListById(T id) { return map.get(id); } public boolean isListNullById(T id) { return map.get(id) == null; } public boolean containsKey(T id) { return map.containsKey(id); } public boolean isListEmptyOrNullById(T id) { List<K> list = map.get(id); return (list == null) || (list.isEmpty()); } public void addToListById(T id, K element) { List<K> list = ensureListById(id); list.add(element); } public void remove(T id) { map.remove(id); } /** * Ensures that a list be created for the given id. The list returned by * this method can be a parameter of a synchronized block. * * @param id * @return */ public List<K> ensureListById(T id) { List<K> list = map.get(id); if (list != null) return list; list = new ArrayList<K>(1); List<K> oldVal = map.putIfAbsent(id, list); if (oldVal != null) return oldVal; else return list; } public void addAllToListById(T id, Collection<K> elements) { List<K> list = ensureListById(id); list.addAll(elements); } public boolean contains(T id, K element) { if (isListEmptyOrNullById(id)) return false; List<K> list = map.get(id); if (list == null) return false; return list.contains(element); } public void clear() { map.clear(); } public boolean isEmpty() { return map.isEmpty(); } public int size() { return map.size(); } public Collection<List<K>> getValues() { return map.values(); } }
bsd-3-clause
lukehutch/gribbit-rox
tests/com/flat502/rox/server/CustomType.java
112
package com.flat502.rox.server; public class CustomType { public String string; public boolean bool; }
bsd-3-clause
ChinaXing/china-rpc
src/main/java/com/chinaxing/framework/rpc/protocol/ChinaSerialize.java
16347
package com.chinaxing.framework.rpc.protocol; import com.chinaxing.framework.rpc.exception.SerializeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; /** * 序列化反序列化工具 * <p/> * TODO : * 1. 支持generic * 2. 支持注解 * 3. 支持transient * <p/> * Created by LambdaCat on 15/8/23. */ public class ChinaSerialize { private static final Logger logger = LoggerFactory.getLogger(ChinaSerialize.class); private static final byte EXCEPTION = -1, NULL = -2, ENUM = -3, ARRAY = -4, OBJECT = -5, COLLECTION = -6, MAP = -7; private static Map<Class, Byte> classCode = new HashMap<Class, Byte>(); private static Class[] classIndex = new Class[]{ int.class, byte.class, char.class, short.class, double.class, float.class, boolean.class, long.class, Integer.class, Byte.class, Character.class, Short.class, Double.class, Float.class, Long.class, Boolean.class, String.class, Date.class }; private static Map<String, Class> primitiveClass = new HashMap<String, Class>(); // private static final DateFormat dateFormat = new SimpleDateFormat(); static { for (byte i = 0; i < classIndex.length; i++) { classCode.put(classIndex[i], i); } for (Class c : classIndex) { primitiveClass.put(c.getName(), c); } } /** * 序列化对象 * TODO 支持有继承关系的类型 * * @param name * @param obj * @param buffer */ public static void serialize(String name, Object obj, SafeBuffer buffer) throws Throwable { writeString(name, buffer); /** * 异常 */ if (obj instanceof Throwable) { buffer.put(EXCEPTION); writeString(obj.getClass().getName(), buffer); writeString(((Throwable) obj).getMessage(), buffer); StackTraceElement[] stackTrace = ((Throwable) obj).getStackTrace(); serialize("stackTrace", stackTrace, buffer); return; } /** * 空对象 */ if (obj == null) { buffer.put(NULL); return; } Class clz = obj.getClass(); Byte index = classCode.get(clz); if (index != null) { serializeBaseClass(index, clz, obj, buffer); return; } /** * 枚举 */ if (clz.isEnum()) { buffer.put(ENUM); writeString(clz.getName(), buffer); String en = ((Enum) obj).name(); byte[] enB = en.getBytes(); buffer.putInt(enB.length); buffer.put(enB); return; } /** * 非原始类型 */ if (clz.isArray()) { buffer.put(ARRAY); Class eClz = clz.getComponentType(); writeClassName(eClz, buffer); buffer.putInt(Array.getLength(obj)); for (int i = 0; i < Array.getLength(obj); i++) { serialize(String.valueOf(i), Array.get(obj, i), buffer); } return; } if (Collection.class.isAssignableFrom(clz)) { serializeCollection(clz, obj, buffer); return; } if (Map.class.isAssignableFrom(clz)) { serializeMap(clz, obj, buffer); return; } /** * 对象 * * TODO 支持有参数的构造器 */ serializeObject(clz, obj, buffer); } private static void serializeMap(Class clz, Object obj, SafeBuffer buffer) throws Throwable { buffer.put(MAP); writeString(clz.getName(), buffer); buffer.putInt(((Map) obj).size()); Iterator<Map.Entry> iterator = ((Map) obj).entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); serialize("k", entry.getKey(), buffer); serialize("v", entry.getValue(), buffer); } } private static void serializeObject(Class clz, Object obj, SafeBuffer buffer) throws Throwable { buffer.put(OBJECT); writeString(clz.getName(), buffer); /** * write the Fields * * TODO support inherited fields */ Class objClz = obj.getClass(); Field[] fields = objClz.getDeclaredFields(); List<Field> fieldList = new ArrayList<Field>(); /** * 去掉静态域 */ for (Field f : fields) { int mod = f.getModifiers(); if (Modifier.isStatic(mod) || Modifier.isTransient(mod) || Modifier.isFinal(mod)) { continue; } fieldList.add(f); } buffer.putInt(fieldList.size()); for (Field f : fieldList) { Object of; if (!f.isAccessible()) { f.setAccessible(true); of = f.get(obj); f.setAccessible(false); } else { of = f.get(obj); } serialize(f.getName(), of, buffer); } } private static void serializeBaseClass(byte index, Class clz, Object obj, SafeBuffer buffer) throws Throwable { buffer.put(index); if (clz.equals(int.class) || clz.equals(Integer.class)) { buffer.putInt(((Integer) obj)); return; } if (clz.equals(byte.class) || clz.equals(Byte.class)) { buffer.put(((Byte) obj)); return; } if (clz.equals(char.class) || clz.equals(Character.class)) { buffer.putChar(((Character) obj)); return; } if (clz.equals(short.class) || clz.equals(Short.class)) { buffer.putShort(((Short) obj)); return; } if (clz.equals(long.class) || clz.equals(Long.class)) { buffer.putLong(((Long) obj)); return; } if (clz.equals(double.class) || clz.equals(Double.class)) { buffer.putDouble(((Double) obj)); return; } if (clz.equals(float.class) || clz.equals(Float.class)) { buffer.putFloat(((Float) obj)); return; } if (clz.equals(boolean.class) || clz.equals(Boolean.class)) { buffer.put(((Boolean) obj) ? (byte) 1 : (byte) 0); return; } if (clz.equals(String.class)) { writeString((String) obj, buffer); return; } if (clz.equals(Date.class)) { buffer.putLong(((Date) obj).getTime()); return; } } private static void serializeCollection(Class clz, Object obj, SafeBuffer buffer) throws Throwable { buffer.put(COLLECTION); /** * generic class name */ writeString(clz.getName(), buffer); Object[] elements = ((Collection) obj).toArray(); buffer.putInt(elements.length); int i = 0; for (Object o : elements) { serialize(String.valueOf(++i), o, buffer); } } private static DeSerializeResult deSerializeCollection(String name, SafeBuffer buffer) throws Throwable { Class c = Class.forName(parseString(buffer)); int size = buffer.getInt(); Collection instance; Constructor cstr = c.getDeclaredConstructor(); if (cstr.isAccessible()) { instance = (Collection) cstr.newInstance(); } else { cstr.setAccessible(true); instance = (Collection) cstr.newInstance(); cstr.setAccessible(false); } for (int i = 0; i < size; i++) { DeSerializeResult e = deserialize(buffer); instance.add(e.value); } return new DeSerializeResult(name, instance); } private static DeSerializeResult deserializeException(String name, SafeBuffer buffer) throws Throwable { /** * exception class name */ Class e = Class.forName(parseString(buffer)); Constructor c; boolean withEx = false; try { c = e.getDeclaredConstructor(String.class); } catch (Exception x) { c = e.getDeclaredConstructor(Throwable.class, String.class); withEx = true; } /** * message */ String msg = parseString(buffer); /** * stackTrace */ DeSerializeResult stackTrace = deserialize(buffer); Throwable t; if (c.isAccessible()) { if (withEx) t = (Throwable) c.newInstance(null, msg); else t = (Throwable) c.newInstance(msg); } else { c.setAccessible(true); if (withEx) t = (Throwable) c.newInstance(null, msg); else t = (Throwable) c.newInstance(msg); c.setAccessible(false); } t.setStackTrace((StackTraceElement[]) stackTrace.value); return new DeSerializeResult(name, t); } public static DeSerializeResult deserialize(SafeBuffer buffer) throws Throwable { String name = parseString(buffer); int code = buffer.get(); /** * 异常 */ if (code == EXCEPTION) { return deserializeException(name, buffer); } if (code == NULL) { return new DeSerializeResult(name, null); } if (code == ENUM) { Class clz = Class.forName(parseString(buffer)); return new DeSerializeResult(name, Enum.valueOf(clz, parseString(buffer))); } /** * 支持1维数组 */ if (code == ARRAY) { // 数组 Class clz = parseArrayElementClass(buffer); int al = buffer.getInt(); Object a = Array.newInstance(clz, al); for (int i = 0; i < al; i++) { DeSerializeResult pa = deserialize(buffer); Array.set(a, i, pa.value); } return new DeSerializeResult(name, a); } if (code == COLLECTION) { return deSerializeCollection(name, buffer); } if (code == MAP) { return deserializeMap(name, buffer); } if (code == OBJECT) { // 非原始类型 Class clz = Class.forName(parseString(buffer)); Object obj; if (clz.equals(StackTraceElement.class)) { Constructor constructor = clz.getDeclaredConstructor(String.class, String.class, String.class, int.class); obj = constructor.newInstance("", "", "", 0); } else { Constructor constructor = clz.getDeclaredConstructor(); if (!constructor.isAccessible()) { constructor.setAccessible(true); obj = constructor.newInstance(); constructor.setAccessible(false); } else { obj = constructor.newInstance(); } } int fl = buffer.getInt(); for (int i = 0; i < fl; i++) { DeSerializeResult dp = deserialize(buffer); Field f = clz.getDeclaredField(dp.name); if (f.isAccessible()) { f.set(obj, dp.value); } else { f.setAccessible(true); f.set(obj, dp.value); f.setAccessible(false); } } return new DeSerializeResult(name, obj); } Class clz = classIndex[code]; if (clz != null) { return deSerializeBase(name, clz, buffer); } throw new SerializeException("unknown code : " + code); } private static DeSerializeResult deserializeMap(String name, SafeBuffer buffer) throws Throwable { Class clz = Class.forName(parseString(buffer)); int size = buffer.getInt(); Map instance = (Map) clz.newInstance(); for (int i = 0; i < size; i++) { DeSerializeResult k = deserialize(buffer); DeSerializeResult v = deserialize(buffer); instance.put(k.value, v.value); } return new DeSerializeResult(name, instance); } private static DeSerializeResult deSerializeBase(String name, Class clz, SafeBuffer buffer) throws Throwable { if (clz.equals(int.class) || clz.equals(Integer.class)) { return new DeSerializeResult(name, buffer.getInt()); } if (clz.equals(byte.class) || clz.equals(Byte.class)) { return new DeSerializeResult(name, buffer.get()); } if (clz.equals(char.class) || clz.equals(Character.class)) { return new DeSerializeResult(name, buffer.getChar()); } if (clz.equals(short.class) || clz.equals(Short.class)) { return new DeSerializeResult(name, buffer.getShort()); } if (clz.equals(long.class) || clz.equals(Long.class)) { return new DeSerializeResult(name, buffer.getLong()); } if (clz.equals(double.class) || clz.equals(Double.class)) { return new DeSerializeResult(name, buffer.getDouble()); } if (clz.equals(float.class) || clz.equals(Float.class)) { return new DeSerializeResult(name, buffer.getFloat()); } if (clz.equals(boolean.class) || clz.equals(Boolean.class)) { return new DeSerializeResult(name, buffer.get() == 1); } if (clz.equals(String.class)) { return new DeSerializeResult(name, parseString(buffer)); } if (clz.equals(Date.class)) { return new DeSerializeResult(name, new Date(buffer.getLong())); } throw new SerializeException("unknown class : " + clz.getName()); } private static Class parseArrayElementClass(SafeBuffer buffer) throws Throwable { Byte index = buffer.get(); if (index >= 0) { return classIndex[index]; } return Class.forName(parseString(buffer)); } private static void writeClassName(Class clz, SafeBuffer buffer) { byte index = getClassIndex(clz); buffer.put(index); if (index < 0) { writeString(clz.getName(), buffer); } } public static void writeString(String str, SafeBuffer buffer) { if (str == null) { buffer.putInt(0); return; } byte[] clzNameByte = str.getBytes(); buffer.putInt(clzNameByte.length); buffer.put(clzNameByte); } public static String parseString(SafeBuffer buffer) { int sbl = buffer.getInt(); byte[] sb = new byte[sbl]; buffer.get(sb); return new String(sb); } private static byte getClassIndex(Class clz) { Byte index = classCode.get(clz); if (index != null) { return index; } if (clz.isEnum()) return ENUM; if (clz.isArray()) return ARRAY; return OBJECT; } public static void main(String[] args) { int[] x = new int[]{20, 203, 44}; byte[] b = new byte[1024]; Integer[] y = new Integer[]{12, 33}; SafeBuffer buffer = new SafeBuffer(1024); try { serialize("test", x, buffer); DeSerializeResult r = deserialize(buffer); System.out.println(r.name); System.out.println(r.value); buffer.clear(); serialize("test", y, buffer); r = deserialize(buffer); System.out.println(r.name); System.out.println(r.value); buffer.clear(); } catch (Throwable e) { e.printStackTrace(); } } public final static class DeSerializeResult { String name; Object value; public DeSerializeResult(String name, Object value) { this.name = name; this.value = value; } } }
bsd-3-clause
vtkio/vtk
src/main/java/vtk/web/service/RequestParameterExistsAssertion.java
4117
/* Copyright (c) 2004, University of Oslo, Norway * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the University of Oslo nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package vtk.web.service; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import vtk.repository.Resource; import vtk.security.Principal; /** * Assertion that matches when a named request parameter exists (or * does not exist) in the query string. * * <p>Configurable properties: * <ul> * <li><code>parameterName</code> - the parameter name to look for * <li><code>invert</code> - if <code>true</code>, match only when * the parameter does not exist * </ul> * */ public class RequestParameterExistsAssertion implements WebAssertion { private String parameterName = null; private boolean invert = false; public void setParameterName(String parameterName) { this.parameterName = parameterName; } public void setInvert(boolean invert) { this.invert = invert; } public String getParameterName() { return this.parameterName; } public boolean isInvert() { return this.invert; } @Override public boolean conflicts(WebAssertion assertion) { if (assertion instanceof RequestParameterExistsAssertion) { if (this.parameterName.equals( ((RequestParameterExistsAssertion)assertion).getParameterName())) { return ! (this.invert == ((RequestParameterExistsAssertion)assertion).isInvert()); } } if (assertion instanceof RequestParameterAssertion) { if (this.parameterName.equals( ((RequestParameterAssertion)assertion).getParameterName())) { return !this.invert; } } return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (this.invert) sb.append("!"); sb.append("request.parameters[").append(this.parameterName).append("].exists"); return sb.toString(); } @Override public Optional<URL> processURL(URL url, Resource resource, Principal principal) { return Optional.of(processURL(url)); } @Override public boolean matches(HttpServletRequest request, Resource resource, Principal principal) { return (this.invert != request.getParameterMap().containsKey(this.parameterName)); } @Override public URL processURL(URL url) { if (!this.invert && (url.getParameter(this.parameterName) == null)) url.addParameter(this.parameterName, ""); return url; } }
bsd-3-clause
y-yammt/approx-svd
src/test/java/com/mukkulab/util/MatrixUtilTest.java
2922
package com.mukkulab.util; import static org.junit.Assert.*; import org.junit.Test; import org.la4j.Matrix; import org.la4j.matrix.dense.Basic2DMatrix; import java.util.Random; public class MatrixUtilTest { private static final double EPS = 0.001; // TODO: variance check @Test public void randomGaussianRandomTest() { Random random = new Random(); Matrix x = MatrixUtils.randomGaussian(1000, 1000, random); int n = 0; double avg = 0.0; for (double e : x) { ++n; avg = avg + (1.0 / n) * (e - avg); } assertEquals(0.0, avg, EPS); } @Test public void processGramSchmidtTest() { // Case 1 // +- -+ +- -+ // | 3 2 1 | -> | 3/sqrt(10) -1/sqrt(10) 0 | // | 1 2 1 | | 1/sqrt(10) 3/sqrt(10) 0 | // +- -+ +- -+ Matrix x = new Basic2DMatrix(new double[][]{ new double[]{3, 2, 1}, new double[]{1, 3, 1} }); Matrix normX = MatrixUtils.processGramSchmidt(x); assertEquals( 3.0 / Math.sqrt(10.0), normX.get(0, 0), EPS); assertEquals( 1.0 / Math.sqrt(10.0), normX.get(1, 0), EPS); assertEquals(- 1.0 / Math.sqrt(10.0), normX.get(0, 1), EPS); assertEquals( 3.0 / Math.sqrt(10.0), normX.get(1, 1), EPS); assertEquals( 0.0, normX.get(0, 2), EPS); assertEquals( 0.0, normX.get(1, 2), EPS); // Case 2 // +- -+ +- -+ // | 1 1 0 | -> | 1/sqrt(2) sqrt(2)/2sqrt(3) -sqrt(3)/3 | // | 1 0 1 | | 1/sqrt(2) -sqrt(2)/2sqrt(3) sqrt(3)/3 | // | 0 1 1 | | 0 sqrt(2)/ sqrt(3) sqrt(3)/3 | // +- -+ +- -+ x = new Basic2DMatrix(new double[][]{ new double[]{1, 1, 0}, new double[]{1, 0, 1}, new double[]{0, 1, 1} }); normX = MatrixUtils.processGramSchmidt(x); assertEquals( 1.0 / Math.sqrt(2.0), normX.get(0, 0), EPS); assertEquals( 1.0 / Math.sqrt(2.0), normX.get(1, 0), EPS); assertEquals( 0.0, normX.get(2, 0), EPS); assertEquals( Math.sqrt(2.0) / (2.0 * Math.sqrt(3.0)), normX.get(0, 1), EPS); assertEquals(- Math.sqrt(2.0) / (2.0 * Math.sqrt(3.0)), normX.get(1, 1), EPS); assertEquals( Math.sqrt(2.0) / Math.sqrt(3.0), normX.get(2, 1), EPS); assertEquals( - Math.sqrt(3.0) / 3.0, normX.get(0, 2), EPS); assertEquals( Math.sqrt(3.0) / 3.0, normX.get(1, 2), EPS); assertEquals( Math.sqrt(3.0) / 3.0, normX.get(2, 2), EPS); } }
bsd-3-clause
madgnome/Buccaneer
src/main/java/com/madgnome/stash/plugins/buccaneer/events/RepositoryListener.java
1954
package com.madgnome.stash.plugins.buccaneer.events; import com.atlassian.event.api.EventListener; import com.atlassian.event.api.EventPublisher; import com.atlassian.stash.content.Change; import com.atlassian.stash.event.RepositoryPushEvent; import com.atlassian.stash.history.HistoryService; import com.atlassian.stash.repository.Repository; import com.atlassian.stash.user.Permission; import com.atlassian.stash.user.SecurityService; import com.atlassian.stash.util.Operation; import com.atlassian.stash.util.Page; import com.atlassian.stash.util.PageRequest; import com.atlassian.stash.util.PageRequestImpl; import org.springframework.beans.factory.DisposableBean; public class RepositoryListener implements DisposableBean { private final EventPublisher eventPublisher; private final HistoryService historyService; private final SecurityService securityService; public RepositoryListener(EventPublisher eventPublisher, HistoryService historyService, SecurityService securityService) { this.eventPublisher = eventPublisher; this.historyService = historyService; this.securityService = securityService; eventPublisher.register(this); } @EventListener public void onPushEvent(RepositoryPushEvent event) { final Repository repository = event.getRepository(); securityService.doWithPermission("changeset-indexing", Permission.REPO_READ, new Operation<Void, RuntimeException>() { @Override public Void perform() throws RuntimeException { indexRepository(repository); return null; } }); } private void indexRepository(Repository repository) { PageRequest pageRequest = new PageRequestImpl(0, 1); final Page<Change> changes = historyService.getChanges(repository, "", "", pageRequest); for (Change change : changes.getValues()) { } } @Override public void destroy() throws Exception { eventPublisher.unregister(this); } }
bsd-3-clause
lutece-platform/lutece-core
src/java/fr/paris/lutece/portal/service/search/LuceneSearchEngine.java
12912
/* * Copyright (c) 2002-2022, City of Paris * 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 * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice * and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * License 1.0 */ package fr.paris.lutece.portal.service.search; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.lucene.document.DateTools; import org.apache.lucene.document.DateTools.Resolution; import org.apache.lucene.document.Document; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.queryparser.classic.QueryParserBase; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TermRangeQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.util.BytesRef; import fr.paris.lutece.portal.business.page.Page; import fr.paris.lutece.portal.service.security.LuteceUser; import fr.paris.lutece.portal.service.security.SecurityService; import fr.paris.lutece.portal.service.util.AppLogService; import fr.paris.lutece.util.date.DateUtil; /** * LuceneSearchEngine */ public class LuceneSearchEngine implements SearchEngine { public static final int MAX_RESPONSES = 1000000; private static final String PARAMETER_TYPE_FILTER = "type_filter"; private static final String PARAMETER_DATE_AFTER = "date_after"; private static final String PARAMETER_DATE_BEFORE = "date_before"; private static final String PARAMETER_TAG_FILTER = "tag_filter"; private static final String PARAMETER_DEFAULT_OPERATOR = "default_operator"; private static final String PARAMETER_OPERATOR_AND = "AND"; /** * Return search results * * @param strQuery * The search query * @param request * The HTTP request * @return Results as a collection of SearchResult */ public List<SearchResult> getSearchResults( String strQuery, HttpServletRequest request ) { List<Query> listFilter = new ArrayList<>( ); boolean bFilterResult = false; if ( SecurityService.isAuthenticationEnable( ) ) { LuteceUser user = SecurityService.getInstance( ).getRegisteredUser( request ); Query [ ] filtersRole = null; if ( user != null ) { String [ ] userRoles = SecurityService.getInstance( ).getRolesByUser( user ); if ( userRoles != null ) { filtersRole = new Query [ userRoles.length + 1]; for ( int i = 0; i < userRoles.length; i++ ) { Query queryRole = new TermQuery( new Term( SearchItem.FIELD_ROLE, userRoles [i] ) ); filtersRole [i] = queryRole; } } else { bFilterResult = true; } } else { filtersRole = new Query [ 1]; } if ( !bFilterResult ) { Query queryRole = new TermQuery( new Term( SearchItem.FIELD_ROLE, Page.ROLE_NONE ) ); filtersRole [filtersRole.length - 1] = queryRole; BooleanQuery.Builder booleanQueryBuilderRole = new BooleanQuery.Builder( ); Arrays.asList( filtersRole ).stream( ).forEach( filterRole -> booleanQueryBuilderRole.add( filterRole, BooleanClause.Occur.SHOULD ) ); listFilter.add( booleanQueryBuilderRole.build( ) ); } } String [ ] typeFilter = request.getParameterValues( PARAMETER_TYPE_FILTER ); String strDateAfter = request.getParameter( PARAMETER_DATE_AFTER ); String strDateBefore = request.getParameter( PARAMETER_DATE_BEFORE ); Query allFilter = buildFinalFilter( listFilter, strDateAfter, strDateBefore, typeFilter, request.getLocale( ) ); String strTagFilter = request.getParameter( PARAMETER_TAG_FILTER ); return search( strTagFilter, strQuery, allFilter, request, bFilterResult ); } private Query buildFinalFilter( List<Query> listFilter, String strDateAfter, String strDateBefore, String [ ] typeFilter, Locale locale ) { Query filterDate = createFilterDate( strDateAfter, strDateBefore, locale ); if ( filterDate != null ) { listFilter.add( filterDate ); } Query filterType = createFilterType( typeFilter ); if ( filterType != null ) { listFilter.add( filterType ); } Query allFilter = null; if ( CollectionUtils.isNotEmpty( listFilter ) ) { BooleanQuery.Builder booleanQueryBuilder = new BooleanQuery.Builder( ); for ( Query filter : listFilter ) { booleanQueryBuilder.add( filter, BooleanClause.Occur.MUST ); } allFilter = booleanQueryBuilder.build( ); } return allFilter; } private Query createFilterType( String [ ] typeFilter ) { if ( ArrayUtils.isNotEmpty( typeFilter ) && !typeFilter [0].equals( SearchService.TYPE_FILTER_NONE ) ) { BooleanQuery.Builder booleanQueryBuilder = new BooleanQuery.Builder( ); for ( int i = 0; i < typeFilter.length; i++ ) { Query queryType = new TermQuery( new Term( SearchItem.FIELD_TYPE, typeFilter [i] ) ); booleanQueryBuilder.add( queryType, BooleanClause.Occur.SHOULD ); } return booleanQueryBuilder.build( ); } return null; } private Query createFilterDate( String strDateAfter, String strDateBefore, Locale locale ) { boolean bDateAfter = false; boolean bDateBefore = false; if ( StringUtils.isNotBlank( strDateAfter ) || StringUtils.isNotBlank( strDateBefore ) ) { BytesRef strAfter = null; BytesRef strBefore = null; if ( StringUtils.isNotBlank( strDateAfter ) ) { Date dateAfter = DateUtil.formatDate( strDateAfter, locale ); strAfter = new BytesRef( DateTools.dateToString( dateAfter, Resolution.DAY ) ); bDateAfter = true; } if ( StringUtils.isNotBlank( strDateBefore ) ) { Date dateBefore = DateUtil.formatDate( strDateBefore, locale ); strBefore = new BytesRef( DateTools.dateToString( dateBefore, Resolution.DAY ) ); bDateBefore = true; } return new TermRangeQuery( SearchItem.FIELD_DATE, strAfter, strBefore, bDateAfter, bDateBefore ); } return null; } private List<SearchResult> search( String strTagFilter, String strQuery, Query allFilter, HttpServletRequest request, boolean bFilterResult ) { List<SearchItem> listResults = new ArrayList<>( ); try ( Directory directory = IndexationService.getDirectoryIndex( ) ; IndexReader ir = DirectoryReader.open( directory ) ; ) { IndexSearcher searcher = new IndexSearcher( ir ); BooleanQuery.Builder bQueryBuilder = new BooleanQuery.Builder( ); if ( StringUtils.isNotBlank( strTagFilter ) ) { QueryParser parser = new QueryParser( SearchItem.FIELD_METADATA, IndexationService.getAnalyser( ) ); String formatQuery = ( strQuery != null ) ? strQuery : ""; Query queryMetaData = parser.parse( formatQuery ); bQueryBuilder.add( queryMetaData, BooleanClause.Occur.SHOULD ); parser = new QueryParser( SearchItem.FIELD_SUMMARY, IndexationService.getAnalyser( ) ); Query querySummary = parser.parse( formatQuery ); bQueryBuilder.add( querySummary, BooleanClause.Occur.SHOULD ); } else { QueryParser parser = new QueryParser( SearchItem.FIELD_CONTENTS, IndexationService.getAnalyser( ) ); String operator = request.getParameter( PARAMETER_DEFAULT_OPERATOR ); if ( PARAMETER_OPERATOR_AND.equals( operator ) ) { parser.setDefaultOperator( QueryParserBase.AND_OPERATOR ); } Query queryContent = parser.parse( ( StringUtils.isNotBlank( strQuery ) ) ? strQuery : "" ); bQueryBuilder.add( queryContent, BooleanClause.Occur.SHOULD ); } Query query = bQueryBuilder.build( ); if ( allFilter != null ) { BooleanQuery.Builder bQueryBuilderWithFilter = new BooleanQuery.Builder( ); bQueryBuilderWithFilter.add( allFilter, BooleanClause.Occur.FILTER ); bQueryBuilderWithFilter.add( query, BooleanClause.Occur.MUST ); query = bQueryBuilderWithFilter.build( ); } // Get results documents TopDocs topDocs = searcher.search( query, MAX_RESPONSES ); ScoreDoc [ ] hits = topDocs.scoreDocs; for ( int i = 0; i < hits.length; i++ ) { int docId = hits [i].doc; Document document = searcher.doc( docId ); SearchItem si = new SearchItem( document ); if ( ( !bFilterResult ) || ( si.getRole( ).equals( Page.ROLE_NONE ) ) || ( SecurityService.getInstance( ).isUserInRole( request, si.getRole( ) ) ) ) { listResults.add( si ); } } } catch( Exception e ) { AppLogService.error( e.getMessage( ), e ); } return convertList( listResults ); } /** * Convert a list of Lucene items into a list of generic search items * * @param listSource * The list of Lucene items * @return A list of generic search items */ private List<SearchResult> convertList( List<SearchItem> listSource ) { List<SearchResult> listDest = new ArrayList<>( ); for ( SearchItem item : listSource ) { SearchResult result = new SearchResult( ); result.setId( item.getId( ) ); try { result.setDate( DateTools.stringToDate( item.getDate( ) ) ); } catch( ParseException e ) { AppLogService.error( "Bad Date Format for indexed item \"{}\" : {}", item.getTitle( ), e.getMessage( ), e ); } result.setUrl( item.getUrl( ) ); result.setTitle( item.getTitle( ) ); result.setSummary( item.getSummary( ) ); result.setType( item.getType( ) ); listDest.add( result ); } return listDest; } }
bsd-3-clause
edina/lockss-daemon
test/src/org/lockss/protocol/TestPeerIdentity.java
4825
/* * $Id$ */ /* Copyright (c) 2000-2005 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.protocol; import java.io.File; import org.lockss.test.*; import org.lockss.util.*; /** Test case for class: org.lockss.protocol.PeerIdentity */ public class TestPeerIdentity extends LockssTestCase { static String KEY1 = "tcp:[1.1.1.1]:111"; static String KEY2 = "tcp:[1.1.1.1]:112"; private IdentityManager idmgr; protected void setUp() throws Exception { super.setUp(); } private PeerIdentity newPI(String key) throws Exception { return (PeerIdentity)PrivilegedAccessor. invokeConstructor(PeerIdentity.class.getName(), key); } // Ensure getId() returns normalized key public void testGetId() throws Exception { String id1 = "TCP:[1.1.1.1]:111"; assertEquals(id1, newPI(id1).getKey()); assertEquals(id1, newPI("tcp:[01.1.1.1]:111").getKey()); assertEquals(id1, newPI("tcp:[1.1.1.1]:0111").getKey()); assertEquals("TCP:[0:0:0:0:0:0:0:1]:9729", newPI("TCP:[0:0:0:0:0:0:0:1]:9729").getKey()); assertEquals("TCP:[0:0:0:0:0:0:0:1]:9729", newPI("tcp:[::1]:9729").getKey()); assertEquals("TCP:[0:0:0:0:0:0:0:1]:9729", newPI("tcp:[::1]:09729").getKey()); } // ensure that equals() and hashCode() have not been overridden to behave // differently from Object default (identity) public void testEqualsHash() throws Exception { PeerIdentity id1 = newPI(KEY1); PeerIdentity id2 = newPI(KEY1); PeerIdentity id3 = newPI(KEY2); assertNotEquals(id1, id2); assertNotEquals(id1, id3); assertNotEquals(id2, id3); assertEquals(System.identityHashCode(id1), id1.hashCode()); assertEquals(System.identityHashCode(id2), id2.hashCode()); assertEquals(System.identityHashCode(id3), id3.hashCode()); } public void testIsLocal() throws Exception { PeerIdentity id1 = new PeerIdentity(KEY1); PeerIdentity id2 = new PeerIdentity.LocalIdentity(KEY2); assertFalse(id1.isLocalIdentity()); assertTrue(id2.isLocalIdentity()); } public void testSerializationRoundtrip() throws Exception { MockLockssDaemon daemon = getMockLockssDaemon(); String host = "1.2.3.4"; String prop = "org.lockss.localIPAddress="+host; ConfigurationUtil. setCurrentConfigFromUrlList(ListUtil.list(FileTestUtil.urlOfString(prop))); idmgr = daemon.getIdentityManager(); ObjectSerializer serializer = new XStreamSerializer(); ObjectSerializer deserializer = new XStreamSerializer(daemon); File temp1 = File.createTempFile("tmp", ".xml"); temp1.deleteOnExit(); PeerIdentity pidv1 = new PeerIdentity("12.34.56.78"); serializer.serialize(temp1, pidv1); PeerIdentity back1 = (PeerIdentity)deserializer.deserialize(temp1); assertEquals(pidv1.getIdString(), back1.getIdString()); assertEquals(pidv1.getPeerAddress(), back1.getPeerAddress()); File temp3 = File.createTempFile("tmp", ".xml"); temp3.deleteOnExit(); PeerIdentity pidv3 = new PeerIdentity(IDUtil.ipAddrToKey("87.65.43.21", "999")); serializer.serialize(temp3, pidv3); PeerIdentity back3 = (PeerIdentity)deserializer.deserialize(temp3); assertEquals(pidv3.getIdString(), back3.getIdString()); assertEquals(pidv3.getPeerAddress(), back3.getPeerAddress()); } public void testIsV3() throws Exception { PeerIdentity pidv3 = new PeerIdentity("tcp:[1.1.1.1]:111"); assertTrue(pidv3.isV3()); PeerIdentity pidv1 = new PeerIdentity("12.34.56.78"); assertFalse(pidv1.isV3()); } }
bsd-3-clause
NCIP/cagrid-portal
cagrid-portal/portlets/src/java/gov/nih/nci/cagrid/portal/portlet/query/results/QueryResultTableToHSSFWorkbookBuilder.java
2649
/** *============================================================================ * The Ohio State University Research Foundation, The University of Chicago - * Argonne National Laboratory, Emory University, SemanticBits LLC, * and Ekagra Software Technologies Ltd. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cagrid-portal/LICENSE.txt for details. *============================================================================ **/ package gov.nih.nci.cagrid.portal.portlet.query.results; import java.util.List; import gov.nih.nci.cagrid.portal.dao.QueryResultTableDao; import gov.nih.nci.cagrid.portal.domain.table.QueryResultCell; import gov.nih.nci.cagrid.portal.domain.table.QueryResultColumn; import gov.nih.nci.cagrid.portal.domain.table.QueryResultRow; import gov.nih.nci.cagrid.portal.domain.table.QueryResultTable; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class QueryResultTableToHSSFWorkbookBuilder { private QueryResultTableDao queryResultTableDao; public HSSFWorkbook build(Integer tableId){ HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("query_results"); short rowIdx = 0; short colIdx = 0; QueryResultTable table = getQueryResultTableDao().getById(tableId); List<QueryResultColumn> cols = table.getColumns(); List<QueryResultRow> rows = table.getRows(); HSSFRow headerRow = sheet.createRow(rowIdx); for(QueryResultColumn col : cols){ HSSFCell cell = headerRow.createCell(colIdx); cell.setCellValue(col.getName()); colIdx++; } HSSFCell serviceUrlCol = headerRow.createCell(colIdx); serviceUrlCol.setCellValue(ResultConstants.DATA_SERVICE_URL_COL_NAME); rowIdx++; for(QueryResultRow row : rows){ HSSFRow r = sheet.createRow(rowIdx); colIdx = 0; for(QueryResultColumn col : cols){ String value = ""; for(QueryResultCell cell : row.getCells()){ if(cell.getColumn().getId().equals(col.getId())){ value = cell.getValue(); break; } } HSSFCell c = r.createCell(colIdx); c.setCellValue(value); colIdx++; } HSSFCell serviceUrlCell = r.createCell(colIdx); serviceUrlCell.setCellValue(row.getServiceUrl()); rowIdx++; } return workbook; } public QueryResultTableDao getQueryResultTableDao() { return queryResultTableDao; } public void setQueryResultTableDao(QueryResultTableDao queryResultTableDao) { this.queryResultTableDao = queryResultTableDao; } }
bsd-3-clause
mikem2005/vijava
src/com/vmware/vim25/mo/samples/perf/PrintPerfMgr.java
4867
/*================================================================================ Copyright (c) 2008 VMware, Inc. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of VMware, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================*/ package com.vmware.vim25.mo.samples.perf; import java.net.URL; import com.vmware.vim25.ElementDescription; import com.vmware.vim25.PerfCounterInfo; import com.vmware.vim25.PerfInterval; import com.vmware.vim25.PerformanceDescription; import com.vmware.vim25.mo.PerformanceManager; import com.vmware.vim25.mo.ServiceInstance; /** * http://vijava.sf.net * @author Steve Jin */ public class PrintPerfMgr { public static void main(String[] args) throws Exception { if(args.length != 3) { System.out.println("Usage: java PrintPerfMgr " + "<url> <username> <password>"); return; } ServiceInstance si = new ServiceInstance( new URL(args[0]), args[1], args[2], true); PerformanceManager perfMgr = si.getPerformanceManager(); System.out.println("***Print All Descriptions:"); PerformanceDescription pd = perfMgr.getDescription(); printPerfDescription(pd); System.out.println("\n***Print All Historical Intervals:"); PerfInterval[] pis = perfMgr.getHistoricalInterval(); printPerfIntervals(pis); System.out.println("\n***Print All Perf Counters:"); PerfCounterInfo[] pcis = perfMgr.getPerfCounter(); printPerfCounters(pcis); si.getServerConnection().logout(); } static void printPerfIntervals(PerfInterval[] pis) { for(int i=0; pis!=null && i<pis.length; i++) { System.out.println("\nPerfInterval # " + i); StringBuffer sb = new StringBuffer(); sb.append("Name:" + pis[i].getName()); sb.append("\nKey:" + pis[i].getKey()); sb.append("\nLevel:"+ pis[i].getLevel()); sb.append("\nSamplingPeriod:" + pis[i].getSamplingPeriod()); sb.append("\nLength:" + pis[i].getLength()); sb.append("\nEnabled:" + pis[i].isEnabled()); System.out.println(sb); } } static void printPerfCounters(PerfCounterInfo[] pcis) { for(int i=0; pcis!=null && i<pcis.length; i++) { System.out.println("\nKey:" + pcis[i].getKey()); String perfCounter = pcis[i].getGroupInfo().getKey() + "." + pcis[i].getNameInfo().getKey() + "." + pcis[i].getRollupType(); System.out.println("PerfCounter:" + perfCounter); System.out.println("Level:" + pcis[i].getLevel()); System.out.println("StatsType:" + pcis[i].getStatsType()); System.out.println("UnitInfo:" + pcis[i].getUnitInfo().getKey()); } } static void printPerfDescription(PerformanceDescription pd) { ElementDescription[] eds = pd.getCounterType(); printElementDescriptions(eds); ElementDescription[] statsTypes = pd.getStatsType(); printElementDescriptions(statsTypes); } static void printElementDescriptions(ElementDescription[] eds) { for(int i=0; eds!=null && i<eds.length; i++) { printElementDescription(eds[i]); } } static void printElementDescription(ElementDescription ed) { System.out.println("\nKey:" + ed.getKey()); System.out.println("Label:" + ed.getLabel()); System.out.println("Summary:" + ed.getSummary()); } }
bsd-3-clause
mjpan/jdentpro
src/com/winningsmiledental/GUI.java
503
package com.winningsmiledental; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; import org.swixml.*; import org.swixml.SwingEngine; import java.util.*; public interface GUI { public void setAppFrame(ApplicationFrame appFrame); public ApplicationFrame getAppFrame(); public void configure(); public Collection getActionableItems(); public JPanel getPane(); public Executioner getExecutioner(); }
bsd-3-clause
groupon/monsoon
lib/src/main/java/com/groupon/lex/metrics/lib/LazyEval.java
1810
package com.groupon.lex.metrics.lib; import static java.util.Objects.requireNonNull; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; /** * Lazy evaluation wrapper. * * Given a supplier (or function with arguments) it will: - invoke the function * exactly once to retrieve the result (upon first access) - use the retrieved * value on subsequence access. * * The exception is if the argument throws an exception or is null. * * @author ariane */ public class LazyEval<T> implements Supplier<T> { private Supplier<? extends T> actual_; private volatile T value_ = null; public static <T> LazyEval<T> byValue(T v) { LazyEval<T> result = new LazyEval<>(() -> v); result.value_ = v; return result; } public LazyEval(Supplier<? extends T> actual) { actual_ = requireNonNull(actual); } public <X> LazyEval(Function<? super X, ? extends T> fn, X arg) { this(() -> fn.apply(arg)); } public <X, Y> LazyEval(BiFunction<? super X, ? super Y, ? extends T> fn, X x, Y y) { this(() -> fn.apply(x, y)); } public <X, Y, Z> LazyEval(TriFunction<? super X, ? super Y, ? super Z, ? extends T> fn, X x, Y y, Z z) { this(() -> fn.apply(x, y, z)); } @Override public T get() { if (value_ == null) { synchronized (this) { if (value_ == null) { value_ = actual_.get(); if (value_ != null) actual_ = null; // Drop dependant data when no longer needed. } } } return value_; } public Optional<T> getIfPresent() { return Optional.ofNullable(value_); } }
bsd-3-clause
wdv4758h/ZipPy
edu.uci.python.nodes/src/edu/uci/python/nodes/statement/ExceptNode.java
3606
/* * Copyright (c) 2013, Regents of the University of California * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.uci.python.nodes.statement; import org.python.core.*; import com.oracle.truffle.api.frame.*; import com.oracle.truffle.api.nodes.*; import edu.uci.python.nodes.*; import edu.uci.python.nodes.frame.*; import edu.uci.python.runtime.*; /** * @author Gulfem */ public class ExceptNode extends StatementNode { @Child protected PNode body; @Children private final PNode[] exceptType; @Child protected PNode exceptName; private final PythonContext context; public ExceptNode(PythonContext context, PNode body, PNode[] exceptType, PNode exceptName) { this.body = body; this.exceptName = exceptName; this.exceptType = exceptType; this.context = context; } protected Object executeExcept(VirtualFrame frame, RuntimeException excep) { PyException e = null; if (excep instanceof PyException) { e = (PyException) excep; } else if (excep instanceof ArithmeticException && excep.getMessage().endsWith("divide by zero")) { e = Py.ZeroDivisionError("divide by zero"); } else { throw excep; } context.setCurrentException(e); /** * TODO: need to support exceptType instance of type e.g. 'divide by zero' instance of * 'Exception' * * TODO: need to make exception messages consistent with Python 3.3 e.g. 'division by zero' */ if (exceptType != null) { PyObject type = null; for (int i = 0; i < exceptType.length && type != e.type; i++) { type = (PyObject) exceptType[i].execute(frame); } if (e.type == type) { if (exceptName != null) { ((WriteNode) exceptName).executeWrite(frame, e); } } else { throw excep; } } body.execute(frame); // clear the exception after executing the except body. context.setCurrentException(null); throw new ControlFlowException(); } @Override public Object execute(VirtualFrame frame) { // TODO Auto-generated method stub return null; } }
bsd-3-clause
NCIP/cadsr-cgmdr-nci-uk
test/src/org/exist/storage/RemoveTest.java
5882
/*L * Copyright Oracle Inc * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details. */ /* * eXist Open Source Native XML Database * Copyright (C) 2001-04 The eXist Project * http://exist-db.org * * 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 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 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.storage; import java.io.StringReader; import junit.textui.TestRunner; import org.exist.collections.IndexInfo; import org.exist.dom.DocumentImpl; import org.exist.dom.DocumentSet; import org.exist.security.SecurityManager; import org.exist.security.xacml.AccessContext; import org.exist.storage.lock.Lock; import org.exist.storage.serializers.Serializer; import org.exist.storage.txn.TransactionManager; import org.exist.storage.txn.Txn; import org.exist.test.TestConstants; import org.exist.xupdate.Modification; import org.exist.xupdate.XUpdateProcessor; import org.xml.sax.InputSource; public class RemoveTest extends AbstractUpdateTest { public static void main(String[] args) { TestRunner.run(RemoveTest.class); } public void testUpdate() { BrokerPool.FORCE_CORRUPTION = true; BrokerPool pool = null; DBBroker broker = null; try { pool = startDB(); assertNotNull(pool); broker = pool.get(SecurityManager.SYSTEM_USER); assertNotNull(broker); TransactionManager mgr = pool.getTransactionManager(); assertNotNull(mgr); IndexInfo info = init(broker, mgr); assertNotNull(info); DocumentSet docs = new DocumentSet(); docs.add(info.getDocument()); XUpdateProcessor proc = new XUpdateProcessor(broker, docs, AccessContext.TEST); assertNotNull(proc); Txn transaction = mgr.beginTransaction(); assertNotNull(transaction); System.out.println("Transaction started ..."); String xupdate; Modification modifications[]; // append some new element to records for (int i = 1; i <= 50; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:append select=\"/products\">" + " <product>" + " <xu:attribute name=\"id\"><xu:value-of select=\"count(/products/product) + 1\"/></xu:attribute>" + " <description>Product " + i + "</description>" + " <price>" + (i * 2.5) + "</price>" + " <stock>" + (i * 10) + "</stock>" + " </product>" + " </xu:append>" + "</xu:modifications>"; proc.setBroker(broker); proc.setDocumentSet(docs); modifications = proc.parse(new InputSource(new StringReader(xupdate))); assertNotNull(modifications); modifications[0].process(transaction); proc.reset(); } mgr.commit(transaction); System.out.println("Transaction commited ..."); Serializer serializer = broker.getSerializer(); serializer.reset(); DocumentImpl doc = broker.getXMLResource(TestConstants.TEST_COLLECTION_URI2.append(TestConstants.TEST_XML_URI), Lock.READ_LOCK); assertNotNull("Document '" + DBBroker.ROOT_COLLECTION + "/test/test2/test.xml' should not be null", doc); String data = serializer.serialize(doc); System.out.println(data); doc.getUpdateLock().release(Lock.READ_LOCK); // the following transaction will not be committed and thus undone during recovery transaction = mgr.beginTransaction(); System.out.println("Transaction started ..."); // remove elements for (int i = 1; i <= 25; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:remove select=\"/products/product[last()]\"/>" + "</xu:modifications>"; proc.setBroker(broker); proc.setDocumentSet(docs); modifications = proc.parse(new InputSource(new StringReader(xupdate))); assertNotNull(modifications); modifications[0].process(transaction); proc.reset(); } // Don't commit... pool.getTransactionManager().getJournal().flushToLog(true); System.out.println("Transaction interrupted ..."); } catch (Exception e) { fail(e.getMessage()); } finally { pool.release(broker); } } }
bsd-3-clause
8v060htwyc/whois
whois-nrtm/src/main/java/net/ripe/db/whois/nrtm/NrtmServer.java
3491
package net.ripe.db.whois.nrtm; import net.ripe.db.whois.common.ApplicationService; import net.ripe.db.whois.common.MaintenanceMode; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.net.InetSocketAddress; import java.util.concurrent.Executors; // TODO: [ES] refactor use of two variables (one static) for port number @Component public class NrtmServer implements ApplicationService { private static final Logger LOGGER = LoggerFactory.getLogger(NrtmServer.class); public static final int NRTM_VERSION = 3; @Value("${nrtm.enabled}") private boolean nrtmEnabled; @Value("${port.nrtm}") private int nrtmPort; @Value("${loadbalancer.nrtm.timeout:5000}") private int markNodeFailedTimeout; private final NrtmChannelsRegistry nrtmChannelsRegistry; private final NrtmServerPipelineFactory nrtmServerPipelineFactory; private final MaintenanceMode maintenanceMode; private Channel serverChannel; private static int port; @Autowired public NrtmServer(final NrtmChannelsRegistry nrtmChannelsRegistry, final NrtmServerPipelineFactory nrtmServerPipelineFactory, final MaintenanceMode maintenanceMode) { this.nrtmChannelsRegistry = nrtmChannelsRegistry; this.nrtmServerPipelineFactory = nrtmServerPipelineFactory; this.maintenanceMode = maintenanceMode; } @Override public void start() { if (!nrtmEnabled) { LOGGER.warn("NRTM not enabled"); return; } serverChannel = bootstrapChannel(nrtmServerPipelineFactory, nrtmPort, "NRTM DUMMIFIER"); port = ((InetSocketAddress) serverChannel.getLocalAddress()).getPort(); } private Channel bootstrapChannel(final ChannelPipelineFactory serverPipelineFactory, final int port, final String instanceName) { final ChannelFactory channelFactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); final ServerBootstrap bootstrap = new ServerBootstrap(channelFactory); bootstrap.setPipelineFactory(serverPipelineFactory); bootstrap.setOption("backlog", 200); bootstrap.setOption("child.keepAlive", true); final Channel channel = bootstrap.bind(new InetSocketAddress(port)); final int actualPort = ((InetSocketAddress) channel.getLocalAddress()).getPort(); LOGGER.info("NRTM server listening on port {} ({})", actualPort, instanceName); return channel; } @Override public void stop(final boolean force) { if (nrtmEnabled) { if (force) { LOGGER.info("Shutting down"); if (serverChannel != null) { serverChannel.close(); serverChannel = null; } nrtmChannelsRegistry.closeChannels(); } else { maintenanceMode.setShutdown(); } } } public static int getPort() { return port; } }
bsd-3-clause
WestTorranceRobotics/WestTorranceSwagbotics2017
src/org/usfirst/frc5124/WestTorranceSwagbotics2017/commands/AgitatorAutoStop.java
683
package org.usfirst.frc5124.WestTorranceSwagbotics2017.commands; import org.usfirst.frc5124.WestTorranceSwagbotics2017.Robot; import edu.wpi.first.wpilibj.command.Command; public class AgitatorAutoStop extends Command { public AgitatorAutoStop() { requires(Robot.agitator); /* Uses the agitator subsystem */ } protected void initialize() { Robot.agitator.stop(); /* Stop the agitator */ } protected void execute() { } protected boolean isFinished() { return true; /* Immediately end. For use in command groups, auto specifically */ } protected void end() { } protected void interrupted() { } }
bsd-3-clause
NCIP/cagrid-core
caGrid/projects/data/src/java/common/gov/nih/nci/cagrid/data/ServiceParametersConstants.java
1012
/** *============================================================================ * Copyright The Ohio State University Research Foundation, The University of Chicago - * Argonne National Laboratory, Emory University, SemanticBits LLC, and * Ekagra Software Technologies Ltd. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cagrid-core/LICENSE.txt for details. *============================================================================ **/ package gov.nih.nci.cagrid.data; public interface ServiceParametersConstants { // data service specific service parameters public static final String DATA_SERVICE_PARAMS_PREFIX = "dataService"; public static final String CLASS_MAPPINGS_FILENAME = DATA_SERVICE_PARAMS_PREFIX + "_classMappingsFilename"; public static final String CLASS_TO_QNAME_XML = "classToQname.xml"; // the server-config.wsdd location public static final String SERVER_CONFIG_LOCATION = "serverConfigLocation"; }
bsd-3-clause
lockss/lockss-daemon
plugins/src/org/lockss/plugin/cloudpublish/CloudPublishUrlConsumerFactory.java
4250
/* Copyright (c) 2000-2021 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.plugin.cloudpublish; import org.apache.commons.lang3.StringUtils; import org.lockss.daemon.Crawler; import org.lockss.plugin.AuUtil; import org.lockss.plugin.FetchedUrlData; import org.lockss.plugin.UrlConsumer; import org.lockss.plugin.UrlConsumerFactory; import org.lockss.plugin.base.HttpToHttpsUrlConsumer; import org.lockss.util.Logger; import org.lockss.util.UrlUtil; public class CloudPublishUrlConsumerFactory implements UrlConsumerFactory { private static final Logger log = Logger.getLogger(CloudPublishUrlConsumerFactory.class); public static final String READ_ITEM_TYPE = "read/?item_type=journal_article&item_id="; @Override public UrlConsumer createUrlConsumer(Crawler.CrawlerFacade crawlFacade, FetchedUrlData fud) { return new CloudPublishUrlConsumer(crawlFacade, fud); } public class CloudPublishUrlConsumer extends HttpToHttpsUrlConsumer { public CloudPublishUrlConsumer(Crawler.CrawlerFacade facade, FetchedUrlData fud) { super(facade, fud); } /** * <p> * Determines if the URL is to be stored under its redirect chain's origin * URL. * * http://dev-liverpoolup.cloudpublish.co.uk/read/?item_type=journal_article&item_id=20082 * * http://dev-liverpoolup.cloudpublish.co.uk/read/?item_type=journal_article&item_id=20194&mode=download * --> * https://liverpoolup.cloudpublish.co.uk/read/?id=20082&type=journal_article&cref=LUP0923&peref=&drm=soft&acs=1&exit=http%3A%2F%2Fdev-liverpoolup.cloudpublish.co.uk%2Fjournals%2Farticle%2F20082%2F&p=6&uid=LUP&t=1639011561&h=fece739719aad172763a1aa10664d1c2 * </p> * */ public boolean shouldStoreAtOrigUrl() { boolean should = false; should = fud.origUrl.contains(READ_ITEM_TYPE);; if (AuUtil.isBaseUrlHttp(au) && fud.redirectUrls != null && fud.redirectUrls.size() >= 1 && UrlUtil.isHttpUrl(fud.origUrl) && UrlUtil.isHttpsUrl(fud.fetchUrl) && !should) { String origBase = StringUtils.substringBefore(UrlUtil.stripProtocol(fud.origUrl),"?"); String fetchBase = StringUtils.substringBefore(UrlUtil.stripProtocol(fud.fetchUrl),"?"); should = ( origBase.equals(fetchBase) || origBase.equals(fetchBase.replaceFirst("/doi/[^/]+/", "/doi/")) || origBase.replaceFirst("/doi/[^/]+/", "/doi/").equals(fetchBase.replaceFirst("/doi/[^/]+/", "/doi/")) || origBase.equals(fetchBase.replace("%2F","/"))); if (fud.redirectUrls != null) { log.debug3("BA redirect " + fud.redirectUrls.size() + ": " + fud.redirectUrls.toString()); log.debug3("BA redirect: " + " " + fud.origUrl + " to " + fud.fetchUrl + " should consume?: " + should); } } return should; } } }
bsd-3-clause
iig-uni-freiburg/SWAT20
src/de/uni/freiburg/iig/telematik/swat/patterns/gui/ParaValuePanelFactory.java
977
package de.uni.freiburg.iig.telematik.swat.patterns.gui; import de.uni.freiburg.iig.telematik.swat.patterns.logic.patterns.parameter.Parameter; import de.uni.freiburg.iig.telematik.swat.patterns.logic.patterns.parameter.ParameterTypeNames; public class ParaValuePanelFactory { public static ParameterValuePanel createPanel(Object selectedItem, Parameter parameter) { String parameterTypeStr = (String) selectedItem; parameter.setValue(parameterTypeStr); //comment to load parameter correctly. But: Breaks Dropdown listener ParameterValuePanel panel = null; if (parameterTypeStr.equals(ParameterTypeNames.STATEPREDICATE)) { panel = new StatePredicateParamValuePanel(parameter); } else if (parameterTypeStr.equals(ParameterTypeNames.NUMBER)) { panel = new NumberParamValuePanel(parameter); } else { //panel = new StandardParamValuePanel(parameter, parameterTypeStr); panel = new StandardParamValuePanel(parameter); } return panel; } }
bsd-3-clause
avast/kafka-tests
src/main/java/com/avast/kafkatests/othertests/nosuchtopic/NoSuchTopicTest.java
2154
package com.avast.kafkatests.othertests.nosuchtopic; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.StringSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Properties; /** * Test of sending to a topic that does not exist while automatic creation of topics is disabled in Kafka (auto.create.topics.enable=false). */ public class NoSuchTopicTest { private static final Logger LOGGER = LoggerFactory.getLogger(NoSuchTopicTest.class); public static void main(String[] args) { Properties properties = new Properties(); properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); properties.setProperty(ProducerConfig.CLIENT_ID_CONFIG, NoSuchTopicTest.class.getSimpleName()); properties.setProperty(ProducerConfig.MAX_BLOCK_MS_CONFIG, "1000"); // Default is 60 seconds try (Producer<String, String> producer = new KafkaProducer<>(properties, new StringSerializer(), new StringSerializer())) { LOGGER.info("Sending message"); producer.send(new ProducerRecord<>("ThisTopicDoesNotExist", "key", "value"), (metadata, exception) -> { if (exception != null) { LOGGER.error("Send failed: {}", exception.toString()); } else { LOGGER.info("Send successful: {}-{}/{}", metadata.topic(), metadata.partition(), metadata.offset()); } }); LOGGER.info("Sending message"); producer.send(new ProducerRecord<>("ThisTopicDoesNotExistToo", "key", "value"), (metadata, exception) -> { if (exception != null) { LOGGER.error("Send failed: {}", exception.toString()); } else { LOGGER.info("Send successful: {}-{}/{}", metadata.topic(), metadata.partition(), metadata.offset()); } }); } } }
bsd-3-clause
cdegroot/sgame
src/main/java/jgame/tutorial/Example9.java
5486
package jgame.tutorial; import jgame.*; import jgame.platform.*; /** Tutorial example 9: Using OpenGL. Demostrates opengl-specific features. */ public class Example9 extends JGEngine { public static void main(String [] args) { // Listens to command line parameters [width] [height]. // By default it starts as full-screen. //new Example9(StdGame.parseSizeArgs(args,0)); new Example9(new JGPoint(640,480)); } /** Application constructor. */ public Example9(JGPoint size) { initEngine(size.x,size.y); } /** Applet constructor. */ public Example9() { initEngineApplet(); } public void initCanvas() { setCanvasSettings(40,30,16,16,null,null,null); } public void initGame() { // set video synced mode, consider 35 frames per second to be the // "normal" speed. setFrameRate(35,1); setVideoSyncedUpdate(true); // load some nice translucent images defineImage("neon1","-",0,"diamond1.png","-"); defineImage("neon2","-",0,"diamond2.png","-"); defineImage("neon3","-",0,"diamond3.png","-"); // define background images for 4 layers of parallax scroll defineImage("bgimage","-",0,"twirly-192-rev-trans2.png","-"); defineImage("bgimage-sm","-",0,"twirly-192-trans-sm.png","-"); defineImage("bgimage-sm2","-",0,"twirly-192-trans-smsm.png","-"); defineImage("bgimage-text","-",0,"parallax-illustration.png","-"); setBGImage("bgimage"); setBGImage(1,"bgimage-text",false,false); setBGImage(2,"bgimage-sm",true,true); setBGImage(3,"bgimage-sm2",true,true); // define colour behind lowest layer setBGColor(JGColor.yellow); // create some objects for (int i=0; i<25; i++) new NeonObject(); // make the objects wrap around nicely setPFWrap(true,true,-50,-50); setPFSize(46,36); } // a translucent rotating zooming object class NeonObject extends JGObject { int type; double rot=0, rotinc; NeonObject() { super("neon",true,random(0,viewWidth()-50),random(0,viewHeight()-50), 1,null, random(-2,2),random(-2,2)); rotinc = random(-0.07,0.07); type = random(1,3,1); } public void move() { // we may be running at variable frame rate: ensure that rotation // speed is constant by multiplying with gamespeed. rot += rotinc*getGameSpeed(); } public void paint() { // blend mode is: source multiplier: alpha/destination multiplier: 1 setBlendMode(1,0); // the extended openGL drawImage method drawImage(x, y, "neon"+type, /* regular image parameters */ new JGColor(1.0,1.0,1.0), /* blend colour */ 0.5, /* alpha */ rot, /* rotation */ 1.0 + 0.15*Math.sin(rot*4.3), /* zoom */ true /* relative to playfield */ ); } } double zoom=1.0; double rotate=0; public void doFrame() { // scroll the different layers setViewOffset((int)(200*Math.sin(rot)),(int)(200*Math.cos(rot)), false); setBGImgOffset(1,-getMouseX(),-getMouseY(),false); setBGImgOffset(2,(200*Math.sin(rot))/2,(200*Math.cos(rot))/2, false); setBGImgOffset(3,(200*Math.sin(rot))/4,(200*Math.cos(rot))/4, false); // move the neon objects moveObjects(null,0); // increment the scroll animation rot += getGameSpeed()*0.01; // key handing if (getKey('V')) { setVideoSyncedUpdate(!getVideoSyncedUpdate()); clearKey('V'); } if (getKey(27)) { exitEngine("User exit"); } // create zoom/rotate effect with mouse button if (getMouseButton(1)) { zoom += 0.02; rotate += 0.01; } else { if (zoom>1.0) zoom -= 0.02; if (zoom<1.0) zoom = 1.0; if (rotate>0) rotate -= 0.01; if (rotate<0) rotate = 0.0; } setViewZoomRotate(zoom,rotate); } double [] xpos = new double [5]; double [] ypos = new double [5]; double rot = 0.0; public void paintFrame() { // colour to use in case we do not have the gradient function setColor(JGColor.blue); setStroke(3.0); // blend mode is: source multiplier: alpha, destination multiplier: 1 setBlendMode(1,0); // draw rectangle with gradient drawRect(viewWidth()/2,180,400,150,true,true,false, new JGColor[] { JGColor.yellow, JGColor.red, JGColor.magenta, JGColor.blue}); // draw polygons with gradient int i=0; for (double r=rot; r<rot+Math.PI*2.0; r += Math.PI*2.001/5.0) { xpos[i] = viewWidth()*(0.5 + 0.25 *Math.sin(r)); ypos[i++] = viewHeight()*(0.5 + 0.4 *Math.cos(r)); } drawPolygon(xpos,ypos, new JGColor [] { JGColor.blue, JGColor.red, JGColor.magenta, JGColor.cyan, JGColor.yellow }, xpos.length, true, false); i=0; for (double r=-rot; r<-rot+Math.PI*2.0; r += Math.PI*2.001/5.0) { xpos[i] = viewWidth()*(0.5 + 0.3 *Math.sin(r)); ypos[i++] = viewHeight()*(0.5 + 0.45 *Math.cos(r)); } drawPolygon(xpos,ypos, new JGColor [] { JGColor.blue, JGColor.red, JGColor.magenta, JGColor.cyan, JGColor.yellow }, xpos.length, false, false); // display some information setFont(new JGFont("arial",0,15)); setColor(new JGColor(0,0.2,0,0.8)); drawString("Back-end used: " + (isOpenGL() ? "OpenGL" : "AWT" ), viewWidth()/2,135,0); if (isOpenGL()) { drawString("Press 'V' to switch between normal and video synced.", viewWidth()/2,160,0); } else { drawString("(No video synced mode available in AWT)", viewWidth()/2,160,0); } setFont(new JGFont("arial",0,25)); drawString("Video synced now: "+ (getVideoSyncedUpdate() ?"ON":"OFF"), viewWidth()/2,200,0); } }
bsd-3-clause
marian-adamjak/ExpressionEvaluator
src/main/java/net/adamjak/math/expressionevaluator/variables/VariableValue.java
5243
/* * Copyright (c) 2016, Marian Adamjak * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.adamjak.math.expressionevaluator.variables; import net.adamjak.math.expressionevaluator.results.ResultSimple; import net.adamjak.math.expressionevaluator.exceptions.VariableContentException; import net.adamjak.utils.Utils; import net.adamjak.utils.validators.ObjectNotNull; import net.adamjak.utils.validators.StringNotNullAndEmpty; /** * * @author Marian Adamjak */ public class VariableValue { private final String name; private final String textContent; private final Number numberContent; private final Boolean booleanContent; private final VariableValueType type; public VariableValue(String name, String textContent) { Utils.validateInput(name, StringNotNullAndEmpty.getInstance(), NullPointerException.class, "Name can not be null or empty"); Utils.validateInput(textContent,ObjectNotNull.getInstance() , NullPointerException.class, "TextContent can not be null"); this.name = name; this.textContent = textContent; this.numberContent = null; this.booleanContent = null; this.type = VariableValueType.TEXT; } public VariableValue(String name, Number numberContent) { Utils.validateInput(name, StringNotNullAndEmpty.getInstance(), NullPointerException.class, "Name can not be null or empty"); Utils.validateInput(numberContent,ObjectNotNull.getInstance() , NullPointerException.class, "NumberContent can not be null"); this.name = name; this.textContent = null; this.numberContent = numberContent; this.booleanContent = null; this.type = VariableValueType.NUMBER; } public VariableValue(String name, Boolean booleanContent) { Utils.validateInput(name, StringNotNullAndEmpty.getInstance(), NullPointerException.class, "Name can not be null or empty"); Utils.validateInput(booleanContent,ObjectNotNull.getInstance() , NullPointerException.class, "BooleanContent can not be null"); this.name = name; this.textContent = null; this.numberContent = null; this.booleanContent = booleanContent; this.type = VariableValueType.BOOLEAN; } public String getName() { return name; } public String getTextContent() throws VariableContentException { if(this.type != VariableValueType.TEXT){ throw new VariableContentException("Content is not text"); } return textContent; } public Number getNumberContent() throws VariableContentException { if(this.type != VariableValueType.NUMBER){ throw new VariableContentException("Content is not number"); } return numberContent; } public Boolean getBooleanContent() throws VariableContentException { if(this.type != VariableValueType.BOOLEAN){ throw new VariableContentException("Content is not boolean"); } return booleanContent; } public VariableValueType getType() { return type; } public ResultSimple getResult(int sourceStartPosition, int sourceLenght){ switch (this.type){ case NUMBER: return new ResultSimple(numberContent, sourceStartPosition, sourceLenght); case TEXT: return new ResultSimple(textContent, sourceStartPosition, sourceLenght); case BOOLEAN: return new ResultSimple(booleanContent, sourceStartPosition, sourceLenght); default: throw new IllegalStateException("Content is not implemented: " + this.type.name()); } } }
bsd-3-clause
jolicloud/exponent
android/app/src/main/java/abi10_0_0/host/exp/exponent/modules/api/components/svg/RNSVGCircleShadowNode.java
1881
/** * Copyright (c) 2015-present, Horcrux. * All rights reserved. * * This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. */ package abi10_0_0.host.exp.exponent.modules.api.components.svg; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import abi10_0_0.com.facebook.react.uimanager.annotations.ReactProp; /** * Shadow node for virtual RNSVGPath view */ public class RNSVGCircleShadowNode extends RNSVGPathShadowNode { private String mCx; private String mCy; private String mR; @ReactProp(name = "cx") public void setCx(String cx) { mCx = cx; markUpdated(); } @ReactProp(name = "cy") public void setCy(String cy) { mCy = cy; markUpdated(); } @ReactProp(name = "r") public void setR(String r) { mR = r; markUpdated(); } @Override public void draw(Canvas canvas, Paint paint, float opacity) { mPath = getPath(canvas, paint); super.draw(canvas, paint, opacity); } @Override protected Path getPath(Canvas canvas, Paint paint) { Path path = new Path(); float cx = PropHelper.fromPercentageToFloat(mCx, mCanvasWidth, 0, mScale); float cy = PropHelper.fromPercentageToFloat(mCy, mCanvasHeight, 0, mScale); float r; if (PropHelper.isPercentage(mR)) { r = PropHelper.fromPercentageToFloat(mR, 1, 0, 1); float powX = (float)Math.pow((mCanvasWidth * r), 2); float powY = (float)Math.pow((mCanvasHeight * r), 2); r = (float)Math.sqrt(powX + powY) / (float)Math.sqrt(2); } else { r = Float.parseFloat(mR) * mScale; } path.addCircle(cx, cy, r, Path.Direction.CW); return path; } }
bsd-3-clause
openxc/nonstandard-android-measurements
src/com/openxc/measurements/FrontWasherStatus.java
529
package com.openxc.measurements; import com.openxc.units.Boolean; /** * FrontWasherStatus Measure is true when the wiper/windshield washer is on */ public class FrontWasherStatus extends BaseMeasurement<Boolean> { public final static String ID = "front_washer_splash"; public FrontWasherStatus(Boolean value) { super(value); } public FrontWasherStatus(java.lang.Boolean value) { this(new Boolean(value)); } @Override public String getGenericName() { return ID; } }
bsd-3-clause
aic-sri-international/aic-expresso
src/main/java/com/sri/ai/grinder/interpreter/SamplingIfNeededMultiQuantifierEliminator.java
5432
/* * Copyright (c) 2017, SRI International * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the aic-expresso nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sri.ai.grinder.interpreter; import java.util.Random; import com.sri.ai.expresso.api.Expression; import com.sri.ai.expresso.api.Type; import com.sri.ai.grinder.api.Context; import com.sri.ai.grinder.api.MultiQuantifierEliminationProblem; import com.sri.ai.grinder.core.solver.AbstractMultiQuantifierEliminator; import com.sri.ai.grinder.core.solver.MeasurableMultiQuantifierEliminationProblem; import com.sri.ai.grinder.helper.GrinderUtil; import com.sri.ai.grinder.rewriter.api.Rewriter; /** * A quantifier eliminator that decides whether to use brute force or sampling * depending on sample size, domain size, and a "always-sample" parameter. */ public class SamplingIfNeededMultiQuantifierEliminator extends AbstractMultiQuantifierEliminator { protected TopRewriterUsingContextAssignments topRewriterUsingContextAssignments; private int sampleSize; private boolean alwaysSample; private Random random; private BruteForceMultiQuantifierEliminator bruteForce; private SamplingWithFixedSampleSizeSingleQuantifierEliminator sampling; public SamplingIfNeededMultiQuantifierEliminator( TopRewriterUsingContextAssignments topRewriterUsingContextAssignments, int sampleSize, boolean alwaysSample, Rewriter indicesConditionEvaluator, Random random) { this.topRewriterUsingContextAssignments = topRewriterUsingContextAssignments; this.sampleSize = sampleSize; this.alwaysSample = alwaysSample; this.random = random; } private BruteForceMultiQuantifierEliminator getBruteForce() { if (bruteForce == null) { bruteForce = new BruteForceMultiQuantifierEliminator(topRewriterUsingContextAssignments); } return bruteForce; } private SamplingWithFixedSampleSizeSingleQuantifierEliminator getSampling() { if (sampling == null) { sampling = new SamplingWithFixedSampleSizeSingleQuantifierEliminator(topRewriterUsingContextAssignments, sampleSize, random); } return sampling; } @Override public Expression solve(MultiQuantifierEliminationProblem problem, Context context) { // we create a measurable problem here so that the measure is computed inside it only once and reused afterwards. MeasurableMultiQuantifierEliminationProblem measurableProblem = new MeasurableMultiQuantifierEliminationProblem(problem); boolean sample = decideWhetherToSample(measurableProblem, context); Expression result = solve(sample, measurableProblem, context); return result; } private boolean decideWhetherToSample(MeasurableMultiQuantifierEliminationProblem problem, Context context) { boolean sample; if (problem.getIndices().size() == 1) { sample = samplingIsCheaper(problem, context); } else { sample = false; } return sample; } private Expression solve(boolean sample, MeasurableMultiQuantifierEliminationProblem problem, Context context) { Expression result; if (sample) { result = getSampling().solve(problem, context); } else { result = getBruteForce().solve(problem, context); } return result; } private boolean samplingIsCheaper(MeasurableMultiQuantifierEliminationProblem problem, Context context) { boolean result = alwaysSample || domainIsContinuousOrDiscreteAndLargerThanSampleSize(problem, context); return result; } private boolean domainIsContinuousOrDiscreteAndLargerThanSampleSize(MeasurableMultiQuantifierEliminationProblem problem, Context context) { Type type = GrinderUtil.getTypeOfExpression(problem.getIndices().get(0), context); boolean result = type == null || !type.isDiscrete() || problem.getMeasure(context).compareTo(sampleSize) > 0; return result; } }
bsd-3-clause
synergynet/synergynet3.1
synergynet3.1-parent/synergynet3-appsystem-core/src/main/java/synergynet3/behaviours/collision/CollisionCircleAnimationElement.java
3848
package synergynet3.behaviours.collision; import java.util.HashMap; import java.util.Map.Entry; import multiplicity3.csys.animation.elements.AnimationElement; import multiplicity3.csys.items.item.IItem; import synergynet3.additionalUtils.AdditionalSynergyNetUtilities; /** * Repositions an item when flick using the JME animation system. Calculates * trajectories when an item bounces off a display border and detects when an * item should be transferred. Initiates network transfers when required. */ public class CollisionCircleAnimationElement extends AnimationElement { /** * Objects for the item to collide with */ private HashMap<IItem, Float> collidables = new HashMap<IItem, Float>(); /** * Item is currently colliding with. */ private HashMap<IItem, Boolean> collidingWith = new HashMap<IItem, Boolean>(); /** * Used to stop further calculations when an item when an item is to be * transferred or has stopped moving. */ private boolean finished; /** * The item which is being managed by this class. */ private IItem item; /** * Creates an animation element for the supplied item which can then create * the flick motion by repositioning the managed item using JME's animation * system. * * @param item * The item to be influenced by this animation. * @param stage * The stage the item currently resides in. */ public CollisionCircleAnimationElement(IItem item) { this.item = item; } /** * @param collidables * the collidables to set */ public void addCollidable(IItem item, Float radius) { collidables.put(item, radius); collidingWith.put(item, false); } /* * (non-Javadoc) * @see * multiplicity3.csys.animation.elements.AnimationElement#elementStart(float * ) */ @Override public void elementStart(float tpf) { } /* * (non-Javadoc) * @see multiplicity3.csys.animation.elements.AnimationElement#isFinished() */ @Override public boolean isFinished() { return finished; } /** * @param collidables * the collidable item to remove */ public void removeCollidable(IItem item) { collidables.remove(item); collidingWith.remove(item); } /* * (non-Javadoc) * @see multiplicity3.csys.animation.elements.AnimationElement#reset() */ @Override public void reset() { finished = true; } /* * (non-Javadoc) * @see * multiplicity3.csys.animation.elements.AnimationElement#updateAnimationState * (float) */ @Override public void updateAnimationState(float tpf) { if (!finished) { for (Entry<IItem, Float> entry : collidables.entrySet()) { if (collidingWith.get(entry.getKey())) { if (!AdditionalSynergyNetUtilities.inRadius(item.getRelativeLocation(), entry.getKey().getRelativeLocation(), entry.getValue())) { collidingWith.put(entry.getKey(), false); onLeavingCollision(entry.getKey()); } } else { if (AdditionalSynergyNetUtilities.inRadius(item.getRelativeLocation(), entry.getKey().getRelativeLocation(), entry.getValue())) { collidingWith.put(entry.getKey(), true); onEnteringCollision(entry.getKey()); } } } } } /** * Override this method to set what action should be performed on entering a * collision. * * @param collidale * The item the managed item collided with. */ protected void onEnteringCollision(IItem collidale) { } /** * Override this method to set what action should be performed on leaving a * collision. * * @param collidale * The item the managed item collided with. */ protected void onLeavingCollision(IItem collidale) { } }
bsd-3-clause
westnorth/weibo_zy
weibo_cm/IKAnalyzerDemo.java
3017
///** // * IK Analyzer Demo // * @param args // */ //import java.io.IOException; // //import org.apache.lucene.analysis.Analyzer; //import org.apache.lucene.document.Document; //import org.apache.lucene.document.Field; //import org.apache.lucene.index.CorruptIndexException; //import org.apache.lucene.index.IndexWriter; //import org.apache.lucene.search.IndexSearcher; //import org.apache.lucene.search.Query; //import org.apache.lucene.search.ScoreDoc; //import org.apache.lucene.search.TopDocs; //import org.apache.lucene.store.Directory; //import org.apache.lucene.store.LockObtainFailedException; //import org.apache.lucene.store.RAMDirectory; ////引用IKAnalyzer3.0的类 //import org.wltea.analyzer.lucene.IKAnalyzer; //import org.wltea.analyzer.lucene.IKQueryParser; //import org.wltea.analyzer.lucene.IKSimilarity; // ///** // * @author linly // * // */ //public class IKAnalyzerDemo { // // public static void main(String[] args) { // // Lucene Document的域名 // String fieldName = "text"; // // 检索内容 // String text = "IK Analyzer是一个结合词典分词和文法分词的中文分词开源工具包。它使用了全新的正向迭代最细粒度切分算法。"; // // // 实例化IKAnalyzer分词器 // Analyzer analyzer = new IKAnalyzer(); // // Directory directory = null; // IndexWriter iwriter = null; // IndexSearcher isearcher = null; // try { // // 建立内存索引对象 // directory = new RAMDirectory(); // iwriter = new IndexWriter(directory, analyzer, true, // IndexWriter.MaxFieldLength.LIMITED); // Document doc = new Document(); // doc.add(new Field(fieldName, text, Field.Store.YES, // Field.Index.ANALYZED)); // iwriter.addDocument(doc); // iwriter.close(); // // // 实例化搜索器 // isearcher = new IndexSearcher(directory); // // 在索引器中使用IKSimilarity相似度评估器 // isearcher.setSimilarity(new IKSimilarity()); // // String keyword = "中文分词工具包"; // // // 使用IKQueryParser查询分析器构造Query对象 // Query query = IKQueryParser.parse(fieldName, keyword); // // // 搜索相似度最高的5条记录 // TopDocs topDocs = isearcher.search(query, 5); // System.out.println("命中:" + topDocs.totalHits); // // 输出结果 // ScoreDoc[] scoreDocs = topDocs.scoreDocs; // for (int i = 0; i < topDocs.totalHits; i++) { // Document targetDoc = isearcher.doc(scoreDocs[i].doc); // System.out.println("内容:" + targetDoc.toString()); // } // // } catch (CorruptIndexException e) { // e.printStackTrace(); // } catch (LockObtainFailedException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // if (isearcher != null) { // try { // isearcher.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // if (directory != null) { // try { // directory.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // } //}
bsd-3-clause
NUBIC/psc-mirror
web/src/test/java/edu/northwestern/bioinformatics/studycalendar/restlets/SchedulePreviewResourceTest.java
6937
package edu.northwestern.bioinformatics.studycalendar.restlets; import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledCalendar; import edu.northwestern.bioinformatics.studycalendar.domain.Study; import edu.northwestern.bioinformatics.studycalendar.domain.StudySegment; import edu.northwestern.bioinformatics.studycalendar.security.authorization.PscRole; import edu.northwestern.bioinformatics.studycalendar.service.SubjectService; import edu.northwestern.bioinformatics.studycalendar.web.accesscontrol.ResourceAuthorization; import org.restlet.data.MediaType; import org.restlet.data.Status; import java.util.Calendar; import static edu.northwestern.bioinformatics.studycalendar.core.Fixtures.*; import static org.easymock.EasyMock.*; /** * @author Jalpa Patel */ public class SchedulePreviewResourceTest extends AuthorizedResourceTestCase<SchedulePreviewResource>{ private AmendedTemplateHelper helper; private SubjectService subjectService; private Study study; @Override public void setUp() throws Exception { super.setUp(); helper = registerMockFor(AmendedTemplateHelper.class); helper.setRequest(request); expect(helper.getReadAuthorizations()). andStubReturn(ResourceAuthorization.createCollection(PscRole.values())); subjectService = registerMockFor(SubjectService.class); study = createSingleEpochStudy("DC", "Treatment", "A", "B"); assignIds(study.getPlannedCalendar().getEpochs().get(0), 0); // A's grid ID is now GRID-50 and B's is GRID-100 } @Override @SuppressWarnings({"unchecked"}) protected SchedulePreviewResource createAuthorizedResource() { SchedulePreviewResource resource = new SchedulePreviewResource(); resource.setAmendedTemplateHelper(helper); resource.setSubjectService(subjectService); resource.setXmlSerializer(xmlSerializer); return resource; } public void testPreviewIsBuiltFromGoodSegmentDatePair() throws Exception { request.getResourceRef().addQueryParameter("segment[0]", "GRID-50"); request.getResourceRef().addQueryParameter("start_date[0]", "2009-03-04"); requestJson(); expect(helper.getAmendedTemplate()).andReturn(study); subjectService.scheduleStudySegmentPreview( (ScheduledCalendar) notNull(), eq(findNodeByName(study, StudySegment.class, "A")), sameDay(2009, Calendar.MARCH, 4)); doGet(); assertResponseStatus(Status.SUCCESS_OK); } public void testPreviewIsBuiltFromRandomlyIndexedSegmentDatePair() throws Exception { request.getResourceRef().addQueryParameter("segment[tortoise]", "GRID-100"); request.getResourceRef().addQueryParameter("start_date[tortoise]", "2009-03-21"); requestJson(); expect(helper.getAmendedTemplate()).andReturn(study); subjectService.scheduleStudySegmentPreview( (ScheduledCalendar) notNull(), eq(findNodeByName(study, StudySegment.class, "B")), sameDay(2009, Calendar.MARCH, 21)); doGet(); assertResponseStatus(Status.SUCCESS_OK); } public void testPreviewMayContainMultipleSegments() throws Exception { request.getResourceRef().addQueryParameter("segment[Alpha]", "GRID-100"); request.getResourceRef().addQueryParameter("segment[Echo]", "GRID-50"); request.getResourceRef().addQueryParameter("start_date[Alpha]", "2009-03-21"); request.getResourceRef().addQueryParameter("start_date[Echo]", "2009-04-13"); requestJson(); expect(helper.getAmendedTemplate()).andReturn(study); subjectService.scheduleStudySegmentPreview( (ScheduledCalendar) notNull(), eq(findNodeByName(study, StudySegment.class, "B")), sameDay(2009, Calendar.MARCH, 21)); subjectService.scheduleStudySegmentPreview( (ScheduledCalendar) notNull(), eq(findNodeByName(study, StudySegment.class, "A")), sameDay(2009, Calendar.APRIL, 13)); doGet(); assertResponseStatus(Status.SUCCESS_OK); } public void testGet404WhenHelperNotfoundException() throws Exception { expect(helper.getAmendedTemplate()).andThrow(new AmendedTemplateHelper.NotFound("Not Found")); doGet(); assertResponseStatus(Status.CLIENT_ERROR_NOT_FOUND); } public void testGet400WhenNoDateForSegment() throws Exception { request.getResourceRef().addQueryParameter("segment[1]", "GRID-50"); expect(helper.getAmendedTemplate()).andReturn(study); doGet(); assertResponseStatus(Status.CLIENT_ERROR_BAD_REQUEST, "The following segment(s) do not have matching start_date(s): [1]"); } public void testGet400WhenNoSegmentForDate() throws Exception { request.getResourceRef().addQueryParameter("start_date[1]", "2007-06-13"); expect(helper.getAmendedTemplate()).andReturn(study); doGet(); assertResponseStatus(Status.CLIENT_ERROR_BAD_REQUEST, "The following start_date(s) do not have matching segment(s): [1]"); } public void testGet400WhenInvalidSegmentRequested() throws Exception { request.getResourceRef().addQueryParameter("segment[1]", "GRID-non"); request.getResourceRef().addQueryParameter("start_date[1]", "2009-07-11"); expect(helper.getAmendedTemplate()).andReturn(study); doGet(); assertResponseStatus(Status.CLIENT_ERROR_BAD_REQUEST, "No study segment with identifier GRID-non in the study"); } public void testGet400ForMismatchedSegmentAndDate() throws Exception { request.getResourceRef().addQueryParameter("segment[moth]", "GRID-50"); request.getResourceRef().addQueryParameter("start_date[hummingbird]", "2009-07-11"); expect(helper.getAmendedTemplate()).andReturn(study); doGet(); assertResponseStatus(Status.CLIENT_ERROR_BAD_REQUEST, "The following start_date(s) do not have matching segment(s): [hummingbird]"); } public void testGet400WhenUnparsableDate() throws Exception { request.getResourceRef().addQueryParameter("segment[0]", "GRID-50"); request.getResourceRef().addQueryParameter("start_date[0]", "2008"); expect(helper.getAmendedTemplate()).andReturn(study); doGet(); assertResponseStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid date: start_date[0]=2008. The date must be formatted as yyyy-mm-dd."); } public void test400ForMissingParams() throws Exception { expect(helper.getAmendedTemplate()).andReturn(study); doGet(); assertResponseStatus(Status.CLIENT_ERROR_BAD_REQUEST, "At least one segment/start_date pair is required"); } private void requestJson() { setAcceptedMediaTypes(MediaType.APPLICATION_JSON); } }
bsd-3-clause
levans/Open-Quark
src/CAL_Runtime/src/org/openquark/cal/internal/runtime/lecc/functions/RTRecordToJRecordValuePrimitive.java
7342
/* * Copyright (c) 2007 BUSINESS OBJECTS SOFTWARE LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of Business Objects nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * RTRecordToJMapPrimitive.java * Created: Jan 9, 2007 * By: Bo Ilic */ package org.openquark.cal.internal.runtime.lecc.functions; import org.openquark.cal.compiler.FieldName; import org.openquark.cal.internal.runtime.RecordValueImpl; import org.openquark.cal.internal.runtime.lecc.LECCMachineConfiguration; import org.openquark.cal.internal.runtime.lecc.RTData; import org.openquark.cal.internal.runtime.lecc.RTExecutionContext; import org.openquark.cal.internal.runtime.lecc.RTRecordValue; import org.openquark.cal.internal.runtime.lecc.RTResultFunction; import org.openquark.cal.internal.runtime.lecc.RTSupercombinator; import org.openquark.cal.internal.runtime.lecc.RTValue; import org.openquark.cal.runtime.CALExecutorException; import org.openquark.cal.runtime.RecordValue; /** * Implements the built-in primitive function: * recordToJMapPrimitive :: Outputable r => {r} -> JRecordValue * defined in the Record module. * * @author Bo Ilic */ public final class RTRecordToJRecordValuePrimitive extends RTSupercombinator { public static final RTRecordToJRecordValuePrimitive $instance = new RTRecordToJRecordValuePrimitive(); private RTRecordToJRecordValuePrimitive() { // Declared private to limit instantiation. } public static final RTRecordToJRecordValuePrimitive make(RTExecutionContext $ec) { return $instance; } @Override public final int getArity() { return 2; } @Override public final RTValue f(final RTResultFunction rootNode, final RTExecutionContext $ec) throws CALExecutorException { // Arguments RTValue x = rootNode.getArgValue(); RTValue recordDictionary = rootNode.prevArg().getArgValue(); // Release the fields in the root node to open them to garbage collection rootNode.clearMembers(); return f2S ( RTValue.lastRef(recordDictionary.evaluate($ec), recordDictionary = null), RTValue.lastRef(x.evaluate($ec), x = null), $ec); } @Override public final RTValue f2L(RTValue recordDictionary, RTValue x, RTExecutionContext $ec) throws CALExecutorException { return f2S ( RTValue.lastRef(recordDictionary.evaluate($ec), recordDictionary = null), RTValue.lastRef(x.evaluate($ec), x = null), $ec); } @Override public final RTValue f2S(RTValue recordDictionary, RTValue x, RTExecutionContext $ec) throws CALExecutorException { // Since all branches of the function code return a HNF we can simply box the result of the unboxed return method. return RTData.CAL_Opaque.make(fUnboxed2S (recordDictionary, x, $ec)); } /** * This is the version of the function logic that directly returns an unboxed value. * All functions whose return types can be unboxed should have a version of the function * logic which returns an unboxed value. * @param recordDictionary * @param x * @param $ec * @return RecordValue * @throws CALExecutorException */ public final RecordValue fUnboxed2S(final RTValue recordDictionary, final RTValue x, final RTExecutionContext $ec) throws CALExecutorException { $ec.incrementNMethodCalls(); if (LECCMachineConfiguration.generateDebugCode() && $ec.isDebugProcessingNeeded(getQualifiedName())) { $ec.debugProcessing(getQualifiedName(), new RTValue[]{recordDictionary, x}); } //recordToJMapPrimitive recordDictionary x. //the compiler ensures that the 2 record arguments all have the same fields. //must iterate in a deterministic order over the field names (as specified by FieldName.CalSourceFormComparator) //so that the function is well-defined in the presence of side effects. //If f is a field, then recordDictionary.f is the dictionary for use when calling the class method Prelude.output on //the value x.f. final RTRecordValue recordDict = (RTRecordValue)recordDictionary; final RTRecordValue xRecord = (RTRecordValue)x; final RecordValue resultMap = RecordValueImpl.make(); final int nFields = recordDict.getNFields(); for (int i = 0; i < nFields; ++i) { final FieldName fieldName = recordDict.getNthFieldName(i); //RTValue fieldDict = recordDictionary.getNthValue(i); //RTValue xField = xRecord.getNthValue(i); //compute "Prelude.output fieldDict xField" //this is just (after inlining Prelude.output d = d" //fieldDict xField final Object fieldValue = recordDict.getNthValue(i).apply(xRecord.getNthValue(i)).evaluate($ec).getOpaqueValue(); resultMap.put(fieldName, fieldValue); } return resultMap; } /** * {@inheritDoc} */ @Override public final String getModuleName () { //JUnit tested to equal its binding file value in RuntimeStringConstantsTest. return "Cal.Core.Record"; } /** * {@inheritDoc} */ @Override public final String getUnqualifiedName () { //JUnit tested to equal its binding file value in RuntimeStringConstantsTest. return "recordToJRecordValuePrimitive"; } /** * {@inheritDoc} */ @Override public final String getQualifiedName() { //JUnit tested to equal its binding file value in RuntimeStringConstantsTest. return "Cal.Core.Record.recordToJRecordValuePrimitive"; } }
bsd-3-clause
jochenwierum/sshclient
src/main/java/de/jowisoftware/sshclient/ui/terminal/DoubleBufferedImage.java
9326
package de.jowisoftware.sshclient.ui.terminal; import de.jowisoftware.sshclient.debug.PerformanceLogger; import de.jowisoftware.sshclient.debug.PerformanceType; import de.jowisoftware.sshclient.terminal.buffer.Position; import de.jowisoftware.sshclient.terminal.buffer.Renderer; import de.jowisoftware.sshclient.terminal.buffer.Snapshot; import de.jowisoftware.sshclient.terminal.gfx.ColorName; import de.jowisoftware.sshclient.terminal.gfx.GfxChar; import de.jowisoftware.sshclient.terminal.gfx.RenderFlag; import de.jowisoftware.sshclient.terminal.gfx.awt.AWTGfxChar; import de.jowisoftware.sshclient.terminal.gfx.awt.AWTGfxInfo; import de.jowisoftware.sshclient.util.Constants; import de.jowisoftware.sshclient.util.FontUtils; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; @SuppressFBWarnings("IS2_INCONSISTENT_SYNC") public class DoubleBufferedImage implements Renderer { private final AWTGfxInfo gfxInfo; private final JPanel parent; private BufferedImage[] images; private Graphics2D[] graphics; private int currentImage = 0; private final Object imageLock = new Object(); private int width; private int height; private int charWidth = 1; private int charHeight = 1; private int baseLinePos = 1; private boolean queued = false; private boolean renderInverted = false; private Position currentSelectionStart; private Position currentSelectionEnd; private volatile boolean isFocused; private long invertUntil; private volatile long blinkingOffset = 0; public DoubleBufferedImage(final AWTGfxInfo gfxInfo, final JPanel parent) { this.gfxInfo = gfxInfo; this.parent = parent; setDimensions(1, 1); } @Override public synchronized void dispose() { synchronized (imageLock) { images = null; if (graphics != null) { graphics[0].dispose(); graphics[1].dispose(); } graphics = null; } } @Override public synchronized void setDimensions(final int width, final int height) { synchronized (imageLock) { this.width = width; this.height = height; dispose(); images = new BufferedImage[2]; graphics = new Graphics2D[2]; for (int i = 0; i < 2; ++i) { images[i] = GraphicsEnvironment.getLocalGraphicsEnvironment() .getDefaultScreenDevice().getDefaultConfiguration() .createCompatibleImage(width, height, Transparency.OPAQUE); graphics[i] = images[i].createGraphics(); graphics[i].setBackground(gfxInfo.mapColor( ColorName.DEFAULT_BACKGROUND, false)); graphics[i].setFont(gfxInfo.getFont()); final int aaModeId = gfxInfo.getAntiAliasingMode(); final Object aaModeValue = FontUtils.getRenderingHintMap().get(aaModeId).value; graphics[i].setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, aaModeValue); } final FontMetrics fontMetrics = graphics[0].getFontMetrics(); this.charWidth = fontMetrics.charWidth('m'); this.charHeight = fontMetrics.getHeight(); this.baseLinePos = fontMetrics.getAscent() + fontMetrics.getLeading(); } } @Override public synchronized void renderSnapshot(final Snapshot snapshot) { final Position selectionStart = this.currentSelectionStart; final Position selectionEnd = this.currentSelectionEnd; final int baseRenderFlags = createGlobalRenderFlags(System.currentTimeMillis()); if (images != null) { PerformanceLogger.start(PerformanceType.BACKGROUND_RENDER); for (int y = 0; y < snapshot.content.length; ++y) { final int yPos = y * charHeight; int x; for (x = 0; x < snapshot.content[y].length; x += snapshot.content[y][x].getCharCount()) { final int xPos = x * charWidth; final int renderFlags = baseRenderFlags | createCharRenderFlags( snapshot.cursorPosition, new Position(x + 1, y + 1), selectionStart, selectionEnd); final GfxChar gfxChar = snapshot.content[y][x]; final Rectangle rect = new Rectangle(xPos, yPos, charWidth * gfxChar.getCharCount(), charHeight); ((AWTGfxChar)gfxChar).drawAt(rect, baseLinePos, graphics[1 - currentImage], renderFlags); } final AWTGfxChar lastChar = (AWTGfxChar)snapshot.content[y][snapshot.content[y].length - 1]; fillLine(yPos, x, lastChar.getBackground()); } swap(); PerformanceLogger.end(PerformanceType.BACKGROUND_RENDER); } } private void fillLine(final int yPos, final int x, final Color background) { final int xPos = x * charWidth; graphics[1 - currentImage].setColor(background); graphics[1 - currentImage].fillRect(xPos, yPos, width - xPos, charHeight); } private int createGlobalRenderFlags(final long time) { int flags = 0; if ((renderInverted && !invertTimed(time)) || (!renderInverted && invertTimed(time))) { flags |= RenderFlag.INVERTED.flag; } if (blinkIsForeground(time)) { flags |= RenderFlag.BLINKING.flag; } if (isFocused) { flags |= RenderFlag.FOCUSED.flag; } return flags; } private boolean blinkIsForeground(final long time) { return ((time - blinkingOffset) / Constants.BLINK_TIMER) % 2 == 0; } private int createCharRenderFlags( final Position cursorPosition, final Position renderPosition, final Position selectionStart, final Position selectionEnd) { int newFlags = 0; if (cursorPosition != null && cursorPosition.equals(renderPosition)) { newFlags |= RenderFlag.CURSOR.flag; } if (selectionStart != null && selectionEnd != null && isInSelectionRange(renderPosition, selectionStart, selectionEnd)) { newFlags |= RenderFlag.SELECTED.flag; } return newFlags; } private boolean isInSelectionRange(final Position currentPosition, final Position selectionStart, final Position selectionEnd) { final boolean outOfRange = currentPosition.isBefore(selectionStart) || currentPosition.isAfter(selectionEnd); return !outOfRange; } private void swap() { synchronized (imageLock) { if (images != null) { currentImage = 1 - currentImage; } } requestRepaint(); } private void requestRepaint() { if (!queued) { queued = true; PerformanceLogger.start(PerformanceType.REQUEST_TO_RENDER); parent.repaint(); // repaint is thread-safe! } } public Image getImage() { synchronized (imageLock) { if (images == null) { return null; } queued = false; return images[currentImage]; } } @Override public synchronized int getLines() { return height / charHeight; } @Override public synchronized int getCharsPerLine() { return width / charWidth; } @Override public synchronized Position translateMousePosition(final int x, final int y) { final int charx = (x + charWidth / 2) / charWidth + 1; final int chary = y / charHeight + 1; return new Position(charx, chary); } @Override public synchronized void renderInverted(final boolean inverted) { renderInverted = inverted; } @Override public synchronized void clearSelection() { this.currentSelectionStart = null; this.currentSelectionEnd = null; } @Override public synchronized void setSelection(final Position pos1, final Position pos2) { this.currentSelectionStart = pos1; this.currentSelectionEnd = pos2; } @Override public void setFocused(final boolean isFocused) { this.isFocused = isFocused; } @Override public void invertFor(final int invertMillis) { invertUntil = System.currentTimeMillis() + invertMillis; } private boolean invertTimed(final long time) { return invertUntil > time; } @Override public void resetBlinking() { blinkingOffset = System.currentTimeMillis() % (2 * Constants.BLINK_TIMER); } }
bsd-3-clause
SnakeDoc/GuestVM
guestvm~guestvm/com.oracle.max.ve/src/com/sun/max/ve/sched/priority/PriorityRingRunQueueFactory.java
1684
/* * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.max.ve.sched.priority; import com.sun.max.*; import com.sun.max.ve.sched.*; import com.sun.max.vm.thread.VmThread; public class PriorityRingRunQueueFactory extends RunQueueFactory { @Override public RunQueue<GUKVmThread> createRunQueue() { final RunQueue<GUKVmThread> result = Utils.cast(new PriorityRingRunQueue<RingGUKVmThread>(Thread.MIN_PRIORITY, Thread.MAX_PRIORITY, new UnlockedRingRunQueueCreator<RingGUKVmThread>())); result.buildtimeInitialize(); return result; } @Override public VmThread newVmThread() { return new RingGUKVmThread(); } }
bsd-3-clause
pygospa/jgraphx
src/com/mxgraph/io/mxCodec.java
10736
/** * Copyright (c) 2012, JGraph Ltd */ package com.mxgraph.io; import java.util.Hashtable; import java.util.Map; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import com.mxgraph.model.mxCell; import com.mxgraph.model.mxCellPath; import com.mxgraph.model.mxICell; import com.mxgraph.util.mxDomUtils; /** * XML codec for Java object graphs. In order to resolve forward references * when reading files the XML document that contains the data must be passed * to the constructor. */ public class mxCodec { /** * Holds the owner document of the codec. */ protected Document document; /** * Maps from IDs to objects. */ protected Map<String, Object> objects = new Hashtable<String, Object>(); /** * Specifies if default values should be encoded. Default is false. */ protected boolean encodeDefaults = false; /** * Constructs an XML encoder/decoder with a new owner document. */ public mxCodec() { this(mxDomUtils.createDocument()); } /** * Constructs an XML encoder/decoder for the specified owner document. * * @param document Optional XML document that contains the data. If no document * is specified then a new document is created using mxUtils.createDocument */ public mxCodec(Document document) { if (document == null) { document = mxDomUtils.createDocument(); } this.document = document; } /** * Returns the owner document of the codec. * * @return Returns the owner document. */ public Document getDocument() { return document; } /** * Sets the owner document of the codec. */ public void setDocument(Document value) { document = value; } /** * Returns if default values of member variables should be encoded. */ public boolean isEncodeDefaults() { return encodeDefaults; } /** * Sets if default values of member variables should be encoded. */ public void setEncodeDefaults(boolean encodeDefaults) { this.encodeDefaults = encodeDefaults; } /** * Returns the object lookup table. */ public Map<String, Object> getObjects() { return objects; } /** * Assoiates the given object with the given ID. * * @param id ID for the object to be associated with. * @param object Object to be associated with the ID. * @return Returns the given object. */ public Object putObject(String id, Object object) { return objects.put(id, object); } /** * Returns the decoded object for the element with the specified ID in * {@link #document}. If the object is not known then {@link #lookup(String)} * is used to find an object. If no object is found, then the element with * the respective ID from the document is parsed using {@link #decode(Node)}. * * @param id ID of the object to be returned. * @return Returns the object for the given ID. */ public Object getObject(String id) { Object obj = null; if (id != null) { obj = objects.get(id); if (obj == null) { obj = lookup(id); if (obj == null) { Node node = getElementById(id); if (node != null) { obj = decode(node); } } } } return obj; } /** * Hook for subclassers to implement a custom lookup mechanism for cell IDs. * This implementation always returns null. * * @param id ID of the object to be returned. * @return Returns the object for the given ID. */ public Object lookup(String id) { return null; } /** * Returns the element with the given ID from the document. * * @param id ID of the element to be returned. * @return Returns the element for the given ID. */ public Node getElementById(String id) { return document.getElementById(id); } /** * Returns the ID of the specified object. This implementation calls * reference first and if that returns null handles the object as an * mxCell by returning their IDs using mxCell.getId. If no ID exists for * the given cell, then an on-the-fly ID is generated using * mxCellPath.create. * * @param obj Object to return the ID for. * @return Returns the ID for the given object. */ public String getId(Object obj) { String id = null; if (obj != null) { id = reference(obj); if (id == null && obj instanceof mxICell) { id = ((mxICell) obj).getId(); if (id == null) { // Uses an on-the-fly Id id = mxCellPath.create((mxICell) obj); if (id.length() == 0) { id = "root"; } } } } return id; } /** * Hook for subclassers to implement a custom method for retrieving IDs from * objects. This implementation always returns null. * * @param obj Object whose ID should be returned. * @return Returns the ID for the given object. */ public String reference(Object obj) { return null; } /** * Encodes the specified object and returns the resulting XML node. * * @param obj Object to be encoded. * @return Returns an XML node that represents the given object. */ public Node encode(Object obj) { Node node = null; if (obj != null) { String name = mxCodecRegistry.getName(obj); mxObjectCodec enc = mxCodecRegistry.getCodec(name); if (enc != null) { node = enc.encode(this, obj); } else { if (obj instanceof Node) { node = ((Node) obj).cloneNode(true); } else { System.err.println("No codec for " + name); } } } return node; } /** * Decodes the given XML node using {@link #decode(Node, Object)}. * * @param node XML node to be decoded. * @return Returns an object that represents the given node. */ public Object decode(Node node) { return decode(node, null); } /** * Decodes the given XML node. The optional "into" argument specifies an * existing object to be used. If no object is given, then a new * instance is created using the constructor from the codec. * * The function returns the passed in object or the new instance if no * object was given. * * @param node XML node to be decoded. * @param into Optional object to be decodec into. * @return Returns an object that represents the given node. */ public Object decode(Node node, Object into) { Object obj = null; if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { mxObjectCodec codec = mxCodecRegistry.getCodec(node.getNodeName()); try { if (codec != null) { obj = codec.decode(this, node, into); } else { obj = node.cloneNode(true); ((Element) obj).removeAttribute("as"); } } catch (Exception e) { System.err.println("Cannot decode " + node.getNodeName() + ": " + e.getMessage()); e.printStackTrace(); } } return obj; } /** * Encoding of cell hierarchies is built-into the core, but is a * higher-level function that needs to be explicitely used by the * respective object encoders (eg. mxModelCodec, mxChildChangeCodec * and mxRootChangeCodec). This implementation writes the given cell * and its children as a (flat) sequence into the given node. The * children are not encoded if the optional includeChildren is false. * The function is in charge of adding the result into the given node * and has no return value. * * @param cell mxCell to be encoded. * @param node Parent XML node to add the encoded cell into. * @param includeChildren Boolean indicating if the method * should include all descendents. */ public void encodeCell(mxICell cell, Node node, boolean includeChildren) { node.appendChild(encode(cell)); if (includeChildren) { int childCount = cell.getChildCount(); for (int i = 0; i < childCount; i++) { encodeCell(cell.getChildAt(i), node, includeChildren); } } } /** * Decodes cells that have been encoded using inversion, ie. where the * user object is the enclosing node in the XML, and restores the group * and graph structure in the cells. Returns a new <mxCell> instance * that represents the given node. * * @param node XML node that contains the cell data. * @param restoreStructures Boolean indicating whether the graph * structure should be restored by calling insert and insertEdge on the * parent and terminals, respectively. * @return Graph cell that represents the given node. */ public mxICell decodeCell(Node node, boolean restoreStructures) { mxICell cell = null; if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { // Tries to find a codec for the given node name. If that does // not return a codec then the node is the user object (an XML node // that contains the mxCell, aka inversion). mxObjectCodec decoder = mxCodecRegistry .getCodec(node.getNodeName()); // Tries to find the codec for the cell inside the user object. // This assumes all node names inside the user object are either // not registered or they correspond to a class for cells. if (!(decoder instanceof mxCellCodec)) { Node child = node.getFirstChild(); while (child != null && !(decoder instanceof mxCellCodec)) { decoder = mxCodecRegistry.getCodec(child.getNodeName()); child = child.getNextSibling(); } String name = mxCell.class.getSimpleName(); decoder = mxCodecRegistry.getCodec(name); } if (!(decoder instanceof mxCellCodec)) { String name = mxCell.class.getSimpleName(); decoder = mxCodecRegistry.getCodec(name); } cell = (mxICell) decoder.decode(this, node); if (restoreStructures) { insertIntoGraph(cell); } } return cell; } /** * Inserts the given cell into its parent and terminal cells. */ public void insertIntoGraph(mxICell cell) { mxICell parent = cell.getParent(); mxICell source = cell.getTerminal(true); mxICell target = cell.getTerminal(false); // Fixes possible inconsistencies during insert into graph cell.setTerminal(null, false); cell.setTerminal(null, true); cell.setParent(null); if (parent != null) { parent.insert(cell); } if (source != null) { source.insertEdge(cell, true); } if (target != null) { target.insertEdge(cell, false); } } /** * Sets the attribute on the specified node to value. This is a * helper method that makes sure the attribute and value arguments * are not null. * * @param node XML node to set the attribute for. * @param attribute Name of the attribute whose value should be set. * @param value New value of the attribute. */ public static void setAttribute(Node node, String attribute, Object value) { if (node.getNodeType() == Node.ELEMENT_NODE && attribute != null && value != null) { ((Element) node).setAttribute(attribute, String.valueOf(value)); } } }
bsd-3-clause
paksv/vijava
src/com/vmware/vim25/ArrayOfAuthorizationPrivilege.java
2221
/*================================================================================ Copyright (c) 2013 Steve Jin. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of VMware, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================*/ package com.vmware.vim25; /** * @author Steve Jin (http://www.doublecloud.org) * @version 5.1 */ public class ArrayOfAuthorizationPrivilege { public AuthorizationPrivilege[] AuthorizationPrivilege; public AuthorizationPrivilege[] getAuthorizationPrivilege() { return this.AuthorizationPrivilege; } public AuthorizationPrivilege getAuthorizationPrivilege(int i) { return this.AuthorizationPrivilege[i]; } public void setAuthorizationPrivilege(AuthorizationPrivilege[] AuthorizationPrivilege) { this.AuthorizationPrivilege=AuthorizationPrivilege; } }
bsd-3-clause
ShadowLordAlpha/TWL
src/main/java/de/matthiasmann/twl/AnimationState.java
8553
/* * Copyright (c) 2008-2011, Matthias Mann * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Matthias Mann nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package de.matthiasmann.twl; /** * * @author Matthias Mann */ public class AnimationState implements de.matthiasmann.twl.renderer.AnimationState { private final AnimationState parent; private State[] stateTable; private GUI gui; /** * Create a new animation state with optional parent. * * When a parent animation state is set, then any request for a state which * has not been set (to either true or false) in this instance are forwarded * to the parent. * * @param parent * the parent animation state or null * @param size * the initial size of the state table (indexed by state IDs) */ public AnimationState(AnimationState parent, int size) { this.parent = parent; this.stateTable = new State[size]; } /** * Create a new animation state with optional parent. * * When a parent animation state is set, then any request for a state which * has not been set (to either true or false) in this instance are forwarded * to the parent. * * @param parent * the parent animation state or null */ public AnimationState(AnimationState parent) { this(parent, 16); } /** * Creates a new animation state without parent * * @see #AnimationState(de.matthiasmann.twl.AnimationState) */ public AnimationState() { this(null); } public void setGUI(GUI gui) { this.gui = gui; long curTime = getCurrentTime(); for (State s : stateTable) { if (s != null) { s.lastChangedTime = curTime; } } } /** * Returns the time since the specified state has changed in ms. If the * specified state was never changed then a free running time is returned. * * @param stateKey * the state key. * @return time since last state change is ms. */ public int getAnimationTime(StateKey stateKey) { State state = getState(stateKey); if (state != null) { return (int) Math.min(Integer.MAX_VALUE, getCurrentTime() - state.lastChangedTime); } if (parent != null) { return parent.getAnimationTime(stateKey); } return (int) getCurrentTime() & ((1 << 31) - 1); } /** * Checks if the given state is active. * * @param stateKey * the state key. * @return true if the state is set */ public boolean getAnimationState(StateKey stateKey) { State state = getState(stateKey); if (state != null) { return state.active; } if (parent != null) { return parent.getAnimationState(stateKey); } return false; } /** * Checks if this state was changed based on user interaction or not. If * this method returns false then the animation time should not be used for * single shot animations. * * @param stateKey * the state key. * @return true if single shot animations should run or not. */ public boolean getShouldAnimateState(StateKey stateKey) { State state = getState(stateKey); if (state != null) { return state.shouldAnimate; } if (parent != null) { return parent.getShouldAnimateState(stateKey); } return false; } /** * Equivalent to calling * {@code setAnimationState(StateKey.get(stateName), active);} * * @param stateName * the string specifying the state key * @param active * the new value * @deprecated * @see #setAnimationState(de.matthiasmann.twl.renderer.AnimationState.StateKey, * boolean) * @see de.matthiasmann.twl.renderer.AnimationState.StateKey#get(java.lang.String) */ @Deprecated public void setAnimationState(String stateName, boolean active) { setAnimationState(StateKey.get(stateName), active); } /** * Sets the specified animation state to the given value. If the value is * changed then the animation time is reset too. * * @param stateKey * the state key * @param active * the new value * @see #getAnimationState(de.matthiasmann.twl.renderer.AnimationState.StateKey) * @see #resetAnimationTime(de.matthiasmann.twl.renderer.AnimationState.StateKey) */ public void setAnimationState(StateKey stateKey, boolean active) { State state = getOrCreate(stateKey); if (state.active != active) { state.active = active; state.lastChangedTime = getCurrentTime(); state.shouldAnimate = true; } } /** * Equivalent to calling * {@code resetAnimationTime(StateKey.get(stateName));} * * @param stateName * the string specifying the state key * @deprecated * @see #resetAnimationTime(de.matthiasmann.twl.renderer.AnimationState.StateKey) * @see de.matthiasmann.twl.renderer.AnimationState.StateKey#get(java.lang.String) */ @Deprecated public void resetAnimationTime(String stateName) { resetAnimationTime(StateKey.get(stateName)); } /** * Resets the animation time of the specified animation state. Resetting the * animation time also enables the {@code shouldAnimate} flag. * * @param stateKey * the state key. * @see #getAnimationTime(de.matthiasmann.twl.renderer.AnimationState.StateKey) * @see #getShouldAnimateState(de.matthiasmann.twl.renderer.AnimationState.StateKey) */ public void resetAnimationTime(StateKey stateKey) { State state = getOrCreate(stateKey); state.lastChangedTime = getCurrentTime(); state.shouldAnimate = true; } /** * Equivalent to calling {@code dontAnimate(StateKey.get(stateName));} * * @param stateName * the string specifying the state key * @deprecated * @see #dontAnimate(de.matthiasmann.twl.renderer.AnimationState.StateKey) * @see de.matthiasmann.twl.renderer.AnimationState.StateKey#get(java.lang.String) */ @Deprecated public void dontAnimate(String stateName) { dontAnimate(StateKey.get(stateName)); } /** * Clears the {@code shouldAnimate} flag of the specified animation state. * * @param stateKey * the state key. * @see #getShouldAnimateState(de.matthiasmann.twl.renderer.AnimationState.StateKey) */ public void dontAnimate(StateKey stateKey) { State state = getState(stateKey); if (state != null) { state.shouldAnimate = false; } } private State getState(StateKey stateKey) { int id = stateKey.getID(); if (id < stateTable.length) { return stateTable[id]; } return null; } private State getOrCreate(StateKey stateKey) { int id = stateKey.getID(); if (id < stateTable.length) { State state = stateTable[id]; if (state != null) { return state; } } return createState(id); } private State createState(int id) { if (id >= stateTable.length) { State[] newTable = new State[id + 1]; System.arraycopy(stateTable, 0, newTable, 0, stateTable.length); stateTable = newTable; } State state = new State(); state.lastChangedTime = getCurrentTime(); stateTable[id] = state; return state; } private long getCurrentTime() { return (gui != null) ? gui.curTime : 0; } static final class State { long lastChangedTime; boolean active; boolean shouldAnimate; } }
bsd-3-clause
nesl/FlowEngine
DataCollector/src/edu/ucla/nesl/datacollector/tools/Base64.java
28620
package edu.ucla.nesl.datacollector.tools; /* * Copyright (C) 2010 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. */ import java.io.UnsupportedEncodingException; /** * Utilities for encoding and decoding the Base64 representation of * binary data. See RFCs <a * href="http://www.ietf.org/rfc/rfc2045.txt">2045</a> and <a * href="http://www.ietf.org/rfc/rfc3548.txt">3548</a>. */ public class Base64 { /** * Default values for encoder/decoder flags. */ public static final int DEFAULT = 0; /** * Encoder flag bit to omit the padding '=' characters at the end * of the output (if any). */ public static final int NO_PADDING = 1; /** * Encoder flag bit to omit all line terminators (i.e., the output * will be on one long line). */ public static final int NO_WRAP = 2; /** * Encoder flag bit to indicate lines should be terminated with a * CRLF pair instead of just an LF. Has no effect if {@code * NO_WRAP} is specified as well. */ public static final int CRLF = 4; /** * Encoder/decoder flag bit to indicate using the "URL and * filename safe" variant of Base64 (see RFC 3548 section 4) where * {@code -} and {@code _} are used in place of {@code +} and * {@code /}. */ public static final int URL_SAFE = 8; /** * Flag to pass to {@link Base64OutputStream} to indicate that it * should not close the output stream it is wrapping when it * itself is closed. */ public static final int NO_CLOSE = 16; // -------------------------------------------------------- // shared code // -------------------------------------------------------- /* package */ static abstract class Coder { public byte[] output; public int op; /** * Encode/decode another block of input data. this.output is * provided by the caller, and must be big enough to hold all * the coded data. On exit, this.opwill be set to the length * of the coded data. * * @param finish true if this is the final call to process for * this object. Will finalize the coder state and * include any final bytes in the output. * * @return true if the input so far is good; false if some * error has been detected in the input stream.. */ public abstract boolean process(byte[] input, int offset, int len, boolean finish); /** * @return the maximum number of bytes a call to process() * could produce for the given number of input bytes. This may * be an overestimate. */ public abstract int maxOutputSize(int len); } // -------------------------------------------------------- // decoding // -------------------------------------------------------- /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * <p>The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @param str the input String to decode, which is converted to * bytes using the default charset * @param flags controls certain features of the decoded output. * Pass {@code DEFAULT} to decode standard Base64. * * @throws IllegalArgumentException if the input contains * incorrect padding */ public static byte[] decode(String str, int flags) { return decode(str.getBytes(), flags); } /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * <p>The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @param input the input array to decode * @param flags controls certain features of the decoded output. * Pass {@code DEFAULT} to decode standard Base64. * * @throws IllegalArgumentException if the input contains * incorrect padding */ public static byte[] decode(byte[] input, int flags) { return decode(input, 0, input.length, flags); } /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * <p>The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @param input the data to decode * @param offset the position within the input array at which to start * @param len the number of bytes of input to decode * @param flags controls certain features of the decoded output. * Pass {@code DEFAULT} to decode standard Base64. * * @throws IllegalArgumentException if the input contains * incorrect padding */ public static byte[] decode(byte[] input, int offset, int len, int flags) { // Allocate space for the most data the input could represent. // (It could contain less if it contains whitespace, etc.) Decoder decoder = new Decoder(flags, new byte[len*3/4]); if (!decoder.process(input, offset, len, true)) { throw new IllegalArgumentException("bad base-64"); } // Maybe we got lucky and allocated exactly enough output space. if (decoder.op == decoder.output.length) { return decoder.output; } // Need to shorten the array, so allocate a new one of the // right size and copy. byte[] temp = new byte[decoder.op]; System.arraycopy(decoder.output, 0, temp, 0, decoder.op); return temp; } /* package */ static class Decoder extends Coder { /** * Lookup table for turning bytes into their position in the * Base64 alphabet. */ private static final int DECODE[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; /** * Decode lookup table for the "web safe" variant (RFC 3548 * sec. 4) where - and _ replace + and /. */ private static final int DECODE_WEBSAFE[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; /** Non-data values in the DECODE arrays. */ private static final int SKIP = -1; private static final int EQUALS = -2; /** * States 0-3 are reading through the next input tuple. * State 4 is having read one '=' and expecting exactly * one more. * State 5 is expecting no more data or padding characters * in the input. * State 6 is the error state; an error has been detected * in the input and no future input can "fix" it. */ private int state; // state number (0 to 6) private int value; final private int[] alphabet; public Decoder(int flags, byte[] output) { this.output = output; alphabet = ((flags & URL_SAFE) == 0) ? DECODE : DECODE_WEBSAFE; state = 0; value = 0; } /** * @return an overestimate for the number of bytes {@code * len} bytes could decode to. */ public int maxOutputSize(int len) { return len * 3/4 + 10; } /** * Decode another block of input data. * * @return true if the state machine is still healthy. false if * bad base-64 data has been detected in the input stream. */ public boolean process(byte[] input, int offset, int len, boolean finish) { if (this.state == 6) return false; int p = offset; len += offset; // Using local variables makes the decoder about 12% // faster than if we manipulate the member variables in // the loop. (Even alphabet makes a measurable // difference, which is somewhat surprising to me since // the member variable is final.) int state = this.state; int value = this.value; int op = 0; final byte[] output = this.output; final int[] alphabet = this.alphabet; while (p < len) { // Try the fast path: we're starting a new tuple and the // next four bytes of the input stream are all data // bytes. This corresponds to going through states // 0-1-2-3-0. We expect to use this method for most of // the data. // // If any of the next four bytes of input are non-data // (whitespace, etc.), value will end up negative. (All // the non-data values in decode are small negative // numbers, so shifting any of them up and or'ing them // together will result in a value with its top bit set.) // // You can remove this whole block and the output should // be the same, just slower. if (state == 0) { while (p+4 <= len && (value = ((alphabet[input[p] & 0xff] << 18) | (alphabet[input[p+1] & 0xff] << 12) | (alphabet[input[p+2] & 0xff] << 6) | (alphabet[input[p+3] & 0xff]))) >= 0) { output[op+2] = (byte) value; output[op+1] = (byte) (value >> 8); output[op] = (byte) (value >> 16); op += 3; p += 4; } if (p >= len) break; } // The fast path isn't available -- either we've read a // partial tuple, or the next four input bytes aren't all // data, or whatever. Fall back to the slower state // machine implementation. int d = alphabet[input[p++] & 0xff]; switch (state) { case 0: if (d >= 0) { value = d; ++state; } else if (d != SKIP) { this.state = 6; return false; } break; case 1: if (d >= 0) { value = (value << 6) | d; ++state; } else if (d != SKIP) { this.state = 6; return false; } break; case 2: if (d >= 0) { value = (value << 6) | d; ++state; } else if (d == EQUALS) { // Emit the last (partial) output tuple; // expect exactly one more padding character. output[op++] = (byte) (value >> 4); state = 4; } else if (d != SKIP) { this.state = 6; return false; } break; case 3: if (d >= 0) { // Emit the output triple and return to state 0. value = (value << 6) | d; output[op+2] = (byte) value; output[op+1] = (byte) (value >> 8); output[op] = (byte) (value >> 16); op += 3; state = 0; } else if (d == EQUALS) { // Emit the last (partial) output tuple; // expect no further data or padding characters. output[op+1] = (byte) (value >> 2); output[op] = (byte) (value >> 10); op += 2; state = 5; } else if (d != SKIP) { this.state = 6; return false; } break; case 4: if (d == EQUALS) { ++state; } else if (d != SKIP) { this.state = 6; return false; } break; case 5: if (d != SKIP) { this.state = 6; return false; } break; } } if (!finish) { // We're out of input, but a future call could provide // more. this.state = state; this.value = value; this.op = op; return true; } // Done reading input. Now figure out where we are left in // the state machine and finish up. switch (state) { case 0: // Output length is a multiple of three. Fine. break; case 1: // Read one extra input byte, which isn't enough to // make another output byte. Illegal. this.state = 6; return false; case 2: // Read two extra input bytes, enough to emit 1 more // output byte. Fine. output[op++] = (byte) (value >> 4); break; case 3: // Read three extra input bytes, enough to emit 2 more // output bytes. Fine. output[op++] = (byte) (value >> 10); output[op++] = (byte) (value >> 2); break; case 4: // Read one padding '=' when we expected 2. Illegal. this.state = 6; return false; case 5: // Read all the padding '='s we expected and no more. // Fine. break; } this.state = state; this.op = op; return true; } } // -------------------------------------------------------- // encoding // -------------------------------------------------------- /** * Base64-encode the given data and return a newly allocated * String with the result. * * @param input the data to encode * @param flags controls certain features of the encoded output. * Passing {@code DEFAULT} results in output that * adheres to RFC 2045. */ public static String encodeToString(byte[] input, int flags) { try { return new String(encode(input, flags), "US-ASCII"); } catch (UnsupportedEncodingException e) { // US-ASCII is guaranteed to be available. throw new AssertionError(e); } } /** * Base64-encode the given data and return a newly allocated * String with the result. * * @param input the data to encode * @param offset the position within the input array at which to * start * @param len the number of bytes of input to encode * @param flags controls certain features of the encoded output. * Passing {@code DEFAULT} results in output that * adheres to RFC 2045. */ public static String encodeToString(byte[] input, int offset, int len, int flags) { try { return new String(encode(input, offset, len, flags), "US-ASCII"); } catch (UnsupportedEncodingException e) { // US-ASCII is guaranteed to be available. throw new AssertionError(e); } } /** * Base64-encode the given data and return a newly allocated * byte[] with the result. * * @param input the data to encode * @param flags controls certain features of the encoded output. * Passing {@code DEFAULT} results in output that * adheres to RFC 2045. */ public static byte[] encode(byte[] input, int flags) { return encode(input, 0, input.length, flags); } /** * Base64-encode the given data and return a newly allocated * byte[] with the result. * * @param input the data to encode * @param offset the position within the input array at which to * start * @param len the number of bytes of input to encode * @param flags controls certain features of the encoded output. * Passing {@code DEFAULT} results in output that * adheres to RFC 2045. */ public static byte[] encode(byte[] input, int offset, int len, int flags) { Encoder encoder = new Encoder(flags, null); // Compute the exact length of the array we will produce. int output_len = len / 3 * 4; // Account for the tail of the data and the padding bytes, if any. if (encoder.do_padding) { if (len % 3 > 0) { output_len += 4; } } else { switch (len % 3) { case 0: break; case 1: output_len += 2; break; case 2: output_len += 3; break; } } // Account for the newlines, if any. if (encoder.do_newline && len > 0) { output_len += (((len-1) / (3 * Encoder.LINE_GROUPS)) + 1) * (encoder.do_cr ? 2 : 1); } encoder.output = new byte[output_len]; encoder.process(input, offset, len, true); assert encoder.op == output_len; return encoder.output; } /* package */ static class Encoder extends Coder { /** * Emit a new line every this many output tuples. Corresponds to * a 76-character line length (the maximum allowable according to * <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>). */ public static final int LINE_GROUPS = 19; /** * Lookup table for turning Base64 alphabet positions (6 bits) * into output bytes. */ private static final byte ENCODE[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', }; /** * Lookup table for turning Base64 alphabet positions (6 bits) * into output bytes. */ private static final byte ENCODE_WEBSAFE[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_', }; final private byte[] tail; /* package */ int tailLen; private int count; final public boolean do_padding; final public boolean do_newline; final public boolean do_cr; final private byte[] alphabet; public Encoder(int flags, byte[] output) { this.output = output; do_padding = (flags & NO_PADDING) == 0; do_newline = (flags & NO_WRAP) == 0; do_cr = (flags & CRLF) != 0; alphabet = ((flags & URL_SAFE) == 0) ? ENCODE : ENCODE_WEBSAFE; tail = new byte[2]; tailLen = 0; count = do_newline ? LINE_GROUPS : -1; } /** * @return an overestimate for the number of bytes {@code * len} bytes could encode to. */ public int maxOutputSize(int len) { return len * 8/5 + 10; } public boolean process(byte[] input, int offset, int len, boolean finish) { // Using local variables makes the encoder about 9% faster. final byte[] alphabet = this.alphabet; final byte[] output = this.output; int op = 0; int count = this.count; int p = offset; len += offset; int v = -1; // First we need to concatenate the tail of the previous call // with any input bytes available now and see if we can empty // the tail. switch (tailLen) { case 0: // There was no tail. break; case 1: if (p+2 <= len) { // A 1-byte tail with at least 2 bytes of // input available now. v = ((tail[0] & 0xff) << 16) | ((input[p++] & 0xff) << 8) | (input[p++] & 0xff); tailLen = 0; }; break; case 2: if (p+1 <= len) { // A 2-byte tail with at least 1 byte of input. v = ((tail[0] & 0xff) << 16) | ((tail[1] & 0xff) << 8) | (input[p++] & 0xff); tailLen = 0; } break; } if (v != -1) { output[op++] = alphabet[(v >> 18) & 0x3f]; output[op++] = alphabet[(v >> 12) & 0x3f]; output[op++] = alphabet[(v >> 6) & 0x3f]; output[op++] = alphabet[v & 0x3f]; if (--count == 0) { if (do_cr) output[op++] = '\r'; output[op++] = '\n'; count = LINE_GROUPS; } } // At this point either there is no tail, or there are fewer // than 3 bytes of input available. // The main loop, turning 3 input bytes into 4 output bytes on // each iteration. while (p+3 <= len) { v = ((input[p] & 0xff) << 16) | ((input[p+1] & 0xff) << 8) | (input[p+2] & 0xff); output[op] = alphabet[(v >> 18) & 0x3f]; output[op+1] = alphabet[(v >> 12) & 0x3f]; output[op+2] = alphabet[(v >> 6) & 0x3f]; output[op+3] = alphabet[v & 0x3f]; p += 3; op += 4; if (--count == 0) { if (do_cr) output[op++] = '\r'; output[op++] = '\n'; count = LINE_GROUPS; } } if (finish) { // Finish up the tail of the input. Note that we need to // consume any bytes in tail before any bytes // remaining in input; there should be at most two bytes // total. if (p-tailLen == len-1) { int t = 0; v = ((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 4; tailLen -= t; output[op++] = alphabet[(v >> 6) & 0x3f]; output[op++] = alphabet[v & 0x3f]; if (do_padding) { output[op++] = '='; output[op++] = '='; } if (do_newline) { if (do_cr) output[op++] = '\r'; output[op++] = '\n'; } } else if (p-tailLen == len-2) { int t = 0; v = (((tailLen > 1 ? tail[t++] : input[p++]) & 0xff) << 10) | (((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 2); tailLen -= t; output[op++] = alphabet[(v >> 12) & 0x3f]; output[op++] = alphabet[(v >> 6) & 0x3f]; output[op++] = alphabet[v & 0x3f]; if (do_padding) { output[op++] = '='; } if (do_newline) { if (do_cr) output[op++] = '\r'; output[op++] = '\n'; } } else if (do_newline && op > 0 && count != LINE_GROUPS) { if (do_cr) output[op++] = '\r'; output[op++] = '\n'; } assert tailLen == 0; assert p == len; } else { // Save the leftovers in tail to be consumed on the next // call to encodeInternal. if (p == len-1) { tail[tailLen++] = input[p]; } else if (p == len-2) { tail[tailLen++] = input[p]; tail[tailLen++] = input[p+1]; } } this.op = op; this.count = count; return true; } } private Base64() { } // don't instantiate }
bsd-3-clause
FuseMCNetwork/ZCore
src/main/java/net/fusemc/zcore/shopAPI/ShopManager.java
1808
package net.fusemc.zcore.shopAPI; import net.fusemc.zcore.ZCore; import net.fusemc.zcore.shopAPI.packets.UpdateListener; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.util.HashMap; import java.util.Map; /** * Created by Niklas on 20.08.2014. */ public class ShopManager { private Map<Player, PlayerShopData> playerCache; public ShopManager() { playerCache = new HashMap<>(); Bukkit.getPluginManager().registerEvents(new LeaveListener(), ZCore.getInstance()); if (!ZCore.OFFLINE)UpdateListener.registerEvents(); } public PlayerShopData getPlayerData(Player player) { if (playerCache.get(player) == null) { playerCache.put(player, new PlayerShopData(player)); } return playerCache.get(player); } public PlayerShopData updateFromDatabase(Player player) { if (playerCache.get(player) != null) { playerCache.get(player).updateFromDatabase(); } return getPlayerData(player); } public PlayerShopData updateCoinsFromDatabase(Player player) { if (playerCache.get(player) != null) { playerCache.get(player).updateCoins(); } return getPlayerData(player); } public PlayerShopData updatePackagesFromDatabase(Player player) { if (playerCache.get(player) != null) { playerCache.get(player).updatePackages(); } return getPlayerData(player); } public static Player getPlayerByUuid(String uuid) { for (Player p : Bukkit.getOnlinePlayers()) { if (p.getUniqueId().toString().equals(uuid)) { return p; } } return null; } void removeFromCache(Player player) { playerCache.remove(player); } }
bsd-3-clause
aic-sri-international/aic-util
src/main/java/com/sri/ai/util/collect/IntegerIterator.java
3628
/* * Copyright (c) 2013, SRI International * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the aic-util nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sri.ai.util.collect; import com.google.common.annotations.Beta; import org.apache.commons.lang3.Validate; /** * An iterator over a given integer interval * {@code [start, end[} (that is, with inclusive start and exclusive end) * with a specified increment over the interval. * * @author braz * */ @Beta public class IntegerIterator extends EZIterator<Integer> { private int i; private boolean infinite; private int end; private int increment; /** * Constructor. * * @param start * the starting integer, inclusive. * @param end * the ending integer in the range, exclusive. * @param increment * the amount to increment on each iteration. */ public IntegerIterator(int start, int end, int increment) { this.i = start; this.end = end; this.infinite = false; this.increment = increment; Validate.isTrue(increment > 0, "Increment=%d must be greater than zero", increment); Validate.isTrue(start < end, "start=%d must be less than end=%d", start, end); } /** * Constructor with a default increment of 1. * * @param start * the starting integer, inclusive. * @param end * the ending integer in the range, exclusive. */ public IntegerIterator(int start, int end) { this(start, end, 1); } /** * Constructor starting at a given integer and incrementing indefinitely. * * @param start the initial value (there is no end value) */ private IntegerIterator(int start) { this.i = start; this.increment = 1; this.infinite = true; } public static IntegerIterator fromThisValueOnForever(int start) { return new IntegerIterator(start); } @Override protected Integer calculateNext() { if (infinite || i < end) { int next = i; i += increment; return next; } return null; } }
bsd-3-clause
iti-luebeck/MARS
MARS_NB/MARS/MARSCore/src/mars/sensors/Orientationmeter.java
5423
/* * Copyright (c) 2015, Institute of Computer Engineering, University of Lübeck * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package mars.sensors; import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.scene.Node; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import mars.Helper.NoiseType; import mars.PhysicalEnvironment; import mars.PhysicalExchange.PhysicalExchanger; import mars.events.AUVObjectEvent; import mars.states.SimState; /** * Gives the exact orientation of the auv. * * @author Thomas Tosik */ @XmlAccessorType(XmlAccessType.NONE) public class Orientationmeter extends Sensor { Quaternion new_orientation = new Quaternion(); Quaternion old_orientation = new Quaternion(); /** * */ public Orientationmeter() { super(); } /** * * @param simstate * @param pe */ public Orientationmeter(SimState simstate, PhysicalEnvironment pe) { super(simstate); this.pe = pe; } /** * * @param simstate */ public Orientationmeter(SimState simstate) { super(simstate); } /** * * @param sensor */ public Orientationmeter(Orientationmeter sensor) { super(sensor); } /** * * @return */ @Override public PhysicalExchanger copy() { Orientationmeter sensor = new Orientationmeter(this); sensor.initAfterJAXB(); return sensor; } /** * */ @Override public void init(Node auv_node) { super.init(auv_node); } /** * * @param tpf */ public void update(float tpf) { new_orientation = physics_control.getPhysicsRotation();//get the new velocity old_orientation = new_orientation.clone(); } /** * * @param addedOrientation */ public void setAddedOrientation(Vector3f addedOrientation) { variables.put("addedOrientation", addedOrientation); } /** * * @return */ public Vector3f getAddedOrientation() { return (Vector3f) variables.get("addedOrientation"); } /** * * @return */ public Quaternion getOrientation() { if (getNoiseType() == NoiseType.NO_NOISE) { return getOrientationRaw(); } else if (getNoiseType() == NoiseType.UNIFORM_DISTRIBUTION) { float noise = getUnifromDistributionNoise(getNoiseValue()); Quaternion noised = new Quaternion(getOrientationRaw().getX() + (((1f / 100f) * noise)), getOrientationRaw().getY() + (((1f / 100f) * noise)), getOrientationRaw().getY() + (((1f / 100f) * noise)), getOrientationRaw().getW() + (((1f / 100f) * noise))); return noised; } else if (getNoiseType() == NoiseType.GAUSSIAN_NOISE_FUNCTION) { float noise = getGaussianDistributionNoise(getNoiseValue()); Quaternion noised = new Quaternion(getOrientationRaw().getX() + (((1f / 100f) * noise)), getOrientationRaw().getY() + (((1f / 100f) * noise)), getOrientationRaw().getZ() + (((1f / 100f) * noise)), getOrientationRaw().getW() + (((1f / 100f) * noise))); return noised; } else { return getOrientationRaw(); } } /** * * @return */ private Quaternion getOrientationRaw() { Quaternion quat = new Quaternion(); quat.fromAngles(getAddedOrientation().getX(), getAddedOrientation().getY(), getAddedOrientation().getZ()); return physics_control.getPhysicsRotation().mult(quat); } /** * */ @Override public void reset() { } @Override public void publishData() { super.publishData(); AUVObjectEvent auvEvent = new AUVObjectEvent(this, getOrientation(), System.currentTimeMillis()); notifyAdvertisementAUVObject(auvEvent); } }
bsd-3-clause
thelateperseus/ant-ivy
src/java/fr/jayasoft/ivy/ant/IvyRepositoryReport.java
8783
package fr.jayasoft.ivy.ant; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.XSLTProcess; import fr.jayasoft.ivy.DefaultModuleDescriptor; import fr.jayasoft.ivy.Ivy; import fr.jayasoft.ivy.ModuleId; import fr.jayasoft.ivy.ModuleRevisionId; import fr.jayasoft.ivy.filter.FilterHelper; import fr.jayasoft.ivy.matcher.PatternMatcher; import fr.jayasoft.ivy.report.ResolveReport; import fr.jayasoft.ivy.report.XmlReportOutputter; import fr.jayasoft.ivy.util.FileUtil; /** * Generates a report of dependencies of a set of modules in the repository. * * The set of modules is specified using organisation/module and matcher. * * @author Xavier Hanin * */ public class IvyRepositoryReport extends IvyTask { private String _organisation = "*"; private String _module; private String _branch; private String _revision = "latest.integration"; private File _cache; private String _matcher = PatternMatcher.EXACT_OR_REGEXP; private File _todir = new File("."); private boolean _graph = false; private boolean _dot = false; private boolean _xml = true; private boolean _xsl = false; private String _xslFile; private String _outputname = "ivy-repository-report"; private String _xslext = "html"; private List _params = new ArrayList(); public void execute() throws BuildException { Ivy ivy = getIvyInstance(); if (_cache == null) { _cache = ivy.getDefaultCache(); } if (_xsl && _xslFile == null) { throw new BuildException("xsl file is mandatory when using xsl generation"); } if (_module == null && PatternMatcher.EXACT.equals(_matcher)) { throw new BuildException("no module name provided for ivy repository graph task: It can either be set explicitely via the attribute 'module' or via 'ivy.module' property or a prior call to <resolve/>"); } else if (_module == null && !PatternMatcher.EXACT.equals(_matcher)) { _module = PatternMatcher.ANY_EXPRESSION; } ModuleRevisionId mrid = ModuleRevisionId.newInstance(_organisation, _module, _revision); try { ModuleId[] mids = ivy.listModules(new ModuleId(_organisation, _module), ivy.getMatcher(_matcher)); ModuleRevisionId[] mrids = new ModuleRevisionId[mids.length]; for (int i = 0; i < mrids.length; i++) { if (_branch != null) { mrids[i] = new ModuleRevisionId(mids[i], _branch, _revision); } else { mrids[i] = new ModuleRevisionId(mids[i], _revision); } } DefaultModuleDescriptor md = DefaultModuleDescriptor.newCallerInstance(mrids, true, false); ResolveReport report = ivy.resolve(md, new String[] {"*"}, _cache, null, doValidate(ivy), false, true, false, false, FilterHelper.NO_FILTER); new XmlReportOutputter().output(report, _cache); if (_graph) { gengraph(_cache, md.getModuleRevisionId().getOrganisation(), md.getModuleRevisionId().getName()); } if (_dot) { gendot(_cache, md.getModuleRevisionId().getOrganisation(), md.getModuleRevisionId().getName()); } if (_xml) { FileUtil.copy(new File(_cache, XmlReportOutputter.getReportFileName(md.getModuleRevisionId().getModuleId(), "default")), new File(_todir, _outputname+".xml"), null); } if (_xsl) { genreport(_cache, md.getModuleRevisionId().getOrganisation(), md.getModuleRevisionId().getName()); } } catch (Exception e) { throw new BuildException("impossible to generate graph for "+ mrid +": "+e, e); } } private void genreport(File cache, String organisation, String module) throws IOException { // first process the report with xslt XSLTProcess xslt = new XSLTProcess(); xslt.setTaskName(getTaskName()); xslt.setProject(getProject()); xslt.init(); xslt.setIn(new File(cache, XmlReportOutputter.getReportFileName(new ModuleId(organisation, module), "default"))); xslt.setOut(new File(_todir, _outputname+"."+_xslext)); xslt.setStyle(_xslFile); XSLTProcess.Param param = xslt.createParam(); param.setName("extension"); param.setExpression(_xslext); // add the provided XSLT parameters for (Iterator it = _params.iterator(); it.hasNext(); ) { param = (XSLTProcess.Param) it.next(); XSLTProcess.Param realParam = xslt.createParam(); realParam.setName(param.getName()); realParam.setExpression(param.getExpression()); } xslt.execute(); } private void gengraph(File cache, String organisation, String module) throws IOException { gen(cache, organisation, module, getGraphStylePath(cache), "graphml"); } private String getGraphStylePath(File cache) throws IOException { // style should be a file (and not an url) // so we have to copy it from classpath to cache File style = new File(cache, "ivy-report-graph-all.xsl"); FileUtil.copy(XmlReportOutputter.class.getResourceAsStream("ivy-report-graph-all.xsl"), style, null); return style.getAbsolutePath(); } private void gendot(File cache, String organisation, String module) throws IOException { gen(cache, organisation, module, getDotStylePath(cache), "dot"); } private String getDotStylePath(File cache) throws IOException { // style should be a file (and not an url) // so we have to copy it from classpath to cache File style = new File(cache, "ivy-report-dot-all.xsl"); FileUtil.copy(XmlReportOutputter.class.getResourceAsStream("ivy-report-dot-all.xsl"), style, null); return style.getAbsolutePath(); } private void gen(File cache, String organisation, String module, String style, String ext) throws IOException { XSLTProcess xslt = new XSLTProcess(); xslt.setTaskName(getTaskName()); xslt.setProject(getProject()); xslt.init(); xslt.setIn(new File(cache, XmlReportOutputter.getReportFileName(new ModuleId(organisation, module), "default"))); xslt.setOut(new File(_todir, _outputname+"."+ext)); xslt.setBasedir(cache); xslt.setStyle(style); xslt.execute(); } public File getTodir() { return _todir; } public void setTodir(File todir) { _todir = todir; } public boolean isGraph() { return _graph; } public void setGraph(boolean graph) { _graph = graph; } public String getXslfile() { return _xslFile; } public void setXslfile(String xslFile) { _xslFile = xslFile; } public boolean isXml() { return _xml; } public void setXml(boolean xml) { _xml = xml; } public boolean isXsl() { return _xsl; } public void setXsl(boolean xsl) { _xsl = xsl; } public String getXslext() { return _xslext; } public void setXslext(String xslext) { _xslext = xslext; } public XSLTProcess.Param createParam() { XSLTProcess.Param result = new XSLTProcess.Param(); _params.add(result); return result; } public String getOutputname() { return _outputname; } public void setOutputname(String outputpattern) { _outputname = outputpattern; } public File getCache() { return _cache; } public void setCache(File cache) { _cache = cache; } public String getMatcher() { return _matcher; } public void setMatcher(String matcher) { _matcher = matcher; } public String getModule() { return _module; } public void setModule(String module) { _module = module; } public String getOrganisation() { return _organisation; } public void setOrganisation(String organisation) { _organisation = organisation; } public String getRevision() { return _revision; } public void setRevision(String revision) { _revision = revision; } public String getBranch() { return _branch; } public void setBranch(String branch) { _branch = branch; } public boolean isDot() { return _dot; } public void setDot(boolean dot) { _dot = dot; } }
bsd-3-clause
croeder/ccp_nlp
ae/src/main/java/edu/ucdenver/ccp/nlp/ae/opendmap/TestSummarizer.java
5426
/* * TestSummarizer.java * Copyright (C) 2007 Center for Computational Pharmacology, University of Colorado School of Medicine * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package edu.ucdenver.ccp.nlp.ae.opendmap; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import org.apache.uima.jcas.JCas; import edu.ucdenver.ccp.nlp.ts.TextAnnotation; import edu.ucdenver.ccp.nlp.ts.ClassMention; /** * This class prints out selected contents of the CAS in the standard * annotation summery format. * * @author R. James Firby */ public class TestSummarizer { private static final String MENTION_SEPARATOR = ";"; private static final String SLOT_SEPARATOR = ","; /* The mentions in the CAS to print */ private HashMap<String, String[]> mentionsOfInterest = null; /** * Create a new TestSummarizer that will generate summary strings for the mentions and slots * specified in the pattern. * <p> * A mention pattern has the form: * <pre> * type,slot,slot;type,slot,slot;... * </pre> * Where 'type' is the name of a mention type to print, and the 'slot's * following the 'type' are thje slots for that type to include in the * output. * * @param mentionPattern The pattern defining the mention types and slots to print. */ public TestSummarizer(String mentionPattern) { if (mentionPattern != null) { String mentionTypes[] = mentionPattern.split(MENTION_SEPARATOR); if ((mentionTypes != null) && (mentionTypes.length > 0)) { mentionsOfInterest = new HashMap<String, String[]>(); for (int i=0; i<mentionTypes.length; i++) { String typeParts[] = mentionTypes[i].split(SLOT_SEPARATOR); if ((typeParts != null) && (typeParts.length > 0)) { String typeName = typeParts[0].trim().toLowerCase(); if (typeParts.length > 1) { String slotNames[] = new String[typeParts.length-1]; for (int j=1; j<typeParts.length; j++) slotNames[j-1] = typeParts[j].trim(); mentionsOfInterest.put(typeName, slotNames); } else { mentionsOfInterest.put(typeName, null); } } } } } } /** * Generate summary strings for all annotations in the JCAS that are described in the * pattern string for this summarizer. * * @param docId The document ID that has been analyzed to fill the JCas * @param jcas The JCas holding the annotations to be summarized * @return A set of summary strings, one for each annotation of interest in the JCas */ public ArrayList<String> summarizeJCas(String docId, JCas jcas) { ArrayList<String> summary = new ArrayList<String>(); // Get the GeneRIF text String docText = jcas.getDocumentText(); // Print out all output annotations for this generif Iterator annotationIter = jcas.getJFSIndexRepository().getAnnotationIndex(TextAnnotation.type).iterator(); while ((annotationIter != null) && annotationIter.hasNext()) { Object thing = annotationIter.next(); if (thing instanceof TextAnnotation) { TextAnnotation annotation = (TextAnnotation) thing; if (isAnnotationOfInterest(annotation)) { // Get the annotation string and print it AnnotationString annotationString = new AnnotationString(annotation, slotsOfInterest(annotation), docId, docText); summary.add(annotationString.toString()); } } } // Done return summary; } /** * Checks whether and annotation is specified in the pattern string for * this summarizer. * * @param annotation The annotation to check. * @return 'True' if this annotation should be summarized in the output. */ private boolean isAnnotationOfInterest(TextAnnotation annotation) { // If nothing was specified, default to everything if (mentionsOfInterest == null) return true; // See if this annotations mention is of interest ClassMention mention = annotation.getClassMention(); String className = mention.getMentionName(); return ((className != null) && mentionsOfInterest.containsKey(className.trim().toLowerCase())); } /** * Get all the slots that should be included in the summary for this annotation. * * @param annotation The annotation to summarize. * @return The set of slots to include in the summary. */ private String[] slotsOfInterest(TextAnnotation annotation) { // If nothing was specified, default to everything if (mentionsOfInterest == null) return null; // See if this annotations mention is of interest ClassMention mention = annotation.getClassMention(); String className = mention.getMentionName(); if (className != null) { return mentionsOfInterest.get(className.trim().toLowerCase()); } else { return null; } } }
bsd-3-clause
kstreee/infer
infer/tests/frontend/c/TypesTest.java
921
/* * Copyright (c) 2013 - present Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package frontend.c; import org.junit.Rule; import org.junit.Test; import java.io.IOException; import utils.DebuggableTemporaryFolder; import utils.InferException; import utils.ClangFrontendUtils; import utils.InferRunner; public class TypesTest { @Rule public DebuggableTemporaryFolder folder = new DebuggableTemporaryFolder(); @Test public void whenCaptureRunStructThenDotFilesAreTheSame() throws InterruptedException, IOException, InferException { String src = "infer/tests/codetoanalyze/c/frontend/types/struct.c"; ClangFrontendUtils.createAndCompareCDotFiles(folder, src); } }
bsd-3-clause
gfiorav/PTAT
app/src/main/java/com/imdea/fioravantti/guido/ecousin_ptat/util/Notifier.java
2059
package com.imdea.fioravantti.guido.ecousin_ptat.util; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import com.imdea.fioravantti.guido.ecousin_ptat.Constants; import com.imdea.fioravantti.guido.ecousin_ptat.R; /** * Created by guido on 12/28/14. */ public class Notifier { Context context; NotificationManager nm; Class goToClass; public Notifier (Context context, Class clss) { setContext(context); setGoToClass(clss); nm = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE); } public void showRunning () { Notification.Builder b = new Notification.Builder(getContext()); Resources rsrc = getContext().getResources(); b.setContentTitle(rsrc.getString(R.string.txtNotTitle)); b.setContentText(rsrc.getString(R.string.txtNotBody)); b.setTicker(rsrc.getString(R.string.txtNotTicker)); b.setSmallIcon(R.drawable.ic_launcher); b.setOngoing(true); Intent goToIntent = new Intent(context, getGoToClass()); goToIntent.setAction(Intent.ACTION_MAIN); goToIntent.addCategory(Intent.CATEGORY_LAUNCHER); PendingIntent pi = PendingIntent.getActivity( context, 0, goToIntent, PendingIntent.FLAG_UPDATE_CURRENT ); b.setContentIntent(pi); nm.notify(Constants.runningNotID, b.build()); } public void hideRunning () { nm.cancel(Constants.runningNotID); } public Context getContext() { return context; } public void setContext(Context context) { this.context = context; } public Class getGoToClass() { return goToClass; } public void setGoToClass(Class goToClass) { this.goToClass = goToClass; } }
bsd-3-clause
ardydedase/mltk
src/mltk/predictor/gam/SPLAMLearner.java
45484
package mltk.predictor.gam; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import mltk.cmdline.Argument; import mltk.cmdline.CmdLineParser; import mltk.core.Instances; import mltk.core.io.InstancesReader; import mltk.predictor.Learner; import mltk.predictor.Regressor; import mltk.predictor.function.CubicSpline; import mltk.predictor.function.LinearFunction; import mltk.predictor.glm.GLM; import mltk.predictor.glm.RidgeLearner; import mltk.predictor.io.PredictorWriter; import mltk.util.ArrayUtils; import mltk.util.MathUtils; import mltk.util.OptimUtils; import mltk.util.StatUtils; import mltk.util.VectorUtils; /** * Class for learning SPLAM models. Currently only cubic spline basis is supported. * * @author Yin Lou * */ public class SPLAMLearner extends Learner { static class ModelStructure { static final byte ELIMINATED = 0; static final byte LINEAR = 1; static final byte NONLINEAR = 2; byte[] structure; ModelStructure(byte[] structure) { this.structure = structure; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ModelStructure other = (ModelStructure) obj; if (!Arrays.equals(structure, other.structure)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(structure); return result; } } static class Options { @Argument(name = "-r", description = "attribute file path") String attPath = null; @Argument(name = "-t", description = "train set path", required = true) String trainPath = null; @Argument(name = "-o", description = "output model path") String outputModelPath = null; @Argument(name = "-g", description = "task between classification (c) and regression (r) (default: r)") String task = "r"; @Argument(name = "-d", description = "number of knots (default: 10)") int numKnots = 10; @Argument(name = "-m", description = "maximum number of iterations (default: 0)") int maxNumIters = 0; @Argument(name = "-l", description = "lambda (default: 0)") double lambda = 0; @Argument(name = "-a", description = "alpha (default: 1, i.e., SPAM model)") double alpha = 1; } /** * <p> * * <pre> * Usage: SPLAMLearner * -t train set path * [-r] attribute file path * [-o] output model path * [-g] task between classification (c) and regression (r) (default: r) * [-d] number of knots (default: 10) * [-m] maximum number of iterations (default: 0) * [-l] lambda (default: 0) * [-a] alpha (default: 1, i.e., SPAM model) * </pre> * * </p> * * @param args the command line arguments. * @throws Exception */ public static void main(String[] args) throws Exception { Options opts = new Options(); CmdLineParser parser = new CmdLineParser(SPLAMLearner.class, opts); Task task = null; try { parser.parse(args); task = Task.getEnum(opts.task); if (opts.numKnots < 0) { throw new IllegalArgumentException("Number of knots must be positive."); } } catch (IllegalArgumentException e) { parser.printUsage(); System.exit(1); } Instances trainSet = InstancesReader.read(opts.attPath, opts.trainPath); SPLAMLearner splamLearner = new SPLAMLearner(); splamLearner.setNumKnots(opts.numKnots); splamLearner.setMaxNumIters(opts.maxNumIters); splamLearner.setLambda(opts.lambda); splamLearner.setAlpha(opts.alpha); splamLearner.setTask(task); splamLearner.setVerbose(true); long start = System.currentTimeMillis(); GAM gam = splamLearner.build(trainSet); long end = System.currentTimeMillis(); System.out.println("Time: " + (end - start) / 1000.0); if (opts.outputModelPath != null) { PredictorWriter.write(gam, opts.outputModelPath); } } private boolean verbose; private boolean fitIntercept; private boolean refit; private int numKnots; private int maxNumIters; private Task task; private double lambda; private double alpha; private double epsilon; /** * Constructor. */ public SPLAMLearner() { verbose = false; fitIntercept = true; refit = false; numKnots = 10; maxNumIters = -1; lambda = 0.0; alpha = 1; epsilon = MathUtils.EPSILON; task = Task.REGRESSION; } @Override public GAM build(Instances instances) { GAM gam = null; if (maxNumIters < 0) { maxNumIters = 20; } if (numKnots < 0) { numKnots = 10; } switch (task) { case REGRESSION: gam = buildRegressor(instances, maxNumIters, numKnots, lambda, alpha); break; case CLASSIFICATION: gam = buildClassifier(instances, maxNumIters, numKnots, lambda, alpha); break; default: break; } return gam; } /** * Returns a binary classifier. * * @param attrs the attribute list. * @param x the inputs. * @param y the targets. * @param knots the knots. * @param maxNumIters the maximum number of iterations. * @param lambda the lambda. * @param alpha the alpha. * @return a binary classifier. */ public GAM buildBinaryClassifier(int[] attrs, double[][][] x, double[] y, double[][] knots, int maxNumIters, double lambda, double alpha) { double[][] w = new double[attrs.length][]; int m = 0; for (int j = 0; j < attrs.length; j++) { w[j] = new double[x[j].length]; if (w[j].length > m) { m = w[j].length; } } double[] tl1 = new double[attrs.length]; double[] tl2 = new double[attrs.length]; getRegularizationParameters(lambda, alpha, tl1, tl2, y.length); double[] pTrain = new double[y.length]; double[] rTrain = new double[y.length]; OptimUtils.computePseudoResidual(pTrain, y, rTrain); double[] stepSize = new double[attrs.length]; for (int j = 0; j < stepSize.length; j++) { double max = 0; double[][] block = x[j]; for (double[] t : block) { double l = StatUtils.sumSq(t) / 4; if (l > max) { max = l; } } stepSize[j] = 1.0 / max; } double[] g = new double[m]; double[] gradient = new double[m]; double[] gamma1 = new double[m]; double[] gamma2 = new double[m - 1]; boolean[] activeSet = new boolean[attrs.length]; double intercept = 0; // Block coordinate gradient descent int iter = 0; while (iter < maxNumIters) { if (fitIntercept) { intercept += OptimUtils.fitIntercept(pTrain, rTrain, y); } boolean activeSetChanged = doOnePass(x, y, tl1, tl2, true, activeSet, w, stepSize, g, gradient, gamma1, gamma2, pTrain, rTrain); iter++; if (!activeSetChanged || iter > maxNumIters) { break; } for (; iter < maxNumIters; iter++) { double prevLoss = OptimUtils.computeLogisticLoss(pTrain, y) + getPenalty(w, tl1, tl2); if (fitIntercept) { intercept += OptimUtils.fitIntercept(pTrain, rTrain, y); } doOnePass(x, y, tl1, tl2, false, activeSet, w, stepSize, g, gradient, gamma1, gamma2, pTrain, rTrain); double currLoss = OptimUtils.computeLogisticLoss(pTrain, y) + getPenalty(w, tl1, tl2); if (OptimUtils.isConverged(prevLoss, currLoss, epsilon)) { break; } if (verbose) { System.out.println("Iteration " + iter + ": " + currLoss); } } } if (refit) { byte[] structure = extractStructure(w); GAM gam = refitClassifier(attrs, structure, x, y, knots, w, maxNumIters); return gam; } else { return getGAM(attrs, knots, w, intercept); } } /** * Returns a binary classifier. * * @param attrs the attribute list. * @param indices the indices. * @param values the values. * @param y the targets. * @param knots the knots. * @param maxNumIters the maximum number of iterations. * @param lambda the lambda. * @param alpha the alpha. * @return a binary classifier. */ public GAM buildBinaryClassifier(int[] attrs, int[][] indices, double[][][] values, double[] y, double[][] knots, int maxNumIters, double lambda, double alpha) { double[][] w = new double[attrs.length][]; int m = 0; for (int j = 0; j < attrs.length; j++) { w[j] = new double[values[j].length]; if (w[j].length > m) { m = w[j].length; } } double[] tl1 = new double[attrs.length]; double[] tl2 = new double[attrs.length]; getRegularizationParameters(lambda, alpha, tl1, tl2, y.length); double[] pTrain = new double[y.length]; double[] rTrain = new double[y.length]; OptimUtils.computePseudoResidual(pTrain, y, rTrain); double[] stepSize = new double[attrs.length]; for (int j = 0; j < stepSize.length; j++) { double max = 0; double[][] block = values[j]; for (double[] t : block) { double l = StatUtils.sumSq(t) / 4; if (l > max) { max = l; } } stepSize[j] = 1.0 / max; } double[] g = new double[m]; double[] gradient = new double[m]; double[] gamma1 = new double[m]; double[] gamma2 = new double[m - 1]; boolean[] activeSet = new boolean[attrs.length]; double intercept = 0; // Block coordinate gradient descent int iter = 0; while (iter < maxNumIters) { if (fitIntercept) { intercept += OptimUtils.fitIntercept(pTrain, y, rTrain); } boolean activeSetChanged = doOnePass(indices, values, y, tl1, tl2, true, activeSet, w, stepSize, g, gradient, gamma1, gamma2, pTrain, rTrain); iter++; if (!activeSetChanged || iter > maxNumIters) { break; } for (; iter < maxNumIters; iter++) { double prevLoss = OptimUtils.computeLogisticLoss(pTrain, y) + getPenalty(w, tl1, tl2); if (fitIntercept) { intercept += OptimUtils.fitIntercept(pTrain, rTrain, y); } doOnePass(indices, values, y, tl1, tl2, false, activeSet, w, stepSize, g, gradient, gamma1, gamma2, pTrain, rTrain); double currLoss = OptimUtils.computeLogisticLoss(pTrain, y) + getPenalty(w, tl1, tl2); if (OptimUtils.isConverged(prevLoss, currLoss, epsilon)) { break; } if (verbose) { System.out.println("Iteration " + iter + ": " + currLoss); } } } if (refit) { byte[] structure = extractStructure(w); GAM gam = refitClassifier(attrs, structure, indices, values, y, knots, w, maxNumIters * 10); return gam; } else { return getGAM(attrs, knots, w, intercept); } } /** * Builds a classifier. * * @param trainSet the training set. * @param isSparse <code>true</code> if the training set is treated as sparse. * @param numKnots the number of knots. * @param maxNumIters the maximum number of iterations. * @param lambda the lambda. * @param alpha the alpha. * @return a classifier. */ public GAM buildClassifier(Instances trainSet, boolean isSparse, int numKnots, int maxNumIters, double lambda, double alpha) { if (isSparse) { SparseDataset sd = getSparseDataset(trainSet, false); SparseDesignMatrix sm = SparseDesignMatrix.createCubicSplineDesignMatrix(trainSet.size(), sd.indices, sd.values, sd.stdList, numKnots); double[] y = sd.y; int[][] indices = sm.indices; double[][][] values = sm.values; double[][] knots = sm.knots; int[] attrs = sd.attrs; // Mapping from attribute index to index in design matrix Map<Integer, Integer> map = new HashMap<>(); for (int j = 0; j < sd.attrs.length; j++) { map.put(attrs[j], j); } GAM gam = buildBinaryClassifier(attrs, indices, values, y, knots, maxNumIters, lambda, alpha); // Rescale weights in gam List<Regressor> regressors = gam.getRegressors(); List<int[]> terms = gam.getTerms(); double intercept = gam.getIntercept(); for (int i = 0; i < regressors.size(); i++) { Regressor regressor = regressors.get(i); int attIndex = terms.get(i)[0]; int idx = map.get(attIndex); double[] std = sm.std[idx]; if (regressor instanceof LinearFunction) { LinearFunction func = (LinearFunction) regressor; func.setSlope(func.getSlope() / std[0]); } else if (regressor instanceof CubicSpline) { CubicSpline spline = (CubicSpline) regressor; double[] w = spline.getCoefficients(); for (int j = 0; j < w.length; j++) { w[j] /= std[j]; } double[] k = spline.getKnots(); for (int j = 0; j < k.length; j++) { intercept -= w[j + 3] * CubicSpline.h(0, k[j]); } } } if (fitIntercept) { gam.setIntercept(intercept); } return gam; } else { DenseDataset dd = getDenseDataset(trainSet, false); DenseDesignMatrix dm = DenseDesignMatrix.createCubicSplineDesignMatrix(dd.x, dd.stdList, numKnots); double[] y = dd.y; double[][][] x = dm.x; double[][] knots = dm.knots; int[] attrs = dd.attrs; // Mapping from attribute index to index in design matrix Map<Integer, Integer> map = new HashMap<>(); for (int j = 0; j < dd.attrs.length; j++) { map.put(dd.attrs[j], j); } GAM gam = buildBinaryClassifier(attrs, x, y, knots, maxNumIters, lambda, alpha); // Rescale weights in gam List<Regressor> regressors = gam.getRegressors(); List<int[]> terms = gam.getTerms(); for (int i = 0; i < regressors.size(); i++) { Regressor regressor = regressors.get(i); int attIndex = terms.get(i)[0]; int idx = map.get(attIndex); double[] std = dm.std[idx]; if (regressor instanceof LinearFunction) { LinearFunction func = (LinearFunction) regressor; func.setSlope(func.getSlope() / std[0]); } else if (regressor instanceof CubicSpline) { CubicSpline spline = (CubicSpline) regressor; double[] w = spline.getCoefficients(); for (int j = 0; j < w.length; j++) { w[j] /= std[j]; } } } return gam; } } /** * Builds a classifier. * * @param trainSet the training set. * @param maxNumIters the maximum number of iterations. * @param numKnots the number of knots. * @param lambda the lambda. * @param alpha the alpha. * @param fitIntercept whether the intercept is included. * @return a classifier. */ public GAM buildClassifier(Instances trainSet, int maxNumIters, int numKnots, double lambda, double alpha) { return buildClassifier(trainSet, isSparse(trainSet), maxNumIters, numKnots, lambda, alpha); } /** * Builds a regressor. * * @param trainSet the training set. * @param isSparse <code>true</code> if the training set is treated as sparse. * @param maxNumIters the maximum number of iterations. * @param numKnots the number of knots. * @param lambda the lambda. * @param alpha the alpha. * @return a regressor. */ public GAM buildRegressor(Instances trainSet, boolean isSparse, int maxNumIters, int numKnots, double lambda, double alpha) { if (isSparse) { SparseDataset sd = getSparseDataset(trainSet, false); SparseDesignMatrix sm = SparseDesignMatrix.createCubicSplineDesignMatrix(trainSet.size(), sd.indices, sd.values, sd.stdList, numKnots); double[] y = sd.y; int[][] indices = sm.indices; double[][][] values = sm.values; double[][] knots = sm.knots; int[] attrs = sd.attrs; // Mapping from attribute index to index in design matrix Map<Integer, Integer> map = new HashMap<>(); for (int j = 0; j < sd.attrs.length; j++) { map.put(attrs[j], j); } GAM gam = buildRegressor(attrs, indices, values, y, knots, maxNumIters, lambda, alpha); // Rescale weights in gam List<Regressor> regressors = gam.getRegressors(); List<int[]> terms = gam.getTerms(); double intercept = gam.getIntercept(); for (int i = 0; i < regressors.size(); i++) { Regressor regressor = regressors.get(i); int attIndex = terms.get(i)[0]; int idx = map.get(attIndex); double[] std = sm.std[idx]; if (regressor instanceof LinearFunction) { LinearFunction func = (LinearFunction) regressor; func.setSlope(func.getSlope() / std[0]); } else if (regressor instanceof CubicSpline) { CubicSpline spline = (CubicSpline) regressor; double[] w = spline.getCoefficients(); for (int j = 0; j < w.length; j++) { w[j] /= std[j]; } double[] k = spline.getKnots(); for (int j = 0; j < k.length; j++) { intercept -= w[j + 3] * CubicSpline.h(0, k[j]); } } } if (fitIntercept) { gam.setIntercept(intercept); } return gam; } else { DenseDataset dd = getDenseDataset(trainSet, false); DenseDesignMatrix dm = DenseDesignMatrix.createCubicSplineDesignMatrix(dd.x, dd.stdList, numKnots); double[] y = dd.y; double[][][] x = dm.x; double[][] knots = dm.knots; int[] attrs = dd.attrs; // Mapping from attribute index to index in design matrix Map<Integer, Integer> map = new HashMap<>(); for (int j = 0; j < dd.attrs.length; j++) { map.put(dd.attrs[j], j); } GAM gam = buildRegressor(attrs, x, y, knots, maxNumIters, lambda, alpha); // Rescale weights in gam List<Regressor> regressors = gam.getRegressors(); List<int[]> terms = gam.getTerms(); for (int i = 0; i < regressors.size(); i++) { Regressor regressor = regressors.get(i); int attIndex = terms.get(i)[0]; int idx = map.get(attIndex); double[] std = dm.std[idx]; if (regressor instanceof LinearFunction) { LinearFunction func = (LinearFunction) regressor; func.setSlope(func.getSlope() / std[0]); } else if (regressor instanceof CubicSpline) { CubicSpline spline = (CubicSpline) regressor; double[] w = spline.getCoefficients(); for (int j = 0; j < w.length; j++) { w[j] /= std[j]; } } } return gam; } } /** * Builds a regressor. * * @param trainSet the training set. * @param maxNumIters the maximum number of iterations. * @param numKnots the number of knots. * @param lambda the lambda. * @param alpha the alpha. * @return a regressor. */ public GAM buildRegressor(Instances trainSet, int maxNumIters, int numKnots, double lambda, double alpha) { return buildRegressor(trainSet, isSparse(trainSet), maxNumIters, numKnots, lambda, alpha); } /** * Returns a regressor. * * @param attrs the attribute list. * @param x the inputs. * @param y the targets. * @param knots the knots. * @param maxNumIters the maximum number of iterations. * @param lambda the lambda. * @param alpha the alpha. * @return a regressor. */ public GAM buildRegressor(int[] attrs, double[][][] x, double[] y, double[][] knots, int maxNumIters, double lambda, double alpha) { // Backup targets double[] rTrain = new double[y.length]; for (int i = 0; i < rTrain.length; i++) { rTrain[i] = y[i]; } double[][] w = new double[attrs.length][]; int m = 0; for (int j = 0; j < attrs.length; j++) { w[j] = new double[x[j].length]; if (w[j].length > m) { m = w[j].length; } } double[] tl1 = new double[attrs.length]; double[] tl2 = new double[attrs.length]; getRegularizationParameters(lambda, alpha, tl1, tl2, y.length); double[] stepSize = new double[attrs.length]; for (int j = 0; j < stepSize.length; j++) { double max = 0; double[][] block = x[j]; for (double[] t : block) { double l = StatUtils.sumSq(t); if (l > max) { max = l; } } stepSize[j] = 1.0 / max; } double[] g = new double[m]; double[] gradient = new double[m]; double[] gamma1 = new double[m]; double[] gamma2 = new double[m - 1]; boolean[] activeSet = new boolean[attrs.length]; double intercept = 0; // Block coordinate gradient descent int iter = 0; while (iter < maxNumIters) { if (fitIntercept) { intercept += OptimUtils.fitIntercept(rTrain); } boolean activeSetChanged = doOnePass(x, tl1, tl2, true, activeSet, w, stepSize, g, gradient, gamma1, gamma2, rTrain); iter++; if (!activeSetChanged || iter > maxNumIters) { break; } for (; iter < maxNumIters; iter++) { double prevLoss = OptimUtils.computeQuadraticLoss(rTrain) + getPenalty(w, tl1, tl2); if (fitIntercept) { intercept += OptimUtils.fitIntercept(rTrain); } doOnePass(x, tl1, tl2, false, activeSet, w, stepSize, g, gradient, gamma1, gamma2, rTrain); double currLoss = OptimUtils.computeQuadraticLoss(rTrain) + getPenalty(w, tl1, tl2); if (OptimUtils.isConverged(prevLoss, currLoss, epsilon)) { break; } if (verbose) { System.out.println("Iteration " + iter + ": " + currLoss); } } } if (refit) { byte[] struct = extractStructure(w); return refitRegressor(attrs, struct, x, y, knots, w, maxNumIters); } else { return getGAM(attrs, knots, w, intercept); } } /** * Returns a regressor. * * @param attrs the attribute list. * @param indices the indices. * @param values the values. * @param y the targets. * @param knots the knots. * @param maxNumIters the maximum number of iterations. * @param lambda the lambda. * @param alpha the alpha. * @return a regressor. */ public GAM buildRegressor(int[] attrs, int[][] indices, double[][][] values, double[] y, double[][] knots, int maxNumIters, double lambda, double alpha) { // Backup targets double[] rTrain = new double[y.length]; for (int i = 0; i < rTrain.length; i++) { rTrain[i] = y[i]; } double[][] w = new double[attrs.length][]; int m = 0; for (int j = 0; j < attrs.length; j++) { w[j] = new double[values[j].length]; if (w[j].length > m) { m = w[j].length; } } double[] tl1 = new double[attrs.length]; double[] tl2 = new double[attrs.length]; getRegularizationParameters(lambda, alpha, tl1, tl2, y.length); double[] stepSize = new double[attrs.length]; for (int j = 0; j < stepSize.length; j++) { double max = 0; int[] index = indices[j]; double[][] block = values[j]; for (double[] t : block) { double l = 0; for (int i = 0; i < index.length; i++) { l += y[index[j]] * t[i]; } if (l > max) { max = l; } } stepSize[j] = 1.0 / max; } double[] g = new double[m]; double[] gradient = new double[m]; double[] gamma1 = new double[m]; double[] gamma2 = new double[m - 1]; boolean[] activeSet = new boolean[attrs.length]; double intercept = 0; // Block coordinate gradient descent int iter = 0; while (iter < maxNumIters) { if (fitIntercept) { intercept += OptimUtils.fitIntercept(rTrain); } boolean activeSetChanged = doOnePass(indices, values, tl1, tl2, true, activeSet, w, stepSize, g, gradient, gamma1, gamma2, rTrain); iter++; if (!activeSetChanged || iter > maxNumIters) { break; } for (; iter < maxNumIters; iter++) { double prevLoss = OptimUtils.computeQuadraticLoss(rTrain) + getPenalty(w, tl1, tl2); if (fitIntercept) { intercept += OptimUtils.fitIntercept(rTrain); } doOnePass(indices, values, tl1, tl2, false, activeSet, w, stepSize, g, gradient, gamma1, gamma2, rTrain); double currLoss = OptimUtils.computeQuadraticLoss(rTrain) + getPenalty(w, tl1, tl2); if (OptimUtils.isConverged(prevLoss, currLoss, epsilon)) { break; } if (verbose) { System.out.println("Iteration " + iter + ": " + currLoss); } } } if (refit) { byte[] structure = extractStructure(w); GAM gam = refitRegressor(attrs, structure, indices, values, y, knots, w, maxNumIters * 10); return gam; } else { return getGAM(attrs, knots, w, intercept); } } /** * Returns <code>true</code> if we fit intercept. * * @return <code>true</code> if we fit intercept. */ public boolean fitIntercept() { return fitIntercept; } /** * Sets whether we fit intercept. * * @param fitIntercept whether we fit intercept. */ public void fitIntercept(boolean fitIntercept) { this.fitIntercept = fitIntercept; } /** * Returns the alpha. * * @return the alpha; */ public double getAlpha() { return alpha; } /** * Returns the convergence threshold epsilon. * * @return the convergence threshold epsilon. */ public double getEpsilon() { return epsilon; } /** * Returns the lambda. * * @return the lambda. */ public double getLambda() { return lambda; } /** * Returns the maximum number of iterations. * * @return the maximum number of iterations. */ public int getMaxNumIters() { return maxNumIters; } /** * Returns the number of knots. * * @return the number of knots. */ public int getNumKnots() { return numKnots; } /** * Returns the task of this learner. * * @return the task of this learner. */ public Task getTask() { return task; } /** * Returns <code>true</code> if we output something during the training. * * @return <code>true</code> if we output something during the training. */ public boolean isVerbose() { return verbose; } /** * Returns <code>true</code> if we refit the model. * * @return <code>true</code> if we refit the model. */ public boolean refit() { return refit; } /** * Sets whether we refit the model. * * @param refit <code>true</code> if we refit the model. */ public void refit(boolean refit) { this.refit = refit; } /** * Sets the alpha. * * @param alpha the alpha. */ public void setAlpha(double alpha) { this.alpha = alpha; } /** * Sets the convergence threshold epsilon. * * @param epsilon the convergence threshold epsilon. */ public void setEpsilon(double epsilon) { this.epsilon = epsilon; } /** * Sets the lambda. * * @param lambda the lambda. */ public void setLambda(double lambda) { this.lambda = lambda; } /** * Sets the maximum number of iterations. * * @param maxNumIters the maximum number of iterations. */ public void setMaxNumIters(int maxNumIters) { this.maxNumIters = maxNumIters; } /** * Sets the number of knots. * * @param numKnots the new number of knots. */ public void setNumKnots(int numKnots) { this.numKnots = numKnots; } /** * Sets the task of this learner. * * @param task the task of this learner. */ public void setTask(Task task) { this.task = task; } /** * Sets whether we output something during the training. * * @param verbose the switch if we output things during training. */ public void setVerbose(boolean verbose) { this.verbose = verbose; } protected void computeGradient(double[][] block, double[] rTrain, double[] gradient) { for (int i = 0; i < block.length; i++) { gradient[i] = VectorUtils.dotProduct(block[i], rTrain); } } protected void computeGradient(int[] index, double[][] block, double[] rTrain, double[] gradient) { for (int j = 0; j < block.length; j++) { double[] t = block[j]; gradient[j] = 0; for (int i = 0; i < t.length; i++) { gradient[j] += rTrain[index[i]] * t[i]; } } } protected boolean doOnePass(double[][][] x, double[] tl1, double[] tl2, boolean isFullPass, boolean[] activeSet, double[][] w, double[] stepSize, double[] g, double[] gradient, double[] gamma1, double[] gamma2, double[] rTrain) { boolean activeSetChanged = false; for (int k = 0; k < x.length; k++) { if (!isFullPass && !activeSet[k]) { continue; } double[][] block = x[k]; double[] beta = w[k]; double tk = stepSize[k]; double lambda1 = tl1[k]; double lambda2 = tl2[k]; // Proximal gradient method computeGradient(block, rTrain, gradient); for (int j = 0; j < beta.length; j++) { g[j] = beta[j] + tk * gradient[j]; } // Dual method if (beta.length > 1) { for (int i = 1; i < beta.length; i++) { gamma2[i - 1] = g[i]; } double norm2 = Math.sqrt(StatUtils.sumSq(gamma2, 0, beta.length - 1)); double t2 = lambda2 * tk; if (norm2 > t2) { VectorUtils.multiply(gamma2, t2 / norm2); } } gamma1[0] = g[0]; for (int i = 1; i < beta.length; i++) { gamma1[i] = g[i] - gamma2[i - 1]; } double norm1 = Math.sqrt(StatUtils.sumSq(gamma1, 0, beta.length)); double t1 = lambda1 * tk; if (norm1 > t1) { VectorUtils.multiply(gamma1, t1 / norm1); } g[0] -= gamma1[0]; for (int i = 1; i < beta.length; i++) { g[i] -= (gamma1[i] + gamma2[i - 1]); } // Update residuals for (int j = 0; j < beta.length; j++) { double[] t = block[j]; double delta = beta[j] - g[j]; for (int i = 0; i < rTrain.length; i++) { rTrain[i] += delta * t[i]; } } // Update weights for (int j = 0; j < beta.length; j++) { beta[j] = g[j]; } if (isFullPass && !activeSet[k] && !ArrayUtils.isConstant(beta, 0, beta.length, 0)) { activeSetChanged = true; activeSet[k] = true; } } return activeSetChanged; } protected boolean doOnePass(double[][][] x, double[] y, double[] tl1, double[] tl2, boolean isFullPass, boolean[] activeSet, double[][] w, double[] stepSize, double[] g, double[] gradient, double[] gamma1, double[] gamma2, double[] pTrain, double[] rTrain) { boolean activeSetChanged = false; for (int k = 0; k < x.length; k++) { if (!isFullPass && !activeSet[k]) { continue; } double[][] block = x[k]; double[] beta = w[k]; double tk = stepSize[k]; double lambda1 = tl1[k]; double lambda2 = tl2[k]; // Proximal gradient method computeGradient(block, rTrain, gradient); for (int j = 0; j < beta.length; j++) { g[j] = beta[j] + tk * gradient[j]; } // Dual method if (beta.length > 1) { for (int i = 1; i < beta.length; i++) { gamma2[i - 1] = g[i]; } double norm2 = Math.sqrt(StatUtils.sumSq(gamma2, 0, beta.length - 1)); double t2 = lambda2 * tk; if (norm2 > t2) { VectorUtils.multiply(gamma2, t2 / norm2); } } gamma1[0] = g[0]; for (int i = 1; i < beta.length; i++) { gamma1[i] = g[i] - gamma2[i - 1]; } double norm1 = Math.sqrt(StatUtils.sumSq(gamma1, 0, beta.length)); double t1 = lambda1 * tk; if (norm1 > t1) { VectorUtils.multiply(gamma1, t1 / norm1); } g[0] -= gamma1[0]; for (int i = 1; i < beta.length; i++) { g[i] -= (gamma1[i] + gamma2[i - 1]); } // Update predictions for (int j = 0; j < beta.length; j++) { double[] t = block[j]; double delta = g[j] - beta[j]; for (int i = 0; i < y.length; i++) { pTrain[i] += delta * t[i]; } } OptimUtils.computePseudoResidual(pTrain, y, rTrain); // Update weights for (int j = 0; j < beta.length; j++) { beta[j] = g[j]; } if (isFullPass && !activeSet[k] && !ArrayUtils.isConstant(beta, 0, beta.length, 0)) { activeSetChanged = true; activeSet[k] = true; } } return activeSetChanged; } protected boolean doOnePass(int[][] indices, double[][][] values, double[] tl1, double[] tl2, boolean isFullPass, boolean[] activeSet, double[][] w, double[] stepSize, double[] g, double[] gradient, double[] gamma1, double[] gamma2, double[] rTrain) { boolean activeSetChanged = false; for (int k = 0; k < values.length; k++) { if (!isFullPass && !activeSet[k]) { continue; } double[][] block = values[k]; int[] index = indices[k]; double[] beta = w[k]; double tk = stepSize[k]; double lambda1 = tl1[k]; double lambda2 = tl2[k]; // Proximal gradient method computeGradient(index, block, rTrain, gradient); for (int j = 0; j < beta.length; j++) { g[j] = beta[j] + tk * gradient[j]; } // Dual method if (beta.length > 1) { for (int i = 1; i < beta.length; i++) { gamma2[i - 1] = g[i]; } double norm2 = Math.sqrt(StatUtils.sumSq(gamma2, 0, beta.length - 1)); double t2 = lambda2 * tk; if (norm2 > t2) { VectorUtils.multiply(gamma2, t2 / norm2); } } gamma1[0] = g[0]; for (int i = 1; i < beta.length; i++) { gamma1[i] = g[i] - gamma2[i - 1]; } double norm1 = Math.sqrt(StatUtils.sumSq(gamma1, 0, beta.length)); double t1 = lambda1 * tk; if (norm1 > t1) { VectorUtils.multiply(gamma1, t1 / norm1); } g[0] -= gamma1[0]; for (int i = 1; i < beta.length; i++) { g[i] -= (gamma1[i] + gamma2[i - 1]); } // Update predictions for (int j = 0; j < beta.length; j++) { double[] t = block[j]; double delta = beta[j] - g[j]; for (int i = 0; i < t.length; i++) { rTrain[index[i]] += delta * t[i]; } } // Update weights for (int j = 0; j < beta.length; j++) { beta[j] = g[j]; } if (isFullPass && !activeSet[k] && !ArrayUtils.isConstant(beta, 0, beta.length, 0)) { activeSetChanged = true; activeSet[k] = true; } } return activeSetChanged; } protected boolean doOnePass(int[][] indices, double[][][] values, double[] y, double[] tl1, double[] tl2, boolean isFullPass, boolean[] activeSet, double[][] w, double[] stepSize, double[] g, double[] gradient, double[] gamma1, double[] gamma2, double[] pTrain, double[] rTrain) { boolean activeSetChanged = false; for (int k = 0; k < values.length; k++) { if (!isFullPass && !activeSet[k]) { continue; } int[] index = indices[k]; double[][] block = values[k]; double[] beta = w[k]; double tk = stepSize[k]; double lambda1 = tl1[k]; double lambda2 = tl2[k]; // Proximal gradient method computeGradient(index, block, rTrain, gradient); for (int j = 0; j < beta.length; j++) { g[j] = beta[j] + tk * gradient[j]; } // Dual method if (beta.length > 1) { for (int j = 1; j < beta.length; j++) { gamma2[j - 1] = g[j]; } double norm2 = Math.sqrt(StatUtils.sumSq(gamma2, 0, beta.length - 1)); double t2 = lambda2 * tk; if (norm2 > t2) { VectorUtils.multiply(gamma2, t2 / norm2); } } gamma1[0] = g[0]; for (int j = 1; j < beta.length; j++) { gamma1[j] = g[j] - gamma2[j - 1]; } double norm1 = Math.sqrt(StatUtils.sumSq(gamma1, 0, beta.length)); double t1 = lambda1 * tk; if (norm1 > t1) { VectorUtils.multiply(gamma1, t1 / norm1); } g[0] -= gamma1[0]; for (int i = 1; i < beta.length; i++) { g[i] -= (gamma1[i] + gamma2[i - 1]); } // Update predictions for (int j = 0; j < beta.length; j++) { double[] value = block[j]; double delta = g[j] - beta[j]; for (int i = 0; i < value.length; i++) { pTrain[index[i]] += delta * value[i]; } } for (int idx : index) { rTrain[idx] = OptimUtils.getPseudoResidual(pTrain[idx], y[idx]); } // Update weights for (int j = 0; j < beta.length; j++) { beta[j] = g[j]; } if (isFullPass && !activeSet[k] && !ArrayUtils.isConstant(beta, 0, beta.length, 0)) { activeSetChanged = true; activeSet[k] = true; } } return activeSetChanged; } protected byte[] extractStructure(double[][] w) { byte[] structure = new byte[w.length]; for (int i = 0; i < structure.length; i++) { double[] beta = w[i]; boolean isLinear = beta.length == 1 || ArrayUtils.isConstant(beta, 1, beta.length, 0); if (isLinear) { if (beta[0] != 0) { structure[i] = ModelStructure.LINEAR; } else { structure[i] = ModelStructure.ELIMINATED; } } else { structure[i] = ModelStructure.NONLINEAR; } } return structure; } protected GAM getGAM(int[] attrs, double[][] knots, double[][] w, double intercept) { GAM gam = new GAM(); for (int j = 0; j < attrs.length; j++) { int attIndex = attrs[j]; double[] beta = w[j]; boolean isLinear = beta.length == 1 || ArrayUtils.isConstant(beta, 1, beta.length, 0); if (isLinear) { if (beta[0] != 0) { // To rule out a feature, it has to be "linear" and 0 slope. gam.add(new int[] { attIndex }, new LinearFunction(attIndex, beta[0])); } } else { double[] coef = Arrays.copyOf(beta, beta.length); CubicSpline spline = new CubicSpline(attIndex, 0, knots[j], coef); gam.add(new int[] { attIndex }, spline); } } gam.setIntercept(intercept); return gam; } protected double getPenalty(double[] w, double lambda1, double lambda2) { double penalty = 0; double sumSq = StatUtils.sumSq(w); double norm1 = Math.sqrt(sumSq); penalty += lambda1 * norm1; double norm2 = sumSq - w[0] * w[0]; norm2 = Math.sqrt(norm2); penalty += lambda2 * norm2; return penalty; } protected double getPenalty(double[][] coef, double[] lambda1, double[] lambda2) { double penalty = 0; for (int i = 0; i < coef.length; i++) { penalty += getPenalty(coef[i], lambda1[i], lambda2[i]); } return penalty; } protected void getRegularizationParameters(double lambda, double alpha, double[] tl1, double[] tl2, int n) { for (int j = 0; j < tl1.length; j++) { tl1[j] = lambda * alpha * n; tl2[j] = lambda * (1 - alpha) * n; } } protected GAM refitClassifier(int[] attrs, byte[] struct, double[][][] x, double[] y, double[][] knots, double[][] w, int maxNumIters) { List<double[]> xList = new ArrayList<>(); for (int i = 0; i < struct.length; i++) { if (struct[i] == ModelStructure.NONLINEAR) { double[][] t = x[i]; for (int j = 0; j < t.length; j++) { xList.add(t[j]); } } else if (struct[i] == ModelStructure.LINEAR) { xList.add(x[i][0]); } } double[][] xNew = new double[xList.size()][]; for (int i = 0; i < xNew.length; i++) { xNew[i] = xList.get(i); } int[] attrsNew = new int[xNew.length]; for (int i = 0; i < attrsNew.length; i++) { attrsNew[i] = i; } RidgeLearner ridgeLearner = new RidgeLearner(); ridgeLearner.setVerbose(verbose); ridgeLearner.setEpsilon(epsilon); ridgeLearner.fitIntercept(fitIntercept); // A ridge regression with very small regularization parameter // This often improves stability a lot GLM glm = ridgeLearner.buildBinaryClassifier(attrsNew, xNew, y, maxNumIters, 1e-8); GAM gam = getGAM(attrs, knots, w, glm.intercept(0)); List<Regressor> regressors = gam.regressors; double[] coef = glm.coefficients(0); int k = 0; for (Regressor regressor : regressors) { if (regressor instanceof LinearFunction) { LinearFunction func = (LinearFunction) regressor; func.setSlope(coef[k++]); } else if (regressor instanceof CubicSpline) { CubicSpline spline = (CubicSpline) regressor; double[] beta = spline.getCoefficients(); for (int i = 0; i < beta.length; i++) { beta[i] = coef[k++]; } } } return gam; } protected GAM refitClassifier(int[] attrs, byte[] struct, int[][] indices, double[][][] values, double[] y, double[][] knots, double[][] w, int maxNumIters) { List<int[]> iList = new ArrayList<>(); List<double[]> vList = new ArrayList<>(); for (int i = 0; i < struct.length; i++) { int[] index = indices[i]; if (struct[i] == ModelStructure.NONLINEAR) { double[][] t = values[i]; for (int j = 0; j < t.length; j++) { iList.add(index); vList.add(t[j]); } } else if (struct[i] == ModelStructure.LINEAR) { iList.add(index); vList.add(values[i][0]); } } int[][] iNew = new int[iList.size()][]; for (int i = 0; i < iNew.length; i++) { iNew[i] = iList.get(i); } double[][] vNew = new double[vList.size()][]; for (int i = 0; i < vNew.length; i++) { vNew[i] = vList.get(i); } int[] attrsNew = new int[iNew.length]; for (int i = 0; i < attrsNew.length; i++) { attrsNew[i] = i; } RidgeLearner ridgeLearner = new RidgeLearner(); ridgeLearner.setVerbose(verbose); ridgeLearner.setEpsilon(epsilon); ridgeLearner.fitIntercept(fitIntercept); // A ridge regression with very small regularization parameter // This often improves stability a lot GLM glm = ridgeLearner.buildBinaryClassifier(attrsNew, iNew, vNew, y, maxNumIters, 1e-8); GAM gam = getGAM(attrs, knots, w, glm.intercept(0)); List<Regressor> regressors = gam.regressors; double[] coef = glm.coefficients(0); int k = 0; for (Regressor regressor : regressors) { if (regressor instanceof LinearFunction) { LinearFunction func = (LinearFunction) regressor; func.setSlope(coef[k++]); } else if (regressor instanceof CubicSpline) { CubicSpline spline = (CubicSpline) regressor; double[] beta = spline.getCoefficients(); for (int j = 0; j < beta.length; j++) { beta[j] = coef[k++]; } } } return gam; } protected GAM refitRegressor(int[] attrs, byte[] struct, double[][][] x, double[] y, double[][] knots, double[][] w, int maxNumIters) { List<double[]> xList = new ArrayList<>(); for (int i = 0; i < struct.length; i++) { if (struct[i] == ModelStructure.NONLINEAR) { double[][] t = x[i]; for (int j = 0; j < t.length; j++) { xList.add(t[j]); } } else if (struct[i] == ModelStructure.LINEAR) { xList.add(x[i][0]); } } if (xList.size() == 0) { if (fitIntercept) { double intercept = StatUtils.mean(y); GAM gam = new GAM(); gam.setIntercept(intercept); return gam; } else { return new GAM(); } } double[][] xNew = new double[xList.size()][]; for (int i = 0; i < xNew.length; i++) { xNew[i] = xList.get(i); } int[] attrsNew = new int[xNew.length]; for (int i = 0; i < attrsNew.length; i++) { attrsNew[i] = i; } RidgeLearner ridgeLearner = new RidgeLearner(); ridgeLearner.setVerbose(verbose); ridgeLearner.setEpsilon(epsilon); ridgeLearner.fitIntercept(fitIntercept); // A ridge regression with very small regularization parameter // This often improves stability a lot GLM glm = ridgeLearner.buildRegressor(attrsNew, xNew, y, maxNumIters, 1e-8); GAM gam = getGAM(attrs, knots, w, glm.intercept(0)); List<Regressor> regressors = gam.regressors; double[] coef = glm.coefficients(0); int k = 0; for (Regressor regressor : regressors) { if (regressor instanceof LinearFunction) { LinearFunction func = (LinearFunction) regressor; func.setSlope(coef[k++]); } else if (regressor instanceof CubicSpline) { CubicSpline spline = (CubicSpline) regressor; double[] beta = spline.getCoefficients(); for (int i = 0; i < beta.length; i++) { beta[i] = coef[k++]; } } } return gam; } protected GAM refitRegressor(int[] attrs, byte[] struct, int[][] indices, double[][][] values, double[] y, double[][] knots, double[][] w, int maxNumIters) { List<int[]> iList = new ArrayList<>(); List<double[]> vList = new ArrayList<>(); for (int i = 0; i < struct.length; i++) { int[] index = indices[i]; if (struct[i] == ModelStructure.NONLINEAR) { double[][] t = values[i]; for (int j = 0; j < t.length; j++) { iList.add(index); vList.add(t[j]); } } else if (struct[i] == ModelStructure.LINEAR) { iList.add(index); vList.add(values[i][0]); } } int[][] iNew = new int[iList.size()][]; for (int i = 0; i < iNew.length; i++) { iNew[i] = iList.get(i); } double[][] vNew = new double[vList.size()][]; for (int i = 0; i < vNew.length; i++) { vNew[i] = vList.get(i); } int[] attrsNew = new int[iNew.length]; for (int i = 0; i < attrsNew.length; i++) { attrsNew[i] = i; } RidgeLearner ridgeLearner = new RidgeLearner(); ridgeLearner.setVerbose(verbose); ridgeLearner.setEpsilon(epsilon); ridgeLearner.fitIntercept(fitIntercept); // A ridge regression with very small regularization parameter // This often improves stability a lot GLM glm = ridgeLearner.buildRegressor(attrsNew, iNew, vNew, y, maxNumIters, 1e-8); GAM gam = getGAM(attrs, knots, w, glm.intercept(0)); List<Regressor> regressors = gam.regressors; double[] coef = glm.coefficients(0); int k = 0; for (Regressor regressor : regressors) { if (regressor instanceof LinearFunction) { LinearFunction func = (LinearFunction) regressor; func.setSlope(coef[k++]); } else if (regressor instanceof CubicSpline) { CubicSpline spline = (CubicSpline) regressor; double[] beta = spline.getCoefficients(); for (int j = 0; j < beta.length; j++) { beta[j] = coef[k++]; } } } return gam; } }
bsd-3-clause
alameluchidambaram/CONNECT
Product/Production/Gateway/PatientDiscovery_10/src/test/java/gov/hhs/fha/nhinc/patientdiscovery/_10/gateway/ws/NhincProxyPatientDiscoverySecuredTest.java
3826
/* * Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the United States Government nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT 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 gov.hhs.fha.nhinc.patientdiscovery._10.gateway.ws; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import gov.hhs.fha.nhinc.patientdiscovery._10.passthru.NhincProxyPatientDiscoveryImpl; import javax.xml.ws.WebServiceContext; import org.hl7.v3.PRPAIN201306UV02; import org.hl7.v3.ProxyPRPAIN201305UVProxySecuredRequestType; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JUnit4Mockery; import org.jmock.lib.legacy.ClassImposteriser; import org.junit.Test; public class NhincProxyPatientDiscoverySecuredTest { // NhincProxyPatientDiscoverySecured Mockery context = new JUnit4Mockery() { { setImposteriser(ClassImposteriser.INSTANCE); } }; @Test public void testDefaultConstructor() { NhincProxyPatientDiscoverySecured patientDiscovery = new NhincProxyPatientDiscoverySecured(); assertNotNull(patientDiscovery); } @Test public void testMockService() { final ProxyPRPAIN201305UVProxySecuredRequestType mockBody = context .mock(ProxyPRPAIN201305UVProxySecuredRequestType.class); final PRPAIN201306UV02 expectedResponse = context.mock(PRPAIN201306UV02.class); final NhincProxyPatientDiscoveryImpl mockService = context.mock(NhincProxyPatientDiscoveryImpl.class); final PatientDiscoveryServiceFactory mockFactory = context.mock(PatientDiscoveryServiceFactory.class); NhincProxyPatientDiscoverySecured patientDiscovery = new NhincProxyPatientDiscoverySecured(mockFactory); context.checking(new Expectations() { { oneOf(mockService).proxyPRPAIN201305UV(with(same(mockBody)), with(any(WebServiceContext.class))); will(returnValue(expectedResponse)); oneOf(mockFactory).getNhincProxyPatientDiscoveryImpl(); will(returnValue(mockService)); } }); PRPAIN201306UV02 actualResponse = patientDiscovery.proxyPRPAIN201305UV(mockBody); assertSame(expectedResponse, actualResponse); } }
bsd-3-clause
kakada/dhis2
dhis-api/src/main/java/org/hisp/dhis/option/OptionService.java
3335
package org.hisp.dhis.option; /* * Copyright (c) 2004-2015, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.util.Collection; import java.util.List; /** * @author Lars Helge Overland */ public interface OptionService { final String ID = OptionService.class.getName(); // ------------------------------------------------------------------------- // OptionSet // ------------------------------------------------------------------------- int saveOptionSet( OptionSet optionSet ); void updateOptionSet( OptionSet optionSet ); OptionSet getOptionSet( int id ); OptionSet getOptionSet( String uid ); OptionSet getOptionSetByName( String name ); OptionSet getOptionSetByCode( String code ); void deleteOptionSet( OptionSet optionSet ); Collection<OptionSet> getAllOptionSets(); List<Option> getOptions( String optionSetUid, String key, Integer max ); List<Option> getOptions( int optionSetId, String name, Integer max ); Integer getOptionSetsCountByName( String name ); Collection<OptionSet> getOptionSetsBetweenByName( String name, int first, int max ); Collection<OptionSet> getOptionSetsBetween( int first, int max ); Integer getOptionSetCount(); // ------------------------------------------------------------------------- // Option // ------------------------------------------------------------------------- void updateOption( Option option ); Option getOption( int id ); Option getOptionByCode( String code ); void deleteOption( Option option ); Option getOptionByName( OptionSet optionSet, String name ); Option getOptionByCode( OptionSet optionSet, String code ); Collection<Option> getOptions( OptionSet optionSet, String option, Integer min, Integer max ); }
bsd-3-clause
groupon/monsoon
lib/src/main/java/com/groupon/lex/metrics/lib/BufferedIterator.java
8423
package com.groupon.lex.metrics.lib; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import static java.util.Objects.requireNonNull; import java.util.Optional; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BooleanSupplier; import java.util.logging.Level; import java.util.logging.Logger; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; public final class BufferedIterator<T> { private static final Logger LOG = Logger.getLogger(BufferedIterator.class.getName()); private static final AtomicInteger THR_IDX = new AtomicInteger(); private static final Executor DFL_WORK_QUEUE = Executors.newCachedThreadPool(new ThreadFactory() { @Override public Thread newThread(Runnable r) { final Thread thr = new Thread(r); thr.setDaemon(true); thr.setName("BufferedIterator-thread-" + THR_IDX.getAndIncrement()); return thr; } }); private static final int DFL_BUFFER_LEN = 16; private final Executor work_queue_; private final Iterator<? extends T> iter_; private final List<T> queue_; private Exception exception = null; private boolean at_end_; private final int queue_size_; private boolean running_ = false; private Runnable wakeup_ = null; public BufferedIterator(Executor work_queue, Iterator<? extends T> iter, int queue_size) { if (queue_size <= 0) throw new IllegalArgumentException("queue size must be at least 1"); work_queue_ = requireNonNull(work_queue); iter_ = requireNonNull(iter); queue_size_ = queue_size; queue_ = new LinkedList<>(); at_end_ = false; fire_(); } public BufferedIterator(Iterator<? extends T> iter, int queue_size) { this(DFL_WORK_QUEUE, iter, queue_size); } public BufferedIterator(Executor work_queue, Iterator<? extends T> iter) { this(work_queue, iter, DFL_BUFFER_LEN); } public BufferedIterator(Iterator<? extends T> iter) { this(DFL_WORK_QUEUE, iter); } public synchronized boolean atEnd() { return at_end_ && queue_.isEmpty() && exception == null; } public synchronized boolean nextAvail() { return !queue_.isEmpty() || exception != null; } public void waitAvail() throws InterruptedException { synchronized (this) { if (nextAvail() || atEnd()) return; } final WakeupListener w = new WakeupListener(() -> nextAvail() || atEnd()); setWakeup(w::wakeup); ForkJoinPool.managedBlock(w); } public void waitAvail(long tv, TimeUnit tu) throws InterruptedException { synchronized (this) { if (nextAvail() || atEnd()) return; } final Delay w = new Delay(() -> { }, tv, tu); setWakeup(w::deliverWakeup); try { ForkJoinPool.managedBlock(w); } catch (InterruptedException ex) { throw ex; } } @SneakyThrows public synchronized T next() { if (exception != null) throw exception; try { final T result = queue_.remove(0); fire_(); return result; } catch (IndexOutOfBoundsException ex) { LOG.log(Level.SEVERE, "next() called on empty queue!", ex); throw ex; } } public void setWakeup(Runnable wakeup) { requireNonNull(wakeup); boolean run_immediately_ = false; synchronized (this) { if (!queue_.isEmpty() || at_end_) { run_immediately_ = true; wakeup_ = null; } else { wakeup_ = wakeup; } } if (run_immediately_) work_queue_.execute(wakeup); } public void setWakeup(Runnable wakeup, long tv, TimeUnit tu) { final Delay delay = new Delay(wakeup, tv, tu); setWakeup(delay::deliverWakeup); work_queue_.execute(delay); } private synchronized void fire_() { if (at_end_) return; if (queue_.size() >= queue_size_) return; if (exception != null) return; if (!running_) { running_ = true; work_queue_.execute(this::add_next_iter_); } } private void add_next_iter_() { final long deadline = System.currentTimeMillis() + 50; // Don't hog the queue, requeue once deadline expires. try { boolean stop_loop = false; while (!stop_loop && queue_.size() < queue_size_) { if (iter_.hasNext()) { final T next = iter_.next(); final Optional<Runnable> wakeup; synchronized (this) { queue_.add(next); wakeup = Optional.ofNullable(wakeup_); wakeup_ = null; } wakeup.ifPresent(this.work_queue_::execute); } else { final Optional<Runnable> wakeup; synchronized (this) { at_end_ = true; stop_loop = true; wakeup = Optional.ofNullable(wakeup_); wakeup_ = null; } wakeup.ifPresent(this.work_queue_::execute); } if (System.currentTimeMillis() >= deadline) stop_loop = true; } synchronized (this) { running_ = false; fire_(); } } catch (Exception e) { final Optional<Runnable> wakeup; synchronized (this) { running_ = false; exception = e; wakeup = Optional.ofNullable(wakeup_); wakeup_ = null; } wakeup.ifPresent(Runnable::run); } } @RequiredArgsConstructor private static class WakeupListener implements ForkJoinPool.ManagedBlocker { private final BooleanSupplier predicate; public synchronized void wakeup() { this.notify(); } @Override public synchronized boolean block() throws InterruptedException { while (!predicate.getAsBoolean()) this.wait(); return true; } @Override public boolean isReleasable() { return predicate.getAsBoolean(); } } private static class Delay implements ForkJoinPool.ManagedBlocker, Runnable { private Runnable wakeup; private final long deadline; private boolean wakeupReceived = false; public Delay(@NonNull Runnable wakeup, long tv, TimeUnit tu) { this.deadline = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(tv, tu); this.wakeup = wakeup; } private synchronized void fireWakeup() { if (wakeup == null) return; try { wakeup.run(); } finally { wakeup = null; } } public synchronized void deliverWakeup() { wakeupReceived = true; this.notify(); fireWakeup(); } @Override public void run() { try { ForkJoinPool.managedBlock(this); } catch (InterruptedException ex) { LOG.log(Level.WARNING, "interrupted wait", ex); } } @Override public synchronized boolean block() throws InterruptedException { final long now = System.currentTimeMillis(); if (wakeupReceived || deadline <= now) return true; this.wait(deadline - now); fireWakeup(); return true; } @Override public boolean isReleasable() { synchronized (this) { if (wakeupReceived) { fireWakeup(); return true; } } return deadline <= System.currentTimeMillis(); } } }
bsd-3-clause
milnet2/event-sourcing-demo
src/main/java/de/tobiasblaschke/eventsource/sample/persistence/sql/jpa/entities/AbstractJpaUserEvent.java
898
package de.tobiasblaschke.eventsource.sample.persistence.sql.jpa.entities; import de.tobiasblaschke.eventsource.sample.events.AbstractUserEvent; import de.tobiasblaschke.eventsource.sample.events.EventFactory; import javax.annotation.Nonnull; import javax.persistence.DiscriminatorColumn; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import java.time.Instant; @Entity(name = "user") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "event_type") public abstract class AbstractJpaUserEvent extends AbstractJpaEvent<Integer> { public AbstractJpaUserEvent() { super(null, null); } public AbstractJpaUserEvent(@Nonnull Integer id, @Nonnull Instant eventTimestamp) { super(id, eventTimestamp); } public abstract AbstractUserEvent unbox(EventFactory factory); }
bsd-3-clause
endlessm/chromium-browser
chrome/android/java/src/org/chromium/chrome/browser/status_indicator/StatusIndicatorMediator.java
18547
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.status_indicator; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ArgbEvaluator; import android.animation.ValueAnimator; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.view.View; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import org.chromium.base.Callback; import org.chromium.base.supplier.Supplier; import org.chromium.chrome.browser.fullscreen.BrowserControlsStateProvider; import org.chromium.components.browser_ui.widget.animation.CancelAwareAnimatorListener; import org.chromium.components.browser_ui.widget.animation.Interpolators; import org.chromium.ui.modelutil.PropertyModel; import java.util.HashSet; class StatusIndicatorMediator implements BrowserControlsStateProvider.Observer, View.OnLayoutChangeListener { private static final int STATUS_BAR_COLOR_TRANSITION_DURATION_MS = 200; private static final int FADE_TEXT_DURATION_MS = 150; private static final int UPDATE_COLOR_TRANSITION_DURATION_MS = 400; private PropertyModel mModel; private BrowserControlsStateProvider mBrowserControlsStateProvider; private HashSet<StatusIndicatorCoordinator.StatusIndicatorObserver> mObservers = new HashSet<>(); private Supplier<Integer> mStatusBarWithoutIndicatorColorSupplier; private Runnable mOnCompositorShowAnimationEnd; private Supplier<Boolean> mCanAnimateNativeBrowserControls; private Callback<Runnable> mInvalidateCompositorView; private Runnable mRequestLayout; private ValueAnimator mStatusBarAnimation; private ValueAnimator mTextFadeInAnimation; private AnimatorSet mUpdateAnimatorSet; private AnimatorSet mHideAnimatorSet; private int mIndicatorHeight; private int mJavaLayoutHeight; private boolean mIsHiding; /** * Constructs the status indicator mediator. * @param model The {@link PropertyModel} for the status indicator. * @param browserControlsStateProvider The {@link BrowserControlsStateProvider} to listen to * for the changes in controls offsets. * @param statusBarWithoutIndicatorColorSupplier A supplier that will get the status bar color * without taking the status indicator into * account. * @param canAnimateNativeBrowserControls Will supply a boolean denoting whether the native * browser controls can be animated. This will be false * where we can't have a reliable cc::BCOM instance, e.g. * tab switcher. * @param invalidateCompositorView Callback to invalidate the compositor texture. * @param requestLayout Runnable to request layout for the view. */ StatusIndicatorMediator(PropertyModel model, BrowserControlsStateProvider browserControlsStateProvider, Supplier<Integer> statusBarWithoutIndicatorColorSupplier, Supplier<Boolean> canAnimateNativeBrowserControls, Callback<Runnable> invalidateCompositorView, Runnable requestLayout) { mModel = model; mBrowserControlsStateProvider = browserControlsStateProvider; mStatusBarWithoutIndicatorColorSupplier = statusBarWithoutIndicatorColorSupplier; mCanAnimateNativeBrowserControls = canAnimateNativeBrowserControls; mInvalidateCompositorView = invalidateCompositorView; mRequestLayout = requestLayout; } @Override public void onControlsOffsetChanged(int topOffset, int topControlsMinHeightOffset, int bottomOffset, int bottomControlsMinHeightOffset, boolean needsAnimate) { // If we aren't animating the browser controls in cc, we shouldn't care about the offsets // we get. if (!mCanAnimateNativeBrowserControls.get()) return; onOffsetChanged(topControlsMinHeightOffset); } @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { // Wait for first valid height while showing indicator. if (mIsHiding || mJavaLayoutHeight != 0 || v.getHeight() <= 0) return; mInvalidateCompositorView.onResult(null); mJavaLayoutHeight = v.getHeight(); updateVisibility(false); } void destroy() { if (mStatusBarAnimation != null) mStatusBarAnimation.cancel(); if (mTextFadeInAnimation != null) mTextFadeInAnimation.cancel(); if (mUpdateAnimatorSet != null) mUpdateAnimatorSet.cancel(); if (mHideAnimatorSet != null) mHideAnimatorSet.cancel(); } void addObserver(StatusIndicatorCoordinator.StatusIndicatorObserver observer) { mObservers.add(observer); } void removeObserver(StatusIndicatorCoordinator.StatusIndicatorObserver observer) { mObservers.remove(observer); } // Animations // TODO(sinansahin): We might want to end the running animations if we need to hide before we're // done showing/updating and vice versa. /** * Transitions the status bar color to the expected status indicator color background. Also, * initializes other properties, e.g. status text, status icon, and colors. * * These animations are transitioning the status bar color to the provided background color * (skipped if the background is the same as the current status bar color), then sliding in the * status indicator, and then fading in the status text with the icon. * * The animation timeline looks like this: * * Status bar transitions |*--------* * Indicator slides in | *--------* * Text fades in | *------* * * @param statusText Status text to show. * @param statusIcon Compound drawable to show next to text. * @param backgroundColor Background color for the indicator. * @param textColor Status text color. * @param iconTint Compound drawable tint. */ void animateShow(@NonNull String statusText, Drawable statusIcon, @ColorInt int backgroundColor, @ColorInt int textColor, @ColorInt int iconTint) { Runnable initializeProperties = () -> { mModel.set(StatusIndicatorProperties.STATUS_TEXT, statusText); mModel.set(StatusIndicatorProperties.STATUS_ICON, statusIcon); mModel.set(StatusIndicatorProperties.TEXT_ALPHA, 0.f); mModel.set(StatusIndicatorProperties.BACKGROUND_COLOR, backgroundColor); mModel.set(StatusIndicatorProperties.TEXT_COLOR, textColor); mModel.set(StatusIndicatorProperties.ICON_TINT, iconTint); mModel.set(StatusIndicatorProperties.ANDROID_VIEW_VISIBILITY, View.INVISIBLE); mOnCompositorShowAnimationEnd = () -> animateTextFadeIn(); }; final int statusBarColor = mStatusBarWithoutIndicatorColorSupplier.get(); // If we aren't changing the status bar color, skip the status bar color animation and // continue with the rest of the animations. if (statusBarColor == backgroundColor) { initializeProperties.run(); return; } mStatusBarAnimation = ValueAnimator.ofInt(statusBarColor, backgroundColor); mStatusBarAnimation.setEvaluator(new ArgbEvaluator()); mStatusBarAnimation.setInterpolator(Interpolators.FAST_OUT_SLOW_IN_INTERPOLATOR); mStatusBarAnimation.setDuration(STATUS_BAR_COLOR_TRANSITION_DURATION_MS); mStatusBarAnimation.addUpdateListener(anim -> { for (StatusIndicatorCoordinator.StatusIndicatorObserver observer : mObservers) { observer.onStatusIndicatorColorChanged((int) anim.getAnimatedValue()); } }); mStatusBarAnimation.addListener(new CancelAwareAnimatorListener() { @Override public void onEnd(Animator animation) { initializeProperties.run(); } }); mStatusBarAnimation.start(); } private void animateTextFadeIn() { if (mTextFadeInAnimation == null) { mTextFadeInAnimation = ValueAnimator.ofFloat(0.f, 1.f); mTextFadeInAnimation.setInterpolator(Interpolators.FAST_OUT_SLOW_IN_INTERPOLATOR); mTextFadeInAnimation.setDuration(FADE_TEXT_DURATION_MS); mTextFadeInAnimation.addUpdateListener((anim -> { final float currentAlpha = (float) anim.getAnimatedValue(); mModel.set(StatusIndicatorProperties.TEXT_ALPHA, currentAlpha); })); mTextFadeInAnimation.addListener(new CancelAwareAnimatorListener() { @Override public void onStart(Animator animation) { mRequestLayout.run(); } }); } mTextFadeInAnimation.start(); } // TODO(sinansahin): See if/how we can skip some of the animations if the properties didn't // change. This might require UX guidance. /** * Updates the contents and background of the status indicator with animations. * * These animations are transitioning the status bar and the background color to the provided * background color while fading out the status text with the icon, and then fading in the new * status text with the icon (with the provided color and tint). * * The animation timeline looks like this: * * Old text fades out |*------* * Background/status bar transition |*------------------* * New text fades in | *------* * * @param statusText New status text to show. * @param statusIcon New compound drawable to show next to text. * @param backgroundColor New background color for the indicator. * @param textColor New status text color. * @param iconTint New compound drawable tint. * @param animationCompleteCallback Callback to run after the animation is done. */ void animateUpdate(@NonNull String statusText, Drawable statusIcon, @ColorInt int backgroundColor, @ColorInt int textColor, @ColorInt int iconTint, Runnable animationCompleteCallback) { final boolean changed = !statusText.equals(mModel.get(StatusIndicatorProperties.STATUS_TEXT)) || statusIcon != mModel.get(StatusIndicatorProperties.STATUS_ICON) || backgroundColor != mModel.get(StatusIndicatorProperties.BACKGROUND_COLOR) || textColor != mModel.get(StatusIndicatorProperties.TEXT_COLOR) || iconTint != mModel.get(StatusIndicatorProperties.ICON_TINT); assert changed : "#animateUpdate() shouldn't be called without any change to the status indicator."; // 1. Fade out old text. ValueAnimator fadeOldOut = ValueAnimator.ofFloat(1.f, 0.f); fadeOldOut.setInterpolator(Interpolators.FAST_OUT_SLOW_IN_INTERPOLATOR); fadeOldOut.setDuration(FADE_TEXT_DURATION_MS); fadeOldOut.addUpdateListener(anim -> { final float currentAlpha = (float) anim.getAnimatedValue(); mModel.set(StatusIndicatorProperties.TEXT_ALPHA, currentAlpha); }); fadeOldOut.addListener(new CancelAwareAnimatorListener() { @Override public void onEnd(Animator animation) { mModel.set(StatusIndicatorProperties.STATUS_TEXT, statusText); mModel.set(StatusIndicatorProperties.STATUS_ICON, statusIcon); mModel.set(StatusIndicatorProperties.TEXT_COLOR, textColor); mModel.set(StatusIndicatorProperties.ICON_TINT, iconTint); } }); // 2. Simultaneously transition the background. ValueAnimator colorAnimation = ValueAnimator.ofInt( mModel.get(StatusIndicatorProperties.BACKGROUND_COLOR), backgroundColor); colorAnimation.setEvaluator(new ArgbEvaluator()); colorAnimation.setInterpolator(Interpolators.FAST_OUT_SLOW_IN_INTERPOLATOR); colorAnimation.setDuration(UPDATE_COLOR_TRANSITION_DURATION_MS); colorAnimation.addUpdateListener(anim -> { final int currentColor = (int) anim.getAnimatedValue(); mModel.set(StatusIndicatorProperties.BACKGROUND_COLOR, currentColor); notifyColorChange(currentColor); }); // 3. Fade in new text, after #1 and #2 are done. ValueAnimator fadeNewIn = ValueAnimator.ofFloat(0.f, 1.f); fadeNewIn.setInterpolator(Interpolators.FAST_OUT_SLOW_IN_INTERPOLATOR); fadeNewIn.setDuration(FADE_TEXT_DURATION_MS); fadeNewIn.addUpdateListener(anim -> { final float currentAlpha = (float) anim.getAnimatedValue(); mModel.set(StatusIndicatorProperties.TEXT_ALPHA, currentAlpha); }); mUpdateAnimatorSet = new AnimatorSet(); mUpdateAnimatorSet.play(fadeOldOut).with(colorAnimation); mUpdateAnimatorSet.play(fadeNewIn).after(colorAnimation); mUpdateAnimatorSet.addListener(new CancelAwareAnimatorListener() { @Override public void onEnd(Animator animation) { animationCompleteCallback.run(); } }); mUpdateAnimatorSet.start(); } /** * Hide the status indicator with animations. * * These animations are transitioning the status bar and background color to the system color * while fading the text out, and then sliding the indicator out. * * The animation timeline looks like this: * * Status bar and background transition |*--------* * Text fades out |*------* * Indicator slides out | *--------* */ void animateHide() { // 1. Transition the background. ValueAnimator colorAnimation = ValueAnimator.ofInt(mModel.get(StatusIndicatorProperties.BACKGROUND_COLOR), mStatusBarWithoutIndicatorColorSupplier.get()); colorAnimation.setEvaluator(new ArgbEvaluator()); colorAnimation.setInterpolator(Interpolators.FAST_OUT_SLOW_IN_INTERPOLATOR); colorAnimation.setDuration(STATUS_BAR_COLOR_TRANSITION_DURATION_MS); colorAnimation.addUpdateListener(anim -> { final int currentColor = (int) anim.getAnimatedValue(); mModel.set(StatusIndicatorProperties.BACKGROUND_COLOR, currentColor); notifyColorChange(currentColor); }); colorAnimation.addListener(new CancelAwareAnimatorListener() { @Override public void onEnd(Animator animation) { notifyColorChange(Color.TRANSPARENT); } }); // 2. Fade out the text simultaneously with #1. ValueAnimator fadeOut = ValueAnimator.ofFloat(1.f, 0.f); fadeOut.setInterpolator(Interpolators.FAST_OUT_SLOW_IN_INTERPOLATOR); fadeOut.setDuration(FADE_TEXT_DURATION_MS); fadeOut.addUpdateListener(anim -> mModel.set( StatusIndicatorProperties.TEXT_ALPHA, (float) anim.getAnimatedValue())); mHideAnimatorSet = new AnimatorSet(); mHideAnimatorSet.play(colorAnimation).with(fadeOut); mHideAnimatorSet.addListener(new CancelAwareAnimatorListener() { @Override public void onEnd(Animator animation) { if (mCanAnimateNativeBrowserControls.get()) { mInvalidateCompositorView.onResult(() -> updateVisibility(true)); } else { updateVisibility(true); } } }); mHideAnimatorSet.start(); } // Observer notifiers private void notifyHeightChange(int height) { for (StatusIndicatorCoordinator.StatusIndicatorObserver observer : mObservers) { observer.onStatusIndicatorHeightChanged(height); } } private void notifyColorChange(@ColorInt int color) { for (StatusIndicatorCoordinator.StatusIndicatorObserver observer : mObservers) { observer.onStatusIndicatorColorChanged(color); } } // Other internal methods /** * Call to kick off height change when status indicator is shown/hidden. * @param hiding Whether the status indicator is hiding. */ private void updateVisibility(boolean hiding) { mIsHiding = hiding; mIndicatorHeight = hiding ? 0 : mJavaLayoutHeight; if (!mIsHiding) { mBrowserControlsStateProvider.addObserver(this); } // If the browser controls won't be animating, we can pretend that the animation ended. if (!mCanAnimateNativeBrowserControls.get()) { onOffsetChanged(mIndicatorHeight); } notifyHeightChange(mIndicatorHeight); } private void onOffsetChanged(int topControlsMinHeightOffset) { final boolean compositedVisible = topControlsMinHeightOffset > 0; // Composited view should be visible if we have a positive top min-height offset, or current // min-height. mModel.set(StatusIndicatorProperties.COMPOSITED_VIEW_VISIBLE, compositedVisible); final boolean isCompletelyShown = topControlsMinHeightOffset == mIndicatorHeight; // Android view should only be visible when the indicator is fully shown. mModel.set(StatusIndicatorProperties.ANDROID_VIEW_VISIBILITY, mIsHiding ? View.GONE : (isCompletelyShown ? View.VISIBLE : View.INVISIBLE)); if (mOnCompositorShowAnimationEnd != null && isCompletelyShown) { mOnCompositorShowAnimationEnd.run(); mOnCompositorShowAnimationEnd = null; } final boolean doneHiding = !compositedVisible && mIsHiding; if (doneHiding) { mBrowserControlsStateProvider.removeObserver(this); mIsHiding = false; mJavaLayoutHeight = 0; } } @VisibleForTesting void updateVisibilityForTesting(boolean hiding) { updateVisibility(hiding); } }
bsd-3-clause
paksv/vijava
src/com/vmware/vim25/ClusterDasAdmissionControlPolicy.java
1835
/*================================================================================ Copyright (c) 2013 Steve Jin. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of VMware, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================*/ package com.vmware.vim25; /** * @author Steve Jin (http://www.doublecloud.org) * @version 5.1 */ @SuppressWarnings("all") public class ClusterDasAdmissionControlPolicy extends DynamicData { }
bsd-3-clause
Workday/OpenFrame
sync/android/javatests/src/org/chromium/sync/notifier/signin/AccountManagerHelperTest.java
2556
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.sync.notifier.signin; import android.accounts.Account; import android.content.Context; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.SmallTest; import org.chromium.sync.signin.AccountManagerHelper; import org.chromium.sync.test.util.AccountHolder; import org.chromium.sync.test.util.MockAccountManager; import org.chromium.sync.test.util.SimpleFuture; /** * Test class for {@link AccountManagerHelper}. */ public class AccountManagerHelperTest extends InstrumentationTestCase { private MockAccountManager mAccountManager; private AccountManagerHelper mHelper; @Override protected void setUp() throws Exception { super.setUp(); Context context = getInstrumentation().getTargetContext(); mAccountManager = new MockAccountManager(context, context); AccountManagerHelper.overrideAccountManagerHelperForTests(context, mAccountManager); mHelper = AccountManagerHelper.get(context); } @SmallTest public void testCanonicalAccount() throws InterruptedException { addTestAccount("test@gmail.com", "password"); assertTrue(hasAccountForName("test@gmail.com")); assertTrue(hasAccountForName("Test@gmail.com")); assertTrue(hasAccountForName("te.st@gmail.com")); } @SmallTest public void testNonCanonicalAccount() throws InterruptedException { addTestAccount("test.me@gmail.com", "password"); assertTrue(hasAccountForName("test.me@gmail.com")); assertTrue(hasAccountForName("testme@gmail.com")); assertTrue(hasAccountForName("Testme@gmail.com")); assertTrue(hasAccountForName("te.st.me@gmail.com")); } private Account addTestAccount(String accountName, String password) { Account account = AccountManagerHelper.createAccountFromName(accountName); AccountHolder.Builder accountHolder = AccountHolder.create().account(account).password(password).alwaysAccept(true); mAccountManager.addAccountHolderExplicitly(accountHolder.build()); return account; } private boolean hasAccountForName(String accountName) throws InterruptedException { SimpleFuture<Boolean> result = new SimpleFuture<Boolean>(); mHelper.hasAccountForName(accountName, result.createCallback()); return result.get(); } }
bsd-3-clause
harshadura/platform-communications
modules/cmslite/api/src/main/java/org/motechproject/cmslite/api/model/Content.java
1851
package org.motechproject.cmslite.api.model; import org.codehaus.jackson.annotate.JsonProperty; import org.motechproject.commons.couchdb.model.MotechBaseDataObject; import java.util.Map; import java.util.Objects; /** * Abstract representation of CMS Lite content. Identified by name and language. */ public abstract class Content extends MotechBaseDataObject { private static final long serialVersionUID = 753195533829136573L; @JsonProperty private String language; @JsonProperty private String name; @JsonProperty private Map<String, String> metadata; protected Content() { this(null, null, null); } protected Content(String language, String name) { this(language, name, null); } protected Content(String language, String name, Map<String, String> metadata) { this.name = name; this.language = language; this.metadata = metadata; } public Map<String, String> getMetadata() { return metadata; } public String getLanguage() { return language; } public String getName() { return name; } @Override public int hashCode() { return Objects.hash(language, name, metadata); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final Content other = (Content) obj; return Objects.equals(this.language, other.language) && Objects.equals(this.name, other.name) && Objects.equals(this.metadata, other.metadata); } @Override public String toString() { return String.format("Content{language='%s', name='%s', metadata=%s}", language, name, metadata); } }
bsd-3-clause
was4444/chromium.src
chrome/android/java/src/org/chromium/chrome/browser/precache/PrecacheTaskScheduler.java
707
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.precache; import android.content.Context; import com.google.android.gms.gcm.GcmNetworkManager; import com.google.android.gms.gcm.Task; import org.chromium.chrome.browser.ChromeBackgroundService; class PrecacheTaskScheduler { void scheduleTask(Context context, Task task) { GcmNetworkManager.getInstance(context).schedule(task); } void cancelTask(Context context, String tag) { GcmNetworkManager.getInstance(context).cancelTask(tag, ChromeBackgroundService.class); } }
bsd-3-clause
mikem2005/vijava
src/com/vmware/vim25/PlatformConfigFault.java
1918
/*================================================================================ Copyright (c) 2009 VMware, Inc. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of VMware, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================*/ package com.vmware.vim25; /** @author Steve Jin (sjin@vmware.com) */ public class PlatformConfigFault extends HostConfigFault { public String text; public String getText() { return this.text; } public void setText(String text) { this.text=text; } }
bsd-3-clause
abryant/Plinth
src/eu/bryants/anthony/plinth/ast/type/ArrayType.java
6494
package eu.bryants.anthony.plinth.ast.type; import java.util.HashSet; import java.util.Set; import eu.bryants.anthony.plinth.ast.LexicalPhrase; import eu.bryants.anthony.plinth.ast.member.ArrayLengthMember; import eu.bryants.anthony.plinth.ast.member.BuiltinMethod; import eu.bryants.anthony.plinth.ast.member.BuiltinMethod.BuiltinMethodType; import eu.bryants.anthony.plinth.ast.metadata.GenericTypeSpecialiser; import eu.bryants.anthony.plinth.ast.metadata.MemberReference; import eu.bryants.anthony.plinth.ast.metadata.MethodReference; /* * Created on 3 May 2012 */ /** * @author Anthony Bryant */ public class ArrayType extends Type { // a type is explicitly immutable if it has been declared as immutable explicitly, // whereas a type is contextually immutable if it is just accessed in an immutable context // if a type is explicitly immutable, then it is always also contextually immutable private boolean explicitlyImmutable; private boolean contextuallyImmutable; private Type baseType; public ArrayType(boolean nullable, boolean explicitlyImmutable, boolean contextuallyImmutable, Type baseType, LexicalPhrase lexicalPhrase) { super(nullable, lexicalPhrase); this.explicitlyImmutable = explicitlyImmutable; this.contextuallyImmutable = explicitlyImmutable | contextuallyImmutable; this.baseType = baseType; } public ArrayType(boolean nullable, boolean isImmutable, Type baseType, LexicalPhrase lexicalPhrase) { this(nullable, isImmutable, false, baseType, lexicalPhrase); } /** * {@inheritDoc} */ @Override public boolean canAssign(Type type) { // only allow assignment if base type assignment would work both ways, // so we cannot do either of the following (for some Bar extends Foo) // 1: // []Bar bs = new [1]Bar; // []Foo fs = bs; // fs[0] = new Foo(); // bs now contains a Foo, despite it being a []Bar // 2: // []Foo fs = new [1]Foo; // fs[0] = new Foo(); // []Bar bs = fs; // bs now contains a Foo, despite it being a []Bar if (type instanceof NullType && isNullable()) { // all nullable types can have null assigned to them return true; } // a nullable type cannot be assigned to a non-nullable type if (!isNullable() && type.canBeNullable()) { return false; } // an explicitly-immutable type cannot be assigned to a non-explicitly-immutable array type if (!isExplicitlyImmutable() && Type.isExplicitlyDataImmutable(type)) { return false; } // a contextually-immutable type cannot be assigned to a non-immutable array type if (!isContextuallyImmutable() && Type.isContextuallyDataImmutable(type)) { return false; } if (type instanceof ArrayType) { Type otherBaseType = ((ArrayType) type).getBaseType(); return baseType.canAssign(otherBaseType) && otherBaseType.canAssign(baseType); } if (type instanceof WildcardType) { // we have already checked the nullability and immutability constraints, so make sure that the wildcard type is a sub-type of this array type return ((WildcardType) type).canBeAssignedTo(this); } return false; } /** * {@inheritDoc} */ @Override public boolean canRuntimeAssign(Type type) { return type instanceof ArrayType && baseType.isRuntimeEquivalent(((ArrayType) type).getBaseType()); } /** * {@inheritDoc} */ @Override public boolean isEquivalent(Type type) { return type instanceof ArrayType && isNullable() == type.isNullable() && isExplicitlyImmutable() == ((ArrayType) type).isExplicitlyImmutable() && isContextuallyImmutable() == ((ArrayType) type).isContextuallyImmutable() && baseType.isEquivalent(((ArrayType) type).getBaseType()); } /** * {@inheritDoc} */ @Override public boolean isRuntimeEquivalent(Type type) { return type instanceof ArrayType && isNullable() == type.isNullable() && isExplicitlyImmutable() == ((ArrayType) type).isExplicitlyImmutable() && isContextuallyImmutable() == ((ArrayType) type).isContextuallyImmutable() && baseType.isRuntimeEquivalent(((ArrayType) type).getBaseType()); } /** * @return true iff this ArrayType is explicitly immutable */ public boolean isExplicitlyImmutable() { return explicitlyImmutable; } /** * @return true iff this ArrayType is contextually immutable or explicitly immutable */ public boolean isContextuallyImmutable() { return contextuallyImmutable; } /** * @return the baseType */ public Type getBaseType() { return baseType; } /** * {@inheritDoc} */ @Override public Set<MemberReference<?>> getMembers(String name) { HashSet<MemberReference<?>> set = new HashSet<MemberReference<?>>(); if (name.equals(ArrayLengthMember.LENGTH_FIELD_NAME)) { set.add(ArrayLengthMember.LENGTH_MEMBER_REFERENCE); } if (name.equals(BuiltinMethodType.TO_STRING.methodName)) { ArrayType notNullThis = new ArrayType(false, explicitlyImmutable, contextuallyImmutable, baseType, null); set.add(new MethodReference(new BuiltinMethod(notNullThis, BuiltinMethodType.TO_STRING), GenericTypeSpecialiser.IDENTITY_SPECIALISER)); } if (name.equals(BuiltinMethodType.EQUALS.methodName)) { ArrayType notNullThis = new ArrayType(false, explicitlyImmutable, contextuallyImmutable, baseType, null); set.add(new MethodReference(new BuiltinMethod(notNullThis, BuiltinMethodType.EQUALS), GenericTypeSpecialiser.IDENTITY_SPECIALISER)); } if (name.equals(BuiltinMethodType.HASH_CODE.methodName)) { ArrayType notNullThis = new ArrayType(false, explicitlyImmutable, contextuallyImmutable, baseType, null); set.add(new MethodReference(new BuiltinMethod(notNullThis, BuiltinMethodType.HASH_CODE), GenericTypeSpecialiser.IDENTITY_SPECIALISER)); } return set; } /** * {@inheritDoc} */ @Override public String getMangledName() { return (isNullable() ? "x" : "") + (isContextuallyImmutable() ? "c" : "") + "A" + baseType.getMangledName(); } /** * {@inheritDoc} */ @Override public boolean hasDefaultValue() { return isNullable(); } /** * {@inheritDoc} */ @Override public String toString() { return (isNullable() ? "?" : "") + (isContextuallyImmutable() ? "#" : "") + "[]" + baseType; } }
bsd-3-clause
UrielCh/ovh-java-sdk
ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/price/dedicatedcloud/_2016v5/bhs1a/infrastructure/filer/OvhHourlyEnum.java
1119
package net.minidev.ovh.api.price.dedicatedcloud._2016v5.bhs1a.infrastructure.filer; import com.fasterxml.jackson.annotation.JsonProperty; /** * Enum of Hourlys */ public enum OvhHourlyEnum { @JsonProperty("iscsi-1200-GB") iscsi_1200_GB("iscsi-1200-GB"), @JsonProperty("iscsi-13200g-GB") iscsi_13200g_GB("iscsi-13200g-GB"), @JsonProperty("iscsi-3300-GB") iscsi_3300_GB("iscsi-3300-GB"), @JsonProperty("iscsi-6600-GB") iscsi_6600_GB("iscsi-6600-GB"), @JsonProperty("iscsi-800-GB") iscsi_800_GB("iscsi-800-GB"), @JsonProperty("nfs-100-GB") nfs_100_GB("nfs-100-GB"), @JsonProperty("nfs-1200-GB") nfs_1200_GB("nfs-1200-GB"), @JsonProperty("nfs-13200-GB") nfs_13200_GB("nfs-13200-GB"), @JsonProperty("nfs-1600-GB") nfs_1600_GB("nfs-1600-GB"), @JsonProperty("nfs-2400-GB") nfs_2400_GB("nfs-2400-GB"), @JsonProperty("nfs-3300-GB") nfs_3300_GB("nfs-3300-GB"), @JsonProperty("nfs-6600-GB") nfs_6600_GB("nfs-6600-GB"), @JsonProperty("nfs-800-GB") nfs_800_GB("nfs-800-GB"); final String value; OvhHourlyEnum(String s) { this.value = s; } public String toString() { return this.value; } }
bsd-3-clause
dmargo/blueprints-seas
blueprints-neo4jbatch-graph/src/main/java/com/tinkerpop/blueprints/pgm/impls/neo4jbatch/Neo4jBatchVertex.java
1976
package com.tinkerpop.blueprints.pgm.impls.neo4jbatch; import com.tinkerpop.blueprints.pgm.Edge; import com.tinkerpop.blueprints.pgm.Vertex; import com.tinkerpop.blueprints.pgm.impls.StringFactory; import java.util.Map; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class Neo4jBatchVertex extends Neo4jBatchElement implements Vertex { public Neo4jBatchVertex(final Neo4jBatchGraph graph, final Long id) { super(graph, id); } public Object removeProperty(final String key) { final Map<String, Object> properties = this.getPropertyMapClone(); final Object value = properties.remove(key); this.graph.getRawGraph().setNodeProperties(this.id, properties); for (final Neo4jBatchAutomaticIndex index : this.graph.getAutomaticVertexIndices()) { index.autoUpdate(this, properties); } return value; } public void setProperty(final String key, final Object value) { final Map<String, Object> properties = this.getPropertyMapClone(); properties.put(key, value); this.graph.getRawGraph().setNodeProperties(this.id, properties); for (final Neo4jBatchAutomaticIndex index : this.graph.getAutomaticVertexIndices()) { index.autoUpdate(this, properties); } } /** * @throws UnsupportedOperationException */ public Iterable<Edge> getOutEdges(final String... labels) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException */ public Iterable<Edge> getInEdges(final String... labels) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } protected Map<String, Object> getPropertyMap() { return this.graph.getRawGraph().getNodeProperties(this.id); } public String toString() { return StringFactory.vertexString(this); } }
bsd-3-clause
sirixdb/sirix
bundles/sirix-gui/src/main/java/org/sirix/gui/WrapLayout.java
8526
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.sirix.gui; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Insets; import java.awt.Window; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; /** * FlowLayout subclass that fully supports wrapping of components. * * @author Johannes Lichtenberger, University of Konstanz */ public class WrapLayout extends FlowLayout { /** * Default Serial UID. */ private static final long serialVersionUID = 1L; /** Preferred layout size. */ private transient Dimension mPreferredLayoutSize; /** * Constructs a new <code>WrapLayout</code> with a left alignment and a * default 5-unit horizontal and vertical gap. */ public WrapLayout() { super(); } /** * Constructs a new <code>FlowLayout</code> with the specified alignment and a * default 5-unit horizontal and vertical gap. The value of the alignment * argument must be one of <code>WrapLayout</code>, <code>WrapLayout</code>, * or <code>WrapLayout</code>. * * @param paramAlign * the alignment value */ public WrapLayout(final int paramAlign) { super(paramAlign); } /** * Creates a new flow layout manager with the indicated alignment and the * indicated horizontal and vertical gaps. * <p> * The value of the alignment argument must be one of <code>WrapLayout</code>, * <code>WrapLayout</code>, or <code>WrapLayout</code>. * * @param paramAlign * the alignment value * @param paramHgap * the horizontal gap between components * @param paramVgap * the vertical gap between components */ public WrapLayout(final int paramAlign, final int paramHgap, final int paramVgap) { super(paramAlign, paramHgap, paramVgap); } /** * Returns the preferred dimensions for this layout given the <i>visible</i> * components in the specified target container. * * @param paramTarget * the component which needs to be laid out * @return the preferred dimensions to lay out the subcomponents of the * specified container */ @Override public final Dimension preferredLayoutSize(final Container paramTarget) { return layoutSize(paramTarget, true); } /** * Returns the minimum dimensions needed to layout the <i>visible</i> * components contained in the specified target container. * * @param paramTarget * the component which needs to be laid out * @return the minimum dimensions to lay out the subcomponents of the * specified container */ @Override public final Dimension minimumLayoutSize(final Container paramTarget) { final Dimension minimum = layoutSize(paramTarget, false); minimum.width -= getHgap() + 1; return minimum; } /** * Returns the minimum or preferred dimension needed to layout the target * container. * * @param paramTarget * target to get layout size for * @param paramPreferred * should preferred size be calculated * @return the dimension to layout the target container */ private Dimension layoutSize(final Container paramTarget, final boolean paramPreferred) { synchronized (paramTarget.getTreeLock()) { // Each row must fit with the width allocated to the containter. // When the container width = 0, the preferred width of the container // has not yet been calculated so lets ask for the maximum. int targetWidth = paramTarget.getSize().width; if (targetWidth == 0) { targetWidth = Integer.MAX_VALUE; } final int hgap = getHgap(); final int vgap = getVgap(); final Insets insets = paramTarget.getInsets(); final int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); final int maxWidth = targetWidth - horizontalInsetsAndGap; // Fit components into the allowed width final Dimension dim = new Dimension(0, 0); int rowWidth = 0; int rowHeight = 0; final int nmembers = paramTarget.getComponentCount(); for (int i = 0; i < nmembers; i++) { final Component m = paramTarget.getComponent(i); if (m.isVisible()) { final Dimension d = paramPreferred ? m.getPreferredSize() : m .getMinimumSize(); // Can't add the component to current row. Start a new row. if (rowWidth + d.width > maxWidth) { addRow(dim, rowWidth, rowHeight); rowWidth = 0; rowHeight = 0; } // Add a horizontal gap for all components after the first if (rowWidth != 0) { rowWidth += hgap; } rowWidth += d.width; rowHeight = Math.max(rowHeight, d.height); } } addRow(dim, rowWidth, rowHeight); dim.width += horizontalInsetsAndGap; dim.height += insets.top + insets.bottom + vgap * 2; // When using a scroll pane or the DecoratedLookAndFeel we need to // make sure the preferred size is less than the size of the // target containter so shrinking the container size works // correctly. Removing the horizontal gap is an easy way to do this. final Container scrollPane = SwingUtilities.getAncestorOfClass( JScrollPane.class, paramTarget); if (scrollPane != null) { dim.width -= hgap + 1; } return dim; } } /** * Layout the components in the Container using the layout logic of the parent * FlowLayout class. * * @param paramTarget * the Container using this WrapLayout */ @Override public final void layoutContainer(final Container paramTarget) { final Dimension size = preferredLayoutSize(paramTarget); // When a frame is minimized or maximized the preferred size of the // Container is assumed not to change. Therefore we need to force a // validate() to make sure that space, if available, is allocated to // the panel using a WrapLayout. if (size.equals(mPreferredLayoutSize)) { super.layoutContainer(paramTarget); } else { mPreferredLayoutSize = size; Container top = paramTarget; while (!(top instanceof Window) && top.getParent() != null) { top = top.getParent(); } top.validate(); } } /** * A new row has been completed. Use the dimensions of this row to update the * preferred size for the container. * * @param paramDim * update the width and height when appropriate * * @param paramRowWidth * the width of the row to add * * @param paramRowHeight * the height of the row to add */ private void addRow(final Dimension paramDim, final int paramRowWidth, final int paramRowHeight) { paramDim.width = Math.max(paramDim.width, paramRowWidth); if (paramDim.height > 0) { paramDim.height += getVgap(); } paramDim.height += paramRowHeight; } }
bsd-3-clause
ra4king/LWJGL-OpenGL-Tutorials
src/com/ra4king/opengl/util/scene/binders/StateBinder.java
826
package com.ra4king.opengl.util.scene.binders; import static org.lwjgl.opengl.GL20.*; import java.util.HashMap; import com.ra4king.opengl.util.ShaderProgram; public interface StateBinder { void bindState(ShaderProgram program); void unbindState(ShaderProgram program); } abstract class UniformBinderBase implements StateBinder { private HashMap<ShaderProgram,Integer> programUniformLocation = new HashMap<>(); public void associateWithProgram(ShaderProgram program, String uniform) { programUniformLocation.put(program, glGetUniformLocation(program.getProgram(), uniform)); } protected int getUniformLocation(ShaderProgram program) { Integer i = programUniformLocation.get(program); if(i == -1) throw new IllegalArgumentException("Unassociated program"); return i; } }
bsd-3-clause
lottie-c/spl_tests_new
src/java/cz/cuni/mff/spl/evaluator/output/impl/html2/FormulaResultDescriptor.java
5179
/* * Copyright (c) 2012, František Haas, Martin Lacina, Jaroslav Kotrč, Jiří Daniel * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL 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 cz.cuni.mff.spl.evaluator.output.impl.html2; import java.util.ArrayList; import cz.cuni.mff.spl.annotation.FormulaDeclaration; import cz.cuni.mff.spl.annotation.Info; import cz.cuni.mff.spl.configuration.ConfigurationBundle; import cz.cuni.mff.spl.evaluator.output.BasicOutputFileMapping; import cz.cuni.mff.spl.evaluator.output.flatformula.FlatEvaluationResult; import cz.cuni.mff.spl.evaluator.output.impl.html2.AnnotationResultDescriptor.AnnotationValidationFlags; import cz.cuni.mff.spl.evaluator.output.results.FormulaEvaluationResult; import cz.cuni.mff.spl.evaluator.statistics.StatisticValueChecker; /** * The formula evaluation result descriptor for XSLT transformation. * * @author Martin Lacina */ public class FormulaResultDescriptor extends OutputResultDescriptor { /** The flat formula evaluation result. */ private final FlatEvaluationResult flatFormulaEvaluationResult; /** * Gets the flat formula evaluation result. * * @return The flat formula evaluation result. */ public FlatEvaluationResult getFlatFormulaEvaluationResult() { return flatFormulaEvaluationResult; } /** The formula declaration. */ private final FormulaDeclaration formulaDeclaration; /** * Gets the formula declaration. * * @return the formula declaration */ public FormulaDeclaration getFormulaDeclaration() { return formulaDeclaration; } /** The comparison validation flags. */ private final FormulaValidationFlags formulaValidationFlags = new FormulaValidationFlags(); /** * Gets the comparison validation flags. * * @return the comparison validation flags */ public FormulaValidationFlags getFormulaValidationFlags() { return formulaValidationFlags; } /** * Instantiates a new measurement result descriptor. * * @param info * The info. * @param configuration * The configuration. * @param formulaEvaluationResult * The formula evaluation result. * @param checker * The checker. * @param graphsMapping * The graphs mapping. * @param outputLinks * The output links. * @param globalAliasesSummary * The global aliases summary. */ public FormulaResultDescriptor(Info info, ConfigurationBundle configuration, FormulaEvaluationResult formulaEvaluationResult, StatisticValueChecker checker, BasicOutputFileMapping graphsMapping, ArrayList<Link> outputLinks, AnnotationValidationFlags globalAliasesSummary) { super(info, configuration, outputLinks, globalAliasesSummary); this.flatFormulaEvaluationResult = formulaEvaluationResult.getFlatFormula(); this.formulaDeclaration = formulaEvaluationResult.getFormulaDeclaration(); this.formulaValidationFlags.setFlags(formulaEvaluationResult, checker); } /** * The formula validation flags. * * @author Martin Lacina */ public static class FormulaValidationFlags { /** * Instantiates a new formula validation flags. */ public FormulaValidationFlags() { } /** * Sets the flags. * * @param result * The formula evaluation result. * @param checker * The checker. */ public void setFlags(FormulaEvaluationResult result, StatisticValueChecker checker) { } } }
bsd-3-clause
mrmakeit/ingress-intel-total-conversion
mobile/src/com/cradle/iitc_mobile/IITC_JSInterface.java
1058
package com.cradle.iitc_mobile; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.webkit.JavascriptInterface; import android.widget.Toast; // provide communication between IITC script and android app public class IITC_JSInterface { // context of main activity Context context; IITC_JSInterface(Context c) { context = c; } // send intent for gmaps link @JavascriptInterface public void intentPosLink(String s) { Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(s)); context.startActivity(intent); } // copy link to specific portal to android clipboard @JavascriptInterface public void copy(String s) { ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Copied Text ", s); clipboard.setPrimaryClip(clip); Toast.makeText(context, "copied to clipboard", Toast.LENGTH_SHORT).show(); } }
isc
avjinder/Minimal-Todo
app/src/main/java/com/example/avjindersinghsekhon/minimaltodo/Utility/CustomTextInputLayout.java
1621
package com.example.avjindersinghsekhon.minimaltodo.Utility; import android.content.Context; import android.graphics.Canvas; import android.support.design.widget.TextInputLayout; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; public class CustomTextInputLayout extends TextInputLayout { private boolean mIsHintSet; private CharSequence mHint; public CustomTextInputLayout(Context context) { super(context); } public CustomTextInputLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if (child instanceof EditText) { // Since hint will be nullify on EditText once on parent addView, store hint value locally mHint = ((EditText) child).getHint(); } super.addView(child, index, params); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (!mIsHintSet && ViewCompat.isLaidOut(this)) { // We have to reset the previous hint so that equals check pass setHint(null); // In case that hint is changed programatically CharSequence currentEditTextHint = getEditText().getHint(); if (currentEditTextHint != null && currentEditTextHint.length() > 0) { mHint = currentEditTextHint; } setHint(mHint); mIsHintSet = true; } } }
mit
rnorth/duct-tape
src/main/java/org/rnorth/ducttape/circuitbreakers/State.java
348
package org.rnorth.ducttape.circuitbreakers; /** * @author richardnorth */ public enum State { /** * The breaker is OK, i.e. trying to perform requested primary actions. */ OK, /** * The breaker is broken, i.e. avoiding calling primary actions, and falling straight through to the fallback actions. */ BROKEN }
mit
thequixotic/ai2-kawa
gnu/text/Options.java
8362
// Copyright (c) 2003, 2010 Per M.A. Bothner. // This is free software; for terms and warranty disclaimer see ./COPYING. package gnu.text; import java.util.*; /** Mananges a table of named options, * Can inherit from another table of "default" options. */ public class Options { /** Bit indicating option value is a boolean. */ public static final int BOOLEAN_OPTION = 1; public static final int STRING_OPTION = 2; /** The option table contain defaults, that we "inherit" from. */ Options previous; OptionInfo first; OptionInfo last; public Options () { } public Options (Options previous) { this.previous = previous; } /** Maps property keys to options values. */ HashMap<String,Object> valueTable; /** Maps property keys to OptionInfo. */ HashMap<String,OptionInfo> infoTable; /** Create a new option and enters it in this table. * A duplicate option throws a RuntimeException. * @param key the options name (key). * @param kind type and other flag bits of the option. * @param documentation a String describing what the option does. */ public OptionInfo add(String key, int kind, String documentation) { return add(key, kind, null, documentation); } public OptionInfo add(String key, int kind, Object defaultValue, String documentation) { if (infoTable == null) infoTable = new HashMap<String,OptionInfo>(); else if (infoTable.get(key) != null) throw new RuntimeException("duplicate option key: "+key); OptionInfo info = new OptionInfo(); info.key = key; info.kind = kind; info.defaultValue = defaultValue; info.documentation = documentation; if (first == null) first = info; else last.next = info; last = info; infoTable.put(key, info); return info; } static Object valueOf (OptionInfo info, String argument) { if ((info.kind & BOOLEAN_OPTION) != 0) { if (argument == null || argument.equals("1") || argument.equals("on") || argument.equals("yes") || argument.equals("true")) return Boolean.TRUE; if (argument.equals("0") || argument.equals("off") || argument.equals("no") || argument.equals("false")) return Boolean.FALSE; return null; } return argument; } private void error(String message, SourceMessages messages) { if (messages == null) throw new RuntimeException(message); else messages.error('e', message); } /** Set the value of a named option. */ public void set (String key, Object value) { set(key, value, null); } /** Set the value of a named option. */ public void set (String key, Object value, SourceMessages messages) { OptionInfo info = getInfo(key); if (info == null) { error("invalid option key: "+key, messages); return; } if ((info.kind & BOOLEAN_OPTION) != 0) { if (value instanceof String) value = valueOf(info, (String) value); if (! (value instanceof Boolean)) { error("value for option "+key +" must be boolean or yes/no/true/false/on/off/1/0", messages); return; } } else if (value == null) value = ""; if (valueTable == null) valueTable = new HashMap<String,Object>(); valueTable.put(key, value); } /** Reset the value of a named option. */ public void reset (String key, Object oldValue) { if (valueTable == null) valueTable = new HashMap<String,Object>(); if (oldValue == null) valueTable.remove(key); else valueTable.put(key, oldValue); } public static final String UNKNOWN = "unknown option name"; /** Set the value of the key to the argument, appropriate parsed. * return null on success or a String error message. * If the option key is invalid, return UNKNOWN. */ public String set (String key, String argument) { OptionInfo info = getInfo(key); if (info == null) return UNKNOWN; Object value = valueOf(info, argument); if (value == null) { if ((info.kind & BOOLEAN_OPTION) != 0) return "value of option "+key+" must be yes/no/true/false/on/off/1/0"; } if (valueTable == null) valueTable = new HashMap<String,Object>(); valueTable.put(key, value); return null; } public OptionInfo getInfo (String key) { Object info = infoTable == null ? null : infoTable.get(key); if (info == null && previous != null) info = previous.getInfo(key); return (OptionInfo) info; } /** Get the value for the option. * Throws an except if there is no option by that name, * Returns defaultValue if there is such an option, but it * hasn't been set. */ public Object get (String key, Object defaultValue) { OptionInfo info = getInfo(key); if (info == null) throw new RuntimeException("invalid option key: "+key); return get(info, defaultValue); } public Object get (OptionInfo key, Object defaultValue) { Options options = this; while (options != null) { for (OptionInfo info = key; ; ) { Object val = options.valueTable == null ? null : options.valueTable.get(info.key); if (val != null) return val; if (info.defaultValue instanceof OptionInfo) info = (OptionInfo) info.defaultValue; else { if (info.defaultValue != null) defaultValue = info.defaultValue; break; } } options = options.previous; } return defaultValue; } public Object get (OptionInfo key) { return get(key, null); } /** Get current option value. * Only look in local table, not in inherited Options. * Return null if there is no binding (even when get would * throw an except on an unknonw option). */ public Object getLocal (String key) { return valueTable == null ? null : valueTable.get(key); } public boolean getBoolean (String key) { return ((Boolean) get (key, Boolean.FALSE)).booleanValue(); } public boolean getBoolean (String key, boolean defaultValue) { Boolean defaultObject = defaultValue ? Boolean.TRUE : Boolean.FALSE; return ((Boolean) get (key, defaultObject)).booleanValue(); } public boolean getBoolean (OptionInfo key, boolean defaultValue) { Boolean defaultObject = defaultValue ? Boolean.TRUE : Boolean.FALSE; return ((Boolean) get (key, defaultObject)).booleanValue(); } public boolean getBoolean (OptionInfo key) { Object value = get (key, null); return value == null ? false : ((Boolean) value).booleanValue(); } /** Set a list of options, remember the old value. * @param options is vector of triples, echo of which is consisting of: * a String option key; * an entry whose valus is ignores and is used to store the old value; and * a new value for the options. */ public void pushOptionValues (Vector options) { int len = options.size(); for (int i = 0; i < len; ) { String key = (String) options.elementAt(i++); Object newValue = options.elementAt(i); options.setElementAt(newValue, i++); set(key, options.elementAt(i++)); } } /** Restore a list of options, as set by pushOptionValues */ public void popOptionValues (Vector options) { for (int i = options.size(); (i -= 3) >= 0; ) { String key = (String) options.elementAt(i); Object oldValue = options.elementAt(i+1); options.setElementAt(null, i+1); reset(key, oldValue); } } /** Return the list of option keys. */ public ArrayList<String> keys () { ArrayList<String> allKeys = new ArrayList<String>(); for (Options options = this; options != null; options = options.previous) { if (options.infoTable != null) { for (String k : options.infoTable.keySet()) { if (! allKeys.contains(k)) allKeys.add(k); } } } return allKeys; } public String getDoc(String key) { OptionInfo info = getInfo(key); if (key == null) return null; return info.documentation; } public static final class OptionInfo { OptionInfo next; String key; int kind; String documentation; Object defaultValue; } }
mit
baryshnikova-lab/safe-java
core/src/main/java/edu/princeton/safe/internal/scoring/RandomizedNeighborhoodScoringMethod.java
2005
package edu.princeton.safe.internal.scoring; import org.apache.commons.math3.random.RandomDataGenerator; import org.apache.commons.math3.random.RandomGenerator; import edu.princeton.safe.AnnotationProvider; import edu.princeton.safe.NeighborhoodScoringMethod; import edu.princeton.safe.model.Neighborhood; /** * Computes the neighborhood score from a random permutation of a fixed number * of neighborhoods. Neighborhoods contributing to the score may be of different * sizes. */ public class RandomizedNeighborhoodScoringMethod implements NeighborhoodScoringMethod { AnnotationProvider annotationProvider; int[] permutations; Neighborhood[] neighborhoods; public RandomizedNeighborhoodScoringMethod(AnnotationProvider annotationProvider, RandomGenerator generator, int totalPermutations, Neighborhood[] neighborhoods) { this.annotationProvider = annotationProvider; this.neighborhoods = neighborhoods; RandomDataGenerator random = new RandomDataGenerator(generator); permutations = random.nextPermutation(neighborhoods.length, totalPermutations); } @Override public double[] computeRandomizedScores(Neighborhood current, int attributeIndex) { int totalPermutations = permutations.length; double[] scores = new double[totalPermutations]; for (int r = 0; r < totalPermutations; r++) { final int permutationIndex = r; Neighborhood randomNeighborhood = neighborhoods[permutations[r]]; randomNeighborhood.forEachMemberIndex(index -> { double value = annotationProvider.getValue(index, attributeIndex); if (!Double.isNaN(value)) { scores[permutationIndex] += value; } }); } return scores; } }
mit
vangulo-trulia/dozer-rets-client
target/filtered-sources/java/org/realtors/rets/client/BrokerCodeRequredException.java
735
/* * cart: CRT's Awesome RETS Tool * * Author: David Terrell * Copyright (c) 2003, The National Association of REALTORS * Distributed under a BSD-style license. See LICENSE.TXT for details. */ package org.realtors.rets.client; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * dbt is lame and hasn't overridden the default * javadoc string. */ public class BrokerCodeRequredException extends RetsException { private final List mCodeList; public BrokerCodeRequredException(Collection codes) { this.mCodeList = Collections.unmodifiableList(new ArrayList(codes)); } public List getCodeList(){ return this.mCodeList; } }
mit
chvrga/outdoor-explorer
java/play-1.4.4/framework/src/play/libs/mail/ProductionMailSystem.java
343
package play.libs.mail; import java.util.concurrent.Future; import org.apache.commons.mail.Email; import play.libs.Mail; class ProductionMailSystem implements MailSystem { @Override public Future<Boolean> sendMessage(Email email) { email.setMailSession(Mail.getSession()); return Mail.sendMessage(email); } }
mit
m0pt0pmatt/SpongeSurvivalGames
src/main/java/io/github/m0pt0pmatt/survivalgames/command/executor/print/AbstractPrintCommand.java
2975
/* * This file is part of SurvivalGames, licensed under the MIT License (MIT). * * Copyright (c) Matthew Broomfield <m0pt0pmatt17@gmail.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.github.m0pt0pmatt.survivalgames.command.executor.print; import io.github.m0pt0pmatt.survivalgames.command.CommandKeys; import io.github.m0pt0pmatt.survivalgames.command.executor.LeafCommand; import io.github.m0pt0pmatt.survivalgames.game.SurvivalGame; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.args.CommandElement; import org.spongepowered.api.text.Text; import javax.annotation.Nonnull; import java.util.Optional; import java.util.function.Function; import static com.google.common.base.Preconditions.checkNotNull; import static io.github.m0pt0pmatt.survivalgames.Util.getOrThrow; import static io.github.m0pt0pmatt.survivalgames.Util.sendSuccess; class AbstractPrintCommand extends LeafCommand { private final Function<SurvivalGame, Optional<Text>> function; AbstractPrintCommand( String name, CommandElement arguments, Function<SurvivalGame, Optional<Text>> function) { super(PrintCommand.getInstance(), name, arguments); this.function = checkNotNull(function, "function"); } @Nonnull @Override public CommandResult executeCommand(@Nonnull CommandSource src, @Nonnull CommandContext args) throws CommandException { SurvivalGame survivalGame = (SurvivalGame) getOrThrow(args, CommandKeys.SURVIVAL_GAME); Text value = getOrThrow(function.apply(survivalGame), getAliases().get(0)); sendSuccess(src, getAliases().get(0), value); return CommandResult.success(); } }
mit