repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
mjeanroy/node-maven-plugin
src/test/java/com/github/mjeanroy/maven/plugins/node/mojos/PreCleanMojoTest.java
5783
/** * The MIT License (MIT) * * Copyright (c) 2015-2021 Mickael Jeanroy * * 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 com.github.mjeanroy.maven.plugins.node.mojos; import com.github.mjeanroy.maven.plugins.node.commands.Command; import com.github.mjeanroy.maven.plugins.node.commands.CommandExecutor; import com.github.mjeanroy.maven.plugins.node.commands.CommandResult; import com.github.mjeanroy.maven.plugins.node.loggers.NpmLogger; import com.github.mjeanroy.maven.plugins.node.model.IncrementalBuildConfiguration; import com.github.mjeanroy.maven.plugins.node.tests.builders.IncrementalBuildConigurationTestBuilder; import org.apache.maven.plugin.logging.Log; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import java.io.File; import static com.github.mjeanroy.maven.plugins.node.tests.FileTestUtils.join; import static com.github.mjeanroy.maven.plugins.node.tests.ReflectTestUtils.readPrivate; import static com.github.mjeanroy.maven.plugins.node.tests.ReflectTestUtils.writePrivate; import static com.github.mjeanroy.maven.plugins.node.tests.builders.CommandResultTestBuilder.successResult; import static java.util.Arrays.asList; import static java.util.Collections.singleton; import static java.util.Collections.singletonMap; import static org.apache.commons.lang3.reflect.FieldUtils.readField; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; public class PreCleanMojoTest extends AbstractNpmScriptIncrementalMojoTest<PreCleanMojo> { @Override String mojoName() { return "pre-clean"; } @Override String script() { return "install"; } @Override String scriptParameterName() { return "preCleanScript"; } @Override void enableSkip(PreCleanMojo mojo) { writePrivate(mojo, "skipPreClean", true); } @Test public void it_should_execute_mojo_using_yarn_to_install_dependencies() throws Exception { PreCleanMojo mojo = lookupMojo("mojo-with-npm-client"); CommandResult result = successResult(); CommandExecutor executor = (CommandExecutor) readField(mojo, "executor", true); when(executor.execute(any(File.class), any(Command.class), any(NpmLogger.class), ArgumentMatchers.<String, String>anyMap())).thenReturn(result); mojo.execute(); Log logger = (Log) readField(mojo, "log", true); verify(logger).info("Running: yarn install --maven"); verify(logger, never()).error(anyString()); ArgumentCaptor<Command> cmdCaptor = ArgumentCaptor.forClass(Command.class); verify(executor).execute(any(File.class), cmdCaptor.capture(), any(NpmLogger.class), ArgumentMatchers.<String, String>anyMap()); Command cmd = cmdCaptor.getValue(); assertThat(cmd).isNotNull(); assertThat(cmd.toString()).isEqualTo("yarn install --maven"); } @Test public void it_should_write_input_state_after_build() throws Exception { IncrementalBuildConfiguration incrementalBuild = IncrementalBuildConigurationTestBuilder.of(true); PreCleanMojo mojo = lookupMojo("mojo", singletonMap("incrementalBuild", incrementalBuild)); File workingDirectory = readPrivate(mojo, "workingDirectory"); mojo.execute(); verifyStateFile(mojo, singleton( join(workingDirectory, "package.json") )); } @Test public void it_should_write_input_state_with_package_lock_after_build() throws Exception { PreCleanMojo mojo = lookupMojo("mojo-with-package-lock"); File workingDirectory = readPrivate(mojo, "workingDirectory"); mojo.execute(); verifyStateFile(mojo, asList( join(workingDirectory, "package-lock.json"), join(workingDirectory, "package.json") )); } @Test public void it_should_write_input_state_with_yarn_lock_after_build() throws Exception { PreCleanMojo mojo = lookupMojo("mojo-with-yarn-lock"); File workingDirectory = readPrivate(mojo, "workingDirectory"); mojo.execute(); verifyStateFile(mojo, asList( join(workingDirectory, "package.json"), join(workingDirectory, "yarn.lock") )); } @Test public void it_should_re_run_mojo_after_incremental_build() throws Exception { IncrementalBuildConfiguration incrementalBuild = IncrementalBuildConigurationTestBuilder.of(true); PreCleanMojo mojo = lookupMojo("mojo", singletonMap( "incrementalBuild", incrementalBuild )); mojo.execute(); resetMojo(mojo); mojo.execute(); verify(readPrivate(mojo, "log", Log.class)).info("Command npm install already done, no changes detected, skipping."); verifyZeroInteractions(readPrivate(mojo, "executor")); } }
mit
bwkimmel/jmist
jmist-core/src/main/java/ca/eandb/jmist/framework/VisibilityFunction3.java
1676
/** * Java Modular Image Synthesis Toolkit (JMIST) * Copyright (C) 2018 Bradley W. Kimmel * * 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.eandb.jmist.framework; import ca.eandb.jmist.math.Ray3; /** * A function that determines if a line segment or ray intersects * something. * @author Brad Kimmel */ public interface VisibilityFunction3 { /** * Determines whether the given ray intersects * an object within the interval [0, infinity). * @param ray The ray with which to check for an intersection. * @return True if no intersection was found, false otherwise. */ boolean visibility(Ray3 ray); }
mit
ReneMuetti/RFTools
src/main/java/mcjty/rftools/blocks/blockprotector/BlockProtectorBlock.java
7027
package mcjty.rftools.blocks.blockprotector; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import mcjty.api.Infusable; import mcjty.rftools.blocks.GenericRFToolsBlock; import mcjty.rftools.RFTools; import mcjty.rftools.items.smartwrench.SmartWrenchItem; import mcjty.varia.BlockTools; import mcjty.varia.Coordinate; import mcjty.varia.GlobalCoordinate; import mcjty.varia.Logging; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import org.lwjgl.input.Keyboard; import java.util.List; public class BlockProtectorBlock extends GenericRFToolsBlock implements Infusable { private IIcon iconFrontOn; public BlockProtectorBlock() { super(Material.iron, BlockProtectorTileEntity.class, true); setBlockName("blockProtectorBlock"); setHorizRotation(true); setCreativeTab(RFTools.tabRfTools); } @Override public int getGuiID() { return RFTools.GUI_BLOCK_PROTECTOR; } @Override public String getIdentifyingIconName() { return "machineBlockProtector"; } @Override public void registerBlockIcons(IIconRegister iconRegister) { super.registerBlockIcons(iconRegister); iconFrontOn = iconRegister.registerIcon(RFTools.MODID + ":" + "machineBlockProtectorOn"); } @SideOnly(Side.CLIENT) @Override public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean whatIsThis) { super.addInformation(itemStack, player, list, whatIsThis); NBTTagCompound tagCompound = itemStack.getTagCompound(); if (tagCompound != null) { int id = tagCompound.getInteger("protectorId"); list.add(EnumChatFormatting.GREEN + "Id: " + id); } if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) { list.add(EnumChatFormatting.WHITE + "Use the smart wrench with this block to select"); list.add(EnumChatFormatting.WHITE + "other blocks to protect them against explosions"); list.add(EnumChatFormatting.WHITE + "and other breackage."); list.add(EnumChatFormatting.YELLOW + "Infusing bonus: reduced power consumption."); } else { list.add(EnumChatFormatting.WHITE + RFTools.SHIFT_MESSAGE); } } @SideOnly(Side.CLIENT) @Override public List<String> getWailaBody(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { super.getWailaBody(itemStack, currenttip, accessor, config); TileEntity te = accessor.getTileEntity(); if (te instanceof BlockProtectorTileEntity) { BlockProtectorTileEntity blockProtectorTileEntity = (BlockProtectorTileEntity) te; int id = blockProtectorTileEntity.getId(); currenttip.add(EnumChatFormatting.GREEN + "Id: " + id); currenttip.add(EnumChatFormatting.GREEN + "Blocks protected: " + blockProtectorTileEntity.getProtectedBlocks().size()); } return currenttip; } @Override protected boolean wrenchSneakSelect(World world, int x, int y, int z, EntityPlayer player) { if (!world.isRemote) { GlobalCoordinate currentBlock = SmartWrenchItem.getCurrentBlock(player.getHeldItem()); if (currentBlock == null) { SmartWrenchItem.setCurrentBlock(player.getHeldItem(), new GlobalCoordinate(new Coordinate(x, y, z), world.provider.dimensionId)); Logging.message(player, EnumChatFormatting.YELLOW + "Selected block"); } else { SmartWrenchItem.setCurrentBlock(player.getHeldItem(), null); Logging.message(player, EnumChatFormatting.YELLOW + "Cleared selected block"); } } return true; } @Override public int onBlockPlaced(World world, int x, int y, int z, int side, float sx, float sy, float sz, int meta) { int rc = super.onBlockPlaced(world, x, y, z, side, sx, sy, sz, meta); if (world.isRemote) { return rc; } BlockProtectors protectors = BlockProtectors.getProtectors(world); GlobalCoordinate gc = new GlobalCoordinate(new Coordinate(x, y, z), world.provider.dimensionId); protectors.getNewId(gc); protectors.save(world); return rc; } @Override @SideOnly(Side.CLIENT) public GuiContainer createClientGui(EntityPlayer entityPlayer, TileEntity tileEntity) { BlockProtectorTileEntity blockProtectorTileEntity = (BlockProtectorTileEntity) tileEntity; return new GuiBlockProtector(blockProtectorTileEntity, new BlockProtectorContainer(entityPlayer)); } @Override public Container createServerContainer(EntityPlayer entityPlayer, TileEntity tileEntity) { return new BlockProtectorContainer(entityPlayer); } @Override public void onNeighborBlockChange(World world, int x, int y, int z, Block block) { checkRedstoneWithTE(world, x, y, z); } @Override public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityLivingBase, ItemStack itemStack) { super.onBlockPlacedBy(world, x, y, z, entityLivingBase, itemStack); // This is called AFTER onBlockPlaced below. Here we need to fix the destination settings. if (!world.isRemote) { BlockProtectorTileEntity blockProtectorTileEntity = (BlockProtectorTileEntity) world.getTileEntity(x, y, z); blockProtectorTileEntity.getOrCalculateID(); blockProtectorTileEntity.updateDestination(); } } @Override public void breakBlock(World world, int x, int y, int z, Block block, int meta) { super.breakBlock(world, x, y, z, block, meta); if (world.isRemote) { return; } BlockProtectors protectors = BlockProtectors.getProtectors(world); protectors.removeDestination(new Coordinate(x, y, z), world.provider.dimensionId); protectors.save(world); } @Override public IIcon getIconInd(IBlockAccess blockAccess, int x, int y, int z, int meta) { int state = BlockTools.getState(meta); switch (state) { case 0: return iconInd; case 1: return iconFrontOn; default: return iconInd; } } }
mit
kelong/react-native-with-amazon-s3
node_modules/react-native-fs/android/src/main/java/com/rnfs/RNFSManager.java
9838
package com.rnfs; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import android.os.Environment; import android.os.AsyncTask; import android.util.Base64; import android.content.Context; import android.support.annotation.Nullable; import android.util.SparseArray; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.BufferedInputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.HttpURLConnection; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.WritableArray; import com.facebook.react.modules.core.DeviceEventManagerModule; public class RNFSManager extends ReactContextBaseJavaModule { private static final String NSDocumentDirectoryPath = "NSDocumentDirectoryPath"; private static final String NSPicturesDirectoryPath = "NSPicturesDirectoryPath"; private static final String NSCachesDirectoryPath = "NSCachesDirectoryPath"; private static final String NSDocumentDirectory = "NSDocumentDirectory"; private static final String NSFileTypeRegular = "NSFileTypeRegular"; private static final String NSFileTypeDirectory = "NSFileTypeDirectory"; private SparseArray<Downloader> downloaders = new SparseArray<Downloader>(); public RNFSManager(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "RNFSManager"; } @ReactMethod public void writeFile(String filepath, String base64Content, ReadableMap options, Callback callback) { try { byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT); FileOutputStream outputStream = new FileOutputStream(filepath); outputStream.write(bytes); outputStream.close(); callback.invoke(null, true, filepath); } catch (Exception ex) { ex.printStackTrace(); callback.invoke(makeErrorPayload(ex)); } } @ReactMethod public void exists(String filepath, Callback callback) { try { File file = new File(filepath); callback.invoke(null, file.exists()); } catch (Exception ex) { ex.printStackTrace(); callback.invoke(makeErrorPayload(ex)); } } @ReactMethod public void readFile(String filepath, Callback callback) { try { File file = new File(filepath); if (!file.exists()) throw new Exception("File does not exist"); FileInputStream inputStream = new FileInputStream(filepath); byte[] buffer = new byte[(int)file.length()]; inputStream.read(buffer); String base64Content = Base64.encodeToString(buffer, Base64.NO_WRAP); callback.invoke(null, base64Content); } catch (Exception ex) { ex.printStackTrace(); callback.invoke(makeErrorPayload(ex)); } } @ReactMethod public void moveFile(String filepath, String destPath, Callback callback) { try { File from = new File(filepath); File to = new File(destPath); from.renameTo(to); callback.invoke(null, true, destPath); } catch (Exception ex) { ex.printStackTrace(); callback.invoke(makeErrorPayload(ex)); } } @ReactMethod public void readDir(String directory, Callback callback) { try { File file = new File(directory); if (!file.exists()) throw new Exception("Folder does not exist"); File[] files = file.listFiles(); WritableArray fileMaps = Arguments.createArray(); for (File childFile : files) { WritableMap fileMap = Arguments.createMap(); fileMap.putString("name", childFile.getName()); fileMap.putString("path", childFile.getAbsolutePath()); fileMap.putInt("size", (int)childFile.length()); fileMap.putInt("type", childFile.isDirectory() ? 1 : 0); fileMaps.pushMap(fileMap); } callback.invoke(null, fileMaps); } catch (Exception ex) { ex.printStackTrace(); callback.invoke(makeErrorPayload(ex)); } } @ReactMethod public void stat(String filepath, Callback callback) { try { File file = new File(filepath); if (!file.exists()) throw new Exception("File does not exist"); WritableMap statMap = Arguments.createMap(); statMap.putInt("ctime", (int)(file.lastModified() / 1000)); statMap.putInt("mtime", (int)(file.lastModified() / 1000)); statMap.putInt("size", (int)file.length()); statMap.putInt("type", file.isDirectory() ? 1 : 0); callback.invoke(null, statMap); } catch (Exception ex) { ex.printStackTrace(); callback.invoke(makeErrorPayload(ex)); } } @ReactMethod public void unlink(String filepath, Callback callback) { try { File file = new File(filepath); if (!file.exists()) throw new Exception("File does not exist"); boolean success = DeleteRecursive(file); callback.invoke(null, success, filepath); } catch (Exception ex) { ex.printStackTrace(); callback.invoke(makeErrorPayload(ex)); } } private boolean DeleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) { for (File child : fileOrDirectory.listFiles()) { DeleteRecursive(child); } } return fileOrDirectory.delete(); } @ReactMethod public void mkdir(String filepath, Boolean excludeFromBackup, Callback callback) { try { File file = new File(filepath); file.mkdirs(); boolean success = file.exists(); callback.invoke(null, success, filepath); } catch (Exception ex) { ex.printStackTrace(); callback.invoke(makeErrorPayload(ex)); } } private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) { reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); } @ReactMethod public void downloadFile(String urlStr, final String filepath, final int jobId, final Callback callback) { try { File file = new File(filepath); URL url = new URL(urlStr); DownloadParams params = new DownloadParams(); params.src = url; params.dest = file; params.onTaskCompleted = new DownloadParams.OnTaskCompleted() { public void onTaskCompleted(DownloadResult res) { if (res.exception == null) { WritableMap infoMap = Arguments.createMap(); infoMap.putInt("jobId", jobId); infoMap.putInt("statusCode", res.statusCode); infoMap.putInt("bytesWritten", res.bytesWritten); callback.invoke(null, infoMap); } else { callback.invoke(makeErrorPayload(res.exception)); } } }; params.onDownloadBegin = new DownloadParams.OnDownloadBegin() { public void onDownloadBegin(int statusCode, int contentLength, Map<String, String> headers) { WritableMap headersMap = Arguments.createMap(); for (Map.Entry<String, String> entry : headers.entrySet()) { headersMap.putString(entry.getKey(), entry.getValue()); } WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); data.putInt("statusCode", statusCode); data.putInt("contentLength", contentLength); data.putMap("headers", headersMap); sendEvent(getReactApplicationContext(), "DownloadBegin-" + jobId, data); } }; params.onDownloadProgress = new DownloadParams.OnDownloadProgress() { public void onDownloadProgress(int contentLength, int bytesWritten) { WritableMap data = Arguments.createMap(); data.putInt("contentLength", contentLength); data.putInt("bytesWritten", bytesWritten); sendEvent(getReactApplicationContext(), "DownloadProgress-" + jobId, data); } }; Downloader downloader = new Downloader(); downloader.execute(params); this.downloaders.put(jobId, downloader); } catch (Exception ex) { ex.printStackTrace(); callback.invoke(makeErrorPayload(ex)); } } @ReactMethod public void stopDownload(int jobId) { Downloader downloader = this.downloaders.get(jobId); if (downloader != null) { downloader.stop(); } } @ReactMethod public void pathForBundle(String bundleNamed, Callback callback) { // TODO: Not sure what equilivent would be? } private WritableMap makeErrorPayload(Exception ex) { WritableMap error = Arguments.createMap(); error.putString("message", ex.getMessage()); return error; } @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put(NSDocumentDirectory, 0); constants.put(NSDocumentDirectoryPath, this.getReactApplicationContext().getFilesDir().getAbsolutePath()); constants.put(NSPicturesDirectoryPath, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()); constants.put(NSCachesDirectoryPath, this.getReactApplicationContext().getCacheDir().getAbsolutePath()); constants.put(NSFileTypeRegular, 0); constants.put(NSFileTypeDirectory, 1); return constants; } }
mit
arteam/codeforces
src/test/java/ProsperousLotTest.java
503
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; class ProsperousLotTest { @ParameterizedTest @CsvSource({ "1, 4", "2, 8", "6, 888", "5, 884", "37, -1", "36, 888888888888888888", }) void test(int numberOfLoops, String result) { Assertions.assertEquals(result, new ProsperousLot().solve(numberOfLoops)); } }
mit
eaglesakura/android-framework
src/main/java/com/eaglesakura/android/framework/delegate/task/SupportFragmentTask.java
2701
package com.eaglesakura.android.framework.delegate.task; import com.eaglesakura.android.framework.delegate.fragment.SupportFragmentDelegate; import com.eaglesakura.android.framework.delegate.lifecycle.FragmentLifecycleDelegate; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.Size; import android.support.annotation.StringRes; import android.support.v4.app.Fragment; import android.view.View; import java.util.List; /** * UIFragment用の分離タスク */ public class SupportFragmentTask<FragmentDelegateType extends SupportFragmentDelegate, LifecycleDelegateType extends FragmentLifecycleDelegate> extends UiLifecycleTask<LifecycleDelegateType> { protected final FragmentDelegateType mFragment; public SupportFragmentTask(FragmentDelegateType fragment, LifecycleDelegateType delegate) { super(delegate); mFragment = fragment; } public Resources getResources() { return mFragment.getFragment().getResources(); } public String getString(@StringRes int resId, Object... args) { return mFragment.getFragment().getString(resId, args); } @NonNull public Fragment getFragment() { return mFragment.getFragment(); } @Nullable public Fragment getParentFragment() { return mFragment.getParentFragment(); } public Activity getActivity() { return mFragment.getActivity(); } public View getView() { return mFragment.getView(); } public Context getContext() { return getFragment().getContext(); } @Nullable public <T extends View> T findViewByIdFromActivity(Class<T> clazz, int id) { return mFragment.findViewByIdFromActivity(clazz, id); } @Nullable public <T extends View> T findViewById(Class<T> clazz, int id) { return mFragment.findViewById(clazz, id); } @Nullable public <T> T getParent(@NonNull Class<T> clazz) { return mFragment.getParent(clazz); } @NonNull public <T> List<T> listInterfaces(@NonNull Class<T> clazz) { return mFragment.listInterfaces(clazz); } @NonNull @Size(min = 1) public <T> List<T> listInterfacesOrThrow(@NonNull Class<T> clazz) { return mFragment.listInterfacesOrThrow(clazz); } public <T> T findInterfaceOrThrow(@NonNull Class<T> clazz) { return mFragment.findInterfaceOrThrow(clazz); } @NonNull public <T> T getParentOrThrow(@NonNull Class<T> clazz) { return mFragment.getParentOrThrow(clazz); } }
mit
GaloisInc/Votail
external_tools/JML/org/jmlspecs/samples/prelimdesign/IntMathOps4_JML_TestData.java
6478
// @(#)$Id: IntMathOps4_JML_TestData.java,v 1.5 2005/12/04 18:09:42 leavens Exp $ // Copyright (C) 2004 Iowa State University // This file is part of JML // JML 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, or (at your option) // any later version. // JML 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 JML; see the file COPYING. If not, write to // the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. package org.jmlspecs.samples.prelimdesign; /** Supply test data for the JML and JUnit based testing of * IntMathOps4. * * <p>Test data is supplied by overriding methods in this class. See * the JML documentation and the comments below about how to do this. * * <p>This class is also the place to override the <kbd>setUp()</kbd> * and <kbd>tearDown()</kbd> methods if your testing needs some * actions to be taken before and after each test is executed. * * <p>This class is never rewritten by jmlunit. * */ public abstract class IntMathOps4_JML_TestData extends junit.framework.TestCase { /** Initialize this class. */ public IntMathOps4_JML_TestData(java.lang.String name) { super(name); } /** Return the overall test suite for accumulating tests; the * result will hold every test that will be run. This factory * method can be altered to provide filtering of test suites, as * they are added to this overall test suite, based on various * criteria. The test driver will first call the method * addTestSuite to add a test suite formed from custom programmed * test methods (named testX for some X), which you can add to * this class; this initial test suite will also include a method * to check that the code being tested was compiled with jmlc. * After that, for each method to be tested, a test suite * containing tests for that method will be added to this overall * test suite, using the addTest method. Test suites added for a * method will have some subtype of TestSuite and that method's * name as their name. So, if you want to control the overall * suite of tests for testing some method, e.g., to limit the * number of tests for each method, return a special-purpose * subclass of junit.framework.TestSuite in which you override the * addTest method. * @see junit.framework.TestSuite */ //@ assignable objectState; //@ ensures \result != null; public junit.framework.TestSuite overallTestSuite() { return new junit.framework.TestSuite("Overall tests for IntMathOps4"); } /** Return an empty test suite for accumulating tests for the * named method. This factory method can be altered to provide * filtering or limiting of the tests for the named method, as * they are added to the test suite for this method. The driver * will add individual tests using the addTest method. So, if you * want to filter individual tests, return a subclass of TestSuite * in which you override the addTest method. * @param methodName The method the tests in this suite are for. * @see junit.framework.TestSuite * @see org.jmlspecs.jmlunit.strategies.LimitedTestSuite */ //@ assignable objectState; //@ ensures \result != null; public junit.framework.TestSuite emptyTestSuiteFor (java.lang.String methodName) { return new junit.framework.TestSuite(methodName); } // You should edit the following code to supply test data. In the // skeleton originally supplied below the jmlunit tool made a // guess as to a minimal strategy for generating test data for // each type of object used as a receiver, and each type used as // an argument. There is a library of strategies for generating // test data in org.jmlspecs.jmlunit.strategies, which are used in // the tool's guesses. See the documentation for JML and in // particular for the org.jmlspecs.jmlunit.strategies package for // a general discussion of how to do this. (This package's // documentation is available through the JML.html file in the top // of the JML release, and also in the package.html file that // ships with the package.) // // You can change the strategies guessed by the jmlunit tool, and // you can also define new ones to suit your needs. You can also // delete any useless sample test data that has been generated // for you to show you the pattern of how to add your own test // data. The only requirement is that you implement the methods // below. // // If you change the type being tested in a way that introduces // new types of arguments for some methods, then you will have to // introduce (by hand) definitions that are similar to the ones // below, because jmlunit never rewrites this file. /** Return a new, freshly allocated indefinite iterator that * produces test data of type * int * for testing the method named by the String methodName in * a loop that encloses loopsThisSurrounds many other loops. * @param methodName name of the method for which this * test data will be used. * @param loopsThisSurrounds number of loops that the test * contains inside this one. */ //@ requires methodName != null && loopsThisSurrounds >= 0; //@ ensures \fresh(\result); protected org.jmlspecs.jmlunit.strategies.IntIterator vintIter (java.lang.String methodName, int loopsThisSurrounds) { return vintStrategy.intIterator(); } /** The strategy for generating test data of type * int. */ private org.jmlspecs.jmlunit.strategies.IntStrategyType vintStrategy = new org.jmlspecs.jmlunit.strategies.IntBigStrategy() { protected int[] addData() { return new int[] { // replace this comment with test data if desired }; } }; }
mit
Yirendai/cicada
cicada-collector/src/main/java/com/yirendai/infra/cicada/util/elastic/IndexManager.java
187
package com.yirendai.infra.cicada.util.elastic; import org.springframework.stereotype.Component; @Component public interface IndexManager { String getCurrentIndexName(String type); }
mit
selvasingh/azure-sdk-for-java
sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/EdgeUsageDataCollectionPolicy.java
4192
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.mediaservices.v2018_07_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * The EdgeUsageDataCollectionPolicy model. */ public class EdgeUsageDataCollectionPolicy { /** * Usage data collection frequency in ISO 8601 duration format e.g. PT10M , * PT5H. */ @JsonProperty(value = "dataCollectionFrequency") private String dataCollectionFrequency; /** * Usage data reporting frequency in ISO 8601 duration format e.g. PT10M , * PT5H. */ @JsonProperty(value = "dataReportingFrequency") private String dataReportingFrequency; /** * Maximum time for which the functionality of the device will not be * hampered for not reporting the usage data. */ @JsonProperty(value = "maxAllowedUnreportedUsageDuration") private String maxAllowedUnreportedUsageDuration; /** * Details of Event Hub where the usage will be reported. */ @JsonProperty(value = "eventHubDetails") private EdgeUsageDataEventHub eventHubDetails; /** * Get usage data collection frequency in ISO 8601 duration format e.g. PT10M , PT5H. * * @return the dataCollectionFrequency value */ public String dataCollectionFrequency() { return this.dataCollectionFrequency; } /** * Set usage data collection frequency in ISO 8601 duration format e.g. PT10M , PT5H. * * @param dataCollectionFrequency the dataCollectionFrequency value to set * @return the EdgeUsageDataCollectionPolicy object itself. */ public EdgeUsageDataCollectionPolicy withDataCollectionFrequency(String dataCollectionFrequency) { this.dataCollectionFrequency = dataCollectionFrequency; return this; } /** * Get usage data reporting frequency in ISO 8601 duration format e.g. PT10M , PT5H. * * @return the dataReportingFrequency value */ public String dataReportingFrequency() { return this.dataReportingFrequency; } /** * Set usage data reporting frequency in ISO 8601 duration format e.g. PT10M , PT5H. * * @param dataReportingFrequency the dataReportingFrequency value to set * @return the EdgeUsageDataCollectionPolicy object itself. */ public EdgeUsageDataCollectionPolicy withDataReportingFrequency(String dataReportingFrequency) { this.dataReportingFrequency = dataReportingFrequency; return this; } /** * Get maximum time for which the functionality of the device will not be hampered for not reporting the usage data. * * @return the maxAllowedUnreportedUsageDuration value */ public String maxAllowedUnreportedUsageDuration() { return this.maxAllowedUnreportedUsageDuration; } /** * Set maximum time for which the functionality of the device will not be hampered for not reporting the usage data. * * @param maxAllowedUnreportedUsageDuration the maxAllowedUnreportedUsageDuration value to set * @return the EdgeUsageDataCollectionPolicy object itself. */ public EdgeUsageDataCollectionPolicy withMaxAllowedUnreportedUsageDuration(String maxAllowedUnreportedUsageDuration) { this.maxAllowedUnreportedUsageDuration = maxAllowedUnreportedUsageDuration; return this; } /** * Get details of Event Hub where the usage will be reported. * * @return the eventHubDetails value */ public EdgeUsageDataEventHub eventHubDetails() { return this.eventHubDetails; } /** * Set details of Event Hub where the usage will be reported. * * @param eventHubDetails the eventHubDetails value to set * @return the EdgeUsageDataCollectionPolicy object itself. */ public EdgeUsageDataCollectionPolicy withEventHubDetails(EdgeUsageDataEventHub eventHubDetails) { this.eventHubDetails = eventHubDetails; return this; } }
mit
flyzsd/java-code-snippets
ibm.jdk8/src/javax/xml/ws/BindingType.java
1859
/*=========================================================================== * Licensed Materials - Property of IBM * "Restricted Materials of IBM" * * IBM SDK, Java(tm) Technology Edition, v8 * (C) Copyright IBM Corp. 2005, 2010. All Rights Reserved * * US Government Users Restricted Rights - Use, duplication or disclosure * restricted by GSA ADP Schedule Contract with IBM Corp. *=========================================================================== */ /* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.xml.ws; import java.lang.annotation.Documented; import java.lang.annotation.Target; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * The <code>BindingType</code> annotation is used to * specify the binding to use for a web service * endpoint implementation class. * <p> * This annotation may be overriden programmatically or via * deployment descriptors, depending on the platform in use. * * @since JAX-WS 2.0 * **/ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface BindingType { /** * A binding identifier (a URI). * If not specified, the default is the SOAP 1.1 / HTTP binding. * <p> * See the <code>SOAPBinding</code> and <code>HTTPBinding</code> * for the definition of the standard binding identifiers. * * @see javax.xml.ws.Binding * @see javax.xml.ws.soap.SOAPBinding#SOAP11HTTP_BINDING * @see javax.xml.ws.soap.SOAPBinding#SOAP12HTTP_BINDING * @see javax.xml.ws.http.HTTPBinding#HTTP_BINDING */ String value() default "" ; }
mit
RedBeardCory/savage
src/models/LargeMap.java
1872
package models; import java.util.HashMap; import java.util.Map; /** * the LargeMap class is the minimap type of map which stores all the other maps inside it * It will be the overall map * */ public class LargeMap { private MedMap[][] miniMap; private Biome aveBiome = Biome.OBLIVION; private int height; private int width; /** * initialising the playable area * @param width the width of the grid * @param height the height of the grid */ public LargeMap(int width, int height) { this.miniMap = this.init(width, height); } /** * some fancy randomised generation of tiles * * @param width is the width of the grid * @param height is the height of the grid * @return new randomly generated tile array */ public MedMap[][] init(int width, int height) { MedMap[][] map = new MedMap[width][height]; // loop over the map and call generate for the children for(int x = 0; x < width; x++) { for(int y = 0; y < height; y++) { map[x][y] = new MedMap(width, height); } } return map; } public MedMap[][] getMiniMap() { return miniMap; } public void setMiniMap(MedMap[][] miniMap) { this.miniMap = miniMap; } /** * counts the average biome of the children and returns it, going to use for rendering purposes * @return Biome */ public Biome getBiome() { if(this.aveBiome == Biome.OBLIVION) { // build an array for counting Map<Biome, Integer> count = new HashMap<Biome, Integer>(); for(Biome b : Biome.values()) { count.put(b, 0); } for(int x = 0; x < this.width; x++) { for(int y = 0; y < this.height; y++) { Biome b = this.miniMap[x][y].getBiome(); count.put(b, count.get(b).intValue() + 1); } } int max = 0; count.forEach((k, v)->{ if(v > max) { this.aveBiome = k; } }); } return this.aveBiome; } }
mit
eXsio/congregation-assistant
src/main/java/pl/exsio/ca/model/repository/TerrainRepository.java
8938
/* * The MIT License * * Copyright 2015 exsio. * * 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 pl.exsio.ca.model.repository; import java.util.Collection; import java.util.Date; import java.util.LinkedHashSet; import org.springframework.data.jpa.repository.Query; import pl.exsio.ca.model.Event; import pl.exsio.ca.model.ServiceGroup; import pl.exsio.ca.model.Terrain; import pl.exsio.ca.model.TerrainType; import pl.exsio.ca.model.dao.TerrainDao; import pl.exsio.ca.model.entity.TerrainImpl; import pl.exsio.frameset.core.repository.GenericJpaRepository; /** * * @author exsio */ public interface TerrainRepository extends GenericJpaRepository<TerrainImpl, Long>, TerrainDao<TerrainImpl> { @Override @Query("from caTerrainImpl where type = ?1 order by type, no") LinkedHashSet<Terrain> findByType(TerrainType type); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a where a.group = ?1 and a.active = true order by t.type, t.no") LinkedHashSet<Terrain> findByGroup(ServiceGroup group); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a where a.group = ?2 and a.active = true and t.type = ?1 order by t.type, t.no") LinkedHashSet<Terrain> findByTypeAndGroup(TerrainType type, ServiceGroup group); @Override @Query("select t from caTerrainImpl t where lastNotificationDate >= ?1 order by t.type, t.no") LinkedHashSet<Terrain> findByLastNotificationDate(Date date); @Override @Query("select t from caTerrainImpl t where type=?1 and lastNotificationDate >= ?2 order by t.type, t.no") LinkedHashSet<Terrain> findByTypeAndLastNotificationDate(TerrainType type, Date date); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a where a.group = ?1 and a.active = true and t.lastNotificationDate >= ?2 order by t.type, t.no") LinkedHashSet<Terrain> findByGroupAndLastNotificationDate(ServiceGroup group, Date date); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a where a.group = ?2 and a.active = true and t.lastNotificationDate >= ?3 and t.type = ?1 order by t.type, t.no") LinkedHashSet<Terrain> findByTypeAndGroupAndLastNotificationDate(TerrainType type, ServiceGroup group, Date date); @Override @Query("select t from caTerrainImpl t order by t.type, t.no") LinkedHashSet<Terrain> findAllTerrains(); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a join a.notifications n where n.event = ?1 order by t.type, t.no") LinkedHashSet<Terrain> findByEvent(Event event); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a join a.notifications n where t.type = ?1 and n.event = ?2 order by t.type, t.no") LinkedHashSet<Terrain> findByTypeAndEvent(TerrainType type, Event event); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a join a.notifications n where a.group = ?1 and n.event = ?2 order by t.type, t.no") LinkedHashSet<Terrain> findByGroupAndEvent(ServiceGroup group, Event event); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a join a.notifications n where t.type = ?1 and a.group = ?2 and n.event = ?3 order by t.type, t.no") LinkedHashSet<Terrain> findByTypeAndGroupAndEvent(TerrainType type, ServiceGroup group, Event event); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a where a.startDate <= ?1 order by t.type, t.no") LinkedHashSet<Terrain> findByAssignmentDate(Date date); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a where a.group = ?1 and a.startDate <= ?2 and (a.endDate >= ?2 or a.endDate is null) order by t.type, t.no") LinkedHashSet<Terrain> findByGroupAndAssignmentDate(ServiceGroup group, Date date); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a where t.type=?1 and a.group = ?2 and a.startDate <= ?3 and (a.endDate >= ?3 or a.endDate is null) order by t.type, t.no") LinkedHashSet<Terrain> findByTypeAndGroupAndAssignmentDate(TerrainType type, ServiceGroup group, Date date); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a where t.type=?1 and a.startDate <= ?2 and (a.endDate >= ?2 or a.endDate is null) order by t.type, t.no") LinkedHashSet<Terrain> findByTypeAndAssignmentDate(TerrainType type, Date date); @Override @Query("select distinct t from caTerrainNotificationImpl n join n.assignment a join a.terrain t where n.date>= ?1 and n.date <= ?2 order by n.date asc") LinkedHashSet<Terrain> findByNotificationDateRange(Date start, Date end); @Override @Query("select distinct t from caTerrainNotificationImpl n join n.assignment a join a.terrain t where n.date>= ?2 and n.date <= ?3 and (a.group = ?1 or ((a.endDate is not null) and (select g2 from caTerrainAssignmentImpl a2 join a2.group g2 where a2.startDate = (select max(a3.startDate) from caTerrainAssignmentImpl a3 where a3.terrain = t and ((a3.startDate >= ?2 and a3.startDate <=?3) or (a3.endDate >= ?2 and a3.endDate <=?3) or (a3.startDate <= ?2 and a3.endDate >=?3)) ) and a2.terrain = t ) = ?1)) order by n.date asc") LinkedHashSet<Terrain> findByGroupAndNotificationDateRange(ServiceGroup group, Date start, Date end); @Override @Query("select distinct t from caTerrainNotificationImpl n join n.assignment a join a.terrain t where n.date>= ?3 and n.date <= ?4 and (a.group = ?2 or ((a.endDate is not null) and (select g2 from caTerrainAssignmentImpl a2 join a2.group g2 where a2.startDate = (select max(a3.startDate) from caTerrainAssignmentImpl a3 where a3.terrain = t and ((a3.startDate >= ?3 and a3.startDate <=?4) or (a3.endDate >= ?3 and a3.endDate <=?4) or (a3.startDate <= ?3 and a3.endDate >=?4)) ) and a2.terrain = t ) = ?2)) and t.type = ?1 order by n.date asc") LinkedHashSet<Terrain> findByTypeAndGroupAndNotificationDateRange(TerrainType type, ServiceGroup group, Date start, Date end); @Override @Query("select distinct t from caTerrainNotificationImpl n join n.assignment a join a.terrain t where n.date>= ?2 and n.date <= ?3 and t.type=?1 order by n.date asc") LinkedHashSet<Terrain> findByTypeAndNotificationDateRange(TerrainType type, Date start, Date end); @Override @Query("from caTerrainImpl where id in ?1") LinkedHashSet<Terrain> findByIds(Collection ids); @Override @Query("from caTerrainImpl where id not in ?1") LinkedHashSet<Terrain> findExcludingIds(Collection ids); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a where a.startDate <= ?1 and t.id not in ?2 order by t.type, t.no") LinkedHashSet<Terrain> findByAssignmentDateExcludingIds(Date date, Collection ids); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a where a.group = ?1 and a.startDate <= ?2 and (a.endDate >= ?2 or a.endDate is null) and t.id not in ?3 order by t.type, t.no") LinkedHashSet<Terrain> findByGroupAndAssignmentDateExcludingIds(ServiceGroup group, Date date, Collection ids); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a where t.type=?1 and a.group = ?2 and a.startDate <= ?3 and (a.endDate >= ?3 or a.endDate is null) and t.id not in ?4 order by t.type, t.no") LinkedHashSet<Terrain> findByTypeAndGroupAndAssignmentDateExcludingIds(TerrainType type, ServiceGroup group, Date date, Collection ids); @Override @Query("select distinct t from caTerrainImpl t join t.assignments a where t.type=?1 and a.startDate <= ?2 and (a.endDate >= ?2 or a.endDate is null) and t.id not in ?3 order by t.type, t.no") LinkedHashSet<Terrain> findByTypeAndAssignmentDateExcludingIds(TerrainType type, Date date, Collection ids); }
mit
thefreshduke/slogo
src/model/TurtleFactory.java
1030
package model; import java.util.ArrayList; import java.util.List; import javafx.scene.image.Image; import turtle.Position; import turtle.Turtle; /** * @author Rahul Harikrishnan, Duke Kim, $cotty $haw * */ public class TurtleFactory { private List<Turtle> myActiveTurtles = new ArrayList<Turtle>(); public void createTurtle (Image image) { Turtle turtle = new Turtle(new Position(0, 0), image); turtle.setFitWidth(60); turtle.setPreserveRatio(true); turtle.setSmooth(true); if (myActiveTurtles.size() == 0) { turtle.setID(0); } else { turtle.setID(myActiveTurtles.size() - 1); } myActiveTurtles.add(turtle); } public List<Turtle> getActiveTurtles () { return myActiveTurtles; } public Turtle findTurtle (int ID) { for (int i = 0; i < myActiveTurtles.size(); i++) { if (i == ID) { return myActiveTurtles.get(i); } } return null; } }
mit
bradyo/ark-java-smart-bridge-listener
src/main/java/io/ark/ark_client/ArkNetworkSettings.java
263
package io.ark.ark_client; import lombok.Data; import java.util.List; @Data public class ArkNetworkSettings { private String scheme; private List<ArkNetworkPeer> peers; private String netHash; private String port; private String version; }
mit
LeetcodeFun/Java-Solutions
Java/src/leetcode/186_ReverseWordsInAStringII.java
627
public class Solution { public void reverseWords(char[] s) { if (s.length == 0) return; reverse(s, 0, s.length - 1); for (int i = 0; i < s.length; i++) { if (s[i] == ' ') { continue; } else { int begin = i; while (i < s.length && s[i] != ' ') i++; reverse(s, begin, --i); } } } private void reverse(char[] s, int i, int j) { while (i <= j) { char temp = s[j]; s[j] = s[i]; s[i] = temp; i++; j--; } } }
mit
Azollas/org.azolla.p.roc
src/main/java/org/azolla/p/roc/vo/ProfessionalVo.java
2556
/* * @(#)ProfessionalVo.java Created at 15/8/15 * * Copyright (c) azolla.org All rights reserved. * Azolla PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package org.azolla.p.roc.vo; import org.springframework.stereotype.Component; import javax.persistence.*; import java.util.Date; /** * The coder is very lazy, nothing to write for this class * * @author sk@azolla.org * @since ADK1.0 */ @Table(name = "roc_t_professional") @Component public class ProfessionalVo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @OrderBy private Integer id; private Integer tagId; private Integer score; private String ip; @OrderBy private Date addDate; private Date modDate; private Date rmvDate; private Integer visible = 1; private Integer operable; private Integer deleted = 0; @Transient private TagVo tagVo; public Integer getId() { return id; } public ProfessionalVo setId(Integer id) { this.id = id; return this; } public Integer getTagId() { return tagId; } public ProfessionalVo setTagId(Integer tagId) { this.tagId = tagId; return this; } public Integer getScore() { return score; } public ProfessionalVo setScore(Integer score) { this.score = score; return this; } public String getIp() { return ip; } public ProfessionalVo setIp(String ip) { this.ip = ip; return this; } public Date getAddDate() { return addDate; } public void setAddDate(Date addDate) { this.addDate = addDate; } public Date getModDate() { return modDate; } public ProfessionalVo setModDate(Date modDate) { this.modDate = modDate; return this; } public Date getRmvDate() { return rmvDate; } public ProfessionalVo setRmvDate(Date rmvDate) { this.rmvDate = rmvDate; return this; } public Integer getVisible() { return visible; } public ProfessionalVo setVisible(Integer visible) { this.visible = visible; return this; } public Integer getOperable() { return operable; } public ProfessionalVo setOperable(Integer operable) { this.operable = operable; return this; } public Integer getDeleted() { return deleted; } public ProfessionalVo setDeleted(Integer deleted) { this.deleted = deleted; return this; } public TagVo getTagVo() { return tagVo; } public ProfessionalVo setTagVo(TagVo tagVo) { this.tagVo = tagVo; return this; } }
mit
christianewillman/shunting-calculator
src/test/java/ninja/willman/calculator/ExpressionEvaluatorTest.java
1386
package ninja.willman.calculator; import static org.junit.Assert.*; import java.util.Collection; import ninja.willman.calculator.ExpressionEvaluator; import ninja.willman.calculator.token.Token; import org.junit.Before; import org.junit.Test; public class ExpressionEvaluatorTest { private ExpressionEvaluator evaluator; @Before public void reset() { evaluator = new ExpressionEvaluator(); } private int evaluate(String expression) { Collection<Token> tokens = Token.tokenize(expression); return evaluator.evaluate(tokens); } @Test public void testAddExpression() { assertEquals(evaluate("5+5"), 10); } @Test public void testSubtractExpression() { assertEquals(evaluate("10-3"), 7); } @Test public void testMultiplyExpression() { assertEquals(evaluate("5*5"), 25); } @Test public void testDivideExpression() { assertEquals(evaluate("10/2"), 5); } @Test public void testNestedExpression() { assertEquals(evaluate("5+(5-1)"), 9); } @Test public void testNegatoryExpression() { assertEquals(evaluate("5--1"), 6); } @Test public void testComplexExpression() { assertEquals(evaluate("1+(3-2)*4"), 5); } @Test(expected = IllegalArgumentException.class) public void testUnbalancedParens() { evaluate("1+(2+3"); } @Test(expected = IllegalArgumentException.class) public void testMissingOperand() { evaluate("1+2+3-"); } }
mit
andrey-yemelyanov/competitive-programming
cp-book/ch4/dag/_10913.java
2709
import java.util.*; import static java.lang.Math.*; import java.util.stream.*; /* Problem name: 10913 Walking on a Grid Problem url: https://uva.onlinejudge.org/external/109/10913.pdf Author: Andrey Yemelyanov */ public class _10913 { public static void main(String[] args){ Scanner s = new Scanner(System.in); int caseNum = 1; while(s.hasNext()){ int N = s.nextInt(); int k = s.nextInt(); if(N == 0 && k == 0) break; int[][] grid = new int[N][N]; for(int i = 0; i < grid.length; i++){ for(int j = 0; j < grid[i].length; j++){ grid[i][j] = s.nextInt(); } } int maxSum = walk(grid, k); if(maxSum == NEG_INF) System.out.printf("Case %d: impossible\n", caseNum++); else System.out.printf("Case %d: %d\n", caseNum++, maxSum); } } static int walk(int[][] grid, int K){ memo = new int[grid.length][grid[0].length][K + 1][grid.length * grid[0].length + 1]; for(int i = 0; i < memo.length; i++){ for(int j = 0; j < memo[i].length; j++){ for(int k = 0; k < memo[i][j].length; k++){ for(int l = 0; l < memo[i][j][k].length; l++){ memo[i][j][k][l] = UNDEF; } } } } int maxSum = walk(grid, 0, 0, grid.length - 1, grid[0].length - 1, grid[0][0] < 0 ? K - 1 : K, -1, -1); if(maxSum != NEG_INF) return maxSum + grid[0][0]; return NEG_INF; } static final int NEG_INF = -1000000; static final int UNDEF = 1000000; static int[][][][] memo; static final int[] dr = new int[] {1, 0, 0}; // down, left, right static final int[] dc = new int[] {0, -1, 1}; // down, left, right static int walk(int[][] grid, int row, int col, int destRow, int destCol, int negLeft, int prevRow, int prevCol){ if(negLeft < 0) return NEG_INF; if(row == destRow && col == destCol) return 0; int prevCell = (prevRow == -1 && prevCol == -1) ? 0 : (prevRow * grid[0].length + prevCol + 1); if(memo[row][col][negLeft][prevCell] != UNDEF) return memo[row][col][negLeft][prevCell]; int maxSum = NEG_INF; for(int i = 0; i < 3; i++){ int nextRow = row + dr[i]; int nextCol = col + dc[i]; if(valid(grid, nextRow, nextCol) && !(prevRow == nextRow && prevCol == nextCol)){ int walk = walk(grid, nextRow, nextCol, destRow, destCol, grid[nextRow][nextCol] < 0 ? negLeft - 1 : negLeft, row, col); if(walk != NEG_INF){ maxSum = max(maxSum, walk + grid[nextRow][nextCol]); } } } return memo[row][col][negLeft][prevCell] = maxSum; } static boolean valid(int[][] grid, int row, int col){ return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length; } }
mit
Team-Fruit/BnnWidget
sources/universal/src/api/java/net/teamfruit/bnnwidget/var/VRange.java
1102
package net.teamfruit.bnnwidget.var; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * 範囲のある値 * * @author TeamFruit */ public class VRange implements VCommon { private @Nullable VCommon min; private @Nullable VCommon max; private @Nonnull VCommon var; /** * 範囲のある値を作成します * @param min 最小値 * @param max 最大値 * @param var 値 */ public VRange(final @Nullable VCommon min, final @Nullable VCommon max, final @Nonnull VCommon var) { this.min = min; this.max = max; this.var = var; } @Override public float get() { return this.var.get(); } @Override public float getAbsCoord(final float a, final float b) { float v = this.var.getAbsCoord(a, b); if (this.min!=null) { final float min = this.min.getAbsCoord(a, b); v = Math.max(min, v); } if (this.max!=null) { final float max = this.max.getAbsCoord(a, b); v = Math.min(max, v); } return v; } @Override public String toString() { return String.format("VRange [min=%s, max=%s, var=%s]", this.min, this.max, this.var); } }
mit
datayo/design-pattern
src/com/github/designpattern/bridge/ConcreteImplementorB.java
1381
/* * The MIT License * * Copyright (c) 2012, Lubing Zhang. * * 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 com.github.designpattern.bridge; /** * Bridge. * * @author Lubing Zhang * */ public class ConcreteImplementorB extends Implementor { @Override public void operationImpl() { System.out.println("OperationImpl B."); } }
mit
bpedman/lambdas-lnl
src/main/java/com/bpedman/lambdas/Example_02.java
1630
package com.bpedman.lambdas; import java.util.Arrays; import java.util.List; import java.util.function.IntPredicate; import java.util.stream.IntStream; /** * @author Brandon Pedersen &lt;bpedersen@getjive.com&gt; */ public class Example_02 { /** * Check if number is prime using an IntStream which removes the sequential nature and allows a * bit more readability and flexibility. * * Now we can transform the anonymous inner class predicate into a lambda to improve readability * even more. */ private static boolean isPrime(final int number) { return number > 1 && IntStream .range(2, number - 1) .noneMatch(new IntPredicate() { @Override public boolean test(final int value) { return number % value == 0; } }); } /** * Our goal...turn this set of calculations into something that is as readable as the method name * itself and more succinct than it is * * @param numbers * potentially unordered, non-unique set of numbers */ public static int findDoubleOfFirstPrimeNumberGreaterThan5(List<Integer> numbers) { int result = 0; for (final Integer number : numbers) { // first check if prime if (isPrime(number)) { if (number > 5) { result = number * 2; } } } return result; } public static void main(String[] args) { System.out.println(findDoubleOfFirstPrimeNumberGreaterThan5( Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))); } }
mit
pulse00/Symfony-2-Eclipse-Plugin
com.dubture.symfony.ui/src/com/dubture/symfony/ui/job/ConsoleJob.java
3653
package com.dubture.symfony.ui.job; import java.io.IOException; import javax.inject.Inject; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.e4.core.contexts.ContextInjectionFactory; import org.eclipse.swt.widgets.Display; import org.eclipse.php.composer.core.launch.ExecutableNotFoundException; import org.eclipse.php.composer.core.launch.ScriptLauncher; import org.eclipse.php.composer.core.launch.ScriptLauncherManager; import org.eclipse.php.composer.core.launch.ScriptNotFoundException; import org.eclipse.php.composer.core.launch.execution.ExecutionResponseAdapter; import org.eclipse.php.composer.core.ComposerPlugin; import org.eclipse.php.composer.ui.handler.ConsoleResponseHandler; import org.eclipse.php.composer.ui.job.runner.ComposerFailureMessageRunner; import org.eclipse.php.composer.ui.job.runner.MissingExecutableRunner; import com.dubture.symfony.core.launch.SymfonyEnvironmentFactory; import com.dubture.symfony.core.log.Logger; import com.dubture.symfony.ui.SymfonyUiPlugin; abstract public class ConsoleJob extends Job { @Inject public ScriptLauncherManager manager; private IProject project; private IProgressMonitor monitor; private boolean cancelling = false; private ScriptLauncher launcher; protected static final IStatus ERROR_STATUS = new Status(Status.ERROR, ComposerPlugin.ID, "Error running symfony console, see log for details"); public ConsoleJob(String name) { super(name); ContextInjectionFactory.inject(this, SymfonyUiPlugin.getDefault().getEclipseContext()); } @Override protected void canceling() { if (cancelling || launcher == null || !monitor.isCanceled()) { return; } launcher.abort(); monitor.done(); cancelling = true; } @Override protected IStatus run(final IProgressMonitor monitor) { try { this.monitor = monitor; try { launcher = manager.getLauncher(SymfonyEnvironmentFactory.FACTORY_ID, getProject()); } catch (ExecutableNotFoundException e) { // inform the user of the missing executable Display.getDefault().asyncExec(new MissingExecutableRunner()); return Status.OK_STATUS; } catch (ScriptNotFoundException e) { // run the downloader // Display.getDefault().asyncExec(new DownloadRunner()); return Status.OK_STATUS; } launcher.addResponseListener(new ConsoleResponseHandler()); launcher.addResponseListener(new ExecutionResponseAdapter() { public void executionFailed(final String response, final Exception exception) { // TODO: write a dialog for symfony console launcher Display.getDefault().asyncExec(new ComposerFailureMessageRunner(response, monitor)); } @Override public void executionMessage(String message) { if (monitor != null && message != null) { monitor.subTask(message); monitor.worked(1); } } }); monitor.beginTask(getName(), IProgressMonitor.UNKNOWN); monitor.worked(1); launch(launcher); monitor.worked(1); // refresh project if (getProject() != null) { getProject().refreshLocal(IProject.DEPTH_INFINITE, null); monitor.worked(1); } } catch (Exception e) { Logger.logException(e); return ERROR_STATUS; } finally { monitor.done(); } return Status.OK_STATUS; } abstract protected void launch(ScriptLauncher launcher) throws IOException, InterruptedException; public IProject getProject() { return project; } public void setProject(IProject project) { this.project = project; } }
mit
macc704/KBDeX
Sen1221/src/net/java/sen/Node.java
6132
package net.java.sen; /* * Node.java - Node which is representation of the morpheme. * * Copyright (C) 2001, 2002 Taku Kudoh, Takashi Okamoto Taku Kudoh * <taku-ku@is.aist-nara.ac.jp> Takashi Okamoto <tora@debian.org> * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ import java.io.IOException; import net.java.sen.util.CSVParser; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; final public class Node { private static Log log = LogFactory.getLog(Node.class); public CToken token = null; // token itself public Node prev = null; // link for previous context public Node next = null; // link for next context public Node lnext = null; public Node rnext = null; // surface, no need to be NULL terminated, use length if needed public char surface[] = null; // POS, sub-POS, cfrom ... etc, must be NULL terminated public String termInfo = null; private String[] termInfoStringArray = null; // Additional Information public String addInfo = null; public int begin = 0; // begining of position public int length = 0; // length of surface public int end = 0; // next seek position // (causion: 'end' doesn't work correctly) public int cost = 0; // cost of best path public int id = 0; // unique id of this node /** * get start index of this node. */ public int start() { return begin; } /** * get end index of this node. */ public int end() { return begin + length; } /** * get length of this node. */ public int length() { return length; } /** * get part of speech as chasen format. * * @return part of speach. */ public String getPos() { int cnt = 0; if (termInfo == null) return null; // to avoid bug. if (termInfo.length() == 0) { log.error("feature information is null at '" + toString() + "'."); log.error("token id = " + this.token.posID); log.error("token rcAttr2 = " + this.token.rcAttr2); log.error("token rcAttr1 = " + this.token.rcAttr1); log.error("token lcAttr = " + this.token.lcAttr); log.error("token length = " + this.token.length); log.error("token cost = " + this.token.cost); return null; } while (termInfo.charAt(cnt++) != ',') ; if (termInfo.charAt(cnt) != '*') { while (termInfo.charAt(cnt++) != ',') ; if (termInfo.charAt(cnt) != '*') { while (termInfo.charAt(cnt++) != ',') ; if (termInfo.charAt(cnt) != '*') { while (termInfo.charAt(cnt++) != ',') ; } } } // convert to chasen format return termInfo.substring(0, cnt - 1).replace(',', '-'); } /** * get un-conjugate string. * * @return un-conjugate representation for morpheme. */ public String getBasicString() { int cnt = 0, begin; if (termInfo == null) return toString(); // to avoid bug. if (termInfo.length() == 0) { log.error("feature information is null at '" + toString() + "'."); log.error("token id = " + this.token.posID); log.error("token rcAttr2 = " + this.token.rcAttr2); log.error("token rcAttr1 = " + this.token.rcAttr1); log.error("token lcAttr = " + this.token.lcAttr); log.error("token length = " + this.token.length); log.error("token cost = " + this.token.cost); return null; } log.debug("posInfo=" + termInfo); return getField(6); } /** * clear node. */ protected void clear() { token = null; prev = null; next = null; lnext = null; rnext = null; surface = null; termInfo = null; addInfo = null; begin = 0; length = 0; end = 0; cost = 0; id = 0; } /** * copy node. */ protected void copy(Node org) { token = org.token; prev = org.prev; next = org.next; lnext = org.lnext; rnext = org.rnext; surface = org.surface; termInfo = org.termInfo; addInfo = org.addInfo; begin = org.begin; length = org.length; end = org.end; cost = org.cost; id = org.id; } /** * convert to string. */ public String toString() { if (surface != null) { return new String(surface, begin, length); } else { return null; } } /** * get conjugational form. * * @return conjugational form */ public String getCform() { if (termInfo == null || termInfo.length() == 0) return null; return getField(5); } /** * get reading. * * @return reading */ public String getReading() { if (termInfo == null || termInfo.length() == 0) return null; return getField(7); } /** * get pronunciation. * * @return pronunciation */ public String getPronunciation() { if (termInfo == null || termInfo.length() == 0) return null; return getField(8); } /** * get additional information. * * @return additional information */ public String getAddInfo() { if (addInfo == null) { return ""; } return addInfo; } /** * get cost * * @return cost of this morpheme. */ public int getCost() { return cost; } private String getField(int index) { if (termInfoStringArray == null) { try { CSVParser parser = new CSVParser(termInfo); termInfoStringArray = parser.nextTokens(); } catch (IOException e) { log.error(e); return null; } } return termInfoStringArray[index]; } }
mit
ralfstuckert/vertical-ui
catalog-service/src/main/java/rst/vertical/service/catalog/service/CatalogInitializer.java
1147
package rst.vertical.service.catalog.service; import java.util.List; import rst.vertical.service.catalog.model.CatalogItem; import com.google.common.collect.Lists; public class CatalogInitializer { public static List<CatalogItem> createCatalog() { List<CatalogItem> catalog = Lists.newArrayList(); int articleNumber = 479239;//new Random().nextInt(100000); catalog.add(new CatalogItem(Integer.toString(articleNumber++), "Nnnnuts", "The chunkiest peanut butter ever, made of non-gound nuts", 2.68)); catalog.add(new CatalogItem(Integer.toString(articleNumber++), "ChoCoCo", "Devine chocolate with whole coconuts", 1.67)); catalog.add(new CatalogItem(Integer.toString(articleNumber++), "Glowing Cow", "The number one illuminating milkshake. Available in various flavors", .88)); catalog.add(new CatalogItem(Integer.toString(articleNumber++), "Hazel Brazil", "Hazelnut flavored brazil nuts. You gotta try this", 3.45)); catalog.add(new CatalogItem(Integer.toString(articleNumber++), "Krem'o'rama", "This chocolate creme is without any natural ingrediants, quite perfect for allergic subjects", 4.54)); return catalog; } }
mit
OblivionNW/Nucleus
src/main/java/io/github/nucleuspowered/nucleus/modules/warn/config/WarnConfig.java
1875
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.modules.warn.config; import ninja.leaping.configurate.objectmapping.Setting; import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; @ConfigSerializable public class WarnConfig { @Setting(value = "show-login", comment = "config.warn.showonlogin") private boolean showOnLogin = true; @Setting(value = "expire-warnings", comment = "config.warn.expire") private boolean expireWarnings = true; @Setting(value = "minimum-warn-length", comment = "config.warn.minwarnlength") private long minWarnLength = -1; @Setting(value = "maximum-warn-length", comment = "config.warn.maxwarnlength") private long maxWarnLength = -1; @Setting(value = "default-length", comment = "config.warn.defaultlength") private long defaultLength = -1; @Setting(value = "warnings-before-action", comment = "config.warn.warningsbeforeaction") private int warningsBeforeAction = -1; @Setting(value = "action-command", comment = "config.warn.actioncommand") private String actionCommand = "tempban {{name}} 1d Exceeding the active warning threshold"; public boolean isShowOnLogin() { return this.showOnLogin; } public boolean isExpireWarnings() { return this.expireWarnings; } public long getMinimumWarnLength() { return this.minWarnLength; } public long getMaximumWarnLength() { return this.maxWarnLength; } public long getDefaultLength() { return this.defaultLength; } public int getWarningsBeforeAction() { return this.warningsBeforeAction; } public String getActionCommand() { return this.actionCommand; } }
mit
ISKU/Algorithm
BOJ/10718/Main.java
314
/* * Author: Kim Min-Ho (ISKU) * Date: 2016.08.02 * email: minho1a@hanmail.net * * https://github.com/ISKU/Algorithm * https://www.acmicpc.net/problem/10718 */ public class Main { public static void main(String args[]) { System.out.printf("강한친구 대한육군\n강한친구 대한육군"); } }
mit
NucleusPowered/Nucleus
nucleus-core/src/main/java/io/github/nucleuspowered/nucleus/core/core/teleport/filters/NoCheckFilter.java
1040
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.core.core.teleport.filters; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.util.Tristate; import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.api.world.teleport.TeleportHelperFilter; import org.spongepowered.math.vector.Vector3i; public final class NoCheckFilter implements TeleportHelperFilter { public static final ResourceKey KEY = ResourceKey.resolve("nucleus:no_check"); @Override public Tristate isValidLocation(final ServerWorld world, final Vector3i position) { return Tristate.TRUE; } @Override public boolean isSafeFloorMaterial(final BlockState blockState) { return true; } @Override public boolean isSafeBodyMaterial(final BlockState blockState) { return true; } }
mit
trolund/11_CDIO_FINAL
11_CDIO_FINAL/src/final_cdio_11/java/data/dao/view/IVOperatorRBDAO.java
342
package final_cdio_11.java.data.dao.view; import java.util.List; import final_cdio_11.java.data.DALException; import final_cdio_11.java.data.dto.view.VOperatorRBDTO; public interface IVOperatorRBDAO { List<VOperatorRBDTO> getVOperatorRB(int raavareId) throws DALException; List<VOperatorRBDTO> getVOperatorRBList() throws DALException; }
mit
sti-uff/dam
collect_syslog/src/main/java/model/Event.java
4936
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package model; import java.util.Date; /** * * @author victor */ public class Event { private Date timestamp; private Date query_timestamp ; private String client_addr; private String server_addr; private long tcp_seq_number; //private String columns; private Date connection_start_timestamp; //private long connection_web_id; private double db_id; private String db_user_name; //private Date end_limit_timestamp; //private String event_type ; private String query_text; private int query_type ; private String tables ; public Event() { this.timestamp = new Date(); this.query_timestamp = new Date(); this.client_addr = ""; this.server_addr = ""; this.tcp_seq_number = new Date().getTime(); //this.columns = ""; this.connection_start_timestamp = new Date(); //this.connection_web_id = new Date().getTime(); this.db_id = 0; this.db_user_name = ""; //this.end_limit_timestamp = new Date(); //this.event_type = ""; this.query_text = ""; this.query_type = 0; this.tables = ""; } public Event(Date timestamp, Date query_timestamp, String client_addr, String server_addr, long tcp_seq_number, String columns, Date connection_start_timestamp, long connection_web_id, double db_id, String db_user_name, Date end_limit_timestamp, String event_type, String query_text, int query_type, String tables) { this.timestamp = timestamp; this.query_timestamp = query_timestamp; this.client_addr = client_addr; this.server_addr = server_addr; this.tcp_seq_number = tcp_seq_number; //this.columns = columns; this.connection_start_timestamp = connection_start_timestamp; //this.connection_web_id = connection_web_id; this.db_id = db_id; this.db_user_name = db_user_name; //this.end_limit_timestamp = end_limit_timestamp; //this.event_type = event_type; this.query_text = query_text; this.query_type = query_type; this.tables = tables; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public Date getQuery_timestamp() { return query_timestamp; } public void setQuery_timestamp(Date query_timestamp) { this.query_timestamp = query_timestamp; } public String getClient_addr() { return client_addr; } public void setClient_addr(String client_addr) { this.client_addr = client_addr; } public String getServer_addr() { return server_addr; } public void setServer_addr(String server_addr) { this.server_addr = server_addr; } public long getTcp_seq_number() { return tcp_seq_number; } public void setTcp_seq_number(long tcp_seq_number) { this.tcp_seq_number = tcp_seq_number; } // public String getColumns() { // return columns; // } // // public void setColumns(String columns) { // this.columns = columns; // } public Date getConnection_start_timestamp() { return connection_start_timestamp; } public void setConnection_start_timestamp(Date connection_start_timestamp) { this.connection_start_timestamp = connection_start_timestamp; } // public long getConnection_web_id() { // return connection_web_id; // } // // public void setConnection_web_id(long connection_web_id) { // this.connection_web_id = connection_web_id; // } public double getDb_id() { return db_id; } public void setDb_id(double db_id) { this.db_id = db_id; } public String getDb_user_name() { return db_user_name; } public void setDb_user_name(String db_user_name) { this.db_user_name = db_user_name; } // public Date getEnd_limit_timestamp() { // return end_limit_timestamp; // } // // public void setEnd_limit_timestamp(Date end_limit_timestamp) { // this.end_limit_timestamp = end_limit_timestamp; // } // public String getEvent_type() { // return event_type; // } // // public void setEvent_type(String event_type) { // this.event_type = event_type; // } public String getQuery_text() { return query_text; } public void setQuery_text(String query_text) { this.query_text = query_text; } public int getQuery_type() { return query_type; } public void setQuery_type(int query_type) { this.query_type = query_type; } public String getTables() { return tables; } public void setTables(String tables) { this.tables = tables; } }
mit
lmarinov/Exercise-repo
Java_OOP_2021/src/Encapsulation/Lab/ValidationData/Person.java
2068
package Encapsulation.Lab.ValidationData; public class Person { private String firstName; private String lastName; private int age; private double salary; public Person(String firstName, String lastName, int age, double salary){ this.setFirstName(firstName); this.setLastName(lastName); this.setAge(age); this.setSalary(salary); } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } public double getSalary() { return salary; } public void setFirstName(String firstName) { if (firstName == null || firstName.trim().length() < 3){ throw new IllegalArgumentException("First name cannot be less than 3 symbols"); } this.firstName = firstName; } public void setLastName(String lastName) { if (lastName == null || lastName.trim().length() < 3){ throw new IllegalArgumentException("Last name cannot be less than 3 symbols"); } this.lastName = lastName; } public void setAge(int age) { if (age <= 0){ throw new IllegalArgumentException("Age cannot be zero or negative integer"); } this.age = age; } public void increaseSalary(double percentage) { if (this.getAge() < 30){ this.salary = this.getSalary() + this.getSalary() / 2 * (percentage / 100); }else{ this.salary = this.getSalary() * (1 + percentage / 100); } } private void setSalary(double salary) { if (salary < 460.0){ throw new IllegalArgumentException("Salary cannot be less than 460 leva"); } this.salary = salary; } @Override public String toString() { return String.format("%s %s gets %.1f leva", this.getFirstName(), this.getLastName(), this.getSalary()); } }
mit
sabarjp/VictusLudus
victusludus/src/com/teamderpy/victusludus/math/heightmap/MidpointGenerator.java
11348
package com.teamderpy.victusludus.math.heightmap; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.badlogic.gdx.math.MathUtils; import com.teamderpy.victusludus.math.MatrixMath; /** * Uses midpoint displacement to calculate random noise. Would most likely be MUCH faster using GPU compute or multiple threads. */ public class MidpointGenerator implements INoiseGenerator { /** The seed. */ private long seed; /** The rand. */ private Random rand; /** The persistence. */ private float persistence; /** multithreading worker pool for matrix math */ private ExecutorService workerPool = Executors.newFixedThreadPool(8, Executors.defaultThreadFactory()); private ArrayList<Callable<Boolean>> workers = new ArrayList<Callable<Boolean>>(); /** Instantiates a new MidpointGenerator generator. */ public MidpointGenerator () { this.persistence = 0.25F; this.rand = new Random(); this.seed(); } /** Instantiates a new MidpointGenerator generator. */ public MidpointGenerator (final float persistence) { this.persistence = persistence; this.rand = new Random(); this.seed(); } /** Instantiates a new MidpointGenerator generator. */ public MidpointGenerator (final float persistence, final long seed) { this.persistence = persistence; this.rand = new Random(); this.seed = seed; } /** Seeds the generator with a new random seed */ public void seed () { // this instance will have a new random seed this.seed = this.rand.nextLong(); } /** Seeds the generator with a specified seed */ public void seed (final long seed) { this.seed = seed; } /** * Smooth noise using simple gaussian blur function. * * @param x the x coord * @param y the y coord * @return the float */ private float simpleGaussianNoise (final int x, final int y) { float corners = this.randomNoise(x - 1, y - 1) + this.randomNoise(x - 1, y + 1) + this.randomNoise(x + 1, y - 1) + this.randomNoise(x + 1, y + 1); float sides = this.randomNoise(x, y - 1) + this.randomNoise(x, y + 1) + this.randomNoise(x + 1, y) + this.randomNoise(x - 1, y); float center = this.randomNoise(x, y); return 0.09470416F * corners + 0.118318F * sides + 0.147761F * center; } /** * Random noise. * * @param x the x coord * @param y the y coord * @return the float */ private float randomNoise (final int x, final int y) { int h = x * 29 + y * 113; h += this.seed; h = h << 13 ^ h; return 1.0F - (h * (h * h * 15731 + 789221) + 1376312589 & 0x7fffffff) / 1073741824.0F; } @Override public int[][] generateInt (final int width, final int height, final boolean normalize) { int[][] array; int actualSize; // array must be a multiple of 2^x + 1 int maxSide = Math.max(width, height); if (MathUtils.isPowerOfTwo(maxSide)) { array = new int[maxSide + 1][maxSide + 1]; actualSize = maxSide; } else { int num = MathUtils.nextPowerOfTwo(Math.max(width, height)); array = new int[num + 1][num + 1]; actualSize = num; } int highestPoint = 0; int lowestPoint = 9999; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { array[i][j] = 1; } } // seed corners array[0][0] = (int)(5 * this.randomNoise(0, 0)); array[actualSize][0] = (int)(5 * this.randomNoise(actualSize, 0)); array[0][actualSize] = (int)(5 * this.randomNoise(0, actualSize)); array[actualSize][actualSize] = (int)(5 * this.randomNoise(actualSize, actualSize)); // find midpoints int squareSize = actualSize; int iteration = 1; while (squareSize > 1) { for (int x = 0; x < actualSize; x += squareSize) { for (int y = 0; y < actualSize; y += squareSize) { // create middle point int midX = x + squareSize / 2; int midY = y + squareSize / 2; int cornerNWValue = array[x][y]; int cornerNEValue = array[x + squareSize][y]; int cornerSEValue = array[x + squareSize][y + squareSize]; int cornerSWValue = array[x][y + squareSize]; int averageCenter = (int)((cornerNWValue + cornerNEValue + cornerSEValue + cornerSWValue) / 4.0F); int averageNorth = (int)((cornerNWValue + cornerNEValue) / 2.0F); int averageEast = (int)((cornerNEValue + cornerSEValue) / 2.0F); int averageSouth = (int)((cornerSEValue + cornerSWValue) / 2.0F); int averageWest = (int)((cornerNWValue + cornerSWValue) / 2.0F); array[midX][midY] = (int)(averageCenter + 5 * Math.pow(this.persistence, iteration) * this.randomNoise(midX, midY)); array[midX][y] = (int)(averageNorth + 5 * Math.pow(this.persistence, iteration) * this.randomNoise(midX, midY)); array[midX][y + squareSize] = (int)(averageSouth + 5 * Math.pow(this.persistence, iteration) * this.randomNoise(midX, y + squareSize)); array[x][midY] = (int)(averageWest + 5 * Math.pow(this.persistence, iteration) * this.randomNoise(x, midY)); array[x + squareSize][midY] = (int)(averageEast + 5 * Math.pow(this.persistence, iteration) * this.randomNoise(x + squareSize, midY)); } } // downsize square squareSize /= 2; iteration++; } // high and low points for (int[] element : array) { for (int element2 : element) { if (element2 > highestPoint) { highestPoint = element2; } if (element2 < lowestPoint) { lowestPoint = element2; } } } // normalize terrain if (normalize) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { array[i][j] -= lowestPoint - 15; } } } // resize int[][] returnArray = new int[width][height]; for (int i = 0; i < returnArray.length; i++) { for (int j = 0; j < returnArray[i].length; j++) { returnArray[i][j] = array[i][j]; } } return returnArray; } @Override public float[][] generateFloat (final int width, final int height, final float minValue, final float maxValue, final boolean blur) { float[][] array; int actualSize; // array must be a multiple of 2^x + 1 int maxSide = Math.max(width, height); if (MathUtils.isPowerOfTwo(maxSide)) { array = new float[maxSide + 1][maxSide + 1]; actualSize = maxSide; } else { int num = MathUtils.nextPowerOfTwo(Math.max(width, height)); array = new float[num + 1][num + 1]; actualSize = num; } // System.err.println("requested area " + width + "x" + height + " and created " + actualSize + "x" + actualSize); for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { array[i][j] = 0; } } // seed corners if (blur) { array[0][0] = this.simpleGaussianNoise(0, 0); array[actualSize][0] = this.simpleGaussianNoise(actualSize, 0); array[0][actualSize] = this.simpleGaussianNoise(0, actualSize); array[actualSize][actualSize] = this.simpleGaussianNoise(actualSize, actualSize); } else { array[0][0] = this.randomNoise(0, 0); array[actualSize][0] = this.randomNoise(actualSize, 0); array[0][actualSize] = this.randomNoise(0, actualSize); array[actualSize][actualSize] = this.randomNoise(actualSize, actualSize); } // find midpoints int squareSize = actualSize; int iteration = 1; this.workers.clear(); while (squareSize > 1) { for (int x = 0; x < actualSize; x += squareSize) { for (int y = 0; y < actualSize; y += squareSize) { this.workers.add(new MidpointThread(array, x, y, squareSize, blur, iteration)); } } try { this.workerPool.invokeAll(this.workers); } catch (InterruptedException e) { e.printStackTrace(); } // downsize square squareSize /= 2; iteration++; this.workers.clear(); } MatrixMath.normalize(array, minValue, maxValue); // resize float[][] returnArray = new float[width][height]; for (int i = 0; i < returnArray.length; i++) { for (int j = 0; j < returnArray[i].length; j++) { returnArray[i][j] = array[i][j]; } } // System.err.println("returning size of " + width + "x" + height); return returnArray; } /** * Gets the persistence. * * @return the persistence */ public float getPersistence () { return this.persistence; } /** * Sets the persistence. * * @param persistence the new persistence */ public void setPersistence (final float persistence) { this.persistence = persistence; } private class MidpointThread implements Callable<Boolean> { private float[][] array; private int x; private int y; private int squareSize; private boolean blur; private int iteration; public MidpointThread (final float[][] array, final int x, final int y, final int squareSize, final boolean blur, final int iteration) { this.array = array; this.x = x; this.y = y; this.squareSize = squareSize; this.blur = blur; this.iteration = iteration; } @Override public Boolean call () throws Exception { // create middle point int midX = this.x + this.squareSize / 2; int midY = this.y + this.squareSize / 2; float cornerNWValue = this.array[this.x][this.y]; float cornerNEValue = this.array[this.x + this.squareSize][this.y]; float cornerSEValue = this.array[this.x + this.squareSize][this.y + this.squareSize]; float cornerSWValue = this.array[this.x][this.y + this.squareSize]; float averageCenter = (cornerNWValue + cornerNEValue + cornerSEValue + cornerSWValue) / 4.0F; float averageNorth = (cornerNWValue + cornerNEValue) / 2.0F; float averageEast = (cornerNEValue + cornerSEValue) / 2.0F; float averageSouth = (cornerSEValue + cornerSWValue) / 2.0F; float averageWest = (cornerNWValue + cornerSWValue) / 2.0F; float finalCenter, finalNorth, finalEast, finalSouth, finalWest; if (this.blur) { finalCenter = MidpointGenerator.this.simpleGaussianNoise(midX, midY); finalNorth = MidpointGenerator.this.simpleGaussianNoise(midX, midY); finalEast = MidpointGenerator.this.simpleGaussianNoise(this.x + this.squareSize, midY); finalSouth = MidpointGenerator.this.simpleGaussianNoise(midX, this.y + this.squareSize); finalWest = MidpointGenerator.this.simpleGaussianNoise(this.x, midY); } else { finalCenter = MidpointGenerator.this.randomNoise(midX, midY); finalNorth = MidpointGenerator.this.randomNoise(midX, midY); finalEast = MidpointGenerator.this.randomNoise(this.x + this.squareSize, midY); finalSouth = MidpointGenerator.this.randomNoise(midX, this.y + this.squareSize); finalWest = MidpointGenerator.this.randomNoise(this.x, midY); } // calculate the side points this.array[midX][midY] = (float)(averageCenter + Math.pow(MidpointGenerator.this.persistence, this.iteration) * finalCenter); this.array[midX][this.y] = (float)(averageNorth + Math.pow(MidpointGenerator.this.persistence, this.iteration) * finalNorth); this.array[midX][this.y + this.squareSize] = (float)(averageSouth + Math.pow(MidpointGenerator.this.persistence, this.iteration) * finalSouth); this.array[this.x][midY] = (float)(averageWest + Math.pow(MidpointGenerator.this.persistence, this.iteration) * finalWest); this.array[this.x + this.squareSize][midY] = (float)(averageEast + Math.pow(MidpointGenerator.this.persistence, this.iteration) * finalEast); return true; } } }
mit
akiress/compilers
prog4/Temp/TempList.java
330
package Temp; public class TempList { public Temp head; public TempList tail; public TempList(Temp h, TempList t) {head=h; tail=t;} public TempList(TempList a, TempList b) { if (a.tail == null) { head = a.head; tail = b; } else { head = a.head; tail = new TempList(a.tail, b); } } }
mit
appliedtech/web-app-bootstrap
ru.appliedtech.application/src/ru/appliedtech/application/registry/IPredicate.java
1381
/* * Copyright (c) 2013 Applied Technologies, Ltd. * * 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 ru.appliedtech.application.registry; /** * Predicate interface for higher-order functions. * @param <T> The type of the operand. * @author Igor Pavlenko */ public interface IPredicate<T> { boolean truly(T object); }
mit
junjieit/pos
src/com/impl/Test.java
2429
package com.impl; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.directjngine.QnAction; import com.empty.Image; import com.google.gson.Gson; import com.qiniu.util.Auth; import com.qiniu.util.StringMap; import com.qiniu.util.UrlSafeBase64; public class Test { public static void main(String[] args) throws Exception { //设置好账号的ACCESS_KEY和SECRET_KEY String ACCESS_KEY = "0Q6swVvzFTBC5av8u7YTaesTjPqHp51_EOZddbbX"; String SECRET_KEY = "j6ym83kG9BCeQuRBBBRZQC-s9BNLkfPFeRDTF_hy"; //要上传的空间 String bucketname = "pos-qnw"; //密钥配置 Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY); System.out.println(auth.uploadToken(bucketname,null,3600,new StringMap() .put("callbackUrl","http://o7ntu9jmt.bkt.clouddn.com/callback") .put("callbackBody", "filename=$(fname)&filesize=$(fsize)"))); //上传到七牛后保存的文件名 //String key = "shuijiao.jpg"; //上传文件的路�? //String FilePath = "F:/fzh/images/shuijiao.jpg"; // String ACCESS_KEY = "0Q6swVvzFTBC5av8u7YTaesTjPqHp51_EOZddbbX"; // String uptoken="{\"scope\":\"pos-qnw\",\"deadline\":1501311011}"; // String encodedPutPolicy = UrlSafeBase64.encodeToString(uptoken.getBytes());//Base64.encode(uptoken.getBytes()); // byte[] data=encodedPutPolicy.getBytes("UTF-8"); // //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称 // SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1"); // //生成一个指定 Mac 算法 的 Mac 对象 // Mac mac = Mac.getInstance("HmacSHA1"); // //用给定密钥初始化 Mac 对象 // mac.init(secretKey); // // byte[] sign = encodedPutPolicy.getBytes("UTF-8"); // //完成 Mac 操作 // String encodedSign=UrlSafeBase64.encodeToString(mac.doFinal(sign)); // String rUptoken="{\"rUptoken\":\""+ACCESS_KEY + ':' + encodedSign + ':' + encodedPutPolicy+"\"}"; // System.out.println(rUptoken); //{"id":2,"url":"test"} } }
mit
akochurov/mxcache
mxcache-runtime/src/main/java/com/maxifier/mxcache/impl/caches/def/BooleanInlineDependencyCache.java
2722
/* * Copyright (c) 2008-2014 Maxifier Ltd. All Rights Reserved. */ package com.maxifier.mxcache.impl.caches.def; import com.maxifier.mxcache.caches.*; import com.maxifier.mxcache.impl.MutableStatistics; import com.maxifier.mxcache.impl.resource.DependencyNode; import com.maxifier.mxcache.util.HashWeakReference; import gnu.trove.set.hash.THashSet; import javax.annotation.Nonnull; import java.lang.ref.Reference; import java.util.Iterator; import java.util.Set; /** * Inline dependency caches are special ones that implement both Cache and DependencyNode. * It is used to reduce memory consumption of memory cache for the simplest types of caches. * * THIS IS GENERATED CLASS! DON'T EDIT IT MANUALLY! * * GENERATED FROM PInlineDependencyCache.template * * @author Andrey Yakoushin (andrey.yakoushin@maxifier.com) * @author Alexander Kochurov (alexander.kochurov@maxifier.com) */ public class BooleanInlineDependencyCache extends BooleanInlineCacheImpl implements DependencyNode { /** * Set of dependent nodes. It may be null cause there is no need to allocate whole set for each node. */ private Set<Reference<DependencyNode>> dependentNodes; private Reference<DependencyNode> selfReference; public BooleanInlineDependencyCache(Object owner, BooleanCalculatable calculable, MutableStatistics statistics) { super(owner, calculable, statistics); setDependencyNode(this); } @Override public synchronized void visitDependantNodes(Visitor visitor) { if (dependentNodes != null) { for (Iterator<Reference<DependencyNode>> it = dependentNodes.iterator(); it.hasNext();) { Reference<DependencyNode> ref = it.next(); DependencyNode instance = ref.get(); if (instance != null) { visitor.visit(instance); } else { it.remove(); } } } } @Override public synchronized Reference<DependencyNode> getSelfReference() { if (selfReference == null) { selfReference = new HashWeakReference<DependencyNode>(this); } return selfReference; } @Override public synchronized void trackDependency(DependencyNode node) { if (dependentNodes == null) { dependentNodes = new THashSet<Reference<DependencyNode>>(); } dependentNodes.add(node.getSelfReference()); } @Override public void addNode(@Nonnull CleaningNode cache) { throw new UnsupportedOperationException("Inline dependency node should has only one cache"); } }
mit
AkikoZ/SecureChat
client/SecureChat/app/src/main/java/com/akikoz/securechat/adapter/MsgAdapter.java
2636
package com.akikoz.securechat.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.akikoz.securechat.R; import com.akikoz.securechat.model.Msg; import com.akikoz.securechat.model.MsgType; import java.util.List; public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder> { private List<Msg> mMsgList; static class ViewHolder extends RecyclerView.ViewHolder { LinearLayout leftLayout; LinearLayout rightLayout; TextView leftMsg; TextView rightMsg; ImageView leftFileIndicator; ImageView rightFileIndicator; ViewHolder(View view) { super(view); leftLayout = (LinearLayout) view.findViewById(R.id.left_layout); rightLayout = (LinearLayout) view.findViewById(R.id.right_layout); leftMsg = (TextView) view.findViewById(R.id.left_msg); rightMsg = (TextView) view.findViewById(R.id.right_msg); leftFileIndicator = (ImageView) view.findViewById(R.id.left_file_indicator); rightFileIndicator = (ImageView) view.findViewById(R.id.right_file_indicator); } } public MsgAdapter(List<Msg> msgList) { mMsgList = msgList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { Msg msg = mMsgList.get(position); MsgType type = msg.getType(); if (type == MsgType.TEXT_RECEIVED || type == MsgType.FILE_RECEIVED) { holder.leftLayout.setVisibility(View.VISIBLE); holder.rightLayout.setVisibility(View.GONE); holder.leftMsg.setText(msg.getContent()); holder.leftFileIndicator.setVisibility(type == MsgType.TEXT_RECEIVED ? View.GONE : View.VISIBLE); } else if (type == MsgType.TEXT_SENT || type == MsgType.FILE_SENT) { holder.leftLayout.setVisibility(View.GONE); holder.rightLayout.setVisibility(View.VISIBLE); holder.rightMsg.setText(msg.getContent()); holder.rightFileIndicator.setVisibility(type == MsgType.TEXT_SENT ? View.GONE : View.VISIBLE); } } @Override public int getItemCount() { return mMsgList.size(); } }
mit
sodash/open-code
winterwell.web/src/com/winterwell/web/fields/AField.java
16229
package com.winterwell.web.fields; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URI; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import com.winterwell.utils.Environment; import com.winterwell.utils.IBuildStrings; import com.winterwell.utils.IProperties; import com.winterwell.utils.Key; import com.winterwell.utils.Printer; import com.winterwell.utils.ReflectionUtils; import com.winterwell.utils.StrUtils; import com.winterwell.utils.Utils; import com.winterwell.utils.containers.ArrayMap; import com.winterwell.utils.io.ISerialize; import com.winterwell.utils.log.Log; import com.winterwell.utils.web.WebUtils; import com.winterwell.utils.web.WebUtils2; import com.winterwell.web.IWidget; import com.winterwell.web.WebInputException; /** * Describes a form field. toString() returns the field's name. * <p> * If for some reason you wish to give a negative output, then "false" is the * preferred coding for false/null/off. * * @author daniel */ public class AField<X> extends Key<X> implements Serializable, IWidget, ISerialize<X> { private static final Key<IProperties> HTTP_REQUEST_PROPERTIES = new Key<IProperties>( "AField.Props"); /** * */ private static final long serialVersionUID = 1L; public static IProperties getRequestProperties() { return Environment.get().get(HTTP_REQUEST_PROPERTIES); } /** * Set this request as the thread-local request object. It is used to supply * default values for {@link #getValue()}, thus preserving use input between * calls. */ public static IProperties setRequest(HttpServletRequest req) { RequestProps props = new RequestProps(req); return setRequest(props); } /** * Set this request as the thread-local request object. It is used to supply * default values for {@link #getValue()}, thus preserving use input between * calls. */ public static IProperties setRequest(IProperties props) { Environment.get().put(HTTP_REQUEST_PROPERTIES, props); return props; } @Deprecated public String cssClass = ""; @Deprecated public final String getCssClass() { return cssClass; } /** * null by default */ protected String id; @Deprecated protected String onChange; protected boolean required; @Deprecated private int size; @Deprecated protected String tooltip; /** * @deprecated * * This is the type attribute for the input tag - it is *not* the type of * the field! */ private String type; private Boolean lenient; /** * If true, this will try to interpret badly formatted urls. * And bad inputs will return null rather than throw an error. * @return false by default */ public boolean isLenient() { return lenient!=null && lenient; } /** * If true, this will try to interpret badly formatted urls. * And bad inputs will return null rather than throw an error. * @param lenient * @return */ public AField<X> setLenient(boolean lenient) { this.lenient = lenient; return this; } /** * Convenience for making a simple text field from a Key * @param key */ public AField(Key key) { this(key.getName(), "text"); } public AField(String name) { this(name, "text"); } public AField(String name, String type) { this(name, type, false); } public AField(String name, String type, boolean required) { super(name); this.type = type; this.required = required; } /** * Add all the just-this-once attributes (tabindex, etc) to the opening * input tag. Call from within appendHtmlTo. * * @param page * @param attributes * should not be null. */ protected void addAttributes(StringBuilder page, Object... attributes) { ArrayMap<String, Object> attrs = new ArrayMap(attributes); for (String k : attrs.keySet()) { Object v = attrs.get(k); // allow Strings, ints, boolean String vs = v.toString(); page.append(k + "='" + WebUtils.attributeEncode(vs) + "' "); } } /** * Convenience wrapper for * {@link WebUtils2#addQueryParameter(String, String, Object)}. * * @param url * If this is a StringBuilder it will be modified directly! * Otherwise a new StringBuilder will be created * @param value * can be null in which case nothing is added * @return url with value encoded as a GET parameter */ public final StringBuilder addQueryParameter(CharSequence url, X value) { if (value == null) return StrUtils.sb(url); StringBuilder sb = url instanceof StringBuilder ? (StringBuilder) url : new StringBuilder(url); WebUtils2.addQueryParameter(sb, this.getName(), toString(value)); return sb; } @Override public final void appendHtmlTo(IBuildStrings page) { appendHtmlTo(page.sb()); } public final void appendHtmlTo(IBuildStrings page, X value, Object... attributes) { appendHtmlTo(page.sb(), value, attributes); } /** * Wrapper for {@link #appendHtmlTo(StringBuilder, Object)} which fetches a * value from the request. * * @param page */ @Override public final void appendHtmlTo(StringBuilder page) { appendHtmlTo(page, getValue()); } /** * @param cssClass e.g. form-control * @return this */ public <F extends AField> F setCssClass(String cssClass) { this.cssClass = cssClass; return (F) this; } /** * Append the html for this field to a page. A potentially slightly more * efficient base for {@link #getHtml(Object)}. * * @param page * @param value * The current value. can be null * @param attributes * any once-only HTML options that should be set. */ public void appendHtmlTo(StringBuilder page, X value, Object... attributes) { String v = value == null ? "" : toString(value); // Escape quotes v = WebUtils.attributeEncode(v); // size (irrelevant for many fields) String sizeAttr = ""; if ("text".equals(type) || size > 0) { int len = Math.min(Math.max(v.length(), 20), 60); sizeAttr = " size='" + (size > 0 ? size : len) + "'"; } // Use " to enclose the value since ' does not get escaped, so 's in v // can cause problems page.append("<input type='" + type + "' name='" + WebUtils.attributeEncode(getName()) + "' value=\"" + v + '"' + sizeAttr + " class='" + cssClass + "' "); if (id != null) { page.append("id='" + id + "' "); } if (onChange != null) { page.append("onChange='" + WebUtils.attributeEncode(onChange) + "' "); } if (tooltip != null) { page.append("title='" + WebUtils.attributeEncode(tooltip) + "' "); } if (required) { page.append("required "); // only works for html5 browser, but // harmless elsewhere } addAttributes(page, attributes); // XHTML ending page.append("/>\n"); } /** * Uses {@link #getValueClass()}, and claims to convert any subclass. */ @Override public boolean canConvert(Class klass) { return ReflectionUtils.isa(klass, getValueClass()); } /** * Subclasses should override and convert from String to whatever. This is * also the place to perform validation. * * @param v * Never null or blank. "false" is the preferred coding for * false/null/off. This has already been url-decoded. * @return value converted into correct form. Can be null for unset * @throws Exception * This will be converted into a {@link WebInputException} by * {@link #getValue(HttpServletRequest)}. */ @Override public X fromString(String v) throws Exception { return (X) v; } /** * HTML code for this form field. If the field had a value in the request * received, then this will be used to set the value. This is for handling * form errors, where it is only polite to preserve the input data rather * than making the poor schmuck enter it all again. Use * {@link #getHtml(null)} if you want to ensure a blank value. */ public final String getHtml() { X v = getValue(); return getHtml(v); } /** * @param value * Will be converted by {@link #toString(Object)}. Can be null. * @return An &lt;input&gt; element with name, value, type and cssClass set * @deprecated OK, but use {@link #getHtml()} instead for most uses * Over-ride {@link #appendHtmlTo(StringBuilder, Object)} if you * need to. */ @Deprecated public final String getHtml(X value) { StringBuilder sb = new StringBuilder(); appendHtmlTo(sb, value); return sb.toString(); } /** * Get the String value for this parameter. Used by * {@link #getValue(HttpServletRequest)}. * <p> * TODO testing across J2EE containers, browsers and nations. * * Warning: null and "" are made equivalent here (since many web forms conflate them with "key=") * * @param request * @return value or null if unset/blank (uses {@link Utils#isBlank(String)}) * @throws MissingFieldException * if the field is required and unset */ // NB: not final cos Checkbox public String getStringValue(HttpServletRequest request) throws MissingFieldException { // UTF8 please... but there were bugs // String enc = request.getCharacterEncoding(); // if(enc == null) { // request.setCharacterEncoding("UTF-8"); // This should perform url decoding // Get the array, in case we have some nulls (as a checkbox hack we use can create) // Badly formatted urls can break this :( // e.g. http://localas.good-loop.com/unit.js?gl.via=loop.me&site=%%SITE%%&gl_url=%%PATTERN:url%%&width=300&height=250&adunit=%%ADUNIT%%&cb=%%CACHEBUSTER%% String[] vs = request.getParameterValues(getName()); String v = null; if (vs!=null) { for (String _v : vs) { if (Utils.isBlank(_v)) continue; // ??should we also screen out "null" and "undefined"?? // They almost certainly are blanks rather than input. if ("undefined".equals(_v)) { continue; } v = _v; break; } } else if (Utils.yes(lenient)) { String qs = request.getQueryString(); if (qs != null) { v = WebUtils2.getQueryParameterQuiet(qs, getName()); } } // null? (or "" or " ", since those would fail the isBlank() above) if (v==null) { if (required) throw new MissingFieldException(this); return null; } // v = WebUtils.urlDecode(v); // WTF? This isn't done already by // HttpServletRequest? // Problem showed up with Spoon's video link. should test this // rigorously! // This *breaks* the text editor when %s are used, so something is wrong // somewhere! // Enforce UTF8? try { byte[] bytes = v.getBytes("UTF-8"); String v2 = new String(bytes, "UTF-8"); v = v2; } catch (UnsupportedEncodingException e) { Log.report(e); } // Using Jetty 6 with Get from Java Everything just works? :) // Using Jetty 6 with Post from FireFox 3: // if ISO-8859 is specified, ISO-8859 are fine & beyond gets html // encoded // if encoding UTF-8 is specified, garbage comes out // return v; } public final String getType() { return type; } /** * @return value to set as default in the html */ protected final X getValue() { IProperties props = Environment.get().get(HTTP_REQUEST_PROPERTIES); if (props == null) return null; X v = props.get(this); return v; } /** * Get the value for this parameter. * * @param request * @return the value, converted into the correct class, or null if unset * @see #getStringValue(HttpServletRequest) * @see #fromString(String) Over-ride this to implement type conversion. */ /* TODO: Consider refactoring to take a RequestState */ public final X getValue(HttpServletRequest request) throws WebInputException { String v = getStringValue(request); if (v == null) return null; try { return fromString(v); } catch (Exception e) { if (Utils.yes(lenient)) { Log.w(getClass().getSimpleName()+"."+name, v+" -> "+e); return null; } if (e instanceof WebInputException) throw (WebInputException) e; throw new WebInputException("Form value for " + getName() + " is invalid: " +StrUtils.ellipsize(v, 300), e); } } /** * Extract a get arg * * @param uri * @return value set in this uri, or null */ public final X getValue(URI uri) { return getValue(uri.toString()); } /** * Extract a get arg * * @param uri * @return value set in this uri, or null */ public X getValue(String url) { String v = WebUtils2.getQueryParameter(url, getName()); if (v == null) return null; try { return fromString(v); } catch (WebInputException e) { throw e; } catch (Exception e) { throw new WebInputException("Form value for " + getName() + " is invalid: " + v, e); } } /** * TODO this is only implemented in a handful of places! It defaults to String * * @return the class of values, i.e. whatever X is bound to */ public Class<X> getValueClass() { return (Class) String.class; } public boolean isRequired() { return required; } public StringBuilder queryParameter(X value) { StringBuilder sb = new StringBuilder(getName()); sb.append("="); if (value != null) { sb.append(WebUtils.urlEncode(toString(value))); } return sb; } /** * Input element id for use in JavaScript */ public void setId(String id) { this.id = id; } /** * This is the type attribute for the input tag (e.g. text, or hidden) - it * is *not* the (Java) type of the field! */ public void setInputType(String type) { this.type = type; } /** * @deprecated * Javascript handler. Will be encoded using * {@link WebUtils#attributeEncode(String)} ad wrapped in quote marks. * * @param onChange */ public final void setOnChange(String onChange) { this.onChange = onChange; } public final AField<X> setRequired(boolean required) { this.required = required; return this; } /** * Sets how wide a text or password field should be. It has no effect on any * other type of field. * * @param size */ public void setSize(int size) { this.size = size; } /** * @deprecated * @param tooltip * @return this for convenient chaining in field initialisers */ public AField<X> setTooltip(String tooltip) { this.tooltip = tooltip; return this; } /** * @param value * never null * @return string representation for value. This is a normal unencoded * string. attribute character encoding is handled elsewhere. The * default implementation just uses toString().<br> * @throws Exception * @see convertString(String) which is the inverse of this */ @Override public String toString(X value) { if (value == null) throw new RuntimeException(); String v = value.toString(); return v; } } /** * Provide values for sending out via {@link #getHtml()}. */ final class RequestProps implements IProperties { private final Map<Key, Object> properties = new HashMap<Key, Object>(); private final HttpServletRequest req; public RequestProps(HttpServletRequest req) { assert req != null; this.req = req; } @Override public <T> boolean containsKey(Key<T> key) { T result = get(key); return (result != null); } @SuppressWarnings("unchecked") @Override public <T> T get(Key<T> key) { Object v = properties.get(key); if (v == null) { AField field = (AField) key; try { // Were we sent a value? If so copy it back out v = field.getValue(req); } catch (MissingFieldException e) { // Ignore } } return (T) v; } @SuppressWarnings("unchecked") @Override public Collection<Key> getKeys() { Set<Key> keys = new HashSet<Key>(); keys.addAll(properties.keySet()); for (Object k : req.getParameterMap().keySet()) { keys.add(new Key(k.toString())); } return keys; } @Override public boolean isTrue(Key<Boolean> key) { Boolean v = get(key); return v != null && v; } @SuppressWarnings("unchecked") @Override public <T> T put(Key<T> key, T value) { if (value == null) return (T) properties.remove(key); else return (T) properties.put(key, value); } @Override public String toString() { return Printer.toString(properties); } }
mit
tbian7/pst
training/src/leetcode/Solution240.java
1289
package leetcode; public class Solution240 { public boolean searchMatrix(int[][] matrix, int target) { if (matrix.length == 0 || matrix[0].length == 0) return false; return searchSubMatrix(matrix, target, 0, matrix.length - 1, 0, matrix[0].length - 1); } private boolean searchSubMatrix(int[][] matrix, int target, int rowMin, int rowMax, int colMin, int colMax) { if (rowMax < rowMin || colMax < colMin) return false; int rowMid = (rowMax + rowMin) / 2; int colMid = binarySearchSubRow(matrix, target, rowMid, colMin, colMax); if (colMid <= colMax && matrix[rowMid][colMid] == target) return true; return searchSubMatrix(matrix, target, rowMin, rowMid - 1, colMid, colMax) || searchSubMatrix(matrix, target, rowMid + 1, rowMax, colMin, colMid - 1); } private int binarySearchSubRow(int[][] matrix, int target, int row, int lo, int hi) { while (lo <= hi) { int mid = (lo + hi) / 2; if (matrix[row][mid] == target) { return mid; } else if (matrix[row][mid] > target) { hi = mid - 1; } else { lo = mid + 1; } } return lo; } }
mit
j574y923/MPOverviewer
src/mpoverviewer/image_layer/tabcontent/CompositionPane.java
25466
package mpoverviewer.image_layer.tabcontent; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javafx.event.EventHandler; import javafx.geometry.Rectangle2D; import javafx.scene.Cursor; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.control.ScrollBar; import javafx.scene.control.ScrollPane; import javafx.scene.control.TabPane; import javafx.scene.image.ImageView; import javafx.scene.input.InputEvent; import javafx.scene.input.KeyCode; import javafx.scene.input.MouseEvent; import javafx.scene.input.ScrollEvent; import javafx.scene.layout.Pane; import javafx.scene.shape.Line; import javafx.scene.text.Text; import mpoverviewer.data_layer.data.MeasureLine; import mpoverviewer.data_layer.data.Note; import mpoverviewer.data_layer.data.Song; import mpoverviewer.global.Constants; import mpoverviewer.global.Variables; import mpoverviewer.image_layer.ImageIndex; import mpoverviewer.ui_layer.tab.TabDraggable; import mpoverviewer.ui_layer.tab.content.ContentControl; /** * * @author J */ public class CompositionPane extends ScrollPane implements ContentControl { private Song song; private Pane pane; private Group content; private int scale = 10; private static final int SCALE_DEFAULT = 10; private static int scaleShared = 10; private ScrollBar scrollBarH = null; private ScrollBar scrollBarV = null; private final List<ImageView> compositionBG = new ArrayList<>(); private final List<Line> lineBG = new ArrayList<>(); private final List<Text> measureNum = new ArrayList<>(); private HashMap<Note, ImageView[]> composition; private List<ImageView> compositionVol; private List<Text> compositionVolText; /* 0 = no mediator, 1 = sieh and block sveh, 2 = sveh and block sieh, note: this is temporary */ private int siehSvehMediator; public void setSiehSvehMediator(int siehSvehMediator) { switch (siehSvehMediator) { case 0: this.siehSvehMediator = 0; break; case 1: this.siehSvehMediator = 1; break; case 2: this.siehSvehMediator = 2; break; default: this.siehSvehMediator = 0; } } public int getSiehSvehMediator() { return siehSvehMediator; } private EventHandlerRubberBand ehrb; public EventHandlerRubberBand getEHRB() { return ehrb; } public CompositionPane(Song song) { super(); //<note, imageNote (0) and imageAccidental (1)> // HashMap<Note, ImageView[]> test; // test = new HashMap<>(); // pane.getChildren().addAll(test.get(new Note(0,0,0))); // to get notes in a rectangle, use math to determine min and max bounds and Song to iterate over notes initBG(); compositionVol = new ArrayList<>(); compositionVolText = new ArrayList<>(); composition = new HashMap<>(); initDraw(song); pane.addEventFilter(ScrollEvent.ANY, new EventHandler<ScrollEvent>() { @Override public void handle(ScrollEvent event) { // if (event.isControlDown()) { // if (event.getDeltaY() < 0) { // zoomOut(); //// keyControl(KeyCode.UP); // } else { // zoomIn(); // //// keyControl(KeyCode.UP); // } // scaleShared = scale; // event.consume(); // } } }); // sharedZoom(); //OPTIMIZATION: do this when switching away to another tab?? // pane.getChildren().clear(); // staff.clear(); // compositionVol.clear(); ehrb = new EventHandlerRubberBand(pane, this); pane.addEventHandler(MouseEvent.ANY, ehrb); pane.addEventFilter(InputEvent.ANY, new StaffInstrumentEventHandler(this, Variables.imageLoader)); pane.addEventFilter(InputEvent.ANY, new StaffVolumeEventHandler(this)); // ArrayList<StackPane> lol = new ArrayList<>(); // for(int i =0 ;i < 7200; i++){ // System.out.println(i); // lol.add(new StackPane()); // } // pane.getChildren().addAll(lol); } @Override public void cleanUp() { // pane.getChildren().clear(); // staff.clear(); // compositionVol.clear(); // compositionBG.clear(); // lineBG.clear(); // measureNum.clear(); } private void initBG() { if (!compositionBG.isEmpty()) { return; } for (int i = 0; i < 22 * 12; i++) { ImageView iv = Variables.imageLoader.getImageView(ImageIndex.STAFF_BG); iv.setTranslateX((i % 22) * 100 + Constants.EDGE_MARGIN); iv.setTranslateY((i / 22) * Constants.ROW_HEIGHT_TOTAL + 16); compositionBG.add(iv); } for (int i = 0; i < 12; i++) { ImageView iv = Variables.imageLoader.getImageView(ImageIndex.TREBLE_CLEF_MPC); iv.setTranslateX(Constants.EDGE_MARGIN); iv.setTranslateY(i * Constants.ROW_HEIGHT_TOTAL + 16); compositionBG.add(iv); int eight = Constants.LINES_IN_A_ROW / 4; for (int j = 0; j < eight; j++) { Text t = new Text(Constants.EDGE_MARGIN + Constants.LINE_SPACING_OFFSET_X + j * Constants.MEASURE_NUM_SPACING_4 - 2, i * Constants.ROW_HEIGHT_TOTAL + 16 - 4, "" + (1 + i * eight + j)); measureNum.add(t); ImageView iv1 = Variables.imageLoader.getImageView(ImageIndex.STAFF_MLINE); iv1.setTranslateX(Constants.EDGE_MARGIN + Constants.LINE_SPACING_OFFSET_X + j * Constants.MEASURE_NUM_SPACING_4); iv1.setTranslateY(i * Constants.ROW_HEIGHT_TOTAL + 16); compositionBG.add(iv1); ImageView iv2 = Variables.imageLoader.getImageView(ImageIndex.STAFF_LINE); iv2.setTranslateX(Constants.EDGE_MARGIN + Constants.LINE_SPACING_OFFSET_X + j * Constants.MEASURE_NUM_SPACING_4 + Constants.LINE_SPACING); iv2.setTranslateY(i * Constants.ROW_HEIGHT_TOTAL + 16); compositionBG.add(iv2); ImageView iv3 = Variables.imageLoader.getImageView(ImageIndex.STAFF_LINE); iv3.setTranslateX(Constants.EDGE_MARGIN + Constants.LINE_SPACING_OFFSET_X + j * Constants.MEASURE_NUM_SPACING_4 + Constants.LINE_SPACING * 2); iv3.setTranslateY(i * Constants.ROW_HEIGHT_TOTAL + 16); compositionBG.add(iv3); ImageView iv4 = Variables.imageLoader.getImageView(ImageIndex.STAFF_LINE); iv4.setTranslateX(Constants.EDGE_MARGIN + Constants.LINE_SPACING_OFFSET_X + j * Constants.MEASURE_NUM_SPACING_4 + Constants.LINE_SPACING * 3); iv4.setTranslateY(i * Constants.ROW_HEIGHT_TOTAL + 16); compositionBG.add(iv4); } } for (int i = 0; i < 12; i++) { Line line = new Line(); line.setStartX(0f); line.setStartY(i * Constants.ROW_HEIGHT_TOTAL + Constants.ROW_HEIGHT_NOTES); line.setEndX((float)Constants.WIDTH_DEFAULT); line.setEndY(i * Constants.ROW_HEIGHT_TOTAL + Constants.ROW_HEIGHT_NOTES); line.setStrokeWidth(2); lineBG.add(line); Line line2 = new Line(); line2.setStartX(0f); line2.setStartY(i * Constants.ROW_HEIGHT_TOTAL + Constants.ROW_HEIGHT_NOTES + Constants.ROW_HEIGHT_VOL + 2); line2.setEndX((float)Constants.WIDTH_DEFAULT); line2.setEndY(i * Constants.ROW_HEIGHT_TOTAL + Constants.ROW_HEIGHT_NOTES + Constants.ROW_HEIGHT_VOL + 2); line2.setStrokeWidth(2); lineBG.add(line2); } } private void initDraw(Song song) { pane = new Pane(); pane.getChildren().addAll(compositionBG); pane.getChildren().addAll(lineBG); pane.getChildren().addAll(measureNum); if (song != null) { //put the song's imageview representation into pane this.song = song; drawSong(song); } content = new Group(pane); setContent(content); } /** * Draw the song if it hasn't been done so already. Call drawSong() after * drawing the bg to draw the contents of a song. This can either be called * upon passing the song via constructor or passing the song after a new * CompositionPane has been declared with no song and song is later loaded * via openSong() in global.Functions. * * @param song passed in via constructor or from the song that gets opened * by openSong() in global.Functions */ public void drawSong(Song song) { for (int i = 0; i < song.size(); i++) { MeasureLine m = song.get(i); ImageView vol = Variables.imageLoader.getImageView(ImageIndex.VOL_BAR); vol.setX(Constants.EDGE_MARGIN + Constants.LINE_SPACING_OFFSET_X + (i % Constants.LINES_IN_A_ROW) * Constants.LINE_SPACING); vol.setY((i / Constants.LINES_IN_A_ROW) * Constants.ROW_HEIGHT_TOTAL + Constants.ROW_HEIGHT_NOTES + Constants.ROW_HEIGHT_VOL + 1); vol.setFitHeight(m.getVolume() / 2); vol.setTranslateY(-m.getVolume()/2); this.compositionVol.add(vol); Text volText = new Text(Constants.EDGE_MARGIN + Constants.LINE_SPACING_OFFSET_X + (i % Constants.LINES_IN_A_ROW) * Constants.LINE_SPACING, (i / Constants.LINES_IN_A_ROW) * Constants.ROW_HEIGHT_TOTAL + Constants.ROW_HEIGHT_NOTES + Constants.ROW_HEIGHT_VOL + 1, "" + m.getVolume()); this.compositionVolText.add(volText); pane.getChildren().add(vol); pane.getChildren().add(volText); if(m.isEmpty()){ vol.setVisible(false); volText.setVisible(false); } for (Note n : m) { ImageIndex imageIndex = ImageIndex.valueOf(n.getInstrument().toString()); ImageView iv = Variables.imageLoader.getImageView(imageIndex); iv.setTranslateX(Constants.EDGE_MARGIN + Constants.LINE_SPACING_OFFSET_X + (i % Constants.LINES_IN_A_ROW) * Constants.LINE_SPACING - 16); iv.setTranslateY(16 + (i / Constants.LINES_IN_A_ROW) * Constants.ROW_HEIGHT_TOTAL + zdy(n.getPosition()) - 11); iv.setSmooth(false); ImageView[] ivArray = new ImageView[2]; ivArray[0] = iv; this.composition.put(n, ivArray); zMod(iv, n); pane.getChildren().add(ivArray[0]); if(ivArray[1] != null) pane.getChildren().add(ivArray[1]); } } } //song data gets modified then call redraw... // public void redrawSong() { // this.composition.clear(); // this.pane.getChildren().clear(); // drawSong(song); // } private void zoomOut() { // System.out.println("zoom Out"); if (scale > 2) { scale--; } double scaleVal = (double) scale / SCALE_DEFAULT; System.out.println("GBIP" + pane.getBoundsInParent().getMinX()); //Apply zoom to all tabs currently selected in their respective windows if (TabDraggable.tabPanes.isEmpty()) { pane.setScaleX(scaleVal); pane.setScaleY(scaleVal); pane.setTranslateX(0); pane.setTranslateX(-(int) pane.getBoundsInParent().getMinX()); pane.setTranslateY(0); pane.setTranslateY(-(int) pane.getBoundsInParent().getMinY()); } else { for (TabPane tabPane : TabDraggable.tabPanes) { Pane paneSel = ((CompositionPane) tabPane.getSelectionModel().getSelectedItem().getContent()).getPane(); paneSel.setScaleX(scaleVal); paneSel.setScaleY(scaleVal); paneSel.setTranslateX(0); paneSel.setTranslateX(-(int) paneSel.getBoundsInParent().getMinX()); paneSel.setTranslateY(0); paneSel.setTranslateY(-(int) paneSel.getBoundsInParent().getMinY()); } } } private void zoomIn() { // System.out.println("zoom In"); if (scale < 20) { scale++; } double scaleVal = (double) scale / SCALE_DEFAULT; System.out.println("GBIP" + pane.getBoundsInParent().getMinX()); //Apply zoom to all tabs currently selected in their respective windows if (TabDraggable.tabPanes.isEmpty()) { pane.setScaleX(scaleVal); pane.setScaleY(scaleVal); pane.setTranslateX(0); pane.setTranslateX(-(int) pane.getBoundsInParent().getMinX()); pane.setTranslateY(0); pane.setTranslateY(-(int) pane.getBoundsInParent().getMinY()); } else { for (TabPane tabPane : TabDraggable.tabPanes) { Pane paneSel = ((CompositionPane) tabPane.getSelectionModel().getSelectedItem().getContent()).getPane(); paneSel.setScaleX(scaleVal); paneSel.setScaleY(scaleVal); paneSel.setTranslateX(0); paneSel.setTranslateX(-(int) paneSel.getBoundsInParent().getMinX()); paneSel.setTranslateY(0); paneSel.setTranslateY(-(int) paneSel.getBoundsInParent().getMinY()); } } } private int zdy(Note.Position p) { return 16 * p.ordinal(); } private void zMod(ImageView iv, Note n) { switch (n.getModifier()) { case SHARP: case FLAT: case DOUBLESHARP: case DOUBLEFLAT: zModHalfStep(iv, n); case NONE: //nothing changes break; case STACCATO: // ImageIndex imageIndex = ImageIndex.valueOf(n.getInstrument().toString() // + "_SIL"); Rectangle2D rect = iv.getViewport(); iv.setViewport(new Rectangle2D(rect.getMinX(), rect.getMinY() + 72, rect.getWidth(), rect.getHeight())); } } private void zModHalfStep(ImageView iv, Note n) { Note.Modifier m = n.getModifier(); ImageIndex imageIndex = ImageIndex.valueOf(m.toString()); ImageView hs = Variables.imageLoader.getImageView(imageIndex); hs.setTranslateX(iv.getTranslateX() - 32); hs.setTranslateY(iv.getTranslateY()); ImageView[] ivArray = composition.get(n); ivArray[1] = hs; // staff.add(hs); } /** * @return pane for zooming calls * @see #zoomOut() * @see #zoomIn() */ public Pane getPane() { return pane; } public Song getSong() { return song; } @Override public Node getNode() { return this; } @Override public void keyControl(KeyCode key, boolean altDown, boolean ctrlDown, boolean shiftDown) { switch (key) { case LEFT: // getScrollBarH().decrement(); // System.out.println(this.getHvalue()); this.setHvalue(this.getHvalue() - 0.05); break; case RIGHT: // getScrollBarH().increment(); this.setHvalue(this.getHvalue() + 0.05); break; case UP: // getScrollBarV().decrement(); this.setVvalue(this.getVvalue() - 0.01); break; case DOWN: // getScrollBarV().increment(); this.setVvalue(this.getVvalue() + 0.01); break; case PAGE_UP: for (int i = 0; i < this.heightProperty().intValue(); i += 50) { // getScrollBarV().decrement(); this.setVvalue(this.getVvalue() - 0.01); } break; case PAGE_DOWN: for (int i = 0; i < this.heightProperty().intValue(); i += 50) { // getScrollBarV().increment(); this.setVvalue(this.getVvalue() + 0.01); } break; case MINUS: if (ctrlDown) { zoomOut(); } break; case PLUS: case EQUALS: if (ctrlDown) { zoomIn(); } break; default: } } @Override public String getTitle() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void sharedBehavior() { sharedZoom(); } private void sharedZoom() { //Apply zoom to the tab selected just now while (scale < scaleShared) { zoomIn(); } while (scale > scaleShared) { zoomOut(); } } @Override public void constructedBehavior() { sharedZoom(); } public void removeNote(int line, Note.Position position){ System.out.println(position); Note n = song.get(line).removeNote(position.ordinal()); if(n != null){ pane.getChildren().remove(composition.get(n)[0]); if(composition.get(n)[1] != null) pane.getChildren().remove(composition.get(n)[1]); composition.remove(n); } if(song.get(line).isEmpty()){ compositionVol.get(line).setVisible(false); compositionVolText.get(line).setVisible(false); } } public void removeNote(int line, Note n){ song.get(line).remove(n); if(n != null){ pane.getChildren().remove(composition.get(n)[0]); if(composition.get(n)[1] != null) pane.getChildren().remove(composition.get(n)[1]); composition.remove(n); } if(song.get(line).isEmpty()){ compositionVol.get(line).setVisible(false); compositionVolText.get(line).setVisible(false); } } public void addNote(int line, Note.Instrument instrument, Note.Position position, Note.Modifier modifier){ System.out.println(position + " " + instrument); Note n = new Note(instrument, position, modifier); if(song.get(line).addNote(n)){ //TODO: add new note imageview... ImageIndex imageIndex = ImageIndex.valueOf(n.getInstrument().toString()); ImageView iv = Variables.imageLoader.getImageView(imageIndex); iv.setTranslateX(Constants.EDGE_MARGIN + Constants.LINE_SPACING_OFFSET_X + (line % Constants.LINES_IN_A_ROW) * Constants.LINE_SPACING - 16); iv.setTranslateY(16 + (line / Constants.LINES_IN_A_ROW) * Constants.ROW_HEIGHT_TOTAL + zdy(n.getPosition()) - 11); ImageView[] ivArray = new ImageView[2]; ivArray[0] = iv; this.composition.put(n, ivArray); zMod(iv, n); redrawLine(line); // pane.getChildren().add(ivArray[0]); // if(ivArray[1] != null) // pane.getChildren().add(ivArray[1]); } else { song.get(line).bringNoteToFront(n); redrawLine(line); } } /** * Should be called whenever a new note is added to the composition hashmap * to properly organize the notes. New note should be added to the song and * composition before calling this. First remove all note ImageViews on that * line from the pane. Then put all note ImageViews on that line into the * pane again. * * @param line at which new note is placed */ public void redrawLine(int line){ for(Note n : song.get(line)){ ImageView[] ivArray = this.composition.get(n); pane.getChildren().remove(ivArray[0]); if(ivArray[1] != null) pane.getChildren().remove(ivArray[1]); } for(Note n : song.get(line)){ ImageView[] ivArray = this.composition.get(n); pane.getChildren().add(ivArray[0]); if(ivArray[1] != null) pane.getChildren().add(ivArray[1]); } if(!song.get(line).isEmpty()) { compositionVol.get(line).setVisible(true); compositionVolText.get(line).setVisible(true); } } /** * Should be called whenever a new note is added or a line is modified in * the song object THEN redrawLine should happen after. This will compare * the notes in composition hashmap and the notes in the song. Updates * composition to include the notes that have been added or removed and adds * or removes their respective imageViews. * * @param line at which notes have changed */ public void reloadLine(int line) { for(Note n : song.get(line)){ if(!this.composition.containsKey(n)) { ImageIndex imageIndex = ImageIndex.valueOf(n.getInstrument().toString()); ImageView iv = Variables.imageLoader.getImageView(imageIndex); iv.setTranslateX(Constants.EDGE_MARGIN + Constants.LINE_SPACING_OFFSET_X + (line % Constants.LINES_IN_A_ROW) * Constants.LINE_SPACING - 16); iv.setTranslateY(16 + (line / Constants.LINES_IN_A_ROW) * Constants.ROW_HEIGHT_TOTAL + zdy(n.getPosition()) - 11); ImageView[] ivArray = new ImageView[2]; ivArray[0] = iv; this.composition.put(n, ivArray); zMod(iv, n); } } for(Note n : song.get(line).popRemovedNotes()) { if(this.composition.containsKey(n)) { removeNote(line, n); } } } /** * Create a shadow around the note image for the note passed in. * * @param n Note passed in * @param highlight flag to create the highlight effect */ private List<Note> highlightedNotes = new ArrayList<>(); public void highlightNote(Note n, boolean highlight){ ImageView[] ivArray = this.composition.get(n); Variables.imageLoader.setImageHighlight(ivArray[0], highlight); if (ivArray[1] != null) { Variables.imageLoader.setImageHighlight(ivArray[1], highlight); } if(highlight) { highlightedNotes.add(n); ivArray[0].setCursor(Cursor.MOVE); } else { // highlightedVols.remove(line); ivArray[0].setCursor(Cursor.DEFAULT); } } private List<Integer> highlightedVols = new ArrayList<>(); public void highlightVol (int line, boolean highlight){ ImageView iv = this.compositionVol.get(line); Variables.imageLoader.setImageHighlight(iv, highlight); if(highlight) { highlightedVols.add(line); iv.setCursor(Cursor.MOVE); } else { // highlightedVols.remove(line); iv.setCursor(Cursor.DEFAULT); } } public void unhighlightAllNotes() { for(Note n : highlightedNotes) { ImageView[] ivArray = this.composition.get(n); if(ivArray != null){ Variables.imageLoader.setImageHighlight(ivArray[0], false); if(ivArray[1] != null) { Variables.imageLoader.setImageHighlight(ivArray[1], false); } ivArray[0].setCursor(Cursor.DEFAULT); } } highlightedNotes.clear(); } public void unhighlightAllVols() { for(Integer line : highlightedVols) { ImageView iv = this.compositionVol.get(line); Variables.imageLoader.setImageHighlight(iv, false); iv.setCursor(Cursor.DEFAULT); } highlightedVols.clear(); } public void setVolume(int line, int volume) { song.get(line).setVolume(volume); compositionVol.get(line).setFitHeight(volume / 2); compositionVol.get(line).setTranslateY(-volume / 2); compositionVolText.get(line).setText("" + volume); } }
mit
Mazdallier/Enchiridion
src/main/java/joshie/enchiridion/EConfig.java
3412
package joshie.enchiridion; import java.util.ArrayList; import net.minecraftforge.common.config.Configuration; import org.apache.logging.log4j.Level; public class EConfig { public static boolean ENABLE_BOOKS = true; public static String DEFAULT_DIR = ""; public static boolean EDIT_ENABLED = true; private static ArrayList<String> colors = new ArrayList(); private static final String[] default_colors = new String[] { "000000", "000080", "00008B", "0000CD", "0000FF", "006400", "080000", "008080", "008B8B", "00BFFF", "00CED1", "00FA9A", "00FF00", "00FF7F", "00FFFF", "191970", "1E90FF", "20B2AA", "228B22", "2E8B57", "2F4F4F", "32CD32", "3CB371", "40E0D0", "4169E1", "4682B4", "483D8B", "48D1CC", "4B0082", "556B2F", "5F9EA0", "6495ED", "66CDAA", "696969", "6A5ACD", "6B8E23", "708090", "778899", "7B68EE", "7CFC00", "7FFF00", "7FFFD4", "800000", "800080", "808000", "808080", "87CEEB", "87CEFA", "8A2BE2", "8B0000", "8B008B", "8B5413", "8FBC8F", "90EE90", "9370DB", "9400D3", "98FB98", "9932CC", "9ACD32", "A0522D", "A52A2A", "A9A9A9", "ADD8E6", "ADFF2F", "AFEEEE", "B0C4DE", "B0E0E6", "B22222", "B8860B", "BA55DE", "BC8F8F", "BDB76B", "C0C0C0", "C71585", "CD5C5C", "CD853F", "D2691E", "D2B48C", "D3D3D3", "D8BFD8", "DA70D6", "DAA520", "DB7093", "DC143C", "DCDCDC", "DDA0DD", "DEB887", "E0FFFF", "E6E6FA", "E9967A", "EE82EE", "EEE8AA", "F08080", "F0E68C", "F0F8FF", "F0FFF0", "F0FFFF", "F4A460", "F5DEB3", "F5F5DC", "F5F5F5", "F5FFFA", "F8F8FF", "FA8072", "FAEBD7", "FAF0E6", "FAFAD2", "FDF5E6", "FF0000", "FF00FF", "FF1493", "FF4500", "FF6347", "FF69B4", "FF7F50", "FF8C00", "FFA07A", "FFA500", "FFB6C1", "FFC0CB", "FFD700", "FFDAB9", "FFDEAD", "FFE4B5", "FFE4C4", "FFE4E1", "FFEBCD", "FFEFD5", "FFF0F5", "FFF5EE", "FFF8DC", "FFFACD", "FFFAF0", "FFFAFA", "FFFF00", "FFFFE0", "FFFFF0", "FFFFFF"}; public static void init(Configuration config) { try { config.load(); String[] color_list = config.get("Settings", "Edit Mode Colours", default_colors, "This is a list of the colours to show up in edit mode by default").getStringList(); ENABLE_BOOKS = config.get("Settings", "Enable Book Item", true).getBoolean(); EDIT_ENABLED = config.get("Settings", "Enable Wiki Editing", true).getBoolean(true); DEFAULT_DIR = config.get("Settings", "Default Save Folder", "").getString(); for(String color: color_list) { addColor(color); } } catch (Exception e) { ELogger.log(Level.ERROR, "Enchiridion 2 failed to load it's config"); e.printStackTrace(); } finally { config.save(); } } public static void addColor(String color) { color = color.replace("#", ""); color = color.replace("0x", ""); if(color.length() == 6) { color = "FF" + color; } boolean added = false; try { Long.parseLong(color, 16); added = true; } catch (Exception e) { added = false; } if(added) { colors.add(color); } } public static String getColor(int index) { return (index >= colors.size() || index < 0)? null: colors.get(index); } }
mit
pagreczner/java-cv-ball-catcher
src/SerialManager.java
3622
//Peter Greczner import javax.comm.*; import java.io.*; import java.util.*; public class SerialManager { public String wantedPort; public SerialPort port; public PrintStream os; public CommPortIdentifier portID; public int baud, databits, parity, flow, stopbits; public char nextChar; public boolean bufferEmpty = true; public SerialManager(String wp) { wantedPort = wp; baud = 230400; parity = SerialPort.PARITY_NONE; databits = SerialPort.DATABITS_8; stopbits = SerialPort.STOPBITS_1; } public boolean findPort() { Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers(); portID = null; while(portIdentifiers.hasMoreElements()) { CommPortIdentifier pid = (CommPortIdentifier)portIdentifiers.nextElement(); if(pid.getPortType() == CommPortIdentifier.PORT_SERIAL && pid.getName().equals(wantedPort)) { portID = pid; break; } } if(portID == null) { System.out.println("Could not find serial port " + wantedPort); return false; } return true; } public void setParams(int b, int d, int s, int p) { baud = b; databits = d; stopbits = s; parity = p; } public boolean openPort() { port = null; try{ port = (SerialPort)portID.open("WebFilter", 10000); port.setSerialPortParams(baud, databits, stopbits, parity); port.addEventListener(new SerialListener()); port.notifyOnOutputEmpty(true); //port.notifyOnDataAvailable(true); bufferEmpty = true; os = new PrintStream(port.getOutputStream(), true); return true; }catch(Exception exc) { exc.printStackTrace(); return false; } } public void closePort() { try{ os.close(); port.close(); }catch(Exception exc) { exc.printStackTrace(); } } public void writeChar(char c) { os.print(c); //nextChar = c; } public void writeByte(byte b) { os.print(b); } public void write(byte b) { os.write(b); } public void writeInt(int i) { os.print(i); } public class SerialListener implements SerialPortEventListener { public void serialEvent(SerialPortEvent event) { switch(event.getEventType()) { case SerialPortEvent.OUTPUT_BUFFER_EMPTY: outputBufferEmpty(event); break; case SerialPortEvent.DATA_AVAILABLE: try{ InputStream is = port.getInputStream(); int c; while((c = is.read()) != -1) { System.out.print(""+(char)c); } System.out.print("\n"); }catch(Exception exc) { } break; } } protected void outputBufferEmpty(SerialPortEvent event) { //os.print(nextChar); bufferEmpty = true; //System.out.println("outputbufferempty"); // Implement writing more data here } } }
mit
Gsantomaggio/turtle
src/main/java/io/turtle/env/nio/client/ClientTurtleEnvironment.java
1698
package io.turtle.env.nio.client; import io.turtle.core.handlers.MessagesHandler; import io.turtle.core.routing.RoutingMessage; import io.turtle.env.local.LocalTurtleEnvironment; import io.turtle.nio.client.NIOClientMT; import java.io.IOException; import java.util.Map; /** * Created by gabriele on 31/03/2015. */ public class ClientTurtleEnvironment extends LocalTurtleEnvironment { private NIOClientMT nioClientMT; private ClientTurtleEnvironment owner = this; public ClientTurtleEnvironment() { super(); nioClientMT = new NIOClientMT() { @Override public void onReadRoutingMessage(RoutingMessage message) { try { owner.publish(message); } catch (InterruptedException e) { e.printStackTrace(); } } }; } @Override public void open() { super.open(); nioClientMT.connect(); } @Override public void close() throws IOException { super.close(); nioClientMT.disconnect(); } public synchronized void remotePublish(Map<String, String> header, byte[] body, String... tags) throws InterruptedException, IOException { nioClientMT.publish(header, body, tags); } public void remotePublish(byte[] body, String... tags) throws InterruptedException, IOException { this.remotePublish(null, body, tags); } public synchronized String remoteSubscribe(MessagesHandler messageHandler, String... tags) throws IOException, InterruptedException { nioClientMT.subscribe(tags); return super.subscribe(messageHandler, tags); } }
mit
RaspberryPiWithJava/Autonomous4j
src/org/autonomous4j/listeners/xyz/A4jErrorListener.java
2703
/* * The MIT License * * Copyright 2014 Mark A. Heckler * * 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.autonomous4j.listeners.xyz; import com.dronecontrol.droneapi.listeners.ErrorListener; import java.util.logging.Level; import java.util.logging.Logger; import org.autonomous4j.interfaces.A4jPublisher; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; /** * * @author Mark Heckler (mark.heckler@gmail.com, @mkheck) */ public class A4jErrorListener implements A4jPublisher, ErrorListener { private final static String TOP_LEVEL_TOPIC = "a4jerrordata"; private MqttClient client; private final MqttMessage msg; private String errorMsg; public A4jErrorListener() { msg = new MqttMessage(); try { client = new MqttClient("tcp://localhost:1883", "a4jerrorlistener"); client.connect(); } catch (MqttException ex) { Logger.getLogger(A4jErrorListener.class.getName()).log(Level.SEVERE, null, ex); } } @Override public String getTopLevelTopic() { return TOP_LEVEL_TOPIC; } @Override public void publish() { try { msg.setPayload(errorMsg.getBytes()); client.publish(TOP_LEVEL_TOPIC + "/error", msg); } catch (MqttException ex) { Logger.getLogger(A4jErrorListener.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void onError(Throwable thrwbl) { errorMsg = thrwbl.getLocalizedMessage(); publish(); } }
mit
PTC-ALM/TIF
jaxb-gen/com/ptc/tifworkbench/jaxbbinding/LoggingType.java
1690
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.08.05 at 03:54:57 PM CEST // package com.ptc.tifworkbench.jaxbbinding; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for LoggingType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="LoggingType"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="none"/> * &lt;enumeration value="mostRecentFirst"/> * &lt;enumeration value="mostRecentLast"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "LoggingType") @XmlEnum public enum LoggingType { @XmlEnumValue("none") NONE("none"), @XmlEnumValue("mostRecentFirst") MOST_RECENT_FIRST("mostRecentFirst"), @XmlEnumValue("mostRecentLast") MOST_RECENT_LAST("mostRecentLast"); private final String value; LoggingType(String v) { value = v; } public String value() { return value; } public static LoggingType fromValue(String v) { for (LoggingType c: LoggingType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
mit
evdubs/XChange
xchange-quadrigacx/src/main/java/org/knowm/xchange/quadrigacx/service/QuadrigaCxTradeServiceRaw.java
3556
package org.knowm.xchange.quadrigacx.service; import java.io.IOException; import java.math.BigDecimal; import org.knowm.xchange.Exchange; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.quadrigacx.QuadrigaCxAuthenticated; import org.knowm.xchange.quadrigacx.QuadrigaCxUtils; import org.knowm.xchange.quadrigacx.dto.trade.QuadrigaCxOrder; import org.knowm.xchange.quadrigacx.dto.trade.QuadrigaCxUserTransaction; import si.mazi.rescu.RestProxyFactory; public class QuadrigaCxTradeServiceRaw extends QuadrigaCxBaseService { private final QuadrigaCxAuthenticated quadrigacxAuthenticated; private final QuadrigaCxDigest signatureCreator; /** * @param exchange */ public QuadrigaCxTradeServiceRaw(Exchange exchange) { super(exchange); this.quadrigacxAuthenticated = RestProxyFactory.createProxy(QuadrigaCxAuthenticated.class, exchange.getExchangeSpecification().getSslUri(), getClientConfig()); this.signatureCreator = QuadrigaCxDigest.createInstance(exchange.getExchangeSpecification().getSecretKey(), exchange.getExchangeSpecification().getUserName(), exchange.getExchangeSpecification().getApiKey()); } public QuadrigaCxOrder[] getQuadrigaCxOpenOrders(CurrencyPair currencyPair) throws IOException { return quadrigacxAuthenticated.getOpenOrders(QuadrigaCxUtils.currencyPairToBook(currencyPair), exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory()); } public QuadrigaCxOrder sellQuadrigaCxOrder(CurrencyPair currencyPair, BigDecimal originalAmount, BigDecimal price) throws IOException { return quadrigacxAuthenticated.sell(QuadrigaCxUtils.currencyPairToBook(currencyPair), exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory(), originalAmount, price); } public QuadrigaCxOrder buyQuadrigaCxOrder(CurrencyPair currencyPair, BigDecimal originalAmount, BigDecimal price) throws IOException { return quadrigacxAuthenticated.buy(QuadrigaCxUtils.currencyPairToBook(currencyPair), exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory(), originalAmount, price); } public QuadrigaCxOrder sellQuadrigaCxOrder(CurrencyPair currencyPair, BigDecimal originalAmount) throws IOException { return quadrigacxAuthenticated.sell(QuadrigaCxUtils.currencyPairToBook(currencyPair), exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory(), originalAmount, null); } public QuadrigaCxOrder buyQuadrigaCxOrder(CurrencyPair currencyPair, BigDecimal originalAmount) throws IOException { return quadrigacxAuthenticated.buy(QuadrigaCxUtils.currencyPairToBook(currencyPair), exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory(), originalAmount, null); } public boolean cancelQuadrigaCxOrder(String orderId) throws IOException { return quadrigacxAuthenticated.cancelOrder(exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory(), orderId); } public QuadrigaCxUserTransaction[] getQuadrigaCxUserTransactions(CurrencyPair currencyPair, Long numberOfTransactions, Long offset, String sort) throws IOException { return quadrigacxAuthenticated.getUserTransactions(QuadrigaCxUtils.currencyPairToBook(currencyPair), exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory(), numberOfTransactions, offset, sort); } }
mit
ElenaKushchenko/otus-java-2017-06-kushchenko
HW12-Jetty/src/main/java/ru/otus/kushchenko/jetty/servlet/util/ServletUtil.java
1176
package ru.otus.kushchenko.jetty.servlet.util; import com.google.gson.Gson; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class ServletUtil { public static void saveToSession(HttpServletRequest request, String attribute, Object object) { request.getSession().setAttribute(attribute, object); } public static Object getFromSession(HttpServletRequest request, String attribute) { return request.getSession().getAttribute(attribute); } public static void removeFromSession(HttpServletRequest request, String attribute) { request.getSession().removeAttribute(attribute); } public static void setStatus(HttpServletResponse response, int sc) { response.setContentType("text/html;charset=utf-8"); response.setStatus(sc); } public static void setBody(HttpServletResponse response, Object object) throws IOException { String json = new Gson().toJson(object); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); } }
mit
zhangqiang110/my4j
pms/src/main/java/com/swfarm/biz/chain/web/DeliverAllocationProductVoucherController.java
2762
package com.swfarm.biz.chain.web; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; import com.swfarm.biz.oa.bo.Employee; import com.swfarm.biz.oa.bo.User; import com.swfarm.biz.oa.dto.SearchEmployeesCriteria; import com.swfarm.biz.oa.srv.UserService; import com.swfarm.pub.framework.Env; import com.swfarm.pub.utils.SpringUtils; public class DeliverAllocationProductVoucherController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { Map<String, Object> dataMap = new HashMap<String, Object>(); dataMap.put("companyCode", Env.COMPANY_CODE); UserService userService = (UserService) SpringUtils .getBean("userService"); SearchEmployeesCriteria criteria = new SearchEmployeesCriteria(); criteria.setDepartment("仓库部"); criteria.setTitle("包货"); List<Employee> employees = userService.searchEmployees(criteria); dataMap.put("employees", employees); if ("accecity".equalsIgnoreCase(Env.COMPANY_CODE)) { List<User> accecityPackageUsers = this .getAccecityPackageEmployees(userService); dataMap.put("accecityPackageUsers", accecityPackageUsers); return new ModelAndView( "chain/deliver_accecityallocationproductvoucher", dataMap); } return new ModelAndView("chain/deliver_allocationproductvoucher", dataMap); } private List<User> getAccecityPackageEmployees(UserService userService) { List<User> users1 = userService.findUsersByRole("见货出单"); List<User> users2 = userService.findUsersByRole("包装员"); return this.mergeUsers(users1, users2); } private List<User> mergeUsers(List<User> users1, List<User> users2) { if (CollectionUtils.isNotEmpty(users1)) { for (Iterator iterator = users1.iterator(); iterator.hasNext();) { User user1 = (User) iterator.next(); if (CollectionUtils.isNotEmpty(users2)) { for (Iterator iterator2 = users2.iterator(); iterator2 .hasNext();) { User user2 = (User) iterator2.next(); if (StringUtils.isNotEmpty(user1.getUsername()) && user1.getUsername().equalsIgnoreCase( user2.getUsername())) { iterator2.remove(); } } } else { return users1; } } users1.addAll(users2); return users1; } return users2; } }
mit
PistoiaHELM/HELMNotationParser
src/test/java/parsertest/groupingsectiontest/GroupingDetailedInformationParserTest.java
3234
/** * ***************************************************************************** * Copyright C 2015, The Pistoia Alliance * * 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 parsertest.groupingsectiontest; import java.io.IOException; import org.helm.notation2.parser.StateMachineParser; import org.helm.notation2.parser.exceptionparser.ConnectionSectionException; import org.helm.notation2.parser.exceptionparser.ExceptionState; import org.helm.notation2.parser.exceptionparser.GroupingSectionException; import org.helm.notation2.parser.groupingsection.BetweenGroupingParser; import org.helm.notation2.parser.groupingsection.GroupingDetailedInformationParser; import org.helm.notation2.parser.groupingsection.GroupingParser; import org.jdom2.JDOMException; import org.testng.annotations.Test; public class GroupingDetailedInformationParserTest { StateMachineParser parser; @Test public void keepThisState() throws ExceptionState, IOException, JDOMException { parser = new StateMachineParser(); parser.setState(new GroupingDetailedInformationParser(parser)); parser.doAction('H'); if(!(parser.getState() instanceof GroupingDetailedInformationParser)){ throw new GroupingSectionException(""); } } @Test public void goToBetweenGroupingParser() throws ExceptionState, IOException, JDOMException { parser = new StateMachineParser(); parser.setState(new GroupingParser(parser)); String test = "G1(G1+G2)"; for(int i = 0; i < test.length(); i ++){ parser.doAction(test.charAt(i)); } if(!(parser.getState() instanceof BetweenGroupingParser)){ throw new ConnectionSectionException(""); } } @Test(expectedExceptions = GroupingSectionException.class) public void goToBetweenGroupingParserWithException() throws ExceptionState, IOException, JDOMException { parser = new StateMachineParser(); parser.setState(new GroupingDetailedInformationParser(parser)); String test = "h)"; for(int i = 0; i < test.length(); i ++){ parser.doAction(test.charAt(i)); } } }
mit
saarons/bottom_line
src/TransactionReducer.java
813
import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.FloatWritable; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; public class TransactionReducer extends MapReduceBase implements Reducer<IntWritable, FloatWritable, IntWritable, FloatWritable> { public void reduce(IntWritable key, Iterator<FloatWritable> values, OutputCollector<IntWritable, FloatWritable> output, Reporter reporter) throws IOException { float sum = 0; while (values.hasNext()) { FloatWritable value = (FloatWritable) values.next(); sum += value.get(); } output.collect(key, new FloatWritable(sum)); } }
mit
jimkyndemeyer/js-graphql-intellij-plugin
src/main/com/intellij/lang/jsgraphql/types/schema/idl/FieldWiringEnvironment.java
2530
/* The MIT License (MIT) Copyright (c) 2015 Andreas Marek and Contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.intellij.lang.jsgraphql.types.schema.idl; import com.intellij.lang.jsgraphql.types.PublicApi; import com.intellij.lang.jsgraphql.types.language.FieldDefinition; import com.intellij.lang.jsgraphql.types.language.TypeDefinition; import com.intellij.lang.jsgraphql.types.schema.GraphQLDirective; import com.intellij.lang.jsgraphql.types.schema.GraphQLOutputType; import java.util.List; @PublicApi public class FieldWiringEnvironment extends WiringEnvironment { private final FieldDefinition fieldDefinition; private final TypeDefinition parentType; private final GraphQLOutputType fieldType; private final List<GraphQLDirective> directives; FieldWiringEnvironment(TypeDefinitionRegistry registry, TypeDefinition parentType, FieldDefinition fieldDefinition, GraphQLOutputType fieldType, List<GraphQLDirective> directives) { super(registry); this.fieldDefinition = fieldDefinition; this.parentType = parentType; this.fieldType = fieldType; this.directives = directives; } public FieldDefinition getFieldDefinition() { return fieldDefinition; } public TypeDefinition getParentType() { return parentType; } public GraphQLOutputType getFieldType() { return fieldType; } public List<GraphQLDirective> getDirectives() { return directives; } }
mit
jonk1993/SpongeAPI
src/main/java/org/spongepowered/api/data/value/mutable/MapValue.java
4627
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.data.value.mutable; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableSet; import org.spongepowered.api.data.value.immutable.ImmutableMapValue; import java.util.Map; import java.util.Map.Entry; /** * Represents a specialized type of {@link Value} that is different from * a {@link CollectionValue} such that the "elements" are * {@link Entry}. Usually, this type of value is used to represent * a particular "type" of "key" that is associated to a particular "value". * * @param <K> The type of the key * @param <V> The type of the value */ public interface MapValue<K, V> extends Value<Map<K, V>> { /** * Gets the size of this map. * * @return The size of this map */ int size(); /** * Associates the provided key to the provided value. If there already * exists a value for the provided key, the value is replaced. * * @param key The key to associate to the value * @param value The value associated with the key * @return This map value, for chaining */ MapValue<K, V> put(K key, V value); /** * Associates all provided {@link Entry} to this map value. * * @param map The map of key values to set * @return This map value, for chaining */ MapValue<K, V> putAll(Map<K, V> map); /** * Removes the association of the provided key to the value currently * associated. * * @param key The key to remove * @return This map value, for chaining */ MapValue<K, V> remove(K key); /** * Removes all key value associations of the provided keys. * * @param keys The keys to remove * @return This map value, for chaining */ MapValue<K, V> removeAll(Iterable<K> keys); /** * Applies the {@link Predicate} to all {@link Entry} within this * {@link MapValue}. Any entries that are false will be removed from the * map value. * * @param predicate The predicate to filer * @return This map value, for chaining */ MapValue<K, V> removeAll(Predicate<Entry<K, V>> predicate); /** * Checks if the provided key is contained within this map. * * @param key The key to check * @return True if the key is contained */ boolean containsKey(K key); /** * Checks if the provided value is contained within this map. * * @param value The value to check * @return True if the value is contained */ boolean containsValue(V value); /** * Gets an {@link ImmutableSet} of all keys contained in this map value. * * @return The set of keys */ ImmutableSet<K> keySet(); /** * Retrieves an {@link ImmutableSet} of the {@link Entry}s contained * within this map value. * * @return The immutable set of entries */ ImmutableSet<Entry<K, V>> entrySet(); /** * Retrieves an {@link ImmutableCollection} of all available values within * this map. * * @return The collection of values */ ImmutableCollection<V> values(); @Override MapValue<K, V> transform(Function<Map<K, V>, Map<K, V>> function); @Override ImmutableMapValue<K, V> asImmutable(); }
mit
Fantast/project-euler
src/main/opener2015/opener15/Task_04.java
1571
package opener15; import org.apfloat.Apfloat; import org.apfloat.ApfloatMath; import tasks.ITask; import tasks.Tester; import utils.log.Logger; //Answer : @SuppressWarnings("SuspiciousNameCombination") public class Task_04 implements ITask { public static void main(String[] args) { Logger.init("default.log"); Tester.test(new Task_04()); Logger.close(); } private final long precision = 300; private final Apfloat ONE = new Apfloat(1, precision); private final Apfloat TWO = new Apfloat(2, precision); private final Apfloat T3 = new Apfloat(3, precision); public void solving() { Apfloat eps = new Apfloat("1e-35", precision); Apfloat l = new Apfloat("0.990", precision); Apfloat r = new Apfloat("0.999", precision); while (r.subtract(l).compareTo(eps) > 0) { Apfloat m1 = l.multiply(TWO).add(r).divide(T3); Apfloat m2 = l.add(r.multiply(TWO)).divide(T3); Apfloat fm1 = f(m1); Apfloat fm2 = f(m2); if (fm1.compareTo(fm2) < 0) { r = m2; } else { l = m1; } } System.out.println(l.toString(true)); System.out.println(r.toString(true)); } public Apfloat f(Apfloat x) { Apfloat num = ApfloatMath.pow(x, 2015).subtract(ONE).multiply(x); Apfloat x2 = x.multiply(x); Apfloat den = ApfloatMath.pow(x2, x2).add(ONE); return num.divide(den); } }
mit
revati1701/topcoder
src/main/java/srm151/ArchimedesTest.java
540
package main.java.srm151; import junit.framework.Assert; import org.junit.Test; public class ArchimedesTest { @Test public void testExample0() { Archimedes archimedes = new Archimedes(); double actual = archimedes.approximatePi(3); double expected = 2.598076211353316; Assert.assertEquals(expected, actual); } @Test public void testExample1() { Archimedes archimedes = new Archimedes(); double actual = archimedes.approximatePi(3); double expected = 2.598076211353316; Assert.assertEquals(expected, actual); } }
mit
NutriCampus/NutriCampus
app/src/main/java/com/nutricampus/app/database/RepositorioEstado.java
2403
package com.nutricampus.app.database; import android.app.Activity; import android.content.Context; import android.util.Log; import com.nutricampus.app.entities.Estado; import com.nutricampus.app.exceptions.EstadoNaoEncontradoException; import com.nutricampus.app.utils.LeitorAssets; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class RepositorioEstado { private List<Estado> lista; private final Context activity; public RepositorioEstado(Context activity) { this.lista = new ArrayList<>(); this.activity = activity; preencheLista("estados.json"); } public RepositorioEstado(Activity activity, String arquivo) { this.lista = new ArrayList<>(); this.activity = activity; preencheLista(arquivo); } public List<Estado> getLista() { return lista; } public List<String> getListaDeNomes() { List<String> nomes = new ArrayList<>(); for (Estado estado : getLista()) { nomes.add(estado.getNome()); } return nomes; } public int getIdPeloNome(String estado) throws EstadoNaoEncontradoException { int cont = 0; while (cont < this.getLista().size()) { if (this.getLista().get(cont).getNome().equals(estado)) return this.getLista().get(cont).getId(); cont++; } throw new EstadoNaoEncontradoException(); } private void preencheLista(String arquivo) { try { JSONObject obj = new JSONObject(LeitorAssets.carregaJSONAssets(arquivo, activity)); JSONArray familiaAray = obj.getJSONArray("estados"); for (int i = 0; i < familiaAray.length(); i++) { JSONObject dadosJSON = familiaAray.getJSONObject(i); String id = dadosJSON.getString("ID"); String nome = dadosJSON.getString("Nome"); String sigla = dadosJSON.getString("Sigla"); Estado estado = new Estado(Integer.valueOf(id), sigla, nome); this.lista.add(estado); } } catch (JSONException e) { Log.i("JSONException", String.valueOf(e)); } catch (IOException e) { Log.getStackTraceString(e); } } }
mit
Jacobingalls/coldboot
src/main/java/edu/utexas/ece/jacobingalls/things/MovingThing.java
2579
package edu.utexas.ece.jacobingalls.things; import edu.utexas.ece.jacobingalls.player.Team; /** * Created by jacobingalls on 11/13/15. */ public abstract class MovingThing extends Thing { private double currentVelocityX = 0; private double currentVelocityY = 0; private double desiredVelocityX = 0; private double desiredVelocityY = 0; private double maxVelocity = 100.0; private double acceleration = 100; public MovingThing(Team team){ super(team); } @Override public void tick(long time_elapsed) { double acc = time_elapsed/1000.0; if(currentVelocityX < desiredVelocityX) currentVelocityX += acceleration * acc; else if(currentVelocityX > desiredVelocityX) currentVelocityX -= acceleration * acc; if(currentVelocityX > maxVelocity) currentVelocityX = maxVelocity; else if(currentVelocityX < -maxVelocity) currentVelocityX = -maxVelocity; if(desiredVelocityY > currentVelocityY) currentVelocityY += acceleration * acc; else if(desiredVelocityY < currentVelocityY) currentVelocityY -= acceleration * acc; if(currentVelocityY > maxVelocity) currentVelocityY = maxVelocity; else if(currentVelocityY < -maxVelocity) currentVelocityY = -maxVelocity; setX(getX() + currentVelocityX * acc); setY(getY() + currentVelocityY * acc); } public double getCurrentVelocityX() { return currentVelocityX; } public MovingThing setCurrentVelocityX(double currentVelocityX) { this.currentVelocityX = currentVelocityX; return this; } public double getCurrentVelocityY() { return currentVelocityY; } public MovingThing setCurrentVelocityY(double currentVelocityY) { this.currentVelocityY = currentVelocityY; return this; } public double getAcceleration() { return acceleration; } public MovingThing setAcceleration(double acceleration) { this.acceleration = acceleration; return this; } public double getDesiredVelocityX() { return desiredVelocityX; } public MovingThing setDesiredVelocityX(double desiredVelocityX) { this.desiredVelocityX = desiredVelocityX; return this; } public double getDesiredVelocityY() { return desiredVelocityY; } public MovingThing setDesiredVelocityY(double desiredVelocityY) { this.desiredVelocityY = desiredVelocityY; return this; } public double getMaxVelocity() { return maxVelocity; } public MovingThing setMaxVelocity(double maxVelocity) { this.maxVelocity = maxVelocity; return this; } public double getVelocityUtilization() { if(maxVelocity <= 0) return -1; else return (Math.abs(currentVelocityX) + Math.abs(currentVelocityY)) / (2 * maxVelocity); } }
mit
scireum/server-sass
src/main/java/org/serversass/Generator.java
20275
/* * Made with all the love in the world * by scireum in Remshalden, Germany * * Copyright by scireum GmbH * http://www.scireum.de - info@scireum.de */ package org.serversass; import org.serversass.ast.Attribute; import org.serversass.ast.Expression; import org.serversass.ast.FunctionCall; import org.serversass.ast.Mixin; import org.serversass.ast.MixinReference; import org.serversass.ast.Section; import org.serversass.ast.Stylesheet; import org.serversass.ast.Value; import org.serversass.ast.Variable; import parsii.tokenizer.ParseException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; /** * Generates CSS code from one or more SASS stylesheets. * <p> * A subclass can be created to override {@link #resolve(String)} to change the way SASS files are * resolved (The default is to use the classpath). Also {@link #warn(String)} and {@link #debug(String)} can be * overridden to process messages which are generated while processing the code. * <p> * The resulting css code can be obtained by calling the {@link #toString()} method. */ public class Generator { /* * Prevents circular imports */ protected Set<String> importedSheets = new TreeSet<>(); /* * Contains all sections which will be part of the output */ protected List<Section> sections = new ArrayList<>(); /* * Contains all sections which can be referenced via @extend */ protected Map<String, Section> extensibleSections = new HashMap<>(); /* * Contains all media queries */ protected Map<String, Section> mediaQueries = new LinkedHashMap<>(); /* * Contains all known mixins */ protected Map<String, Mixin> mixins = new HashMap<>(); /* * Contains the evaluation context (all variables) */ protected Scope scope = new Scope(); protected File baseDir; /** * Generates a new Generator without a directory used for lookups. * <p> * This generator will resolve all imports using the classpath. */ public Generator() { } /** * Generates a new Generator using the given directory for lookups. * <p> * This generator will resolve all imports using the given directory or the classpath. * * @param baseDir the directory with contains the imports */ public Generator(File baseDir) { this.baseDir = baseDir; } /** * Called to signal a warning, like an invalid operation or parse errors in a source file. * <p> * By default all messages are discarded. * * @param message the message which is reported */ public void warn(String message) { // unused } /** * Contains a message which might be helpful in development systems but are generally not of great * interest in production systems. * * @param message the message which is reported */ public void debug(String message) { // unused } /** * Resolves a given name into a template. * <p> * By default the classloader is used to resolve the template. Also .scss or _ are added as post-/prefix * if required. * * @param sheet the name of the file to resolve * @return the resolved stylesheet or <tt>null</tt> if the file is not found */ protected Stylesheet resolve(String sheet) { try { sheet = sheet.replace("\\", "/"); if (!sheet.endsWith(".scss")) { sheet += ".scss"; } try (InputStream is = resolveIntoStream(sheet)) { if (is == null) { warn("Cannot resolve '" + sheet + "'. Skipping import."); return null; } Parser p = new Parser(sheet, new InputStreamReader(is)); return p.parse(); } } catch (ParseException e) { warn(String.format("Error parsing: %s%n%s", sheet, e.toString())); } catch (Exception e) { warn(String.format("Error importing: %s: %s (%s)", sheet, e.getMessage(), e.getClass().getName())); } return null; } /** * Resolves the given file name into an {@link InputStream} * * @param sheet the file to resolve (already cleaned up by replacing \ with / and appending .scss if necessary). * @return an InputStream for the resolved data or <tt>null</tt> to indicate that the resource cannot be found * @throws IOException in case of an error while resolving or reading the contents */ protected InputStream resolveIntoStream(String sheet) throws IOException { if (baseDir != null) { File file = baseDir; for (String part : sheet.split("/")) { file = new File(file, part); } if (file.exists() && file.isFile()) { return new FileInputStream(file); } else { return null; } } else { InputStream is = getClass().getResourceAsStream((sheet.startsWith("/") ? "" : "/") + sheet); if (is == null) { is = getClass().getResourceAsStream((sheet.startsWith("/") ? "" : "/") + "_" + sheet); } return is; } } /** * Instructs the generator to include a scss file. This is also used to load the initial file. * * @param sheet the scss file to load. */ public void importStylesheet(String sheet) { if (importedSheets.contains(sheet)) { return; } importStylesheet(resolve(sheet)); } /** * Imports an already parsed stylesheet. * * @param sheet the stylesheet to import */ public void importStylesheet(Stylesheet sheet) { if (sheet == null) { return; } if (importedSheets.contains(sheet.getName())) { return; } importedSheets.add(sheet.getName()); for (String imp : sheet.getImports()) { importStylesheet(imp); } for (Mixin mix : sheet.getMixins()) { mixins.put(mix.getName(), mix); } for (Variable var : sheet.getVariables()) { if (!scope.has(var.getName()) || !var.isDefaultValue()) { scope.set(var.getName(), var.getValue()); } else { debug("Skipping redundant variable definition: '" + var + "'"); } } for (Section section : sheet.getSections()) { List<Section> stack = new ArrayList<>(); expand(null, section, stack); } } /* * Expands nested sections / media queries into a flat structure as expected by CSS */ private void expand(String mediaQueryPath, Section section, List<Section> stack) { stack = new ArrayList<>(stack); if (!section.getSelectors().isEmpty()) { expandSection(mediaQueryPath, section, stack); } else { mediaQueryPath = expandMediaQuery(mediaQueryPath, section, stack); } if (section.getSelectorString() != null && !section.getSelectorString().startsWith("@")) { // Unfold subsections for (Section child : section.getSubSections()) { expand(mediaQueryPath, child, stack); } // Delete subsections - no longer necessary (and not supported by css) section.getSubSections().clear(); } } private String expandMediaQuery(String mediaQueryPath, Section section, List<Section> stack) { mediaQueryPath = expandMediaQueryPath(mediaQueryPath, section); // We have implicit attributes - copy the next non-media-query parent // and create a pseudo-secion covering these attributes if (!section.getAttributes().isEmpty()) { transfertImplicitAttributes(mediaQueryPath, section, stack); } return mediaQueryPath; } private void transfertImplicitAttributes(String mediaQueryPath, Section section, List<Section> stack) { Section copy = new Section(); if (!stack.isEmpty()) { Section parent = stack.get(stack.size() - 1); if (copy.getSelectors().isEmpty()) { copy.getSelectors().addAll(parent.getSelectors()); } else if (!parent.getSelectors().isEmpty()) { for (List<String> selector : copy.getSelectors()) { selector.addAll(0, parent.getSelectors().get(0)); } } } if (copy.getSelectors().isEmpty()) { warn(String.format("Cannot define attributes in @media selector '%s'", section.getMediaQuery(scope, this))); } else { copy.getAttributes().addAll(section.getAttributes()); addResultSection(mediaQueryPath, copy); } } private String expandMediaQueryPath(String mediaQueryPath, Section section) { // We're a media query - update path if (mediaQueryPath == null) { mediaQueryPath = "@media " + section.getMediaQuery(scope, this); } else { mediaQueryPath += " and " + section.getMediaQuery(scope, this); } return mediaQueryPath; } private void expandSection(String mediaQueryPath, Section section, List<Section> stack) { // We have selectors -> we're a normal section no a media query if (mediaQueryPath == null) { // Add to output sections.add(section); } else { // We're already inside a media query, add to the appropriate result section addResultSection(mediaQueryPath, section); } // Expand all selectors with those of the parents (flatten nesting) List<List<String>> newSelectors = new ArrayList<>(); for (List<String> selector : section.getSelectors()) { if (stack.isEmpty()) { // no parent selector newSelectors.add(expandSelector(section, selector, null)); } else { // create the cross product of the parent selector set and the current selector set for (List<String> parentSelector : stack.get(stack.size() - 1).getSelectors()) { // clone selector, so that each expansion starts with the initial child selector newSelectors.add(expandSelector(section, new ArrayList<>(selector), parentSelector)); } } } // overwrite all selectors of this section, because the size may have changed section.getSelectors().clear(); section.getSelectors().addAll(newSelectors); // Add to nesting stack used by children stack.add(section); } private List<String> expandSelector(Section section, List<String> selector, List<String> parentSelector) { if (parentSelector != null) { if (selector.size() > 1 && !parentSelector.isEmpty() && "&".equals(selector.get(0))) { combineSelectors(selector, parentSelector); } else if ("&".equals(selector.get(selector.size() - 1))) { selector.remove(selector.size() - 1); selector.addAll(parentSelector); } else { selector.addAll(0, parentSelector); } } // Selectors with only one element can be referenced by @extend if (selector.size() == 1) { extensibleSections.put(selector.get(0), section); } return selector; } /* * If a child selector starts with & e.g. &.test we have to marry the last element of * the parent selector with the first element of the child selector to create * "ul nav.test" (if the parent as "ul nav"). Without the & this would become * "ul nav .test"... */ private void combineSelectors(List<String> selector, List<String> parentSelectors) { String firstChild = selector.get(1); selector.remove(0); selector.remove(0); List<String> selectorsToAdd = new ArrayList<>(parentSelectors); String lastParent = selectorsToAdd.get(selectorsToAdd.size() - 1); selectorsToAdd.remove(selectorsToAdd.size() - 1); selector.add(0, lastParent + firstChild); selector.addAll(0, selectorsToAdd); } /* * Adds a section to the given media query section - creates if necessary */ private void addResultSection(String mediaQueryPath, Section section) { Section qry = mediaQueries.get(mediaQueryPath); if (qry == null) { qry = new Section(); qry.getSelectors().add(Collections.singletonList(mediaQueryPath)); mediaQueries.put(mediaQueryPath, qry); } qry.addSubSection(section); } /** * Compiles the parsed sources. * <p> * This will evaluate all @mixin and @extends statements and evaluate all expressions. Needs to be called before * the sources are retrieved via {@link #toString()}. */ public void compile() { // Treat media queries as "normal" sections as they are supported by CSS sections.addAll(mediaQueries.values()); for (Section section : new ArrayList<Section>(sections)) { compileSection(section); } // Delete empty selectors sections.removeIf(section -> section.getSubSections().isEmpty() && section.getAttributes().isEmpty()); } private void compileSection(Section section) { // Handle and perform all @extend instructions for (String extend : section.getExtendedSections()) { Section toBeExtended = extensibleSections.get(extend); if (toBeExtended != null) { toBeExtended.getSelectors().addAll(section.getSelectors()); } else { warn(String.format("Skipping unknown @extend '%s' referenced by selector '%s'", extend, section.getSelectorString())); } } // Handle and perform all @mixin instructions compileMixins(section); // Evaluate expressions of the section for (Attribute attr : section.getAttributes()) { attr.setExpression(attr.getExpression().eval(scope, this)); } for (Section subSection : section.getSubSections()) { compileSection(subSection); } } protected void compileMixins(Section section) { for (MixinReference ref : section.getReferences()) { // Create a sub scope which will have access to the parameter values Scope subScope = new Scope(scope); // Find mixin.. Mixin mixin = mixins.get(ref.getName()); if (mixin == null) { warn(String.format("Skipping unknown @mixin '%s' referenced by selector '%s'", ref.getName(), section.getSelectorString())); return; } compileMixin(section, ref, subScope, mixin); } } private void compileMixin(Section section, MixinReference ref, Scope subScope, Mixin mixin) { // Check if number of parameters match if (mixin.getParameters().size() != ref.getParameters().size()) { warn(String.format( "@mixin call '%s' by selector '%s' does not match expected number of parameters. Found: %d, expected: %d", ref.getName(), section.getSelectorString(), ref.getParameters().size(), mixin.getParameters().size())); } // Evaluate all parameters and populate sub scope evaluateParameters(ref, subScope, mixin); // Copy attributes and evaluate expression copyAndEvaluateAttributes(section, subScope, mixin); for (Section child : mixin.getSubSections()) { processSubSection(section, subScope, child); } } private void processSubSection(Section section, Scope subScope, Section child) { Section newCombination = new Section(); for (List<String> outer : child.getSelectors()) { for (List<String> inner : section.getSelectors()) { List<String> fullSelector = new ArrayList<>(outer); if ("&".equals(outer.get(outer.size() - 1))) { fullSelector.remove(fullSelector.size() - 1); fullSelector.addAll(inner); } else if ("&".equals(outer.get(0))) { combineSelectors(fullSelector, inner); } else { fullSelector.addAll(0, inner); } newCombination.getSelectors().add(fullSelector); } } for (Attribute attr : child.getAttributes()) { Attribute copy = new Attribute(attr.getName()); copy.setExpression(attr.getExpression().eval(subScope, this)); newCombination.addAttribute(copy); } sections.add(newCombination); } private void copyAndEvaluateAttributes(Section section, Scope subScope, Mixin mixin) { for (Attribute attr : mixin.getAttributes()) { if (attr.getExpression().isConstant()) { section.addAttribute(attr); } else { Attribute copy = new Attribute(attr.getName()); copy.setExpression(attr.getExpression().eval(subScope, this)); section.addAttribute(copy); } } } private void evaluateParameters(MixinReference ref, Scope subScope, Mixin mixin) { int i = 0; for (String name : mixin.getParameters()) { if (ref.getParameters().size() > i) { subScope.set(name, ref.getParameters().get(i)); } i++; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Section section : sections) { sb.append(section); sb.append("\n"); } return sb.toString(); } /** * Generates the final output into the given parameter. * * @param out the target for the generated output * @throws IOException in case of an io error in the underlying writer */ public void generate(Output out) throws IOException { for (Section section : sections) { section.generate(out); out.lineBreak(); out.optionalLineBreak(); } } /** * Evaluates the given function. * <p> * Can be overridden by subclasses. If no matching function is found, the raw sources are output to handle * {@code url('..')} etc. * * @param call the function to evaluate * @return the result of the evaluation */ public Expression evaluateFunction(FunctionCall call) { try { return (Expression) Functions.class.getDeclaredMethod(call.getName() .toLowerCase() .replaceAll("[^a-z0-9]", ""), Generator.class, FunctionCall.class).invoke(null, this, call); } catch (NoSuchMethodException ignored) { return new Value(call.toString()); } catch (InvocationTargetException e) { warn("Cannot execute function: " + call + " - " + e.getCause().getMessage()); } catch (Exception e) { warn("Cannot execute function: " + call + " - " + e.getMessage()); } return new Value(call.toString()); } }
mit
opentok/opentok-android-sdk-samples
Basic-Video-Driver-Java/app/src/main/java/com/tokbox/sample/basicvideodriver/MainActivity.java
8310
package com.tokbox.sample.basicvideodriver; import android.Manifest; import android.opengl.GLSurfaceView; import android.os.Bundle; import android.util.Log; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.opentok.android.BaseVideoRenderer; import com.opentok.android.OpentokError; import com.opentok.android.Publisher; import com.opentok.android.PublisherKit; import com.opentok.android.Session; import com.opentok.android.Stream; import com.opentok.android.Subscriber; import com.opentok.android.SubscriberKit; import pub.devrel.easypermissions.AfterPermissionGranted; import pub.devrel.easypermissions.EasyPermissions; import java.util.List; public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks { private static final String TAG = MainActivity.class.getSimpleName(); private static final int PERMISSIONS_REQUEST_CODE = 124; private Session session; private Publisher publisher; private Subscriber subscriber; private RelativeLayout publisherViewContainer; private LinearLayout subscriberViewContainer; private PublisherKit.PublisherListener publisherListener = new PublisherKit.PublisherListener() { @Override public void onStreamCreated(PublisherKit publisherKit, Stream stream) { Log.d(TAG, "onStreamCreated: Own stream " + stream.getStreamId() + " created"); } @Override public void onStreamDestroyed(PublisherKit publisherKit, Stream stream) { Log.d(TAG, "onStreamDestroyed: Own stream " + stream.getStreamId() + " destroyed"); } @Override public void onError(PublisherKit publisherKit, OpentokError opentokError) { finishWithMessage("PublisherKit error: " + opentokError.getMessage()); } }; private Session.SessionListener sessionListener = new Session.SessionListener() { @Override public void onConnected(Session session) { Log.d(TAG, "onConnected: Connected to session " + session.getSessionId()); MirrorVideoCapturer mirrorVideoCapturer = new MirrorVideoCapturer(MainActivity.this); InvertedColorsVideoRenderer invertedColorsVideoRenderer = new InvertedColorsVideoRenderer(MainActivity.this); publisher = new Publisher.Builder(MainActivity.this) .capturer(mirrorVideoCapturer) .renderer(invertedColorsVideoRenderer) .build(); publisher.setPublisherListener(publisherListener); publisher.setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL); publisherViewContainer.addView(publisher.getView()); if (publisher.getView() instanceof GLSurfaceView) { ((GLSurfaceView) (publisher.getView())).setZOrderOnTop(true); } session.publish(publisher); } @Override public void onDisconnected(Session session) { Log.d(TAG, "onDisconnected: disconnected from session " + session.getSessionId()); MainActivity.this.session = null; } @Override public void onError(Session session, OpentokError opentokError) { finishWithMessage("Session error: " + opentokError.getMessage()); } @Override public void onStreamReceived(Session session, Stream stream) { Log.d(TAG, "onStreamReceived: New stream " + stream.getStreamId() + " in session " + session.getSessionId()); if (subscriber != null) { return; } subscribeToStream(stream); } @Override public void onStreamDropped(Session session, Stream stream) { Log.d(TAG, "onStreamDropped: Stream " + stream.getStreamId() + " dropped from session " + session.getSessionId()); if (subscriber == null) { return; } if (subscriber.getStream().equals(stream)) { subscriberViewContainer.removeView(subscriber.getView()); subscriber = null; } } }; private Subscriber.VideoListener videoListener = new Subscriber.VideoListener() { @Override public void onVideoDataReceived(SubscriberKit subscriberKit) { subscriber.setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL); subscriberViewContainer.addView(subscriber.getView()); } @Override public void onVideoDisabled(SubscriberKit subscriberKit, String s) { } @Override public void onVideoEnabled(SubscriberKit subscriberKit, String s) { } @Override public void onVideoDisableWarning(SubscriberKit subscriberKit) { } @Override public void onVideoDisableWarningLifted(SubscriberKit subscriberKit) { } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (!OpenTokConfig.isValid()) { finishWithMessage("Invalid OpenTokConfig. " + OpenTokConfig.getDescription()); return; } publisherViewContainer = findViewById(R.id.publisherview); subscriberViewContainer = findViewById(R.id.subscriberview); requestPermissions(); } @Override protected void onPause() { super.onPause(); if (session == null) { return; } session.onPause(); if (isFinishing()) { disconnectSession(); } } @Override protected void onResume() { super.onResume(); if (session == null) { return; } session.onResume(); } @Override protected void onDestroy() { disconnectSession(); super.onDestroy(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this); } @Override public void onPermissionsGranted(int requestCode, List<String> perms) { Log.d(TAG, "onPermissionsGranted:" + requestCode + ": " + perms); } @Override public void onPermissionsDenied(int requestCode, List<String> perms) { finishWithMessage("onPermissionsDenied: " + requestCode + ": " + perms); } @AfterPermissionGranted(PERMISSIONS_REQUEST_CODE) private void requestPermissions() { String[] perms = {Manifest.permission.INTERNET, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}; if (EasyPermissions.hasPermissions(this, perms)) { session = new Session.Builder(this, OpenTokConfig.API_KEY, OpenTokConfig.SESSION_ID).build(); session.setSessionListener(sessionListener); session.connect(OpenTokConfig.TOKEN); } else { EasyPermissions.requestPermissions(this, getString(R.string.rationale_video_app), PERMISSIONS_REQUEST_CODE, perms); } } private void subscribeToStream(Stream stream) { subscriber = new Subscriber.Builder(this, stream).build(); subscriber.setVideoListener(videoListener); session.subscribe(subscriber); } private void disconnectSession() { if (session == null) { return; } if (subscriber != null) { subscriberViewContainer.removeView(subscriber.getView()); session.unsubscribe(subscriber); subscriber = null; } if (publisher != null) { publisherViewContainer.removeView(publisher.getView()); session.unpublish(publisher); publisher = null; } session.disconnect(); } private void finishWithMessage(String message) { Log.e(TAG, message); Toast.makeText(this, message, Toast.LENGTH_LONG).show(); this.finish(); } }
mit
eXsio/ddd-poc
domain/src/main/java/com/ddd/poc/domain/security/subscriber/GroupEventsSubscriber.java
1960
package com.ddd.poc.domain.security.subscriber; import com.ddd.poc.domain.security.event.GroupCreatedEvent; import com.ddd.poc.domain.security.event.GroupDeletedEvent; import com.ddd.poc.domain.security.event.GroupUpdatedEvent; import com.ddd.poc.domain.security.model.Group; import com.ddd.poc.domain.security.model.GroupRepository; import com.ddd.poc.domain.security.util.ThreadUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; @Service @Transactional public class GroupEventsSubscriber { private final static Logger LOGGER = LoggerFactory.getLogger(GroupEventsSubscriber.class); private final GroupRepository groupRepository; @Autowired public GroupEventsSubscriber(GroupRepository groupRepository) { this.groupRepository = groupRepository; } @EventListener public void onGroupCreated(GroupCreatedEvent event) { LOGGER.info("Group created subscriber called"); ThreadUtil.simulateLatecy(); groupRepository.save(groupRepository.create().update(event.getName())); } @EventListener public void onGroupUpdated(GroupUpdatedEvent event) { LOGGER.info("Group updated subscriber called"); ThreadUtil.simulateLatecy(); Optional<Group> group = groupRepository.find(event.getGroupId()); group.ifPresent(groupObj -> groupRepository.save(groupObj.update(event.getNewName()))); } @EventListener public void onGroupDeleted(GroupDeletedEvent event) { LOGGER.info("Group deleted subscriber called"); ThreadUtil.simulateLatecy(); Optional<Group> group = groupRepository.find(event.getGroupId()); group.ifPresent(groupRepository::delete); } }
mit
magx2/jSupla
protocol-java/src/test/java/pl/grzeslowski/jsupla/protocoljava/impl/serializers/sdc/GetVersionResultSerializerImplTest.java
1920
package pl.grzeslowski.jsupla.protocoljava.impl.serializers.sdc; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import pl.grzeslowski.jsupla.protocol.api.structs.sdc.SuplaGetVersionResult; import pl.grzeslowski.jsupla.protocoljava.api.entities.sdc.GetVersionResult; import pl.grzeslowski.jsupla.protocoljava.api.serializers.Serializer; import pl.grzeslowski.jsupla.protocoljava.api.serializers.StringSerializer; import pl.grzeslowski.jsupla.protocoljava.impl.serializers.SerializerTest; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.verify; import static pl.grzeslowski.jsupla.protocol.api.consts.ProtoConsts.SUPLA_SOFTVER_MAXSIZE; @SuppressWarnings("WeakerAccess") public class GetVersionResultSerializerImplTest extends SerializerTest<GetVersionResult, SuplaGetVersionResult> { @InjectMocks GetVersionResultSerializerImpl serializer; @Mock StringSerializer stringSerializer; @Override protected GetVersionResult given() { givenStringSerializer(stringSerializer); return super.given(); } @Override protected void then(final GetVersionResult entity, final SuplaGetVersionResult proto) { assertThat((int) proto.protoVersionMin).isEqualTo(entity.getProtoVersionMin()); assertThat((int) proto.protoVersion).isEqualTo(entity.getProtoVersion()); verify(stringSerializer).serialize(entity.getSoftVer(), SUPLA_SOFTVER_MAXSIZE); } @Override protected Serializer<GetVersionResult, SuplaGetVersionResult> serializer() { return serializer; } @Override protected Class<GetVersionResult> entityClass() { return GetVersionResult.class; } @Test(expected = NullPointerException.class) public void shouldThrowNullPointerExceptionWhenStringSerializerIsNull() { new GetVersionResultSerializerImpl(null); } }
mit
balanced/balanced-java
src/main/java/com/balancedpayments/Callback.java
1301
package com.balancedpayments; import com.balancedpayments.core.Resource; import com.balancedpayments.core.ResourceCollection; import com.balancedpayments.core.ResourceField; import com.balancedpayments.core.ResourceQuery; import com.balancedpayments.errors.HTTPError; import java.util.Map; public class Callback extends Resource { public static final String resource_href = "/callbacks"; @ResourceField(mutable=true) public String url; @ResourceField(mutable=true, required=false) public String method; @ResourceField(required=false) public String revision; public static class Collection extends ResourceCollection<Callback> { public Collection(String href) { super(Callback.class, href); } }; public Callback() { super(); } public Callback(String href) throws HTTPError { super(href); } public Callback(Map<String, Object> payload) throws HTTPError { super(payload); } public static ResourceQuery<Callback> query() { return new ResourceQuery<Callback>(Callback.class, resource_href); } @Override public void save() throws HTTPError { if (id == null && href == null) { href = resource_href; } super.save(); } }
mit
ActiveStack/syncengine
src/main/java/com/percero/agents/sync/metadata/JpqlQuery.java
3438
package com.percero.agents.sync.metadata; import java.util.Date; import java.util.Iterator; import java.util.Map; import org.apache.log4j.Logger; import org.hibernate.Query; import org.hibernate.engine.query.NamedParameterDescriptor; import org.hibernate.engine.query.ParameterMetadata; import org.hibernate.impl.SessionFactoryImpl; import org.hibernate.impl.SessionImpl; import org.hibernate.type.TimestampType; import org.hibernate.type.Type; public class JpqlQuery extends MappedQuery { private static final Logger log = Logger.getLogger(JpqlQuery.class); private ParameterMetadata parameterMetadata = null; @Override public void setQuery(String value) { int index = value.indexOf("jpql:"); if (index >= 0) value = value.substring(index + 5); super.setQuery(value); } public Query createQuery(Object theObject, String userId, Object[] params, SessionImpl s) throws Exception { String queryString = getQuery(); queryString = setQueryParameters(queryString, theObject, userId, params); queryString = setParameterMetadata(queryString, theObject, userId, params, s); Query theQuery = s.createQuery(queryString); return theQuery; } private String setParameterMetadata(String theQuery, Object theObject, String userId, Object[] params, SessionImpl s) { // Get Parameter MetaData. if (params != null && params.length > 0) { if (parameterMetadata == null) { try { parameterMetadata = ((SessionFactoryImpl)s.getSessionFactory()).getQueryPlanCache().getHQLQueryPlan(theQuery, false, (s).getEnabledFilters()).getParameterMetadata(); } catch(Exception e) { log.warn("Unable to get ParameterMetaData from Query:\n" + theQuery, e); } } for(Object nextParam : params) { if (nextParam instanceof Map) { Map nextMapParam = (Map) nextParam; Iterator itr = nextMapParam.entrySet().iterator(); while(itr.hasNext()) { Boolean paramSet = false; try { Map.Entry pairs = (Map.Entry) itr.next(); Object key = pairs.getKey(); Object value = pairs.getValue(); if (key instanceof String) { String strKey = (String) key; if (parameterMetadata != null) { NamedParameterDescriptor npd = parameterMetadata.getNamedParameterDescriptor(strKey); if (npd != null) { Type expectedType = npd.getExpectedType(); if (expectedType instanceof TimestampType) { Date dateValue = new Date((Long)value); theQuery = theQuery.replaceAll(":" + strKey, "'" + dateValue + "'"); } else { theQuery = theQuery.replaceAll(":" + (String) key, "\"" + value + "\""); } paramSet = true; } } // Last ditch effort to set this parameter. if (!paramSet) theQuery = theQuery.replaceAll(":" + (String) key, "\"" + value + "\""); } } catch(Exception e) { log.warn("Unable to apply parameter to filter", e); } } } else if (nextParam instanceof String) { String nextStringParam = (String) nextParam; try { String[] paramSplit = nextStringParam.split(":"); String key = paramSplit[0]; String value = paramSplit[1]; theQuery = theQuery.replaceAll(":" + key, "\"" + value + "\""); } catch(Exception e) { log.warn("Unable to apply parameter to filter", e); } } } } return theQuery; } }
mit
mathewsunit/cs6301
SP2/Problem 2/SortableList.java
2657
/* * Created by * Group 50 * * Varun Simha Balaraju * Venkata Sarath Chandra Prasad Nelapati * Jithin Paul * Sunit Mathew * on 9/10/2017. */ //package cs6301.g50; import java.util.NoSuchElementException; import SinglyLinkedList; public class SortableList<T extends Comparable<? super T>> extends SinglyLinkedList<T> { /*Default Constructor */ public SortableList() {super();} /*Parameterized Constructor */ public SortableList(Entry<T> head,Entry<T> tail,int size) {super(head, tail, size);} /* Splits the List into two and returns them as SortableLists*/ public void splitList(SortableList<T> l1,SortableList<T> l2) { int listSize = size(); int mid = listSize/2; Entry<T> tail0 = head; while(mid-- > 0) { tail0 = tail0.next; } Entry<T> head1 = tail0.next; tail0.next = null; l1 = new SortableList<T>(head.next,tail0,listSize/2); l2 = new SortableList<T>(head1,tail,listSize- listSize/2); } /*Merge this list with other list*/ void merge(SortableList<T> otherList) { Entry<T> self = head.next; Entry<T> other = otherList.head.next; Entry<T> prev = null; while(self != null && other != null) { if(self.element.compareTo(other.element) < 0){ prev = self; self = self.next; }else{ Entry<T> temp = other; other = other.next; if(prev!=null) prev.next = temp; temp.next = self; } } if(self==null && other != null && prev != null) prev.next = other; } /*Sort this list*/ void mergeSort() { int listSize = size(); if(listSize < 2) return; int mid = listSize/2; Entry<T> tail0 = head; while(mid-- > 0) { tail0 = tail0.next; } Entry<T> head1 = tail0.next; tail0.next = null; SortableList<T> l1 = new SortableList<T>(head.next,tail0,listSize/2); SortableList<T> l2 = new SortableList<T>(head1,tail,listSize- listSize/2); l1.mergeSort(); l2.mergeSort(); l1.merge(l2); } public static<T extends Comparable<? super T>> void mergeSort(SortableList<T> list) { list.mergeSort(); } public static void main(String[] args) throws NoSuchElementException { int n = 10; //if(args.length > 0) { // n = Integer.parseInt(args[0]); //} SortableList<Integer> lst = new SortableList<Integer>(); Random generator = new Random(); for(int i=1; i<=n; i++) { lst.add(generator.nextInt(100)); } lst.mergeSort(); lst.printList(); } } /* Sample input: 4 2 3 1 10 5 6 8 9 7 Sample output: 1 2 3 4 5 6 7 8 9 10 */
mit
owolp/Mini-Demo-Apps-Android
AnimationDemo/app/src/main/java/com/owolp/animationdemo/MainActivity.java
8064
package com.owolp.animationdemo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener, Animation.AnimationListener { Animation animFadeIn; Animation animFadeOut; Animation animFadeInOut; Animation animZoomIn; Animation animZoomOut; Animation animLeftRight; Animation animRightLeft; Animation animTopBottom; Animation animBounce; Animation animFlash; Animation animRotateLeft; Animation animRotateRight; ImageView imageView; TextView textStatus; TextView textSeekerSpeed; Button btnFadeIn; Button btnFadeOut; Button btnFadeInOut; Button zoomIn; Button zoomOut; Button leftRight; Button rightLeft; Button topBottom; Button bounce; Button flash; Button rotateLeft; Button rotateRight; SeekBar seekBarSpeed; int seekSpeedProgress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); loadAnimations(); loadUI(); } private void loadUI() { imageView = (ImageView) findViewById(R.id.imageView); textStatus = (TextView) findViewById(R.id.textView); btnFadeIn = (Button) findViewById(R.id.btnFadeIn); btnFadeOut = (Button) findViewById(R.id.btnFadeOut); btnFadeInOut = (Button) findViewById(R.id.btnInOut); zoomIn = (Button) findViewById(R.id.btnZoomIn); zoomOut = (Button) findViewById(R.id.btnZoomOut); leftRight = (Button) findViewById(R.id.btnLeftRight); rightLeft = (Button) findViewById(R.id.btnRightLeft); topBottom = (Button) findViewById(R.id.btnTopBot); bounce = (Button) findViewById(R.id.btnBounce); flash = (Button) findViewById(R.id.btnFlash); rotateLeft = (Button) findViewById(R.id.btnRotateLeft); rotateRight = (Button) findViewById(R.id.btnRotateRight); btnFadeIn.setOnClickListener(this); btnFadeOut.setOnClickListener(this); btnFadeInOut.setOnClickListener(this); zoomIn.setOnClickListener(this); zoomOut.setOnClickListener(this); leftRight.setOnClickListener(this); rightLeft.setOnClickListener(this); topBottom.setOnClickListener(this); bounce.setOnClickListener(this); flash.setOnClickListener(this); rotateLeft.setOnClickListener(this); rotateRight.setOnClickListener(this); seekBarSpeed = (SeekBar) findViewById(R.id.seekBarSpeed); textSeekerSpeed = (TextView) findViewById(R.id.textSeekerSpeed); seekBarSpeed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { seekSpeedProgress = progress; textSeekerSpeed.setText("" + seekSpeedProgress + " of " + seekBarSpeed.getMax()); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } private void loadAnimations() { animFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in); animFadeIn.setAnimationListener(this); animFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out); animFadeInOut = AnimationUtils.loadAnimation(this, R.anim.fade_in_out); animZoomIn = AnimationUtils.loadAnimation(this, R.anim.zoom_in); animZoomOut = AnimationUtils.loadAnimation(this, R.anim.zoom_out); animLeftRight = AnimationUtils.loadAnimation(this, R.anim.left_right); animRightLeft = AnimationUtils.loadAnimation(this, R.anim.right_left); animTopBottom = AnimationUtils.loadAnimation(this, R.anim.top_bot); animBounce = AnimationUtils.loadAnimation(this, R.anim.bounce); animFlash = AnimationUtils.loadAnimation(this, R.anim.flash); animRotateLeft = AnimationUtils.loadAnimation(this, R.anim.rotate_left); animRotateRight = AnimationUtils.loadAnimation(this, R.anim.rotate_right); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnFadeIn: animFadeIn.setDuration(seekSpeedProgress); animFadeIn.setAnimationListener(this); imageView.startAnimation(animFadeIn); break; case R.id.btnFadeOut: animFadeOut.setDuration(seekSpeedProgress); animFadeOut.setAnimationListener(this); imageView.startAnimation(animFadeOut); break; case R.id.btnInOut: animFadeInOut.setDuration(seekSpeedProgress); animFadeInOut.setAnimationListener(this); imageView.startAnimation(animFadeInOut); break; case R.id.btnZoomIn: animZoomIn.setDuration(seekSpeedProgress); animZoomIn.setAnimationListener(this); imageView.startAnimation(animZoomIn); break; case R.id.btnZoomOut: animZoomOut.setDuration(seekSpeedProgress); animZoomOut.setAnimationListener(this); imageView.startAnimation(animZoomOut); break; case R.id.btnLeftRight: animLeftRight.setDuration(seekSpeedProgress); animLeftRight.setAnimationListener(this); imageView.startAnimation(animLeftRight); break; case R.id.btnRightLeft: animRightLeft.setDuration(seekSpeedProgress); animRightLeft.setAnimationListener(this); imageView.startAnimation(animRightLeft); break; case R.id.btnTopBot: animTopBottom.setDuration(seekSpeedProgress); animTopBottom.setAnimationListener(this); imageView.startAnimation(animTopBottom); break; case R.id.btnBounce: /* Divide seekSpeedProgress by 10 because with the seekbar having a max value of 5000 it will make the animations range between almost instant and half a second 5000 / 10 = 500 milliseconds */ animBounce.setDuration(seekSpeedProgress / 10); animBounce.setAnimationListener(this); imageView.startAnimation(animBounce); break; case R.id.btnFlash: animFlash.setDuration(seekSpeedProgress / 10); animFlash.setAnimationListener(this); imageView.startAnimation(animFlash); break; case R.id.btnRotateLeft: animRotateLeft.setDuration(seekSpeedProgress); animRotateLeft.setAnimationListener(this); imageView.startAnimation(animRotateLeft); break; case R.id.btnRotateRight: animRotateRight.setDuration(seekSpeedProgress); animRotateRight.setAnimationListener(this); imageView.startAnimation(animRotateRight); break; } } @Override public void onAnimationStart(Animation animation) { textStatus.setText("RUNNING"); } @Override public void onAnimationEnd(Animation animation) { textStatus.setText("STOPPED"); } @Override public void onAnimationRepeat(Animation animation) { textStatus.setText("REPEATING"); } }
mit
paine1690/cdp4j
src/main/java/io/webfolder/cdp/command/Tethering.java
1682
/** * The MIT License * Copyright © 2017 WebFolder OÜ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.webfolder.cdp.command; import io.webfolder.cdp.annotation.Domain; import io.webfolder.cdp.annotation.Experimental; /** * The Tethering domain defines methods and events for browser port binding */ @Experimental @Domain("Tethering") public interface Tethering { /** * Request browser port binding. * * @param port Port number to bind. */ void bind(Integer port); /** * Request browser port unbinding. * * @param port Port number to unbind. */ void unbind(Integer port); }
mit
supagit/SteamGifts
core/src/main/java/net/mabako/steamgifts/tasks/LoadGiveawayListTask.java
4706
package net.mabako.steamgifts.tasks; import android.os.AsyncTask; import android.text.TextUtils; import android.util.Log; import net.mabako.Constants; import net.mabako.steamgifts.data.Giveaway; import net.mabako.steamgifts.data.Rating; import net.mabako.steamgifts.fragments.GiveawayListFragment; import net.mabako.steamgifts.persistentdata.FilterData; import net.mabako.steamgifts.persistentdata.SavedGameInfo; import net.mabako.steamgifts.persistentdata.SavedRatings; import net.mabako.steamgifts.persistentdata.SteamGiftsUserData; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; public class LoadGiveawayListTask extends AsyncTask<Void, Void, List<Giveaway>> { private static final String TAG = LoadGiveawayListTask.class.getSimpleName(); private final GiveawayListFragment fragment; private final int page; private final GiveawayListFragment.Type type; private final String searchQuery; private final boolean showPinnedGiveaways; private String foundXsrfToken = null; private final SavedGameInfo savedGameInfo; public LoadGiveawayListTask(GiveawayListFragment activity, int page, GiveawayListFragment.Type type, String searchQuery, boolean showPinnedGiveaways) { this.fragment = activity; savedGameInfo = new SavedGameInfo(activity.getContext()); this.page = page; this.type = type; this.searchQuery = searchQuery; this.showPinnedGiveaways = showPinnedGiveaways && type == GiveawayListFragment.Type.ALL && TextUtils.isEmpty(searchQuery); } @Override protected List<Giveaway> doInBackground(Void... params) { Log.d(TAG, "Fetching giveaways for page " + page); try { // Fetch the Giveaway page Connection jsoup = Jsoup.connect("https://www.steamgifts.com/giveaways/search") .userAgent(Constants.JSOUP_USER_AGENT) .timeout(Constants.JSOUP_TIMEOUT); jsoup.data("page", Integer.toString(page)); if (searchQuery != null) jsoup.data("q", searchQuery); FilterData filterData = FilterData.getCurrent(fragment.getContext()); if (!filterData.isEntriesPerCopy()) { addFilterParameter(jsoup, "entry_max", filterData.getMaxEntries()); addFilterParameter(jsoup, "entry_min", filterData.getMinEntries()); } if (!filterData.isRestrictLevelOnlyOnPublicGiveaways()) { addFilterParameter(jsoup, "level_min", filterData.getMinLevel()); addFilterParameter(jsoup, "level_max", filterData.getMaxLevel()); } addFilterParameter(jsoup, "region_restricted", filterData.isRegionRestrictedOnly()); addFilterParameter(jsoup, "copy_min", filterData.getMinCopies()); addFilterParameter(jsoup, "copy_max", filterData.getMaxCopies()); if (type != GiveawayListFragment.Type.ALL) jsoup.data("type", type.name().toLowerCase(Locale.ENGLISH)); if (SteamGiftsUserData.getCurrent(fragment.getContext()).isLoggedIn()) jsoup.cookie("PHPSESSID", SteamGiftsUserData.getCurrent(fragment.getContext()).getSessionId()); Document document = jsoup.get(); SteamGiftsUserData.extract(fragment.getContext(), document); // Fetch the xsrf token Element xsrfToken = document.select("input[name=xsrf_token]").first(); if (xsrfToken != null) foundXsrfToken = xsrfToken.attr("value"); // Do away with pinned giveaways. if (!showPinnedGiveaways) document.select(".pinned-giveaways__outer-wrap").html(""); // Parse all rows of giveaways return Utils.loadGiveawaysFromList(document, savedGameInfo); } catch (Exception e) { Log.e(TAG, "Error fetching URL", e); return null; } } @Override protected void onPostExecute(List<Giveaway> result) { super.onPostExecute(result); fragment.addItems(result, page == 1, foundXsrfToken); savedGameInfo.close(); } private void addFilterParameter(Connection jsoup, String parameterName, int value) { if (value >= 0) jsoup.data(parameterName, String.valueOf(value)); } private void addFilterParameter(Connection jsoup, String parameterName, boolean value) { if (value) jsoup.data(parameterName, "true"); } }
mit
ivanshen/Who-Are-You-Really
org/jfree/base/BootableProjectInfo.java
1922
package org.jfree.base; import java.util.ArrayList; public class BootableProjectInfo extends BasicProjectInfo { private boolean autoBoot; private String bootClass; public BootableProjectInfo() { this.autoBoot = true; } public BootableProjectInfo(String name, String version, String licence, String info) { this(); setName(name); setVersion(version); setLicenceName(licence); setInfo(info); } public BootableProjectInfo(String name, String version, String info, String copyright, String licenceName) { this(); setName(name); setVersion(version); setLicenceName(licenceName); setInfo(info); setCopyright(copyright); } public BootableProjectInfo[] getDependencies() { ArrayList dependencies = new ArrayList(); Library[] libraries = getLibraries(); for (Library lib : libraries) { if (lib instanceof BootableProjectInfo) { dependencies.add(lib); } } Library[] optionalLibraries = getOptionalLibraries(); for (Library lib2 : optionalLibraries) { if (lib2 instanceof BootableProjectInfo) { dependencies.add(lib2); } } return (BootableProjectInfo[]) dependencies.toArray(new BootableProjectInfo[dependencies.size()]); } public void addDependency(BootableProjectInfo projectInfo) { if (projectInfo == null) { throw new NullPointerException(); } addLibrary(projectInfo); } public String getBootClass() { return this.bootClass; } public void setBootClass(String bootClass) { this.bootClass = bootClass; } public boolean isAutoBoot() { return this.autoBoot; } public void setAutoBoot(boolean autoBoot) { this.autoBoot = autoBoot; } }
mit
ricky3350/Terrain-TD
src/terraintd/types/TowerUpgrade.java
1596
package terraintd.types; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import terraintd.object.Tower; public class TowerUpgrade extends Upgrade { public final double range; public final boolean rotate; public final ImageType image; public final ProjectileUpgrade[] projectiles; protected TowerUpgrade(String id, Mod mod, int cost, int sellCost, ImageType icon, double range, boolean rotate, ImageType image, ProjectileUpgrade[] projectiles) { super(id, mod, cost, sellCost, icon); this.range = range; this.rotate = rotate; this.image = image; this.projectiles = projectiles; } public TowerType upgradeTower(Tower tower) { TowerType type = tower.getType(); List<TowerUpgrade> remainingUpgrades = new ArrayList<>(); for (TowerUpgrade u : type.upgrades) { if (u != this) remainingUpgrades.add(u); } List<ProjectileUpgrade> projectileUpgrades = new ArrayList<>(); for (TowerUpgrade u : tower.getAppliedUpgrades()) { projectileUpgrades.addAll(Arrays.asList(u.projectiles)); } projectileUpgrades.addAll(Arrays.asList(this.projectiles)); return new TowerType(type.mod, type.id, type.cost + cost, type.sellCost + sellCost, type.width, type.height, type.terrain, type.onHill, type.range + range, rotate, image == ImageType.BLANK ? type.image : image, type.icon, ProjectileUpgrade.upgrade(tower.baseType.projectiles, projectileUpgrades.toArray(new ProjectileUpgrade[projectileUpgrades.size()])), remainingUpgrades.toArray(new TowerUpgrade[remainingUpgrades.size()])); } }
mit
fouady/DocuTranslator
PersonalTranslator/src/com/droidprojects/personaltranslator/controllers/ConnectionHandler.java
7292
package com.droidprojects.personaltranslator.controllers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.droidprojects.personaltranslator.constants.Constants; import android.util.Base64; /** * This class works as an abstraction between the Android client and server(s). * It handles the http connection, query creation and parsing of the results. * @author Fouad */ public class ConnectionHandler { private HttpURLConnection mConnection; // Connection instance private boolean mTerminateConnection=false; // Flag to terminate connection /** * Sets up data to be sent to server for translation and parses the received data * @param text Text on which the OCR should be run * @param fromLanguage * @param toLanguage * @return The translated text * @throws IOException */ public String runRemoteTranslator( String text, String fromLanguage, String toLanguage) throws IOException { // Bing translator recognizes carriage return text = text.replace("\n", "\r\n"); // Set up name value pairs ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("From", "'"+fromLanguage+"'")); params.add(new BasicNameValuePair("To", "'"+toLanguage+"'")); params.add(new BasicNameValuePair("Text", "'"+text+"'")); // Set the data as part of URL String url = Constants.SERVER_URL_TRANSLATOR_BING+"?"+getQuery(params); // Set authorization credentials String auth = Base64.encodeToString(("ignored:"+Constants.SERVER_PRIMARY_KEY_BING) .getBytes(), Base64.DEFAULT); ArrayList<NameValuePair> requestProperties = new ArrayList<NameValuePair>(); requestProperties.add(new BasicNameValuePair("Authorization", "Basic "+auth)); String result = sendReceive(url, null, requestProperties); // Extract the required data from the returned string String translation=null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(result))); translation = doc.getElementsByTagName("d:Text").item(0).getTextContent(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e1) { e1.printStackTrace(); } return translation; } /** * * @param encodedImage Base64 encoded image for OCR extraction * @param language Language of the text in image * @return The extracted text string * @throws IOException */ public String runRemoteOCR(String encodedImage, String language) throws IOException{ // Set up data to be sent ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("image", encodedImage)); params.add(new BasicNameValuePair("language", language)); return sendReceive(Constants.SERVER_URL_OCR, params, null); } /** * Establishes connection, sets up parameters and receives data * @param serverURL * @param params The get/post parameters * @param requestProperties * @return Response from server * @throws IOException */ public String sendReceive( String serverURL, List<NameValuePair> params, List<NameValuePair> requestProperties) throws IOException { InputStream is = null; try { URL url = new URL(serverURL); mConnection = (HttpURLConnection) url.openConnection(); mConnection.setReadTimeout(50000 /* milliseconds */); mConnection.setConnectTimeout(40000 /* milliseconds */); mConnection.setRequestMethod("POST"); mConnection.setDoInput(true); mConnection.setDoOutput(true); // Set authorization and other properties, if they exist if (requestProperties!=null) for (NameValuePair nvp : requestProperties){ mConnection.setRequestProperty(nvp.getName(), nvp.getValue()); } // Set post parameters, if they exist if (params!=null){ OutputStream os = mConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(params)); writer.flush(); writer.close(); os.close(); } // Just before establishing connection, see if there is a request from the UI to // terminate connection. If so, return null. if(mTerminateConnection) return null; // Starts the query mConnection.connect(); int response = mConnection.getResponseCode(); is = mConnection.getInputStream(); // Convert the InputStream into a string String contentAsString = convertStreamToString(is); return contentAsString; // Makes sure that the InputStream is closed after the app is // finished using it. } finally { if (is != null) { is.close(); } } } /** * Reads and inputstream and converts it to string * @param stream * @return * @throws IOException * @throws UnsupportedEncodingException */ private String convertStreamToString(InputStream stream) throws IOException, UnsupportedEncodingException { BufferedReader reader = new BufferedReader( new InputStreamReader(stream,"UTF-8")); StringBuilder out = new StringBuilder(); String buffer; while ((buffer=reader.readLine()) != null){ out.append(buffer+"\n"); } reader.close(); return out.toString(); } /** * Changes the name-value pairs to a get/post query * @param params The nvps * @return The query string * @throws UnsupportedEncodingException */ private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (NameValuePair pair : params) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(pair.getName(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(pair.getValue(), "UTF-8")); } return result.toString(); } /** * This function is called by the UI/Views in order to request the connection to terminate */ public void terminateConnection(){ mTerminateConnection=true; if (mConnection!=null){ mConnection.disconnect(); } } }
mit
uael/jds
src/main/java/org/uael/jds/Reversed.java
767
package org.uael.jds; import java.util.Iterator; /** * The type Reversed. * @param <T> the type parameter */ public class Reversed<T> implements Iterable<T> { private DoubleIterable<T> iterable; /** * Instantiates a new Reversed. * @param iterable the iterable */ public Reversed(DoubleIterable<T> iterable) { this.iterable = iterable; } @Override public Iterator<T> iterator() { final DoubleIterator<T> it = iterable.iterator(); return new Iterator<T>() { @Override public boolean hasNext() { return it.hasPrevious(); } @Override public T next() { return it.previous(); } }; } }
mit
andyhedges/jmimeinfo
src/main/java/net/hedges/mimeinfo/globs/GlobsFile.java
1758
/* * jmimeinfo is an implementation of shared mime info specification * The MIT License (MIT) * * Copyright (c) 2014 Andy Hedges * * 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 net.hedges.mimeinfo.globs; import java.io.File; import java.util.ArrayList; import java.util.List; /** * * @author Andy Hedges * */ public final class GlobsFile { private List<Glob> globs = new ArrayList<Glob>(); protected GlobsFile() { } public List<Glob> getGlobs() { return globs; } public String match(final File file) { for (Glob glob : globs) { if (glob.match(file)) { return glob.getMimeType(); } } return null; } }
mit
aalto-trafficsense/regular-routes-client
regularroutesfunfprobes/src/main/java/fi/aalto/trafficsense/funfprobes/activityrecognition/ActivityFilterProbe.java
6782
/** * * TODO: add MIT license text here * */ package fi.aalto.trafficsense.funfprobes.activityrecognition; import android.content.Intent; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import com.google.gson.IJsonObject; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.regex.Matcher; import java.util.regex.Pattern; import edu.mit.media.funf.config.Configurable; import edu.mit.media.funf.probe.Probe; import edu.mit.media.funf.probe.Probe.RequiredProbes; import timber.log.Timber; /** * The purpose of this probe is to detect when person is moving (by analyzing data from ActivityRecognition) * and if so send activity to all listeners. Other probes (such as FusedLocationProbe, AccelerometerSensor, and OrientationSensor), * that are both data and battery intensive can then use it as their "schedule" for sensing data * * @author Kimmo Karhu */ /* Funf configuration example: { "@type": "edu.mit.media.funf.probe.builtin.AccelerometerSensorProbe", "sensorDelay": "NORMAL", "@schedule": { "duration": 10, "@type": "fi.aalto.trafficsense.funfprobes.activityrecognition.ActivityFilterProbe", } } */ // TODO: Consider integrating with ActivityRecognition. @RequiredProbes(ActivityRecognitionProbe.class) //@Schedule.DefaultSchedule(interval=60) public class ActivityFilterProbe extends Probe.Base implements Probe.ContinuousProbe { @Configurable private String startRegExp = "IN_VEHICLE|ON_BICYCLE|ON_FOOT|RUNNING|TILTING|UNKNOWN|WALKING"; @Configurable private int startThreshold = 2; @Configurable private String stopRegExp = "STILL"; @Configurable private int stopThreshold = 8; private int consecutiveCount=0; private Pattern startPattern; private Pattern stopPattern; private ActivityRecognitionListener listener; private class ActivityRecognitionListener implements DataListener { @Override public void onDataReceived(IJsonObject completeProbeUri, IJsonObject activityRecognitionData) { String activity=null; Matcher m; JsonElement j = activityRecognitionData.get("activities"); if(j!=null) { if(j.isJsonArray()) { JsonArray ja = j.getAsJsonArray(); int confidence = 0; for(JsonElement je : ja){ JsonObject jo = je.getAsJsonObject(); int newConfidence = jo.get("confidence").getAsInt(); if(newConfidence > confidence) { activity = jo.get("activityType").getAsString(); confidence = newConfidence; } } Timber.d("Activity with highest confidence: " + activity + ":" + confidence + "%"); } } // return if activity cannot be parsed if(activity == null) { Timber.w("ActivityRecognitionListener:onDataReceived activity type parsing failed"); return; } switch (getState()) { case RUNNING: // if enough consecutive matches of "stop" activities then stop otherwise emit activity to other probes using this probe as scheduler m = stopPattern.matcher(activity); if(m.matches()) consecutiveCount++; else consecutiveCount = 0; if(consecutiveCount >= stopThreshold) { Timber.i("Going to sleep..."); // TODO: Figure out how to import InternalBroadcasts here notifyProbeResults("GOING_TO_SLEEP"); consecutiveCount = 0; stop(); } else { Timber.i("Staying awake..."); sendData(activityRecognitionData.getAsJsonObject()); } break; case ENABLED: // if enough consecutive matches of "start" activities then start and emit activity to other probes using this probe as scheduler, otherwise do nothing m = startPattern.matcher(activity); if(m.matches()) consecutiveCount++; else consecutiveCount = 0; if(consecutiveCount >= startThreshold) { consecutiveCount = 0; Timber.i("Waking up..."); start(); notifyProbeResults("WAKING_UP"); sendData(activityRecognitionData.getAsJsonObject()); } break; } } @Override public void onDataCompleted(IJsonObject completeProbeUri, JsonElement checkpoint) { // TODO Auto-generated method stub } } @Override protected void onStart() { super.onStart(); Timber.i("Activity Recognition Filter Probe started"); } @Override protected void onStop() { super.onStop(); Timber.i("Activity Recognition Filter Probe stopped"); } @Override protected void onEnable() { super.onEnable(); startPattern = Pattern.compile(startRegExp); stopPattern = Pattern.compile(stopRegExp); listener = new ActivityRecognitionListener(); getGson().fromJson("{\"@type\":\"fi.aalto.trafficsense.funfprobes.activityrecognition.ActivityRecognitionProbe\"}", ActivityRecognitionProbe.class).registerPassiveListener(listener); } @Override protected void onDisable() { super.onDisable(); getGson().fromJson("{\"@type\":\"fi.aalto.trafficsense.funfprobes.activityrecognition.ActivityRecognitionProbe\"}", ActivityRecognitionProbe.class).unregisterPassiveListener(listener); } private void notifyProbeResults(String messageType) { notifyProbeResults(messageType, null); } private void notifyProbeResults(String messageType, Bundle args) { LocalBroadcastManager mLocalBroadcastManager = LocalBroadcastManager.getInstance(getContext()); if (mLocalBroadcastManager != null) { Intent intent = new Intent(messageType); if (args != null) { intent.putExtras(args); } mLocalBroadcastManager.sendBroadcast(intent); Timber.i("ActivityFilterProbe: Sending "+messageType); } } }
mit
NoYouShutup/CryptMeme
CryptMeme/src/java/net/i2p/client/RequestLeaseSetMessageHandler.java
7280
package net.i2p.client; /* * free (adj.): unencumbered; not under the control of others * Written by jrandom in 2003 and released into the public domain * with no warranty of any kind, either expressed or implied. * It probably won't make your computer catch on fire, or eat * your children, but it might. Use at your own risk. * */ import java.security.GeneralSecurityException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import net.i2p.I2PAppContext; import net.i2p.crypto.KeyGenerator; import net.i2p.crypto.SigType; import net.i2p.data.DataFormatException; import net.i2p.data.DataHelper; import net.i2p.data.Destination; import net.i2p.data.Lease; import net.i2p.data.LeaseSet; import net.i2p.data.PrivateKey; import net.i2p.data.PublicKey; import net.i2p.data.SessionKey; import net.i2p.data.SigningPrivateKey; import net.i2p.data.SigningPublicKey; import net.i2p.data.SimpleDataStructure; import net.i2p.data.i2cp.I2CPMessage; import net.i2p.data.i2cp.RequestLeaseSetMessage; import net.i2p.util.Log; /** * Handle I2CP RequestLeaseSetMessage from the router by granting all leases, * using the specified expiration time for each lease. * * @author jrandom */ class RequestLeaseSetMessageHandler extends HandlerImpl { private final Map<Destination, LeaseInfo> _existingLeaseSets; public RequestLeaseSetMessageHandler(I2PAppContext context) { this(context, RequestLeaseSetMessage.MESSAGE_TYPE); } /** * For extension * @since 0.9.7 */ protected RequestLeaseSetMessageHandler(I2PAppContext context, int messageType) { super(context, messageType); // not clear why there would ever be more than one _existingLeaseSets = new ConcurrentHashMap<Destination, LeaseInfo>(4); } public void handleMessage(I2CPMessage message, I2PSessionImpl session) { if (_log.shouldLog(Log.DEBUG)) _log.debug("Handle message " + message); RequestLeaseSetMessage msg = (RequestLeaseSetMessage) message; LeaseSet leaseSet = new LeaseSet(); for (int i = 0; i < msg.getEndpoints(); i++) { Lease lease = new Lease(); lease.setGateway(msg.getRouter(i)); lease.setTunnelId(msg.getTunnelId(i)); lease.setEndDate(msg.getEndDate()); //lease.setStartDate(msg.getStartDate()); leaseSet.addLease(lease); } signLeaseSet(leaseSet, session); } /** * Finish creating and signing the new LeaseSet * @since 0.9.7 */ protected void signLeaseSet(LeaseSet leaseSet, I2PSessionImpl session) { // also, if this session is connected to multiple routers, include other leases here leaseSet.setDestination(session.getMyDestination()); // reuse the old keys for the client LeaseInfo li = _existingLeaseSets.get(session.getMyDestination()); if (li == null) { li = new LeaseInfo(session.getMyDestination()); _existingLeaseSets.put(session.getMyDestination(), li); if (_log.shouldLog(Log.DEBUG)) _log.debug("Creating new leaseInfo keys for " + session.getMyDestination().calculateHash().toBase64()); } else { if (_log.shouldLog(Log.DEBUG)) _log.debug("Caching the old leaseInfo keys for " + session.getMyDestination().calculateHash().toBase64()); } leaseSet.setEncryptionKey(li.getPublicKey()); leaseSet.setSigningKey(li.getSigningPublicKey()); boolean encrypt = Boolean.parseBoolean(session.getOptions().getProperty("i2cp.encryptLeaseSet")); String sk = session.getOptions().getProperty("i2cp.leaseSetKey"); if (encrypt && sk != null) { SessionKey key = new SessionKey(); try { key.fromBase64(sk); leaseSet.encrypt(key); _context.keyRing().put(session.getMyDestination().calculateHash(), key); } catch (DataFormatException dfe) { _log.error("Bad leaseset key: " + sk); } } try { leaseSet.sign(session.getPrivateKey()); // Workaround for unparsable serialized signing private key for revocation // Send him a dummy DSA_SHA1 private key since it's unused anyway // See CreateLeaseSetMessage.doReadMessage() SigningPrivateKey spk = li.getSigningPrivateKey(); if (!_context.isRouterContext() && spk.getType() != SigType.DSA_SHA1) { byte[] dummy = new byte[SigningPrivateKey.KEYSIZE_BYTES]; _context.random().nextBytes(dummy); spk = new SigningPrivateKey(dummy); } session.getProducer().createLeaseSet(session, leaseSet, li.getSigningPrivateKey(), li.getPrivateKey()); session.setLeaseSet(leaseSet); } catch (DataFormatException dfe) { session.propogateError("Error signing the leaseSet", dfe); } catch (I2PSessionException ise) { session.propogateError("Error sending the signed leaseSet", ise); } } private static class LeaseInfo { private final PublicKey _pubKey; private final PrivateKey _privKey; private final SigningPublicKey _signingPubKey; private final SigningPrivateKey _signingPrivKey; public LeaseInfo(Destination dest) { Object encKeys[] = KeyGenerator.getInstance().generatePKIKeypair(); // must be same type as the Destination's signing key SimpleDataStructure signKeys[]; try { signKeys = KeyGenerator.getInstance().generateSigningKeys(dest.getSigningPublicKey().getType()); } catch (GeneralSecurityException gse) { throw new IllegalStateException(gse); } _pubKey = (PublicKey) encKeys[0]; _privKey = (PrivateKey) encKeys[1]; _signingPubKey = (SigningPublicKey) signKeys[0]; _signingPrivKey = (SigningPrivateKey) signKeys[1]; } public PublicKey getPublicKey() { return _pubKey; } public PrivateKey getPrivateKey() { return _privKey; } public SigningPublicKey getSigningPublicKey() { return _signingPubKey; } public SigningPrivateKey getSigningPrivateKey() { return _signingPrivKey; } @Override public int hashCode() { return DataHelper.hashCode(_pubKey) + 7 * DataHelper.hashCode(_privKey) + 7 * 7 * DataHelper.hashCode(_signingPubKey) + 7 * 7 * 7 * DataHelper.hashCode(_signingPrivKey); } @Override public boolean equals(Object obj) { if ((obj == null) || !(obj instanceof LeaseInfo)) return false; LeaseInfo li = (LeaseInfo) obj; return DataHelper.eq(_pubKey, li.getPublicKey()) && DataHelper.eq(_privKey, li.getPrivateKey()) && DataHelper.eq(_signingPubKey, li.getSigningPublicKey()) && DataHelper.eq(_signingPrivKey, li.getSigningPrivateKey()); } } }
mit
alfib/RBOSS
src/main/java/com/mycompany/rboss/domain/CreditCard.java
1869
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.rboss.domain; import javax.persistence.Embeddable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.validator.constraints.CreditCardNumber; /** * * @author ib */ @Entity public class CreditCard { private String issuer; //@CreditCardNumber private String creditCardNumber; private String expirationDate; private String securityCode; @Id @GeneratedValue private int id; public CreditCard() { } public CreditCard(String issuer, String creditCardNumber, String expirationDate , String securityCode) { this.issuer = issuer; this.creditCardNumber = creditCardNumber; this.expirationDate = expirationDate; this.securityCode = securityCode; } public String getSecurityCode() { return securityCode; } public void setSecurityCode(String securityCode) { this.securityCode = securityCode; } public String getIssuer() { return issuer; } public void setIssuer(String issuer) { this.issuer = issuer; } public String getCreditCardNumber() { return creditCardNumber; } public void setCreditCardNumber(String creditCardNumber) { this.creditCardNumber = creditCardNumber; } public String getExpirationDate() { return expirationDate; } public void setExpirationDate(String expirationDate) { this.expirationDate = expirationDate; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
mit
bing-ads-sdk/BingAds-Java-SDK
src/test/java/com/microsoft/bingads/v12/api/test/entities/ads/dynamicSearch/BulkDynamicSearchAdTest.java
2146
package com.microsoft.bingads.v12.api.test.entities.ads.dynamicSearch; import java.util.Map; import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer; import com.microsoft.bingads.internal.functionalinterfaces.Function; import com.microsoft.bingads.internal.functionalinterfaces.Supplier; import com.microsoft.bingads.v12.api.test.entities.BulkEntityTest; import com.microsoft.bingads.v12.bulk.entities.BulkDynamicSearchAd; import com.microsoft.bingads.v12.campaignmanagement.DynamicSearchAd; public abstract class BulkDynamicSearchAdTest extends BulkEntityTest<BulkDynamicSearchAd> { @Override protected void onEntityCreation(BulkDynamicSearchAd entity) { entity.setDynamicSearchAd(new DynamicSearchAd()); } @Override protected <TProperty> void testWriteProperty(String header, String expectedRowValue, TProperty propertyValue, BiConsumer<BulkDynamicSearchAd, TProperty> setFunc) { this.<TProperty>testWriteProperty(header, expectedRowValue, propertyValue, setFunc, new Supplier<BulkDynamicSearchAd>() { @Override public BulkDynamicSearchAd get() { return new BulkDynamicSearchAd(); } }); } @Override protected <TProperty> void testReadProperty(String header, String input, TProperty expectedResult, Function<BulkDynamicSearchAd, TProperty> actualValueFunc) { this.<TProperty>testReadProperty(header, input, expectedResult, actualValueFunc, new Supplier<BulkDynamicSearchAd>() { @Override public BulkDynamicSearchAd get() { return new BulkDynamicSearchAd(); } }); } @Override protected <TProperty> void testReadProperty(Map<String, String> rowValues, TProperty expectedResult, Function<BulkDynamicSearchAd, TProperty> actualValueFunc) { this.<TProperty>testReadProperty(rowValues, expectedResult, actualValueFunc, new Supplier<BulkDynamicSearchAd>() { @Override public BulkDynamicSearchAd get() { return new BulkDynamicSearchAd(); } }); } }
mit
arapaka/algorithms-datastructures
algorithms/src/main/java/Facebook/WordSearch.java
4082
package Facebook; import java.util.LinkedList; import java.util.Queue; /** * Created by archithrapaka on 4/29/17. */ public class WordSearch { public static boolean search(char[][] grid, String s) { String sub = ""; char[] w = s.toCharArray(); boolean[][] visited = new boolean[grid.length][grid[0].length]; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == s.charAt(0)) { if (dfs(grid, i, j, sub, s, visited, w, 0)) { return true; } ; } } } return false; } public static boolean searchBfs(char[][] grid, String s) { String sub = ""; char[] w = s.toCharArray(); boolean[][] visited = new boolean[grid.length][grid[0].length]; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == s.charAt(0)) { if (bfs(grid, i, j, sub, s, w, visited, 1)) { return true; } } } } return false; } static class Cordinate { int x; int y; public Cordinate(int x, int y) { this.x = x; this.y = y; } } private static boolean bfs(char[][] grid, int i, int j, String sub, String s, char[] w, boolean[][] visited, int index) { Queue<Cordinate> queue = new LinkedList<>(); queue.add(new Cordinate(i, j)); while (!queue.isEmpty()) { if (index == s.length()) { System.out.print(sub); return true; } Cordinate current = queue.poll(); sub += "(" + current.x + "," + current.y + ")"; visited[current.x][current.y] = true; if (isValid(grid, current.x, current.y + 1, visited, w, index)) { queue.add(new Cordinate(current.x, current.y + 1)); index++; } if (isValid(grid, current.x + 1, current.y, visited, w, index)) { queue.add(new Cordinate(current.x + 1, current.y)); index++; } if (isValid(grid, current.x, current.y - 1, visited, w, index)) { queue.add(new Cordinate(current.x, current.y - 1)); index++; } if (isValid(grid, current.x - 1, current.y, visited, w, index)) { queue.add(new Cordinate(current.x - 1, current.y)); index++; } } return false; } private static boolean dfs(char[][] grid, int i, int j, String sub, String target, boolean[][] visited, char[] w, int index) { if (index == target.length()) { System.out.print(sub); return true; } if (!isValid(grid, i, j, visited, w, index)) { return false; } sub += "(" + i + "," + j + ")"; visited[i][j] = true; boolean exist = dfs(grid, i, j + 1, sub, target, visited, w, index + 1) || dfs(grid, i + 1, j, sub, target, visited, w, index + 1) || dfs(grid, i, j - 1, sub, target, visited, w, index + 1) || dfs(grid, i - 1, j, sub, target, visited, w, index + 1); return exist; } private static boolean isValid(char[][] grid, int i, int j, boolean[][] visited, char[] w, int index) { return (i >= 0 && i < grid.length) && (j >= 0 && j < grid[0].length) && !visited[i][j] && index < w.length && w[index] == grid[i][j]; } public static void main(String[] args) { String s = "ABFD"; char[][] a = { {'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'} }; //System.out.print(search(a,s)); System.out.print(searchBfs(a, s)); } }
mit
onixred/golos4j
src/main/java/ru/maksimov/andrey/golos4j/dto/operation/CommentDto.java
6027
package ru.maksimov.andrey.golos4j.dto.operation; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import ru.maksimov.andrey.golos4j.deserializes.Object2StringDeserializer; import ru.maksimov.andrey.golos4j.exception.BusinessException; import ru.maksimov.andrey.golos4j.util.Util; /** * DTO for operation comment * * @author <a href="mailto:onixbed@gmail.com">amaksimov</a> */ public class CommentDto extends BaseOperation { private static final long serialVersionUID = -4822924304260583578L; private static final OperationType TYPE = OperationType.COMMENT_OPERATION; public static String TAGS_KEY = "tags"; public static String IMAGE_KEY = "image"; public static String LINKS_KEY = "links"; // если этот параметр пустой то это считается // созданием новой публикации @JsonProperty("parent_author") private String parentAuthor; @JsonProperty("parent_permlink") private String parentPermlink; @JsonProperty("author") private String author; @JsonProperty("permlink") private String permlink; @JsonProperty("title") private String title; @JsonProperty("body") private String body; private String jsonMetadata; public CommentDto() { super(TYPE); } /** * Get author name of the parent article or comment. Null if new article. * * @return get parent author */ public String getParentAuthor() { return parentAuthor; } public void setParentAuthor(String parentAuthor) { this.parentAuthor = parentAuthor; } /** * Get of the parent comment or article. If this article is first category. * If this comment is url of the article or comment. * * @return get parent permlink */ public String getParentPermlink() { return parentPermlink; } public void setParentPermlink(String parentPermlink) { this.parentPermlink = parentPermlink; } /** * Get author comment or article. * * @return get author */ public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } /** * Get the url of the article or comment. If this first comment is add * "re-PARENT-AUTHOR-NAME-ARTICLE". If this last comment is add * "re-AUTHOR-re-PATENT-AUTHOR-PATENT-PERMLINK-DATE" * * @return get permlink */ public String getPermlink() { return permlink; } public void setPermlink(String permlink) { this.permlink = permlink; } /** * Get the title of the article. Null if comment. * * @return get title */ public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } /** * Get the body of the article. Null if comment. (html/markdown) * * @return get body */ public String getBody() { return body; } public void setBody(String body) { this.body = body; } @JsonProperty("json_metadata") @JsonDeserialize(using = Object2StringDeserializer.class) public String getJsonMetadata() { return jsonMetadata; } public void setJsonMetadata(String jsonMetadata) { this.jsonMetadata = jsonMetadata; } /** * Set map where key {@link #TAGS_KEY}, {@link #IMAGE_KEY}, * {@link #LINKS_KEY} and value is tags, images and гкд links * * @param jsonMetadata * map is json metadata * @throws JsonProcessingException * исключение преобразования */ public void setJsonMetadata(Map<String, List<String>> jsonMetadata) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); String jsonInString; try { jsonInString = mapper.writeValueAsString(jsonMetadata); } catch (JsonProcessingException e) { jsonInString = " "; } this.jsonMetadata = jsonInString; } @Override public List<Byte> toBytes() { byte typeByte = (byte) getType().ordinal(); List<Byte> typeBytes = Collections.singletonList(typeByte); List<Byte> parentAuthorBytes = Collections .<Byte> singletonList((byte) 0); List<Byte> parentPermlinkBytes = Collections .<Byte> singletonList((byte) 0); List<Byte> authorBytes = Collections.<Byte> singletonList((byte) 0); List<Byte> permlinkBytes = Collections.<Byte> singletonList((byte) 0); List<Byte> titleBytes = Collections.<Byte> singletonList((byte) 0); List<Byte> bodyBytes = Collections.<Byte> singletonList((byte) 0); List<Byte> jsonMetadataBytes = Collections .<Byte> singletonList((byte) 0); try { parentAuthorBytes = Util.stringUtf82ByteList(parentAuthor); parentPermlinkBytes = Util.stringUtf82ByteList(parentPermlink); authorBytes = Util.stringUtf82ByteList(author); permlinkBytes = Util.stringUtf82ByteList(permlink); titleBytes = Util.stringUtf82ByteList(title); bodyBytes = Util.stringUtf82ByteList(body); jsonMetadataBytes = Util.stringUtf82ByteList(jsonMetadata); } catch (BusinessException e) { // TODO Auto-generated catch block e.printStackTrace(); } List<Byte> list = new ArrayList<Byte>(); list.addAll(typeBytes); list.addAll(parentAuthorBytes); list.addAll(parentPermlinkBytes); list.addAll(authorBytes); list.addAll(permlinkBytes); list.addAll(titleBytes); list.addAll(bodyBytes); list.addAll(jsonMetadataBytes); return list; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } public static OperationType getOperationType() { return TYPE; } }
mit
TRex22/OldCodeArchive
SchoolWork/2010/IT10_2010/Doodles/MemCheck/MemCheck.java
3391
package MemCheck; import java.awt.BorderLayout; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.JButton; import javax.swing.JLabel; import java.awt.Dimension; import java.awt.GridBagLayout; import java.awt.TextArea; import java.awt.Frame; import java.awt.Window; public class MemCheck extends JFrame { private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JButton jButton = null; private JPanel jPanel = null; private TextArea textArea = null; // @jve:decl-index=0:visual-constraint="164,109" /** * This is the default constructor */ public MemCheck() { super(); initialize(); } /** * This method initializes this * * @return void */ private void initialize() { this.setSize(363, 285); this.setContentPane(getJContentPane()); this.setTitle("MemCheck by Jason Chalom"); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { jContentPane = new JPanel(); jContentPane.setLayout(new BorderLayout()); jContentPane.add(getJButton(), BorderLayout.SOUTH); jContentPane.add(getTextArea(), BorderLayout.CENTER); } return jContentPane; } /** * This method initializes textArea * * @return java.awt.TextArea */ private TextArea getTextArea() { if (textArea == null) { textArea = new TextArea(); //int repeat=0; //long tot = 0; //long free = 0; //while (repeat==0) //{ long tot = (((Runtime.getRuntime().totalMemory())/8)/1024); long free = (((Runtime.getRuntime().freeMemory())/8)/1024); //} textArea.setText(""+ "totalMemory: "+(int)tot+" MB" + "\nfreeMemory: "+(int)free+" MB" ); Runtime.getRuntime().gc(); } return textArea; } /** * This method initializes jButton * * @return javax.swing.JButton */ private JButton getJButton() { if (jButton == null) { jButton = new JButton(); jButton.setPreferredSize(new Dimension(34, 50)); jButton.setText("About "); jButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JOptionPane.showMessageDialog(null, "MemCheck By Jason Chalom" + "\nCopyRight 2010" + "\nVersion 0.1 Initial Test Version" + "\nTotal Memory Shows the total memory that Java Virtual Machine has access to" + "\nTherefore it is not exactly the amount of memory the computer has access to" + "\nBut should reflect what most high level programs could possibly use." + "\nPlease note the figures are rounded off and are an indication of buffer which" + "\ninclude page file and ram which is virtual memory in Windows" + "\nJava will try to use "+(((Runtime.getRuntime().maxMemory())/8)/1024)+" MB" + "\nA Garbage Collector included with Java Runtime is also run constantly when this program" + "\nis running.\n"); } }); } return jButton; } /** * This method initializes window * * @return java.awt.Window */ } // @jve:decl-index=0:visual-constraint="283,21"
mit
clusterpoint/java-client-api
src/com/clusterpoint/api/request/CPSListLastRetrieveFirstRequest.java
2428
package com.clusterpoint.api.request; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.clusterpoint.api.CPSRequest; import com.clusterpoint.api.CPSTerm; /** * The CPSListLastRetrieveFirstRequest class is a wrapper for the CPSRequest class for list-last, list-first, retrieve-last, and retrieve-first requests * @see com.clusterpoint.api.response.CPSListLastRetrieveFirstResponse */ public class CPSListLastRetrieveFirstRequest extends CPSRequest { /** * Constructs an instance of the CPSListLastRetrieveFirstRequest class. * @param command command name * @param offset offset * @param docs max number of docs to return * @param list map where key is xpath and value contains listing options (yes, no, snippet or highlight) * @throws Exception */ public CPSListLastRetrieveFirstRequest(String command, int offset, int docs, Map<String, String> list) throws Exception { super(command); this.setParam("offset", String.valueOf(offset)); this.setParam("docs", String.valueOf(docs)); setList(list); } /** * Constructs an instance of the CPSListLastRetrieveFirstRequest class. * @param command command name * @param offset offset * @param docs max number of docs to return * @throws Exception */ public CPSListLastRetrieveFirstRequest(String command, int offset, int docs) throws Exception { super(command); this.setParam("offset", String.valueOf(offset)); this.setParam("docs", String.valueOf(docs)); } /** * Defines which tags of the search results should be listed in the response * @param list map where key is xpath and value contains listing options (yes, no, snippet or highlight) */ public void setList(Map<String, String> list) throws Exception { String listStr = ""; Iterator<Entry<String, String>> it = list.entrySet().iterator(); while (it.hasNext()) { listStr += CPSTerm.get(it.next().getValue(), it.next().getKey()); } this.setParam("list", listStr); } /** * Set limits for documents to be returned by command * @param docs * @throws Exception */ public void setDocs(int docs) throws Exception { this.setParam("docs", String.valueOf(docs)); } /** * Set offset from beginning of results from which documents will be returned * @param offset * @throws Exception */ public void setOffset(int offset) throws Exception { this.setParam("offset", String.valueOf(offset)); } }
mit
traktion0/safenet-java-fuse
src/main/java/org/traktion0/safenet/fuse/SafenetFuse.java
2602
package org.traktion0.safenet.fuse; import co.paralleluniverse.javafs.*; import org.glassfish.jersey.client.ClientProperties; import org.traktion0.safenet.client.beans.App; import org.traktion0.safenet.client.beans.Auth; import org.traktion0.safenet.client.commands.ErrorResponseFilter; import org.traktion0.safenet.client.commands.SafenetFactory; import org.traktion0.safenet.filesystem.SafenetFileSystemProvider; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import java.net.URI; import java.nio.file.FileSystem; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; /** * Created by paul on 11/10/16. */ public class SafenetFuse { private static final String LAUNCHER_URL = "http://localhost:8100"; private static final String APP_NAME = "Safenet FUSE"; private static final String APP_ID = "safenetfuse"; private static final String APP_VERSION = "0.0.1"; private static final String APP_VENDOR = "Paul Green"; private static Auth auth; private static WebTarget webTarget; public static void main(String args[]) { // args[0] source URL - "safe://localhost/" // args[1] mount point - "/home/paul/tmp/safemount/" String[] permissions = {"SAFE_DRIVE_ACCESS"}; auth = new Auth( new App( APP_NAME, APP_ID, APP_VERSION, APP_VENDOR ), permissions ); Client client = ClientBuilder.newClient(); client.register(ErrorResponseFilter.class); client.property(ClientProperties.REQUEST_ENTITY_PROCESSING, "CHUNKED"); webTarget = client.target(LAUNCHER_URL); Map<String, Object> env = new HashMap<>(); SafenetFactory safenetFactory = SafenetFactory.getInstance(webTarget, auth, "drive"); env.put("SafenetFactory", safenetFactory); Path mountPoint = Paths.get(args[1]); SafenetFileSystemProvider provider = new SafenetFileSystemProvider(); try (FileSystem fileSystem = provider.newFileSystem(URI.create(args[0]), env)) { JavaFS.mount(fileSystem, mountPoint, false, true); Thread.sleep(Long.MAX_VALUE); } catch (Exception e) { System.err.println(e.getMessage()); try { JavaFS.unmount(mountPoint); } catch (Exception e2) { System.err.println(e2.getMessage()); } } } }
mit
archimatetool/archi
com.archimatetool.editor/src/com/archimatetool/editor/actions/Messages.java
4070
/** * This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt */ package com.archimatetool.editor.actions; import org.eclipse.osgi.util.NLS; public class Messages extends NLS { private static final String BUNDLE_NAME = "com.archimatetool.editor.actions.messages"; //$NON-NLS-1$ public static String ArchiActionBarAdvisor_0; public static String ArchiActionBarAdvisor_1; public static String ArchiActionBarAdvisor_10; public static String ArchiActionBarAdvisor_11; public static String ArchiActionBarAdvisor_12; public static String ArchiActionBarAdvisor_13; public static String ArchiActionBarAdvisor_14; public static String ArchiActionBarAdvisor_15; public static String ArchiActionBarAdvisor_16; public static String ArchiActionBarAdvisor_17; public static String ArchiActionBarAdvisor_18; public static String ArchiActionBarAdvisor_19; public static String ArchiActionBarAdvisor_2; public static String ArchiActionBarAdvisor_20; public static String ArchiActionBarAdvisor_21; public static String ArchiActionBarAdvisor_22; public static String ArchiActionBarAdvisor_23; public static String ArchiActionBarAdvisor_24; public static String ArchiActionBarAdvisor_25; public static String ArchiActionBarAdvisor_26; public static String ArchiActionBarAdvisor_27; public static String ArchiActionBarAdvisor_28; public static String ArchiActionBarAdvisor_29; public static String ArchiActionBarAdvisor_3; public static String ArchiActionBarAdvisor_30; public static String ArchiActionBarAdvisor_4; public static String ArchiActionBarAdvisor_5; public static String ArchiActionBarAdvisor_6; public static String ArchiActionBarAdvisor_7; public static String ArchiActionBarAdvisor_8; public static String ArchiActionBarAdvisor_9; public static String ArchiActionFactory_0; public static String ArchiActionFactory_1; public static String ArchiActionFactory_2; public static String ArchiActionFactory_3; public static String ArchiActionFactory_4; public static String ArchiActionFactory_5; public static String ArchiActionFactory_6; public static String ArchiActionFactory_7; public static String ArchiActionFactory_8; public static String CheckForNewVersionAction_0; public static String CheckForNewVersionAction_1; public static String CheckForNewVersionAction_2; public static String CheckForNewVersionAction_3; public static String CheckForNewVersionAction_4; public static String CheckForNewVersionAction_5; public static String CheckForNewVersionAction_6; public static String ExportModelAction_0; public static String ImportIntoModelAction_0; public static String ImportModelAction_0; public static String MRUMenuManager_0; public static String MRUMenuManager_1; public static String MRUMenuManager_2; public static String MRUMenuManager_3; public static String NewArchimateModelAction_0; public static String NewArchimateModelAction_1; public static String NewDropDownAction_0; public static String NewDropDownAction_1; public static String OpenModelAction_0; public static String OpenModelAction_1; public static String OpenModelAction_2; public static String OpenModelAction_3; public static String SaveAction_0; public static String SaveAction_1; public static String SaveAsAction_0; public static String SaveAsAction_1; public static String ShowToolbarAction_0; public static String ShowToolbarAction_1; static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, Messages.class); } private Messages() { } }
mit
thanple/ThinkingInTechnology
src/main/java/com/thanple/gameserver/framework/common/nio/handler/MyProtobufDecoder.java
1220
package com.thanple.gameserver.framework.common.nio.handler; import com.google.protobuf.ExtensionRegistry; import com.google.protobuf.ExtensionRegistryLite; import com.google.protobuf.MessageLite; import com.thanple.gameserver.framework.common.nio.protocol._GameServerCMsg; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.protobuf.ProtobufDecoder; import java.util.List; /** * Created by Thanple on 2017/1/22. */ public class MyProtobufDecoder extends ProtobufDecoder{ public MyProtobufDecoder(MessageLite prototype) { super(prototype); } public MyProtobufDecoder(){ super(_GameServerCMsg.GameServerCMsg.getDefaultInstance()); //使用统一解码器GameServerCMsg } public MyProtobufDecoder(MessageLite prototype, ExtensionRegistry extensionRegistry) { super(prototype, extensionRegistry); } public MyProtobufDecoder(MessageLite prototype, ExtensionRegistryLite extensionRegistry) { super(prototype, extensionRegistry); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { super.decode(ctx, msg, out); } }
mit
DukeMobileTech/AndroidSurvey
app/src/main/java/org/adaptlab/chpir/android/survey/viewpagerfragments/SurveyViewPagerFragment.java
19505
package org.adaptlab.chpir.android.survey.viewpagerfragments; import android.app.ActivityOptions; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.graphics.Canvas; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.text.style.RelativeSizeSpan; 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.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import org.adaptlab.chpir.android.survey.InstrumentActivity; import org.adaptlab.chpir.android.survey.R; import org.adaptlab.chpir.android.survey.SurveyActivity; import org.adaptlab.chpir.android.survey.SurveyFragment; import org.adaptlab.chpir.android.survey.models.Survey; import org.adaptlab.chpir.android.survey.tasks.SetInstrumentLabelTask; import org.adaptlab.chpir.android.survey.tasks.SubmitSurveyTask; import org.adaptlab.chpir.android.survey.utils.AppUtil; import org.adaptlab.chpir.android.survey.utils.InstrumentListLabel; import java.text.DateFormat; import java.util.ArrayList; import java.util.List; public class SurveyViewPagerFragment extends Fragment { private static final String TAG = "SurveyViewPagerFragment"; private SurveyAdapter surveyAdapter; private List<Survey> mSurveys; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setSurveyLists(); View view = inflater.inflate(R.layout.recycler_view, container, false); RecyclerView recyclerView = view.findViewById(R.id.recyclerView); surveyAdapter = new SurveyAdapter(mSurveys); recyclerView.setAdapter(surveyAdapter); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView .getContext(), DividerItemDecoration.VERTICAL); dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.border)); recyclerView.addItemDecoration(dividerItemDecoration); ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new SwipeCallback(surveyAdapter, getContext())); itemTouchHelper.attachToRecyclerView(recyclerView); return view; } private void submitAll() { new AlertDialog.Builder(getActivity()) .setTitle(R.string.submit_survey) .setMessage(R.string.submit_survey_message) .setPositiveButton(R.string.submit, (dialog, id) -> { for (Survey survey : mSurveys) { prepareForSubmission(survey); } new SubmitSurveyTask(getActivity()).execute(); startActivity(new Intent(getActivity(), InstrumentActivity.class)); if (getActivity() != null) getActivity().finish(); }) .setNegativeButton(R.string.cancel, (dialog, id) -> { }) .show(); } private void setSurveyLists() { mSurveys = new ArrayList<>(); for (Survey survey : Survey.getAllProjectSurveys(AppUtil.getProjectId())) { if (survey.isSent() || survey.isQueued()) continue; if (survey.readyToSend()) { mSurveys.add(survey); } else { mSurveys.add(survey); } } } @Override public void onResume() { super.onResume(); setSurveyLists(); surveyAdapter.updateSurveys(mSurveys); } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.fragment_instrument, menu); } @Override public void onPrepareOptionsMenu(@NonNull Menu menu) { super.onPrepareOptionsMenu(menu); menu.findItem(R.id.menu_item_submit_all).setEnabled(true).setVisible(true); menu.findItem(R.id.menu_item_settings).setEnabled(false).setVisible(false); menu.findItem(R.id.menu_item_refresh).setEnabled(false).setVisible(false); menu.findItem(R.id.menu_item_progress_action).setEnabled(false).setVisible(false); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_item_submit_all) { submitAll(); return true; } return super.onOptionsItemSelected(item); } private void prepareForSubmission(Survey survey) { if (survey.readyToSend()) { if (survey.getCompletedResponseCount() == 0 && survey.responses().size() > 0) { survey.setCompletedResponseCount(survey.responses().size()); } survey.setQueued(true); } } public class SurveyAdapter extends RecyclerView.Adapter<SurveyViewHolder> { List<Survey> mSurveys; SurveyAdapter(List<Survey> surveys) { mSurveys = surveys; } public void add(Survey survey) { mSurveys.add(0, survey); notifyItemInserted(0); } void updateSurveys(List<Survey> newSurveys) { final List<Survey> oldSurveys = new ArrayList<>(this.mSurveys); this.mSurveys.clear(); if (newSurveys != null) { this.mSurveys.addAll(newSurveys); } DiffUtil.calculateDiff(new DiffUtil.Callback() { @Override public int getOldListSize() { return oldSurveys.size(); } @Override public int getNewListSize() { return mSurveys.size(); } @Override public boolean areItemsTheSame(int oldSurveyPosition, int newSurveyPosition) { return oldSurveys.get(oldSurveyPosition).equals(mSurveys.get(newSurveyPosition)); } @Override public boolean areContentsTheSame(int oldSurveyPosition, int newSurveyPosition) { Survey oldSurvey = oldSurveys.get(oldSurveyPosition); Survey newSurvey = mSurveys.get(newSurveyPosition); return oldSurvey.getLastUpdated().equals(newSurvey.getLastUpdated()) && oldSurvey.responses().size() == newSurvey.responses().size(); } }).dispatchUpdatesTo(this); } @NonNull @Override public SurveyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View surveyView = getLayoutInflater().inflate(R.layout.list_item_survey, parent, false); return new SurveyViewHolder(surveyView); } @Override public void onBindViewHolder(@NonNull final SurveyViewHolder viewHolder, int position) { viewHolder.setSurvey(mSurveys.get(position)); setSurveyLaunchAction(viewHolder); } private void setSurveyLaunchAction(@NonNull final SurveyViewHolder viewHolder) { viewHolder.mViewContent.setOnClickListener(v -> { Survey survey = mSurveys.get(viewHolder.getAdapterPosition()); if (getActivity() == null || survey == null) return; if (survey.isQueued() || survey.isSent()) { Toast.makeText(getActivity(), R.string.survey_submitted, Toast.LENGTH_LONG).show(); } else if (!survey.getInstrument().loaded()) { Toast.makeText(getActivity(), R.string.instrument_not_loaded, Toast.LENGTH_LONG).show(); } else { Intent i = new Intent(getActivity(), SurveyActivity.class); i.putExtra(SurveyFragment.EXTRA_INSTRUMENT_ID, survey.getInstrument().getRemoteId()); i.putExtra(SurveyFragment.EXTRA_SURVEY_ID, survey.getId()); i.putExtra(SurveyFragment.EXTRA_QUESTION_NUMBER, survey.getLastQuestion().getNumberInInstrument() - 1); i.putExtra(SurveyFragment.EXTRA_AUTHORIZE_SURVEY, ((InstrumentActivity) getActivity()).isAuthorizeSurvey()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { startActivity(i, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle()); } else { startActivity(i); } } }); } public void remove(int position) { if (position > -1 && position < mSurveys.size()) { Survey survey = mSurveys.get(position); if (survey != null) { mSurveys.remove(position); survey.delete(); notifyItemRemoved(position); } } } @Override public int getItemCount() { return mSurveys.size(); } void deleteItem(final int position) { new AlertDialog.Builder(getActivity()) .setTitle(R.string.delete_survey_title) .setMessage(R.string.delete_survey_message) .setPositiveButton(R.string.delete, (dialog, id) -> remove(position)) .setNegativeButton(R.string.cancel, (dialog, id) -> notifyItemChanged(position)) .show(); } void uploadItem(final int position) { final Survey survey = mSurveys.get(position); if (getActivity() == null || survey == null) return; if (survey.readyToSend()) { new AlertDialog.Builder(getActivity()) .setTitle(R.string.submit_survey) .setMessage(R.string.submit_survey_message) .setPositiveButton(R.string.submit, (dialog, id) -> { prepareForSubmission(survey); new SubmitSurveyTask(getActivity()).execute(); mSurveys.remove(position); notifyItemRemoved(position); }) .setNegativeButton(R.string.cancel, (dialog, id) -> notifyItemChanged(position)) .show(); } else { new AlertDialog.Builder(getActivity()) .setTitle(getActivity().getString(R.string.incomplete_survey)) .setMessage(getActivity().getString(R.string.incomplete_survey_message)) .setPositiveButton(R.string.okay, (dialog, id) -> notifyItemChanged(position)) .show(); } } } public class SurveyViewHolder extends RecyclerView.ViewHolder { View mViewContent; TextView surveyTextView; TextView progressTextView; Survey mSurvey; SurveyViewHolder(final View itemView) { super(itemView); surveyTextView = itemView.findViewById(R.id.surveyProperties); progressTextView = itemView.findViewById(R.id.surveyProgress); mViewContent = itemView.findViewById(R.id.list_item_survey_content); } public void setSurvey(Survey survey) { this.mSurvey = survey; String surveyTitle = survey.identifier(AppUtil.getContext()) + "\n"; String instrumentTitle = survey.getInstrument().getTitle() + "\n"; String lastUpdated = DateFormat.getDateTimeInstance().format( survey.getLastUpdated()) + " "; SpannableString spannableString = new SpannableString(surveyTitle + instrumentTitle + lastUpdated); // survey title spannableString.setSpan(new RelativeSizeSpan(1.2f), 0, surveyTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(new ForegroundColorSpan(getResources().getColor( R.color.primary_text)), 0, surveyTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // instrument title spannableString.setSpan(new RelativeSizeSpan(0.8f), surveyTitle.length(), surveyTitle.length() + instrumentTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(new ForegroundColorSpan(getResources().getColor( R.color.secondary_text)), surveyTitle.length(), surveyTitle.length() + instrumentTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // last updated at int end = surveyTitle.length() + instrumentTitle.length() + lastUpdated.length(); spannableString.setSpan(new RelativeSizeSpan(0.8f), surveyTitle.length() + instrumentTitle.length(), end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color .secondary_text)), surveyTitle.length() + instrumentTitle.length(), end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // progress spannableString.setSpan(new RelativeSizeSpan(0.8f), end, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color .secondary_text)), end, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); surveyTextView.setText(spannableString); if (!survey.isQueued()) { new SetInstrumentLabelTask(SurveyViewPagerFragment.this).execute( new InstrumentListLabel(survey.getInstrument(), surveyTextView)); } String progress = getString(R.string.progress) + " " + survey.responses().size() + " " + getString(R.string.of) + " " + survey.getInstrument().getQuestionCount(); SpannableString progressString = new SpannableString(progress); if (survey.readyToSend()) { progressString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.green)), 0, progress.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else { progressString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.red)), 0, progress.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } progressTextView.setText(progressString); } } private class SwipeCallback extends ItemTouchHelper.SimpleCallback { private final ColorDrawable mDeleteBackground; private final ColorDrawable mUploadBackground; private SurveyAdapter mAdapter; private Drawable mDeleteIcon; private Drawable mUploadIcon; SwipeCallback(SurveyAdapter adapter, Context context) { super(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT); mAdapter = adapter; mDeleteIcon = ContextCompat.getDrawable(context, R.drawable.ic_delete_forever_black_24dp); mUploadIcon = ContextCompat.getDrawable(context, R.drawable.ic_cloud_upload_black_24dp); mDeleteBackground = new ColorDrawable(getResources().getColor(R.color.red)); mUploadBackground = new ColorDrawable(getResources().getColor(R.color.green)); } @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { int position = viewHolder.getAdapterPosition(); if (direction == ItemTouchHelper.LEFT) { mAdapter.deleteItem(position); } else if (direction == ItemTouchHelper.RIGHT) { mAdapter.uploadItem(position); } } @Override public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); View itemView = viewHolder.itemView; int backgroundCornerOffset = 20; if (dX > 0) { // Swiping to the right int iconMargin = (itemView.getHeight() - mUploadIcon.getIntrinsicHeight()) / 2; int iconTop = itemView.getTop() + (itemView.getHeight() - mUploadIcon.getIntrinsicHeight()) / 2; int iconBottom = iconTop + mUploadIcon.getIntrinsicHeight(); int iconLeft = itemView.getLeft() + iconMargin; int iconRight = itemView.getLeft() + iconMargin + mUploadIcon.getIntrinsicWidth(); mUploadIcon.setBounds(iconLeft, iconTop, iconRight, iconBottom); mUploadBackground.setBounds(itemView.getLeft(), itemView.getTop(), itemView.getLeft() + ((int) dX) + backgroundCornerOffset, itemView.getBottom()); mUploadBackground.draw(c); mUploadIcon.draw(c); } else if (dX < 0) { // Swiping to the left int iconMargin = (itemView.getHeight() - mDeleteIcon.getIntrinsicHeight()) / 2; int iconTop = itemView.getTop() + (itemView.getHeight() - mDeleteIcon.getIntrinsicHeight()) / 2; int iconBottom = iconTop + mDeleteIcon.getIntrinsicHeight(); int iconLeft = itemView.getRight() - iconMargin - mDeleteIcon.getIntrinsicWidth(); int iconRight = itemView.getRight() - iconMargin; mDeleteIcon.setBounds(iconLeft, iconTop, iconRight, iconBottom); mDeleteBackground.setBounds(itemView.getRight() + ((int) dX) - backgroundCornerOffset, itemView.getTop(), itemView.getRight(), itemView.getBottom()); mDeleteBackground.draw(c); mDeleteIcon.draw(c); } else { // view is unSwiped mDeleteBackground.setBounds(0, 0, 0, 0); } } } }
mit
Ikaguia/miniHaskell
VersaoJava/src-tests/br/unb/cic/poo/mh/TesteAplicacaoFuncao.java
2165
package br.unb.cic.poo.mh; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import br.unb.poo.mh.Ambiente; import br.unb.poo.mh.AplicacaoFuncao; import br.unb.poo.mh.DeclaracaoFuncao; import br.unb.poo.mh.Expressao; import br.unb.poo.mh.ExpressaoSoma; import br.unb.poo.mh.ExpressaoSubtracao; import br.unb.poo.mh.Identificador; import br.unb.poo.mh.PrettyPrinter; import br.unb.poo.mh.TamanhoDasExpressoes; import br.unb.poo.mh.ValorInteiro; public class TesteAplicacaoFuncao { private DeclaracaoFuncao soma; private DeclaracaoFuncao subtracao; @BeforeClass public static void SuiteSetUp(){ System.out.println("\n==Teste Aplicação de Função=="); } @Before public void setUp() { Identificador id_x = new Identificador("x"); Identificador id_y = new Identificador("y"); List<String> args = new ArrayList<>(); args.add("x"); args.add("y"); Expressao corpo_soma = new ExpressaoSoma(id_x,id_y); soma = new DeclaracaoFuncao("soma", args, corpo_soma); Ambiente.instance().declaraFuncao(soma); Expressao corpo_subtracao = new ExpressaoSubtracao(id_x, id_y); subtracao = new DeclaracaoFuncao("subtracao", args, corpo_subtracao); Ambiente.instance().declaraFuncao(subtracao); } @Test public void testeAplicacaoFuncao() { List<Expressao> parametros = new ArrayList<>(); parametros.add(new ValorInteiro(3)); parametros.add(new ExpressaoSoma(new ValorInteiro(4), new ValorInteiro(5))); Expressao aplicaSoma = new AplicacaoFuncao("soma", parametros); Assert.assertEquals(new ValorInteiro(12), aplicaSoma.avaliar()); PrettyPrinter pp = new PrettyPrinter(); TamanhoDasExpressoes t = new TamanhoDasExpressoes(); aplicaSoma.aceitar(pp); aplicaSoma.aceitar(t); Assert.assertEquals(5, t.getTamanho()); System.out.println("Tamanho da expressão soma: " + t.getTamanho()); Expressao aplicaSubtracao = new AplicacaoFuncao("subtracao", parametros); Assert.assertEquals(new ValorInteiro(6), aplicaSubtracao.avaliar()); aplicaSubtracao.aceitar(pp); aplicaSubtracao.aceitar(t); } }
mit
MindSelf/ImageLoader
app/src/main/java/com/example/zhaolexi/imageloader/home/album/Photo.java
2399
package com.example.zhaolexi.imageloader.home.album; import com.example.zhaolexi.imageloader.detail.Detail; import com.google.gson.annotations.SerializedName; import java.io.Serializable; /** * Created by ZHAOLEXI on 2017/10/14. */ public class Photo implements Detail, Serializable { /** * _id : 59dd6a91421aa90fef20346c * createdAt : 2017-10-11T08:49:21.485Z * description : 10-11 * publishedAt : 2017-10-11T12:40:42.545Z * source : chrome * type : 福利 * thumbUrl : http://7xi8d6.com1.z0.glb.clouddn.com/20171011084856_0YQ0jN_joanne_722_11_10_2017_8_39_5_505.jpeg * used : true * who : 代码家 */ private String pid; private String who; @SerializedName(value = "pdesc", alternate = "desc") private String description; private String publishAt; @SerializedName(value = "thumbUrl", alternate = "url") private String thumbUrl; private String fullUrl; private boolean hasThumbUp; private int thumbUp; public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getPublishAt() { return publishAt; } public void setPublishAt(String publishAt) { this.publishAt = publishAt; } public int getThumbUp() { return thumbUp; } public void setThumbUp(int thumbUp) { this.thumbUp = thumbUp; } public String getFullUrl() { return fullUrl; } public void setFullUrl(String fullUrl) { this.fullUrl = fullUrl; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getWho() { return who; } public void setWho(String who) { this.who = who; } @Override public String getDetailUrl() { return fullUrl == null ? thumbUrl : fullUrl; } @Override public boolean shouldResized() { return fullUrl == null; } public boolean hasThumbUp() { return hasThumbUp; } public void setHasThumbUp(boolean hasThumbUp) { this.hasThumbUp = hasThumbUp; } }
mit
TinusTinus/javafx8sandbox
src/main/java/nl/mvdr/javafx8sandbox/CollectorSandbox.java
2197
package nl.mvdr.javafx8sandbox; import java.util.Arrays; import java.util.List; /** * Playing around with Collectors for fun. (Not really related to JavaFX.) * * @author Martijn van de Rijdt */ public class CollectorSandbox { /** * Main method. * * @param args command line parameters; these are ignored */ public static void main(String[] args) { List<String> names = Arrays.asList("Jan", "Klaas", "Piet", "Ton", "Kees", "Sjaak", "Herman", "en", "nog", "meer", "namen"); long start = System.currentTimeMillis(); String string = names .parallelStream() .collect(CollectorSandbox::supply, CollectorSandbox::accumulate, CollectorSandbox::combine) .toString(); System.out.println(string); System.out.println("Time spent: " + (System.currentTimeMillis() - start) + "milliseconds."); } /** * Supplies a new string builder. * * @return */ private static StringBuilder supply() { log("Creating new string buffer."); return new StringBuilder(); } /** * Accumulates the given string into the given string builder. * * @param builder builder * @param string string */ private static void accumulate(StringBuilder builder, String string) { log("Appending to builder \"" + builder + "\": \"" + string + "\""); try { Thread.sleep(1_000); } catch (InterruptedException e) { e.printStackTrace(); } builder.append(string); } /** * Combines the given builders. * * @param builder0 builder * @param builder1 builder */ private static void combine(StringBuilder builder0, StringBuilder builder1) { log("Combining string builders \"" + builder0 + "\" and \"" + builder1 + "\""); builder0.append(builder1); } /** * Logs the given message. * * @param message message */ private static void log(String message) { System.out.println(Thread.currentThread().getName() + " - " + message); } }
mit
gardncl/elements-of-programming-interviews
sorting/src/test/java/RemoveFirstNameDuplicatesTest.java
2043
import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collector; import java.util.stream.Collectors; import static org.junit.Assert.*; public class RemoveFirstNameDuplicatesTest { private List<String> expected; private List<RemoveFirstNameDuplicates.Name> A; @Test public void eliminateDuplicates1() throws Exception { expected = Arrays.asList("Ian", "David"); A = Arrays.asList( new RemoveFirstNameDuplicates.Name("Ian","Botham"), new RemoveFirstNameDuplicates.Name("David","Gower"), new RemoveFirstNameDuplicates.Name("Ian","Bell"), new RemoveFirstNameDuplicates.Name("Ian","Chappell") ); test(expected, A); } @Test public void eliminateDuplicates2() throws Exception { expected = Arrays.asList("Ian"); A = Arrays.asList( new RemoveFirstNameDuplicates.Name("Ian","Botham"), new RemoveFirstNameDuplicates.Name("Ian","Bell"), new RemoveFirstNameDuplicates.Name("Ian","Chappell") ); test(expected, A); } @Test public void eliminateDuplicates3() throws Exception { expected = Arrays.asList("Ian", "David", "Chazz"); A = Arrays.asList( new RemoveFirstNameDuplicates.Name("Ian","Botham"), new RemoveFirstNameDuplicates.Name("David","Gower"), new RemoveFirstNameDuplicates.Name("Ian","Bell"), new RemoveFirstNameDuplicates.Name("Chazz","Chappell") ); test(expected, A); } private void test(List<String> expected, List<RemoveFirstNameDuplicates.Name> A) { RemoveFirstNameDuplicates.eliminateDuplicates(A); List<String> result = A.stream() .map(name -> name.first) .collect(Collectors.toList()); AssertUtils.assertSameContentsString(expected, result); } }
mit
letrunghieu/laravel-netbeans
src/info/hieule/framework/laravel/versions/LaravelVersion.java
1572
/* * The MIT License * * Copyright 2014 Hieu Le <letrunghieu.cse09@gmail.com>. * * 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 info.hieule.framework.laravel.versions; import com.github.zafarkhaja.semver.Version; /** * * @author Hieu Le <letrunghieu.cse09@gmail.com> */ public class LaravelVersion { public static Version fromString(String version) { return Version.valueOf(version.substring(1)); } public static String versionToString(Version version) { return "v" + version.toString(); } }
mit
openforis/calc
calc-core/unused/old-hibernate/metadata/Category.java
1932
package org.openforis.calc.metadata; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.openforis.calc.common.UserObject; import com.fasterxml.jackson.annotation.JsonIgnore; /** * Represents one possible value of a {@link CategoricalVariable}. * * @author G. Miceli * @author M. Togna * @author S. Ricci */ @javax.persistence.Entity @Table(name = "category") public class Category extends UserObject { public static final BigDecimal TRUE_VALUE = BigDecimal.valueOf(1.0); public static final BigDecimal FALSE_VALUE = BigDecimal.valueOf(0.0); @Column(name = "code") private String code; @Column(name = "override") private boolean overrideInputMetadata; @Column(name = "sort_order") private int sortOrder; @Column(name = "original_id") private Integer originalId; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "variable_id") @JsonIgnore private Variable<?> variable; @Column(name = "value") private Double value; public Variable<?> getVariable() { return this.variable; } public void setVariable(Variable<?> variable) { this.variable = variable; } public void setCode(String code) { this.code = code; } public String getCode() { return this.code; } public void setOverrideInputMetadata(boolean overrideInputMetadata) { this.overrideInputMetadata = overrideInputMetadata; } public boolean isOverrideInputMetadata() { return this.overrideInputMetadata; } public void setSortOrder(int sortOrder) { this.sortOrder = sortOrder; } public int getSortOrder() { return this.sortOrder; } public Double getValue() { return value; } public void setValue(Double value) { this.value = value; } }
mit
cooervo/java-design-patterns
intercepting-filter/src/main/java/com/iluwatar/DepositFilter.java
349
package com.iluwatar; /** * Concrete implementation of filter * * This checks for the deposit code, returns null when deposit field is empty * @author joshzambales * */ public class DepositFilter implements Filter { public String execute(String[] request) { if (request[3].equals("")) { return null; } else return request[3]; } }
mit
williamfiset/Algorithms
src/main/java/com/williamfiset/algorithms/graphtheory/analysis/PrimsGraphRepresentationAnaylsis.java
17391
/* Performs density analysis to figure out whether an adjacency list or an adjacency matrix is better for prims MST algorithm. Results seem to indicate that the adjacency matrix is better starting at around ~33% edge percentage density: Percentage full: ~0%, Edges included: 0 List: 1168811 nanos Matrix: 300204 nanos Percentage full: ~5%, Edges included: 1249282 List: 78032794 nanos Matrix: 160413885 nanos Percentage full: ~10%, Edges included: 2499128 List: 53444885 nanos Matrix: 136684636 nanos Percentage full: ~15%, Edges included: 3747556 List: 84818677 nanos Matrix: 154946744 nanos Percentage full: ~20%, Edges included: 4996636 List: 105822314 nanos Matrix: 167086118 nanos Percentage full: ~25%, Edges included: 6246068 List: 117237558 nanos Matrix: 190984980 nanos Percentage full: ~30%, Edges included: 7497476 List: 249309754 nanos Matrix: 233969389 nanos Percentage full: ~35%, Edges included: 8748710 List: 265593928 nanos Matrix: 235897178 nanos Percentage full: ~40%, Edges included: 10000808 List: 317905981 nanos Matrix: 255262713 nanos Percentage full: ~45%, Edges included: 11245712 List: 428115402 nanos Matrix: 244939994 nanos Percentage full: ~50%, Edges included: 12495078 List: 485647021 nanos Matrix: 241433180 nanos Percentage full: ~55%, Edges included: 13744132 List: 523930222 nanos Matrix: 240345667 nanos Percentage full: ~60%, Edges included: 14991078 List: 565671594 nanos Matrix: 250618728 nanos Percentage full: ~65%, Edges included: 16249278 List: 635804318 nanos Matrix: 247628418 nanos Percentage full: ~70%, Edges included: 17492252 List: 448590410 nanos Matrix: 218092040 nanos Percentage full: ~75%, Edges included: 18748276 List: 365672497 nanos Matrix: 209152347 nanos Percentage full: ~80%, Edges included: 19997560 List: 389878221 nanos Matrix: 197766511 nanos Percentage full: ~85%, Edges included: 21243518 List: 360389630 nanos Matrix: 181542371 nanos Percentage full: ~90%, Edges included: 22496480 List: 486827671 nanos Matrix: 182686235 nanos Percentage full: ~95%, Edges included: 23747794 List: 423884430 nanos Matrix: 159974003 nanos Percentage full: ~100%, Edges included: 24995000 List: 436565071 nanos Matrix: 154691124 nanos */ package com.williamfiset.algorithms.graphtheory.analysis; import static java.lang.Math.*; import java.time.Duration; import java.time.Instant; import java.util.*; import java.util.concurrent.TimeUnit; public class PrimsGraphRepresentationAnaylsis { private static class Edge implements Comparable<Edge> { int from, to, cost; public Edge(int from, int to, int cost) { this.from = from; this.to = to; this.cost = cost; } @Override public int compareTo(Edge other) { return cost - other.cost; } } private static class PrimsAdjList { // Inputs private final int n; private final List<List<Edge>> graph; // Internal private boolean solved; private boolean mstExists; private boolean[] visited; private MinIndexedDHeap<Edge> ipq; // Outputs private long minCostSum; private Edge[] mstEdges; public PrimsAdjList(List<List<Edge>> graph) { if (graph == null || graph.isEmpty()) throw new IllegalArgumentException(); this.n = graph.size(); this.graph = graph; } // Returns the edges used in finding the minimum spanning tree, // or returns null if no MST exists. public Edge[] getMst() { solve(); return mstExists ? mstEdges : null; } public Long getMstCost() { solve(); return mstExists ? minCostSum : null; } private void relaxEdgesAtNode(int currentNodeIndex) { visited[currentNodeIndex] = true; // edges will never be null if the createEmptyGraph method was used to build the graph. List<Edge> edges = graph.get(currentNodeIndex); for (Edge edge : edges) { int destNodeIndex = edge.to; // Skip edges pointing to already visited nodes. if (visited[destNodeIndex]) continue; if (ipq.contains(destNodeIndex)) { // Try and improve the cheapest edge at destNodeIndex with the current edge in the IPQ. ipq.decrease(destNodeIndex, edge); } else { // Insert edge for the first time. ipq.insert(destNodeIndex, edge); } } } // Computes the minimum spanning tree and minimum spanning tree cost. private void solve() { if (solved) return; solved = true; int m = n - 1, edgeCount = 0; visited = new boolean[n]; mstEdges = new Edge[m]; // The degree of the d-ary heap supporting the IPQ can greatly impact performance, especially // on dense graphs. The base 2 logarithm of n is a decent value based on my quick experiments // (even better than E/V in many cases). int degree = (int) Math.ceil(Math.log(n) / Math.log(2)); ipq = new MinIndexedDHeap<>(max(2, degree), n); // Add initial set of edges to the priority queue starting at node 0. relaxEdgesAtNode(0); while (!ipq.isEmpty() && edgeCount != m) { int destNodeIndex = ipq.peekMinKeyIndex(); // equivalently: edge.to Edge edge = ipq.pollMinValue(); mstEdges[edgeCount++] = edge; minCostSum += edge.cost; relaxEdgesAtNode(destNodeIndex); } // Verify MST spans entire graph. mstExists = (edgeCount == m); } /* Graph construction helpers. */ // Creates an empty adjacency list graph with n nodes. static List<List<Edge>> createEmptyGraph(int n) { List<List<Edge>> g = new ArrayList<>(); for (int i = 0; i < n; i++) g.add(new ArrayList<>()); return g; } static void addDirectedEdge(List<List<Edge>> g, int from, int to, int cost) { g.get(from).add(new Edge(from, to, cost)); } static void addUndirectedEdge(List<List<Edge>> g, int from, int to, int cost) { addDirectedEdge(g, from, to, cost); addDirectedEdge(g, to, from, cost); } } private static class PrimsAdjMatrix { // Inputs private final int n; private final Integer[][] graph; // Internal private boolean solved; private boolean mstExists; private boolean[] visited; private MinIndexedDHeap<Integer> ipq; // Outputs private long minCostSum; private Edge[] mstEdges; public PrimsAdjMatrix(Integer[][] graph) { if (graph == null || graph.length == 0 || graph[0].length != graph.length) throw new IllegalArgumentException(); this.n = graph.length; this.graph = graph; } // Returns the edges used in finding the minimum spanning tree, // or returns null if no MST exists. public Edge[] getMst() { // Unimplemented. return null; } public Long getMstCost() { solve(); return mstExists ? minCostSum : null; } private void relaxEdgesAtNode(int currentNodeIndex) { visited[currentNodeIndex] = true; for (int to = 0; to < n; to++) { Integer cost = graph[currentNodeIndex][to]; // Edge doesn't exist. if (cost == null) continue; // Skip edges pointing to already visited nodes. if (visited[to]) continue; if (ipq.contains(to)) { // Try and improve the cheapest edge at to with the current edge in the IPQ. ipq.decrease(to, cost); } else { // Insert edge for the first time. ipq.insert(to, cost); } } } // Computes the minimum spanning tree and minimum spanning tree cost. private void solve() { if (solved) return; solved = true; int m = n - 1, edgeCount = 0; visited = new boolean[n]; // The degree of the d-ary heap supporting the IPQ can greatly impact performance, especially // on dense graphs. The base 2 logarithm of n is a decent value based on my quick experiments // (even better than E/V in many cases). int degree = (int) Math.ceil(Math.log(n) / Math.log(2)); ipq = new MinIndexedDHeap<>(max(2, degree), n); // Add initial set of edges to the priority queue starting at node 0. relaxEdgesAtNode(0); while (!ipq.isEmpty() && edgeCount != m) { int destNodeIndex = ipq.peekMinKeyIndex(); int edgeCost = ipq.pollMinValue(); minCostSum += edgeCost; edgeCount++; relaxEdgesAtNode(destNodeIndex); } // Verify MST spans entire graph. mstExists = (edgeCount == m); } /* Graph construction helpers. */ // Creates an empty adjacency matrix graph with n nodes. static Integer[][] createEmptyGraph(int n) { return new Integer[n][n]; } static void addDirectedEdge(Integer[][] g, int from, int to, int cost) { g[from][to] = cost; } static void addUndirectedEdge(Integer[][] g, int from, int to, int cost) { addDirectedEdge(g, from, to, cost); addDirectedEdge(g, to, from, cost); } } /* Example usage. */ public static void main(String[] args) throws InterruptedException { densityTest(); } static Random random = new Random(); private static void densityTest() throws InterruptedException { String rows = "", header = "edge density percentage, adj list, adj matrix\n"; for (int percentage = 5; percentage <= 100; percentage += 5) { // Calling GC seems to give more consistent results? System.gc(); TimeUnit.SECONDS.sleep(2); int n = 5000; List<List<Edge>> g1 = PrimsAdjList.createEmptyGraph(n); Integer[][] g2 = PrimsAdjMatrix.createEmptyGraph(n); int numEdgesIncluded = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int r = Math.abs(random.nextInt()) % 100; if (r >= percentage) continue; PrimsAdjList.addUndirectedEdge(g1, i, j, r); PrimsAdjMatrix.addUndirectedEdge(g2, i, j, r); numEdgesIncluded += 2; } } PrimsAdjList adjListSolver = new PrimsAdjList(g1); PrimsAdjMatrix matrixSolver = new PrimsAdjMatrix(g2); System.out.println( "\nPercentage full: ~" + percentage + "%, Edges included: " + numEdgesIncluded); Instant start = Instant.now(); Long listCost = adjListSolver.getMstCost(); Instant end = Instant.now(); long listTimeMs = Duration.between(start, end).toMillis(); System.out.println("List: " + listTimeMs + " millis"); start = Instant.now(); Long matrixCost = matrixSolver.getMstCost(); end = Instant.now(); long matrixTimeMs = Duration.between(start, end).toMillis(); System.out.println("Matrix: " + matrixTimeMs + " millis"); if (listCost != null && listCost.longValue() != matrixCost.longValue()) { System.out.println("Oh dear. " + listCost + " != " + matrixCost); } rows += String.format("%d%%,%d,%d\n", percentage, listTimeMs, matrixTimeMs); } System.out.println("CSV printout:\n\n" + header + rows); } /* Supporting indexed priority queue implementation. */ private static class MinIndexedDHeap<T extends Comparable<T>> { // Current number of elements in the heap. private int sz; // Maximum number of elements in the heap. private final int N; // The degree of every node in the heap. private final int D; // Lookup arrays to track the child/parent indexes of each node. private final int[] child, parent; // The Position Map (pm) maps Key Indexes (ki) to where the position of that // key is represented in the priority queue in the domain [0, sz). public final int[] pm; // The Inverse Map (im) stores the indexes of the keys in the range // [0, sz) which make up the priority queue. It should be noted that // 'im' and 'pm' are inverses of each other, so: pm[im[i]] = im[pm[i]] = i public final int[] im; // The values associated with the keys. It is very important to note // that this array is indexed by the key indexes (aka 'ki'). public final Object[] values; // Initializes a D-ary heap with a maximum capacity of maxSize. public MinIndexedDHeap(int degree, int maxSize) { if (maxSize <= 0) throw new IllegalArgumentException("maxSize <= 0"); D = max(2, degree); N = max(D + 1, maxSize); im = new int[N]; pm = new int[N]; child = new int[N]; parent = new int[N]; values = new Object[N]; for (int i = 0; i < N; i++) { parent[i] = (i - 1) / D; child[i] = i * D + 1; pm[i] = im[i] = -1; } } public int size() { return sz; } public boolean isEmpty() { return sz == 0; } public boolean contains(int ki) { keyInBoundsOrThrow(ki); return pm[ki] != -1; } public int peekMinKeyIndex() { isNotEmptyOrThrow(); return im[0]; } public int pollMinKeyIndex() { int minki = peekMinKeyIndex(); delete(minki); return minki; } @SuppressWarnings("unchecked") public T peekMinValue() { isNotEmptyOrThrow(); return (T) values[im[0]]; } public T pollMinValue() { T minValue = peekMinValue(); delete(peekMinKeyIndex()); return minValue; } public void insert(int ki, T value) { if (contains(ki)) throw new IllegalArgumentException("index already exists; received: " + ki); valueNotNullOrThrow(value); pm[ki] = sz; im[sz] = ki; values[ki] = value; swim(sz++); } @SuppressWarnings("unchecked") public T valueOf(int ki) { keyExistsOrThrow(ki); return (T) values[ki]; } @SuppressWarnings("unchecked") public T delete(int ki) { keyExistsOrThrow(ki); final int i = pm[ki]; swap(i, --sz); sink(i); swim(i); T value = (T) values[ki]; values[ki] = null; pm[ki] = -1; im[sz] = -1; return value; } @SuppressWarnings("unchecked") public T update(int ki, T value) { keyExistsAndValueNotNullOrThrow(ki, value); final int i = pm[ki]; T oldValue = (T) values[ki]; values[ki] = value; sink(i); swim(i); return oldValue; } // Strictly decreases the value associated with 'ki' to 'value' public void decrease(int ki, T value) { keyExistsAndValueNotNullOrThrow(ki, value); if (less(value, values[ki])) { values[ki] = value; swim(pm[ki]); } } // Strictly increases the value associated with 'ki' to 'value' public void increase(int ki, T value) { keyExistsAndValueNotNullOrThrow(ki, value); if (less(values[ki], value)) { values[ki] = value; sink(pm[ki]); } } /* Helper functions */ private void sink(int i) { for (int j = minChild(i); j != -1; ) { swap(i, j); i = j; j = minChild(i); } } private void swim(int i) { while (less(i, parent[i])) { swap(i, parent[i]); i = parent[i]; } } // From the parent node at index i find the minimum child below it private int minChild(int i) { int index = -1, from = child[i], to = min(sz, from + D); for (int j = from; j < to; j++) if (less(j, i)) index = i = j; return index; } private void swap(int i, int j) { pm[im[j]] = i; pm[im[i]] = j; int tmp = im[i]; im[i] = im[j]; im[j] = tmp; } // Tests if the value of node i < node j @SuppressWarnings("unchecked") private boolean less(int i, int j) { return ((Comparable<? super T>) values[im[i]]).compareTo((T) values[im[j]]) < 0; } @SuppressWarnings("unchecked") private boolean less(Object obj1, Object obj2) { return ((Comparable<? super T>) obj1).compareTo((T) obj2) < 0; } @Override public String toString() { List<Integer> lst = new ArrayList<>(sz); for (int i = 0; i < sz; i++) lst.add(im[i]); return lst.toString(); } /* Helper functions to make the code more readable. */ private void isNotEmptyOrThrow() { if (isEmpty()) throw new NoSuchElementException("Priority queue underflow"); } private void keyExistsAndValueNotNullOrThrow(int ki, Object value) { keyExistsOrThrow(ki); valueNotNullOrThrow(value); } private void keyExistsOrThrow(int ki) { if (!contains(ki)) throw new NoSuchElementException("Index does not exist; received: " + ki); } private void valueNotNullOrThrow(Object value) { if (value == null) throw new IllegalArgumentException("value cannot be null"); } private void keyInBoundsOrThrow(int ki) { if (ki < 0 || ki >= N) throw new IllegalArgumentException("Key index out of bounds; received: " + ki); } /* Test functions */ // Recursively checks if this heap is a min heap. This method is used // for testing purposes to validate the heap invariant. public boolean isMinHeap() { return isMinHeap(0); } private boolean isMinHeap(int i) { int from = child[i], to = min(sz, from + D); for (int j = from; j < to; j++) { if (!less(i, j)) return false; if (!isMinHeap(j)) return false; } return true; } } }
mit
yangra/SoftUni
JavaFundamentals/JavaAdvanced/03.StringProcessingExercise/src/P09MatchFullName.java
630
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class P09MatchFullName { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String pattern = "^[A-Z][a-z]+\\s[A-Z][a-z]+$"; while(true) { String line = scanner.nextLine(); if("end".equals(line)){ break; } Pattern regex = Pattern.compile(pattern); Matcher matcher = regex.matcher(line); if(matcher.find()){ System.out.println(line); } } } }
mit
HenryHarper/Acquire-Reboot
gradle/src/launcher/org/gradle/launcher/daemon/server/exec/LogToClient.java
5557
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.launcher.daemon.server.exec; import org.gradle.api.logging.LogLevel; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; import org.gradle.launcher.daemon.diagnostics.DaemonDiagnostics; import org.gradle.launcher.daemon.logging.DaemonMessages; import org.gradle.launcher.daemon.protocol.Build; import org.gradle.launcher.daemon.server.api.DaemonCommandExecution; import org.gradle.launcher.daemon.server.api.DaemonConnection; import org.gradle.logging.internal.LoggingOutputInternal; import org.gradle.logging.internal.OutputEvent; import org.gradle.logging.internal.OutputEventListener; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; public class LogToClient extends BuildCommandOnly { public static final String DISABLE_OUTPUT = "org.gradle.daemon.disable-output"; private static final Logger LOGGER = Logging.getLogger(LogToClient.class); private final LoggingOutputInternal loggingOutput; private final DaemonDiagnostics diagnostics; private volatile AsynchronousLogDispatcher dispatcher; public LogToClient(LoggingOutputInternal loggingOutput, DaemonDiagnostics diagnostics) { this.loggingOutput = loggingOutput; this.diagnostics = diagnostics; } protected void doBuild(final DaemonCommandExecution execution, Build build) { if (Boolean.getBoolean(DISABLE_OUTPUT)) { execution.proceed(); return; } dispatcher = new AsynchronousLogDispatcher(execution.getConnection(), build.getParameters().getLogLevel()); LOGGER.info("{}{}). The daemon log file: {}", DaemonMessages.STARTED_RELAYING_LOGS, diagnostics.getPid(), diagnostics.getDaemonLog()); dispatcher.start(); try { execution.proceed(); } finally { dispatcher.waitForCompletion(); } } private class AsynchronousLogDispatcher extends Thread { private final CountDownLatch completionLock = new CountDownLatch(1); private final BlockingQueue<OutputEvent> eventQueue = new LinkedBlockingDeque<OutputEvent>(); private final DaemonConnection connection; private final OutputEventListener listener; private volatile boolean shouldStop; private boolean unableToSend; private AsynchronousLogDispatcher(DaemonConnection conn, final LogLevel buildLogLevel) { super("Asynchronous log dispatcher for " + conn); this.connection = conn; this.listener = new OutputEventListener() { public void onOutput(OutputEvent event) { if (event.getLogLevel() != null && event.getLogLevel().compareTo(buildLogLevel) >= 0) { dispatcher.submit(event); } } }; LOGGER.debug(DaemonMessages.ABOUT_TO_START_RELAYING_LOGS); loggingOutput.addOutputEventListener(listener); } public void submit(OutputEvent event) { eventQueue.add(event); } @Override public void run() { OutputEvent event; try { while (!shouldStop) { // we must not use interrupt() because it would automatically // close the connection (sending data from an interrupted thread // automatically closes the connection) event = eventQueue.poll(10, TimeUnit.MILLISECONDS); if (event != null) { dispatchAsync(event); } } } catch (InterruptedException ex) { shouldStop = true; } sendRemainingEvents(); completionLock.countDown(); } private void sendRemainingEvents() { OutputEvent event; while ((event = eventQueue.poll()) != null) { dispatchAsync(event); } } private void dispatchAsync(OutputEvent event) { if (unableToSend) { return; } try { connection.logEvent(event); } catch (Exception ex) { shouldStop = true; unableToSend = true; //Ignore. It means the client has disconnected so no point sending him any log output. //we should be checking if client still listens elsewhere anyway. } } public void waitForCompletion() { loggingOutput.removeOutputEventListener(listener); shouldStop = true; try { completionLock.await(); } catch (InterruptedException e) { // the caller has been interrupted } } } }
mit
nkgwer/Pong2
StartFrameS.java
2237
import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComboBox; import javax.swing.JPanel; // PongServer向けスタート画面: 自分の名前と、対戦人数を指定する。 public class StartFrameS extends StartFrame implements ActionListener { PongServer pongServer; JPanel p1, p2, p3; JComboBox<String> textField2; private final String[] COMBO_DATA = { "2", "3", "4", "5", "6", "7", "8" }; // コンボボックスの選択肢 boolean isAccept; // 対戦相手を受付中 public StartFrameS(PongServer nps) { super(); this.pongServer = nps; this.isAccept = false; this.menuItem[0].setEnabled(false); // Setting labels this.upperLabel.setText("Input Your Name and Number of Players:"); this.label2.setText("Number of Players:"); // Setting combobox of number of players this.textField2 = new JComboBox<String>(this.COMBO_DATA); // 自分も含めた対戦人数のコンボボックス this.textField2.setPreferredSize(this.LABEL_SIZE); // JPanel p3: setting 2 labels, a textfield and a combobox this.p3 = new JPanel(); this.p3.setLayout(new GridLayout(2, 2)); this.p3.add(this.label1); this.p3.add(this.textField1); this.p3.add(this.label2); this.p3.add(this.textField2); // JPanel p2: setting p3 and log's scrollpane this.p2 = new JPanel(); this.p2.setLayout(null); this.p2.add(this.p3); this.p2.add(this.scrollpane); this.p3.setBounds(0, 0, 400, 60); this.scrollpane.setBounds(0, 60, 400, 200); // JPanel p1: setting upper label, p2 and button this.p1 = new JPanel(); this.p1.setLayout(null); this.p1.add(this.upperLabel); this.p1.add(this.p2); this.p1.add(this.btn); this.upperLabel.setBounds(120, 0, 400, 40); this.p2.setBounds(120, 30, 400, 260); this.btn.setBounds(290, 300, 60, 30); // container: setting p1 this.container.add(this.p1, BorderLayout.CENTER); } // ボタンが押されたときの動作 public void actionPerformed(ActionEvent e) { super.actionPerformed(e); Object obj = e.getSource(); if (obj == this.btn) { this.textField2.setEnabled(false); this.upperLabel.setText("Waiting for players..."); } } }
mit
smtchahal/RegexTester
app/src/main/java/smtchahal/regextester/MainActivity.java
30989
package smtchahal.regextester; import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.text.style.TypefaceSpan; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener { private static final String PACKAGE_NAME = "sumit.regextester"; private static final String LOG_TAG = "MainActivity"; private static final String PREF_NAME = PACKAGE_NAME; private static final String PREFS_STRING_SUBJECT = PACKAGE_NAME + ".Subject"; private static final String PREFS_STRING_PATTERN = PACKAGE_NAME + ".Pattern"; private static final String PREFS_STRING_JSON_SAVED_REGEXES = PACKAGE_NAME + ".JsonSavedRegexes"; private static final String PREFS_BOOL_CASE_INSENSITIVE = PACKAGE_NAME + ".CaseInsensitive"; private static final String PREFS_BOOL_UNIX = PACKAGE_NAME + ".Unix"; private static final String PREFS_BOOL_COMMENTS = PACKAGE_NAME + ".Comments"; private static final String PREFS_BOOL_DOT_ALL = PACKAGE_NAME + ".DotAll"; private static final String PREFS_BOOL_LITERAL = PACKAGE_NAME + ".Literal"; private static final String PREFS_BOOL_MULTILINE = PACKAGE_NAME + ".Multline"; private static final String PREFS_INT_MATCH = PACKAGE_NAME + ".Match"; private static final String PREFS_BOOL_PERM_DENIED = PACKAGE_NAME + ".PermissionDenied"; private String initialJsonArrayString = "[]"; private FloatingActionButton findButton; private FloatingActionButton saveButton; private EditText patternEditText; private EditText subjectEditText; private SharedPreferences prefs; private SharedPreferences.Editor prefsEditor; private CoordinatorLayout mainClayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); subjectEditText = (EditText) findViewById(R.id.subject_edittext); patternEditText = (EditText) findViewById(R.id.pattern_edittext); findButton = (FloatingActionButton) findViewById(R.id.find_button); saveButton = (FloatingActionButton) findViewById(R.id.save_button); mainClayout = (CoordinatorLayout) findViewById(R.id.activity_main_clayout); prefs = this.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); prefsEditor = prefs.edit(); findButton.setOnClickListener(this); saveButton.setOnClickListener(this); findButton.setOnLongClickListener(this); saveButton.setOnLongClickListener(this); // Reset this value each time onCreate() is called prefsEditor.putInt(PREFS_INT_MATCH, -1); prefsEditor.commit(); try { InputStream is = getAssets().open("regex_values_preset.json"); StringBuilder buf = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); String str; while ((str = in.readLine()) != null) { str += "\n"; buf.append(str); } in.close(); initialJsonArrayString = buf.toString(); } catch (IOException e) { Log.d(LOG_TAG, "IOException, e.getMessage() = " + e.getMessage()); String messageLiteral = getResources().getString(R.string.io_exception_toast_message); String message = String.format(messageLiteral, e.getMessage()); Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } } @Override public void onResume() { super.onResume(); restoreValues(); // After restoring saved values, check if intent was received // containing required selectedPatternText from ViewSavedRegexesActivity Intent intent = getIntent(); //notnull Bundle bundle = intent.getExtras(); if (bundle != null) { for (String key : bundle.keySet()) { Object value = bundle.get(key); if (value != null) Log.d(LOG_TAG, key + " = " + value.toString() + "; " + value.getClass().getName()); } } // Handle explicit intent from ViewSavedRegexesActivity //noinspection ConstantConditions String selectedPatternValue; if ((selectedPatternValue = intent.getStringExtra(PACKAGE_NAME + ".SelectedPatternText")) != null) { patternEditText.setText(selectedPatternValue); } // Handle implicit intents handleImplicitIntents(); } private void handleImplicitIntents() { Intent intent = getIntent(); String action = intent.getAction(); Bundle bundle = intent.getExtras(); // Share action if (Intent.ACTION_SEND.equals(action)) { String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT); if (sharedText == null) { Uri fileUri = null; if (bundle != null) { fileUri = (Uri) bundle.get(Intent.EXTRA_STREAM); } // If a file was "shared" if (fileUri != null) { Log.d(LOG_TAG, "fileUri = " + fileUri); String fileUriString = fileUri.toString(); String filePath = fileUriString.substring("file://".length(), fileUriString.length()); Log.d(LOG_TAG, "filePath = " + filePath); // Marshmallow+: If permission not granted... if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !prefs.getBoolean(PREFS_BOOL_PERM_DENIED, false) && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // ...request it ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1); } else if (prefs.getBoolean(PREFS_BOOL_PERM_DENIED, false)) { Snackbar.make(mainClayout, R.string.permission_grant_failed, Snackbar.LENGTH_LONG) .setAction(R.string.snackbar_button_dismiss, null) .show(); } else { try { sharedText = getStringFromFile(filePath); if (sharedText != null) { subjectEditText.setText(sharedText); Log.d(LOG_TAG, "Logging sharedText below..."); Log.d(LOG_TAG, sharedText); } else { Log.d(LOG_TAG, "sharedText is null"); } } catch (Exception e) { e.printStackTrace(); } } } } else { subjectEditText.setText(sharedText); Log.d(LOG_TAG, "Logging sharedText below..."); Log.d(LOG_TAG, sharedText); } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case 1: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d(LOG_TAG, "Permission granted"); prefsEditor.putBoolean(PREFS_BOOL_PERM_DENIED, false); prefsEditor.commit(); handleImplicitIntents(); } else { Log.d(LOG_TAG, "Permission denied"); prefsEditor.putBoolean(PREFS_BOOL_PERM_DENIED, true); prefsEditor.commit(); } } } } public static String convertStreamToString(InputStream is) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } reader.close(); return sb.toString(); } public static String getStringFromFile(String filePath) throws Exception { File fl = new File(filePath); FileInputStream fin = new FileInputStream(fl); String ret = convertStreamToString(fin); // Make sure you close all streams. fin.close(); return ret; } // Restore values saved in SharedPreferences // Note that the BOOL values of menu checkboxes aren't included, // they will be handled in separate methods private void restoreValues() { String subjectPresetValue = prefs.getString(PREFS_STRING_SUBJECT, ""); String patternPresetValue = prefs.getString(PREFS_STRING_PATTERN, ""); // Don't restore values if both strings are empty if (subjectPresetValue.length() != 0 || patternPresetValue.length() != 0) { subjectEditText.setText(subjectPresetValue); patternEditText.setText(patternPresetValue); } } @Override public void onPause() { super.onPause(); savePrefs(); } // Save preferences // Note that the BOOL values of menu checkboxes aren't included, // they will be handled in separate methods private void savePrefs() { prefsEditor.putString(PREFS_STRING_SUBJECT, subjectEditText.getText().toString()); prefsEditor.putString(PREFS_STRING_PATTERN, patternEditText.getText().toString()); prefsEditor.putBoolean(PREFS_BOOL_PERM_DENIED, false); prefsEditor.commit(); prefsEditor.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); restoreMenuValues(menu); return true; } // Menu checkboxes are restored here private void restoreMenuValues(Menu menu) { boolean caseInsensitiveChecked = prefs.getBoolean(PREFS_BOOL_CASE_INSENSITIVE, false); boolean unixChecked = prefs.getBoolean(PREFS_BOOL_UNIX, false); boolean commentsChecked = prefs.getBoolean(PREFS_BOOL_COMMENTS, false); boolean dotAllChecked = prefs.getBoolean(PREFS_BOOL_DOT_ALL, false); boolean literalChecked = prefs.getBoolean(PREFS_BOOL_LITERAL, false); boolean multiLineChecked = prefs.getBoolean(PREFS_BOOL_MULTILINE, false); menu.findItem(R.id.case_insensitive_checkbox).setChecked(caseInsensitiveChecked); menu.findItem(R.id.unix_lines_checkbox).setChecked(unixChecked); menu.findItem(R.id.comments_checkbox).setChecked(commentsChecked); menu.findItem(R.id.dot_all_checkbox).setChecked(dotAllChecked); menu.findItem(R.id.literal_checkbox).setChecked(literalChecked); menu.findItem(R.id.multiline_checkbox).setChecked(multiLineChecked); } @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(); // If item is checkable if (item.isCheckable()) { boolean checked = !item.isChecked(); // Switch state (unchecked -> checked, checked -> unchecked) item.setChecked(checked); // Save these preferences saveMenuPrefs(item); return true; } switch (id) { case R.id.action_menu_about: // Action "About" startAboutActivity(); break; case R.id.action_menu_view_saved_regexes: // Action "View saved regexes startViewSavedRegexesActivity(); break; } return super.onOptionsItemSelected(item); } private void startViewSavedRegexesActivity() { Intent intent = new Intent(this, ViewSavedRegexesActivity.class); startActivity(intent); } private void startAboutActivity() { Intent intent = new Intent(this, AboutActivity.class); startActivity(intent); } private void saveMenuPrefs(MenuItem item) { // Don't invert the boolean this time // it has already been inverted boolean checked = item.isChecked(); int id = item.getItemId(); switch (id) { case R.id.case_insensitive_checkbox: prefsEditor.putBoolean(PREFS_BOOL_CASE_INSENSITIVE, checked); prefsEditor.commit(); break; case R.id.unix_lines_checkbox: prefsEditor.putBoolean(PREFS_BOOL_UNIX, checked); prefsEditor.commit(); break; case R.id.comments_checkbox: prefsEditor.putBoolean(PREFS_BOOL_COMMENTS, checked); prefsEditor.commit(); break; case R.id.dot_all_checkbox: prefsEditor.putBoolean(PREFS_BOOL_DOT_ALL, checked); prefsEditor.commit(); break; case R.id.literal_checkbox: prefsEditor.putBoolean(PREFS_BOOL_LITERAL, checked); prefsEditor.commit(); break; case R.id.multiline_checkbox: prefsEditor.putBoolean(PREFS_BOOL_MULTILINE, checked); prefsEditor.commit(); break; } } private void onFindClick() { // Get flags int flags = 0; if (prefs.getBoolean(PREFS_BOOL_CASE_INSENSITIVE, false)) flags |= Pattern.CASE_INSENSITIVE; if (prefs.getBoolean(PREFS_BOOL_UNIX, false)) flags |= Pattern.UNIX_LINES; if (prefs.getBoolean(PREFS_BOOL_COMMENTS, false)) flags |= Pattern.COMMENTS; if (prefs.getBoolean(PREFS_BOOL_DOT_ALL, false)) flags |= Pattern.DOTALL; if (prefs.getBoolean(PREFS_BOOL_LITERAL, false)) flags |= Pattern.LITERAL; if (prefs.getBoolean(PREFS_BOOL_MULTILINE, false)) flags |= Pattern.MULTILINE; String subject = subjectEditText.getText().toString(); String patternText = patternEditText.getText().toString(); try { RegexFind regexFind = new RegexFind(subject, patternText, flags); // If match was found if (regexFind.matchFound()) { // Get indices where the matches were found int[][] matchesIndices = regexFind.getIndices(); // Number of times the user pressed find button int count = 0; // If this is the first time the user clicked // the find button if (prefs.getInt(PREFS_INT_MATCH, -1) == -1) { prefsEditor.putInt(PREFS_INT_MATCH, count); prefsEditor.commit(); // If patternEditText already has focus // requestFocus() from subjectEditText // to steal focus away temporarily if (subjectEditText.hasFocus()) patternEditText.requestFocus(); // Now request focus, make a toast // if request failed if (!subjectEditText.requestFocus()) Toast.makeText(this, R.string.cannot_request_focus_err_msg, Toast.LENGTH_SHORT).show(); // Select the first match subjectEditText.setSelection(matchesIndices[0][0], matchesIndices[0][1]); } else { // Increment count by 1 // After the above if structure, // and after the below statement, // count should be equal to 0 // after that it keeps incrementing on each click // until it equals matchesIndices.length (see below) count = prefs.getInt(PREFS_INT_MATCH, -1) + 1; // count must never exceed matchesIndices.length if (count < matchesIndices.length) { // If patternEditText already has focus // requestFocus() from subjectEditText // to steal focus away temporarily if (subjectEditText.hasFocus()) patternEditText.requestFocus(); // Now request focus, make a toast // if request failed if (!subjectEditText.requestFocus()) Toast.makeText(this, R.string.cannot_request_focus_err_msg, Toast.LENGTH_SHORT).show(); // Select (count)th match subjectEditText.setSelection(matchesIndices[count][0], matchesIndices[count][1]); // Save the value of count into prefs prefsEditor.putInt(PREFS_INT_MATCH, count); prefsEditor.commit(); } else { // if count == matchesIndices.length // reset the counter... prefsEditor.putInt(PREFS_INT_MATCH, -1); prefsEditor.commit(); // ...and display a toast message Toast.makeText(this, R.string.reached_bottom, Toast.LENGTH_SHORT).show(); // also set the selection to the first char subjectEditText.setSelection(0); } } } else { // if no matches found // log it... Log.d(LOG_TAG, "No matches found"); // ...and display a snackbar Snackbar.make(mainClayout, R.string.no_matches_found, Snackbar.LENGTH_SHORT) .setAction(R.string.snackbar_button_dismiss, new View.OnClickListener() { @Override public void onClick(View v) {} }) .show(); } } catch (PatternSyntaxException e) { // If pattern contains syntax errors AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.syntax_error_title); // The position of the bad character // causing syntax error int index = e.getIndex(); // Description of the error in the form // "%1$s near index %2$d" String description = String.format( this.getResources().getString(R.string.syntax_error_description), e.getDescription(), index); String pattern = e.getPattern(); // The complete message, before adding // ForegroundColorSpan String str = description + pattern; // Add a span for the bad character causing syntax error SpannableStringBuilder message = new SpannableStringBuilder(str); int color = ContextCompat.getColor(this, R.color.red500); // Set the span message.setSpan(new ForegroundColorSpan(color), description.length() + index - 1, // before the bad character description.length() + index, // right after the bad character Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // Change the fontStyle of the pattern to monospace message.setSpan(new TypefaceSpan("monospace"), description.length(), message.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // Show dialog builder.setMessage(message); builder.setPositiveButton(R.string.syntax_error_button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.show(); } } @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.find_button: onFindClick(); break; case R.id.save_button: onSaveClick(); break; } } private void onSaveClick() { // Create a new AlertDialog.Builder final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.save_regex_title); // Get patternText String patternText = patternEditText.getText().toString(); // Get view to set for the Builder final View view = LayoutInflater.from(this).inflate(R.layout.save_confirm_dialog, null); AutoCompleteTextView keyEditText = (AutoCompleteTextView) view.findViewById(R.id.save_regex_key_edittext); final TextView textView = (TextView) view.findViewById(R.id.save_regex_pre_message_textview); try { // Get the JSON-encoded preferences MyJSONArray jsonArray = new MyJSONArray(prefs.getString(PREFS_STRING_JSON_SAVED_REGEXES, initialJsonArrayString)); String[] keys = jsonArray.getKeys(); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, keys); keyEditText.setAdapter(adapter); } catch (JSONException e) { Log.d(LOG_TAG, "JSONException, this shouldn't have happened..."); e.printStackTrace(); Toast.makeText(this, R.string.json_exception_toast_message, Toast.LENGTH_LONG); } // Get literal message string from resources String messageLiteral = getResources().getString(R.string.save_confirm_text); // Create a SpannableStringBuilder SpannableStringBuilder message = new SpannableStringBuilder(String.format(messageLiteral, patternText)); // Start and end points for the pattern // to change its style to monospace int start = message.toString().indexOf('"'); int end = start + patternText.length(); // Set span message.setSpan(new TypefaceSpan("monospace"), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // Change text of the textView textView.setText(message); // Set the Builder's view builder.setView(view); builder.setPositiveButton(R.string.save_regex_button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final EditText editText = (EditText) view.findViewById(R.id.save_regex_key_edittext); // Get key and value pairs final String key = editText.getText().toString(); final String value = patternEditText.getText().toString(); // If the key entered was empty, // display a toast with error message // and return if (key.length() == 0) { Snackbar.make(mainClayout, R.string.key_cannot_be_empty, Snackbar.LENGTH_LONG) .setAction(R.string.generic_button_ok, new View.OnClickListener() { @Override public void onClick(View v) {} }) .show(); return; } try { final MyJSONArray jsonArray = new MyJSONArray(prefs.getString(PREFS_STRING_JSON_SAVED_REGEXES, initialJsonArrayString)); final JSONObject jsonObject = new JSONObject(); jsonObject.put(key, value); // Get the index of the matching key in MyJSONArray final int keyIndex = jsonArray.getIndexOfKey(key); // If the key was found if (keyIndex >= 0) { JSONObject jsonOldObject = jsonArray.optJSONObject(keyIndex); AlertDialog.Builder builder2 = new AlertDialog.Builder(MainActivity.this); final String dialogTitle = String.format(getResources() .getString(R.string.key_exists_title), key); final String dialogMessageString = String.format(getResources() .getString(R.string.key_exists_message), key, jsonOldObject.getString(key)); final SpannableStringBuilder dialogMessage = new SpannableStringBuilder(dialogMessageString); int start = dialogMessageString.length() - jsonOldObject.getString(key).length(); int end = dialogMessage.toString().length(); dialogMessage.setSpan(new TypefaceSpan("monospace"), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); builder2.setTitle(dialogTitle); builder2.setMessage(dialogMessage); builder2.setPositiveButton(R.string.key_exists_button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MyJSONArray jsonArrayNew = jsonArray.remove(keyIndex); jsonArrayNew.put(jsonObject); prefsEditor.putString(PREFS_STRING_JSON_SAVED_REGEXES, jsonArrayNew.toString()); prefsEditor.commit(); // Make a snackbar, telling the user // that the regex has been saved successfully Snackbar.make(mainClayout, R.string.regex_saved_success_message, Snackbar.LENGTH_SHORT) .setAction(R.string.snackbar_button_dismiss, new View.OnClickListener() { @Override public void onClick(View v) {} }) .show(); } }); builder2.setNegativeButton(R.string.key_exists_button_cancel, null); builder2.show(); } else { jsonArray.put(jsonObject); prefsEditor.putString(PREFS_STRING_JSON_SAVED_REGEXES, jsonArray.toString()); Log.d(LOG_TAG, "Saving to prefs: jsonArray = " + jsonArray.toString()); prefsEditor.commit(); // Make a snackbar, telling the user // that the regex has been saved successfully Snackbar.make(mainClayout, R.string.regex_saved_success_message, Snackbar.LENGTH_SHORT) .setAction(R.string.snackbar_button_dismiss, new View.OnClickListener() { @Override public void onClick(View v) {} }) .show(); } } catch (JSONException e) { Toast.makeText(MainActivity.this, R.string.json_exception_toast_message, Toast.LENGTH_LONG).show(); Log.d(LOG_TAG, "JSONException, this shouldn't have happened..."); e.printStackTrace(); } } }); builder.setNegativeButton(R.string.save_regex_button_cancel, null); builder.show(); } @Override public boolean onLongClick(View v) { int id = v.getId(); switch (id) { case R.id.find_button: AnchoredToast.makeText(findButton, this, R.string.find_button_text, AnchoredToast.LENGTH_SHORT) .show(); break; case R.id.save_button: AnchoredToast.makeText(saveButton, this, R.string.save_button_text, AnchoredToast.LENGTH_SHORT) .show(); break; } return true; } }
mit
zutnop/telekom-workflow-engine
telekom-workflow-engine/src/test/java/ee/telekom/workflow/graph/node/gateway/_03_SynchronizationTest.java
1525
package ee.telekom.workflow.graph.node.gateway; import org.junit.Test; import ee.telekom.workflow.graph.AbstractGraphTest; import ee.telekom.workflow.graph.GraphFactory; public class _03_SynchronizationTest extends AbstractGraphTest{ @Test public void one(){ assertExecution( GraphFactory.INSTANCE.synchronzation_one(), "2" ); } @Test public void two(){ assertExecution( GraphFactory.INSTANCE.synchronzation_two(), "2,3" ); } @Test public void three(){ assertExecution( GraphFactory.INSTANCE.synchronzation_three(), "2,3,4" ); } @Test public void two_firstBranchEmpty(){ assertExecution( GraphFactory.INSTANCE.synchronzation_two_firstBranchEmpty(), "2" ); } @Test public void two_secondBranchEmpty(){ assertExecution( GraphFactory.INSTANCE.synchronzation_two_secondBranchEmpty(), "2" ); } @Test public void two_bothBranchesEmpty(){ assertExecution( GraphFactory.INSTANCE.synchronzation_two_bothBranchesEmpty(), null ); } @Test public void two_pre_post(){ assertExecution( GraphFactory.INSTANCE.synchronzation_two_pre_post(), "1,3,4,6" ); } @Test public void firstBranchEmpty_pre_post(){ assertExecution( GraphFactory.INSTANCE.synchronization_firstBranchEmpty_pre_post(), "1,3,6" ); } @Test public void secondBranchEmpty_pre_post(){ assertExecution( GraphFactory.INSTANCE.synchronization_secondBranchEmpty_pre_post(), "1,3,6" ); } }
mit
wszdwp/AlgorithmPractice
src/main/java/com/codingpan/leetcode/todo/LC728SelfDividingNumbers.java
943
package com.codingpan.leetcode.todo; import java.util.ArrayList; import java.util.List; public class LC728SelfDividingNumbers { // A self-dividing number is a number that is divisible by every digit it contains. // // For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == // 0. // // Also, a self-dividing number is not allowed to contain the digit zero. // // Given a lower and upper number bound, output a list of every possible self dividing number, // including the bounds if possible. // // Example 1: // Input: // left = 1, right = 22 // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] // Note: // // The boundaries of each input argument are 1 <= left <= right <= 10000. public List<Integer> selfDividingNumbers(int left, int right) { List<Integer> res = new ArrayList<Integer>(); return res; } }
mit
cliffano/swaggy-jenkins
clients/java-play-framework/generated/app/apimodels/PipelineStepImpl.java
6021
package apimodels; import apimodels.InputStepImpl; import apimodels.PipelineStepImpllinks; import com.fasterxml.jackson.annotation.*; import java.util.Set; import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; /** * PipelineStepImpl */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen", date = "2022-02-13T02:17:56.963279Z[Etc/UTC]") @SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) public class PipelineStepImpl { @JsonProperty("_class") private String propertyClass; @JsonProperty("_links") @Valid private PipelineStepImpllinks links; @JsonProperty("displayName") private String displayName; @JsonProperty("durationInMillis") private Integer durationInMillis; @JsonProperty("id") private String id; @JsonProperty("input") @Valid private InputStepImpl input; @JsonProperty("result") private String result; @JsonProperty("startTime") private String startTime; @JsonProperty("state") private String state; public PipelineStepImpl propertyClass(String propertyClass) { this.propertyClass = propertyClass; return this; } /** * Get propertyClass * @return propertyClass **/ public String getPropertyClass() { return propertyClass; } public void setPropertyClass(String propertyClass) { this.propertyClass = propertyClass; } public PipelineStepImpl links(PipelineStepImpllinks links) { this.links = links; return this; } /** * Get links * @return links **/ public PipelineStepImpllinks getLinks() { return links; } public void setLinks(PipelineStepImpllinks links) { this.links = links; } public PipelineStepImpl displayName(String displayName) { this.displayName = displayName; return this; } /** * Get displayName * @return displayName **/ public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public PipelineStepImpl durationInMillis(Integer durationInMillis) { this.durationInMillis = durationInMillis; return this; } /** * Get durationInMillis * @return durationInMillis **/ public Integer getDurationInMillis() { return durationInMillis; } public void setDurationInMillis(Integer durationInMillis) { this.durationInMillis = durationInMillis; } public PipelineStepImpl id(String id) { this.id = id; return this; } /** * Get id * @return id **/ public String getId() { return id; } public void setId(String id) { this.id = id; } public PipelineStepImpl input(InputStepImpl input) { this.input = input; return this; } /** * Get input * @return input **/ public InputStepImpl getInput() { return input; } public void setInput(InputStepImpl input) { this.input = input; } public PipelineStepImpl result(String result) { this.result = result; return this; } /** * Get result * @return result **/ public String getResult() { return result; } public void setResult(String result) { this.result = result; } public PipelineStepImpl startTime(String startTime) { this.startTime = startTime; return this; } /** * Get startTime * @return startTime **/ public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public PipelineStepImpl state(String state) { this.state = state; return this; } /** * Get state * @return state **/ public String getState() { return state; } public void setState(String state) { this.state = state; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PipelineStepImpl pipelineStepImpl = (PipelineStepImpl) o; return Objects.equals(propertyClass, pipelineStepImpl.propertyClass) && Objects.equals(links, pipelineStepImpl.links) && Objects.equals(displayName, pipelineStepImpl.displayName) && Objects.equals(durationInMillis, pipelineStepImpl.durationInMillis) && Objects.equals(id, pipelineStepImpl.id) && Objects.equals(input, pipelineStepImpl.input) && Objects.equals(result, pipelineStepImpl.result) && Objects.equals(startTime, pipelineStepImpl.startTime) && Objects.equals(state, pipelineStepImpl.state); } @Override public int hashCode() { return Objects.hash(propertyClass, links, displayName, durationInMillis, id, input, result, startTime, state); } @SuppressWarnings("StringBufferReplaceableByString") @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PipelineStepImpl {\n"); sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append(" links: ").append(toIndentedString(links)).append("\n"); sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n"); sb.append(" durationInMillis: ").append(toIndentedString(durationInMillis)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" input: ").append(toIndentedString(input)).append("\n"); sb.append(" result: ").append(toIndentedString(result)).append("\n"); sb.append(" startTime: ").append(toIndentedString(startTime)).append("\n"); sb.append(" state: ").append(toIndentedString(state)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
mit
cscotta/miso-java
jetty/extras/client/src/main/java/org/mortbay/jetty/client/HttpDestination.java
17963
//======================================================================== //Copyright 2006-2007 Mort Bay Consulting Pty. 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.mortbay.jetty.client; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import javax.servlet.http.Cookie; import org.mortbay.io.Buffer; import org.mortbay.io.ByteArrayBuffer; import org.mortbay.jetty.HttpHeaders; import org.mortbay.jetty.client.security.Authorization; import org.mortbay.jetty.client.security.SecurityListener; import org.mortbay.jetty.servlet.PathMap; import org.mortbay.log.Log; /** * @author Greg Wilkins * @author Guillaume Nodet */ public class HttpDestination { private ByteArrayBuffer _hostHeader; private final Address _address; private final LinkedList<HttpConnection> _connections = new LinkedList<HttpConnection>(); private final ArrayList<HttpConnection> _idle = new ArrayList<HttpConnection>(); private final HttpClient _client; private final boolean _ssl; private int _maxConnections; private int _pendingConnections=0; private ArrayBlockingQueue<Object> _newQueue = new ArrayBlockingQueue<Object>(10,true); private int _newConnection=0; private Address _proxy; private Authorization _proxyAuthentication; private PathMap _authorizations; private List<Cookie> _cookies; public void dump() throws IOException { synchronized (this) { System.err.println(this); System.err.println("connections="+_connections.size()); System.err.println("idle="+_idle.size()); System.err.println("pending="+_pendingConnections); for (HttpConnection c : _connections) { if (!c.isIdle()) c.dump(); } } } /* The queue of exchanged for this destination if connections are limited */ private LinkedList<HttpExchange> _queue=new LinkedList<HttpExchange>(); /* ------------------------------------------------------------ */ HttpDestination(HttpClient pool, Address address, boolean ssl, int maxConnections) { _client=pool; _address=address; _ssl=ssl; _maxConnections=maxConnections; String addressString = address.getHost(); if (address.getPort() != (_ssl ? 443 : 80)) addressString += ":" + address.getPort(); _hostHeader = new ByteArrayBuffer(addressString); } /* ------------------------------------------------------------ */ public Address getAddress() { return _address; } /* ------------------------------------------------------------ */ public Buffer getHostHeader() { return _hostHeader; } /* ------------------------------------------------------------ */ public HttpClient getHttpClient() { return _client; } /* ------------------------------------------------------------ */ public boolean isSecure() { return _ssl; } /* ------------------------------------------------------------ */ public int getConnections() { synchronized (this) { return _connections.size(); } } /* ------------------------------------------------------------ */ public int getIdleConnections() { synchronized (this) { return _idle.size(); } } /* ------------------------------------------------------------ */ public void addAuthorization(String pathSpec,Authorization authorization) { synchronized (this) { if (_authorizations==null) _authorizations=new PathMap(); _authorizations.put(pathSpec,authorization); } // TODO query and remove methods } /* ------------------------------------------------------------------------------- */ public void addCookie(Cookie cookie) { synchronized (this) { if (_cookies==null) _cookies=new ArrayList<Cookie>(); _cookies.add(cookie); } // TODO query, remove and age methods } /* ------------------------------------------------------------------------------- */ /** * Get a connection. We either get an idle connection if one is available, or * we make a new connection, if we have not yet reached maxConnections. If we * have reached maxConnections, we wait until the number reduces. * @param timeout max time prepared to block waiting to be able to get a connection * @return * @throws IOException */ private HttpConnection getConnection(long timeout) throws IOException { HttpConnection connection = null; while ((connection == null) && (connection = getIdleConnection()) == null && timeout>0) { int totalConnections = 0; boolean starting = false; synchronized (this) { totalConnections = _connections.size() + _pendingConnections; if (totalConnections < _maxConnections) { _newConnection++; startNewConnection(); starting = true; } } if (!starting) { try { Thread.currentThread().sleep(200); timeout-=200; } catch (InterruptedException e) { Log.ignore(e); } } else { try { Object o = _newQueue.take(); if (o instanceof HttpConnection) { connection = (HttpConnection)o; } else throw (IOException)o; } catch (InterruptedException e) { Log.ignore(e); } } } return connection; } /* ------------------------------------------------------------------------------- */ public HttpConnection reserveConnection(long timeout) throws IOException { HttpConnection connection = getConnection(timeout); if (connection != null) connection.setReserved(true); return connection; } /* ------------------------------------------------------------------------------- */ public HttpConnection getIdleConnection() throws IOException { long now = _client.getNow(); long idleTimeout=_client.getIdleTimeout(); HttpConnection connection = null; while (true) { synchronized (this) { if (connection!=null) { _connections.remove(connection); connection.close(); connection=null; } if (_idle.size() > 0) connection = _idle.remove(_idle.size()-1); } if (connection==null) return null; if (connection.cancelIdleTimeout() ) return connection; } } /* ------------------------------------------------------------------------------- */ protected void startNewConnection() { try { synchronized (this) { _pendingConnections++; } _client._connector.startConnection(this); } catch(Exception e) { Log.debug(e); onConnectionFailed(e); } } /* ------------------------------------------------------------------------------- */ public void onConnectionFailed(Throwable throwable) { Throwable connect_failure=null; synchronized (this) { _pendingConnections--; if (_newConnection>0) { connect_failure=throwable; _newConnection--; } else if (_queue.size()>0) { HttpExchange ex=_queue.removeFirst(); ex.setStatus(HttpExchange.STATUS_EXCEPTED); ex.getEventListener().onConnectionFailed(throwable); } } if(connect_failure!=null) { try { _newQueue.put(connect_failure); } catch (InterruptedException e) { Log.ignore(e); } } } /* ------------------------------------------------------------------------------- */ public void onException(Throwable throwable) { synchronized (this) { _pendingConnections--; if (_queue.size()>0) { HttpExchange ex=_queue.removeFirst(); ex.setStatus(HttpExchange.STATUS_EXCEPTED); ex.getEventListener().onException(throwable); } } } /* ------------------------------------------------------------------------------- */ public void onNewConnection(HttpConnection connection) throws IOException { HttpConnection q_connection=null; synchronized (this) { _pendingConnections--; _connections.add(connection); if (_newConnection>0) { q_connection=connection; _newConnection--; } else if (_queue.size()==0) { _idle.add(connection); } else { HttpExchange ex=_queue.removeFirst(); connection.send(ex); } } if (q_connection!=null) { try { _newQueue.put(q_connection); } catch (InterruptedException e) { Log.ignore(e); } } } /* ------------------------------------------------------------------------------- */ public void returnConnection(HttpConnection connection, boolean close) throws IOException { if (connection.isReserved()) connection.setReserved(false); if (close) { try { connection.close(); } catch(IOException e) { Log.ignore(e); } } if (!_client.isStarted()) return; if (!close && connection.getEndPoint().isOpen()) { synchronized (this) { if (_queue.size()==0) { connection.setIdleTimeout(_client.getNow()+_client.getIdleTimeout()); _idle.add(connection); } else { HttpExchange ex = _queue.removeFirst(); connection.send(ex); } this.notifyAll(); } } else { synchronized (this) { _connections.remove(connection); if (!_queue.isEmpty()) startNewConnection(); } } } /* ------------------------------------------------------------ */ public void returnIdleConnection(HttpConnection connection) throws IOException { try { connection.close(); } catch (IOException e) { Log.ignore(e); } synchronized (this) { _idle.remove(connection); _connections.remove(connection); if (!_queue.isEmpty() && _client.isStarted()) startNewConnection(); } } /* ------------------------------------------------------------ */ public void send(HttpExchange ex) throws IOException { LinkedList<String> listeners = _client.getRegisteredListeners(); if (listeners != null) { // Add registered listeners, fail if we can't load them for (int i = listeners.size(); i > 0; --i) { String listenerClass = listeners.get(i - 1); try { Class listener = Class.forName(listenerClass); Constructor constructor = listener.getDeclaredConstructor(HttpDestination.class, HttpExchange.class); HttpEventListener elistener = (HttpEventListener) constructor.newInstance(this, ex); ex.setEventListener(elistener); } catch (Exception e) { Log.debug(e); throw new IOException("Unable to instantiate registered listener for destination: " + listenerClass ); } } } // Security is supported by default and should be the first consulted if ( _client.hasRealms() ) { ex.setEventListener( new SecurityListener( this, ex ) ); } doSend(ex); } /* ------------------------------------------------------------ */ public void resend(HttpExchange ex) throws IOException { ex.getEventListener().onRetry(); ex.reset(); doSend(ex); } /* ------------------------------------------------------------ */ protected void doSend(HttpExchange ex) throws IOException { // add cookies // TODO handle max-age etc. if (_cookies!=null) { StringBuilder buf=null; for (Cookie cookie : _cookies) { if (buf==null) buf=new StringBuilder(); else buf.append("; "); buf.append(cookie.getName()); // TODO quotes buf.append("="); buf.append(cookie.getValue()); // TODO quotes } if (buf!=null) ex.addRequestHeader(HttpHeaders.COOKIE,buf.toString()); } // Add any known authorizations if (_authorizations!=null) { Authorization auth= (Authorization)_authorizations.match(ex.getURI()); if (auth !=null) ((Authorization)auth).setCredentials(ex); } HttpConnection connection = getIdleConnection(); if (connection != null) { boolean sent = connection.send(ex); if (!sent) connection = null; } if (connection == null) { synchronized (this) { _queue.add(ex); if (_connections.size() + _pendingConnections < _maxConnections) { startNewConnection(); } } } } /* ------------------------------------------------------------ */ public synchronized String toString() { return "HttpDestination@" + hashCode() + "//" + _address.getHost() + ":" + _address.getPort() + "(" + _connections.size() + "," + _idle.size() + "," + _queue.size() + ")"; } /* ------------------------------------------------------------ */ public synchronized String toDetailString() { StringBuilder b = new StringBuilder(); b.append(toString()); b.append('\n'); synchronized(this) { for (HttpConnection connection : _connections) { if (connection._exchange!=null) { b.append(connection.toDetailString()); if (_idle.contains(connection)) b.append(" IDLE"); b.append('\n'); } } } b.append("--"); b.append('\n'); return b.toString(); } /* ------------------------------------------------------------ */ public void setProxy(Address proxy) { _proxy=proxy; } /* ------------------------------------------------------------ */ public Address getProxy() { return _proxy; } /* ------------------------------------------------------------ */ public Authorization getProxyAuthentication() { return _proxyAuthentication; } /* ------------------------------------------------------------ */ public void setProxyAuthentication(Authorization authentication) { _proxyAuthentication = authentication; } /* ------------------------------------------------------------ */ public boolean isProxied() { return _proxy!=null; } /* ------------------------------------------------------------ */ public void close() throws IOException { synchronized (this) { for (HttpConnection connection : _connections) { connection.close(); } } } }
mit
gfneto/Hive2Hive
org.hive2hive.core/src/test/java/org/hive2hive/core/security/PasswordUtilTest.java
6376
package org.hive2hive.core.security; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Arrays; import javax.crypto.SecretKey; import org.hive2hive.core.H2HJUnitTest; import org.hive2hive.core.security.EncryptionUtil.AES_KEYLENGTH; import org.junit.BeforeClass; import org.junit.Test; public class PasswordUtilTest extends H2HJUnitTest { @BeforeClass public static void initTest() throws Exception { testClass = PasswordUtilTest.class; beforeClass(); } @Test public void generateSaltTest() { byte[][] salt = new byte[100][]; for (int i = 0; i < salt.length; i++) { // test salt generation salt[i] = PasswordUtil.generateRandomSalt(); assertNotNull(salt[i]); assertTrue(salt[i].length == PasswordUtil.SALT_BIT_SIZE / 8); logger.debug("Generated Salt: {}.", EncryptionUtil.byteToHex(salt[i])); // test whether salts are random for (int j = 0; j < i; j++) { assertFalse(Arrays.equals(salt[i], salt[j])); } } } @Test public void generateFixedSaltTest() { // test for different input byte[][] input = new byte[5][]; for (int i = 0; i < input.length; i++) { input[i] = randomString(15).getBytes(); logger.debug("Random Input: {}.", EncryptionUtil.byteToHex(input[i])); byte[][] fixedSalt = new byte[10][]; for (int j = 0; j < fixedSalt.length; j++) { // test fixed salt generation fixedSalt[j] = PasswordUtil.generateFixedSalt(input[i]); assertNotNull(fixedSalt[j]); assertTrue(fixedSalt[j].length == PasswordUtil.SALT_BIT_SIZE / 8); logger.debug("Generated Fixed Salt: {}.", EncryptionUtil.byteToHex(fixedSalt[j])); // test whether salts are equal for (int k = 0; k < j; k++) { assertTrue(Arrays.equals(fixedSalt[k], fixedSalt[j])); } } } } @Test public void generateAESKeyFromPasswordTest() { // test all key sizes AES_KEYLENGTH[] sizes = EncryptionUtilTest.getAESKeySizes(); for (int s = 0; s < sizes.length; s++) { // test various UserPasswords for (int i = 0; i < 3; i++) { String randomPW = randomString(20); String randomPIN = randomString(6); logger.debug("Testing {}-bit AES key generation from user password and PIN:", sizes[s].value()); logger.debug("Random PW: {}.", randomPW); logger.debug("Random PIN: {}.", randomPIN); // test the generation process multiple times to ensure consistent result SecretKey[] aesKey = new SecretKey[3]; for (int j = 0; j < aesKey.length; j++) { // generate AES key aesKey[j] = PasswordUtil.generateAESKeyFromPassword(randomPW, randomPIN, sizes[s]); assertNotNull(aesKey[j]); assertNotNull(aesKey[j].getEncoded()); assertTrue(aesKey[j].getEncoded().length == sizes[s].value() / 8); logger.debug("Generated {}-bit AES key: {}.", sizes[s].value(), EncryptionUtil.byteToHex(aesKey[j].getEncoded())); // test whether generated AES passwords are equal for (int k = 0; k < j; k++) { assertTrue(Arrays.equals(aesKey[k].getEncoded(), aesKey[j].getEncoded())); } } } } } @Test public void generateHashTest() { // test various passwords char[][] password = new char[5][]; for (int i = 0; i < password.length; i++) { // set a random password and salt password[i] = randomString(20).toCharArray(); byte[] salt = PasswordUtil.generateRandomSalt(); logger.debug("Tested Password: {}.", String.valueOf(password[i])); // test hash generation byte[] hash = PasswordUtil.generateHash(password[i], salt); assertNotNull(hash); assertTrue(hash.length == PasswordUtil.HASH_BIT_SIZE / 8); logger.debug("Generated Salt: {}.", EncryptionUtil.byteToHex(hash)); // test if hash outcome stays always the same with the same password and salt for (int j = 0; j < 5; j++) { assertTrue(Arrays.equals(hash, PasswordUtil.generateHash(password[i], salt))); } // test if hash outcome changes with other password or salt for (int j = 0; j < 5; j++) { // assure new parameters char[] otherPW; do { otherPW = randomString(20).toCharArray(); } while (Arrays.equals(otherPW, password[i])); byte[] otherSalt; do { otherSalt = PasswordUtil.generateRandomSalt(); } while (Arrays.equals(otherSalt, salt)); assertFalse(Arrays.equals(hash, PasswordUtil.generateHash(password[i], otherSalt))); assertFalse(Arrays.equals(hash, PasswordUtil.generateHash(otherPW, salt))); assertFalse(Arrays.equals(hash, PasswordUtil.generateHash(otherPW, otherSalt))); } } } @Test public void validatePasswordTest() { // test various passwords char[][] password = new char[10][]; for (int i = 0; i < password.length; i++) { // set a random password and salt password[i] = randomString(20).toCharArray(); byte[] salt = PasswordUtil.generateRandomSalt(); logger.debug("Validating password '{}' with salt '{}'.", String.valueOf(password[i]), EncryptionUtil.byteToHex(salt)); // generate hash byte[] hash = PasswordUtil.generateHash(password[i], salt); // validate password boolean isValid = PasswordUtil.validatePassword(password[i], salt, hash); assertTrue(isValid); // test validation with wrong password, salt or hash for (int j = 0; j < 3; j++) { // assure new parameters char[] otherPW; do { otherPW = randomString(20).toCharArray(); } while (Arrays.equals(otherPW, password[i])); byte[] otherSalt; do { otherSalt = PasswordUtil.generateRandomSalt(); } while (Arrays.equals(otherSalt, salt)); byte[] otherHash = null; do { otherHash = PasswordUtil.generateHash(randomString(20).toCharArray(), PasswordUtil.generateRandomSalt()); } while (Arrays.equals(otherHash, hash)); assertFalse(PasswordUtil.validatePassword(otherPW, salt, hash)); assertFalse(PasswordUtil.validatePassword(password[i], otherSalt, hash)); assertFalse(PasswordUtil.validatePassword(password[i], salt, otherHash)); assertFalse(PasswordUtil.validatePassword(otherPW, otherSalt, hash)); assertFalse(PasswordUtil.validatePassword(password[i], otherSalt, otherHash)); assertFalse(PasswordUtil.validatePassword(otherPW, salt, otherHash)); assertFalse(PasswordUtil.validatePassword(otherPW, otherSalt, otherHash)); } } } }
mit
vvrsk/Hacker-Rank-Solutions
Algorithms/Graph Theory/Roads and Libraries.java
2941
/* Roads and Libraries Algorithms Roads and Libraries - This was solved in reference to the discussions in the Hacker Rank. Thanks to @i_siddhant and @mohamedrefat007 */ import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { static long connectedComponents; static boolean[] isVisited; static ArrayList<Integer>[] adjCities; public static void main(String[] args) { Scanner in = new Scanner(System.in); int q = in.nextInt(); for(int a0 = 0; a0 < q; a0++){ //HashMap hm = new HashMap(); int cities = in.nextInt(); int roads = in.nextInt(); int clib = in.nextInt(); int croad = in.nextInt(); adjCities = (ArrayList<Integer>[]) new ArrayList[cities+1]; //Corner Case of low library cost // No roads. if(croad>clib||roads ==0){ long out = (long) clib * cities; System.out.println(out); for (int i = 0; i < (roads*2); i++){ in.nextInt(); } continue; } else{ adjCities = (ArrayList<Integer>[])new ArrayList[cities+1]; //Initializing all the elements of the Array for (int c = 0; c <= cities; c++){ adjCities[c] = new ArrayList<Integer>(); } isVisited = new boolean[cities+1]; for(int a1 = 0; a1 < roads; a1++){ int city_1 = in.nextInt(); int city_2 = in.nextInt(); //Adding a 2-way/ bi directional road between cities adjCities[city_1].add(city_2); adjCities[city_2].add(city_1); } for(int c = 1; c <= cities; c++) { if(!isVisited[c]) { dfs(c); connectedComponents++; } } long out = (long) croad * (cities - connectedComponents) + clib * connectedComponents; System.out.println(out); connectedComponents = 0; // isVisited = new boolean[cities]; // adjCities = (ArrayList<Integer>[]) new ArrayList[cities+1]; isVisited = new boolean[10000]; adjCities = (ArrayList<Integer>[]) new ArrayList[10000+1]; } } } private static void dfs(int city){ isVisited[city] = true; for (int c = 0; c < adjCities[city].size(); c++){ if(!isVisited[adjCities[city].get(c)]){ dfs(adjCities[city].get(c)); } } } }
mit