repo_name
stringlengths
7
104
file_path
stringlengths
11
238
context
list
import_statement
stringlengths
103
6.85k
code
stringlengths
60
38.4k
next_line
stringlengths
10
824
gold_snippet_index
int32
0
8
Rubentxu/DreamsLibGdx
core/src/main/java/com/rubentxu/juegos/core/pantallas/BaseScreen.java
[ "public class DreamsGame extends BaseGame {\n\n public static boolean DEBUG = false;\n public static FPSLogger log;\n\n @Override\n public void create() {\n Gdx.input.setCatchBackKey(true);\n resourcesManager =new ResourcesManager();\n preferencesManager = PreferencesManager.instanc...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.actions.MoveToAction; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Stack; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.Window; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.rubentxu.juegos.core.DreamsGame; import com.rubentxu.juegos.core.constantes.Constants; import com.rubentxu.juegos.core.constantes.GameState; import com.rubentxu.juegos.core.pantallas.transiciones.ScreenTransition; import com.rubentxu.juegos.core.pantallas.transiciones.ScreenTransitionSlide; import static com.badlogic.gdx.scenes.scene2d.actions.Actions.fadeIn;
package com.rubentxu.juegos.core.pantallas; public abstract class BaseScreen implements Screen { protected final DreamsGame game; protected Stage stage; protected Table mainTable; protected Window dialog; protected Label message; protected Stack container; protected float width; protected float height; public static SCREEN CURRENT_SCREEN = SCREEN.SPLASH; //private ScreenTransition transition = ScreenTransitionFade.init(0.75f);
private ScreenTransition transition = ScreenTransitionSlide.init(0.7f,
3
davidmoten/rxjava2-jdbc
rxjava2-jdbc/src/main/java/org/davidmoten/rx/jdbc/GetterTx.java
[ "public class Tuple2<T1, T2> {\n\n private final T1 value1;\n private final T2 value2;\n\n /**\n * Constructor.\n * \n * @param value1\n * first element\n * @param value2\n * second element\n */\n public Tuple2(T1 value1, T2 value2) {\n this.value...
import java.sql.ResultSet; import java.util.Optional; import javax.annotation.Nonnull; import org.davidmoten.rx.jdbc.tuple.Tuple2; import org.davidmoten.rx.jdbc.tuple.Tuple3; import org.davidmoten.rx.jdbc.tuple.Tuple4; import org.davidmoten.rx.jdbc.tuple.Tuple5; import org.davidmoten.rx.jdbc.tuple.Tuple6; import org.davidmoten.rx.jdbc.tuple.Tuple7; import org.davidmoten.rx.jdbc.tuple.TupleN; import org.davidmoten.rx.jdbc.tuple.Tuples; import com.github.davidmoten.guavamini.Preconditions; import io.reactivex.Flowable; import io.reactivex.Single;
package org.davidmoten.rx.jdbc; public interface GetterTx { /** * Transforms the results using the given function. * * @param mapper * transforms ResultSet row to an object of type T * @param <T> * the type being mapped to * @return the results of the query as an Observable */ <T> Flowable<Tx<T>> get(@Nonnull ResultSetMapper<? extends T> mapper); default <T> Flowable<Tx<T>> getAs(@Nonnull Class<T> cls) { Preconditions.checkNotNull(cls, "cls cannot be null"); return get(rs -> Util.mapObject(rs, cls, 1)); } default <T> Flowable<Tx<Optional<T>>> getAsOptional(@Nonnull Class<T> cls) { Preconditions.checkNotNull(cls, "cls cannot be null"); return get(rs -> Optional.ofNullable(Util.mapObject(rs, cls, 1))); } /** * <p> * Transforms each row of the {@link ResultSet} into an instance of * <code>T</code> using <i>automapping</i> of the ResultSet columns into * corresponding constructor parameters that are assignable. Beyond normal * assignable criteria (for example Integer 123 is assignable to a Double) other * conversions exist to facilitate the automapping: * </p> * <p> * They are: * <ul> * <li>java.sql.Blob --&gt; byte[]</li> * <li>java.sql.Blob --&gt; java.io.InputStream</li> * <li>java.sql.Clob --&gt; String</li> * <li>java.sql.Clob --&gt; java.io.Reader</li> * <li>java.sql.Date --&gt; java.util.Date</li> * <li>java.sql.Date --&gt; Long</li> * <li>java.sql.Timestamp --&gt; java.util.Date</li> * <li>java.sql.Timestamp --&gt; Long</li> * <li>java.sql.Time --&gt; java.util.Date</li> * <li>java.sql.Time --&gt; Long</li> * <li>java.math.BigInteger --&gt; * Short,Integer,Long,Float,Double,BigDecimal</li> * <li>java.math.BigDecimal --&gt; * Short,Integer,Long,Float,Double,BigInteger</li> * </ul> * * @param cls * class to automap each row of the ResultSet to * @param <T> * generic type of returned stream emissions * @return Flowable of T * */ default <T> Flowable<Tx<T>> autoMap(@Nonnull Class<T> cls) { Preconditions.checkNotNull(cls, "cls cannot be null"); return get(Util.autoMap(cls)); } /** * Automaps all the columns of the {@link ResultSet} into the target class * <code>cls</code>. See {@link #autoMap(Class) autoMap()}. * * @param cls * class of the TupleN elements * @param <T> * generic type of returned stream emissions * @return stream of transaction items */ default <T> Flowable<Tx<TupleN<T>>> getTupleN(@Nonnull Class<T> cls) { Preconditions.checkNotNull(cls, "cls cannot be null"); return get(Tuples.tupleN(cls)); } /** * Automaps all the columns of the {@link ResultSet} into {@link Object} . See * {@link #autoMap(Class) autoMap()}. * * @return stream of transaction items */ default Flowable<Tx<TupleN<Object>>> getTupleN() { return get(Tuples.tupleN(Object.class)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param <T1> * type of first class * @param <T2> * type of second class * @return stream of transaction items */ default <T1, T2> Flowable<Tx<Tuple2<T1, T2>>> getAs(@Nonnull Class<T1> cls1, @Nonnull Class<T2> cls2) { return get(Tuples.tuple(cls1, cls2)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param cls3 * third class * @param <T1> * type of first class * @param <T2> * type of second class * @param <T3> * type of third class * @return stream of tuples */ default <T1, T2, T3> Flowable<Tx<Tuple3<T1, T2, T3>>> getAs(@Nonnull Class<T1> cls1, @Nonnull Class<T2> cls2, @Nonnull Class<T3> cls3) { return get(Tuples.tuple(cls1, cls2, cls3)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param cls3 * third class * @param cls4 * fourth class * @param <T1> * type of first class * @param <T2> * type of second class * @param <T3> * type of third class * @param <T4> * type of fourth class * @return stream of tuples */ default <T1, T2, T3, T4> Flowable<Tx<Tuple4<T1, T2, T3, T4>>> getAs(@Nonnull Class<T1> cls1, @Nonnull Class<T2> cls2, @Nonnull Class<T3> cls3, @Nonnull Class<T4> cls4) { return get(Tuples.tuple(cls1, cls2, cls3, cls4)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param cls3 * third class * @param cls4 * fourth class * @param cls5 * fifth class * @param <T1> * type of first class * @param <T2> * type of second class * @param <T3> * type of third class * @param <T4> * type of fourth class * @param <T5> * type of fifth class * @return stream of transaction items */ default <T1, T2, T3, T4, T5> Flowable<Tx<Tuple5<T1, T2, T3, T4, T5>>> getAs( @Nonnull Class<T1> cls1, @Nonnull Class<T2> cls2, @Nonnull Class<T3> cls3, @Nonnull Class<T4> cls4, @Nonnull Class<T5> cls5) { return get(Tuples.tuple(cls1, cls2, cls3, cls4, cls5)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param cls3 * third class * @param cls4 * fourth class * @param cls5 * fifth class * @param cls6 * sixth class * @param <T1> * type of first class * @param <T2> * type of second class * @param <T3> * type of third class * @param <T4> * type of fourth class * @param <T5> * type of fifth class * @param <T6> * type of sixth class * @return stream of transaction items */ default <T1, T2, T3, T4, T5, T6> Flowable<Tx<Tuple6<T1, T2, T3, T4, T5, T6>>> getAs( @Nonnull Class<T1> cls1, @Nonnull Class<T2> cls2, @Nonnull Class<T3> cls3, @Nonnull Class<T4> cls4, @Nonnull Class<T5> cls5, @Nonnull Class<T6> cls6) { return get(Tuples.tuple(cls1, cls2, cls3, cls4, cls5, cls6)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param cls3 * third class * @param cls4 * fourth class * @param cls5 * fifth class * @param cls6 * sixth class * @param cls7 * seventh class * @param <T1> * type of first class * @param <T2> * type of second class * @param <T3> * type of third class * @param <T4> * type of fourth class * @param <T5> * type of fifth class * @param <T6> * type of sixth class * @param <T7> * type of seventh class * @return stream of transaction items */
default <T1, T2, T3, T4, T5, T6, T7> Flowable<Tx<Tuple7<T1, T2, T3, T4, T5, T6, T7>>> getAs(
5
axxepta/project-argon
src/main/java/de/axxepta/oxygen/workspace/DitaMapManagerChangeListener.java
[ "public class CheckInAction extends AbstractAction {\n\n private static final Logger logger = LogManager.getLogger(CheckInAction.class);\n\n private final TreeListener treeListener;\n private URL urlString = null;\n\n public CheckInAction(String name, Icon icon, String urlString, TreeListener treeListen...
import de.axxepta.oxygen.actions.CheckInAction; import de.axxepta.oxygen.actions.CheckOutAction; import de.axxepta.oxygen.api.*; import de.axxepta.oxygen.customprotocol.ArgonEditorsWatchMap; import de.axxepta.oxygen.customprotocol.CustomProtocolURLUtils; import de.axxepta.oxygen.utils.ImageUtils; import de.axxepta.oxygen.utils.Lang; import de.axxepta.oxygen.versioncontrol.VersionHistoryUpdater; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import ro.sync.ecss.extensions.api.AuthorDocumentController; import ro.sync.ecss.extensions.api.node.AttrValue; import ro.sync.ecss.extensions.api.node.AuthorElement; import ro.sync.ecss.extensions.api.node.AuthorNode; import ro.sync.exml.editor.EditorPageConstants; import ro.sync.exml.workspace.api.editor.WSEditor; import ro.sync.exml.workspace.api.editor.page.ditamap.DITAMapPopupMenuCustomizer; import ro.sync.exml.workspace.api.editor.page.ditamap.WSDITAMapEditorPage; import ro.sync.exml.workspace.api.listeners.WSEditorChangeListener; import ro.sync.exml.workspace.api.standalone.StandalonePluginWorkspace; import javax.swing.*; import java.io.IOException; import java.net.URL; import static de.axxepta.oxygen.utils.WorkspaceUtils.booleanDialog;
package de.axxepta.oxygen.workspace; /** * @author Markus on 05.11.2016. */ class DitaMapManagerChangeListener extends WSEditorChangeListener { private static final Logger logger = LogManager.getLogger(DitaMapManagerChangeListener.class); private final StandalonePluginWorkspace pluginWorkspaceAccess; DitaMapManagerChangeListener(StandalonePluginWorkspace pluginWorkspace) { super(); this.pluginWorkspaceAccess = pluginWorkspace; } @Override public void editorPageChanged(URL editorLocation) { customizeEditorPopupMenu(); } @Override public void editorSelected(URL editorLocation) { customizeEditorPopupMenu(); TopicHolder.changedEditorStatus.postMessage(VersionHistoryUpdater.checkVersionHistory(editorLocation)); } @Override public void editorActivated(URL editorLocation) { customizeEditorPopupMenu(); TopicHolder.changedEditorStatus.postMessage(VersionHistoryUpdater.checkVersionHistory(editorLocation)); } @Override public void editorClosed(URL editorLocation) { if (editorLocation.toString().startsWith(ArgonConst.ARGON)) { try (Connection connection = BaseXConnectionWrapper.getConnection()) { BaseXSource source = CustomProtocolURLUtils.sourceFromURL(editorLocation); String path = CustomProtocolURLUtils.pathFromURL(editorLocation); if (connection.lockedByUser(source, path) && !ArgonEditorsWatchMap.getInstance().askedForCheckIn(editorLocation)) { int checkInFile = booleanDialog(pluginWorkspaceAccess, "Closed checked out file", "You just closed a checked out file. Do you want to check it in?", "Yes", 0, "No", 1, 0); if (checkInFile == 0) { connection.unlock(source, path); } } } catch (IOException ioe) { logger.debug(ioe.getMessage()); } ArgonEditorsWatchMap.getInstance().removeURL(editorLocation); } } private void customizeEditorPopupMenu() { WSEditor editorAccess = pluginWorkspaceAccess.getCurrentEditorAccess(StandalonePluginWorkspace.DITA_MAPS_EDITING_AREA); if (editorAccess != null) { if (EditorPageConstants.PAGE_DITA_MAP.equals(editorAccess.getCurrentPageID())) { WSDITAMapEditorPage currentCustomizedDitaPageAccess; currentCustomizedDitaPageAccess = (WSDITAMapEditorPage) editorAccess.getCurrentPage(); currentCustomizedDitaPageAccess.setPopUpMenuCustomizer(new ArgonDitaPopupMenuCustomizer(currentCustomizedDitaPageAccess)); } } } private JMenuItem createCheckOutEditorPopUpAddition(String urlString) { return new JMenuItem(new CheckOutAction(Lang.get(Lang.Keys.cm_checkout), ImageUtils.getIcon(ImageUtils.UNLOCK), urlString)); } private JMenuItem createCheckInEditorPopUpAddition(String urlString) {
return new JMenuItem(new CheckInAction(Lang.get(Lang.Keys.cm_checkin), ImageUtils.getIcon(ImageUtils.BASEX_LOCKED), urlString));
0
dragonite-network/dragonite-java
dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/network/server/ProxyServer.java
[ "public class ProxyServerConfig {\n\n private InetSocketAddress bindAddress;\n\n private String password;\n\n private int mbpsLimit = 0;\n\n private String welcomeMessage = \"Welcome to \" + SystemInfo.getHostname();\n\n private boolean allowLoopback = false;\n\n private final DragoniteSocketParam...
import com.vecsight.dragonite.proxy.config.ProxyServerConfig; import com.vecsight.dragonite.proxy.misc.ProxyGlobalConstants; import com.vecsight.dragonite.sdk.cryptor.PacketCryptor; import com.vecsight.dragonite.sdk.socket.DragoniteServer; import com.vecsight.dragonite.sdk.socket.DragoniteSocket; import org.pmw.tinylog.Logger; import java.net.InetSocketAddress; import java.net.SocketException;
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.proxy.network.server; public class ProxyServer { private final InetSocketAddress bindAddress; private final int limitMbps; private final String welcomeMessage; private final boolean allowLoopback;
private final PacketCryptor packetCryptor;
2
hprose/hprose-j2me
cldc/1.0/src/hprose/client/HproseClient.java
[ "public interface HproseCallback {\r\n void handler(Object result, Object[] arguments);\r\n}\r", "public interface HproseInvoker {\r\n void invoke(String functionName, HproseCallback callback);\r\n void invoke(String functionName, HproseCallback callback, HproseErrorEvent errorEvent);\r\n void invoke(...
import java.io.InputStream; import java.io.OutputStream; import hprose.common.HproseErrorEvent; import hprose.common.HproseCallback; import hprose.common.HproseInvoker; import hprose.common.HproseException; import hprose.common.HproseResultMode; import hprose.common.HproseFilter; import hprose.io.HproseHelper; import hprose.io.HproseWriter; import hprose.io.HproseReader; import hprose.io.HproseTags; import java.io.ByteArrayOutputStream; import java.io.IOException;
invoke(functionName, arguments, callback, null, null, false, HproseResultMode.Normal); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent) { invoke(functionName, arguments, callback, errorEvent, null, false, HproseResultMode.Normal); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, boolean byRef) { invoke(functionName, arguments, callback, null, null, byRef, HproseResultMode.Normal); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, boolean byRef) { invoke(functionName, arguments, callback, errorEvent, null, byRef, HproseResultMode.Normal); } public final void invoke(String functionName, HproseCallback callback, Class returnType) { invoke(functionName, nullArgs, callback, null, returnType, false, HproseResultMode.Normal); } public final void invoke(String functionName, HproseCallback callback, HproseErrorEvent errorEvent, Class returnType) { invoke(functionName, nullArgs, callback, errorEvent, returnType, false, HproseResultMode.Normal); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, Class returnType) { invoke(functionName, arguments, callback, null, returnType, false, HproseResultMode.Normal); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, Class returnType) { invoke(functionName, arguments, callback, errorEvent, returnType, false, HproseResultMode.Normal); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, Class returnType, boolean byRef) { invoke(functionName, arguments, callback, null, returnType, byRef, HproseResultMode.Normal); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, Class returnType, boolean byRef) { invoke(functionName, arguments, callback, errorEvent, returnType, byRef, HproseResultMode.Normal); } public final void invoke(String functionName, HproseCallback callback, HproseResultMode resultMode) { invoke(functionName, nullArgs, callback, null, null, false, resultMode); } public final void invoke(String functionName, HproseCallback callback, HproseErrorEvent errorEvent, HproseResultMode resultMode) { invoke(functionName, nullArgs, callback, errorEvent, null, false, resultMode); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseResultMode resultMode) { invoke(functionName, arguments, callback, null, null, false, resultMode); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, HproseResultMode resultMode) { invoke(functionName, arguments, callback, errorEvent, null, false, resultMode); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, boolean byRef, HproseResultMode resultMode) { invoke(functionName, arguments, callback, null, null, byRef, resultMode); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, boolean byRef, HproseResultMode resultMode) { invoke(functionName, arguments, callback, errorEvent, null, byRef, resultMode); } private void invoke(final String functionName, final Object[] arguments, final HproseCallback callback, final HproseErrorEvent errorEvent, final Class returnType, final boolean byRef, final HproseResultMode resultMode) { new Thread() { public void run() { try { Object result = invoke(functionName, arguments, returnType, byRef, resultMode); callback.handler(result, arguments); } catch (Throwable ex) { if (errorEvent != null) { errorEvent.handler(functionName, ex); } else if (onError != null) { onError.handler(functionName, ex); } } } }.start(); } public final Object invoke(String functionName) throws IOException { return invoke(functionName, nullArgs, (Class)null, false, HproseResultMode.Normal); } public final Object invoke(String functionName, Object[] arguments) throws IOException { return invoke(functionName, arguments, (Class)null, false, HproseResultMode.Normal); } public final Object invoke(String functionName, Object[] arguments, boolean byRef) throws IOException { return invoke(functionName, arguments, (Class)null, byRef, HproseResultMode.Normal); } public final Object invoke(String functionName, Class returnType) throws IOException { return invoke(functionName, nullArgs, returnType, false, HproseResultMode.Normal); } public final Object invoke(String functionName, Object[] arguments, Class returnType) throws IOException { return invoke(functionName, arguments, returnType, false, HproseResultMode.Normal); } public final Object invoke(String functionName, Object[] arguments, Class returnType, boolean byRef) throws IOException { return invoke(functionName, arguments, returnType, byRef, HproseResultMode.Normal); } public final Object invoke(String functionName, HproseResultMode resultMode) throws IOException { return invoke(functionName, nullArgs, (Class)null, false, resultMode); } public final Object invoke(String functionName, Object[] arguments, HproseResultMode resultMode) throws IOException { return invoke(functionName, arguments, (Class)null, false, resultMode); } public final Object invoke(String functionName, Object[] arguments, boolean byRef, HproseResultMode resultMode) throws IOException { return invoke(functionName, arguments, (Class)null, byRef, resultMode); } private Object invoke(String functionName, Object[] arguments, Class returnType, boolean byRef, HproseResultMode resultMode) throws IOException { Object context = getInvokeContext(); OutputStream ostream = getOutputStream(context); boolean success = false; try { doOutput(functionName, arguments, byRef, ostream); success = true; } finally { sendData(ostream, context, success); } Object result = null; InputStream istream = getInputStream(context); success = false; try { result = doInput(arguments, returnType, resultMode, istream); success = true; } finally { endInvoke(istream, context, success); }
if (result instanceof HproseException) {
2
kihira/Tails
src/main/java/uk/kihira/tails/client/ClientEventHandler.java
[ "public class GuiEditor extends GuiBase\n{\n static final int TEXT_COLOUR = 0xFFFFFF;\n static final int HOZ_LINE_COLOUR = 0xFF000000;\n static final int SOFT_BLACK = 0xEA000000;\n static final int DARK_GREY = 0xFF1A1A1A;\n static final int GREY = 0xFF666666;\n\n private static final int TINT_PANE...
import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screen.IngameMenuScreen; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.client.resources.I18n; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.client.event.ClientPlayerNetworkEvent; import net.minecraftforge.client.event.GuiScreenEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import uk.kihira.tails.client.gui.GuiEditor; import uk.kihira.tails.common.Config; import uk.kihira.tails.common.Tails; import uk.kihira.tails.common.network.PlayerDataMessage; import uk.kihira.tails.common.network.TailsPacketHandler; import uk.kihira.tails.proxy.ClientProxy;
package uk.kihira.tails.client; public class ClientEventHandler { private boolean sentPartInfoToServer = false; private boolean clearAllPartInfo = false; /* *** Tails Editor Button *** */ @SubscribeEvent public void onScreenInitPost(GuiScreenEvent.InitGuiEvent.Post event) { if (event.getGui() instanceof IngameMenuScreen) { Button tailsButton = new Button((event.getGui().width / 2) - 35, event.getGui().height - 25, 70, 20, new TranslationTextComponent("tails.gui.button.editor"), (button) -> { event.getGui().getMinecraft().displayGuiScreen(new GuiEditor()); event.setCanceled(true); }); event.addWidget(tailsButton); } } /* *** Tails syncing *** */ @SubscribeEvent public void onConnectToServer(ClientPlayerNetworkEvent.LoggedInEvent event) { //Add local player texture to map if (Config.localOutfit != null) { Tails.proxy.setActiveOutfit(Minecraft.getInstance().getSession().getProfile().getId(), Config.localOutfit.get()); } } @SubscribeEvent public void onDisconnect(ClientPlayerNetworkEvent.LoggedOutEvent e) { Tails.hasRemote = false; sentPartInfoToServer = false; clearAllPartInfo = true; Config.loadConfig(); } @SubscribeEvent public void onClientTick(TickEvent.ClientTickEvent e) { if (e.phase == TickEvent.Phase.START) { if (clearAllPartInfo) { Tails.proxy.clearAllPartsData(); clearAllPartInfo = false; } //World can't be null if we want to send a packet it seems else if (!sentPartInfoToServer && Minecraft.getInstance().world != null) {
TailsPacketHandler.networkWrapper.sendToServer(new PlayerDataMessage(Minecraft.getInstance().getSession().getProfile().getId(), Config.localOutfit.get(), false));
3
tupilabs/tap4j
src/test/java/org/tap4j/consumer/TestTap13YamlConsumer2.java
[ "public class BaseTapTest {\n\n /**\n * Get a test set for a given file name.\n * @param name File name.\n * @return Test Set.\n */\n protected TestSet getTestSet(String name) {\n return this.getTestSet(new Tap13Parser(), name);\n }\n\n /**\n * Get a test set for given parser ...
import org.tap4j.model.Directive; import org.tap4j.model.Plan; import org.tap4j.model.TestResult; import org.tap4j.model.TestSet; import org.tap4j.util.DirectiveValues; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.tap4j.BaseTapTest;
/* * The MIT License * * Copyright (c) 2010 tap4j team (see AUTHORS) * * 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 org.tap4j.consumer; /** * @since 1.0 */ public class TestTap13YamlConsumer2 extends BaseTapTest { @Test public void testTapConsumerYaml() { final TestSet testSet = getTestSet("/org/tap4j/consumer/tap_with_yaml_comments_bailout_directives.tap"); assertNotNull(testSet); final Plan plan = testSet.getPlan(); assertEquals(1, (int) plan.getInitialTestNumber()); assertEquals(3, (int) plan.getLastTestNumber()); assertEquals(3, testSet.getNumberOfTestResults()); assertTrue(testSet.containsBailOut()); final TestResult testNumber2WithSkipDirective = testSet.getTestResult(2); assertNotNull(testNumber2WithSkipDirective); final Directive skipDirective = testNumber2WithSkipDirective.getDirective();
assertSame(skipDirective.getDirectiveValue(), DirectiveValues.SKIP);
5
twothe/DaVincing
src/main/java/two/davincing/renderer/PieceRenderer.java
[ "@Mod(modid = DaVincing.MOD_ID, name = DaVincing.MOD_NAME, version = DaVincing.MOD_VERSION)\npublic class DaVincing {\n\n /* Global logger that uses string format type logging */\n public static final Logger log = LogManager.getLogger(DaVincing.class.getSimpleName(), new StringFormatterMessageFactory());\n /* Ta...
import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import two.davincing.DaVincing; import two.davincing.ProxyBase; import two.davincing.item.PieceItem; import two.davincing.sculpture.SculptureBlock; import two.davincing.utils.Utils;
package two.davincing.renderer; @SideOnly(Side.CLIENT) public class PieceRenderer implements IItemRenderer { protected static final Minecraft mc = Minecraft.getMinecraft(); protected final RenderItem renderItem = new RenderItem(); protected ItemStack is; @Override public boolean handleRenderType(ItemStack item, ItemRenderType type) { return type == ItemRenderType.INVENTORY || type == ItemRenderType.ENTITY || type == ItemRenderType.EQUIPPED || type == ItemRenderType.EQUIPPED_FIRST_PERSON; } @Override public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { return type == ItemRenderType.ENTITY || type == ItemRenderType.EQUIPPED_FIRST_PERSON; } @Override public void renderItem(ItemRenderType type, ItemStack itemStack, Object... data) { if (is == null) { is = new ItemStack(ProxyBase.blockSculpture.getBlock()); }
SculptureBlock sculpture = ProxyBase.blockSculpture.getBlock();
3
jazz-community/jazz-debug-environment
buildSrc/src/main/java/org/jazzcommunity/development/library/config/ConfigReader.java
[ "public class DetectOperatingSystem {\n public static boolean isWindows() {\n return OperatingSystem.current().isWindows();\n }\n\n public static boolean isLinux() {\n return OperatingSystem.current().isLinux();\n }\n}", "public final class FileTools {\n\n private static final Logger logger = LoggerFac...
import com.google.common.io.CharSource; import com.google.common.io.Files; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jazzcommunity.development.library.DetectOperatingSystem; import org.jazzcommunity.development.library.FileTools; import org.jazzcommunity.development.library.config.plugin.IniEntry; import org.jazzcommunity.development.library.config.plugin.PluginEntryFactory; import org.jazzcommunity.development.library.file.FileReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.jazzcommunity.development.library.config; public class ConfigReader { private static final Logger logger = LoggerFactory.getLogger("ConfigReader"); public ConfigReader() {} public static String[] windowsTerminal() { return readConfig(FileTools.toAbsolute("jde/user/windows_terminal_emulator.cfg")) .findFirst() .map(s -> s.split(" ")) .orElseGet(() -> new String[] {"cmd", "/K", "start", "powershell", "./run_jetty.ps1"}); } public static String[] linuxTerminal() { return readConfig(FileTools.toAbsolute("jde/user/linux_terminal_emulator.cfg")) .findFirst() .map(s -> s.split(" ")) .orElseGet(() -> new String[] {"gnome-terminal", "--", "./run_jetty.sh"}); } public static String javaPath() { return readConfig(FileTools.toAbsolute("jde/user/java_command.cfg")) .findFirst() .orElseGet(ConfigReader::defaultJava); } /** * This returns a list because we need to have a possible null-check when writing to the jtwig * templates. Otherwise, this method would be a lot cleaner. * * <p>TODO: Move empty check to template */ public static List<String> runtimeParameters() { List<String> lines = readConfig(FileTools.toAbsolute("jde/user/run_time_parameters.cfg")) .collect(Collectors.toList()); return !lines.isEmpty() ? lines : null; } public static Stream<String> flattenConfigs(String directory) { return flattenConfigs(FileTools.toAbsolute(directory)); } public static Stream<String> flattenConfigs(File directory) { File[] files = directory.listFiles(); return Arrays.stream(files) .map(f -> Files.asCharSource(f, StandardCharsets.UTF_8)) .flatMap(FileReader::read) .filter(ConfigReader::isConfigLine); } public static Stream<IniEntry> userConfiguration() { return flattenConfigs(FileTools.toAbsolute("jde/user/workspaces")) .filter(ConfigReader::isConfigLine) .map(File::new)
.map(PluginEntryFactory::getEntry);
3
baratine/lucene-plugin
service/src/test/java/tests/TestSearchCollection.java
[ "public class LuceneEntry\n{\n private int _id;\n private float _score;\n private String _externalId;\n\n public LuceneEntry()\n {\n }\n\n public LuceneEntry(int id)\n {\n this(0, Float.MAX_VALUE);\n }\n\n public LuceneEntry(int id, float score)\n {\n this(id, score, null);\n }\n\n public LuceneE...
import java.io.IOException; import java.util.concurrent.ExecutionException; import com.caucho.junit.ConfigurationBaratine; import com.caucho.junit.RunnerBaratine; import com.caucho.junit.ServiceTest; import com.caucho.lucene.LuceneEntry; import com.caucho.lucene.LuceneFacadeImpl; import com.caucho.lucene.LuceneReaderImpl; import com.caucho.lucene.LuceneWriterImpl; import com.caucho.lucene.SearcherUpdateServiceImpl; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith;
package tests; /** * title: tests collection */ @RunWith(RunnerBaratine.class) @ServiceTest(LuceneWriterImpl.class) @ServiceTest(LuceneReaderImpl.class)
@ServiceTest(LuceneFacadeImpl.class)
1
ebolwidt/cassowary-java
src/main/java/org/klomp/cassowary/clconstraint/ClLinearInequality.java
[ "public class CL {\n protected final static boolean fDebugOn = false;\n public static boolean fTraceOn = false; // true;\n protected final static boolean fTraceAdded = false;\n protected final static boolean fGC = false;\n\n protected static void debugprint(String s) {\n System.err.println(s);...
import org.klomp.cassowary.CL; import org.klomp.cassowary.CLInternalError; import org.klomp.cassowary.ClAbstractVariable; import org.klomp.cassowary.ClLinearExpression; import org.klomp.cassowary.ClStrength; import org.klomp.cassowary.ClVariable;
/* * Cassowary Incremental Constraint Solver * Original Smalltalk Implementation by Alan Borning * * Java Implementation by: * Greg J. Badros * Erwin Bolwidt * * (C) 1998, 1999 Greg J. Badros and Alan Borning * (C) Copyright 2012 Erwin Bolwidt * * See the file LICENSE for legal details regarding this software */ package org.klomp.cassowary.clconstraint; public class ClLinearInequality extends ClLinearConstraint { public ClLinearInequality(ClLinearExpression cle, ClStrength strength, double weight) { super(cle, strength, weight); } public ClLinearInequality(ClLinearExpression cle, ClStrength strength) { super(cle, strength); } public ClLinearInequality(ClLinearExpression cle) { super(cle); } public ClLinearInequality(ClVariable clv1, byte op_enum, ClVariable clv2, ClStrength strength, double weight) throws CLInternalError { super(new ClLinearExpression(clv2), strength, weight); if (op_enum == CL.GEQ) { _expression.multiplyMe(-1.0); _expression.addVariable(clv1); } else if (op_enum == CL.LEQ) { _expression.addVariable(clv1, -1.0); } else // the operator was invalid throw new CLInternalError("Invalid operator in ClLinearInequality constructor"); } public ClLinearInequality(ClVariable clv1, byte op_enum, ClVariable clv2, ClStrength strength) throws CLInternalError { this(clv1, op_enum, clv2, strength, 1.0); } public ClLinearInequality(ClVariable clv1, byte op_enum, ClVariable clv2) throws CLInternalError { this(clv1, op_enum, clv2, ClStrength.required, 1.0); } public ClLinearInequality(ClVariable clv, byte op_enum, double val, ClStrength strength, double weight) throws CLInternalError { super(new ClLinearExpression(val), strength, weight); if (op_enum == CL.GEQ) { _expression.multiplyMe(-1.0); _expression.addVariable(clv); } else if (op_enum == CL.LEQ) { _expression.addVariable(clv, -1.0); } else // the operator was invalid throw new CLInternalError("Invalid operator in ClLinearInequality constructor"); } public ClLinearInequality(ClVariable clv, byte op_enum, double val, ClStrength strength) throws CLInternalError { this(clv, op_enum, val, strength, 1.0); } public ClLinearInequality(ClVariable clv, byte op_enum, double val) throws CLInternalError { this(clv, op_enum, val, ClStrength.required, 1.0); } public ClLinearInequality(ClLinearExpression cle1, byte op_enum, ClLinearExpression cle2, ClStrength strength, double weight) throws CLInternalError { super(cle2.clone(), strength, weight); if (op_enum == CL.GEQ) { _expression.multiplyMe(-1.0); _expression.addExpression(cle1); } else if (op_enum == CL.LEQ) { _expression.addExpression(cle1, -1.0); } else // the operator was invalid throw new CLInternalError("Invalid operator in ClLinearInequality constructor"); } public ClLinearInequality(ClLinearExpression cle1, byte op_enum, ClLinearExpression cle2, ClStrength strength) throws CLInternalError { this(cle1, op_enum, cle2, strength, 1.0); } public ClLinearInequality(ClLinearExpression cle1, byte op_enum, ClLinearExpression cle2) throws CLInternalError { this(cle1, op_enum, cle2, ClStrength.required, 1.0); }
public ClLinearInequality(ClAbstractVariable clv, byte op_enum, ClLinearExpression cle, ClStrength strength, double weight)
2
gto76/fun-photo-time
src/main/java/si/gto76/funphototime/enums/MultipleParameterFilter.java
[ "public class MyInternalFrame extends JInternalFrame \n\t\t\t\t\t\timplements InternalFrameListener /*, MouseMotionListener*/ {\n\t\n\tprivate static final long serialVersionUID = -1665181775406001910L;\n\t\n\t// TODO: This is true for metal L&F, probably not for others,\n\t// and will thus probably effect tile ope...
import java.awt.image.BufferedImage; import si.gto76.funphototime.MyInternalFrame; import si.gto76.funphototime.Utility; import si.gto76.funphototime.dialogs.ColorsDialog; import si.gto76.funphototime.dialogs.FilterDialogThatReturnsInts; import si.gto76.funphototime.dialogs.HistogramStretchingDialog; import si.gto76.funphototime.filterthreads2.ColorsThread2; import si.gto76.funphototime.filterthreads2.HistogramStretchingThread2;
package si.gto76.funphototime.enums; public enum MultipleParameterFilter { HISTOGRAM_STRETCHING, COLOR_BALANCE; public FilterDialogThatReturnsInts getDialog(MyInternalFrame frame) { switch (this) { case HISTOGRAM_STRETCHING: double[] histogram = Utility.getHistogram(frame.getImg()); BufferedImage histogramImg = Utility.getHistogramImage(histogram);
return new HistogramStretchingDialog(frame, histogramImg);
4
protolambda/blocktopograph
app/src/main/java/com/protolambda/blocktopograph/WorldActivity.java
[ "public enum Dimension {\n\n OVERWORLD(0, \"overworld\", \"Overworld\", 16, 16, 128, 1, MapType.OVERWORLD_SATELLITE),\n NETHER(1, \"nether\", \"Nether\", 16, 16, 128, 8, MapType.NETHER),\n END(2, \"end\", \"End\", 16, 16, 128, 1, MapType.END_SATELLITE);//mcpe: SOON^TM /jk\n\n public final int id;\n p...
import android.app.AlertDialog; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.text.Editable; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.google.firebase.analytics.FirebaseAnalytics; import com.protolambda.blocktopograph.map.Dimension; import com.protolambda.blocktopograph.map.marker.AbstractMarker; import com.protolambda.blocktopograph.nbt.convert.NBTConstants; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.protolambda.blocktopograph.chunk.NBTChunkData; import com.protolambda.blocktopograph.map.MapFragment; import com.protolambda.blocktopograph.map.renderer.MapType; import com.protolambda.blocktopograph.nbt.EditableNBT; import com.protolambda.blocktopograph.nbt.EditorFragment; import com.protolambda.blocktopograph.nbt.convert.DataConverter; import com.protolambda.blocktopograph.nbt.tags.CompoundTag; import com.protolambda.blocktopograph.nbt.tags.Tag;
package com.protolambda.blocktopograph; public class WorldActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, WorldActivityInterface, MenuHelper.MenuContext { private World world;
private MapFragment mapFragment;
4
googlearchive/android-AutofillFramework
afservice/src/main/java/com/example/android/autofill/service/data/adapter/DatasetAdapter.java
[ "public final class AutofillHints {\n public static final int PARTITION_ALL = -1;\n public static final int PARTITION_OTHER = 0;\n public static final int PARTITION_ADDRESS = 1;\n public static final int PARTITION_EMAIL = 2;\n public static final int PARTITION_CREDIT_CARD = 3;\n public static fina...
import android.app.assist.AssistStructure; import android.content.IntentSender; import android.service.autofill.Dataset; import android.util.MutableBoolean; import android.view.View; import android.view.autofill.AutofillId; import android.view.autofill.AutofillValue; import android.widget.RemoteViews; import com.example.android.autofill.service.AutofillHints; import com.example.android.autofill.service.ClientParser; import com.example.android.autofill.service.model.DatasetWithFilledAutofillFields; import com.example.android.autofill.service.model.FieldType; import com.example.android.autofill.service.model.FieldTypeWithHeuristics; import com.example.android.autofill.service.model.FilledAutofillField; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import static com.example.android.autofill.service.util.Util.indexOf; import static com.example.android.autofill.service.util.Util.logv; import static com.example.android.autofill.service.util.Util.logw; import static java.util.stream.Collectors.toMap;
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofill.service.data.adapter; public class DatasetAdapter { private final ClientParser mClientParser; public DatasetAdapter(ClientParser clientParser) { mClientParser = clientParser; } /** * Wraps autofill data in a {@link Dataset} object which can then be sent back to the client. */ public Dataset buildDataset(HashMap<String, FieldTypeWithHeuristics> fieldTypesByAutofillHint, DatasetWithFilledAutofillFields datasetWithFilledAutofillFields, RemoteViews remoteViews) { return buildDataset(fieldTypesByAutofillHint, datasetWithFilledAutofillFields, remoteViews, null); } public Dataset buildDatasetForFocusedNode(FilledAutofillField filledAutofillField, FieldType fieldType, RemoteViews remoteViews) { Dataset.Builder datasetBuilder = new Dataset.Builder(remoteViews); boolean setAtLeastOneValue = bindDatasetToFocusedNode(filledAutofillField, fieldType, datasetBuilder); if (!setAtLeastOneValue) { return null; } return datasetBuilder.build(); } /** * Wraps autofill data in a {@link Dataset} object with an IntentSender, which can then be * sent back to the client. */ public Dataset buildDataset(HashMap<String, FieldTypeWithHeuristics> fieldTypesByAutofillHint, DatasetWithFilledAutofillFields datasetWithFilledAutofillFields, RemoteViews remoteViews, IntentSender intentSender) { Dataset.Builder datasetBuilder = new Dataset.Builder(remoteViews); if (intentSender != null) { datasetBuilder.setAuthentication(intentSender); } boolean setAtLeastOneValue = bindDataset(fieldTypesByAutofillHint, datasetWithFilledAutofillFields, datasetBuilder); if (!setAtLeastOneValue) { return null; } return datasetBuilder.build(); } /** * Build an autofill {@link Dataset} using saved data and the client's AssistStructure. */ private boolean bindDataset(HashMap<String, FieldTypeWithHeuristics> fieldTypesByAutofillHint, DatasetWithFilledAutofillFields datasetWithFilledAutofillFields, Dataset.Builder datasetBuilder) { MutableBoolean setValueAtLeastOnce = new MutableBoolean(false); Map<String, FilledAutofillField> filledAutofillFieldsByTypeName = datasetWithFilledAutofillFields.filledAutofillFields.stream() .collect(toMap(FilledAutofillField::getFieldTypeName, Function.identity())); mClientParser.parse((node) -> parseAutofillFields(node, fieldTypesByAutofillHint, filledAutofillFieldsByTypeName, datasetBuilder, setValueAtLeastOnce) ); return setValueAtLeastOnce.value; } private boolean bindDatasetToFocusedNode(FilledAutofillField field, FieldType fieldType, Dataset.Builder builder) { MutableBoolean setValueAtLeastOnce = new MutableBoolean(false); mClientParser.parse((node) -> { if (node.isFocused() && node.getAutofillId() != null) { bindValueToNode(node, field, builder, setValueAtLeastOnce); } }); return setValueAtLeastOnce.value; } private void parseAutofillFields(AssistStructure.ViewNode viewNode, HashMap<String, FieldTypeWithHeuristics> fieldTypesByAutofillHint, Map<String, FilledAutofillField> filledAutofillFieldsByTypeName, Dataset.Builder builder, MutableBoolean setValueAtLeastOnce) { String[] rawHints = viewNode.getAutofillHints(); if (rawHints == null || rawHints.length == 0) { logv("No af hints at ViewNode - %s", viewNode.getIdEntry()); return; } String fieldTypeName = AutofillHints.getFieldTypeNameFromAutofillHints( fieldTypesByAutofillHint, Arrays.asList(rawHints)); if (fieldTypeName == null) { return; } FilledAutofillField field = filledAutofillFieldsByTypeName.get(fieldTypeName); if (field == null) { return; } bindValueToNode(viewNode, field, builder, setValueAtLeastOnce); } void bindValueToNode(AssistStructure.ViewNode viewNode, FilledAutofillField field, Dataset.Builder builder, MutableBoolean setValueAtLeastOnce) { AutofillId autofillId = viewNode.getAutofillId(); if (autofillId == null) {
logw("Autofill ID null for %s", viewNode.toString());
8
DanielThomas/groundhog
proxy/src/main/java/io/groundhog/proxy/ProxyModule.java
[ "@Immutable\npublic enum URIScheme {\n HTTP(\"http\", 80),\n HTTPS(\"https\", 443);\n\n private final String scheme;\n private final int defaultPort;\n\n private URIScheme(String scheme, int defaultPort) {\n this.scheme = scheme;\n this.defaultPort = defaultPort;\n }\n\n public String scheme() {\n r...
import io.groundhog.base.URIScheme; import io.groundhog.capture.CaptureController; import io.groundhog.capture.CaptureWriter; import io.groundhog.capture.DefaultCaptureController; import io.groundhog.har.HarFileCaptureWriter; import com.google.common.base.Optional; import com.google.common.base.Throwables; import com.google.common.net.HostAndPort; import com.google.inject.AbstractModule; import com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.inject.name.Names; import io.netty.channel.ChannelHandler; import org.littleshoot.proxy.HttpFiltersSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull;
package io.groundhog.proxy; public class ProxyModule extends AbstractModule { private static final Logger LOG = LoggerFactory.getLogger(ProxyModule.class); private static final int PARENT_LIMIT = 2; private static final String PROPERTIES_FILENAME = "conf/config.properties"; @Override protected void configure() { Properties properties = new Properties(); try { // Depending on the type of distribution, the conf directory can be one or two directories up File parentDir = new File(System.getProperty("user.dir")); Optional<File> configFile = findConfigInParent(parentDir, PARENT_LIMIT); File propertiesFile; if (!configFile.isPresent()) { propertiesFile = new File("src/dist", PROPERTIES_FILENAME); // Gradle application run task if (!propertiesFile.exists()) { propertiesFile = new File("proxy/src/dist", PROPERTIES_FILENAME); // IntelliJ launch } LOG.warn("Could not locate {} in current or parent directories up to {} levels deep. Falling back to developer config {}", PROPERTIES_FILENAME, PARENT_LIMIT, propertiesFile); } else { propertiesFile = configFile.get(); } properties.load(new FileInputStream(propertiesFile)); } catch (IOException e) { LOG.error("Failed to load properties file"); Throwables.propagate(e); } for (String addressType : Arrays.asList("target", "listen")) { String host = properties.getProperty(addressType + ".address"); for (URIScheme uriScheme : URIScheme.values()) { String prefix = addressType + "." + uriScheme.scheme(); int port = Integer.valueOf(properties.getProperty(prefix + "_port")); bind(HostAndPort.class).annotatedWith(Names.named(prefix)).toInstance(HostAndPort.fromParts(host, port)); } } File outputLocation = new File(properties.getProperty("output.location")); checkArgument(outputLocation.isDirectory(), "output.location must be a directory and must exist"); String outputCompression = properties.getProperty("output.compression"); CaptureWriter captureWriter = new HarFileCaptureWriter(outputLocation, true, false, false, "gzip".equals(outputCompression)); bind(CaptureWriter.class).toInstance(captureWriter);
bind(CaptureController.class).to(DefaultCaptureController.class);
1
alex73/OSMemory
src/org/alex73/osmemory/geometry/OsmHelper.java
[ "public interface IOsmNode extends IOsmObject {\n public static final double DIVIDER = 0.0000001;\n\n /**\n * Get latitude as int, i.e. multiplied by 10000000.\n */\n int getLat();\n\n /**\n * Get longitude as int, i.e. multiplied by 10000000.\n */\n int getLon();\n\n /**\n * G...
import org.alex73.osmemory.IOsmNode; import org.alex73.osmemory.IOsmObject; import org.alex73.osmemory.IOsmRelation; import org.alex73.osmemory.IOsmWay; import org.alex73.osmemory.MemoryStorage; import com.vividsolutions.jts.geom.Geometry;
/************************************************************************** OSMemory library for OSM data processing. Copyright (C) 2014 Aleś Bułojčyk <alex73mail@gmail.com> This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ package org.alex73.osmemory.geometry; /** * Creates area geometry from way or relation. */ public class OsmHelper { public static Geometry areaFromObject(IOsmObject obj, MemoryStorage osm) { if (obj.isWay()) {
return new ExtendedWay((IOsmWay) obj, osm).getArea();
3
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/MobileOrgApplication.java
[ "public class SyncService extends Service implements\n\t\tSharedPreferences.OnSharedPreferenceChangeListener {\n\tprivate static final String ACTION = \"action\";\n\tprivate static final String START_ALARM = \"START_ALARM\";\n\tprivate static final String STOP_ALARM = \"STOP_ALARM\";\n\n\tprivate SharedPreferences ...
import android.app.Application; import android.content.Context; import android.preference.PreferenceManager; import com.matburt.mobileorg.services.SyncService; import com.matburt.mobileorg.synchronizers.DropboxSynchronizer; import com.matburt.mobileorg.synchronizers.NullSynchronizer; import com.matburt.mobileorg.synchronizers.SDCardSynchronizer; import com.matburt.mobileorg.synchronizers.SSHSynchronizer; import com.matburt.mobileorg.synchronizers.Synchronizer; import com.matburt.mobileorg.synchronizers.UbuntuOneSynchronizer; import com.matburt.mobileorg.synchronizers.WebDAVSynchronizer;
package com.matburt.mobileorg.orgdata; public class MobileOrgApplication extends Application { private static MobileOrgApplication instance; public static Context getContext() { return instance; } @Override public void onCreate() { super.onCreate(); instance = this; OrgDatabase.startDB(this); startSynchronizer(); OrgFileParser.startParser(this); SyncService.startAlarm(this); } public void startSynchronizer() { String syncSource = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()) .getString("syncSource", ""); Context c = getApplicationContext(); if (syncSource.equals("webdav")) Synchronizer.setInstance(new WebDAVSynchronizer(c)); else if (syncSource.equals("sdcard")) Synchronizer.setInstance(new SDCardSynchronizer(c)); else if (syncSource.equals("dropbox")) Synchronizer.setInstance(new DropboxSynchronizer(c)); else if (syncSource.equals("ubuntu")) Synchronizer.setInstance(new UbuntuOneSynchronizer(c)); else if (syncSource.equals("scp"))
Synchronizer.setInstance(new SSHSynchronizer(c));
4
Nilhcem/devoxxfr-2016
app/src/main/java/com/nilhcem/devoxxfr/data/database/DbMapper.java
[ "@Singleton\npublic class LocalDateTimeAdapter {\n\n private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm\", Locale.US);\n\n @Inject\n public LocalDateTimeAdapter() {\n }\n\n @ToJson\n public String toText(LocalDateTime dateTime) {\n return dateTime.for...
import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.nilhcem.devoxxfr.core.moshi.LocalDateTimeAdapter; import com.nilhcem.devoxxfr.data.app.AppMapper; import com.nilhcem.devoxxfr.data.app.model.Room; import com.nilhcem.devoxxfr.data.database.model.Session; import com.nilhcem.devoxxfr.data.database.model.Speaker; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import com.squareup.moshi.Types; import org.threeten.bp.LocalDateTime; import org.threeten.bp.temporal.ChronoUnit; import java.io.IOException; import java.util.List; import java.util.Map; import javax.inject.Inject; import java8.util.stream.Collectors; import timber.log.Timber; import static java8.util.stream.StreamSupport.stream;
package com.nilhcem.devoxxfr.data.database; public class DbMapper { private final AppMapper appMapper; private final LocalDateTimeAdapter localDateTimeAdapter; private final JsonAdapter<List<Integer>> intListAdapter; @Inject public DbMapper(Moshi moshi, AppMapper appMapper, LocalDateTimeAdapter localDateTimeAdapter) { this.appMapper = appMapper; this.localDateTimeAdapter = localDateTimeAdapter; this.intListAdapter = moshi.adapter(Types.newParameterizedType(List.class, Integer.class)); }
public List<com.nilhcem.devoxxfr.data.app.model.Session> toAppSessions(@NonNull List<Session> from, @NonNull Map<Integer, com.nilhcem.devoxxfr.data.app.model.Speaker> speakersMap) {
3
DDoS/JICI
src/main/java/ca/sapon/jici/parser/expression/logic/BooleanLogic.java
[ "public class Environment {\n // TODO make me thread safe\n private static final Map<String, Class<?>> DEFAULT_CLASSES = new HashMap<>();\n private final Map<String, Class<?>> classes = new LinkedHashMap<>(DEFAULT_CLASSES);\n private final Map<String, Variable> variables = new LinkedHashMap<>();\n\n ...
import ca.sapon.jici.parser.expression.Expression; import ca.sapon.jici.util.TypeUtil; import ca.sapon.jici.evaluator.Environment; import ca.sapon.jici.evaluator.EvaluatorException; import ca.sapon.jici.evaluator.type.PrimitiveType; import ca.sapon.jici.evaluator.type.Type; import ca.sapon.jici.evaluator.value.BooleanValue; import ca.sapon.jici.evaluator.value.Value; import ca.sapon.jici.lexer.Symbol;
/* * This file is part of JICI, licensed under the MIT License (MIT). * * Copyright (c) 2015-2016 Aleksi Sapon <http://sapon.ca/jici/> * * 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 ca.sapon.jici.parser.expression.logic; public class BooleanLogic implements Expression { private final Expression left; private final Expression right;
private final Symbol operator;
6
Kindrat/cassandra-client
src/main/java/com/github/kindrat/cassandra/client/ui/widget/DataExportWidget.java
[ "public interface MessageByLocaleService {\n String getMessage(String id);\n}", "@Value\npublic class CsvTargetMetadata {\n private String table;\n private CSVFormat format;\n private File target;\n}", "@Data\n@ConfigurationProperties(prefix = \"client.ui\")\npublic class UIProperties {\n private...
import com.github.kindrat.cassandra.client.i18n.MessageByLocaleService; import com.github.kindrat.cassandra.client.model.CsvTargetMetadata; import com.github.kindrat.cassandra.client.properties.UIProperties; import com.github.kindrat.cassandra.client.ui.fx.component.LabeledComponentColumn; import com.github.kindrat.cassandra.client.util.UIUtil; import javafx.collections.FXCollections; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Modality; import javafx.stage.Stage; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.QuoteMode; import org.apache.commons.lang3.StringUtils; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoProcessor; import java.io.File; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import static com.github.kindrat.cassandra.client.ui.listener.CheckBoxListener.create; import static com.github.kindrat.cassandra.client.util.UIUtil.fillParent;
ComboBox<String> formats = buildFormatBox(200); CheckBox customizeCheckbox = new CheckBox("override format settings"); customizeCheckbox.selectedProperty().addListener(create( () -> { FormatSettingsBox formatSettingsBox = buildFormatSettingsBox(formats); formatSettingsBox.prefWidthProperty().bind(settingsContainer.widthProperty()); settingsContainer.getChildren().add(formatSettingsBox); startButton.setOnAction(event -> { if (customizeCheckbox.isSelected()) { CSVFormat csvFormat = formatSettingsBox.build(); File target = new File(pathField.getText()); metadataProcessor.onNext(new CsvTargetMetadata(table, csvFormat, target)); hide(); } }); }, () -> settingsContainer.getChildren().clear()) ); startButton.setOnAction(event -> { if (!customizeCheckbox.isSelected()) { FormatSettingsBox formatSettingsBox = buildFormatSettingsBox(formats); CSVFormat csvFormat = formatSettingsBox.build(); File target = new File(pathField.getText()); metadataProcessor.onNext(new CsvTargetMetadata(table, csvFormat, target)); hide(); } }); formats.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { if (!Objects.equals(oldValue, newValue)) { customizeCheckbox.setSelected(!customizeCheckbox.isSelected()); customizeCheckbox.setSelected(!customizeCheckbox.isSelected()); } }); HBox format = new HBox(formatLabel, formats, customizeCheckbox); format.setAlignment(Pos.CENTER); format.setSpacing(properties.getExportSpacing()); pathField.prefWidthProperty().bind(editor.widthProperty().multiply(0.6)); Button destinationButton = new Button("Choose destination"); HBox savePath = new HBox(pathField, destinationButton); savePath.setAlignment(Pos.CENTER); savePath.setSpacing(properties.getExportSpacing()); destinationButton.setOnAction(event -> { FileChooser savePathProvider = new FileChooser(); savePathProvider.setTitle("Save CSV"); savePathProvider.setInitialFileName(table + ".csv"); savePathProvider.setSelectedExtensionFilter(new FileChooser.ExtensionFilter("CSV", "csv")); File file = savePathProvider.showSaveDialog(this); if (file != null) { pathField.setText(file.getAbsolutePath()); } }); editor.getChildren().addAll(format, savePath, settingsContainer, startButton); return new Scene(container, properties.getExportWidth(), properties.getExportHeight()); } private ComboBox<String> buildFormatBox(int width) { ComboBox<String> box = new ComboBox<>(FXCollections.observableList(CSV_FORMATS)); box.getSelectionModel().select(CSVFormat.Predefined.Default.toString()); box.setMinWidth(width - 20); box.setMaxWidth(width - 20); return box; } private FormatSettingsBox buildFormatSettingsBox(ComboBox<String> formatBox) { String selectedFormat = formatBox.getSelectionModel().getSelectedItem(); return new FormatSettingsBox(CSVFormat.valueOf(selectedFormat), properties.getExportSpacing()); } static class FormatSettingsBox extends HBox { private final CSVFormat format; private final TextField delimiter; private final TextField quoteCharacter; private final ComboBox<QuoteMode> quoteModeComboBox; private final TextField commentStart; private final TextField escapeCharacter; private final CheckBox ignoreSurroundingSpaces; private final CheckBox allowMissingColumnNames; private final CheckBox ignoreEmptyLines; private final TextField recordSeparator; private final TextField nullString; private final TextField headerComments; private final TextField headers; private final CheckBox skipHeaderRecord; private final CheckBox ignoreHeaderCase; private final CheckBox trailingDelimiter; private final CheckBox trim; FormatSettingsBox(CSVFormat format, Integer spacing) { this.format = format; delimiter = new TextField(String.valueOf(format.getDelimiter())); quoteCharacter = new TextField(String.valueOf(format.getQuoteCharacter())); quoteModeComboBox = new ComboBox<>(FXCollections.observableList(Arrays.asList(QuoteMode.values()))); quoteModeComboBox.getSelectionModel().select(format.getQuoteMode()); commentStart = new TextField(String.valueOf(format.getCommentMarker())); escapeCharacter = new TextField(String.valueOf(format.getEscapeCharacter())); ignoreSurroundingSpaces = new CheckBox(); ignoreSurroundingSpaces.selectedProperty().setValue(format.getIgnoreSurroundingSpaces()); allowMissingColumnNames = new CheckBox(); allowMissingColumnNames.selectedProperty().setValue(format.getAllowMissingColumnNames()); ignoreEmptyLines = new CheckBox(); ignoreEmptyLines.selectedProperty().setValue(format.getIgnoreEmptyLines()); recordSeparator = new TextField(encloseRecordSeparator(format.getRecordSeparator())); nullString = new TextField(format.getNullString()); headerComments = new TextField(Arrays.toString(format.getHeaderComments())); headers = new TextField(Arrays.toString(format.getHeader())); skipHeaderRecord = new CheckBox(); skipHeaderRecord.selectedProperty().setValue(format.getSkipHeaderRecord()); ignoreHeaderCase = new CheckBox(); ignoreHeaderCase.selectedProperty().setValue(format.getIgnoreHeaderCase()); trailingDelimiter = new CheckBox(); trailingDelimiter.selectedProperty().setValue(format.getTrailingDelimiter()); trim = new CheckBox(); trim.selectedProperty().setValue(format.getTrailingDelimiter());
UIUtil.setWidth(delimiter, 50);
4
Cantara/Java-Auto-Update
src/main/java/no/cantara/jau/coms/CheckForUpdateHelper.java
[ "public class ApplicationProcess {\n private static final Logger log = LoggerFactory.getLogger(ApplicationProcess.class);\n private File workingDirectory;\n private String[] command;\n private Map<String, String> environment;\n private Process runningProcess;\n\n private String clientId;\n priv...
import no.cantara.cs.client.ConfigServiceClient; import no.cantara.cs.client.EventExtractionUtil; import no.cantara.cs.client.HttpException; import no.cantara.cs.dto.CheckForUpdateRequest; import no.cantara.cs.dto.ClientConfig; import no.cantara.cs.dto.event.Event; import no.cantara.cs.dto.event.ExtractedEventsStore; import no.cantara.jau.ApplicationProcess; import no.cantara.jau.JavaAutoUpdater; import no.cantara.jau.eventextraction.EventExtractorService; import no.cantara.jau.util.ClientEnvironmentUtil; import no.cantara.jau.util.PropertiesHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.List; import java.util.Properties; import java.util.SortedMap; import java.util.concurrent.ScheduledFuture;
package no.cantara.jau.coms; /** * Created by jorunfa on 29/10/15. */ public class CheckForUpdateHelper { private static final Logger log = LoggerFactory.getLogger(CheckForUpdateHelper.class); public static Runnable getCheckForUpdateRunnable(long interval, ConfigServiceClient configServiceClient, ApplicationProcess processHolder, ScheduledFuture<?> processMonitorHandle, EventExtractorService extractorService,
JavaAutoUpdater jau
1
bitkylin/BitkyShop
Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/userfragment/loginfragment/SignupActivity.java
[ "public class KyUser extends BmobUser {\n private String pwdResumeQuestion;\n private String pwdResumeAnswer;\n private Boolean haveDetailInfo;\n\n public Boolean getHaveDetailInfo() {\n return haveDetailInfo;\n }\n\n public void setHaveDetailInfo(Boolean haveDetailInfo) {\n this.haveDetailInfo = haveDe...
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import cc.bitky.bitkyshop.R; import cc.bitky.bitkyshop.bean.cart.KyUser; import cc.bitky.bitkyshop.utils.KyToolBar; import cc.bitky.bitkyshop.utils.ToastUtil; import cc.bitky.bitkyshop.utils.tools.KyPattern; import cc.bitky.bitkyshop.utils.tools.KySet; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.SaveListener; import cn.bmob.v3.listener.UpdateListener; import rx.Subscriber;
package cc.bitky.bitkyshop.fragment.userfragment.loginfragment; public class SignupActivity extends AppCompatActivity implements View.OnClickListener { ToastUtil toastUtil; private EditText confirmPwd; private EditText inputPwd; private EditText pwdResumeAnswer; private EditText pwdResumeQuestion; private EditText userName; private String userNameStr; private String inputPwdStr; private String confirmPwdStr; private String pwdResumeQuestionStr; private String pwdResumeAnswerStr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); toastUtil = new ToastUtil(this); KyToolBar kyToolBar = (KyToolBar) findViewById(R.id.signupActivity_toolbar); kyToolBar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); userName = (EditText) findViewById(R.id.signupActivity_editText_userName); inputPwd = (EditText) findViewById(R.id.signupActivity_editText_inputPwd); confirmPwd = (EditText) findViewById(R.id.signupActivity_editText_confirmPwd); pwdResumeQuestion = (EditText) findViewById(R.id.signupActivity_editText_pwdResumeQuestion); pwdResumeAnswer = (EditText) findViewById(R.id.signupActivity_editText_pwdResumeAnswer); Button btnSignup = (Button) findViewById(R.id.signupActivity_btn_signup); btnSignup.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.signupActivity_btn_signup: userNameStr = userName.getText().toString().trim(); inputPwdStr = inputPwd.getText().toString().trim(); confirmPwdStr = confirmPwd.getText().toString().trim(); pwdResumeQuestionStr = pwdResumeQuestion.getText().toString().trim(); pwdResumeAnswerStr = pwdResumeQuestion.getText().toString().trim(); //验证是否填写完整 if (userNameStr.length() == 0 || inputPwdStr.length() == 0 || confirmPwdStr.length() == 0 || pwdResumeQuestionStr.length() == 0 || pwdResumeAnswerStr.length() == 0) { toastUtil.show("请将上面的编辑框填写完整"); break; } //验证密码是否一致 if (!inputPwdStr.equals(confirmPwdStr)) { toastUtil.show("密码框中的密码不一致,请重新输入"); inputPwd.setText(""); confirmPwd.setText(""); break; } //验证语法规则
if (!KyPattern.checkUserName(userNameStr)) {
3
cdancy/artifactory-rest
src/test/java/com/cdancy/artifactory/rest/features/StorageApiMockTest.java
[ "public static void assertFalse(boolean value) {\n assertThat(value).isFalse();\n}", "public static void assertNotNull(Object value) {\n assertThat(value).isNotNull();\n}", "public static void assertNull(Object value) {\n assertThat(value).isNull();\n}", "public static void assertTrue(boolean value) ...
import com.squareup.okhttp.mockwebserver.MockWebServer; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.cdancy.artifactory.rest.TestUtilities.assertFalse; import static com.cdancy.artifactory.rest.TestUtilities.assertNotNull; import static com.cdancy.artifactory.rest.TestUtilities.assertNull; import static com.cdancy.artifactory.rest.TestUtilities.assertTrue; import com.cdancy.artifactory.rest.domain.artifact.Artifact; import com.cdancy.artifactory.rest.domain.storage.FileList; import com.cdancy.artifactory.rest.domain.storage.StorageInfo; import com.google.common.collect.Lists; import org.testng.annotations.Test; import com.cdancy.artifactory.rest.ArtifactoryApi; import com.cdancy.artifactory.rest.BaseArtifactoryMockTest; import com.squareup.okhttp.mockwebserver.MockResponse;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cdancy.artifactory.rest.features; /** * Mock tests for the {@link com.cdancy.artifactory.rest.features.StorageApi} * class. */ @Test(groups = "unit", testName = "StorageApiMockTest") public class StorageApiMockTest extends BaseArtifactoryMockTest { public void testSetItemProperties() throws Exception { MockWebServer server = mockArtifactoryJavaWebServer(); server.enqueue(new MockResponse().setResponseCode(200));
ArtifactoryApi jcloudsApi = api(server.getUrl("/"));
7
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/rest/resource/ChatroomResource.java
[ "@Vetoed //CDI対象外\n@Entity\npublic class Chat implements Serializable {\n \n /** id(自動生成) */\n @Id\n @GeneratedValue // ID自動生成 \n private long id;\n \n /** チャットを行ったチャットルーム */\n @ManyToOne // 多対1関連\n private Room room;\n \n /** 発言者 */\n @ManyToOne\n private Account speaker;\n ...
import enterprisegeeks.entity.Chat; import enterprisegeeks.entity.Room; import enterprisegeeks.rest.anotation.WithAuth; import enterprisegeeks.rest.dto.Authed; import enterprisegeeks.rest.dto.ChatList; import enterprisegeeks.rest.dto.NewChat; import enterprisegeeks.service.ChatNotifier; import enterprisegeeks.service.Service; import java.sql.Timestamp; import java.util.List; import javax.ws.rs.Path; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.transaction.Transactional; import javax.validation.Valid; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.glassfish.jersey.server.mvc.Viewable;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest.resource; /** * REST Web Service */ @Path("chatroom") @RequestScoped @Transactional public class ChatroomResource { @Inject private Service service; @Inject private Authed authed; @Inject private ChatNotifier notify; @GET @WithAuth public Viewable init() { return new Viewable("/WEB-INF/jsp/chatroom.jsp", authed.getAccount()); } @GET @Path("rooms") @WithAuth @Produces(MediaType.APPLICATION_JSON) public List<Room> getRooms() { return service.allRooms(); } /** 指定時刻以降のチャット一覧の取得。 */ @GET @Path("chat") @WithAuth @Produces(MediaType.APPLICATION_JSON) public ChatList getChat(@QueryParam("roomId")long roomId, @QueryParam("from")long from) { Room r = new Room(); r.setId(roomId); Timestamp tsFrom = new Timestamp(from);
List<Chat> chatList = service.findChatByRoom(r, tsFrom);
0
cytomine/Cytomine-java-client
src/test/java/client/JobTest.java
[ "public class CytomineException extends Exception {\n\n private static final Logger log = LogManager.getLogger(CytomineException.class);\n\n int httpCode;\n String message = \"\";\n\n public CytomineException(Exception e) {\n super(e);\n this.message = e.getMessage();\n }\n\n public ...
import be.cytomine.client.CytomineException; import be.cytomine.client.collections.Collection; import be.cytomine.client.collections.JobCollection; import be.cytomine.client.models.Job; import be.cytomine.client.models.Project; import be.cytomine.client.models.Software; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals;
package client; /* * Copyright (c) 2009-2020. Authors: see NOTICE file. * * 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. */ public class JobTest { private static final Logger log = LogManager.getLogger(JobTest.class); @BeforeAll static void init() throws CytomineException { Utils.connect(); } @Test void testCreateJob() throws CytomineException { log.info("test create software_parameter"); Software software = Utils.getSoftware();
Project project = Utils.getProject();
4
flutterwireless/ArduinoCodebase
app/src/cc/arduino/packages/uploaders/SerialUploader.java
[ "public abstract class Uploader implements MessageConsumer {\n\n private static final List<String> STRINGS_TO_SUPPRESS;\n private static final List<String> AVRDUDE_PROBLEMS;\n\n static {\n STRINGS_TO_SUPPRESS = Arrays.asList(\"Connecting to programmer:\",\n \"Found programmer: Id = \\\"CATERIN\\\";...
import processing.app.debug.RunnerException; import processing.app.debug.TargetPlatform; import processing.app.helpers.PreferencesMap; import processing.app.helpers.StringReplacer; import java.io.File; import java.util.ArrayList; import java.util.List; import static processing.app.I18n._; import cc.arduino.packages.Uploader; import processing.app.*;
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* BasicUploader - generic command line uploader implementation Part of the Arduino project - http://www.arduino.cc/ Copyright (c) 2004-05 Hernando Barragan Copyright (c) 2012 Cristian Maglie <c.maglie@bug.st> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id$ */ package cc.arduino.packages.uploaders; public class SerialUploader extends Uploader { public boolean uploadUsingPreferences(File sourcePath, String buildPath, String className, boolean usingProgrammer, List<String> warningsAccumulator) throws Exception { // FIXME: Preferences should be reorganized TargetPlatform targetPlatform = Base.getTargetPlatform(); PreferencesMap prefs = Preferences.getMap(); prefs.putAll(Base.getBoardPreferences()); String tool = prefs.getOrExcept("upload.tool"); if (tool.contains(":")) { String[] split = tool.split(":", 2); targetPlatform = Base.getCurrentTargetPlatformFromPackage(split[0]); tool = split[1]; } prefs.putAll(targetPlatform.getTool(tool)); // if no protocol is specified for this board, assume it lacks a // bootloader and upload using the selected programmer. if (usingProgrammer || prefs.get("upload.protocol") == null) { return uploadUsingProgrammer(buildPath, className); } // need to do a little dance for Leonardo and derivatives: // open then close the port at the magic baudrate (usually 1200 bps) first // to signal to the sketch that it should reset into bootloader. after doing // this wait a moment for the bootloader to enumerate. On Windows, also must // deal with the fact that the COM port number changes from bootloader to // sketch. String t = prefs.get("upload.use_1200bps_touch"); boolean doTouch = t != null && t.equals("true"); t = prefs.get("upload.wait_for_upload_port"); boolean waitForUploadPort = (t != null) && t.equals("true"); if (doTouch) { String uploadPort = prefs.getOrExcept("serial.port"); try { // Toggle 1200 bps on selected serial port to force board reset. List<String> before = Serial.list(); if (before.contains(uploadPort)) { if (verbose)
System.out.println(_("Forcing reset using 1200bps open/close on port ") + uploadPort);
4
tokuhirom/jtt
src/test/java/me/geso/jtt/tt/TTParserTest.java
[ "public class Source {\n\tprivate final SourceType type;\n\tprivate final String source;\n\n\tenum SourceType {\n\t\tFROM_FILE, FROM_STRING\n\t}\n\n\tpublic Source(SourceType type, String source) {\n\t\tthis.type = type;\n\t\tthis.source = source;\n\t}\n\n\t/**\n\t * Create new source object from string.\n\t * \n\t...
import static org.junit.Assert.assertEquals; import java.util.List; import me.geso.jtt.Source; import me.geso.jtt.Syntax; import me.geso.jtt.exception.ParserError; import me.geso.jtt.lexer.Token; import me.geso.jtt.parser.Node; import me.geso.jtt.parser.NodeType; import me.geso.jtt.tt.TTSyntax; import org.junit.Test;
public void testAndAnd() throws ParserError { Node node = parse("[% true && false %]"); assertEquals( "(template (expression (andand (true) (false))))", node.toString()); } // left AND @Test public void testLooseAnd() throws ParserError { assertEquals( "(template (expression (andand (true) (false))))", parse("[% true AND false %]").toString()); assertEquals( "(template (expression (andand (andand (true) (false)) (true))))", parse("[% true AND false AND true %]").toString()); } @Test public void testOrOr() throws ParserError { Node node = parse("[% true || false %]"); assertEquals( "(template (expression (oror (true) (false))))", node.toString()); } @Test public void testLooseOr() throws ParserError { Node node = parse("[% true OR false %]"); assertEquals( "(template (expression (oror (true) (false))))", node.toString()); } @Test public void testNE() throws ParserError { Node node = parse("[% true != false %]"); assertEquals( "(template (expression (ne (true) (false))))", node.toString()); } @Test public void testDollarVar() throws ParserError { Node node = parse("[% list.$var %]"); assertEquals( "(template (expression (attribute (ident list) (dollarvar var))))", node.toString()); } @Test public void testArrayIndex() throws ParserError { assertEquals( "(template (expression (attribute (ident list) (dollarvar var))))", parse("[% list[$var] %]").toString()); assertEquals( "(template (expression (attribute (attribute (ident list) (dollarvar var)) (ident boo))))", parse("[% list[$var][boo] %]").toString()); assertEquals( "(template (expression (attribute (ident list) (ident var))))", parse("[% list[var] %]").toString()); } @Test public void testLoop() throws ParserError { assertEquals( "(template (expression (loop_index)))", parse("[% loop %]").toString()); } @Test public void testLoopIndex() throws ParserError { assertEquals( "(template (expression (loop_index)))", parse("[% loop %]").toString()); } @Test public void testLoopCount() throws ParserError { assertEquals( "(template (expression (loop_count)))", parse("[% loop.count %]").toString()); } @Test public void testLoopHasNext() throws ParserError { assertEquals( "(template (expression (loop_has_next)))", parse("[% loop.has_next %]").toString()); } @Test public void testFile() throws ParserError { assertEquals( "(template (expression (string -)))", parse("[% __FILE__ %]").toString()); } @Test public void testLine() throws ParserError { assertEquals( "(template (expression (integer 1)) (raw_string \n) (expression (integer 2)))", parse("[% __LINE__ %]\n[% __LINE__ %]").toString()); } @Test public void testInclude2() throws ParserError { assertEquals( "(template (include (string hoge.tt) (ident foo) (ident bar)))", parse("[% INCLUDE \"hoge.tt\" WITH foo=bar %]").toString()); } @Test public void testWrapper() throws ParserError { assertEquals( "(template (wrapper (string foo.tt) (template (raw_string ohoho))))", parse("[% WRAPPER \"foo.tt\" %]ohoho[% END %]").toString()); } private Node parse(String sourceString) throws ParserError {
Syntax syntax = new TTSyntax("[%", "%]");
6
52North/SensorPlanningService
52n-sps-api/src/test/java/org/n52/sps/util/nodb/InMemorySensorConfigurationRepositoryTest.java
[ "public abstract class SensorPlugin implements ResultAccessAvailabilityDescriptor, ResultAccessServiceReference {\r\n\r\n protected SensorConfiguration configuration;\r\n\r\n protected SensorTaskService sensorTaskService;\r\n \r\n protected SensorPlugin() {\r\n // allow default constructor for de...
import org.junit.Test; import org.n52.sps.sensor.SensorPlugin; import org.n52.sps.sensor.SimpleSensorPluginTestInstance; import org.n52.sps.sensor.model.SensorConfiguration; import org.n52.sps.service.InternalServiceException; import org.n52.sps.store.SensorConfigurationRepository; import org.n52.sps.util.nodb.InMemorySensorConfigurationRepository; import static org.junit.Assert.*; import org.junit.Before;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package org.n52.sps.util.nodb; public class InMemorySensorConfigurationRepositoryTest { private SensorConfigurationRepository repository; @Before public void setUp() {
repository = new InMemorySensorConfigurationRepository();
5
Zhuinden/simple-stack
simple-stack/src/test/java/com/zhuinden/simplestack/ScopeLookupModeTest.java
[ "public interface Action {\n public void doSomething();\n}", "public interface HasParentServices\n extends ScopeKey.Child {\n void bindServices(ServiceBinder serviceBinder);\n}", "public interface HasServices\n extends ScopeKey {\n void bindServices(ServiceBinder serviceBinder);\n}", "p...
import static org.assertj.core.api.Assertions.assertThat; import android.os.Parcel; import com.zhuinden.simplestack.helpers.Action; import com.zhuinden.simplestack.helpers.HasParentServices; import com.zhuinden.simplestack.helpers.HasServices; import com.zhuinden.simplestack.helpers.ServiceProvider; import com.zhuinden.simplestack.helpers.TestKey; import org.junit.Test; import java.util.List; import javax.annotation.Nonnull; import static com.zhuinden.simplestack.helpers.AssertionHelper.assertThrows;
@Nonnull @Override public String getScopeTag() { return name; } @Nonnull @Override public List<String> getParentScopes() { return History.of("parent1"); } } class Key2 extends TestKey implements HasServices, HasParentServices { Key2(String name) { super(name); } protected Key2(Parcel in) { super(in); } @Override public void bindServices(ServiceBinder serviceBinder) { if("parent2".equals(serviceBinder.getScopeTag())) { serviceBinder.addService("parentService2", parentService2); } else if(name.equals(serviceBinder.getScopeTag())) { serviceBinder.addService("service2", service2); } } @Nonnull @Override public String getScopeTag() { return name; } @Nonnull @Override public List<String> getParentScopes() { return History.of("parent2"); } } backstack.setup(History.of(new Key1("beep"), new Key2("boop"))); assertThat(backstack.canFindFromScope("boop", "service")).isFalse(); backstack.setStateChanger(new StateChanger() { @Override public void handleStateChange(@Nonnull StateChange stateChange, @Nonnull Callback completionCallback) { completionCallback.stateChangeComplete(); } }); // default (ALL) assertThat(backstack.canFindFromScope("beep", "service1")).isTrue(); assertThat(backstack.canFindFromScope("beep", "service2")).isFalse(); assertThat(backstack.canFindFromScope("beep", "parentService1")).isTrue(); assertThat(backstack.canFindFromScope("beep", "parentService2")).isFalse(); assertThat(backstack.canFindFromScope("parent1", "service1")).isFalse(); assertThat(backstack.canFindFromScope("parent1", "service2")).isFalse(); assertThat(backstack.canFindFromScope("parent1", "parentService1")).isTrue(); assertThat(backstack.canFindFromScope("parent1", "parentService2")).isFalse(); assertThat(backstack.canFindFromScope("boop", "service1")).isTrue(); assertThat(backstack.canFindFromScope("boop", "service2")).isTrue(); assertThat(backstack.canFindFromScope("boop", "parentService1")).isTrue(); assertThat(backstack.canFindFromScope("boop", "parentService2")).isTrue(); assertThat(backstack.canFindFromScope("parent2", "service1")).isTrue(); assertThat(backstack.canFindFromScope("parent2", "service2")).isFalse(); assertThat(backstack.canFindFromScope("parent2", "parentService1")).isTrue(); assertThat(backstack.canFindFromScope("parent2", "parentService2")).isTrue(); // ALL specified assertThat(backstack.canFindFromScope("beep", "service1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("beep", "service2", ScopeLookupMode.ALL)).isFalse(); assertThat(backstack.canFindFromScope("beep", "parentService1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("beep", "parentService2", ScopeLookupMode.ALL)).isFalse(); assertThat(backstack.canFindFromScope("parent1", "service1", ScopeLookupMode.ALL)).isFalse(); assertThat(backstack.canFindFromScope("parent1", "service2", ScopeLookupMode.ALL)).isFalse(); assertThat(backstack.canFindFromScope("parent1", "parentService1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("parent1", "parentService2", ScopeLookupMode.ALL)).isFalse(); assertThat(backstack.canFindFromScope("boop", "service1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("boop", "service2", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("boop", "parentService1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("boop", "parentService2", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("parent2", "service1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("parent2", "service2", ScopeLookupMode.ALL)).isFalse(); assertThat(backstack.canFindFromScope("parent2", "parentService1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("parent2", "parentService2", ScopeLookupMode.ALL)).isTrue(); // EXPLICIT specified assertThat(backstack.canFindFromScope("beep", "service1", ScopeLookupMode.EXPLICIT)).isTrue(); assertThat(backstack.canFindFromScope("beep", "service2", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("beep", "parentService1", ScopeLookupMode.EXPLICIT)).isTrue(); assertThat(backstack.canFindFromScope("beep", "parentService2", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("parent1", "service1", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("parent1", "service2", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("parent1", "parentService1", ScopeLookupMode.EXPLICIT)).isTrue(); assertThat(backstack.canFindFromScope("parent1", "parentService2", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("boop", "service1", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("boop", "service2", ScopeLookupMode.EXPLICIT)).isTrue(); assertThat(backstack.canFindFromScope("boop", "parentService1", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("boop", "parentService2", ScopeLookupMode.EXPLICIT)).isTrue(); assertThat(backstack.canFindFromScope("parent2", "service1", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("parent2", "service2", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("parent2", "parentService1", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("parent2", "parentService2", ScopeLookupMode.EXPLICIT)).isTrue(); // default (ALL)
assertThrows(new Action() {
5
idega/com.idega.block.category
src/java/com/idega/block/category/business/FolderBlockBusinessBean.java
[ "public interface ICInformationCategory extends TreeableEntity,com.idega.block.category.data.InformationCategory\n{\n public void addCategoryToInstance(int p0)throws java.sql.SQLException;\n public int getChildCount();\n public java.util.Iterator getChildrenIterator();\n public java.util.Iterator getChildrenIterato...
import java.rmi.RemoteException; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Vector; import javax.ejb.CreateException; import javax.ejb.FinderException; import com.idega.block.category.data.ICInformationCategory; import com.idega.block.category.data.ICInformationCategoryHome; import com.idega.block.category.data.ICInformationCategoryTranslation; import com.idega.block.category.data.ICInformationCategoryTranslationHome; import com.idega.block.category.data.ICInformationFolder; import com.idega.block.category.data.InformationCategory; import com.idega.business.IBOLookup; import com.idega.business.IBOLookupException; import com.idega.business.IBOServiceBean; import com.idega.core.component.data.ICObjectInstance; import com.idega.core.component.data.ICObjectInstanceHome; import com.idega.core.localisation.business.ICLocaleBusiness; import com.idega.data.EntityFinder; import com.idega.data.GenericEntity; import com.idega.data.IDOException; import com.idega.data.IDOLookup; import com.idega.data.IDOLookupException; import com.idega.data.IDORemoveRelationshipException; import com.idega.data.IDOStoreException; import com.idega.idegaweb.IWApplicationContext; import com.idega.presentation.IWContext; import com.idega.util.IWTimestamp;
package com.idega.block.category.business; /** * <p>Title: idegaWeb</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2002</p> * <p>Company: idega</p> * @author <a href="gummi@idega.is">Gudmundur Agust Saemundsson</a> * @version 1.0 */ public class FolderBlockBusinessBean extends IBOServiceBean implements FolderBlockBusiness { public FolderBlockBusinessBean() { } public static FolderBlockBusinessBean getInstance(IWApplicationContext iwac) throws IBOLookupException { return (FolderBlockBusinessBean) IBOLookup.getServiceInstance(iwac,FolderBlockBusiness.class); }
public ICInformationFolder getInstanceWorkeFolder(int icObjectInstanceId, int icObjectId, int localeId, boolean autocreate) {
4
ghelmling/beeno
src/java/meetup/beeno/Criteria.java
[ "public class ColumnMatchFilter implements Filter {\n\n\t/** Comparison operators. */\n\tpublic enum CompareOp {\n\t\t/** less than */\n\t\tLESS,\n\t\t/** less than or equal to */\n\t\tLESS_OR_EQUAL,\n\t\t/** equals */\n\t\tEQUAL,\n\t\t/** not equal */\n\t\tNOT_EQUAL,\n\t\t/** greater than or equal to */\n\t\tGREAT...
import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.List; import meetup.beeno.filter.ColumnMatchFilter; import meetup.beeno.filter.WhileMatchFilter; import meetup.beeno.mapping.EntityInfo; import meetup.beeno.mapping.FieldMapping; import meetup.beeno.mapping.MappingException; import meetup.beeno.util.IOUtil; import meetup.beeno.util.PBUtil; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.FilterList; import org.apache.hadoop.hbase.util.Bytes; import org.apache.log4j.Logger;
package meetup.beeno; /** * Utility for building up criteria for HBaseEntity queries. * * @author garyh * */ public class Criteria implements Externalizable { private static Logger log = Logger.getLogger(Criteria.class); private List<Expression> expressions = new ArrayList<Expression>(); public Criteria() { } public Criteria add(Expression expr) { this.expressions.add(expr); return this; } public boolean isEmpty() { return this.expressions.isEmpty(); } public List<Expression> getExpressions() { return this.expressions; } @Override public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { this.expressions = (in.readBoolean() ? null : (List<Expression>)in.readObject()); } @Override public void writeExternal( ObjectOutput out ) throws IOException { IOUtil.writeNullable(out, this.expressions); } /* ************* Expressions and builder methods ************** */ public static Expression require(Expression expr) { return new RequireExpression(expr); } public static Expression and(Expression... expr) { CompoundExpression wrapper = new CompoundExpression(true); for (Expression e : expr) { wrapper.add(e); } return wrapper; } public static Expression or(Expression... expr) { CompoundExpression wrapper = new CompoundExpression(false); for (Expression e : expr) { if (log.isDebugEnabled()) log.debug(String.format("Adding OR expression %s", expr.toString())); wrapper.add(e); } return wrapper; } public static Expression or(List<Expression> expr) { CompoundExpression wrapper = new CompoundExpression(false); for (Expression e : expr) { if (log.isDebugEnabled()) log.debug(String.format("Adding OR expression %s", expr)); wrapper.add(e); } return wrapper; } public static Expression eq(String prop, Object val) { return new PropertyComparison(prop, val, ColumnMatchFilter.CompareOp.EQUAL); } public static Expression ne(String prop, Object val) { return new PropertyComparison(prop, val, ColumnMatchFilter.CompareOp.NOT_EQUAL); } public static abstract class Expression implements Externalizable { public Expression() { } public abstract Filter getFilter(EntityInfo info) throws HBaseException; public String toString() { return "["+this.getClass().getSimpleName()+"]"; } } public static abstract class PropertyExpression extends Expression implements Externalizable { protected String property; protected Object value; public PropertyExpression() { // for Externalizable } public PropertyExpression(String prop, Object val) { this.property = prop; this.value = val; } public String getProperty() { return this.property; } public Object getValue() { return this.value; } @Override public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { this.property = IOUtil.readString(in); this.value = IOUtil.readWithType(in); } @Override public void writeExternal( ObjectOutput out ) throws IOException { IOUtil.writeNullable(out, this.property); IOUtil.writeNullableWithType(out, this.value); } public String toString() { return "["+this.getClass().getSimpleName()+": property="+this.property+", value="+this.value+"]"; } } public static class PropertyComparison extends PropertyExpression { private ColumnMatchFilter.CompareOp op = null; public PropertyComparison() { // for Externalizable } public PropertyComparison(String prop, Object val, ColumnMatchFilter.CompareOp op) { super(prop, val); this.op = op; } public Filter getFilter(EntityInfo entityInfo) throws HBaseException { FieldMapping mapping = entityInfo.getPropertyMapping(this.property); if (mapping == null) {
throw new MappingException( entityInfo.getEntityClass(),
4
BlackCraze/GameResourceBot
src/main/java/de/blackcraze/grb/commands/FileProcessor.java
[ "public static Device getMateDevice(Message message) {\r\n Mate mate = getMateDao().getOrCreateMate(message, getDefaultLocale());\r\n return mate.getDevice();\r\n}\r", "public static Locale getResponseLocale(Message message) {\r\n Locale channelLocale = getDefaultLocale();\r\n Mate mate = getMateDao()...
import static de.blackcraze.grb.util.CommandUtils.getMateDevice; import static de.blackcraze.grb.util.CommandUtils.getResponseLocale; import static de.blackcraze.grb.util.PrintUtils.prettyPrint; import static org.bytedeco.javacpp.Pointer.deallocateReferences; import java.io.BufferedInputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Locale; import java.util.Map; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import de.blackcraze.grb.commands.concrete.Update; import de.blackcraze.grb.core.BotConfig; import de.blackcraze.grb.core.Speaker; import de.blackcraze.grb.i18n.Resource; import de.blackcraze.grb.model.Device; import de.blackcraze.grb.ocr.OCR; import net.dv8tion.jda.api.entities.ChannelType; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Message.Attachment;
package de.blackcraze.grb.commands; public class FileProcessor { public static void ocrImages(Message message) { Locale locale = getResponseLocale(message); Device device = getMateDevice(message); for (Attachment att : message.getAttachments()) { if (att.isImage()) { InputStream stream = null; try { // Check if the filename ends with .png (only working image format). if (!FilenameUtils.getExtension(att.getFileName()).equalsIgnoreCase("png")) {
Speaker.err(message, Resource.getError("ONLY_PNG_IMAGES", locale));
6
zetbaitsu/CodePolitan
app/src/main/java/id/zelory/codepolitan/ui/fragment/AbstractHomeFragment.java
[ "public abstract class BenihRecyclerAdapter<Data, Holder extends BenihItemViewHolder> extends\n RecyclerView.Adapter<Holder>\n{\n protected Context context;\n protected List<Data> data;\n protected OnItemClickListener itemClickListener;\n protected OnLongItemClickListener longItemClickListener;\n...
import android.os.Bundle; import android.os.Handler; import android.support.design.widget.Snackbar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.SearchView; import android.view.Menu; import android.view.View; import java.util.List; import butterknife.Bind; import id.zelory.benih.adapter.BenihRecyclerAdapter; import id.zelory.benih.fragment.BenihFragment; import id.zelory.benih.util.BenihBus; import id.zelory.benih.util.KeyboardUtil; import id.zelory.benih.view.BenihRecyclerView; import id.zelory.codepolitan.R; import id.zelory.codepolitan.controller.ArticleController; import id.zelory.codepolitan.controller.event.ErrorEvent; import id.zelory.codepolitan.data.model.Article; import id.zelory.codepolitan.data.LocalDataManager; import timber.log.Timber;
/* * Copyright (c) 2015 Zelory. * * 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 id.zelory.codepolitan.ui.fragment; /** * Created on : August 3, 2015 * Author : zetbaitsu * Name : Zetra * Email : zetra@mail.ugm.ac.id * GitHub : https://github.com/zetbaitsu * LinkedIn : https://id.linkedin.com/in/zetbaitsu */ public abstract class AbstractHomeFragment<Adapter extends BenihRecyclerAdapter> extends BenihFragment implements ArticleController.Presenter, SwipeRefreshLayout.OnRefreshListener, SearchView.OnQueryTextListener { protected ArticleController articleController; @Bind(R.id.swipe_layout) SwipeRefreshLayout swipeRefreshLayout; @Bind(R.id.recycler_view) BenihRecyclerView recyclerView; protected SearchView searchView; protected Adapter adapter; protected int currentPage = 1; protected boolean searching = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override protected void onViewReady(Bundle bundle) { BenihBus.pluck() .receive() .subscribe(o -> { if (o instanceof Menu) { onMenuCreated((Menu) o); } }, throwable -> Timber.e(throwable.getMessage())); currentPage = bundle != null ? bundle.getInt("currentPage") : 1; setUpSwipeLayout(); setUpAdapter(bundle); setUpRecyclerView(); setupController(bundle); } protected abstract void setUpRecyclerView(); protected abstract Adapter createAdapter(); protected void setUpAdapter(Bundle bundle) { if (adapter == null) { adapter = createAdapter(); adapter.setOnItemClickListener(this::onItemClick); recyclerView.setAdapter(adapter); } } protected abstract void onItemClick(View view, int position); protected void setUpSwipeLayout() { swipeRefreshLayout.setColorSchemeResources(R.color.primary, R.color.accent); swipeRefreshLayout.setOnRefreshListener(this); } private void onMenuCreated(Menu menu) { searchView = (SearchView) menu.getItem(0).getActionView(); searchView.setOnQueryTextListener(this); } protected void setupController(Bundle bundle) { if (articleController == null) { articleController = new ArticleController(this); } if (bundle != null) { articleController.loadState(bundle); } else { new Handler().postDelayed(this::onRefresh, 800); } } @Override public void onRefresh() { currentPage = 1; adapter.clear(); setUpRecyclerView(); } @Override public void showArticle(Article article) { } @Override public void showArticles(List<Article> articles) { if (!searching && adapter != null) { adapter.add(articles); } } @Override public void showFilteredArticles(List<Article> articles) { adapter.clear(); adapter.add(articles); } @Override public void showLoading() { if (!searching) { swipeRefreshLayout.setRefreshing(true); } } @Override public void dismissLoading() { swipeRefreshLayout.setRefreshing(false); } @Override public void showError(Throwable throwable) { switch (throwable.getMessage()) { case ErrorEvent.LOAD_STATE_LIST_ARTICLE: onRefresh(); break; case ErrorEvent.LOAD_LIST_ARTICLE_BY_PAGE: Snackbar.make(recyclerView, R.string.error_message, Snackbar.LENGTH_LONG) .setAction(R.string.retry, v -> {
if (LocalDataManager.isFollowAll())
6
RepreZen/KaiZen-OpenAPI-Editor
com.reprezen.swagedit.core/src/com/reprezen/swagedit/core/hyperlinks/ReferenceHyperlinkDetector.java
[ "public abstract class JsonDocument extends Document {\n\n private final ObjectMapper mapper;\n private CompositeSchema schema;\n\n public enum Version {\n SWAGGER, OPENAPI;\n }\n\n private final Yaml yaml = new Yaml();\n\n private AtomicReference<Result<JsonNode>> jsonContent = new AtomicR...
import java.net.URI; import org.eclipse.core.resources.IFile; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.hyperlink.IHyperlink; import org.eclipse.ui.part.FileEditorInput; import com.fasterxml.jackson.core.JsonPointer; import com.reprezen.swagedit.core.editor.JsonDocument; import com.reprezen.swagedit.core.json.references.JsonReference; import com.reprezen.swagedit.core.json.references.JsonReferenceFactory; import com.reprezen.swagedit.core.model.AbstractNode; import com.reprezen.swagedit.core.utils.DocumentUtils;
/******************************************************************************* * Copyright (c) 2016 ModelSolv, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * ModelSolv, Inc. - initial API and implementation and/or initial documentation *******************************************************************************/ package com.reprezen.swagedit.core.hyperlinks; public abstract class ReferenceHyperlinkDetector extends AbstractJsonHyperlinkDetector { protected final JsonReferenceFactory factory = new JsonReferenceFactory(); protected abstract JsonFileHyperlink createFileHyperlink(IRegion linkRegion, String label, IFile file, JsonPointer pointer); @Override protected abstract boolean canDetect(JsonPointer pointer); @Override protected IHyperlink[] doDetect(JsonDocument doc, ITextViewer viewer, HyperlinkInfo info, JsonPointer pointer) { URI baseURI = getBaseURI();
AbstractNode node = doc.getModel().find(pointer);
3
Divendo/math-dragon
mathdragon/src/main/java/org/teaminfty/math_dragon/view/fragments/FragmentKeyboard.java
[ "public class MathSymbolEditor extends View\n{\n /** An enum that represents the symbol we're currently editing */\n public enum EditingSymbol\n {\n FACTOR((byte) 0), PI((byte) 1), E((byte) 2), I((byte) 3), VAR((byte) 4);\n \n private byte b;\n \n private EditingSymbol(by...
import java.util.ArrayList; import org.teaminfty.math_dragon.R; import org.teaminfty.math_dragon.view.MathSymbolEditor; import org.teaminfty.math_dragon.view.ShowcaseViewDialog; import org.teaminfty.math_dragon.view.ShowcaseViewDialogs; import org.teaminfty.math_dragon.view.MathSymbolEditor.EditingSymbol; import org.teaminfty.math_dragon.view.math.Expression; import org.teaminfty.math_dragon.view.math.Symbol; import android.app.Activity; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.res.Configuration; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.HorizontalScrollView; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ToggleButton;
package org.teaminfty.math_dragon.view.fragments; public class FragmentKeyboard extends DialogFragment implements MathSymbolEditor.OnStateChangeListener, MathSymbolEditor.OnScrollToListener, Tutorial { /** The {@link MathSymbolEditor} in this fragment */ private MathSymbolEditor mathSymbolEditor = null; /** A {@link Expression} we saved for later to set to {@link FragmentKeyboard#mathSymbolEditor mathSymbolEditor} */
private Expression exprForLater = null;
4
Ahmed-Abdelmeged/ADAS
app/src/main/java/com/example/mego/adas/accidents/ui/AccidentFragment.java
[ "public class AccidentAdapterRecycler extends RecyclerView.Adapter<AccidentAdapterRecycler.AccidentViewHolder> {\n\n /**\n * An on-click handler that we've defined to make it easy for an Activity to interface with\n * our RecyclerView\n */\n final private AccidentClickCallBacks mOnClickListener;\n...
import android.arch.lifecycle.LifecycleFragment; import android.arch.lifecycle.ViewModelProviders; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.example.mego.adas.R; import com.example.mego.adas.accidents.adapter.AccidentAdapterRecycler; import com.example.mego.adas.accidents.adapter.AccidentClickCallBacks; import com.example.mego.adas.accidents.viewmodel.AccidentViewModel; import com.example.mego.adas.auth.AuthenticationUtilities; import com.example.mego.adas.auth.User; import com.example.mego.adas.accidents.db.entity.Accident; import com.example.mego.adas.utils.Constants; import com.example.mego.adas.utils.NetworkUtil; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.ArrayList; import java.util.List;
/* * Copyright (c) 2017 Ahmed-Abdelmeged * * github: https://github.com/Ahmed-Abdelmeged * email: ahmed.abdelmeged.vm@gamil.com * Facebook: https://www.facebook.com/ven.rto * Twitter: https://twitter.com/A_K_Abd_Elmeged * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.mego.adas.accidents.ui; /** * A simple {@link Fragment} subclass. * <p> * to show list of accidents */ public class AccidentFragment extends LifecycleFragment implements AccidentClickCallBacks { /** * UI Elements */ private RecyclerView accidentsRecycler; private ProgressBar loadingBar; private TextView emptyText; /** * adapter for accidents list */ private AccidentAdapterRecycler accidentAdapterRecycler; private AccidentFragment accidentFragment; private AccidentViewModel viewModel; private List<Accident> currentAccdeints = new ArrayList<>(); /** * Firebase objects * to specific part of the database */ private FirebaseDatabase mFirebaseDatabase; private DatabaseReference accidentsDatabaseReference; private ChildEventListener accidentsEventListener; public AccidentFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_accident, container, false); initializeScreen(rootView); accidentFragment = (AccidentFragment) getFragmentManager().findFragmentById(R.id.fragment_container); accidentAdapterRecycler = new AccidentAdapterRecycler(this); viewModel = ViewModelProviders.of(this).get(AccidentViewModel.class); LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false); accidentsRecycler.setLayoutManager(layoutManager); accidentsRecycler.setHasFixedSize(true); accidentsRecycler.setAdapter(accidentAdapterRecycler); //set up the firebase mFirebaseDatabase = FirebaseDatabase.getInstance(); //get the current user uid User currentUser = AuthenticationUtilities.getCurrentUser(getContext()); String uid = currentUser.getUserUid(); //get the references for the childes
accidentsDatabaseReference = mFirebaseDatabase.getReference().child(Constants.FIREBASE_USERS)
6
jpaoletti/jPOS-Presentation-Manager
modules/pm_struts/src/org/jpos/ee/pm/struts/actions/ActionSupport.java
[ "public class PMMessage {\n private String key;\n private String message;\n private String arg0;\n private String arg1;\n private String arg2;\n private String arg3;\n \n /**\n * Constructor with a key\n * \n * @param key The key\n */\n public PMMessage(String key){\n ...
import org.jpos.ee.pm.core.PMUnauthorizedException; import org.jpos.ee.pm.core.PresentationManager; import org.jpos.ee.pm.struts.PMEntitySupport; import org.jpos.ee.pm.struts.PMForwardException; import org.jpos.ee.pm.struts.PMStrutsContext; import org.jpos.ee.pm.struts.PMStrutsService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.jpos.ee.Constants; import org.jpos.ee.pm.core.PMException; import org.jpos.ee.pm.core.PMMessage;
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2010 Alejandro P. Revilla * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.ee.pm.struts.actions; /** * A super class for all actions with some helpers and generic stuff * * @author jpaoletti */ public abstract class ActionSupport extends Action implements Constants { public static final String CONTINUE = "continue"; public static final String SUCCESS = "success"; public static final String FAILURE = "failure"; public static final String USER = "user"; public static final String DENIED = "denied"; public static final String STRUTS_LOGIN = "login"; protected abstract void doExecute(PMStrutsContext ctx) throws PMException; /**Forces execute to check if any user is logged in*/ protected boolean checkUser() { return true; } protected boolean prepare(PMStrutsContext ctx) throws PMException { if(checkUser() && ctx.getPMSession()==null){ //Force logout final PMEntitySupport es = PMEntitySupport.getInstance(); ctx.getSession().invalidate(); es.setContext_path(ctx.getRequest().getContextPath()); ctx.getSession().setAttribute(ENTITY_SUPPORT, es); ctx.getRequest().setAttribute("reload", 1); throw new PMUnauthorizedException(); } return true; } @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PMStrutsContext ctx = (PMStrutsContext) request.getAttribute(PM_CONTEXT); ctx.setMapping(mapping); ctx.setForm(form); try { boolean step = prepare(ctx); if (step) { excecute(ctx); } return mapping.findForward(SUCCESS); } catch (PMForwardException e) { return mapping.findForward(e.getKey()); } catch (PMUnauthorizedException e) { return mapping.findForward(STRUTS_LOGIN); } catch (PMException e) { ctx.getPresentationManager().debug(this, e); if (e.getKey() != null) { ctx.getErrors().add(new PMMessage(ActionMessages.GLOBAL_MESSAGE, e.getKey())); } ActionErrors errors = new ActionErrors(); for (PMMessage msg : ctx.getErrors()) { errors.add(msg.getKey(), new ActionMessage(msg.getMessage(), msg.getArg0(), msg.getArg1(), msg.getArg2(), msg.getArg3())); } saveErrors(request, errors); return mapping.findForward(FAILURE); } } protected void excecute(PMStrutsContext ctx) throws PMException { doExecute(ctx); } protected PMStrutsService getPMService() throws PMException { try {
return (PMStrutsService) PresentationManager.pm.getService();
2
yunnet/kafkaEagle
src/main/java/org/smartloli/kafka/eagle/core/factory/ZkServiceImpl.java
[ "public class AlarmDomain {\n\n\tprivate String group = \"\";\n\tprivate String topics = \"\";\n\tprivate long lag = 0L;\n\tprivate String owners = \"\";\n\tprivate String modifyDate = \"\";\n\n\tpublic String getGroup() {\n\t\treturn group;\n\t}\n\n\tpublic void setGroup(String group) {\n\t\tthis.group = group;\n\...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; import org.I0Itec.zkclient.ZkClient; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.smartloli.kafka.eagle.common.domain.AlarmDomain; import org.smartloli.kafka.eagle.common.domain.OffsetsLiteDomain; import org.smartloli.kafka.eagle.common.util.CalendarUtils; import org.smartloli.kafka.eagle.common.util.SystemConfigUtils; import org.smartloli.kafka.eagle.common.util.ZKPoolUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import kafka.utils.ZkUtils; import scala.Option; import scala.Tuple2; import scala.collection.JavaConversions; import scala.collection.Seq;
/** Zookeeper ls command. */ public String ls(String clusterAlias, String cmd) { String target = ""; ZkClient zkc = zkPool.getZkClient(clusterAlias); boolean status = ZkUtils.apply(zkc, false).pathExists(cmd); if (status) { target = zkc.getChildren(cmd).toString(); } if (zkc != null) { zkPool.release(clusterAlias, zkc); zkc = null; } return target; } /** * Remove the metadata information in the Ke root directory in zookeeper, * with group and topic as the only sign. * * @param group * Consumer group. * @param topic * Consumer topic. * @param theme * Consumer theme. */ public void remove(String clusterAlias, String group, String topic, String theme) { if (zkc == null) { zkc = zkPool.getZkClient(clusterAlias); } String path = theme + "/" + group + "/" + topic; if (ZkUtils.apply(zkc, false).pathExists(KE_ROOT_PATH + "/" + path)) { ZkUtils.apply(zkc, false).deletePath(KE_ROOT_PATH + "/" + path); } if (zkc != null) { zkPool.release(clusterAlias, zkc); zkc = null; } } /** * Get zookeeper health status. * * @param host * Zookeeper host * @param port * Zookeeper port * @return String. */ public String status(String host, String port) { String target = ""; Socket sock = null; try { String tmp = ""; if (port.contains("/")) { tmp = port.split("/")[0]; } else { tmp = port; } sock = new Socket(host, Integer.parseInt(tmp)); } catch (Exception e) { LOG.error("Socket[" + host + ":" + port + "] connect refused"); return "death"; } BufferedReader reader = null; try { OutputStream outstream = sock.getOutputStream(); outstream.write("stat".getBytes()); outstream.flush(); sock.shutdownOutput(); reader = new BufferedReader(new InputStreamReader(sock.getInputStream())); String line; while ((line = reader.readLine()) != null) { if (line.indexOf("Mode: ") != -1) { target = line.replaceAll("Mode: ", "").trim(); } } } catch (Exception ex) { LOG.error("Read ZK buffer has error,msg is " + ex.getMessage()); return "death"; } finally { try { sock.close(); if (reader != null) { reader.close(); } } catch (Exception ex) { LOG.error("Close read has error,msg is " + ex.getMessage()); } } return target; } /** * Update metadata information in ke root path in zookeeper. * * @param data * Update datasets. * @param path * Update datasets path. */ private void update(String clusterAlias, String data, String path) { if (zkc == null) { zkc = zkPool.getZkClient(clusterAlias); } if (!ZkUtils.apply(zkc, false).pathExists(KE_ROOT_PATH + "/" + path)) { ZkUtils.apply(zkc, false).createPersistentPath(KE_ROOT_PATH + "/" + path, "", ZkUtils.apply(zkc, false).DefaultAcls()); } if (ZkUtils.apply(zkc, false).pathExists(KE_ROOT_PATH + "/" + path)) { ZkUtils.apply(zkc, false).updatePersistentPath(KE_ROOT_PATH + "/" + path, data, ZkUtils.apply(zkc, false).DefaultAcls()); } if (zkc != null) { zkPool.release(clusterAlias, zkc); zkc = null; } } /** Get zookeeper cluster information. */ public String zkCluster(String clusterAlias) {
String[] zks = SystemConfigUtils.getPropertyArray(clusterAlias + ".zk.list", ",");
3
zznate/intravert-ug
src/main/java/io/teknek/intravert/service/DefaultRequestProcessor.java
[ "public interface Action {\n void doAction(Operation operation, Response response, RequestContext request, ApplicationContext application);\n}", "public class ActionFactory {\n \n public static final String CREATE_SESSION = \"createsession\";\n public static final String LOAD_SESSION = \"loadsession\";\n pub...
import io.teknek.intravert.action.Action; import io.teknek.intravert.action.ActionFactory; import io.teknek.intravert.model.Operation; import io.teknek.intravert.model.Request; import io.teknek.intravert.model.Response;
package io.teknek.intravert.service; public class DefaultRequestProcessor implements RequestProcessor { private ActionFactory actionFatory = new ActionFactory(); @Override public void process(Request request, Response response, RequestContext requestContext, ApplicationContext application) { for (int i = 0; i < request.getOperations().size(); i++) { Operation operation = null; try { operation = request.getOperations().get(i);
Action action = actionFatory.findAction(operation.getType());
0
caseydavenport/biermacht
src/com/biermacht/brews/database/DatabaseAPI.java
[ "public class ItemNotFoundException extends Exception {\n public ItemNotFoundException() {\n }\n\n //Constructor that accepts a message\n public ItemNotFoundException(String message) {\n super(message);\n }\n}", "public abstract class Ingredient implements Parcelable {\n\n // Beer XML 1.0 Required Fields...
import android.content.Context; import android.util.Log; import com.biermacht.brews.exceptions.ItemNotFoundException; import com.biermacht.brews.ingredient.Ingredient; import com.biermacht.brews.recipe.BeerStyle; import com.biermacht.brews.recipe.MashProfile; import com.biermacht.brews.recipe.MashStep; import com.biermacht.brews.recipe.Recipe; import com.biermacht.brews.utils.Constants; import java.util.ArrayList;
package com.biermacht.brews.database; public class DatabaseAPI { private Context context; private DatabaseInterface databaseInterface; public DatabaseAPI(Context c) { this.context = c; this.databaseInterface = new DatabaseInterface(this.context); this.databaseInterface.open(); } // Get all recipes in database. public ArrayList<Recipe> getRecipeList() { ArrayList<Recipe> list = this.databaseInterface.getRecipeList(); for (Recipe r : list) { r.update(); } return list; } // Create recipe with the given name public Recipe createRecipeWithName(String name) { Recipe r = new Recipe(name); long id = this.databaseInterface.addRecipeToDatabase(r); r = this.databaseInterface.getRecipeWithId(id); return r; } // Creates recipe from an existing one. public Recipe createRecipeFromExisting(Recipe r) { long id = this.databaseInterface.addRecipeToDatabase(r); r = this.databaseInterface.getRecipeWithId(id); return r; } // Updates existing recipe public boolean updateRecipe(Recipe r) { r.update(); return this.databaseInterface.updateExistingRecipe(r); } // Updates existing ingredient
public boolean updateIngredient(Ingredient i, long dbid) {
1
OlliV/angr
workspace/Angr/src/fi/hbp/angr/models/actors/Grenade.java
[ "public class AssetContainer {\n /**\n * Texture for the body.\n */\n public Texture texture;\n\n /**\n * BodyDef for the body.\n */\n public BodyDef bd;\n\n /**\n * FixtureDef for the body.\n */\n public FixtureDef fd;\n}", "public class G {\n /**\n * Debug mode\n...
import aurelienribon.bodyeditor.BodyEditorLoader; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.ParticleEffect; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import fi.hbp.angr.AssetContainer; import fi.hbp.angr.G; import fi.hbp.angr.ItemDestruction; import fi.hbp.angr.logic.DamageModel; import fi.hbp.angr.models.CollisionFilterMasks; import fi.hbp.angr.models.Destructible; import fi.hbp.angr.models.Explosion; import fi.hbp.angr.models.SlingshotActor; import fi.hbp.angr.stage.GameStage;
package fi.hbp.angr.models.actors; /** * A Throwable and explodable grenade model. */ public class Grenade extends SlingshotActor implements Destructible { /** * Name of this model. */ private final static String MODEL_NAME = "grenade"; /** * Texture file path. */ private final static String TEXTURE_PATH = "data/" + MODEL_NAME + ".png"; /** * Sound effect file path. */ private final static String SOUND_FX_PATH = "data/grenade.wav"; /** * Delay between release of grenade and explosion. */ private final static float EXPLOSION_DELAY = 3.0f; /** * Item destruction list. */
private final ItemDestruction itdes;
2
mokies/ratelimitj
ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/request/RedisSlidingWindowSyncRequestRequestRateLimiterPerformanceTest.java
[ "@ParametersAreNonnullByDefault\npublic class RequestLimitRule {\n\n private final int durationSeconds;\n private final long limit;\n private final int precision;\n private final String name;\n private final Set<String> keys;\n\n private RequestLimitRule(int durationSeconds, long limit, int precis...
import es.moki.ratelimitj.core.limiter.request.RequestLimitRule; import es.moki.ratelimitj.core.limiter.request.RequestRateLimiter; import es.moki.ratelimitj.core.time.TimeSupplier; import es.moki.ratelimitj.redis.extensions.RedisStandaloneConnectionSetupExtension; import es.moki.ratelimitj.test.limiter.request.AbstractSyncRequestRateLimiterPerformanceTest; import io.lettuce.core.RedisClient; import io.lettuce.core.api.StatefulRedisConnection; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.extension.RegisterExtension; import java.util.Set;
package es.moki.ratelimitj.redis.request; public class RedisSlidingWindowSyncRequestRequestRateLimiterPerformanceTest extends AbstractSyncRequestRateLimiterPerformanceTest { @RegisterExtension
static RedisStandaloneConnectionSetupExtension extension = new RedisStandaloneConnectionSetupExtension();
3
GoogleCloudPlatform/healthcare-api-dicom-fuse
src/test/java/com/google/dicomwebfuse/AppMountProcessTest.java
[ "public interface FuseDao {\n\n List<DicomStore> getAllDicomStores(QueryBuilder queryBuilder) throws DicomFuseException;\n DicomStore getSingleDicomStore(QueryBuilder queryBuilder) throws DicomFuseException;\n List<Study> getStudies(QueryBuilder queryBuilder) throws DicomFuseException;\n Study getSingleStudy(Qu...
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItems; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.ArgumentMatchers.any; import com.google.dicomwebfuse.dao.FuseDao; import com.google.dicomwebfuse.exception.DicomFuseException; import com.google.dicomwebfuse.fuse.DicomFuse; import com.google.dicomwebfuse.fuse.Parameters; import com.google.dicomwebfuse.parser.Arguments; import java.io.IOException; import java.util.Arrays; import java.util.List; import jnr.ffi.Platform; import jnr.ffi.Platform.OS; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito;
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.dicomwebfuse; class AppMountProcessTest { private static OS systemOs; @BeforeAll static void setup() { systemOs = Platform.getNativePlatform().getOS(); } @Test void testShouldReturnExceptionIfUserDoesNotHaveAccessToAnDataset() throws DicomFuseException { // Given Arguments arguments = new Arguments(); // Setting OS OS os = OS.LINUX;
FuseDao fuseDao = Mockito.mock(FuseDao.class);
0
gentoku/pinnacle-api-client
src/pinnacle/api/dataobjects/Fixtures.java
[ "public class Json {\n\n\tprivate JsonObject jsonObject;\n\n\t/**\n\t * Private constructor by JsonObject.\n\t * \n\t * @param json\n\t */\n\tprivate Json(JsonObject jsonObject) {\n\t\tthis.jsonObject = jsonObject;\n\t}\n\n\t/**\n\t * Factory\n\t * \n\t * @param text\n\t * @return\n\t * @throws PinnacleException\n\...
import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import pinnacle.api.Json; import pinnacle.api.PinnacleException; import pinnacle.api.enums.EVENT_STATUS; import pinnacle.api.enums.LIVE_STATUS; import pinnacle.api.enums.PARLAY_RESTRICTION;
package pinnacle.api.dataobjects; public class Fixtures extends AbstractDataObject { private Integer sportId; public Integer sportId() { return this.sportId; } private Long last; public Long last() { return this.last; } private List<League> league = new ArrayList<>(); public List<League> league() { return this.league; } public Stream<League> leagueAsStream() { return this.league.stream(); } private Fixtures(Json json) { this.sportId = json.getAsInteger("sportId").orElse(null); this.last = json.getAsLong("last").orElse(null); this.league = json.getAsJsonStream("league").map(League::new).collect(Collectors.toList()); this.checkRequiredKeys(); } private Fixtures() { this.isEmpty = true; } public static Fixtures parse(String jsonText) throws PinnacleException { return jsonText.equals("{}") ? new Fixtures() : new Fixtures(Json.of(jsonText)); } @Override boolean hasRequiredKeyWithNull() { return this.sportId == null || this.last == null; } @Override public String toString() { return "Fixtures [sportId=" + sportId + ", last=" + last + ", league=" + league + "]"; } public static class League extends AbstractDataObject { private Long id; public Long id() { return this.id; } private List<Event> events = new ArrayList<>(); public List<Event> events() { return this.events; } public Stream<Event> eventsAsStream() { return this.events.stream(); } private League(Json json) { this.id = json.getAsLong("id").orElse(null); this.events = json.getAsJsonStream("events").map(Event::new).collect(Collectors.toList()); this.checkRequiredKeys(); } @Override boolean hasRequiredKeyWithNull() { return this.id == null; } @Override public String toString() { return "League [id=" + id + ", events=" + events + "]"; } } public static class Event extends AbstractDataObject { private Long id; public Long id() { return this.id; } private Instant starts; public Instant starts() { return this.starts; } private String home; public String home() { return this.home; } private String away; public String away() { return this.away; } private String rotNum; public String rotNum() { return this.rotNum; } private Optional<LIVE_STATUS> liveStatus; public Optional<LIVE_STATUS> liveStatus() { return this.liveStatus; }
private EVENT_STATUS status;
2
vy/log4j2-logstash-layout
layout/src/main/java/com/vlkan/log4j2/logstash/layout/LogstashLayout.java
[ "public class EventResolverContext implements TemplateResolverContext<LogEvent, EventResolverContext> {\n\n private final ObjectMapper objectMapper;\n\n private final StrSubstitutor substitutor;\n\n private final int writerCapacity;\n\n private final TimeZone timeZone;\n\n private final Locale locale...
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.vlkan.log4j2.logstash.layout.resolver.EventResolverContext; import com.vlkan.log4j2.logstash.layout.resolver.StackTraceElementObjectResolverContext; import com.vlkan.log4j2.logstash.layout.resolver.TemplateResolver; import com.vlkan.log4j2.logstash.layout.resolver.TemplateResolvers; import com.vlkan.log4j2.logstash.layout.util.AutoCloseables; import com.vlkan.log4j2.logstash.layout.util.ByteBufferDestinations; import com.vlkan.log4j2.logstash.layout.util.ByteBufferOutputStream; import com.vlkan.log4j2.logstash.layout.util.Uris; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.Node; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute; import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory; import org.apache.logging.log4j.core.config.plugins.PluginConfiguration; import org.apache.logging.log4j.core.config.plugins.PluginElement; import org.apache.logging.log4j.core.layout.ByteBufferDestination; import org.apache.logging.log4j.core.lookup.StrSubstitutor; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.core.util.KeyValuePair; import org.apache.logging.log4j.core.util.datetime.FastDateFormat; import java.io.IOException; import java.lang.reflect.Method; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.function.Supplier;
.setStackTraceEnabled(builder.stackTraceEnabled) .setStackTraceElementObjectResolver(stackTraceElementObjectResolver) .setEmptyPropertyExclusionEnabled(builder.emptyPropertyExclusionEnabled) .setMdcKeyPattern(builder.mdcKeyPattern) .setNdcPattern(builder.ndcPattern) .setAdditionalFields(builder.eventTemplateAdditionalFields.pairs) .setMapMessageFormatterIgnored(builder.mapMessageFormatterIgnored) .build(); return TemplateResolvers.ofTemplate(resolverContext, eventTemplate); } private static Supplier<LogstashLayoutSerializationContext> createSerializationContextSupplier(Builder builder, ObjectMapper objectMapper) { return LogstashLayoutSerializationContexts.createSupplier( objectMapper, builder.maxByteCount, builder.prettyPrintEnabled, builder.emptyPropertyExclusionEnabled, builder.maxStringLength); } private static String readEventTemplate(Builder builder) { return readTemplate(builder.eventTemplate, builder.eventTemplateUri); } private static String readStackTraceElementTemplate(Builder builder) { return readTemplate(builder.stackTraceElementTemplate, builder.stackTraceElementTemplateUri); } private static String readTemplate(String template, String templateUri) { return StringUtils.isBlank(template) ? Uris.readUri(templateUri) : template; } private static Locale readLocale(String locale) { if (locale == null) { return Locale.getDefault(); } String[] localeFields = locale.split("_", 3); switch (localeFields.length) { case 1: return new Locale(localeFields[0]); case 2: return new Locale(localeFields[0], localeFields[1]); case 3: return new Locale(localeFields[0], localeFields[1], localeFields[2]); } throw new IllegalArgumentException("invalid locale: " + locale); } @Override public String toSerializable(LogEvent event) { LogstashLayoutSerializationContext context = getResetSerializationContext(); try { encode(event, context); return context.getOutputStream().toString(CHARSET); } catch (Exception error) { reloadSerializationContext(context); throw new RuntimeException("failed serializing JSON", error); } } @Override public byte[] toByteArray(LogEvent event) { LogstashLayoutSerializationContext context = getResetSerializationContext(); try { encode(event, context); return context.getOutputStream().toByteArray(); } catch (Exception error) { reloadSerializationContext(context); throw new RuntimeException("failed serializing JSON", error); } } @Override public void encode(LogEvent event, ByteBufferDestination destination) { LogstashLayoutSerializationContext context = getResetSerializationContext(); try { encode(event, context); ByteBuffer byteBuffer = context.getOutputStream().getByteBuffer(); // noinspection RedundantCast (for Java 8 compatibility) ((Buffer) byteBuffer).flip(); // noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (destination) { ByteBufferDestinations.writeToUnsynchronized(byteBuffer, destination); } } catch (Exception error) { reloadSerializationContext(context); throw new RuntimeException("failed serializing JSON", error); } } // Visible for tests. LogstashLayoutSerializationContext getSerializationContext() { return Constants.ENABLE_THREADLOCALS ? serializationContextRef.get() : serializationContextSupplier.get(); } private LogstashLayoutSerializationContext getResetSerializationContext() { LogstashLayoutSerializationContext context; if (Constants.ENABLE_THREADLOCALS) { context = serializationContextRef.get(); context.reset(); } else { context = serializationContextSupplier.get(); } return context; } private void reloadSerializationContext(LogstashLayoutSerializationContext oldContext) { AutoCloseables.closeUnchecked(oldContext); if (Constants.ENABLE_THREADLOCALS) { LogstashLayoutSerializationContext newContext = serializationContextSupplier.get(); serializationContextRef.set(newContext); } } private void encode(LogEvent event, LogstashLayoutSerializationContext context) throws IOException { JsonGenerator jsonGenerator = context.getJsonGenerator(); eventResolver.resolve(event, jsonGenerator); jsonGenerator.flush();
ByteBufferOutputStream outputStream = context.getOutputStream();
6
xoxefdp/farmacia
src/Vista/VistaLaboratorioManejo.java
[ "public class Botonera extends JPanel{ \r\n JButton[] botones;\r\n JPanel cuadroBotonera;\r\n \r\n public Botonera(int botonesBotonera){\r\n cuadroBotonera = new JPanel();\r\n cuadroBotonera.setLayout(new FlowLayout());\r\n \r\n if (botonesBotonera == 2) {\r\n ...
import Vista.Formatos.Botonera; import Control.CerrarVentana; import Control.IncluirActualizarEliminar; import Control.OyenteActualizar; import Control.OyenteEliminar; import Control.OyenteIncluir; import Vista.Tablas.TablaDeLaboratorios; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame;
package Vista; /** * * @author José Diaz */ public class VistaLaboratorioManejo extends JFrame implements ActionListener, CerrarVentana, IncluirActualizarEliminar{ private TablaDeLaboratorios tablaLab; private Botonera botoneraLab; public VistaLaboratorioManejo(){ crearVentana(); } final void crearVentana(){ setTitle("Manejo de Laboratorios"); setLayout(new BorderLayout()); tablaLab = new TablaDeLaboratorios(); botoneraLab = new Botonera(3); botoneraLab.adherirEscucha(0, new OyenteIncluir(this)); botoneraLab.adherirEscucha(1, new OyenteActualizar(this));
botoneraLab.adherirEscucha(2, new OyenteEliminar(this));
4
Rai220/Telephoto
app/src/main/java/com/rai220/securityalarmbot/commands/HDPhotoCommand.java
[ "public class BotService extends Service implements MotionDetectorController.MotionDetectorListener, IStartService {\n public static final String TELEPHOTO_SERVICE_STOPPED = \"TELEPHOTO_SERVICE_STOPPED\";\n\n private TelegramService telegramService;\n private BatteryReceiver batteryReceiver;\n private S...
import com.pengrad.telegrambot.model.Message; import com.rai220.securityalarmbot.BotService; import com.rai220.securityalarmbot.R; import com.rai220.securityalarmbot.photo.CameraTask; import com.rai220.securityalarmbot.photo.ImageShot; import com.rai220.securityalarmbot.prefs.Prefs; import com.rai220.securityalarmbot.prefs.PrefsController; import com.rai220.securityalarmbot.utils.FabricUtils; import com.rai220.securityalarmbot.utils.L; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package com.rai220.securityalarmbot.commands; /** * */ public class HDPhotoCommand extends AbstractCommand { private final ExecutorService es = Executors.newCachedThreadPool(); public HDPhotoCommand(BotService service) { super(service); } @Override public String getCommand() { return "/hd_photo"; } @Override public String getName() { return "HD Photo"; } @Override public String getDescription() { return "Take a HD photo"; } @Override public boolean isHide() { return true; } @Override public boolean execute(final Message message, Prefs prefs) { es.submit(new Runnable() { @Override public void run() { final Long chatId = message.chat().id(); if (PrefsController.instance.isPro()) { final int[] cameraIds = FabricUtils.getSelectedCameras(); for (int cameraId : cameraIds) {
boolean addTaskResult = botService.getCamera().addTask(new CameraTask(cameraId, 10000, 10000) {
1
comtel2000/jfxvnc
jfxvnc-app/src/main/java/org/jfxvnc/app/presentation/connect/ConnectViewPresenter.java
[ "public class HistoryEntry implements Comparable<HistoryEntry>, Serializable {\n\n private static final long serialVersionUID = 2877392353047511185L;\n\n private final String host;\n private final int port;\n private int securityType;\n private String password;\n private String serverName;\n\n public History...
import java.net.URL; import java.util.Optional; import java.util.ResourceBundle; import javax.inject.Inject; import org.jfxvnc.app.persist.HistoryEntry; import org.jfxvnc.app.persist.SessionContext; import org.jfxvnc.net.rfb.codec.ProtocolVersion; import org.jfxvnc.net.rfb.codec.security.SecurityType; import org.jfxvnc.net.rfb.render.ConnectInfoEvent; import org.jfxvnc.net.rfb.render.ProtocolConfiguration; import org.jfxvnc.ui.service.VncRenderService; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.ListView; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.util.StringConverter; import javafx.util.converter.NumberStringConverter;
/******************************************************************************* * Copyright (c) 2016 comtel inc. * * 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.jfxvnc.app.presentation.connect; public class ConnectViewPresenter implements Initializable { @Inject SessionContext ctx; @Inject
VncRenderService con;
6
Darkona/AdventureBackpack2
src/main/java/com/darkona/adventurebackpack/handlers/PlayerEventHandler.java
[ "public class ServerActions\n{\n public static final boolean HOSE_SWITCH = false;\n public static final boolean HOSE_TOGGLE = true;\n\n /**\n * Cycles tools. In a cycle. The tool in your hand with the tools in the special tool slots of the backpack, to be precise.\n *\n * @param player - Duh...
import com.darkona.adventurebackpack.common.ServerActions; import com.darkona.adventurebackpack.config.ConfigHandler; import com.darkona.adventurebackpack.entity.EntityFriendlySpider; import com.darkona.adventurebackpack.entity.ai.EntityAIHorseFollowOwner; import com.darkona.adventurebackpack.init.ModBlocks; import com.darkona.adventurebackpack.init.ModItems; import com.darkona.adventurebackpack.item.IBackWearableItem; import com.darkona.adventurebackpack.playerProperties.BackpackProperty; import com.darkona.adventurebackpack.proxy.ServerProxy; import com.darkona.adventurebackpack.reference.BackpackNames; import com.darkona.adventurebackpack.util.LogHelper; import com.darkona.adventurebackpack.util.Utils; import com.darkona.adventurebackpack.util.Wearing; import cpw.mods.fml.common.eventhandler.Event; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.common.gameevent.TickEvent; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.monster.EntitySpider; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.item.ItemNameTag; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChunkCoordinates; import net.minecraftforge.event.entity.EntityEvent; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.event.entity.living.LivingFallEvent; import net.minecraftforge.event.entity.player.EntityInteractEvent; import net.minecraftforge.event.entity.player.PlayerWakeUpEvent;
package com.darkona.adventurebackpack.handlers; /** * Created on 11/10/2014 * Handle ALL the events! * * @author Darkona * @see com.darkona.adventurebackpack.client.ClientActions */ public class PlayerEventHandler { private static int tickCounter = 0; @SubscribeEvent public void registerBackpackProperty(EntityEvent.EntityConstructing event) { if (event.entity instanceof EntityPlayer && BackpackProperty.get((EntityPlayer) event.entity) == null) { BackpackProperty.register((EntityPlayer) event.entity); /*if (!event.entity.worldObj.isRemote) { AdventureBackpack.proxy.joinPlayer((EntityPlayer)event.entity); }*/ } } @SubscribeEvent public void joinPlayer(EntityJoinWorldEvent event) { if (!event.world.isRemote) {
if (Utils.notNullAndInstanceOf(event.entity, EntityPlayer.class))
5
philliphsu/ClockPlus
app/src/main/java/com/philliphsu/clock2/timers/ui/TimersFragment.java
[ "public class EditTimerActivity extends BaseActivity implements AddLabelDialog.OnLabelSetListener {\n private static final int FIELD_LENGTH = 2;\n private static final String KEY_LABEL = \"key_label\";\n\n public static final String EXTRA_HOUR = \"com.philliphsu.clock2.edittimer.extra.HOUR\";\n public s...
import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.Loader; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.philliphsu.clock2.timers.EditTimerActivity; import com.philliphsu.clock2.timers.data.AsyncTimersTableUpdateHandler; import com.philliphsu.clock2.R; import com.philliphsu.clock2.list.RecyclerViewFragment; import com.philliphsu.clock2.timers.Timer; import com.philliphsu.clock2.timers.data.TimerCursor; import com.philliphsu.clock2.timers.data.TimersListCursorLoader; import static butterknife.ButterKnife.findById; import static com.philliphsu.clock2.util.ConfigurationUtils.getOrientation;
/* * Copyright 2017 Phillip Hsu * * This file is part of ClockPlus. * * ClockPlus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ClockPlus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ClockPlus. If not, see <http://www.gnu.org/licenses/>. */ package com.philliphsu.clock2.timers.ui; public class TimersFragment extends RecyclerViewFragment<Timer, TimerViewHolder, TimerCursor, TimersCursorAdapter> { // TODO: Different number of columns for different display densities, instead of landscape. // Use smallest width qualifiers. I can imagine 3 or 4 columns for a large enough tablet in landscape. private static final int LANDSCAPE_LAYOUT_COLUMNS = 2; public static final int REQUEST_CREATE_TIMER = 0; public static final String EXTRA_SCROLL_TO_TIMER_ID = "com.philliphsu.clock2.timers.extra.SCROLL_TO_TIMER_ID"; private AsyncTimersTableUpdateHandler mAsyncTimersTableUpdateHandler; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAsyncTimersTableUpdateHandler = new AsyncTimersTableUpdateHandler(getActivity(), this); long scrollToStableId = getActivity().getIntent().getLongExtra(EXTRA_SCROLL_TO_TIMER_ID, -1); if (scrollToStableId != -1) { setScrollToStableId(scrollToStableId); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); final Resources r = getResources(); if (getOrientation(r) == Configuration.ORIENTATION_LANDSCAPE) { RecyclerView list = findById(view, R.id.list); int cardViewMargin = r.getDimensionPixelSize(R.dimen.cardview_margin); list.setPaddingRelative(cardViewMargin/*start*/, cardViewMargin/*top*/, 0, list.getPaddingBottom()); } return view; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != Activity.RESULT_OK || data == null) return; // TODO: From EditTimerActivity, pass back the Timer as a parcelable and // retrieve it here directly. int hour = data.getIntExtra(EditTimerActivity.EXTRA_HOUR, -1); int minute = data.getIntExtra(EditTimerActivity.EXTRA_MINUTE, -1); int second = data.getIntExtra(EditTimerActivity.EXTRA_SECOND, -1); String label = data.getStringExtra(EditTimerActivity.EXTRA_LABEL); boolean startTimer = data.getBooleanExtra(EditTimerActivity.EXTRA_START_TIMER, false); // TODO: Timer's group? Timer t = Timer.createWithLabel(hour, minute, second, label); if (startTimer) { t.start(); } mAsyncTimersTableUpdateHandler.asyncInsert(t); } @Override public void onFabClick() { Intent intent = new Intent(getActivity(), EditTimerActivity.class); startActivityForResult(intent, REQUEST_CREATE_TIMER); } @Override protected TimersCursorAdapter onCreateAdapter() { // Create a new adapter. This is called before we can initialize mAsyncTimersTableUpdateHandler, // so right now it is null. However, after super.onCreate() returns, it is initialized, and // the reference variable will be pointing to an actual object. This assignment "propagates" // to all references to mAsyncTimersTableUpdateHandler. return new TimersCursorAdapter(this, mAsyncTimersTableUpdateHandler); } @Override protected RecyclerView.LayoutManager getLayoutManager() { switch (getOrientation(getResources())) { case Configuration.ORIENTATION_LANDSCAPE: return new GridLayoutManager(getActivity(), LANDSCAPE_LAYOUT_COLUMNS); default: return super.getLayoutManager(); } } @Override protected int emptyMessage() { return R.string.empty_timers_container; } @Override protected int emptyIcon() { return R.drawable.ic_timer_96dp; } @Override public Loader<TimerCursor> onCreateLoader(int id, Bundle args) {
return new TimersListCursorLoader(getActivity());
5
cm-heclouds/JAVA-HTTP-SDK
javaSDK/src/main/java/cmcc/iot/onenet/javasdk/api/device/GetDevicesStatus.java
[ "public abstract class AbstractAPI<T> {\n public String key;\n public String url;\n public Method method;\n public ObjectMapper mapper = initObjectMapper();\n\n private ObjectMapper initObjectMapper() {\n ObjectMapper objectMapper = new ObjectMapper();\n //关闭字段不识别报错\n objectMappe...
import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cmcc.iot.onenet.javasdk.api.AbstractAPI; import cmcc.iot.onenet.javasdk.exception.OnenetApiException; import cmcc.iot.onenet.javasdk.http.HttpGetMethod; import cmcc.iot.onenet.javasdk.request.RequestInfo.Method; import cmcc.iot.onenet.javasdk.response.BasicResponse; import cmcc.iot.onenet.javasdk.response.device.DevicesStatusList; import cmcc.iot.onenet.javasdk.utils.Config;
package cmcc.iot.onenet.javasdk.api.device; public class GetDevicesStatus extends AbstractAPI { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private HttpGetMethod HttpMethod; private String devIds; /** * 批量查询设备状态 * 参数顺序与构造函数顺序一致 * @param devIds:设备id用逗号隔开, 限制1000个设备,String * @param key :masterkey */ public GetDevicesStatus(String devIds,String key) { this.devIds = devIds; this.key = key;
this.method = Method.GET;
3
optimizely/android-sdk
android-sdk/src/androidTest/java/com/optimizely/ab/android/sdk/OptimizelyManagerTest.java
[ "@Deprecated\npublic interface DatafileHandler {\n /**\n * Synchronous call to download the datafile.\n *\n * @param context application context for download\n * @param datafileConfig DatafileConfig for the datafile\n * @return a valid datafile or null\n */\n String downloadDatafile(...
import android.app.AlarmManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.SdkSuppress; import androidx.test.platform.app.InstrumentationRegistry; import com.optimizely.ab.android.datafile_handler.DatafileHandler; import com.optimizely.ab.android.datafile_handler.DatafileLoadedListener; import com.optimizely.ab.android.datafile_handler.DatafileService; import com.optimizely.ab.android.datafile_handler.DefaultDatafileHandler; import com.optimizely.ab.android.event_handler.DefaultEventHandler; import com.optimizely.ab.android.shared.DatafileConfig; import com.optimizely.ab.android.shared.ServiceScheduler; import com.optimizely.ab.android.user_profile.DefaultUserProfileService; import com.optimizely.ab.bucketing.UserProfileService; import com.optimizely.ab.config.DatafileProjectConfig; import com.optimizely.ab.config.ProjectConfig; import com.optimizely.ab.config.Variation; import com.optimizely.ab.config.parser.ConfigParseException; import com.optimizely.ab.event.EventHandler; import com.optimizely.ab.event.EventProcessor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.slf4j.Logger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
@Test public void initializeWithMalformedDatafile() { Context context = mock(Context.class); Context appContext = mock(Context.class); when(context.getApplicationContext()).thenReturn(appContext); when(appContext.getPackageName()).thenReturn("com.optly"); when(defaultDatafileHandler.getConfig()).thenReturn(null); String emptyString = "malformed data"; optimizelyManager.initialize(context, emptyString); assertFalse(optimizelyManager.getOptimizely().isValid()); } @Test public void initializeWithNullDatafile() { Context context = mock(Context.class); Context appContext = mock(Context.class); when(context.getApplicationContext()).thenReturn(appContext); when(appContext.getPackageName()).thenReturn("com.optly"); String emptyString = null; optimizelyManager.initialize(context, emptyString); verify(logger).error(eq("Invalid datafile")); } @Test public void initializeAsyncWithNullDatafile() { optimizelyManager.initialize(InstrumentationRegistry.getInstrumentation().getContext(), new OptimizelyStartListener() { @Override public void onStart(OptimizelyClient optimizely) { assertNotNull(optimizely); } }); } @Test public void load() { Context context = mock(Context.class); Context appContext = mock(Context.class); when(context.getApplicationContext()).thenReturn(appContext); when(appContext.getPackageName()).thenReturn("com.optly"); String emptyString = null; optimizelyManager.initialize(context, emptyString); verify(logger).error(eq("Invalid datafile")); } @Test public void stop() { Context context = mock(Context.class); Context appContext = mock(Context.class); when(context.getApplicationContext()).thenReturn(appContext); optimizelyManager.getDatafileHandler().downloadDatafile(context, optimizelyManager.getDatafileConfig(), null); optimizelyManager.stop(context); assertNull(optimizelyManager.getOptimizelyStartListener()); } @Test public void injectOptimizely() { Context context = mock(Context.class); UserProfileService userProfileService = mock(UserProfileService.class); OptimizelyStartListener startListener = mock(OptimizelyStartListener.class); optimizelyManager.setOptimizelyStartListener(startListener); optimizelyManager.injectOptimizely(context, userProfileService, minDatafile); try { executor.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("Timed out"); } verify(logger).info("Sending Optimizely instance to listener"); verify(startListener).onStart(any(OptimizelyClient.class)); verify(optimizelyManager.getDatafileHandler()).startBackgroundUpdates(eq(context), eq(new DatafileConfig(testProjectId, null)), eq(3600L), any(DatafileLoadedListener.class)); } @Test public void injectOptimizelyWithDatafileListener() { Context context = mock(Context.class); UserProfileService userProfileService = mock(UserProfileService.class); OptimizelyStartListener startListener = mock(OptimizelyStartListener.class); optimizelyManager.setOptimizelyStartListener(startListener); optimizelyManager.injectOptimizely(context, userProfileService, minDatafile); try { executor.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("Timed out"); } verify(optimizelyManager.getDatafileHandler()).startBackgroundUpdates(eq(context), eq(new DatafileConfig(testProjectId, null)), eq(3600L), any(DatafileLoadedListener.class)); verify(logger).info("Sending Optimizely instance to listener"); verify(startListener).onStart(any(OptimizelyClient.class)); } @Test @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP) public void injectOptimizelyNullListener() { Context context = mock(Context.class); PackageManager packageManager = mock(PackageManager.class); when(context.getPackageName()).thenReturn("com.optly"); when(context.getApplicationContext()).thenReturn(context); when(context.getApplicationContext().getPackageManager()).thenReturn(packageManager); try { when(packageManager.getPackageInfo("com.optly", 0)).thenReturn(mock(PackageInfo.class)); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } UserProfileService userProfileService = mock(UserProfileService.class); ServiceScheduler serviceScheduler = mock(ServiceScheduler.class); ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
ArgumentCaptor<DefaultUserProfileService.StartCallback> callbackArgumentCaptor =
7
Zhuinden/simple-stack
simple-stack/src/test/java/com/zhuinden/simplestack/ScopingGlobalScopeTest.java
[ "public interface HasParentServices\n extends ScopeKey.Child {\n void bindServices(ServiceBinder serviceBinder);\n}", "public interface HasServices\n extends ScopeKey {\n void bindServices(ServiceBinder serviceBinder);\n}", "public class ServiceProvider\n implements ScopedServices {\n...
import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nonnull; import javax.annotation.Nullable; import static org.assertj.core.api.Assertions.assertThat; import android.os.Parcel; import com.zhuinden.simplestack.helpers.HasParentServices; import com.zhuinden.simplestack.helpers.HasServices; import com.zhuinden.simplestack.helpers.ServiceProvider; import com.zhuinden.simplestack.helpers.TestKey; import com.zhuinden.simplestack.helpers.TestKeyWithScope; import com.zhuinden.statebundle.StateBundle; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Objects;
assertThat(backstack.canFindFromScope("beep", "parentService1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.lookupFromScope("boop", "parentService1", ScopeLookupMode.ALL)).isSameAs(parentService1); assertThat(backstack.lookupFromScope("beep", "parentService1", ScopeLookupMode.ALL)).isSameAs(parentService1); assertThat(backstack.lookupService("parentService1")).isSameAs(parentService1); backstack.setHistory(History.of(new Key2("boop")), StateChange.REPLACE); assertThat(backstack.lookupService("parentService1")).isSameAs(globalService); } private enum ServiceEvent { CREATE, ACTIVE, INACTIVE, DESTROY } private static class Pair<S, T> { private S first; private T second; private Pair(S first, T second) { this.first = first; this.second = second; } public static <S, T> Pair<S, T> of(S first, T second) { return new Pair<>(first, second); } @Override public boolean equals(Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } Pair<?, ?> pair = (Pair<?, ?>) o; return Objects.equals(first, pair.first) && Objects.equals(second, pair.second); } @Override public int hashCode() { return Objects.hash(first, second); } @Override public String toString() { return "Pair{" + "first=" + first + ", second=" + second + '}'; } } @Test public void serviceLifecycleCallbacksWork() { final List<Pair<Object, ServiceEvent>> events = new ArrayList<>(); Backstack backstack = new Backstack(); backstack.setScopedServices(new ServiceProvider()); class MyService implements ScopedServices.Activated, ScopedServices.Registered { private int id = 0; MyService(int id) { this.id = id; } @Override public void onServiceActive() { events.add(Pair.of((Object) this, ServiceEvent.ACTIVE)); } @Override public void onServiceInactive() { events.add(Pair.of((Object) this, ServiceEvent.INACTIVE)); } @Override public String toString() { return "MyService{" + "id=" + id + '}'; } @Override public void onServiceRegistered() { events.add(Pair.of((Object) this, ServiceEvent.CREATE)); } @Override public void onServiceUnregistered() { events.add(Pair.of((Object) this, ServiceEvent.DESTROY)); } } final Object service0 = new MyService(0); backstack.setGlobalServices(GlobalServices.builder() .addService("SERVICE0", service0) .build()); final Object service1 = new MyService(1); final Object service2 = new MyService(2); final Object service3 = new MyService(3); final Object service4 = new MyService(4); final Object service5 = new MyService(5); final Object service6 = new MyService(6); final Object service7 = new MyService(7); final Object service8 = new MyService(8); final Object service9 = new MyService(9);
TestKeyWithScope beep = new TestKeyWithScope("beep") {
4
apptik/MultiView
app/src/main/java/io/apptik/multiview/AnimatorsFragment.java
[ "public class BasicMixedRecyclerAdapter extends RecyclerView.Adapter<BasicMixedRecyclerAdapter.ViewHolder> {\n private static final String TAG = \"BasicMixedAdapter\";\n private JsonArray jarr;\n Cursor c;\n\n\n public class ViewHolder extends RecyclerView.ViewHolder {\n public final TextView txt...
import io.apptik.multiview.adapter.BasicMixedRecyclerAdapter; import io.apptik.multiview.adapter.BasicRecyclerAdapter; import io.apptik.multiview.mock.MockData; import io.apptik.multiview.animators.AnimatorProvider; import io.apptik.multiview.animators.FlexiItemAnimator; import io.apptik.multiview.animators.Providers; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup;
/* * Copyright (C) 2015 AppTik Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apptik.multiview; public class AnimatorsFragment extends Fragment { RecyclerView recyclerView = null;
BasicRecyclerAdapter recyclerAdapter;
1
Darkona/AdventureBackpack2
src/main/java/com/darkona/adventurebackpack/item/ItemAdventureBackpack.java
[ "@Mod(modid = ModInfo.MOD_ID,\n name = ModInfo.MOD_NAME,\n version = ModInfo.MOD_VERSION,\n guiFactory = ModInfo.GUI_FACTORY_CLASS\n)\npublic class AdventureBackpack\n{\n\n @SidedProxy(clientSide = ModInfo.MOD_CLIENT_PROXY, serverSide = ModInfo.MOD_SERVER_PROXY)\n public static IProxy pro...
import com.darkona.adventurebackpack.AdventureBackpack; import com.darkona.adventurebackpack.block.BlockAdventureBackpack; import com.darkona.adventurebackpack.block.TileAdventureBackpack; import com.darkona.adventurebackpack.client.models.ModelBackpackArmor; import com.darkona.adventurebackpack.common.BackpackAbilities; import com.darkona.adventurebackpack.config.ConfigHandler; import com.darkona.adventurebackpack.events.WearableEvent; import com.darkona.adventurebackpack.init.ModBlocks; import com.darkona.adventurebackpack.init.ModItems; import com.darkona.adventurebackpack.init.ModNetwork; import com.darkona.adventurebackpack.network.GUIPacket; import com.darkona.adventurebackpack.playerProperties.BackpackProperty; import com.darkona.adventurebackpack.proxy.ClientProxy; import com.darkona.adventurebackpack.reference.BackpackNames; import com.darkona.adventurebackpack.util.BackpackUtils; import com.darkona.adventurebackpack.util.Resources; import com.darkona.adventurebackpack.util.Utils; import com.darkona.adventurebackpack.util.Wearing; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.client.model.ModelBiped; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.ForgeDirection; import java.util.List;
super.onCreated(stack, par2World, par3EntityPlayer); BackpackNames.setBackpackColorNameFromDamage(stack, stack.getItemDamage()); } public boolean placeBackpack(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, boolean from) { if (!stack.hasTagCompound()) stack.setTagCompound(new NBTTagCompound()); if (!player.canPlayerEdit(x, y, z, side, stack)) return false; if (!stack.stackTagCompound.hasKey("colorName") || stack.stackTagCompound.getString("colorName").isEmpty()) { stack.stackTagCompound.setString("colorName", "Standard"); } // world.spawnEntityInWorld(new EntityLightningBolt(world, x, y, z)); BlockAdventureBackpack backpack = ModBlocks.blockBackpack; if (y <= 0 || y >= world.getHeight()) { return false; } if (backpack.canPlaceBlockOnSide(world, x, y, z, side)) { if (world.getBlock(x, y, z).getMaterial().isSolid()) { switch (side) { case 0: --y; break; case 1: ++y; break; case 2: --z; break; case 3: ++z; break; case 4: --x; break; case 5: ++x; break; } } if (y <= 0 || y >= world.getHeight()) { return false; } if (backpack.canPlaceBlockAt(world, x, y, z)) { if (world.setBlock(x, y, z, ModBlocks.blockBackpack)) { backpack.onBlockPlacedBy(world, x, y, z, player, stack); world.playSoundAtEntity(player, BlockAdventureBackpack.soundTypeCloth.getStepResourcePath(), 0.5f, 1.0f); ((TileAdventureBackpack) world.getTileEntity(x, y, z)).loadFromNBT(stack.stackTagCompound); if (from) { player.inventory.decrStackSize(player.inventory.currentItem, 1); } else { BackpackProperty.get(player).setWearable(null); } WearableEvent event = new WearableEvent(player, stack); MinecraftForge.EVENT_BUS.post(event); return true; } } } return false; } @Override public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { return player.canPlayerEdit(x, y, z, side, stack) && placeBackpack(stack, player, world, x, y, z, side, true); } @Override public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { MovingObjectPosition mop = getMovingObjectPositionFromPlayer(world, player, true); if (mop == null || mop.typeOfHit == MovingObjectPosition.MovingObjectType.ENTITY) { if (world.isRemote) { ModNetwork.net.sendToServer(new GUIPacket.GUImessage(GUIPacket.BACKPACK_GUI, GUIPacket.FROM_HOLDING)); } } return stack; } @Override public boolean isDamageable() { return false; } @Override public boolean onDroppedByPlayer(ItemStack stack, EntityPlayer player) { return true; } @SideOnly(Side.CLIENT) @Override public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack stack, int armorSlot) { return new ModelBackpackArmor(); } @SideOnly(Side.CLIENT) @Override public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) { String modelTexture; if (BackpackNames.getBackpackColorName(stack).equals("Standard")) {
modelTexture = Resources.backpackTextureFromString(AdventureBackpack.instance.Holiday).toString();
0
cdelmas/microservices-comparison
vertx/src/main/java/io/github/cdelmas/spike/vertx/Main.java
[ "public class Car {\n\n private Integer id;\n private String name;\n\n public Car(String name) {\n this.name = name;\n }\n\n Car() {\n\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n ...
import com.fasterxml.jackson.databind.DeserializationFeature; import io.github.cdelmas.spike.common.domain.Car; import io.github.cdelmas.spike.common.domain.CarRepository; import io.github.cdelmas.spike.common.persistence.InMemoryCarRepository; import io.github.cdelmas.spike.vertx.car.CarResource; import io.github.cdelmas.spike.vertx.car.CarsResource; import io.github.cdelmas.spike.vertx.hello.HelloResource; import io.github.cdelmas.spike.vertx.infrastructure.auth.BearerAuthHandler; import io.github.cdelmas.spike.vertx.infrastructure.auth.FacebookOauthTokenVerifier; import io.vertx.core.Vertx; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientOptions; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerOptions; import io.vertx.core.json.Json; import io.vertx.core.net.JksOptions; import io.vertx.ext.web.Router; import io.vertx.ext.web.handler.AuthHandler; import io.vertx.ext.web.handler.BodyHandler; import static java.util.stream.Collectors.toList;
/* Copyright 2015 Cyril Delmas 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 io.github.cdelmas.spike.vertx; public class Main { public static void main(String[] args) { // TODO start a vertx instance // deploy verticles / one per resource in this case Json.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); Vertx vertx = Vertx.vertx(); HttpClientOptions clientOptions = new HttpClientOptions() .setSsl(true) .setTrustStoreOptions(new JksOptions() .setPath(System.getProperty("javax.net.ssl.trustStore")) .setPassword(System.getProperty("javax.net.ssl.trustStorePassword"))); HttpClient httpClient = vertx.createHttpClient(clientOptions); Router router = Router.router(vertx); AuthHandler auth = new BearerAuthHandler(new FacebookOauthTokenVerifier(httpClient)); router.route("/*").handler(auth); HelloResource helloResource = new HelloResource(httpClient); router.get("/hello").produces("text/plain").handler(helloResource::hello); CarRepository carRepository = new InMemoryCarRepository();
CarsResource carsResource = new CarsResource(carRepository);
4
asascience-open/ncSOS
src/main/java/com/asascience/ncsos/outputformatter/go/JsonFormatter.java
[ "public class Grid extends baseCDMClass implements iStationData {\n\n public static final String DEPTH = \"depth\";\n public static final String LAT = \"latitude\";\n public static final String LON = \"longitude\";\n private List<String> stationNameList;\n private List<String> stationDescripList;\n ...
import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import ucar.nc2.constants.AxisType; import ucar.nc2.dataset.CoordinateAxis; import com.asascience.ncsos.cdmclasses.Grid; import com.asascience.ncsos.cdmclasses.TimeSeriesProfile; import com.asascience.ncsos.cdmclasses.baseCDMClass; import com.asascience.ncsos.go.GetObservationRequestHandler; import com.asascience.ncsos.outputformatter.OutputFormatter; import com.asascience.ncsos.service.BaseRequestHandler; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper;
package com.asascience.ncsos.outputformatter.go; public class JsonFormatter extends OutputFormatter { private GetObservationRequestHandler handler; public JsonFormatter( GetObservationRequestHandler getObservationRequestHandler) { this.handler = getObservationRequestHandler; } public void createDataStructs(Map<String, Map<String, JsonFormatterData>> stationData, Map<String, Integer> stationToNum){ List<String> obsProps = handler.getRequestedObservedProperties();
String time_keyname = baseCDMClass.TIME_STR.replace("=","");
2
olgamiller/SSTVEncoder2
app/src/main/java/om/sstvencoder/Encoder.java
[ "public interface IMode {\n void init();\n\n int getProcessCount();\n\n boolean process();\n\n void finish(boolean cancel);\n}", "public interface IModeInfo {\n int getModeName();\n\n String getModeClassName();\n\n ModeSize getModeSize();\n}", "public final class ModeFactory {\n public s...
import android.graphics.Bitmap; import java.util.LinkedList; import java.util.List; import om.sstvencoder.ModeInterfaces.IMode; import om.sstvencoder.ModeInterfaces.IModeInfo; import om.sstvencoder.Modes.ModeFactory; import om.sstvencoder.Output.IOutput; import om.sstvencoder.Output.OutputFactory; import om.sstvencoder.Output.WaveFileOutputContext;
/* Copyright 2017 Olga Miller <olga.rgb@gmail.com> 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 om.sstvencoder; // Creates IMode instance class Encoder { private final MainActivityMessenger mMessenger; private final Thread mThread; private Thread mSaveWaveThread; private final List<IMode> mQueue; private final ProgressBarWrapper mProgressBar, mProgressBar2; private boolean mQuit, mStop; private Class<?> mModeClass; Encoder(MainActivityMessenger messenger, ProgressBarWrapper progressBar, ProgressBarWrapper progressBar2) { mMessenger = messenger; mProgressBar = progressBar; mProgressBar2 = progressBar2; mQueue = new LinkedList<>(); mQuit = false; mStop = false; mModeClass = ModeFactory.getDefaultMode(); mThread = new Thread() { @Override public void run() { while (true) { IMode mode; synchronized (this) { while (mQueue.isEmpty() && !mQuit) { try { wait(); } catch (Exception ignore) { } } if (mQuit) return; mStop = false; mode = mQueue.remove(0); } mode.init(); mProgressBar.begin(mode.getProcessCount(), "Sending..."); while (mode.process()) { mProgressBar.step(); synchronized (this) { if (mQuit || mStop) break; } } mode.finish(mStop); mProgressBar.end(); } } }; mThread.start(); } boolean setMode(String className) { try { mModeClass = Class.forName(className); } catch (Exception ignore) { return false; } return true; } IModeInfo getModeInfo() { return ModeFactory.getModeInfo(mModeClass); } IModeInfo[] getModeInfoList() { return ModeFactory.getModeInfoList(); } void play(Bitmap bitmap) {
IOutput output = OutputFactory.createOutputForSending();
3
ofelbaum/spb-transport-app
src/main/java/com/emal/android/transport/spb/activity/SettingsFragment.java
[ "public enum VehicleType {\n BUS(\"vehicle_bus\", \"0\", \"A\", false, Color.BLUE),\n TROLLEY(\"vehicle_trolley\", \"1\", \"Ш\", true, Color.GREEN),\n TRAM(\"vehicle_tram\", \"2\", \"T\", false, Color.RED),\n SHIP(\"vehicle_ship\", \"46\", \"S\", false, Color.YELLOW);\n\n private String code;\n pr...
import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.preference.*; import android.util.Log; import com.emal.android.transport.spb.R; import android.os.Bundle; import com.emal.android.transport.spb.VehicleType; import com.emal.android.transport.spb.model.ApplicationParams; import com.emal.android.transport.spb.model.Theme; import com.emal.android.transport.spb.utils.Constants; import com.emal.android.transport.spb.task.LoadAddressTask; import com.emal.android.transport.spb.component.SeekBarDialogPreference; import com.google.android.maps.GeoPoint; import java.util.*;
package com.emal.android.transport.spb.activity; /** * User: alexey.emelyanenko@gmail.com * Date: 5/21/13 12:40 AM */ public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = SettingsFragment.class.getName(); private static final String MAP_SYNC_TIME = "map_sync_time"; private static final String MAP_TYPE = "map_type"; private static final String VEHICLE_TYPES = "vehicle_types"; private static final String MY_PLACE = "my_place"; private static final String MAP_SHOW_TRAFFIC = "map_show_traffic"; private static final String APP_THEME = "app_theme"; private static final String ICON_SIZE = "icon_size"; private ListPreference syncTimePref; private MultiSelectListPreference vehicleTypes; private ListPreference mapTypePref; private ListPreference appTheme;
private ApplicationParams appParams;
1
jbossas/jboss-vfs
src/test/java/org/jboss/test/vfs/util/automount/AutomounterTestCase.java
[ "public abstract class AbstractVFSTest extends BaseTestCase {\n protected TempFileProvider provider;\n\n public AbstractVFSTest(String name) {\n super(name);\n }\n\n protected void setUp() throws Exception {\n super.setUp();\n\n provider = TempFileProvider.create(\"test\", new Sched...
import java.io.File; import org.jboss.test.vfs.AbstractVFSTest; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.util.automount.Automounter; import org.jboss.vfs.util.automount.MountOption; import org.jboss.vfs.util.automount.MountOwner; import org.jboss.vfs.util.automount.SimpleMountOwner; import org.jboss.vfs.util.automount.VirtualFileOwner;
/* * JBoss, Home of Professional Open Source * Copyright 2009, JBoss Inc., and individual contributors as indicated * by the @authors tag. * * 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.jboss.test.vfs.util.automount; /** * Test for {@link Automounter} * * @author <a href="jbailey@redhat.com">John Bailey</a> */ public class AutomounterTestCase extends AbstractVFSTest { public AutomounterTestCase(String name) { super(name); } public void testMountAndCleanup() throws Exception { VirtualFile virtualFile = getVirtualFile("/vfs/test/simple.ear"); MountOwner owner = new VirtualFileOwner(virtualFile); Automounter.mount(owner, virtualFile); assertTrue(Automounter.isMounted(virtualFile)); Automounter.cleanup(owner); assertFalse(Automounter.isMounted(virtualFile)); } public void testCleanupWithOwner() throws Exception { VirtualFile earVirtualFile = getVirtualFile("/vfs/test/simple.ear"); Automounter.mount(earVirtualFile); VirtualFileOwner owner = new VirtualFileOwner(earVirtualFile); VirtualFile jarVirtualFile = earVirtualFile.getChild("archive.jar"); Automounter.mount(owner, jarVirtualFile); VirtualFile warVirtualFile = earVirtualFile.getChild("simple.war"); Automounter.mount(owner, warVirtualFile); assertTrue(Automounter.isMounted(earVirtualFile)); assertTrue(Automounter.isMounted(warVirtualFile)); assertTrue(Automounter.isMounted(jarVirtualFile)); Automounter.cleanup(owner); assertFalse(Automounter.isMounted(earVirtualFile)); assertFalse(Automounter.isMounted(warVirtualFile)); assertFalse(Automounter.isMounted(jarVirtualFile)); } public void testCleanupRecursive() throws Exception { VirtualFile earVirtualFile = getVirtualFile("/vfs/test/simple.ear"); Automounter.mount(earVirtualFile); VirtualFile jarVirtualFile = earVirtualFile.getChild("archive.jar"); Automounter.mount(jarVirtualFile); VirtualFile warVirtualFile = earVirtualFile.getChild("simple.war"); Automounter.mount(warVirtualFile); assertTrue(Automounter.isMounted(earVirtualFile)); assertTrue(Automounter.isMounted(warVirtualFile)); assertTrue(Automounter.isMounted(jarVirtualFile)); Automounter.cleanup(new VirtualFileOwner(earVirtualFile)); assertFalse(Automounter.isMounted(earVirtualFile)); assertFalse(Automounter.isMounted(warVirtualFile)); assertFalse(Automounter.isMounted(jarVirtualFile)); } public void testCleanupRefereces() throws Exception { VirtualFile earVirtualFile = getVirtualFile("/vfs/test/simple.ear"); Automounter.mount(earVirtualFile); VirtualFileOwner owner = new VirtualFileOwner(earVirtualFile); VirtualFile jarVirtualFile = getVirtualFile("/vfs/test/jar1.jar"); Automounter.mount(owner, jarVirtualFile); VirtualFile warVirtualFile = getVirtualFile("/vfs/test/filesonly.war"); Automounter.mount(owner, warVirtualFile); assertTrue(Automounter.isMounted(earVirtualFile)); assertTrue(Automounter.isMounted(warVirtualFile)); assertTrue(Automounter.isMounted(jarVirtualFile)); VirtualFile otherEarVirtualFile = getVirtualFile("/vfs/test/spring-ear.ear"); Automounter.mount(otherEarVirtualFile, jarVirtualFile); Automounter.cleanup(owner); assertFalse(Automounter.isMounted(earVirtualFile)); assertFalse(Automounter.isMounted(warVirtualFile)); assertTrue("Should not have unmounted the reference from two locations", Automounter.isMounted(jarVirtualFile)); Automounter.cleanup(otherEarVirtualFile); assertFalse(Automounter.isMounted(jarVirtualFile)); } public void testCleanupReferecesSameVF() throws Exception { VirtualFile earVirtualFile = getVirtualFile("/vfs/test/simple.ear"); Automounter.mount(earVirtualFile); VirtualFileOwner owner = new VirtualFileOwner(earVirtualFile); VirtualFile jarVirtualFile = getVirtualFile("/vfs/test/jar1.jar"); Automounter.mount(owner, jarVirtualFile); VirtualFileOwner otherOwner = new VirtualFileOwner(earVirtualFile); Automounter.mount(otherOwner, jarVirtualFile); Automounter.cleanup(owner); assertFalse("Should have been unmounted since the VirtualFile is the same", Automounter.isMounted(jarVirtualFile)); } public void testCleanupReferecesSimpleOwner() throws Exception { MountOwner owner = new SimpleMountOwner(new Object()); VirtualFile jarVirtualFile = getVirtualFile("/vfs/test/jar1.jar"); Automounter.mount(owner, jarVirtualFile); MountOwner otherOwner = new SimpleMountOwner(new Object()); Automounter.mount(otherOwner, jarVirtualFile); Automounter.cleanup(owner); assertTrue("Should not have unmounted the reference from two locations", Automounter.isMounted(jarVirtualFile)); Automounter.cleanup(otherOwner); assertFalse(Automounter.isMounted(jarVirtualFile)); } public void testCleanupReferecesSimpleOwnerSameObj() throws Exception { Object ownerObject = new Object(); VirtualFile jarVirtualFile = getVirtualFile("/vfs/test/jar1.jar"); Automounter.mount(ownerObject, jarVirtualFile); Automounter.mount(ownerObject, jarVirtualFile); Automounter.cleanup(ownerObject); assertFalse("Should have been unmounted since the owner object is the same", Automounter.isMounted(jarVirtualFile)); } public void testMountWithCopy() throws Exception { VirtualFile jarVirtualFile = getVirtualFile("/vfs/test/jar1.jar"); File originalFile = jarVirtualFile.getPhysicalFile();
Automounter.mount(jarVirtualFile, MountOption.COPY);
3
JEEventStore/JEEventStore
persistence-jpa/src/test/java/org/jeeventstore/persistence/jpa/EventStorePersistenceJPATest.java
[ "@Singleton\n@LocalBean\n@Startup\npublic class PersistenceTestHelper {\n\n @EJB(lookup = \"java:global/test/ejb/EventStorePersistence\")\n private EventStorePersistence persistence;\n\n private static final int COUNT_TEST = 150;\n\n private List<ChangeSet> data_default = new ArrayList<ChangeSet>();\n ...
import org.jeeventstore.persistence.AbstractPersistenceTest; import org.jeeventstore.serialization.XMLSerializer; import org.jeeventstore.tests.DefaultDeployment; import static org.testng.Assert.*; import org.testng.annotations.Test; import org.jeeventstore.persistence.PersistenceTestHelper; import java.io.File; import javax.ejb.EJBTransactionRequiredException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jeeventstore.StreamNotFoundException; import org.jeeventstore.TestUTF8Utils;
/* * Copyright (c) 2013-2014 Red Rainbow IT Solutions GmbH, Germany * * 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 org.jeeventstore.persistence.jpa; public class EventStorePersistenceJPATest extends AbstractPersistenceTest { @Deployment public static EnterpriseArchive deployment() { EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "test.ear"); DefaultDeployment.addDependencies(ear, "org.jeeventstore:jeeventstore-persistence-jpa", false); ear.addAsModule(ShrinkWrap.create(JavaArchive.class, "ejb.jar") .addAsManifestResource(new File("src/test/resources/META-INF/beans.xml")) .addAsManifestResource(new File("src/test/resources/META-INF/persistence.xml")) .addAsManifestResource(new File( "src/test/resources/META-INF/ejb-jar-EventStorePersistenceJPATest.xml"), "ejb-jar.xml") .addClass(XMLSerializer.class)
.addClass(TestUTF8Utils.class)
2
NicolaasWeideman/RegexStaticAnalysis
src/main/java/analysis/ExploitStringBuilder.java
[ "public static class IdaSpecialTransitionLabel implements TransitionLabel {\n\n\t@Override\n\tpublic boolean matches(String word) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean matches(TransitionLabel tl) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic TransitionLabel intersection(TransitionLabel tl)...
import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import analysis.NFAAnalyser.IdaSpecialTransitionLabel; import analysis.NFAAnalyserInterface.EdaAnalysisResultsESCC; import analysis.NFAAnalyserInterface.EdaAnalysisResultsFilter; import analysis.NFAAnalyserInterface.EdaAnalysisResultsParallel; import analysis.NFAAnalyserInterface.IdaAnalysisResultsIda; import nfa.NFAGraph; import nfa.NFAEdge; import nfa.NFAVertexND; import nfa.transitionlabel.*; import nfa.transitionlabel.TransitionLabel.TransitionType;
package analysis; public class ExploitStringBuilder implements ExploitStringBuilderInterface<EdaAnalysisResults, IdaAnalysisResults> { @Override public ExploitString buildEdaExploitString(EdaAnalysisResults results) throws InterruptedException { switch (results.edaCase) { case PARALLEL: return getParallelExploitString((EdaAnalysisResultsParallel) results); case ESCC: return getEsccExploitString((EdaAnalysisResultsESCC) results); case FILTER:
return getFilterExploitString((EdaAnalysisResultsFilter) results);
2
hecoding/Pac-Man
src/jeco/core/algorithm/moga/NSGAII.java
[ "public abstract class Algorithm<V extends Variable<?>> extends AlgObservable {\n\n protected Problem<V> problem = null;\n // Attribute to stop execution of the algorithm.\n protected boolean stop = false;\n \n /**\n * Allows to stop execution after finishing the current generation; must be\n * taken into ...
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.logging.Logger; import jeco.core.algorithm.Algorithm; import jeco.core.operator.assigner.CrowdingDistance; import jeco.core.operator.assigner.FrontsExtractor; import jeco.core.operator.comparator.ComparatorNSGAII; import jeco.core.operator.comparator.SolutionDominance; import jeco.core.operator.crossover.CrossoverOperator; import jeco.core.operator.mutation.MutationOperator; import jeco.core.operator.selection.SelectionOperator; import jeco.core.problem.Problem; import jeco.core.problem.Solution; import jeco.core.problem.Solutions; import jeco.core.problem.Variable; import jeco.core.util.Maths;
package jeco.core.algorithm.moga; /** * * * Input parameters: - MAX_GENERATIONS - MAX_POPULATION_SIZE * * Operators: - CROSSOVER: Crossover operator - MUTATION: Mutation operator - * SELECTION: Selection operator * * @author José L. Risco-Martín * */ public class NSGAII<T extends Variable<?>> extends Algorithm<T> { private static final Logger logger = Logger.getLogger(NSGAII.class.getName()); ///////////////////////////////////////////////////////////////////////// protected int maxGenerations; protected int maxPopulationSize; ///////////////////////////////////////////////////////////////////////// protected Comparator<Solution<T>> dominance; protected int currentGeneration; protected Solutions<T> population; public Solutions<T> getPopulation() { return population; } protected MutationOperator<T> mutationOperator;
protected CrossoverOperator<T> crossoverOperator;
1
BlackCraze/GameResourceBot
src/main/java/de/blackcraze/grb/commands/concrete/Group.java
[ "public interface BaseCommand {\r\n\r\n void run(Scanner scanner, Message message);\r\n\r\n default String help(Message message) {\r\n String className = this.getClass().getSimpleName();\r\n String key = className.toUpperCase();\r\n return Resource.getHelp(key, getResponseLocale(message),...
import de.blackcraze.grb.commands.BaseCommand; import de.blackcraze.grb.core.Speaker; import de.blackcraze.grb.i18n.Resource; import de.blackcraze.grb.model.PrintableTable; import de.blackcraze.grb.model.entity.StockType; import de.blackcraze.grb.model.entity.StockTypeGroup; import de.blackcraze.grb.util.PrintUtils; import de.blackcraze.grb.util.StockTypeComparator; import de.blackcraze.grb.util.wagu.Block; import net.dv8tion.jda.api.entities.Message; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Scanner; import static de.blackcraze.grb.util.CommandUtils.getResponseLocale; import static de.blackcraze.grb.util.CommandUtils.parseGroupName; import static de.blackcraze.grb.util.InjectorUtils.getMateDao; import static de.blackcraze.grb.util.InjectorUtils.getStockTypeDao; import static de.blackcraze.grb.util.InjectorUtils.getStockTypeGroupDao;
Speaker.err(message, msg); } }; public static final BaseCommand groupAdd = (Scanner scanner, Message message) -> { Optional<StockTypeGroup> groupOpt = getTargetGroup(scanner, message, "ADD"); if (groupOpt.isPresent()) { List<StockType> stockTypes = getTargetStockTypes(scanner, message, "ADD"); StockTypeGroup group = groupOpt.get(); if (!stockTypes.isEmpty()) { List<StockType> types = group.getTypes(); if (types == null) { types = new ArrayList<>(); group.setTypes(types); } types.addAll(stockTypes); // removing doubles types = new ArrayList<>(new HashSet<>(types)); group.setTypes(types); getStockTypeGroupDao().update(group); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } } }; public static final BaseCommand groupRemove = (Scanner scanner, Message message) -> { Optional<StockTypeGroup> groupOpt = getTargetGroup(scanner, message, "REMOVE"); if (groupOpt.isPresent()) { List<StockType> stockTypes = getTargetStockTypes(scanner, message, "REMOVE"); StockTypeGroup group = groupOpt.get(); if (!stockTypes.isEmpty()) { List<StockType> types = group.getTypes(); if (types == null) { group.setTypes(new ArrayList<>()); } group.getTypes().removeAll(stockTypes); getStockTypeGroupDao().update(group); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } } }; public static final BaseCommand groupDelete = (Scanner scanner, Message message) -> { List<String> groupNames = parseGroupName(scanner); List<String> unknown = new ArrayList<>(); for (String groupName : groupNames) { Optional<StockTypeGroup> group = getStockTypeGroupDao().findByName(groupName); if (group.isPresent()) { getStockTypeGroupDao().delete(group.get()); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } else { unknown.add(groupName); } } if (groupNames.isEmpty()) { Speaker.err(message, Resource.getError("GROUP_DELETE_UNKNOWN", getResponseLocale(message))); } if (!unknown.isEmpty()) { String msg = String.format( Resource.getError("GROUP_DELETE_UNKNOWN", getResponseLocale(message)), unknown.toString()); Speaker.err(message, msg); } }; public static final BaseCommand groupRename = (Scanner scanner, Message message) -> { Locale locale = getResponseLocale(message); Optional<StockTypeGroup> groupOpt = getTargetGroup(scanner, message, "RENAME"); if (groupOpt.isPresent()) { if (scanner.hasNext()) { String groupName = scanner.next(); Optional<StockTypeGroup> newName = getStockTypeGroupDao().findByName(groupName); if (newName.isPresent()) { String msg = String.format( /* TODO maybe a standalone error message? */ Resource.getError("GROUP_CREATE_IN_USE", locale), groupName); Speaker.err(message, msg); } else { StockTypeGroup group = groupOpt.get(); group.setName(groupName); getStockTypeGroupDao().update(group); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } } else { Speaker.err(message, Resource.getError("GROUP_RENAME_UNKNOWN", locale)); } } }; public static final BaseCommand groupList = (Scanner scanner, Message message) -> { Locale locale = getResponseLocale(message); List<String> groupNames = parseGroupName(scanner); List<StockTypeGroup> groups; if (groupNames.isEmpty()) { groups = getStockTypeGroupDao().findAll(); } else { groups = getStockTypeGroupDao().findByNameLike(groupNames); } List<List<String>> rows = new ArrayList<>(); for (StockTypeGroup stockTypeGroup : groups) { List<StockType> types = stockTypeGroup.getTypes(); String amount = String.format(locale, "%,d", types != null ? types.size() : 0); rows.add(Arrays.asList(stockTypeGroup.getName(), amount)); if (types != null) { types.sort(new StockTypeComparator(locale)); for (Iterator<StockType> it2 = types.iterator(); it2.hasNext();) { StockType stockType = it2.next(); String localisedStockName = Resource.getItem(stockType.getName(), locale); String tree = it2.hasNext() ? "├─ " : "└─ "; rows.add(Arrays.asList(tree + localisedStockName, " ")); } } } if (rows.isEmpty()) { rows.add(Arrays.asList(" ", " ")); } List<String> titles = Arrays.asList(Resource.getHeader("NAME", locale), Resource.getHeader("QUANTITY", locale)); String header = Resource.getHeader("GROUP_LIST_HEADER", locale); List<Integer> aligns = Arrays.asList(Block.DATA_MIDDLE_LEFT, Block.DATA_BOTTOM_RIGHT); List<String> footer = Collections.emptyList(); PrintableTable table = new PrintableTable(header, footer, titles, rows, aligns);
Speaker.sayCode(message.getChannel(), PrintUtils.prettyPrint(table));
3
chedim/minedriod
src/main/java/com/onkiup/minedroid/gui/views/CheckBox.java
[ "public interface Context {\n /**\n * @return Context id\n */\n int contextId();\n\n}", "@SideOnly(Side.CLIENT)\npublic class GuiManager {\n /**\n * Current MineDroid theme\n */\n public static HashMap<Integer, Style> themes = new HashMap<Integer, Style>();\n\n /**\n * Minecraft...
import com.onkiup.minedroid.Context; import com.onkiup.minedroid.gui.GuiManager; import com.onkiup.minedroid.gui.XmlHelper; import com.onkiup.minedroid.gui.drawables.Drawable; import com.onkiup.minedroid.gui.drawables.TextDrawable; import com.onkiup.minedroid.gui.events.Event; import com.onkiup.minedroid.gui.events.MouseEvent; import com.onkiup.minedroid.gui.primitives.Rect; import com.onkiup.minedroid.gui.resources.Style;
package com.onkiup.minedroid.gui.views; /** * Created by chedim on 5/31/15. */ public class CheckBox extends ContentView { protected Drawable check; protected boolean value; protected TextDrawable label;
public CheckBox(Context context) {
0
CMPUT301F14T14/android-question-answer-app
QuestionApp/src/ca/ualberta/cs/cmput301f14t14/questionapp/MainActivity.java
[ "public interface Callback<T> {\n\t/**\n\t * Run by the onPostExecute method of a Task\n\t * @param object\n\t */\n\tpublic void run(T object);\n}", "public class ClientData {\n\n\tprivate static final String PREF_SET = \"cs.ualberta.cs.cmput301f14t14.questionapp.prefs\";\n\tprivate static final String VAL_USERNA...
import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.UUID; import ca.ualberta.cs.cmput301f14t14.questionapp.data.Callback; import ca.ualberta.cs.cmput301f14t14.questionapp.data.ClientData; import ca.ualberta.cs.cmput301f14t14.questionapp.data.DataManager; import ca.ualberta.cs.cmput301f14t14.questionapp.model.Image; import ca.ualberta.cs.cmput301f14t14.questionapp.model.Question; import ca.ualberta.cs.cmput301f14t14.questionapp.view.AddImage; import ca.ualberta.cs.cmput301f14t14.questionapp.view.AddQuestionDialogFragment; import ca.ualberta.cs.cmput301f14t14.questionapp.view.QuestionListAdapter; import ca.ualberta.cs.cmput301f14t14.questionapp.view.SearchQueryDialogFragment; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.app.FragmentManager; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import android.content.Context;
package ca.ualberta.cs.cmput301f14t14.questionapp; public class MainActivity extends Activity { private DataManager dataManager; private QuestionListAdapter qla = null; private List<Question> qList = null; private ClientData cd = null; private Callback<List<Question>> listCallback = null; private Callback<Question> favouriteQuestionCallback = null; private Callback<Question> readLaterQuestionCallback = null; private AddImage AI = new AddImage(); private static final int CAMERA = 1; private static final int ADD_IMAGE = 2;
public Image img;
3
Robyer/Gamework
GameworkApp/src/cz/robyer/gamework/app/activity/GameMapActivity.java
[ "public class GameEvent implements Serializable {\n\n\tprivate static final long serialVersionUID = -624979683919801177L;\n\n\tpublic enum EventType {\n\t\tGAME_START,\t\t\t/** Game start/continue. */\n\t\tGAME_PAUSE,\t\t\t/** Event for pausing game service. */\n\t\tGAME_WIN,\t\t\t/** Player won the game. */\n\t\tG...
import java.util.List; import java.util.Map; import android.graphics.Color; import android.location.Location; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolygonOptions; import cz.robyer.gamework.game.GameEvent; import cz.robyer.gamework.game.GameService; import cz.robyer.gamework.scenario.Scenario; import cz.robyer.gamework.scenario.area.Area; import cz.robyer.gamework.scenario.area.MultiPointArea; import cz.robyer.gamework.scenario.area.PointArea; import cz.robyer.gamework.scenario.area.SoundArea; import cz.robyer.gamework.utils.GPoint; import cz.robyer.gamework.app.R;
package cz.robyer.gamework.app.activity; /** * Represents game map with showed areas and player position. * @author Robert Pösel */ public class GameMapActivity extends BaseGameActivity { private static final String TAG = GameMapActivity.class.getSimpleName(); private GoogleMap map; private Marker playerMarker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game_map); initButtons(); } @Override protected void onResume() { super.onResume(); if (!GameService.isRunning()) return; final GameService game = getGame(); if (map == null) { map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); if (map != null) { Scenario scenario = null; if (game != null) scenario = game.getScenario(); if (scenario != null) { Map<String, Area> areas = scenario.getAreas(); for (Area a : areas.values()) { Log.d(TAG, "Draw area " + a.getId()); if (a instanceof PointArea || a instanceof SoundArea) { PointArea area = (PointArea)a; CircleOptions circle = new CircleOptions(); circle.center(toLatLng(area.getPoint())); circle.radius(area.getRadius()); circle.strokeWidth(2); circle.fillColor(Color.argb(40, 255, 0, 0)); map.addCircle(circle); } else if (a instanceof MultiPointArea) { MultiPointArea area = (MultiPointArea)a; PolygonOptions polygon = new PolygonOptions(); List<GPoint> points = area.getPoints(); for (GPoint p : points) { polygon.add(toLatLng(p)); } polygon.strokeWidth(2); polygon.fillColor(Color.argb(40, 0, 255, 0)); map.addPolygon(polygon); } } } map.setOnMapLongClickListener(new OnMapLongClickListener() { @Override public void onMapLongClick(LatLng point) { Toast.makeText(GameMapActivity.this, "Player location set.", Toast.LENGTH_SHORT).show(); Location location = new Location("custom"); location.setLatitude(point.latitude); location.setLongitude(point.longitude); game.onLocationChanged(location); } }); } } if (game != null) updateMarker(game.getLocation()); } /** * Checks game events and enabled/disables player location layer. */
public void receiveEvent(final GameEvent event) {
0
gill3s/opentipbot
opentipbot-service/src/main/java/opentipbot/service/OpenTipBotUserService.java
[ "@Entity\n@Table(name = \"opentipbot_command\")\npublic class OpenTipBotCommand extends BaseEntity<Long> {\n\n @Id\n @GeneratedValue\n private Long id;\n\n @NotNull\n private OpenTipBotCommandEnum opentipbotCommandEnum;\n\n private String fromUserName;\n\n private String toUserName;\n\n priv...
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.social.twitter.api.impl.TwitterTemplate; import org.springframework.stereotype.Service; import opentipbot.persistence.model.OpenTipBotCommand; import opentipbot.persistence.model.OpenTipBotUser; import opentipbot.persistence.repository.OpenTipBotCommandRepository; import opentipbot.persistence.repository.OpenTipBotUserRepository; import opentipbot.service.exception.OpenTipBotServiceException; import java.util.List;
package opentipbot.service; @Service public class OpenTipBotUserService { @Autowired private OpenTipBotUserRepository opentipbotUserRepository; @Autowired private OpenTipBotCommandRepository opentipbotCommandRepository; @Autowired private BitcoinService bitcoinService; @Autowired Environment env; @Autowired TwitterTemplate twitterTemplate; public OpenTipBotUser findByTwitterIdentifier(String twitterIndentifier){ return opentipbotUserRepository.findByTwitterIdentifier(twitterIndentifier); } public OpenTipBotUser findByUserName(String userName){ return opentipbotUserRepository.findByUserName(userName); }
public void createNewOpenTipBotUser(OpenTipBotUser opentipbotUser) throws OpenTipBotServiceException {
4
jansoren/akka-persistence-java-example
mymicroservice-server/src/main/java/no/jansoren/mymicroservice/MymicroserviceApplication.java
[ "public class EventStore {\n\n private static final Logger LOG = LoggerFactory.getLogger(EventStore.class);\n\n private ActorRef persistenceActor;\n private LeveldbReadJournal readJournal;\n private Map<Class<? extends Projection>, Projection> projections = new HashMap<>();\n\n public EventStore(Mymi...
import io.dropwizard.Application; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import no.jansoren.mymicroservice.eventsourcing.EventStore; import no.jansoren.mymicroservice.eventsourcing.ShutdownManager; import no.jansoren.mymicroservice.health.ActorSystemHealthCheck; import no.jansoren.mymicroservice.monitoring.ApplicationIsStartingCommand; import no.jansoren.mymicroservice.monitoring.MonitoringResource; import no.jansoren.mymicroservice.something.SomethingResource; import no.jansoren.mymicroservice.somethingelse.SomethingElseResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package no.jansoren.mymicroservice; public class MymicroserviceApplication extends Application<MymicroserviceConfiguration> { private static final Logger LOG = LoggerFactory.getLogger(MymicroserviceApplication.class); public static final String APPLICATION_NAME = "Mymicroservice"; private EventStore eventStore; public static void main(final String[] args) throws Exception { new MymicroserviceApplication().run(args); } @Override public String getName() { return APPLICATION_NAME; } @Override public void initialize(final Bootstrap<MymicroserviceConfiguration> bootstrap) { } @Override public void run(final MymicroserviceConfiguration configuration, final Environment environment) { eventStore = new EventStore(configuration); environment.healthChecks().register("ActorSystemHealthCheck", new ActorSystemHealthCheck(eventStore)); environment.lifecycle().manage(new ShutdownManager(eventStore)); environment.jersey().register(new MymicroserviceResource(getName())); environment.jersey().register(new MonitoringResource(eventStore)); environment.jersey().register(new SomethingResource(eventStore)); environment.jersey().register(new SomethingElseResource(eventStore));
eventStore.tell(new ApplicationIsStartingCommand(), null);
3
dgrunwald/arden2bytecode
src/arden/tests/ActionTests.java
[ "public final class Compiler {\n\tprivate boolean isDebuggingEnabled = false;\n\tprivate String sourceFileName;\n\n\t/** Enables debugging for the code being produced. */\n\tpublic void enableDebugging(String sourceFileName) {\n\t\tthis.isDebuggingEnabled = true;\n\t\tthis.sourceFileName = sourceFileName;\n\t}\n\n\...
import java.io.InputStreamReader; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import arden.compiler.Compiler; import arden.compiler.CompilerException; import arden.runtime.ArdenRunnable; import arden.runtime.ArdenString; import arden.runtime.ArdenValue; import arden.runtime.ExecutionContext; import arden.runtime.MedicalLogicModule; import org.junit.Assert; import org.junit.Test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream;
// arden2bytecode // Copyright (c) 2010, Daniel Grunwald // 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 owner 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 arden.tests; public class ActionTests { private static String inputStreamToString(InputStream in) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append("\n"); } bufferedReader.close(); return stringBuilder.toString(); } public static MedicalLogicModule parseTemplate(String dataCode, String logicCode, String actionCode) throws CompilerException { try { InputStream s = ActionTests.class.getResourceAsStream("ActionTemplate.mlm"); String fullCode = inputStreamToString(s).replace("$ACTION", actionCode).replace("$DATA", dataCode).replace( "$LOGIC", logicCode);
Compiler c = new Compiler();
0
dariober/ASCIIGenome
src/main/java/tracks/TrackSeqRegex.java
[ "public class InvalidColourException extends Exception {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n}", "public class InvalidGenomicCoordsException extends Exception {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n}", "public class InvalidRecord...
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import exceptions.InvalidColourException; import exceptions.InvalidGenomicCoordsException; import exceptions.InvalidRecordException; import htsjdk.samtools.util.SequenceUtil; import htsjdk.tribble.index.tabix.TabixFormat; import samTextViewer.GenomicCoords; import samTextViewer.Utils; import sortBgzipIndex.MakeTabixIndex;
package tracks; public class TrackSeqRegex extends TrackIntervalFeature { private String seqRegex= "a^"; // Match nothing final private String noRe= "a^"; private boolean isCaseSensitive= false; private boolean isIupac= false; public TrackSeqRegex(GenomicCoords gc) throws ClassNotFoundException, IOException, InvalidGenomicCoordsException, InvalidRecordException, SQLException{ super(gc); this.setGc(gc); this.setFilename(new File(gc.getFastaFile()).getAbsolutePath()); this.setWorkFilename(new File(gc.getFastaFile()).getAbsolutePath()); this.setTrackTag(new File(gc.getFastaFile()).getName()); this.setHideTrack(true); this.setTrackFormat(TrackFormat.BED); } @Override /** Find regex matches and update the screen map. See alos parent method. * */ public void update() throws ClassNotFoundException, IOException, InvalidGenomicCoordsException, InvalidRecordException, SQLException{ this.findRegex(); for(IntervalFeature ift : this.getIntervalFeatureList()){ ift.mapToScreen(this.getGc().getMapping()); } } /** * Find regex matches in current genomic interval and update the IntervalFeature set and list. * */ private void findRegex() throws IOException, InvalidGenomicCoordsException, ClassNotFoundException, InvalidRecordException, SQLException{ // Find matches // ============ Pattern pattern= Pattern.compile(this.seqRegex, Pattern.CASE_INSENSITIVE); if(this.isCaseSensitive){ pattern= Pattern.compile(this.seqRegex); } byte[] seq= this.getGc().getSequenceFromFasta(); Matcher matcher = pattern.matcher(new String(seq)); // One list for matches on forward, one for reverse, one for palindromic Set<String> regionListPos= new HashSet<String>(); Set<String> regionListNeg= new HashSet<String>(); Set<String> regionListPalind= new HashSet<String>(); // Forward match while (matcher.find()) { int matchStart= this.getGc().getFrom() + matcher.start() - 1; int matchEnd= this.getGc().getFrom() + matcher.end() - 1; String reg= this.getGc().getChrom() + "\t" + matchStart + "\t" + matchEnd + "\t" + this.trimMatch(matcher.group(), 100); regionListPos.add(reg); } // Reverse comp match SequenceUtil.reverseComplement(seq); matcher = pattern.matcher(new String(seq)); while (matcher.find()) { int matchStart= this.getGc().getTo() - matcher.end(); int matchEnd= this.getGc().getTo() - matcher.start(); String reg= this.getGc().getChrom() + "\t" + matchStart + "\t" + matchEnd + "\t" + this.trimMatch(matcher.group(), 100); if(regionListPos.contains(reg)){ regionListPos.remove(reg); regionListPalind.add(reg); } else { regionListNeg.add(reg); } } // Prepare tmp file // ================ String tmpname= Utils.createTempFile(".asciigenome.regexMatchTrack", ".tmp.bed", true).getAbsolutePath(); // This is a hack: Copy the newly created tmp file to another file. This overcomes some // permission (?) problems later with the tabix indexing. String regexMatchFile= tmpname.replaceAll("\\.tmp\\.bed$", ".bed"); FileUtils.copyFile(new File(tmpname), new File(regexMatchFile)); new File(tmpname).delete(); new File(regexMatchFile).deleteOnExit(); BufferedWriter wr= new BufferedWriter(new FileWriter(new File(regexMatchFile))); // Write sets of matches to file // ============================= for(String reg : regionListPos){ reg += "\t.\t+\n"; if(this.featureIsVisible(reg)){ wr.write(reg); } } for(String reg : regionListNeg){ reg += "\t.\t-\n"; if(this.featureIsVisible(reg)){ wr.write(reg); } } for(String reg : regionListPalind){ reg += "\t.\t.\n"; if(this.featureIsVisible(reg)){ wr.write(reg); } } wr.close(); // Compress, index, read back as list of IntervalFeatures // ====================================================== File regexMatchBgzip= new File(regexMatchFile + ".gz"); File regexMatchIndex= new File(regexMatchFile + ".gz.tbi"); regexMatchBgzip.deleteOnExit(); regexMatchIndex.deleteOnExit();
new MakeTabixIndex(regexMatchFile, regexMatchBgzip, TabixFormat.BED);
5
OneNoteDev/Android-REST-API-Explorer
app/src/main/java/com/microsoft/o365_android_onenote_rest/SnippetDetailFragment.java
[ "public class AuthenticationManager {\n\n private static final String USER_ID_VAR_NAME = \"userId\";\n\n private static final int PREFERENCES_MODE = Context.MODE_PRIVATE;\n\n private final Activity mActivity;\n\n private final AuthenticationContext mAuthenticationContext;\n\n private final String\n ...
import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.ClipData; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.ClipboardManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.microsoft.AuthenticationManager; import com.microsoft.aad.adal.AuthenticationCallback; import com.microsoft.aad.adal.AuthenticationResult; import com.microsoft.live.LiveAuthClient; import com.microsoft.live.LiveAuthException; import com.microsoft.live.LiveAuthListener; import com.microsoft.live.LiveConnectSession; import com.microsoft.live.LiveStatus; import com.microsoft.o365_android_onenote_rest.snippet.AbstractSnippet; import com.microsoft.o365_android_onenote_rest.snippet.Callback; import com.microsoft.o365_android_onenote_rest.snippet.Input; import com.microsoft.o365_android_onenote_rest.snippet.SnippetContent; import com.microsoft.o365_android_onenote_rest.util.SharedPrefsUtil; import com.microsoft.o365_android_onenote_rest.util.User; import com.microsoft.onenotevos.BaseVO; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; import retrofit.RetrofitError; import retrofit.client.Header; import retrofit.client.Response; import timber.log.Timber; import static android.R.layout.simple_spinner_dropdown_item; import static android.R.layout.simple_spinner_item; import static android.view.View.GONE; import static android.view.View.VISIBLE; import static com.microsoft.o365_android_onenote_rest.R.id.btn_launch_browser; import static com.microsoft.o365_android_onenote_rest.R.id.btn_run; import static com.microsoft.o365_android_onenote_rest.R.id.progressbar; import static com.microsoft.o365_android_onenote_rest.R.id.spinner; import static com.microsoft.o365_android_onenote_rest.R.id.txt_desc; import static com.microsoft.o365_android_onenote_rest.R.id.txt_hyperlink; import static com.microsoft.o365_android_onenote_rest.R.id.txt_input; import static com.microsoft.o365_android_onenote_rest.R.id.txt_request_url; import static com.microsoft.o365_android_onenote_rest.R.id.txt_response_body; import static com.microsoft.o365_android_onenote_rest.R.id.txt_response_headers; import static com.microsoft.o365_android_onenote_rest.R.id.txt_status_code; import static com.microsoft.o365_android_onenote_rest.R.id.txt_status_color; import static com.microsoft.o365_android_onenote_rest.R.string.clippy; import static com.microsoft.o365_android_onenote_rest.R.string.req_url; import static com.microsoft.o365_android_onenote_rest.R.string.response_body; import static com.microsoft.o365_android_onenote_rest.R.string.response_headers;
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. */ package com.microsoft.o365_android_onenote_rest; public class SnippetDetailFragment<T, Result> extends BaseFragment implements Callback<Result>, AuthenticationCallback<AuthenticationResult>, LiveAuthListener { public static final String ARG_ITEM_ID = "item_id"; public static final String ARG_TEXT_INPUT = "TextInput"; public static final String ARG_SPINNER_SELECTION = "SpinnerSelection"; public static final int UNSET = -1; public static final String APP_STORE_URI = "https://play.google.com/store/apps/details?id=com.microsoft.office.onenote"; @InjectView(txt_status_code) protected TextView mStatusCode; @InjectView(txt_status_color) protected View mStatusColor; @InjectView(txt_desc) protected TextView mSnippetDescription; @InjectView(txt_request_url) protected TextView mRequestUrl; @InjectView(txt_response_headers) protected TextView mResponseHeaders; @InjectView(txt_response_body) protected TextView mResponseBody; @InjectView(spinner) protected Spinner mSpinner; @InjectView(txt_input) protected EditText mEditText; @InjectView(progressbar) protected ProgressBar mProgressbar; @InjectView(btn_run) protected Button mRunButton; @Inject protected AuthenticationManager mAuthenticationManager; @Inject protected LiveAuthClient mLiveAuthClient; boolean setupDidRun = false; private AbstractSnippet<T, Result> mItem; public SnippetDetailFragment() { } @OnClick(txt_request_url) public void onRequestUrlClicked(TextView tv) { clipboard(tv); } @OnClick(txt_response_headers) public void onResponseHeadersClicked(TextView tv) { clipboard(tv); } @OnClick(txt_response_body) public void onResponseBodyClicked(TextView tv) { clipboard(tv); } @InjectView(btn_launch_browser) protected Button mLaunchBrowser; private void clipboard(TextView tv) { int which; switch (tv.getId()) { case txt_request_url: which = req_url; break; case txt_response_headers: which = response_headers; break; case txt_response_body: which = response_body; break; default: which = UNSET; } String what = which == UNSET ? "" : getString(which) + " "; what += getString(clippy); Toast.makeText(getActivity(), what, Toast.LENGTH_SHORT).show(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // old way ClipboardManager clipboardManager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); clipboardManager.setText(tv.getText()); } else { clipboard11(tv); } } @TargetApi(11) private void clipboard11(TextView tv) { android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager) getActivity() .getSystemService(Context.CLIPBOARD_SERVICE); ClipData clipData = ClipData.newPlainText("OneNote", tv.getText()); clipboardManager.setPrimaryClip(clipData); } @OnClick(btn_run) public void onRunClicked(Button btn) { mRequestUrl.setText(""); mResponseHeaders.setText(""); mResponseBody.setText(""); displayStatusCode("", getResources().getColor(R.color.transparent)); mProgressbar.setVisibility(VISIBLE); mItem.request(mItem.mService, this); } @OnClick(txt_hyperlink) public void onDocsLinkClicked(TextView textView) { launchUri(Uri.parse(mItem.getUrl())); } private void launchUri(Uri uri) { Intent launchOneNoteExtern = new Intent(Intent.ACTION_VIEW, uri); try { startActivity(launchOneNoteExtern); } catch (ActivityNotFoundException e) { launchOneNoteExtern = new Intent(Intent.ACTION_VIEW, Uri.parse(APP_STORE_URI)); startActivity(launchOneNoteExtern); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments().containsKey(ARG_ITEM_ID)) { mItem = (AbstractSnippet<T, Result>)
SnippetContent.ITEMS.get(getArguments().getInt(ARG_ITEM_ID));
4
Jigsaw-Code/Intra
Android/app/src/main/java/app/intra/net/go/GoVpnAdapter.java
[ "public class CountryCode {\n // The SIM or CDMA country.\n private final @NonNull String deviceCountry;\n\n // The country claimed by the attached cell network.\n private final @NonNull String networkCountry;\n\n public CountryCode(Context context) {\n TelephonyManager telephonyManager =\n (Telephon...
import android.content.Context; import android.content.res.Resources; import android.net.VpnService; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.ParcelFileDescriptor; import android.os.SystemClock; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import app.intra.R; import app.intra.sys.CountryCode; import app.intra.sys.IntraVpnService; import app.intra.sys.PersistentState; import app.intra.sys.VpnController; import app.intra.sys.firebase.AnalyticsWrapper; import app.intra.sys.firebase.LogWrapper; import app.intra.sys.firebase.RemoteConfig; import doh.Transport; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Locale; import protect.Protector; import tun2socks.Tun2socks;
public static GoVpnAdapter establish(@NonNull IntraVpnService vpnService) { ParcelFileDescriptor tunFd = establishVpn(vpnService); if (tunFd == null) { return null; } return new GoVpnAdapter(vpnService, tunFd); } private GoVpnAdapter(IntraVpnService vpnService, ParcelFileDescriptor tunFd) { this.vpnService = vpnService; this.tunFd = tunFd; } public synchronized void start() { connectTunnel(); } private void connectTunnel() { if (tunnel != null) { return; } // VPN parameters final String fakeDns = FAKE_DNS_IP + ":" + DNS_DEFAULT_PORT; // Strip leading "/" from ip:port string. listener = new GoIntraListener(vpnService); String dohURL = PersistentState.getServerUrl(vpnService); try { LogWrapper.log(Log.INFO, LOG_TAG, "Starting go-tun2socks"); Transport transport = makeDohTransport(dohURL); // connectIntraTunnel makes a copy of the file descriptor. tunnel = Tun2socks.connectIntraTunnel(tunFd.getFd(), fakeDns, transport, getProtector(), listener); } catch (Exception e) { LogWrapper.logException(e); VpnController.getInstance().onConnectionStateChanged(vpnService, IntraVpnService.State.FAILING); return; } if (RemoteConfig.getChoirEnabled()) { enableChoir(); } } // Set up failure reporting with Choir. private void enableChoir() { CountryCode countryCode = new CountryCode(vpnService); @NonNull String country = countryCode.getNetworkCountry(); if (country.isEmpty()) { country = countryCode.getDeviceCountry(); } if (country.isEmpty()) { // Country code is mandatory for Choir. Log.i(LOG_TAG, "No country code found"); return; } String file = vpnService.getFilesDir() + File.separator + CHOIR_FILENAME; try { tunnel.enableSNIReporter(file, "intra.metrics.gstatic.com", country); } catch (Exception e) { // Choir setup failure is logged but otherwise ignored, because it does not prevent Intra // from functioning correctly. LogWrapper.logException(e); } } private static ParcelFileDescriptor establishVpn(IntraVpnService vpnService) { try { VpnService.Builder builder = vpnService.newBuilder() .setSession("Intra go-tun2socks VPN") .setMtu(VPN_INTERFACE_MTU) .addAddress(LanIp.GATEWAY.make(IPV4_TEMPLATE), IPV4_PREFIX_LENGTH) .addRoute("0.0.0.0", 0) .addDnsServer(LanIp.DNS.make(IPV4_TEMPLATE)); if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { builder.addDisallowedApplication(vpnService.getPackageName()); } if (VERSION.SDK_INT >= VERSION_CODES.Q) { builder.setMetered(false); // There's no charge for using Intra. } return builder.establish(); } catch (Exception e) { LogWrapper.logException(e); return null; } } private @Nullable Protector getProtector() { if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { // We don't need socket protection in these versions because the call to // "addDisallowedApplication" effectively protects all sockets in this app. return null; } return vpnService; } public synchronized void close() { if (tunnel != null) { tunnel.disconnect(); } if (tunFd != null) { try { tunFd.close(); } catch (IOException e) { LogWrapper.logException(e); } } tunFd = null; } private doh.Transport makeDohTransport(@Nullable String url) throws Exception { @NonNull String realUrl = PersistentState.expandUrl(vpnService, url); String dohIPs = getIpString(vpnService, realUrl); String host = new URL(realUrl).getHost(); long startTime = SystemClock.elapsedRealtime(); final doh.Transport transport; try { transport = Tun2socks.newDoHTransport(realUrl, dohIPs, getProtector(), null, listener); } catch (Exception e) {
AnalyticsWrapper.get(vpnService).logBootstrapFailed(host);
4
Mangopay/cardregistration-android-kit
mangopay/src/main/java/com/mangopay/android/sdk/domain/GetTokenInteractorImpl.java
[ "public interface GetTokenInteractor {\n interface Callback {\n void onGetTokenSuccess(String response);\n\n void onGetTokenError(MangoException error);\n }\n\n void execute(Callback callback, String cardRegistrationURL, String preregistrationData,\n String accessKeyRef, String cardNumber, St...
import com.mangopay.android.sdk.domain.api.GetTokenInteractor; import com.mangopay.android.sdk.domain.service.CardService; import com.mangopay.android.sdk.domain.service.CardServiceImpl; import com.mangopay.android.sdk.domain.service.ServiceCallback; import com.mangopay.android.sdk.executor.Executor; import com.mangopay.android.sdk.executor.Interactor; import com.mangopay.android.sdk.executor.MainThread; import com.mangopay.android.sdk.model.CreateTokenRequest; import com.mangopay.android.sdk.model.exception.MangoException;
package com.mangopay.android.sdk.domain; /** * Get Token request implementation */ public class GetTokenInteractorImpl extends BaseInteractorImpl<CardService> implements Interactor, GetTokenInteractor { private String mRegistrationURL; private String mPreData; private String mAccessKey; private String mCardNumber; private String mExpirationDate; private String mCardCvx; private Callback mCallback; public GetTokenInteractorImpl(Executor executor, MainThread mainThread) { super(executor, mainThread, new CardServiceImpl()); } @Override public void execute(Callback callback, String cardRegistrationURL, String preregistrationData, String accessKeyRef, String cardNumber, String cardExpirationDate, String cardCvx) { validateCallbackSpecified(callback); this.mCallback = callback; this.mRegistrationURL = cardRegistrationURL; this.mPreData = preregistrationData; this.mAccessKey = accessKeyRef; this.mCardNumber = cardNumber; this.mExpirationDate = cardExpirationDate; this.mCardCvx = cardCvx; this.mExecutor.run(this); } @Override public void run() { CreateTokenRequest requestBody = new CreateTokenRequest(mPreData, mAccessKey, mCardNumber, mExpirationDate, mCardCvx);
ServiceCallback<String> callback = new ServiceCallback<String>() {
3
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/parts/Point.java
[ "public class BoneBinding {\n\t/** To be interpreted as unsigned */\n\tpublic byte boneIndex;\n\tpublic float bindingValue;\n\n\tpublic static BoneBinding[] readMultipleFrom(DataInputStream di) throws IOException {\n\t\tBoneBinding[] bindings = new BoneBinding[RawDataV1.MAX_NBR_BONEBINDINGS];\n\t\tint bindIndex;\n\...
import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.vecmath.Point4f; import javax.vecmath.Tuple2f; import javax.vecmath.Tuple3f; import javax.vecmath.Tuple4f; import javax.vecmath.Vector2f; import javax.vecmath.Vector3f; import javax.vecmath.Vector4f; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.BoneBinding; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.TesselationPoint; import com.github.worldsender.mcanm.client.renderer.ITesselator; import com.github.worldsender.mcanm.common.skeleton.IBone; import com.github.worldsender.mcanm.common.skeleton.ISkeleton; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.client.renderer.vertex.VertexFormatElement; import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad;
package com.github.worldsender.mcanm.client.mcanmmodel.parts; public class Point { private static class BoundPoint extends Point { private static class Binding { // Used as a buffer, doesn't requite to always create new // temporaries. Prevents parallelization, though private static Point4f posBuff = new Point4f(); private static Vector3f normBuff = new Vector3f(); private IBone bone; private float strength; public Binding(IBone bone, float strenght) { this.bone = Objects.requireNonNull(bone); this.strength = strenght; } /** * Computes the transformed and weighted position of the given vertex. Adds that to the target vertex. * * @param base * the vertex to transform * @param trgt * the vertex to add to. If null is given, it is just assigned to * @return the final vertex, a new vertex if <code>null</code> was given */ public void addTransformed(Vertex base, Vertex trgt) { Objects.requireNonNull(base); Objects.requireNonNull(trgt); base.getPosition(posBuff); base.getNormal(normBuff); // Transform points with matrix this.bone.transform(posBuff); this.bone.transformNormal(normBuff); posBuff.scale(this.strength); normBuff.scale(this.strength); trgt.offset(posBuff); trgt.addNormal(normBuff); } public void normalize(float sum) { this.strength /= sum; } } private List<Binding> binds; private Vertex transformed;
public BoundPoint(Vector3f pos, Vector3f norm, Vector2f uv, BoneBinding[] readBinds, ISkeleton skelet) {
0
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/handler/MessageEventInterceptor.java
[ "@SuppressWarnings(\"serial\")\npublic class AccessDeniedException extends Exception {\n\n\tpublic AccessDeniedException(String message) {\n\t\tsuper(message);\n\t}\n\t\n}", "@SuppressWarnings(\"serial\")\npublic class InvalidRelationException extends Exception {\n\n\tpublic InvalidRelationException(String messag...
import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.activity.InvalidActivityException; import org.dom4j.Element; import org.jivesoftware.openfire.SessionManager; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.interceptor.PacketInterceptor; import org.jivesoftware.openfire.interceptor.PacketRejectedException; import org.jivesoftware.openfire.session.ClientSession; import org.jivesoftware.openfire.session.Session; import org.jivesoftware.util.Log; import org.onesocialweb.model.activity.ActivityEntry; import org.onesocialweb.model.relation.Relation; import org.onesocialweb.openfire.exception.AccessDeniedException; import org.onesocialweb.openfire.exception.InvalidRelationException; import org.onesocialweb.openfire.handler.activity.PEPActivityHandler; import org.onesocialweb.openfire.manager.ActivityManager; import org.onesocialweb.openfire.manager.RelationManager; import org.onesocialweb.openfire.model.activity.PersistentActivityDomReader; import org.onesocialweb.openfire.model.relation.PersistentRelationDomReader; import org.onesocialweb.xml.dom.ActivityDomReader; import org.onesocialweb.xml.dom.RelationDomReader; import org.onesocialweb.xml.dom4j.ElementAdapter; import org.xmpp.packet.JID; import org.xmpp.packet.Message; import org.xmpp.packet.Packet;
/* * Copyright 2010 Vodafone Group Services Ltd. * * 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.onesocialweb.openfire.handler; public class MessageEventInterceptor implements PacketInterceptor { private final XMPPServer server; public MessageEventInterceptor() { server = XMPPServer.getInstance(); } @SuppressWarnings( { "deprecation", "unchecked" }) public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) throws PacketRejectedException { // We only care for incoming Messages has not yet been processed if (incoming && !processed && packet instanceof Message) { final Message message = (Message) packet; final JID fromJID = message.getFrom(); final JID toJID = message.getTo(); // We are only interested by message to bareJID (we don't touch the one sent to fullJID) if (!toJID.toBareJID().equalsIgnoreCase(toJID.toString())) { return; } // We only care for messaes to local users if (!server.isLocal(toJID) || !server.getUserManager().isRegisteredUser(toJID)) { return; } // We only bother about pubsub events Element eventElement = message.getChildElement("event", "http://jabber.org/protocol/pubsub#event"); if (eventElement == null) { return; } // That contains items Element itemsElement = eventElement.element("items"); if (itemsElement == null || itemsElement.attribute("node") == null) return; // Relating to the microblogging node if (itemsElement.attribute("node").getValue().equals( PEPActivityHandler.NODE)) { Log.debug("Processing an activity event from " + fromJID + " to " + toJID); final ActivityDomReader reader = new PersistentActivityDomReader(); List<Element> items=(List<Element>) itemsElement.elements("item"); if ((items!=null) && (items.size()!=0)){ for (Element itemElement :items) { ActivityEntry activity = reader .readEntry(new ElementAdapter(itemElement .element("entry"))); try { ActivityManager.getInstance().handleMessage( fromJID.toBareJID(), toJID.toBareJID(), activity); } catch (InvalidActivityException e) { throw new PacketRejectedException();
} catch (AccessDeniedException e) {
0
ervinsae/EZCode
app/src/main/java/com/ervin/litepal/MainActivity.java
[ "public class BaseActivity extends AppCompatActivity {\n\n @Override\n public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {\n super.onCreate(savedInstanceState, persistentState);\n\n }\n\n}", "public class HomeActivity extends BaseActivity implements View.OnClickLis...
import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.ervin.litepal.ui.BaseActivity; import com.ervin.litepal.ui.HomeActivity; import com.ervin.litepal.ui.fragment.WelcomeFragments; import com.ervin.litepal.event.BusProvider; import com.ervin.litepal.event.EventBase; import com.ervin.litepal.event.SyncEvent; import com.squareup.otto.Subscribe;
package com.ervin.litepal; public class MainActivity extends BaseActivity implements View.OnClickListener{ Button btn; Button decline; Fragment fragment; private TextView tvTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = (Button) findViewById(R.id.btn); decline = (Button) findViewById(R.id.button_decline); btn.setOnClickListener(this); decline.setOnClickListener(this); tvTitle = (TextView) findViewById(R.id.toolbar_center_title); tvTitle.setText(R.string.welcome); fragment = new WelcomeFragments(); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.welcome_content, fragment); fragmentTransaction.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn: enterHome(); break; case R.id.button_decline: finish(); break; } } private void enterHome(){ Intent intent = new Intent(this, HomeActivity.class); startActivity(intent); } @Override protected void onResume() { super.onResume();
BusProvider.getInstance().register(this);
3
Catherine22/MobileManager
app/src/main/java/com/itheima/mobilesafe/SplashActivity.java
[ "@SuppressWarnings(\"unused\")\npublic class CLog {\n private static final boolean DEBUG = BuildConfig.SHOW_LOG;\n\n public static String getTag() {\n String tag = \"\";\n final StackTraceElement[] ste = Thread.currentThread().getStackTrace();\n for (int i = 0; i < ste.length; i++) {\n ...
import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.BitmapFactory; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.DisplayMetrics; import android.view.animation.AlphaAnimation; import android.widget.TextView; import android.widget.Toast; import com.itheima.mobilesafe.utils.CLog; import com.itheima.mobilesafe.utils.Constants; import com.itheima.mobilesafe.utils.SecurityUtils; import com.itheima.mobilesafe.utils.Settings; import com.itheima.mobilesafe.utils.SpNames; import com.itheima.mobilesafe.utils.StreamUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.security.NoSuchAlgorithmException;
//进入主页面 enterHome(); dialog.dismiss(); } }); builder.setMessage(description); builder.setPositiveButton("立刻升级", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 下载APK,并且替换安装 if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { // sdcard存在 // afnal // FinalHttp finalhttp = new FinalHttp(); // finalhttp.download(apkurl, Environment // .getExternalStorageDirectory().getAbsolutePath() + "/mobilesafe2.0.apk", // new AjaxCallBack<File>() { // // @Override // public void onFailure(Throwable t, int errorNo, // String strMsg) { // t.printStackTrace(); // Toast.makeText(getApplicationContext(), "下载失败", Toast.LENGTH_LONG).show(); // super.onFailure(t, errorNo, strMsg); // } // // @Override // public void onLoading(long count, long current) { // // super.onLoading(count, current); // tv_update_info.setVisibility(View.VISIBLE); // //当前下载百分比 // int progress = (int) (current * 100 / count); // tv_update_info.setText("下载进度:" + progress + "%"); // } // // @Override // public void onSuccess(File t) { // // super.onSuccess(t); // installAPK(t); // } // // /** // * 安装APK // * @param t // */ // private void installAPK(File t) { // Intent intent = new Intent(); // intent.setAction("android.intent.action.VIEW"); // intent.addCategory("android.intent.category.DEFAULT"); // intent.setDataAndType(Uri.fromFile(t), "application/vnd.android.package-archive"); // // startActivity(intent); // // } // // // }); } else { Toast.makeText(getApplicationContext(), "没有sdcard,请安装上在试", Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("下次再说", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); enterHome();// 进入主页面 } }); builder.show(); } protected void enterHome() { Intent intent = new Intent(this, HomeActivity.class); intent.putExtra("launchFromIntent", launchFromIntent); startActivity(intent); // 关闭当前页面 finish(); //必须要在finish()或startActivity()后面执行 overridePendingTransition(R.anim.tran_in, R.anim.tran_out); } /** * 得到应用程序的版本名称 */ private String getVersionName() { // 用来管理手机的APK PackageManager pm = getPackageManager(); try { // 得到知道APK的功能清单文件 PackageInfo info = pm.getPackageInfo(getPackageName(), 0); return info.versionName; } catch (NameNotFoundException e) { e.printStackTrace(); return ""; } } /** * 取得设备信息 * 初始化数据库 */ private void initSettings() { //取得屏幕信息 DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics);
Settings.DISPLAY_WIDTH_PX = metrics.widthPixels;
3
instaclick/PDI-Plugin-Step-AMQP
src/test/java/com/instaclick/pentaho/plugin/amqp/processor/ProcessorFactoryTest.java
[ "public class AMQPPlugin extends BaseStep implements StepInterface\r\n{\r\n private AMQPPluginData data;\r\n private AMQPPluginMeta meta;\r\n\r\n final private ProcessorFactory factory = new ProcessorFactory();\r\n private Processor processor;\r\n\r\n private final TransListener transListener = new T...
import com.instaclick.pentaho.plugin.amqp.AMQPPlugin; import com.instaclick.pentaho.plugin.amqp.AMQPPluginData; import com.instaclick.pentaho.plugin.amqp.AMQPPluginMeta; import com.instaclick.pentaho.plugin.amqp.initializer.ActiveConvirmationInitializer; import com.instaclick.pentaho.plugin.amqp.initializer.ConsumerDeclareInitializer; import com.instaclick.pentaho.plugin.amqp.initializer.ProducerDeclareInitializer; import com.rabbitmq.client.Channel; import static org.hamcrest.CoreMatchers.instanceOf; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Before; import static org.mockito.Mockito.*;
package com.instaclick.pentaho.plugin.amqp.processor; public class ProcessorFactoryTest { AMQPPluginMeta meta; AMQPPluginData data; AMQPPlugin plugin; Channel channel; @Before public void setUp() { channel = mock(Channel.class, RETURNS_MOCKS); meta = mock(AMQPPluginMeta.class); data = mock(AMQPPluginData.class); plugin = mock(AMQPPlugin.class); data.target = "queue_name"; } @Test public void testProcessorForActiveConfirmationDeclaringConsumer() throws Exception { final ProcessorFactory instance = new ProcessorFactory() { @Override protected Channel channelFor(AMQPPluginData data) { return channel; } }; data.activeConfirmation = true; data.isWaitingConsumer = true; data.isDeclare = true; data.isConsumer = true; final Processor processor = instance.processorFor(plugin, data, meta); assertThat(processor, instanceOf(WaitingConsumerProcessor.class)); final BaseProcessor baseProcessor = (BaseProcessor) processor; assertEquals(2, baseProcessor.initializers.size());
assertTrue(baseProcessor.initializers.contains(ConsumerDeclareInitializer.INSTANCE));
4
marcocor/smaph
src/main/java/it/unipi/di/acube/smaph/learn/featurePacks/BindingFeaturePack.java
[ "public class QueryInformation {\n\tpublic boolean includeSourceNormalSearch;\n\tpublic boolean includeSourceWikiSearch;\n\tpublic boolean includeSourceSnippets;\n\tpublic Double webTotalNS;\n\tpublic List<String> allBoldsNS;\n\tpublic HashMap<Integer, Integer> idToRankNS;\n\tpublic List<Pair<String, Integer>> bold...
import it.unipi.di.acube.batframework.data.Annotation; import it.unipi.di.acube.batframework.utils.Pair; import it.unipi.di.acube.batframework.utils.WikipediaInterface; import it.unipi.di.acube.smaph.QueryInformation; import it.unipi.di.acube.smaph.SmaphUtils; import it.unipi.di.acube.smaph.WATRelatednessComputer; import it.unipi.di.acube.smaph.datasets.wikiAnchors.EntityToAnchors; import it.unipi.di.acube.smaph.datasets.wikitofreebase.WikipediaToFreebase; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Vector; import org.apache.commons.lang3.tuple.Triple;
package it.unipi.di.acube.smaph.learn.featurePacks; public class BindingFeaturePack extends FeaturePack<HashSet<Annotation>> { private static final long serialVersionUID = 1L; private static String[] ftrNames = null; public BindingFeaturePack( HashSet<Annotation> binding, String query, QueryInformation qi, WikipediaInterface wikiApi, WikipediaToFreebase w2f, EntityToAnchors e2a, HashMap<Annotation, HashMap<String, Double>> debugAnnotationFeatures, HashMap<String, Double> debugBindingFeatures){ super(getFeatures(binding, query, qi, wikiApi, w2f, e2a, debugAnnotationFeatures, debugBindingFeatures)); } public BindingFeaturePack() { super(null); } @Override public String[] getFeatureNames() { return getFeatureNamesStatic(); } public static String[] getFeatureNamesStatic() { if (ftrNames == null) { List<String> ftrNamesVect = new Vector<>(); for (String ftrName : AnnotationFeaturePack .getFeatureNamesStatic()) if (ftrName.startsWith("found_")) { ftrNamesVect.add("count_" + ftrName); } else { ftrNamesVect.add("min_" + ftrName); ftrNamesVect.add("max_" + ftrName); ftrNamesVect.add("avg_" + ftrName); } ftrNamesVect.add("min_relatedness"); ftrNamesVect.add("max_relatedness"); ftrNamesVect.add("avg_relatedness"); ftrNamesVect.add("query_tokens"); ftrNamesVect.add("annotation_count"); ftrNamesVect.add("covered_tokens"); ftrNamesVect.add("min_relatedness_mw"); ftrNamesVect.add("max_relatedness_mw"); ftrNamesVect.add("avg_relatedness_mw"); ftrNamesVect.add("segments_lp_sum"); ftrNamesVect.add("segments_lp_avg"); ftrNamesVect.add("webtotal"); ftrNamesVect.add("bolds_number"); ftrNamesVect.add("distinct_bolds"); ftrNamesVect.add("bolds_query_mined_avg"); ftrNames = ftrNamesVect.toArray(new String[] {}); } return ftrNames; } @Override public void checkFeatures(HashMap<String, Double> features) { String[] ftrNames = getFeatureNames(); for (String ftrName : features.keySet()) if (!Arrays.asList(ftrNames).contains(ftrName)) throw new RuntimeException("Feature " + ftrName + " does not exist!"); } /** * Given a list of feature vectors, return a single * feature vector (in hashmap form). This vector will contain the max, * min, and avg of for [0,1] features and the sum for counting features. * * @param allFtrVects * @return a single representation */ private static HashMap<String, Double> collapseFeatures( List<HashMap<String, Double>> allFtrVects) { // count feature presence HashMap<String, Integer> ftrCount = new HashMap<>(); for (HashMap<String, Double> ftrVectToMerge : allFtrVects) for (String ftrName : ftrVectToMerge.keySet()) { if (!ftrCount.containsKey(ftrName)) ftrCount.put(ftrName, 0); ftrCount.put(ftrName, ftrCount.get(ftrName) + 1); } // compute min, max, avg, count HashMap<String, Double> entitySetFeatures = new HashMap<>(); // Initialize sources count features to 0.0 for (String ftrName : new EntityFeaturePack().getFeatureNames()) if (ftrName.startsWith("found_")) { String key = "count_" + ftrName; entitySetFeatures.put(key, 0.0); } for (HashMap<String, Double> ftrVectToMerge : allFtrVects) { for (String ftrName : ftrVectToMerge.keySet()) { if (ftrName.startsWith("found_")) { String key = "count_" + ftrName; entitySetFeatures.put(key, entitySetFeatures.get(key) + ftrVectToMerge.get(ftrName)); } else { if (!entitySetFeatures.containsKey("min_" + ftrName)) entitySetFeatures.put("min_" + ftrName, Double.POSITIVE_INFINITY); if (!entitySetFeatures.containsKey("max_" + ftrName)) entitySetFeatures.put("max_" + ftrName, Double.NEGATIVE_INFINITY); if (!entitySetFeatures.containsKey("avg_" + ftrName)) entitySetFeatures.put("avg_" + ftrName, 0.0); double ftrValue = ftrVectToMerge.get(ftrName); entitySetFeatures.put("min_" + ftrName, Math.min( entitySetFeatures.get("min_" + ftrName), ftrValue)); entitySetFeatures.put("max_" + ftrName, Math.max( entitySetFeatures.get("max_" + ftrName), ftrValue)); entitySetFeatures.put("avg_" + ftrName, entitySetFeatures.get("avg_" + ftrName) + ftrValue / ftrCount.get(ftrName)); } } } return entitySetFeatures; } private static HashMap<String, Double> getFeatures( HashSet<Annotation> binding, String query, QueryInformation qi, WikipediaInterface wikiApi, WikipediaToFreebase w2f, EntityToAnchors e2a, HashMap<Annotation, HashMap<String, Double>> debugAnnotationFeatures, HashMap<String, Double> debugBindingFeatures) { List<HashMap<String, Double>> allAnnotationsFeatures = new Vector<>(); for (Annotation ann : binding) { HashMap<String, Double> annFeatures = AnnotationFeaturePack .getFeaturesStatic(ann, query, qi, wikiApi, w2f, e2a); allAnnotationsFeatures.add(annFeatures); if (debugAnnotationFeatures != null) debugAnnotationFeatures.put(ann, annFeatures); } /* HashSet<Tag> selectedEntities = new HashSet<>(); for (Annotation ann : binding) selectedEntities.add(new Tag(ann.getConcept())); List<HashMap<String, Double>> allEntitiesFeatures = new Vector<>(); for (Tag t : selectedEntities) allEntitiesFeatures.addAll(qi.entityToFtrVects.get(t)); */ HashMap<String, Double> bindingFeatures = collapseFeatures( allAnnotationsFeatures); /*Vector<Double> mutualInfos = new Vector<>(); for (Annotation a : binding) { Tag t = new Tag(a.getConcept()); double minED = 1.0; if (entitiesToBolds.containsKey(t)) for (String bold : entitiesToBolds.get(t)) minED = Math.min(SmaphUtils.getMinEditDist( query.substring(a.getPosition(), a.getPosition() + a.getLength()), bold), minED); mutualInfos.add(mutualInfo); } */ /*Triple<Double, Double, Double> minMaxAvgMI = getMinMaxAvg(mutualInfos); features.put("min_mutual_info", minMaxAvgMI.getLeft()); features.put("avg_mutual_info", minMaxAvgMI.getRight()); features.put("max_mutual_info", minMaxAvgMI.getMiddle());*/ bindingFeatures.put("query_tokens", (double) SmaphUtils.tokenize(query).size()); bindingFeatures.put("annotation_count", (double) binding.size()); int coveredTokens = 0; for (Annotation a: binding) coveredTokens += SmaphUtils.tokenize(query.substring(a.getPosition(), a.getPosition()+a.getLength())).size(); bindingFeatures.put("covered_tokens", (double)coveredTokens/(double) SmaphUtils.tokenize(query).size()); /* Add relatedness among entities (only if there are more than two entities)*/ Vector<Double> relatednessPairsJaccard = new Vector<>(); Vector<Double> relatednessPairsMW = new Vector<>(); for (Annotation a1 : binding) for (Annotation a2 : binding) if (a1.getConcept() != a2.getConcept()){
relatednessPairsJaccard.add(WATRelatednessComputer.getJaccardRelatedness(a1.getConcept(), a2.getConcept()));
2
addradio/mpeg-audio-streams
src/main/java/net/addradio/codec/mpeg/audio/MPEGAudioFrameOutputStream.java
[ "public final class BitRateCodec {\n\n /**\n * decode.\n *\n * @param frame\n * {@link MPEGAudioFrame}\n * @param value\n * {@code int}\n * @return {@link BitRate}\n * @throws MPEGAudioCodecException\n * if bit rate could not be decoded.\n ...
import net.addradio.streams.BitInputStream; import net.addradio.streams.BitOutputStream; import net.addradio.streams.BitStreamDecorator; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.addradio.codec.mpeg.audio.codecs.BitRateCodec; import net.addradio.codec.mpeg.audio.codecs.MPEGAudioCodecException; import net.addradio.codec.mpeg.audio.codecs.ModeExtensionCodec; import net.addradio.codec.mpeg.audio.codecs.SamplingRateCodec; import net.addradio.codec.mpeg.audio.model.MPEGAudioContent; import net.addradio.codec.mpeg.audio.model.MPEGAudioFrame;
/** * Class: MPEGAudioFrameOutputStream<br/> * <br/> * Created: 20.10.2017<br/> * Filename: MPEGAudioFrameOutputStream.java<br/> * Version: $Revision: $<br/> * <br/> * last modified on $Date: $<br/> * by $Author: $<br/> * <br/> * @author <a href="mailto:sebastian.weiss@nacamar.de">Sebastian A. Weiss, nacamar GmbH</a> * @version $Author: $ -- $Revision: $ -- $Date: $ * <br/> * (c) Sebastian A. Weiss, nacamar GmbH 2012 - All rights reserved. */ package net.addradio.codec.mpeg.audio; /** * MPEGAudioFrameOutputStream */ public class MPEGAudioFrameOutputStream extends BitOutputStream { /** {@link Logger} LOG. */ @SuppressWarnings("unused") private final static Logger LOG = LoggerFactory.getLogger(MPEGAudioFrameOutputStream.class); /** {@code long} durationSoFar. Overall duration of encoded frames so far in milliseconds. */ private long durationSoFar; /** * MPEGAudioFrameOutputStream constructor. * * @param innerRef * {@link OutputStream} */ public MPEGAudioFrameOutputStream(final OutputStream innerRef) { super(innerRef); this.durationSoFar = 0; } /** * @return the {@code long} durationSoFar. Overall duration of encoded frames so far in milliseconds. */ public long getDurationSoFar() { return this.durationSoFar; } /** * writeFrame. * @param frame {@link MPEGAudioContent} * @return {@code int} number of bytes written. * @throws IOException due to IO problems. * @throws MPEGAudioCodecException if encoding encountered a bad model state. */
public int writeFrame(final MPEGAudioContent frame) throws IOException, MPEGAudioCodecException {
1
xedin/sasi
src/java/org/apache/cassandra/db/index/sasi/memory/IndexMemtable.java
[ "public class SSTableAttachedSecondaryIndex extends PerRowSecondaryIndex implements INotificationConsumer\n{\n private static final Logger logger = LoggerFactory.getLogger(SSTableAttachedSecondaryIndex.class);\n\n private IndexMetrics metrics;\n\n private final ConcurrentMap<ByteBuffer, ColumnIndex> indexe...
import org.cliffc.high_scale_lib.NonBlockingHashMap; import org.github.jamm.MemoryMeter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentMap; import org.apache.cassandra.db.Column; import org.apache.cassandra.db.index.SSTableAttachedSecondaryIndex; import org.apache.cassandra.db.index.sasi.conf.ColumnIndex; import org.apache.cassandra.db.index.sasi.disk.Token; import org.apache.cassandra.db.index.sasi.plan.Expression; import org.apache.cassandra.db.index.sasi.utils.RangeIterator; import org.apache.cassandra.db.index.sasi.utils.TypeUtil; import org.apache.cassandra.db.marshal.AbstractType;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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.apache.cassandra.db.index.sasi.memory; public class IndexMemtable { private static final Logger logger = LoggerFactory.getLogger(IndexMemtable.class); private final MemoryMeter meter; private final ConcurrentMap<ByteBuffer, MemIndex> indexes; private final SSTableAttachedSecondaryIndex backend; public IndexMemtable(final SSTableAttachedSecondaryIndex backend) { this.indexes = new NonBlockingHashMap<>(); this.backend = backend; this.meter = new MemoryMeter().omitSharedBufferOverhead().withTrackerProvider(new Callable<Set<Object>>() { public Set<Object> call() throws Exception { // avoid counting this once for each row Set<Object> set = Collections.newSetFromMap(new IdentityHashMap<Object, Boolean>()); set.add(backend.getBaseCfs().metadata); return set; } }); } public long estimateSize() { long deepSize = 0; for (MemIndex index : indexes.values()) deepSize += index.estimateSize(meter); return deepSize; } public void index(ByteBuffer key, Iterator<Column> row) { final long now = System.currentTimeMillis(); while (row.hasNext()) { Column column = row.next(); if (column.isMarkedForDelete(now)) continue;
ColumnIndex columnIndex = backend.getIndex(column.name());
1
hoijui/JavaOSC
modules/core/src/main/java/com/illposed/osc/transport/udp/UDPTransport.java
[ "public final class LibraryInfo {\n\n\tprivate static final String MANIFEST_FILE = \"/META-INF/MANIFEST.MF\";\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic static final String UNKNOWN_VALUE = \"<unknown>\";\n\tprivate static final char MANIFEST_CONTINUATION_LINE_INDICATOR = ' ';\n\t/** 1 key + 1...
import com.illposed.osc.LibraryInfo; import com.illposed.osc.OSCPacket; import com.illposed.osc.OSCParseException; import com.illposed.osc.OSCSerializerAndParserBuilder; import com.illposed.osc.OSCSerializeException; import com.illposed.osc.transport.Transport; import com.illposed.osc.transport.channel.OSCDatagramChannel; import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.StandardProtocolFamily; import java.net.StandardSocketOptions; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel;
// SPDX-FileCopyrightText: 2004-2019 C. Ramakrishnan / Illposed Software // SPDX-FileCopyrightText: 2021 Robin Vobruba <hoijui.quaero@gmail.com> // // SPDX-License-Identifier: BSD-3-Clause package com.illposed.osc.transport.udp; /** * A {@link Transport} implementation for sending and receiving OSC packets over * a network via UDP. */ public class UDPTransport implements Transport { /** * Buffers were 1500 bytes in size, but were increased to 1536, as this * is a common MTU, and then increased to 65507, as this is the maximum * incoming datagram data size. */ public static final int BUFFER_SIZE = 65507; private final ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); private final SocketAddress local; private final SocketAddress remote; private final DatagramChannel channel; private final OSCDatagramChannel oscChannel; public UDPTransport( final SocketAddress local, final SocketAddress remote) throws IOException { this(local, remote, new OSCSerializerAndParserBuilder()); } public UDPTransport( final SocketAddress local, final SocketAddress remote, final OSCSerializerAndParserBuilder serializerAndParserBuilder) throws IOException { this.local = local; this.remote = remote; final DatagramChannel tmpChannel; if ((local instanceof InetSocketAddress) && LibraryInfo.hasStandardProtocolFamily()) { final InetSocketAddress localIsa = (InetSocketAddress) local; final InetSocketAddress remoteIsa = (InetSocketAddress) remote; final Class<?> localClass = localIsa.getAddress().getClass(); final Class<?> remoteClass = remoteIsa.getAddress().getClass(); if (!localClass.equals(remoteClass)) { throw new IllegalArgumentException( "local and remote addresses are not of the same family" + " (IP v4 vs v6)"); } if (localIsa.getAddress() instanceof Inet4Address) { tmpChannel = DatagramChannel.open(StandardProtocolFamily.INET); } else if (localIsa.getAddress() instanceof Inet6Address) { tmpChannel = DatagramChannel.open(StandardProtocolFamily.INET6); } else { throw new IllegalArgumentException( "Unknown address type: " + localIsa.getAddress().getClass().getCanonicalName()); } } else { tmpChannel = DatagramChannel.open(); } this.channel = tmpChannel; if (LibraryInfo.hasStandardProtocolFamily()) { this.channel.setOption(StandardSocketOptions.SO_SNDBUF, BUFFER_SIZE); // NOTE So far, we never saw an issue with the receive-buffer size, // thus we leave it at its default. this.channel.setOption(StandardSocketOptions.SO_REUSEADDR, true); this.channel.setOption(StandardSocketOptions.SO_BROADCAST, true); } else { this.channel.socket().setSendBufferSize(BUFFER_SIZE); // NOTE So far, we never saw an issue with the receive-buffer size, // thus we leave it at its default. this.channel.socket().setReuseAddress(true); this.channel.socket().setBroadcast(true); } this.channel.socket().bind(local); this.oscChannel = new OSCDatagramChannel(channel, serializerAndParserBuilder); } @Override public void connect() throws IOException { if (remote == null) { throw new IllegalStateException( "Can not connect a socket without a remote address specified" ); } channel.connect(remote); } @Override public void disconnect() throws IOException { channel.disconnect(); } @Override public boolean isConnected() { return channel.isConnected(); } /** * Close the socket and free-up resources. * It is recommended that clients call this when they are done with the port. * @throws IOException If an I/O error occurs on the channel */ @Override public void close() throws IOException { channel.close(); } @Override public void send(final OSCPacket packet) throws IOException, OSCSerializeException { oscChannel.send(buffer, packet, remote); } @Override
public OSCPacket receive() throws IOException, OSCParseException {
2
jeperon/freqtrade-java
src/main/java/ch/urbanfox/freqtrade/telegram/command/ForceSellCommandHandler.java
[ "@Component\npublic class FreqTradeMainRunner {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(FreqTradeMainRunner.class);\n\n private State state = State.RUNNING;\n\n @Autowired\n private FreqTradeProperties properties;\n\n @Autowired\n private AnalyzeService analyzeService;\n\n...
import java.math.BigDecimal; import java.math.MathContext; import java.util.Optional; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import ch.urbanfox.freqtrade.FreqTradeMainRunner; import ch.urbanfox.freqtrade.exchange.FreqTradeExchangeService; import ch.urbanfox.freqtrade.telegram.TelegramService; import ch.urbanfox.freqtrade.trade.TradeEntity; import ch.urbanfox.freqtrade.trade.TradeService; import ch.urbanfox.freqtrade.type.State;
package ch.urbanfox.freqtrade.telegram.command; /** * Handler for /forcesell <id> * * Sells the given trade at current price */ @Component public class ForceSellCommandHandler extends AbstractCommandHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ForceSellCommandHandler.class); @Autowired
private FreqTradeMainRunner runner;
0
GhostFlying/PortalWaitingList
app/src/main/java/com/ghostflying/portalwaitinglist/fragment/ReDesignDetailFragment.java
[ "public class MainActivity extends ActionBarActivity\n implements PortalListFragment.OnFragmentInteractionListener{\n private static final String LIST_FRAGMENT_TAG = \"LIST_FRAGMENT\";\n private static final String DETAIL_FRAGMENT_TAG = \"DETAIL_FRAGMENT\";\n\n String account;\n PortalDetail clic...
import android.app.Fragment; import android.app.LoaderManager; import android.content.Intent; import android.content.Loader; import android.graphics.Bitmap; import android.graphics.Canvas; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.view.ViewCompat; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.ghostflying.portalwaitinglist.MainActivity; import com.ghostflying.portalwaitinglist.ObservableScrollView; import com.ghostflying.portalwaitinglist.R; import com.ghostflying.portalwaitinglist.loader.SearchResultLoader; import com.ghostflying.portalwaitinglist.model.PortalDetail; import com.ghostflying.portalwaitinglist.model.PortalEvent; import com.ghostflying.portalwaitinglist.util.SettingUtil; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; import com.squareup.picasso.Picasso; import java.io.File; import java.io.FileOutputStream; import java.text.DateFormat; import java.util.Date;
return fragment; } public ReDesignDetailFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); localDateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); mClient = new GoogleApiClient.Builder(getActivity()).addApi(AppIndex.APP_INDEX_API).build(); if (getArguments() != null) { clickedPortal = getArguments().getParcelable(ARG_CLICKED_PORTAL_NAME); firstEventId = getArguments().getString(ARG_FIRST_EVENT_ID); } } @Override public void onStart(){ super.onStart(); if (clickedPortal != null) recordView(); } private void recordView() { mClient.connect(); final String TITLE = clickedPortal.getName(); String messageId = clickedPortal.getEvents().get(0).getMessageId(); appUri = BASE_APP_URI.buildUpon().appendPath(messageId).build(); final Uri WEB_URI = Uri.parse(BASE_WEB_URL + messageId); AppIndex.AppIndexApi.view(mClient, getActivity(), appUri, TITLE, WEB_URI, null); } @Override public void onStop(){ super.onStop(); AppIndex.AppIndexApi.viewEnd(mClient, getActivity(), appUri); mClient.disconnect(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_re_design_detail, container, false); // toolbar mToolbar = (Toolbar)view.findViewById(R.id.detail_toolbar); mToolbar.setTitle(""); ((ActionBarActivity)getActivity()).setSupportActionBar(mToolbar); mToolbar.setNavigationIcon(R.drawable.ic_up); mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (firstEventId != null){ startActivity(new Intent(getActivity(), MainActivity.class)); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ getActivity().finishAfterTransition(); } else getActivity().finish(); } }); // remove the elevation to make header unify if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) mToolbar.setElevation(0); mScrollView = (ObservableScrollView)view.findViewById(R.id.scroll_view); mScrollView.addCallbacks(this); // Header mHeaderBox = view.findViewById(R.id.header_portal); mPhotoView = (ImageView)view.findViewById(R.id.portal_photo); mPhotoViewContainer = view.findViewById(R.id.portal_photo_container); mPortalName = (TextView)view.findViewById(R.id.portal_name); mPortalSummary = (TextView)view.findViewById(R.id.portal_status_in_detail); mMaxHeaderElevation = getResources().getDimensionPixelSize( R.dimen.portal_detail_max_header_elevation); // details mDetailsContainer = view.findViewById(R.id.detail_container); mPortalAddress = (TextView)view.findViewById(R.id.portal_address_in_detail); mPortalAddressView = view.findViewById(R.id.portal_address_view_in_detail); mPortalEventListContainer = view.findViewById(R.id.portal_event_list); // set observer for views ViewTreeObserver vto = mScrollView.getViewTreeObserver(); if (vto.isAlive()) { vto.addOnGlobalLayoutListener(mGlobalLayoutListener); } // menu setHasOptionsMenu(true); if (clickedPortal != null) showPortal(clickedPortal); else { getLoaderManager().initLoader(0, null, this); } return view; } private void showPortal(PortalDetail portal){ mPortalName.setText(portal.getName()); mPortalSummary.setText(getSummaryText(portal)); String address = portal.getAddress(); if (address != null){ mPortalAddress.setText(address); } else { mPortalAddressView.setVisibility(View.GONE); } addEventViews(portal, (ViewGroup)mPortalEventListContainer); // photo String photoUrl = portal.getImageUrl();
if (SettingUtil.getIfShowImages() && photoUrl != null && photoUrl.startsWith("http")){
5
NuVotifier/NuVotifier
common/src/main/java/com/vexsoftware/votifier/util/standalone/StandaloneVotifierPlugin.java
[ "public class Vote {\n\n /**\n * The name of the vote service.\n */\n private String serviceName;\n\n /**\n * The username of the voter.\n */\n private String username;\n\n /**\n * The address of the voter.\n */\n private String address;\n\n /**\n * The date and time...
import com.vexsoftware.votifier.model.Vote; import com.vexsoftware.votifier.net.VotifierServerBootstrap; import com.vexsoftware.votifier.net.VotifierSession; import com.vexsoftware.votifier.platform.JavaUtilLogger; import com.vexsoftware.votifier.platform.LoggingAdapter; import com.vexsoftware.votifier.platform.VotifierPlugin; import com.vexsoftware.votifier.platform.scheduler.ScheduledExecutorServiceVotifierScheduler; import com.vexsoftware.votifier.platform.scheduler.VotifierScheduler; import java.net.InetSocketAddress; import java.security.Key; import java.security.KeyPair; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.function.Consumer; import java.util.logging.Logger;
package com.vexsoftware.votifier.util.standalone; public class StandaloneVotifierPlugin implements VotifierPlugin { private final Map<String, Key> tokens; private final VoteReceiver receiver; private final KeyPair v1Key; private final InetSocketAddress bind; private final VotifierScheduler scheduler; private VotifierServerBootstrap bootstrap; public StandaloneVotifierPlugin(Map<String, Key> tokens, VoteReceiver receiver, KeyPair v1Key, InetSocketAddress bind) { this.receiver = receiver; this.bind = bind; this.tokens = Collections.unmodifiableMap(new HashMap<>(tokens)); this.v1Key = v1Key; this.scheduler = new ScheduledExecutorServiceVotifierScheduler(Executors.newScheduledThreadPool(1)); } public void start() { start(o -> {}); } public void start(Consumer<Throwable> error) { if (bootstrap != null) { bootstrap.shutdown(); } this.bootstrap = new VotifierServerBootstrap(bind.getHostString(), bind.getPort(), this, v1Key == null); this.bootstrap.start(error); } @Override public Map<String, Key> getTokens() { return tokens; } @Override public KeyPair getProtocolV1Key() { return v1Key; } @Override public LoggingAdapter getPluginLogger() { return new JavaUtilLogger(Logger.getAnonymousLogger()); } @Override public VotifierScheduler getScheduler() { return scheduler; } @Override
public void onVoteReceived(Vote vote, VotifierSession.ProtocolVersion protocolVersion, String remoteAddress) throws Exception {
2
cjdaly/fold
net.locosoft.fold.channel.fold/src/net/locosoft/fold/channel/fold/internal/FoldChannel.java
[ "public abstract class AbstractChannel implements IChannel, IChannelInternal {\n\n\t//\n\t// IChannel\n\t//\n\n\tprivate String _id;\n\n\tpublic String getChannelId() {\n\t\treturn _id;\n\t}\n\n\tprivate String _description;\n\n\tpublic String getChannelData(String key, String... params) {\n\t\tswitch (key) {\n\t\t...
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.locosoft.fold.channel.AbstractChannel; import net.locosoft.fold.channel.ChannelUtil; import net.locosoft.fold.channel.IChannel; import net.locosoft.fold.channel.fold.IFoldChannel; import net.locosoft.fold.sketch.pad.html.ChannelHeaderFooterHtml; import net.locosoft.fold.sketch.pad.neo4j.CounterPropertyNode; import net.locosoft.fold.sketch.pad.neo4j.HierarchyNode; import net.locosoft.fold.util.HtmlComposer; import org.eclipse.core.runtime.Path; import com.eclipsesource.json.JsonObject;
/***************************************************************************** * Copyright (c) 2015 Chris J Daly (github user cjdaly) * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * cjdaly - initial API and implementation ****************************************************************************/ package net.locosoft.fold.channel.fold.internal; public class FoldChannel extends AbstractChannel implements IFoldChannel { private FoldFinder _foldFinder = new FoldFinder(this); private long _startCount = -1; public long getStartCount() { return _startCount; } public Class<? extends IChannel> getChannelInterface() { return IFoldChannel.class; } public void init() { CounterPropertyNode foldStartCount = new CounterPropertyNode( getChannelNodeId()); _startCount = foldStartCount.incrementCounter("fold_startCount"); _foldFinder.start(); } public void fini() { _foldFinder.stop(); } public void channelHttpGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); if ((pathInfo == null) || ("".equals(pathInfo)) || ("/".equals(pathInfo))) { // empty channel segment (/fold) new ChannelHttpGetDashboard() .composeHtmlResponse(request, response); } else { Path path = new Path(pathInfo); String channelSegment = path.segment(0); if ("fold".equals(channelSegment)) { // fold channel segment (/fold/fold) new ChannelHttpGetFold().composeHtmlResponse(request, response); } else { // everything else new ChannelHttpGetUndefined().composeHtmlResponse(request, response); } } }
private class ChannelHttpGetDashboard extends ChannelHeaderFooterHtml {
4
spacecowboy/NotePad
app/src/main/java/com/nononsenseapps/notepad/util/ListHelper.java
[ "public class LegacyDBHelper extends SQLiteOpenHelper {\n\n\tpublic static final String LEGACY_DATABASE_NAME = \"note_pad.db\";\n\tpublic static final int LEGACY_DATABASE_FINAL_VERSION = 8;\n\n\tpublic LegacyDBHelper(Context context) {\n\t\tthis(context, \"\");\n\t}\n\n\tpublic LegacyDBHelper(Context context, Strin...
import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.preference.PreferenceManager; import com.nononsenseapps.notepad.R; import com.nononsenseapps.notepad.data.local.sql.LegacyDBHelper; import com.nononsenseapps.notepad.data.model.sql.Task; import com.nononsenseapps.notepad.data.model.sql.TaskList; import com.nononsenseapps.notepad.ui.editor.TaskDetailFragment; import com.nononsenseapps.notepad.ui.list.TaskListFragment;
/* * Copyright (c) 2015 Jonas Kalderstam. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nononsenseapps.notepad.util; /** * Simple utility class to hold some general functions. */ public class ListHelper { /** * If temp list is > 0, returns it if it exists. Else, checks if a default list is set * then returns that. If none set, then returns first (alphabetical) list * Returns #{TaskListFragment.LIST_ID_ALL} if no lists in database. */ public static long getAViewList(final Context context, final long tempList) { long returnList = tempList;
if (returnList == TaskListFragment.LIST_ID_ALL) {
4
chetan/sewer
src/main/java/net/pixelcop/sewer/sink/durable/TransactionManager.java
[ "@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\npublic class PlumbingBuilder<T> {\n\n private Class clazz;\n private String[] args;\n\n public PlumbingBuilder(Class clazz, String[] args) {\n this.clazz = clazz;\n this.args = args;\n }\n\n public Object build() throws Exception {\n return (T) claz...
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import net.pixelcop.sewer.DrainSink; import net.pixelcop.sewer.PlumbingBuilder; import net.pixelcop.sewer.PlumbingFactory; import net.pixelcop.sewer.Sink; import net.pixelcop.sewer.node.ExitCodes; import net.pixelcop.sewer.node.Node; import net.pixelcop.sewer.node.NodeConfig; import net.pixelcop.sewer.sink.SequenceFileSink; import net.pixelcop.sewer.source.TransactionSource; import net.pixelcop.sewer.util.BackoffHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper;
if (drainingTx != null) { failedTransactions.add(drainingTx); drainingTx = null; } saveOpenTransactionsToDisk(); return; } if (drainingTx == null) { continue; } setStatus(DRAINING); // drain it if (!drainTx()) { // drain failed (interrupted, tx man shutting down), stick tx at end of queue (front ??) failedTransactions.add(drainingTx); drainingTx = null; saveOpenTransactionsToDisk(); return; } drainingTx.deleteTxFiles(); drainingTx = null; saveOpenTransactionsToDisk(); setStatus(IDLE); } } /** * Save all transactions we know about to disk */ protected void saveOpenTransactionsToDisk() { synchronized (DEFAULT_WAL_PATH) { File txLog = getTxLog(); if (LOG.isDebugEnabled()) { LOG.debug("Saving transaction queues to disk " + txLog.toString()); } List<Transaction> txList = new ArrayList<Transaction>(); if (drainingTx != null) { if (LOG.isTraceEnabled()) { LOG.trace("Found tx currently being drained"); } txList.add(drainingTx); } if (!transactions.isEmpty()) { if (LOG.isTraceEnabled()) { LOG.trace("Found " + transactions.size() + " presently open transactions"); } txList.addAll(transactions.values()); } if (!failedTransactions.isEmpty()) { if (LOG.isTraceEnabled()) { LOG.trace("Found " + failedTransactions.size() + " lost transactions"); } txList.addAll(failedTransactions); } try { new ObjectMapper().writeValue(txLog, txList); LOG.trace("save complete"); } catch (IOException e) { LOG.error("Failed to write txn.log: " + e.getMessage(), e); } } } /** * Load transaction log from disk so we can restart them */ protected void loadTransctionsFromDisk() { File txLog = getTxLog(); if (LOG.isDebugEnabled()) { LOG.debug("Loading transaction queues from disk " + txLog.toString()); } try { ArrayList<Transaction> recovered = new ObjectMapper().readValue(txLog, new TypeReference<ArrayList<Transaction>>() {}); LOG.info("Loaded " + recovered.size() + " txns from disk"); failedTransactions.addAll(recovered); } catch (FileNotFoundException e) { LOG.debug(e.getMessage()); return; // no biggie, just doesn't exist yet } catch (Exception e) { LOG.error("Failed to load txn.log: " + e.getMessage()); System.exit(ExitCodes.STARTUP_ERROR); } } protected File getTxLog() { return new File(getWALPath() + "/txn.log"); } /** * Drains the currently selected Transaction. Returns on completion or if interrupted */ private boolean drainTx() { // drain this tx to sink LOG.debug("Draining tx " + drainingTx);
BackoffHelper backoff = new BackoffHelper();
8
bretthshelley/Maven-IIB9-Plug-In
src/main/java/ch/sbb/maven/plugins/iib/mojos/PackageBarMojo.java
[ "public static String validateCreateOrPackageBar(String createOrPackageBar, Log log) throws MojoFailureException\n{\n if (createOrPackageBar != null && !createOrPackageBar.trim().isEmpty())\n {\n if (createOrPackageBar.trim().equalsIgnoreCase(\"create\")\n || createOrPackageBar.trim().eq...
import static ch.sbb.maven.plugins.iib.utils.ConfigurationValidator.validateCreateOrPackageBar; import static ch.sbb.maven.plugins.iib.utils.ConfigurationValidator.validatePathToMqsiProfileScript; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.FileUtils; import ch.sbb.maven.plugins.iib.utils.DependenciesManager; import ch.sbb.maven.plugins.iib.utils.DirectoriesUtil; import ch.sbb.maven.plugins.iib.utils.MqsiCommand; import ch.sbb.maven.plugins.iib.utils.MqsiCommandLauncher; import ch.sbb.maven.plugins.iib.utils.SkipUtil; import com.ibm.broker.config.appdev.CommandProcessorPublicWrapper;
package ch.sbb.maven.plugins.iib.mojos; /** * Packages or Creates a .bar file. */ @Mojo(name = "package-bar", defaultPhase = LifecyclePhase.COMPILE) public class PackageBarMojo extends AbstractMojo { /** * indicates whether this MOJO will use MQSI commands to perform tasks or default to original SBB approach. * */ @Parameter(property = "createOrPackageBar", required = false, defaultValue = "create") protected String createOrPackageBar; private boolean create; /** * indicates the absolute file path to the location of the mqsiprofile command or shell script. */ @Parameter(property = "pathToMqsiProfileScript", defaultValue = "\"C:\\Program Files\\IBM\\MQSI\\9.0.0.2\\bin\\mqsiprofile.cmd\"", required = false) protected String pathToMqsiProfileScript; /** * a comma-separated list of commands that will be issued to the underlying os before launching the mqsi* command. * This will substitute for the Windows approach covered by the 'pathToMqsiProfileScript' value. These * commands should be operating system specific and * execute the mqsiprofile command as well as setup the launch of the followup mqsi command * */ @Parameter(property = "mqsiPrefixCommands", required = false) protected String mqsiPrefixCommands; @Parameter(property = "mqsiCreateBarReplacementCommand", required = false, defaultValue = "") protected String mqsiCreateBarReplacementCommand; @Parameter(property = "mqsiCreateBarCompileOnlyReplacementCommand", required = false, defaultValue = "") protected String mqsiCreateBarCompileOnlyReplacementCommand; /** * The name of the BAR (compressed file format) archive file where the * result is stored. */ @Parameter(property = "barName", defaultValue = "${project.build.directory}/${project.artifactId}-${project.version}.bar", required = true) protected File barName; /** * The name of the trace file to use when packaging bar files */ @Parameter(property = "packageBarTraceFile", defaultValue = "${project.build.directory}/packagebartrace.txt", required = true) protected File packageBarTraceFile; /** * The name of the trace file to use when packaging bar files */ @Parameter(property = "createBarTraceFile", defaultValue = "${project.build.directory}/createbartrace.txt", required = true) protected File createBarTraceFile; /** * The path of the workspace in which the projects are extracted to be built. */ @Parameter(property = "workspace", required = true) protected File workspace; /** * The Maven Project Object */ @Parameter(property = "project", required = true, readonly = true) protected MavenProject project; /** * The Maven Session Object */ @Parameter(property = "session", required = true, readonly = true) protected MavenSession session; /** * The Maven PluginManager Object */ @Component protected BuildPluginManager buildPluginManager; DependenciesManager dependenciesManager; private List<String> getApplicationAndLibraryParams() throws MojoFailureException { dependenciesManager = new DependenciesManager(project, workspace, getLog()); List<String> params = new ArrayList<String>(); params.add("-k"); params.add(dependenciesManager.getApp()); // if there are applications, add them if (!dependenciesManager.getDependentApps().isEmpty()) { params.addAll(dependenciesManager.getDependentApps()); } // if there are libraries, add them if (!dependenciesManager.getDependentLibs().isEmpty()) { // instead of adding the dependent libraries ( which don't make it into the appzip - fix the // indirect references problem by altering the project's .project file try { dependenciesManager.fixIndirectLibraryReferences(project.getBasedir()); } catch (Exception e) { // TODO handle exception throw new MojoFailureException("problem fixing Indirect Library References", e); } // params.add("-y"); // params.addAll(dependenciesManager.getDependentLibs()); } // if (dependenciesManager.getDependentApps().isEmpty() && dependenciesManager.getDependentLibs().isEmpty()) { // throw new MojoFailureException("unable to determine apps or libraries to packagebar/createbar"); // } return params; } protected List<String> constructPackageBarParams() throws MojoFailureException { List<String> params = new ArrayList<String>(); // bar file name - required params.add("-a"); params.add(barName.getAbsolutePath()); // workspace parameter - required createWorkspaceDirectory(); params.add("-w"); params.add(workspace.toString()); // object names - required params.addAll(getApplicationAndLibraryParams()); // always trace the packaging process params.add("-v"); params.add(packageBarTraceFile.getAbsolutePath()); return params; } protected List<String> constructCreateBarParams() throws MojoFailureException { List<String> params = new ArrayList<String>(); // bar file name - required // workspace parameter - required createWorkspaceDirectory(); params.add("-data"); params.add(workspace.toString()); params.add("-b"); params.add(barName.getAbsolutePath()); params.add("-a"); params.add(project.getName()); params.add("-cleanBuild"); params.addAll(getApplicationAndLibraryParams()); // always trace the packaging process params.add("-trace"); params.add("-v"); params.add(createBarTraceFile.getAbsolutePath()); return params; } protected List<String> constructCreateBarCompileOnlyParams() throws MojoFailureException { List<String> params = new ArrayList<String>(); params.add("-data"); params.add(workspace.toString()); params.add("-compileOnly"); return params; } /** * @param params * @throws MojoFailureException * @throws IOException */ private void executeMqsiCreateBar(List<String> params) throws MojoFailureException, IOException { DirectoriesUtil util = new DirectoriesUtil(); try { // / the better approach is simply to rename the pom.xml files as pom-xml-temp.txt // / and run maven with a "mvn [goal] -f pom.xml.txt" util.renamePomXmlFiles(workspace, getLog()); new MqsiCommandLauncher().execute( getLog(), pathToMqsiProfileScript, mqsiPrefixCommands,
MqsiCommand.mqsicreatebar,
4
cm-heclouds/JAVA-HTTP-SDK
javaSDK/src/main/java/cmcc/iot/onenet/javasdk/api/datastreams/DeleteDatastreamsApi.java
[ "public abstract class AbstractAPI<T> {\n public String key;\n public String url;\n public Method method;\n public ObjectMapper mapper = initObjectMapper();\n\n private ObjectMapper initObjectMapper() {\n ObjectMapper objectMapper = new ObjectMapper();\n //关闭字段不识别报错\n objectMappe...
import java.util.HashMap; import java.util.Map; import org.apache.http.HttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import cmcc.iot.onenet.javasdk.api.AbstractAPI; import cmcc.iot.onenet.javasdk.exception.OnenetApiException; import cmcc.iot.onenet.javasdk.http.HttpDeleteMethod; import cmcc.iot.onenet.javasdk.request.RequestInfo.Method; import cmcc.iot.onenet.javasdk.response.BasicResponse; import cmcc.iot.onenet.javasdk.utils.Config;
package cmcc.iot.onenet.javasdk.api.datastreams; public class DeleteDatastreamsApi extends AbstractAPI{ private final Logger logger = LoggerFactory.getLogger(this.getClass()); private String devId; private HttpDeleteMethod HttpMethod; private String datastreamId; /** * @param devId * @param datastreamId * @param key */ public DeleteDatastreamsApi(String devId, String datastreamId,String key) { this.devId = devId; this.datastreamId = datastreamId; this.key=key; this.method = Method.DELETE; Map<String, Object> headmap = new HashMap<String, Object>(); HttpMethod = new HttpDeleteMethod(method); headmap.put("api-key", key); HttpMethod.setHeader(headmap); this.url = Config.getString("test.url") + "/devices/" + devId+"/datastreams/"+datastreamId; HttpMethod.setcompleteUrl(url,null); }
public BasicResponse<Void> executeApi() {
4
shiziqiu/shiziqiu-configuration
shiziqiu-configuration-console/src/main/java/com/shiziqiu/configuration/console/web/controller/GroupController.java
[ "public class ResultT<T> {\n\n\tpublic static final ResultT<String> SUCCESS = new ResultT<String>(null);\n\tpublic static final ResultT<String> FAIL = new ResultT<String>(500, null);\n\t\n\tprivate int code;\n\tprivate String msg;\n\tprivate T content;\n\t\n\tpublic ResultT(){}\n\t\n\tpublic ResultT(int code, Strin...
import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.shiziqiu.configuration.console.model.ResultT; import com.shiziqiu.configuration.console.model.ShiZiQiuConfGroup; import com.shiziqiu.configuration.console.service.ShiZiQiuConfGroupService; import com.shiziqiu.configuration.console.service.ShiZiQiuConfNodeService; import com.shiziqiu.configuration.util.StringUtils;
package com.shiziqiu.configuration.console.web.controller; /** * @title : GroupController * @author : crazy * @date : 2017年9月7日 上午9:57:18 * @Fun : */ @Controller @RequestMapping("/group") public class GroupController { @Resource private ShiZiQiuConfNodeService shiZiQiuConfNodeService; @Resource private ShiZiQiuConfGroupService shiZiQiuConfGroupService; @RequestMapping public String index(Model model) { List<ShiZiQiuConfGroup> list = shiZiQiuConfGroupService.findAll(); model.addAttribute("list", list); return "group/index"; } @RequestMapping("/save") @ResponseBody public ResultT<String> save(ShiZiQiuConfGroup shiZiQiuConfGroup){
if (null == shiZiQiuConfGroup.getGroupName() || StringUtils.isBlank(shiZiQiuConfGroup.getGroupName())) {
4
52North/geoar-app
src/main/java/org/n52/geoar/ar/view/ARObject.java
[ "public interface OpenGLCallable {\r\n\tvoid onPreRender(); // unused\r\n\r\n\tvoid render(final float[] projectionMatrix, final float[] viewMatrix,\r\n\t\t\tfinal float[] parentMatrix, final float[] lightPosition);\r\n}\r", "public class GLESCamera {\r\n\r\n\tprivate static class GeometryPlane {\r\n\t\tprivate s...
import java.util.List; import javax.microedition.khronos.opengles.GL10; import org.n52.geoar.ar.view.gl.ARSurfaceViewRenderer.OpenGLCallable; import org.n52.geoar.ar.view.gl.GLESCamera; import org.n52.geoar.newdata.DataSourceInstanceHolder; import org.n52.geoar.newdata.SpatialEntity2; import org.n52.geoar.newdata.Visualization; import org.n52.geoar.newdata.Visualization.FeatureVisualization; import org.n52.geoar.newdata.vis.DataSourceVisualization.DataSourceVisualizationCanvas; import org.n52.geoar.tracking.location.LocationHandler; import org.n52.geoar.view.geoar.gl.mode.RenderFeature2; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.location.Location; import android.opengl.GLU; import android.opengl.Matrix; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup.LayoutParams; import android.widget.RelativeLayout; import com.vividsolutions.jts.geom.Geometry;
/** * Copyright 2012 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.geoar.ar.view; /** * * @author Arne de Wall <a.dewall@52North.org> * */ public class ARObject implements OpenGLCallable { private static float getScaleByDistance(float distance) { // XXX TODO FIXME reworking scaling function int x = org.n52.geoar.view.geoar.Settings.BUFFER_MAPINTERPOLATION; if (distance > x) { return 0.5f; } float scale = 1 - (distance / (x * 2)); return Math.max(0.5f, scale); } private static Paint distancePaint = new Paint(); static { distancePaint.setAntiAlias(true); distancePaint.setColor(Color.GRAY); distancePaint.setAlpha(100); } /** Model Matrix of this feature */ private final float[] modelMatrix = new float[16]; /** Model view Matrix of this feature */ private final float[] modelViewMatrix = new float[16]; /** Model-View-Projection Matrix of our feature */ private final float[] mvpMatrix = new float[16]; /** temporary Matrix for caching */ private final float[] tmpMatrix = new float[16]; private float distanceTo; private float featureDetailsScale; private final float[] newPosition = new float[4]; private final float[] screenCoordinates = new float[3]; private volatile boolean isInFrustum = false; // XXX Why mapping by Class? Compatible with multiinstancedatasources? // private final Map<Class<? extends ItemVisualization>, VisualizationLayer> // visualizationLayers = new HashMap<Class<? extends ItemVisualization>, // VisualizationLayer>(); private final SpatialEntity2<? extends Geometry> entity; private DataSourceVisualizationCanvas canvasFeature; private List<RenderFeature2> renderFeatures; private FeatureVisualization visualization; private View featureDetailView; private Bitmap featureDetailBitmap; private DataSourceInstanceHolder dataSourceInstance; // TODO FIXME XXX task: ARObject gains most functionalities of RenderFeature // (-> RenderFeature to be more optional) public ARObject(SpatialEntity2<? extends Geometry> entity, Visualization.FeatureVisualization visualization, List<RenderFeature2> features, DataSourceVisualizationCanvas canvasFeature, DataSourceInstanceHolder dataSourceInstance) { this.entity = entity; this.renderFeatures = features; this.canvasFeature = canvasFeature; this.visualization = visualization; this.dataSourceInstance = dataSourceInstance;
onLocationUpdate(LocationHandler.getLastKnownLocation());
3
kristian/JDigitalSimulator
src/main/java/lc/kra/jds/components/buildin/display/TenSegmentDisplay.java
[ "public static String getTranslation(String key) { return getTranslation(key, TranslationType.TEXT); }", "public static enum TranslationType { TEXT, ALTERNATIVE, TITLE, EXTERNAL, TOOLTIP, DESCRIPTION; }", "public abstract class Component implements Paintable, Locatable, Moveable, Cloneable, Serializable {\n\tpr...
import lc.kra.jds.contacts.InputContact; import static lc.kra.jds.Utilities.getTranslation; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Polygon; import lc.kra.jds.Utilities.TranslationType; import lc.kra.jds.components.Component; import lc.kra.jds.components.Sociable; import lc.kra.jds.contacts.Contact; import lc.kra.jds.contacts.ContactList; import lc.kra.jds.contacts.ContactUtilities;
/* * JDigitalSimulator * Copyright (C) 2017 Kristian Kraljic * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package lc.kra.jds.components.buildin.display; /** * Ten segment display (build-in component) * @author Kristian Kraljic (kris@kra.lc) */ public class TenSegmentDisplay extends Component implements Sociable { private static final long serialVersionUID = 2l; private static final String KEY; static { KEY = "component.display."+TenSegmentDisplay.class.getSimpleName().toLowerCase(); } public static final ComponentAttributes componentAttributes = new ComponentAttributes(KEY, getTranslation(KEY), "group.display", getTranslation(KEY, TranslationType.DESCRIPTION), "Kristian Kraljic (kris@kra.lc)", 1); private static final int POLYGONS_X[][] = { { 4, 8, 32, 36, 32, 8, 4}, {36, 40, 40, 36, 32, 32, 36}, {36, 40, 40, 36, 32, 32, 36}, { 4, 8, 32, 36, 32, 8, 4}, { 4, 8, 8, 4, 0, 0, 4}, { 4, 8, 8, 4, 0, 0, 4}, { 4, 8, 16, 20, 16, 8, 4}, {20, 24, 32, 36, 32, 24, 20}, {20, 23, 23, 20, 17, 17, 20}, {20, 23, 23, 20, 17, 17, 20}, }; private static final int POLYGONS_Y[][] = { { 4, 0, 0, 4, 8, 8, 4}, { 4, 8, 32, 36, 32, 8, 4}, {36, 40, 64, 68, 64, 40, 36}, {68, 64, 64, 68, 72, 72, 68}, {36, 40, 64, 68, 64, 40, 36}, { 4, 8, 32, 36, 32, 8, 4}, {36, 32, 32, 36, 40, 40, 36}, {36, 32, 32, 36, 40, 40, 36}, { 9, 12, 31, 34, 31, 12, 9}, {38, 41, 60, 63, 60, 41, 38}, }; private Dimension size; private InputContact[] inputs; public TenSegmentDisplay() { size = new Dimension(60, 80); inputs = new InputContact[10]; for(int input=0;input<inputs.length;input++) inputs[input] = new InputContact(this); ContactList.setContactLocations(this, inputs); } @Override public void paint(Graphics graphics) { graphics.setColor(Color.BLACK); graphics.drawRect(10, 0, size.width-10, size.height); for(int input=0;input<inputs.length;input++) { Polygon polygon = new Polygon(POLYGONS_X[input], POLYGONS_Y[input], 7); polygon.translate(15, 4); if(inputs[input].isCharged()) { graphics.setColor(Color.RED); graphics.fillPolygon(polygon); } graphics.setColor(Color.BLACK); graphics.drawPolyline(polygon.xpoints, polygon.ypoints, polygon.npoints); }
ContactUtilities.paintSolderingJoints(graphics, 10, 0, inputs);
6
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/session/DBSessionFactory.java
[ "public class CacheEntity {\n\n private int size;\n\n private CacheMode mode;\n\n private boolean enable;\n\n public CacheEntity(int size, CacheMode mode, boolean enable) {\n this.size = size;\n this.mode = mode;\n this.enable = enable;\n if (size == 0){\n this.ena...
import org.easyarch.slardar.entity.CacheEntity; import org.easyarch.slardar.jdbc.exec.AbstractExecutor; import org.easyarch.slardar.jdbc.exec.CachedExecutor; import org.easyarch.slardar.jdbc.exec.SqlExecutor; import org.easyarch.slardar.session.impl.DefaultDBSession; import org.easyarch.slardar.session.impl.MapperDBSession; import java.sql.SQLException;
package org.easyarch.slardar.session; /** * Description : * Created by xingtianyu on 16-12-29 * 上午12:11 * description: */ public class DBSessionFactory { private Configuration configuration; public DBSessionFactory(Configuration configuration){ this.configuration = configuration; } public DBSession newDefaultSession(){ return new DefaultDBSession(configuration,getExecutor()); } public DBSession newDelegateSession(){ return new MapperDBSession(configuration,getExecutor()); } private AbstractExecutor getExecutor(){ AbstractExecutor executor = null; CacheEntity entity = configuration.getCacheEntity(); try { if (entity.isEnable()){
executor = new CachedExecutor(new SqlExecutor(
3
maximeAudrain/jenerate
org.jenerate/src/java/org/jenerate/internal/ui/dialogs/factory/impl/CompareToDialogFactory.java
[ "public interface CommandIdentifier {\r\n\r\n /**\r\n * @return the unique string identifier of a command\r\n */\r\n String getIdentifier();\r\n\r\n}\r", "public enum MethodsGenerationCommandIdentifier implements CommandIdentifier {\r\n\r\n EQUALS_HASH_CODE(\"org.jenerate.commands.GenerateEqualsH...
import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Set; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.swt.widgets.Shell; import org.jenerate.internal.domain.data.CompareToGenerationData; import org.jenerate.internal.domain.identifier.CommandIdentifier; import org.jenerate.internal.domain.identifier.StrategyIdentifier; import org.jenerate.internal.domain.identifier.impl.MethodsGenerationCommandIdentifier; import org.jenerate.internal.manage.DialogStrategyManager; import org.jenerate.internal.manage.PreferencesManager; import org.jenerate.internal.ui.dialogs.factory.DialogFactory; import org.jenerate.internal.ui.dialogs.factory.DialogFactoryHelper; import org.jenerate.internal.ui.dialogs.impl.OrderableFieldDialogImpl; import org.jenerate.internal.util.JavaInterfaceCodeAppender;
package org.jenerate.internal.ui.dialogs.factory.impl; /** * {@link DialogFactory} implementation for the {@link CompareToDialog} * * @author maudrain */ public class CompareToDialogFactory extends AbstractDialogFactory<CompareToGenerationData> { private JavaInterfaceCodeAppender javaInterfaceCodeAppender; /** * Constructor * * @param dialogFactoryHelper the dialog factory helper * @param preferencesManager the preference manager * @param javaInterfaceCodeAppender the java interface code appender */
public CompareToDialogFactory(DialogStrategyManager dialogStrategyManager, DialogFactoryHelper dialogFactoryHelper,
2
FlyingPumba/SoundBox
src/com/arcusapp/soundbox/adapter/FoldersActivityAdapter.java
[ "public class SoundBoxApplication extends Application {\n private static Context appContext;\n\n public static final String ACTION_MAIN_ACTIVITY = \"com.arcusapp.soundbox.action.MAIN_ACTIVITY\";\n public static final String ACTION_FOLDERS_ACTIVITY = \"com.arcusapp.soundbox.action.FOLDERS_ACTIVITY\";\n p...
import com.arcusapp.soundbox.activity.FoldersActivity; import com.arcusapp.soundbox.data.MediaProvider; import com.arcusapp.soundbox.model.SongEntry; import com.arcusapp.soundbox.util.MediaEntryHelper; import java.io.File; import java.util.ArrayList; import java.util.List; import android.provider.MediaStore; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.arcusapp.soundbox.R; import com.arcusapp.soundbox.SoundBoxApplication;
/* * SoundBox - Android Music Player * Copyright (C) 2013 Iván Arcuschin Moreno * * This file is part of SoundBox. * * SoundBox 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. * * SoundBox 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 SoundBox. If not, see <http://www.gnu.org/licenses/>. */ package com.arcusapp.soundbox.adapter; public class FoldersActivityAdapter extends BaseAdapter { private FoldersActivity mActivity; private TextView txtCurrentDirectory; private List<File> subDirs;
private List<SongEntry> songs;
3
4FunApp/4Fun
client/FourFun/app/src/main/java/com/joker/fourfun/ui/MovieDetailActivity.java
[ "public class Constants {\n public static final String MAIN_ACTIVITY_BUNDLE = \"main_bundle\";\n public static final String MEDIA_BUNDLE = \"media_bundle\";\n public static final String MOVIE_BUNDLE = \"movie_bundle\";\n public static final String PICTURE_BUNDLE = \"picture_bundle\";\n public static ...
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Layout; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.AbsoluteSizeSpan; import android.text.style.AlignmentSpan; import android.widget.TextView; import android.widget.Toast; import com.joker.fourfun.Constants; import com.joker.fourfun.R; import com.joker.fourfun.base.BaseMvpActivity; import com.joker.fourfun.model.Movie; import com.joker.fourfun.presenter.MovieDetailPresenter; import com.joker.fourfun.presenter.contract.MovieDetailContract; import com.joker.fourfun.utils.SystemUtil; import butterknife.BindView;
package com.joker.fourfun.ui; public class MovieDetailActivity extends BaseMvpActivity<MovieDetailContract.View, MovieDetailPresenter> implements MovieDetailContract.View { @BindView(R.id.tv_movie_content) TextView mTvMovieContent; private Movie mMovie; public static Intent newInstance(AppCompatActivity activity, Bundle bundle) { Intent intent = new Intent(activity, MovieDetailActivity.class); intent.putExtra(Constants.MOVIE_BUNDLE, bundle); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); analyseIntent();
String day = SystemUtil.beforeToday(0);
4
Ericsongyl/PullRefreshAndLoadMore
sample/src/main/java/com/nicksong/pullrefresh/activities/NestedScrollingActivity.java
[ "public class Fragment0 extends Fragment implements BaseHeaderView.OnRefreshListener, BaseFooterView.OnLoadListener {\n View view;\n\n ListView listView;\n BaseHeaderView headerView;\n BaseFooterView footerView;\n\n ArrayAdapter adapter;\n\n List<String> list = new ArrayList<String>();\n\n @Nul...
import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.nicksong.pullrefresh.R; import com.nicksong.pullrefresh.fragment.Fragment0; import com.nicksong.pullrefresh.fragment.Fragment2; import com.nicksong.pullrefresh.fragment.Fragment3; import com.nicksong.pullrefresh.fragment.Fragment1; import com.nicksong.pullrefresh.fragment.Fragment4; import java.util.ArrayList;
package com.nicksong.pullrefresh.activities; /** * Modified by nicksong at 2016/12/20 */ public class NestedScrollingActivity extends AppCompatActivity { ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_nestedscrolling); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ArrayList<Fragment> fragments = new ArrayList<>();
fragments.add(new Fragment0());
0
bkueng/clash_of_balls
src/com/sapos_aplastados/game/clash_of_balls/menu/MenuItemList.java
[ "public class Texture {\n\tprivate TextureBase m_texture;\n\t\n\tpublic int textureHandle() { return m_texture.textureHandle(); }\n\t\n\t//tex_coords can be null to use default tex coords\n\tpublic Texture(TextureBase t) {\n\t\tm_texture = t;\n\t}\n\t\n\tpublic void useTexture(RenderHelper renderer) {\n m_te...
import java.util.ArrayList; import java.util.List; import com.sapos_aplastados.game.clash_of_balls.R; import com.sapos_aplastados.game.clash_of_balls.Texture; import com.sapos_aplastados.game.clash_of_balls.TextureManager; import com.sapos_aplastados.game.clash_of_balls.VertexBufferFloat; import com.sapos_aplastados.game.clash_of_balls.game.RenderHelper; import com.sapos_aplastados.game.clash_of_balls.game.Vector; import com.sapos_aplastados.game.clash_of_balls.menu.MenuItemArrow.ArrowType;
/* * Copyright (C) 2012-2013 Hans Hardmeier <hanshardmeier@gmail.com> * Copyright (C) 2012-2013 Andrin Jenal * Copyright (C) 2012-2013 Beat Küng <beat-kueng@gmx.net> * * 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; version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ package com.sapos_aplastados.game.clash_of_balls.menu; /** * this list can hold multiple MenuItem's in a list * scrolling through the list is done through 2 buttons * * Note: the added MenuItems must have the same width as the list! * the position will be set by this class * */ public class MenuItemList extends MenuItem { private static final String LOG_TAG = "MenuItemList"; private float m_view_height; //=m_size.y - (next or prev buttons height) private final float m_item_spacing; //vertical spacing between 2 items private List<MenuItem> m_items = new ArrayList<MenuItem>(); private int m_sel_item=-1; private int m_first_drawn_item = 0; private int m_last_drawn_item = 0; //page selection MenuItemArrow m_left_arrow; boolean m_left_arrow_visible = true; MenuItemArrow m_right_arrow; boolean m_right_arrow_visible = true; private Texture m_background_texture;
public MenuItemList(Vector position, Vector size, Vector arrow_button_size
3