repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
joda17/Diorite-Core
src/main/java/org/diorite/impl/world/chunk/ChunkPartImpl.java
5658
package org.diorite.impl.world.chunk; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.diorite.material.BlockMaterialData; import org.diorite.material.Material; import org.diorite.utils.collections.arrays.NibbleArray; import org.diorite.utils.concurrent.atomic.AtomicShortArray; import org.diorite.world.chunk.Chunk; public class ChunkPartImpl // part of chunk 16x16x16 { public static final int CHUNK_DATA_SIZE = Chunk.CHUNK_SIZE * Chunk.CHUNK_PART_HEIGHT * Chunk.CHUNK_SIZE; private final byte yPos; // from 0 to 15 private volatile int blocksCount; private AtomicShortArray blocks; // id and sub-id(0-15) of every block private NibbleArray skyLight; private NibbleArray blockLight; public ChunkPartImpl(final byte yPos, final boolean hasSkyLight) { this.yPos = yPos; this.blocks = new AtomicShortArray(CHUNK_DATA_SIZE); this.blockLight = new NibbleArray(CHUNK_DATA_SIZE); if (hasSkyLight) { this.skyLight = new NibbleArray(CHUNK_DATA_SIZE); //noinspection MagicNumber this.skyLight.fill((byte) 0xf); } this.blockLight.fill((byte) 0x0); } public ChunkPartImpl(final AtomicShortArray blocks, final byte yPos, final boolean hasSkyLight) { this.blocks = blocks; this.blockLight = new NibbleArray(CHUNK_DATA_SIZE); this.yPos = yPos; if (hasSkyLight) { this.skyLight = new NibbleArray(CHUNK_DATA_SIZE); //noinspection MagicNumber this.skyLight.fill((byte) 0xf); } this.blockLight.fill((byte) 0x0); } public ChunkPartImpl(final AtomicShortArray blocks, final NibbleArray skyLight, final NibbleArray blockLight, final byte yPos) { this.blocks = blocks; this.skyLight = skyLight; this.blockLight = blockLight; this.yPos = yPos; } /** * Take a snapshot of this section which will not reflect future changes. */ public ChunkPartImpl snapshot() { return new ChunkPartImpl(new AtomicShortArray(this.blocks.getArray()), this.skyLight.snapshot(), this.blockLight.snapshot(), this.yPos); } public BlockMaterialData setBlock(final int x, final int y, final int z, final int id, final int meta) { final BlockMaterialData old = this.getBlockType(x, y, z); if ((id == old.ordinal()) && (meta == old.getType())) { return old; } if (this.blocks.compareAndSet(toArrayIndex(x, y, z), (short) ((old.ordinal() << 4) | old.getType()), (short) ((id << 4) | meta))) { if (old.getType() != 0) { if (id == 0) { this.blocksCount--; } } else if (id != 0) { this.blocksCount++; } return old; } return this.getBlockType(x, y, z); } @SuppressWarnings("MagicNumber") public BlockMaterialData rawSetBlock(final int x, final int y, final int z, final int id, final int meta) { final short data = this.blocks.getAndSet(toArrayIndex(x, y, z), (short) ((id << 4) | meta)); final BlockMaterialData type = (BlockMaterialData) Material.getByID(data >> 4, data & 15); return (type == null) ? Material.AIR : type; } public BlockMaterialData setBlock(final int x, final int y, final int z, final BlockMaterialData material) { return this.setBlock(x, y, z, material.ordinal(), material.getType()); } @SuppressWarnings("MagicNumber") public BlockMaterialData getBlockType(final int x, final int y, final int z) { final short data = this.blocks.get(toArrayIndex(x, y, z)); final BlockMaterialData type = (BlockMaterialData) Material.getByID(data >> 4, data & 15); return (type == null) ? Material.AIR : type; } public AtomicShortArray getBlocks() { return this.blocks; } public void setBlocks(final AtomicShortArray blocks) { this.blocks = blocks; } public int recalculateBlockCount() { this.blocksCount = 0; for (final short type : this.blocks.getArray()) { if (type != 0) { this.blocksCount++; } } return this.blocksCount; } public int getBlocksCount() { return this.blocksCount; } public NibbleArray getBlockLight() { return this.blockLight; } public void setBlockLight(final NibbleArray blockLight) { this.blockLight = blockLight; } public NibbleArray getSkyLight() { return this.skyLight; } public void setSkyLight(final NibbleArray skyLight) { this.skyLight = skyLight; } public byte getYPos() { return this.yPos; } public boolean isEmpty() { return this.blocksCount == 0; } @SuppressWarnings("MagicNumber") public static int toArrayIndex(final int x, final int y, final int z) { return ((y & 0xf) << 8) | (z << 4) | x; } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("yPos", this.yPos).append("blocks", this.blocks).append("skyLight", this.skyLight).append("blockLight", this.blockLight).append("blocksCount", this.blocksCount).toString(); } }
mit
jgaltidor/VarJ
analyzed_libs/jdk1.6.0_06_src/java/util/concurrent/RunnableScheduledFuture.java
905
/* * @(#)RunnableScheduledFuture.java 1.3 06/01/30 * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package java.util.concurrent; /** * A {@link ScheduledFuture} that is {@link Runnable}. Successful * execution of the <tt>run</tt> method causes completion of the * <tt>Future</tt> and allows access to its results. * @see FutureTask * @see Executor * @since 1.6 * @author Doug Lea * @param <V> The result type returned by this Future's <tt>get</tt> method */ public interface RunnableScheduledFuture<V> extends RunnableFuture<V>, ScheduledFuture<V> { /** * Returns true if this is a periodic task. A periodic task may * re-run according to some schedule. A non-periodic task can be * run only once. * * @return true if this task is periodic */ boolean isPeriodic(); }
mit
audrius-a/smart-mirror
app/src/test/java/com/development/audrius/smartmirror/ExampleUnitTest.java
413
package com.development.audrius.smartmirror; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
mit
bacta/pre-cu
src/old/message/trade/AddItemMessage.java
149
package com.ocdsoft.bacta.swg.precu.message.trade; /** * Created by crush on 8/13/2014. */ public class AddItemMessage { //NetworkId object }
mit
jamesw6811/SpiritGame
IntelliJ/SpiritAndroid/src/com/spiritgame/GLText.java
29724
// This is a OpenGL ES 1.0 dynamic font rendering system. It loads actual font // files, generates a font map (texture) from them, and allows rendering of // text strings. // // NOTE: the rendering portions of this class uses a sprite batcher in order // provide decent speed rendering. Also, rendering assumes a BOTTOM-LEFT // origin, and the (x,y) positions are relative to that, as well as the // bottom-left of the string to render. package com.spiritgame; import javax.microedition.khronos.opengles.GL10; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Typeface; import android.opengl.GLUtils; public class GLText { //--Constants--// public final static int CHAR_START = 32; // First Character (ASCII Code) public final static int CHAR_END = 126; // Last Character (ASCII Code) public final static int CHAR_CNT = (((CHAR_END - CHAR_START) + 1) + 1); // Character Count (Including Character to use for Unknown) public final static int CHAR_NONE = 32; // Character to Use for Unknown (ASCII Code) public final static int CHAR_UNKNOWN = (CHAR_CNT - 1); // Index of the Unknown Character public final static int FONT_SIZE_MIN = 6; // Minumum Font Size (Pixels) public final static int FONT_SIZE_MAX = 180; // Maximum Font Size (Pixels) public final static int CHAR_BATCH_SIZE = 100; // Number of Characters to Render Per Batch //--Members--// GL10 gl; // GL10 Instance AssetManager assets; // Asset Manager SpriteBatch batch; // Batch Renderer int fontPadX, fontPadY; // Font Padding (Pixels; On Each Side, ie. Doubled on Both X+Y Axis) float fontHeight; // Font Height (Actual; Pixels) float fontAscent; // Font Ascent (Above Baseline; Pixels) float fontDescent; // Font Descent (Below Baseline; Pixels) int textureId; // Font Texture ID [NOTE: Public for Testing Purposes Only!] int textureSize; // Texture Size for Font (Square) [NOTE: Public for Testing Purposes Only!] TextureRegion textureRgn; // Full Texture Region float charWidthMax; // Character Width (Maximum; Pixels) float charHeight; // Character Height (Maximum; Pixels) final float[] charWidths; // Width of Each Character (Actual; Pixels) TextureRegion[] charRgn; // Region of Each Character (Texture Coordinates) int cellWidth, cellHeight; // Character Cell Width/Height int rowCnt, colCnt; // Number of Rows/Columns float scaleX, scaleY; // Font Scale (X,Y Axis) float spaceX; // Additional (X,Y Axis) Spacing (Unscaled) //--Constructor--// // D: save GL instance + asset manager, create arrays, and initialize the members // A: gl - OpenGL ES 10 Instance public GLText(GL10 gl, AssetManager assets) { this.gl = gl; // Save the GL10 Instance this.assets = assets; // Save the Asset Manager Instance batch = new SpriteBatch(gl, CHAR_BATCH_SIZE); // Create Sprite Batch (with Defined Size) charWidths = new float[CHAR_CNT]; // Create the Array of Character Widths charRgn = new TextureRegion[CHAR_CNT]; // Create the Array of Character Regions // initialize remaining members fontPadX = 0; fontPadY = 0; fontHeight = 0.0f; fontAscent = 0.0f; fontDescent = 0.0f; textureId = -1; textureSize = 0; charWidthMax = 0; charHeight = 0; cellWidth = 0; cellHeight = 0; rowCnt = 0; colCnt = 0; scaleX = 1.0f; // Default Scale = 1 (Unscaled) scaleY = 1.0f; // Default Scale = 1 (Unscaled) spaceX = 0.0f; } public GLText(GL10 gl) { this.gl = gl; // Save the GL10 Instance batch = new SpriteBatch(gl, CHAR_BATCH_SIZE); // Create Sprite Batch (with Defined Size) charWidths = new float[CHAR_CNT]; // Create the Array of Character Widths charRgn = new TextureRegion[CHAR_CNT]; // Create the Array of Character Regions // initialize remaining members fontPadX = 0; fontPadY = 0; fontHeight = 0.0f; fontAscent = 0.0f; fontDescent = 0.0f; textureId = -1; textureSize = 0; charWidthMax = 0; charHeight = 0; cellWidth = 0; cellHeight = 0; rowCnt = 0; colCnt = 0; scaleX = 1.0f; // Default Scale = 1 (Unscaled) scaleY = 1.0f; // Default Scale = 1 (Unscaled) spaceX = 0.0f; } //--Load Font--// // description // this will load the specified font file, create a texture for the defined // character range, and setup all required values used to render with it. // arguments: // file - Filename of the font (.ttf, .otf) to use. In 'Assets' folder. // size - Requested pixel size of font (height) // padX, padY - Extra padding per character (X+Y Axis); to prevent overlapping characters. public boolean load(String file, int size, int padX, int padY) { // setup requested values fontPadX = padX; // Set Requested X Axis Padding fontPadY = padY; // Set Requested Y Axis Padding // load the font and setup paint instance for drawing Typeface tf = Typeface.createFromAsset(assets, file); // Create the Typeface from Font File Paint paint = new Paint(); // Create Android Paint Instance paint.setAntiAlias(true); // Enable Anti Alias paint.setTextSize(size); // Set Text Size paint.setColor(0xffffffff); // Set ARGB (White, Opaque) paint.setTypeface(tf); // Set Typeface // get font metrics Paint.FontMetrics fm = paint.getFontMetrics(); // Get Font Metrics fontHeight = (float) Math.ceil(Math.abs(fm.bottom) + Math.abs(fm.top)); // Calculate Font Height fontAscent = (float) Math.ceil(Math.abs(fm.ascent)); // Save Font Ascent fontDescent = (float) Math.ceil(Math.abs(fm.descent)); // Save Font Descent // determine the width of each character (including unknown character) // also determine the maximum character width char[] s = new char[2]; // Create Character Array charWidthMax = charHeight = 0; // Reset Character Width/Height Maximums float[] w = new float[2]; // Working Width Value int cnt = 0; // Array Counter for (char c = CHAR_START; c <= CHAR_END; c++) { // FOR Each Character s[0] = c; // Set Character paint.getTextWidths(s, 0, 1, w); // Get Character Bounds charWidths[cnt] = w[0]; // Get Width if (charWidths[cnt] > charWidthMax) // IF Width Larger Than Max Width charWidthMax = charWidths[cnt]; // Save New Max Width cnt++; // Advance Array Counter } s[0] = CHAR_NONE; // Set Unknown Character paint.getTextWidths(s, 0, 1, w); // Get Character Bounds charWidths[cnt] = w[0]; // Get Width if (charWidths[cnt] > charWidthMax) // IF Width Larger Than Max Width charWidthMax = charWidths[cnt]; // Save New Max Width cnt++; // Advance Array Counter // set character height to font height charHeight = fontHeight; // Set Character Height // find the maximum size, validate, and setup cell sizes cellWidth = (int) charWidthMax + (2 * fontPadX); // Set Cell Width cellHeight = (int) charHeight + (2 * fontPadY); // Set Cell Height int maxSize = cellWidth > cellHeight ? cellWidth : cellHeight; // Save Max Size (Width/Height) if (maxSize < FONT_SIZE_MIN || maxSize > FONT_SIZE_MAX) // IF Maximum Size Outside Valid Bounds return false; // Return Error // set texture size based on max font size (width or height) // NOTE: these values are fixed, based on the defined characters. when // changing start/end characters (CHAR_START/CHAR_END) this will need adjustment too! if (maxSize <= 24) // IF Max Size is 18 or Less textureSize = 256; // Set 256 Texture Size else if (maxSize <= 40) // ELSE IF Max Size is 40 or Less textureSize = 512; // Set 512 Texture Size else if (maxSize <= 80) // ELSE IF Max Size is 80 or Less textureSize = 1024; // Set 1024 Texture Size else // ELSE IF Max Size is Larger Than 80 (and Less than FONT_SIZE_MAX) textureSize = 2048; // Set 2048 Texture Size // create an empty bitmap (alpha only) Bitmap bitmap = Bitmap.createBitmap(textureSize, textureSize, Bitmap.Config.ALPHA_8); // Create Bitmap Canvas canvas = new Canvas(bitmap); // Create Canvas for Rendering to Bitmap bitmap.eraseColor(0x00000000); // Set Transparent Background (ARGB) // calculate rows/columns // NOTE: while not required for anything, these may be useful to have :) colCnt = textureSize / cellWidth; // Calculate Number of Columns rowCnt = (int) Math.ceil((float) CHAR_CNT / (float) colCnt); // Calculate Number of Rows // render each of the characters to the canvas (ie. build the font map) float x = fontPadX; // Set Start Position (X) float y = (cellHeight - 1) - fontDescent - fontPadY; // Set Start Position (Y) for (char c = CHAR_START; c <= CHAR_END; c++) { // FOR Each Character s[0] = c; // Set Character to Draw canvas.drawText(s, 0, 1, x, y, paint); // Draw Character x += cellWidth; // Move to Next Character if ((x + cellWidth - fontPadX) > textureSize) { // IF End of Line Reached x = fontPadX; // Set X for New Row y += cellHeight; // Move Down a Row } } s[0] = CHAR_NONE; // Set Character to Use for NONE canvas.drawText(s, 0, 1, x, y, paint); // Draw Character // generate a new texture int[] textureIds = new int[1]; // Array to Get Texture Id gl.glGenTextures(1, textureIds, 0); // Generate New Texture textureId = textureIds[0]; // Save Texture Id // setup filters for texture gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId); // Bind Texture gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); // Set Minification Filter gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); // Set Magnification Filter gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); // Set U Wrapping gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); // Set V Wrapping // load the generated bitmap onto the texture GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); // Load Bitmap to Texture gl.glBindTexture(GL10.GL_TEXTURE_2D, 0); // Unbind Texture // release the bitmap bitmap.recycle(); // Release the Bitmap // setup the array of character texture regions x = 0; // Initialize X y = 0; // Initialize Y for (int c = 0; c < CHAR_CNT; c++) { // FOR Each Character (On Texture) charRgn[c] = new TextureRegion(textureSize, textureSize, x, y, cellWidth - 1, cellHeight - 1); // Create Region for Character x += cellWidth; // Move to Next Char (Cell) if (x + cellWidth > textureSize) { x = 0; // Reset X Position to Start y += cellHeight; // Move to Next Row (Cell) } } // create full texture region textureRgn = new TextureRegion(textureSize, textureSize, 0, 0, textureSize, textureSize); // Create Full Texture Region // return success return true; // Return Success } public boolean load(Typeface tf, int size, int padX, int padY) { // setup requested values fontPadX = padX; // Set Requested X Axis Padding fontPadY = padY; // Set Requested Y Axis Padding // load the font and setup paint instance for drawing Paint paint = new Paint(); // Create Android Paint Instance paint.setAntiAlias(true); // Enable Anti Alias paint.setTextSize(size); // Set Text Size paint.setColor(0xffffffff); // Set ARGB (White, Opaque) paint.setTypeface(tf); // Set Typeface // get font metrics Paint.FontMetrics fm = paint.getFontMetrics(); // Get Font Metrics fontHeight = (float) Math.ceil(Math.abs(fm.bottom) + Math.abs(fm.top)); // Calculate Font Height fontAscent = (float) Math.ceil(Math.abs(fm.ascent)); // Save Font Ascent fontDescent = (float) Math.ceil(Math.abs(fm.descent)); // Save Font Descent // determine the width of each character (including unknown character) // also determine the maximum character width char[] s = new char[2]; // Create Character Array charWidthMax = charHeight = 0; // Reset Character Width/Height Maximums float[] w = new float[2]; // Working Width Value int cnt = 0; // Array Counter for (char c = CHAR_START; c <= CHAR_END; c++) { // FOR Each Character s[0] = c; // Set Character paint.getTextWidths(s, 0, 1, w); // Get Character Bounds charWidths[cnt] = w[0]; // Get Width if (charWidths[cnt] > charWidthMax) // IF Width Larger Than Max Width charWidthMax = charWidths[cnt]; // Save New Max Width cnt++; // Advance Array Counter } s[0] = CHAR_NONE; // Set Unknown Character paint.getTextWidths(s, 0, 1, w); // Get Character Bounds charWidths[cnt] = w[0]; // Get Width if (charWidths[cnt] > charWidthMax) // IF Width Larger Than Max Width charWidthMax = charWidths[cnt]; // Save New Max Width cnt++; // Advance Array Counter // set character height to font height charHeight = fontHeight; // Set Character Height // find the maximum size, validate, and setup cell sizes cellWidth = (int) charWidthMax + (2 * fontPadX); // Set Cell Width cellHeight = (int) charHeight + (2 * fontPadY); // Set Cell Height int maxSize = cellWidth > cellHeight ? cellWidth : cellHeight; // Save Max Size (Width/Height) if (maxSize < FONT_SIZE_MIN || maxSize > FONT_SIZE_MAX) // IF Maximum Size Outside Valid Bounds return false; // Return Error // set texture size based on max font size (width or height) // NOTE: these values are fixed, based on the defined characters. when // changing start/end characters (CHAR_START/CHAR_END) this will need adjustment too! if (maxSize <= 24) // IF Max Size is 18 or Less textureSize = 256; // Set 256 Texture Size else if (maxSize <= 40) // ELSE IF Max Size is 40 or Less textureSize = 512; // Set 512 Texture Size else if (maxSize <= 80) // ELSE IF Max Size is 80 or Less textureSize = 1024; // Set 1024 Texture Size else // ELSE IF Max Size is Larger Than 80 (and Less than FONT_SIZE_MAX) textureSize = 2048; // Set 2048 Texture Size // create an empty bitmap (alpha only) Bitmap bitmap = Bitmap.createBitmap(textureSize, textureSize, Bitmap.Config.ALPHA_8); // Create Bitmap Canvas canvas = new Canvas(bitmap); // Create Canvas for Rendering to Bitmap bitmap.eraseColor(0x00000000); // Set Transparent Background (ARGB) // calculate rows/columns // NOTE: while not required for anything, these may be useful to have :) colCnt = textureSize / cellWidth; // Calculate Number of Columns rowCnt = (int) Math.ceil((float) CHAR_CNT / (float) colCnt); // Calculate Number of Rows // render each of the characters to the canvas (ie. build the font map) float x = fontPadX; // Set Start Position (X) float y = (cellHeight - 1) - fontDescent - fontPadY; // Set Start Position (Y) for (char c = CHAR_START; c <= CHAR_END; c++) { // FOR Each Character s[0] = c; // Set Character to Draw canvas.drawText(s, 0, 1, x, y, paint); // Draw Character x += cellWidth; // Move to Next Character if ((x + cellWidth - fontPadX) > textureSize) { // IF End of Line Reached x = fontPadX; // Set X for New Row y += cellHeight; // Move Down a Row } } s[0] = CHAR_NONE; // Set Character to Use for NONE canvas.drawText(s, 0, 1, x, y, paint); // Draw Character // generate a new texture int[] textureIds = new int[1]; // Array to Get Texture Id gl.glGenTextures(1, textureIds, 0); // Generate New Texture textureId = textureIds[0]; // Save Texture Id // setup filters for texture gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId); // Bind Texture gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); // Set Minification Filter gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); // Set Magnification Filter gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); // Set U Wrapping gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); // Set V Wrapping // load the generated bitmap onto the texture GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); // Load Bitmap to Texture gl.glBindTexture(GL10.GL_TEXTURE_2D, 0); // Unbind Texture // release the bitmap bitmap.recycle(); // Release the Bitmap // setup the array of character texture regions x = 0; // Initialize X y = 0; // Initialize Y for (int c = 0; c < CHAR_CNT; c++) { // FOR Each Character (On Texture) charRgn[c] = new TextureRegion(textureSize, textureSize, x, y, cellWidth - 1, cellHeight - 1); // Create Region for Character x += cellWidth; // Move to Next Char (Cell) if (x + cellWidth > textureSize) { x = 0; // Reset X Position to Start y += cellHeight; // Move to Next Row (Cell) } } // create full texture region textureRgn = new TextureRegion(textureSize, textureSize, 0, 0, textureSize, textureSize); // Create Full Texture Region // return success return true; // Return Success } //--Begin/End Text Drawing--// // D: call these methods before/after (respectively all draw() calls using a text instance // NOTE: color is set on a per-batch basis, and fonts should be 8-bit alpha only!!! // A: red, green, blue - RGB values for font (default = 1.0) // alpha - optional alpha value for font (default = 1.0) // R: [none] public void begin() { begin(1.0f, 1.0f, 1.0f, 1.0f); // Begin with White Opaque } public void begin(float alpha) { begin(1.0f, 1.0f, 1.0f, alpha); // Begin with White (Explicit Alpha) } public void begin(float red, float green, float blue, float alpha) { gl.glColor4f(red, green, blue, alpha); // Set Color+Alpha gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId); // Bind the Texture batch.beginBatch(); // Begin Batch } public void end() { batch.endBatch(); // End Batch gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // Restore Default Color/Alpha } //--Draw Text--// // D: draw text at the specified x,y position // A: text - the string to draw // x, y - the x,y position to draw text at (bottom left of text; including descent) // R: [none] public void draw(String text, float x, float y) { float chrHeight = cellHeight * scaleY; // Calculate Scaled Character Height float chrWidth = cellWidth * scaleX; // Calculate Scaled Character Width int len = text.length(); // Get String Length x += (chrWidth / 2.0f) - (fontPadX * scaleX); // Adjust Start X y += (chrHeight / 2.0f) - (fontPadY * scaleY); // Adjust Start Y for (int i = 0; i < len; i++) { // FOR Each Character in String int c = (int) text.charAt(i) - CHAR_START; // Calculate Character Index (Offset by First Char in Font) if (c < 0 || c >= CHAR_CNT) // IF Character Not In Font c = CHAR_UNKNOWN; // Set to Unknown Character Index batch.drawSprite(x, y, chrWidth, chrHeight, charRgn[c]); // Draw the Character x += (charWidths[c] + spaceX) * scaleX; // Advance X Position by Scaled Character Width } } //--Draw Text Centered--// // D: draw text CENTERED at the specified x,y position // A: text - the string to draw // x, y - the x,y position to draw text at (bottom left of text) // R: the total width of the text that was drawn public float drawC(String text, float x, float y) { float len = getLength(text); // Get Text Length draw(text, x - (len / 2.0f), y - (getCharHeight() / 2.0f)); // Draw Text Centered return len; // Return Length } public float drawCX(String text, float x, float y) { float len = getLength(text); // Get Text Length draw(text, x - (len / 2.0f), y); // Draw Text Centered (X-Axis Only) return len; // Return Length } public void drawCY(String text, float x, float y) { draw(text, x, y - (getCharHeight() / 2.0f)); // Draw Text Centered (Y-Axis Only) } //--Set Scale--// // D: set the scaling to use for the font // A: scale - uniform scale for both x and y axis scaling // sx, sy - separate x and y axis scaling factors // R: [none] public void setScale(float scale) { scaleX = scaleY = scale; // Set Uniform Scale } public void setScale(float sx, float sy) { scaleX = sx; // Set X Scale scaleY = sy; // Set Y Scale } //--Get Scale--// // D: get the current scaling used for the font // A: [none] // R: the x/y scale currently used for scale public float getScaleX() { return scaleX; // Return X Scale } public float getScaleY() { return scaleY; // Return Y Scale } //--Set Space--// // D: set the spacing (unscaled; ie. pixel size) to use for the font // A: space - space for x axis spacing // R: [none] public void setSpace(float space) { spaceX = space; // Set Space } //--Get Space--// // D: get the current spacing used for the font // A: [none] // R: the x/y space currently used for scale public float getSpace() { return spaceX; // Return X Space } //--Get Length of a String--// // D: return the length of the specified string if rendered using current settings // A: text - the string to get length for // R: the length of the specified string (pixels) public float getLength(String text) { float len = 0.0f; // Working Length int strLen = text.length(); // Get String Length (Characters) for (int i = 0; i < strLen; i++) { // For Each Character in String (Except Last int c = (int) text.charAt(i) - CHAR_START; // Calculate Character Index (Offset by First Char in Font) len += (charWidths[c] * scaleX); // Add Scaled Character Width to Total Length } len += (strLen > 1 ? ((strLen - 1) * spaceX) * scaleX : 0); // Add Space Length return len; // Return Total Length } //--Get Width/Height of Character--// // D: return the scaled width/height of a character, or max character width // NOTE: since all characters are the same height, no character index is required! // NOTE: excludes spacing!! // A: chr - the character to get width for // R: the requested character size (scaled) public float getCharWidth(char chr) { int c = chr - CHAR_START; // Calculate Character Index (Offset by First Char in Font) return (charWidths[c] * scaleX); // Return Scaled Character Width } public float getCharWidthMax() { return (charWidthMax * scaleX); // Return Scaled Max Character Width } public float getCharHeight() { return (charHeight * scaleY); // Return Scaled Character Height } //--Get Font Metrics--// // D: return the specified (scaled) font metric // A: [none] // R: the requested font metric (scaled) public float getAscent() { return (fontAscent * scaleY); // Return Font Ascent } public float getDescent() { return (fontDescent * scaleY); // Return Font Descent } public float getHeight() { return (fontHeight * scaleY); // Return Font Height (Actual) } //--Draw Font Texture--// // D: draw the entire font texture (NOTE: for testing purposes only) // A: width, height - the width and height of the area to draw to. this is used // to draw the texture to the top-left corner. public void drawTexture(int width, int height) { batch.beginBatch(textureId); // Begin Batch (Bind Texture) batch.drawSprite(textureSize / 2, height - (textureSize / 2), textureSize, textureSize, textureRgn); // Draw batch.endBatch(); // End Batch } }
mit
NiurenZhu/ibas-framework-0.1.1
bobas.businessobjectscommon/src/main/java/org/colorcoding/ibas/bobas/logics/IBusinessLogic.java
515
package org.colorcoding.ibas.bobas.logics; import org.colorcoding.ibas.bobas.core.IBusinessObjectBase; /** * 业务逻辑 * * @author Niuren.Zhu * */ public interface IBusinessLogic<B extends IBusinessObjectBase> { /** * 正向执行逻辑 * */ void forward(); /** * 反向执行逻辑 * */ void reverse(); /** * 被影响的对象 * * @return */ B getBeAffected(); /** * 是否完成 * * @return */ boolean isDone(); /** * 提交逻辑 */ void commit(); }
mit
thjanssen/HibernateTips
SpringBootBootstrapping/src/test/java/org/thoughts/on/java/SpringBootstrappingTest.java
952
package org.thoughts.on.java; import javax.persistence.EntityManager; import org.apache.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.Commit; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import org.thoughts.on.java.model.Author; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBootstrappingTest { Logger log = Logger.getLogger(this.getClass().getName()); @Autowired private EntityManager em; @Test @Transactional @Commit public void accessHibernateSession() { log.info("... accessHibernateSession ..."); Author a = new Author(); a.setFirstName("Thorben"); a.setLastName("Janssen"); em.persist(a); } }
mit
moasifk/weatherdata
weatherdata/src/main/java/com/au/weatherdata/driver/WeatherDataModel.java
5430
package com.au.weatherdata.driver; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import com.au.weatherdata.constants.WeatherDataUnit; import com.au.weatherdata.model.WeatherData; import com.au.weatherdata.model.WeatherDataAdjacentDetails; import com.au.weatherdata.reader.WeatherDataReader; /** * @author Asif * * @param <T> * Class for creating the weather data model from the input file */ public class WeatherDataModel<T extends WeatherData> { private final static Logger LOGGER = Logger.getLogger(WeatherDataModel.class); Map<String, Map<Integer, Map<WeatherDataUnit, WeatherDataAdjacentDetails>>> weatherModel = new HashMap<>(); private final WeatherDataReader<T> reader; /** * @param reader */ public WeatherDataModel(WeatherDataReader<T> reader) { this.reader = reader; // Loading the weather data loadWeatherData(); } /** * */ private void loadWeatherData() { T line; while ((line = readNextLine()) != null) { // LocationMap with key as the month number as 1 for Jan, 2 for Feb etc. // Inner map has the key the WeatherDataUnit like Highest/Lowest // WeatherDataAdjacentDetails has weather details for the adjacent months Map<Integer, Map<WeatherDataUnit, WeatherDataAdjacentDetails>> locationMap = null; String key = line.getLocation() + "|" + line.getLatitude() + "," + line.getLongitude() + "," + line.getElevation(); if (!weatherModel.containsKey(key)) { weatherModel.put(key, new HashMap<Integer, Map<WeatherDataUnit, WeatherDataAdjacentDetails>>()); } locationMap = weatherModel.get(key); // Jan if (!locationMap.containsKey(1)) { locationMap.put(1, new HashMap<WeatherDataUnit, WeatherDataAdjacentDetails>()); } locationMap.get(1).put( line.getUnit(), new WeatherDataAdjacentDetails(line.getDecVal(), line.getJanVal(), line .getFebVal())); // Feb if (!locationMap.containsKey(2)) { locationMap.put(2, new HashMap<WeatherDataUnit, WeatherDataAdjacentDetails>()); } locationMap.get(2).put( line.getUnit(), new WeatherDataAdjacentDetails(line.getJanVal(), line.getFebVal(), line .getMarVal())); // March if (!locationMap.containsKey(3)) { locationMap.put(3, new HashMap<WeatherDataUnit, WeatherDataAdjacentDetails>()); } locationMap.get(3).put( line.getUnit(), new WeatherDataAdjacentDetails(line.getFebVal(), line.getMarVal(), line .getAprVal())); // Apri if (!locationMap.containsKey(4)) { locationMap.put(4, new HashMap<WeatherDataUnit, WeatherDataAdjacentDetails>()); } locationMap.get(4).put( line.getUnit(), new WeatherDataAdjacentDetails(line.getMarVal(), line.getAprVal(), line .getMayVal())); // May if (!locationMap.containsKey(5)) { locationMap.put(5, new HashMap<WeatherDataUnit, WeatherDataAdjacentDetails>()); } locationMap.get(5).put( line.getUnit(), new WeatherDataAdjacentDetails(line.getAprVal(), line.getMayVal(), line .getJunVal())); // June if (!locationMap.containsKey(6)) { locationMap.put(6, new HashMap<WeatherDataUnit, WeatherDataAdjacentDetails>()); } locationMap.get(6).put( line.getUnit(), new WeatherDataAdjacentDetails(line.getMayVal(), line.getJunVal(), line .getJulVal())); // July if (!locationMap.containsKey(7)) { locationMap.put(7, new HashMap<WeatherDataUnit, WeatherDataAdjacentDetails>()); } locationMap.get(7).put( line.getUnit(), new WeatherDataAdjacentDetails(line.getJunVal(), line.getJulVal(), line .getAugVal())); // Aug if (!locationMap.containsKey(8)) { locationMap.put(8, new HashMap<WeatherDataUnit, WeatherDataAdjacentDetails>()); } locationMap.get(8).put( line.getUnit(), new WeatherDataAdjacentDetails(line.getJulVal(), line.getAugVal(), line .getSepVal())); // Sep if (!locationMap.containsKey(9)) { locationMap.put(9, new HashMap<WeatherDataUnit, WeatherDataAdjacentDetails>()); } locationMap.get(9).put( line.getUnit(), new WeatherDataAdjacentDetails(line.getAugVal(), line.getSepVal(), line .getOctVal())); // Oct if (!locationMap.containsKey(10)) { locationMap.put(10, new HashMap<WeatherDataUnit, WeatherDataAdjacentDetails>()); } locationMap.get(10).put( line.getUnit(), new WeatherDataAdjacentDetails(line.getSepVal(), line.getOctVal(), line .getNovVal())); // Nov if (!locationMap.containsKey(11)) { locationMap.put(11, new HashMap<WeatherDataUnit, WeatherDataAdjacentDetails>()); } locationMap.get(11).put( line.getUnit(), new WeatherDataAdjacentDetails(line.getOctVal(), line.getNovVal(), line .getDecVal())); // Dec if (!locationMap.containsKey(12)) { locationMap.put(12, new HashMap<WeatherDataUnit, WeatherDataAdjacentDetails>()); } locationMap.get(12).put( line.getUnit(), new WeatherDataAdjacentDetails(line.getNovVal(), line.getDecVal(), line .getJanVal())); } } public T readNextLine() { try { return reader.readLine(); } catch (IOException e) { LOGGER.error("Error while reading the line"); throw new RuntimeException("Read line error", e); } } public Map<String, Map<Integer, Map<WeatherDataUnit, WeatherDataAdjacentDetails>>> getModel() { return weatherModel; } }
mit
TerribleEngineer/NginxController
src/main/java/com/terribleengineer/ngservice/nginxconfiguration/NginxConfigurationBuilder.java
1941
package com.terribleengineer.ngservice.nginxconfiguration; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class NginxConfigurationBuilder { protected static final Logger log = LogManager.getLogger(NginxConfigurationBuilder.class); public static String buildConfig(NginxConfiguration config) { StringBuilder sb = new StringBuilder(); sb.append("\n\n"); sb.append("worker_processes 2;\n"); sb.append("\n\n"); sb.append("events {\n"); sb.append("\tworker_connections 1000;\n"); sb.append("}\n"); sb.append("\n\n"); sb.append("http {\n"); sb.append("\tinclude /etc/nginx/mime.types;\n"); sb.append("server {\n"); sb.append("\tserver_name " + config.getServerName() + ";\n"); sb.append("\tlisten " + config.getPort() + ";\n"); Map<String, Location> locations = config.getLocations(); for (String locationKey : locations.keySet()) { Location location = locations.get(locationKey); if (location.isStaticContentLocation()) { StaticContentLocation scl = (StaticContentLocation) location; sb.append("\tlocation " + scl.getLocation() + " {\n"); sb.append("\t\tindex index.html index.htm;\n"); sb.append("\t\tautoindex on;\n"); sb.append("\t\troot " + scl.getRootPath() + ";\n"); sb.append("\t\tadd_header Authentication 'Bearer " + config.getJwt() + "';\n"); sb.append("\t}\n\n"); } else { ProxyLocation pl = (ProxyLocation) location; sb.append("\tlocation " + pl.getLocation() + " {\n"); sb.append("\t\tproxy_pass " + pl.getProxypass() + ";\n"); sb.append("\t\tproxy_set_header Host $host;\n"); sb.append("\t\tproxy_set_header X-Real-IP $remote_addr;\n"); sb.append("\t\tadd_header Authentication 'Bearer " + config.getJwt() + "';\n"); sb.append("\t}\n\n"); } } sb.append("}\n"); sb.append("}\n"); String cfg = sb.toString(); log.debug(cfg); return cfg; } }
mit
assisstion/Communicator
src/com/github/assisstion/Communicator/gui/LogHandler.java
799
package com.github.assisstion.Communicator.gui; import java.util.Calendar; import java.util.logging.Handler; import java.util.logging.LogRecord; public class LogHandler extends Handler{ protected LoggerPane gui; public LogHandler(LoggerPane gui){ this.gui = gui; } @Override public void close() throws SecurityException{ // Unimplemented } @Override public void flush(){ // Unimplemented } @Override public void publish(LogRecord record){ Calendar c = Calendar.getInstance(); String timeStamp = String.format("%1$tY-%1$tm-%1td %1$tH:%1$tM:%1$tS", c); if(!record.getLevel().getName().equals("NOMESSAGE")){ gui.worker.push(timeStamp + " - [" + record.getLevel().getName() + "] " + record.getMessage()); } else{ gui.worker.push(record.getMessage()); } } }
mit
TyrfingX/TyrLib
legacy/TyrLib2/src/com/tyrlib2/graphics/materials/DefaultMaterial3.java
15387
package com.tyrlib2.graphics.materials; import java.nio.FloatBuffer; import com.tyrlib2.graphics.renderer.Material; import com.tyrlib2.graphics.renderer.Mesh; import com.tyrlib2.graphics.renderer.OpenGLRenderer; import com.tyrlib2.graphics.renderer.Program; import com.tyrlib2.graphics.renderer.ProgramManager; import com.tyrlib2.graphics.renderer.Texture; import com.tyrlib2.graphics.renderer.TextureManager; import com.tyrlib2.graphics.renderer.TyrGL; import com.tyrlib2.graphics.renderer.VertexLayout; import com.tyrlib2.graphics.scene.SceneManager; import com.tyrlib2.math.Matrix; import com.tyrlib2.math.Vector2; import com.tyrlib2.math.Vector3; import com.tyrlib2.util.Color; /** * Default material for rendering 3D objects especially entities. * Supports: * - Lighting * - Per vertex coloring * - Skinning/skeletal animation * - Texturing * @author Sascha * */ public class DefaultMaterial3 extends LightedMaterial { /** Per vertex color of this object **/ private Color[] colors; /** Per vertex normals of this object **/ public static final int DEFAULT_NORMAL_OFFSET = 3; public static final int DEFAULT_NORMAL_SIZE = 3; protected int normalHandle; /** Texture information of this object **/ public static final int DEFAULT_UV_OFFSET = 6; public static final int DEFAULT_UV_SIZE = 2; public static final int DIFFUSE_OFFSET = 8; public static final int DIFFUSE = 4; private int textureUniformHandle; private int textureCoordinateHandle; private int shadowTextureHandle; private int depthMVPHandle; private String textureName; private Texture texture; protected float repeatX; protected float repeatY; public static final int posOffset = 0; /** Contains the normal matrix **/ private static float[] shadowMVP = new float[16]; public static final String PER_PIXEL_PROGRAM_NAME = "TEXTURED_PPL"; private boolean transparent; private static boolean wasAnimated = false; private int modelMatrixHandle; /** Default vertex layout **/ public final static VertexLayout DEFAULT_LAYOUT = new VertexLayout(); /** Vertex layout used for meshs with baked in lighting information **/ public final static VertexLayout BAKED_LIGHTING_LAYOUT = new VertexLayout(); private static final float[] mvpMatrix = new float[16]; static { DEFAULT_LAYOUT.setPos(VertexLayout.POSITION, 0); DEFAULT_LAYOUT.setSize(VertexLayout.POSITION, 3); DEFAULT_LAYOUT.setPos(VertexLayout.NORMAL, DEFAULT_NORMAL_OFFSET); DEFAULT_LAYOUT.setSize(VertexLayout.NORMAL, DEFAULT_NORMAL_SIZE); DEFAULT_LAYOUT.setPos(VertexLayout.UV, DEFAULT_UV_OFFSET); DEFAULT_LAYOUT.setSize(VertexLayout.UV, DEFAULT_UV_SIZE); BAKED_LIGHTING_LAYOUT.setPos(VertexLayout.POSITION, 0); BAKED_LIGHTING_LAYOUT.setSize(VertexLayout.POSITION, 3); BAKED_LIGHTING_LAYOUT.setPos(VertexLayout.NORMAL, DEFAULT_NORMAL_OFFSET); BAKED_LIGHTING_LAYOUT.setSize(VertexLayout.NORMAL, DEFAULT_NORMAL_SIZE); BAKED_LIGHTING_LAYOUT.setPos(VertexLayout.UV, DEFAULT_UV_OFFSET); BAKED_LIGHTING_LAYOUT.setSize(VertexLayout.UV, DEFAULT_UV_SIZE); BAKED_LIGHTING_LAYOUT.setPos(DIFFUSE, DIFFUSE_OFFSET); BAKED_LIGHTING_LAYOUT.setSize(DIFFUSE, 1); } public DefaultMaterial3() { } public DefaultMaterial3(Program program, String textureName, float repeatX, float repeatY, Color[] colors) { this.program = program; if (colors == null) { colors = new Color[1]; colors[0] = new Color(1,1,1,1); } if (textureName != null) { texture = TextureManager.getInstance().getTexture(textureName); } setup(textureName, repeatX, repeatY, colors); } public DefaultMaterial3(String textureName, float repeatX, float repeatY, Color[] colors) { if (!SceneManager.getInstance().getRenderer().isInServerMode()) { program = ProgramManager.getInstance().getProgram(PER_PIXEL_PROGRAM_NAME); if (colors == null) { colors = new Color[1]; colors[0] = new Color(1,1,1,1); } if (textureName != null) { texture = TextureManager.getInstance().getTexture(textureName); } } setup(textureName, repeatX, repeatY, colors); } public DefaultMaterial3(String textureName, float repeatX, float repeatY, Color[] colors, boolean animated) { if (colors == null) { colors = new Color[1]; colors[0] = new Color(1,1,1,1); } String add = ""; this.animated = animated; if (animated) { add = "_ANIMATED"; } program = ProgramManager.getInstance().getProgram(PER_PIXEL_PROGRAM_NAME + add); if (textureName != null) { texture = TextureManager.getInstance().getTexture(textureName); } setup(textureName, repeatX, repeatY, colors); } protected void setup(String textureName, float repeatX, float repeatY, Color[] colors) { lighted = true; this.boneParam = "u_Bone"; this.boneIndexParam = "a_BoneIndex"; this.boneWeightParam = "a_BoneWeight"; this.textureName = textureName; this.colors = colors; this.repeatX = repeatX; this.repeatY = repeatY; init(posOffset,3, "u_MVPMatrix", "a_Position"); addVertexInfo(VertexLayout.NORMAL, DEFAULT_NORMAL_OFFSET, DEFAULT_NORMAL_SIZE); addVertexInfo(VertexLayout.UV, DEFAULT_UV_OFFSET, DEFAULT_UV_SIZE); if (!SceneManager.getInstance().getRenderer().isInServerMode()) { updateHandles(); } } public void setLighted(boolean lighted) { this.lighted = lighted; } @Override public void updateHandles() { super.updateHandles(); normalMatrixHandle = TyrGL.glGetUniformLocation(program.handle, "u_NormalMatrix"); textureUniformHandle = TyrGL.glGetUniformLocation(program.handle, "u_Texture"); ambientHandle = TyrGL.glGetUniformLocation(program.handle, "u_Ambient"); textureUniformHandle = TyrGL.glGetUniformLocation(program.handle, "u_Texture"); normalHandle = TyrGL.glGetAttribLocation(program.handle, "a_Normal"); textureCoordinateHandle = TyrGL.glGetAttribLocation(program.handle, "a_TexCoordinate"); shadowTextureHandle = TyrGL.glGetUniformLocation(program.handle, "u_ShadowMap"); depthMVPHandle = TyrGL.glGetUniformLocation(program.handle, "u_DepthMVP"); modelMatrixHandle = TyrGL.glGetUniformLocation(program.handle, "u_M"); } @Override public void render(Mesh mesh, float[] modelMatrix) { super.render(mesh, modelMatrix); if (program.meshChange) { passMesh(mesh); } //passModelViewMatrix(modelMatrix); // SceneManager sceneManager = SceneManager.getInstance(); // float[] viewMatrix = sceneManager.getRenderer().getCamera().getViewMatrix(); // Matrix.multiplyMM(normalMatrix, 0, viewMatrix, 0, modelMatrix, 0); // Pass in the modelview matrix. //TyrGL.glUniformMatrix4fv(normalMatrixHandle, 1, false, normalMatrix, 0); if (modelMatrixHandle != -1) { Matrix.setLookAtM( mvpMatrix, 0, 0,0,1, 0,0,0, 1,0,0); // Apply the projection and view transformation Matrix.multiplyMM(mvpMatrix, 0, mvpMatrix, 0, modelMatrix, 0); // Combine the rotation matrix with the projection and camera view TyrGL.glUniformMatrix4fv(modelMatrixHandle, 1, false, mvpMatrix, 0); } if (SceneManager.getInstance().getRenderer().isShadowsEnabled() && depthMVPHandle != -1) { // Apply the projection and view transformation Matrix.multiplyMM(shadowMVP, 0, SceneManager.getInstance().getRenderer().getShadowVP(), 0, modelMatrix, 0); // Combine the rotation matrix with the projection and camera view TyrGL.glUniformMatrix4fv(depthMVPHandle, 1, false, shadowMVP, 0); // Set the active texture unit to texture unit 2. TyrGL.glActiveTexture(TyrGL.GL_TEXTURE2); // Bind the texture to this unit. TyrGL.glBindTexture(TyrGL.GL_TEXTURE_2D, SceneManager.getInstance().getRenderer().getShadowMapHandle()); // Tell the texture uniform sampler to use this texture in the shader by binding to texture unit 0. TyrGL.glUniform1i(shadowTextureHandle, 2); } int textureHandle = texture.getHandle(); if (program.textureHandle != textureHandle) { passTexture(textureHandle); } if (!animated && wasAnimated) { wasAnimated = false; } else { wasAnimated = true; } if (transparent) { Program.blendEnable(TyrGL.GL_SRC_ALPHA, TyrGL.GL_ONE_MINUS_SRC_ALPHA); } } public void setBlendMode(int mode) { //this.blendMode = mode; } // private void passModelViewMatrix(float[] modelMatrix) { // SceneManager sceneManager = SceneManager.getInstance(); // float[] viewMatrix = sceneManager.getRenderer().getCamera().getViewMatrix(); // Matrix.multiplyMM(mvMatrix, 0, viewMatrix, 0, modelMatrix, 0); // // // // Pass in the modelview matrix. // TyrGL.glUniformMatrix4fv(mvMatrixHandle, 1, false, mvMatrix, 0); // } protected void passMesh(Mesh mesh) { FloatBuffer vertexBuffer = mesh.getVertexBuffer(); if (mesh.isUsingVBO()) { // Pass in the normal information if (normalHandle != -1) { TyrGL.glVertexAttribPointer(normalHandle, getNormalSize(), TyrGL.GL_FLOAT, false, getByteStride() * OpenGLRenderer.BYTES_PER_FLOAT, getNormalOffset() * OpenGLRenderer.BYTES_PER_FLOAT); TyrGL.glEnableVertexAttribArray(normalHandle); } if (textureCoordinateHandle != -1) { // Pass in the texture coordinate information TyrGL.glVertexAttribPointer(textureCoordinateHandle, getUVSize(), TyrGL.GL_FLOAT, false, getByteStride() * OpenGLRenderer.BYTES_PER_FLOAT, getUVOffset() * OpenGLRenderer.BYTES_PER_FLOAT); TyrGL.glEnableVertexAttribArray(textureCoordinateHandle); } } else { if (getNormalSize() > 0) { // Pass in the normal information vertexBuffer.position(getNormalOffset()); TyrGL.glVertexAttribPointer(normalHandle, getNormalSize(), TyrGL.GL_FLOAT, false, getByteStride() * OpenGLRenderer.BYTES_PER_FLOAT, vertexBuffer); TyrGL.glEnableVertexAttribArray(normalHandle); } // Pass in the texture coordinate information vertexBuffer.position(getUVOffset()); TyrGL.glVertexAttribPointer(textureCoordinateHandle, getUVSize(), TyrGL.GL_FLOAT, false, getByteStride() * OpenGLRenderer.BYTES_PER_FLOAT, vertexBuffer); TyrGL.glEnableVertexAttribArray(textureCoordinateHandle); } } protected void passTexture(int textureHandle) { // Set the active texture unit to texture unit 0. TyrGL.glActiveTexture(TyrGL.GL_TEXTURE0); // Bind the texture to this unit. TyrGL.glBindTexture(TyrGL.GL_TEXTURE_2D, textureHandle); // Tell the texture uniform sampler to use this texture in the shader by binding to texture unit 0. TyrGL.glUniform1i(textureUniformHandle, 0); program.textureHandle = textureHandle; OpenGLRenderer.setTextureFails(OpenGLRenderer.getTextureFails() + 1); } public Color[] getColors() { return colors; } public void setTransparent(boolean transparent) { this.transparent = transparent; } public boolean isTransparent() { return transparent; } public float[] createVertexData(Vector3[] points, float[] uvCoords, short[] drawOrder) { float[] vertexData = super.createVertexData(points, drawOrder); int vertexCount = points.length; Vector3[] normals = new Vector3[points.length]; for (int i = 0; i < vertexCount; ++i) { normals[i] = new Vector3(); for (int j = 0; j < drawOrder.length; j += 3) { if (j + 2 < drawOrder.length) { if (drawOrder[j] == i || drawOrder[j+1] == i || drawOrder[j + 2] == i) { Vector3 u = points[drawOrder[j]].vectorTo(points[drawOrder[j+1]]); Vector3 v = points[drawOrder[j+1]].vectorTo(points[drawOrder[j+2]]); Vector3 normal = u.cross(v); normal.normalize(); normals[i] = normals[i].add(normal); } } } normals[i].normalize(); } int uvCoord = 0; for (int i = 0; i < vertexCount; i++) { int pos = i * getByteStride(); int normalOffset = getNormalOffset(); vertexData[pos + normalOffset + 0] = normals[i].x; vertexData[pos + normalOffset + 1] = normals[i].y; vertexData[pos + normalOffset + 2] = normals[i].z; int uvOffset = getUVOffset(); vertexData[pos + uvOffset + 0] = uvCoords[uvCoord] * repeatX; vertexData[pos + uvOffset + 1] = uvCoords[uvCoord+1] * repeatY; uvCoord += 2; if (uvCoord >= uvCoords.length) { uvCoord = 0; // Increase the coordinate numbers in order to prevent // weird clamping effects to occur in most cases for (int j = 0; j < uvCoords.length; ++j) { uvCoords[j] = uvCoords[j] + 1; } } } return vertexData; } /** * Adds the colors to the vertex data. * Repeats the colors if there are more vertices than colors */ public float[] createVertexData(Vector3[] points, short[] drawOrder) { // Assign some arbitary uvCoordinates for the textures // The default uvCoords assigned by this work for shapes // like planes, meshs, etc float[] uvCoords = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, }; return createVertexData(points, uvCoords, drawOrder); } public String getTextureName() { return textureName; } public int getNormalOffset() { return getInfoOffset(VertexLayout.NORMAL); } public int getUVOffset(){ return getInfoOffset(VertexLayout.UV); } public int getUVSize() { return getInfoSize(VertexLayout.UV); } public int getNormalSize() { return getInfoSize(VertexLayout.NORMAL); } public void setNormalSize(int size) { vertexLayout.setSize(VertexLayout.NORMAL, size); } public void setNormalOffset(int offset) { vertexLayout.setPos(VertexLayout.NORMAL, offset); } public void setUVSize(int size) { vertexLayout.setSize(VertexLayout.UV, size); } public void setUVOffset(int offset) { vertexLayout.setPos(VertexLayout.UV, offset); } public Material copy() { DefaultMaterial3 material = new DefaultMaterial3(textureName, repeatX, repeatY, colors, animated); material.vertexLayout = vertexLayout.copy(); return material; } public Material copy(boolean animated) { DefaultMaterial3 material = new DefaultMaterial3(textureName, repeatX, repeatY, colors, animated); material.vertexLayout = vertexLayout.copy(); return material; } public void setTexture(Texture texture, String textureName) { this.texture = texture; this.textureName = textureName; } public void setTexture( String textureName) { this.textureName = textureName; this.texture = TextureManager.getInstance().getTexture(textureName); } public Vector2 getRepeat() { return new Vector2(repeatX, repeatY); } public boolean isAnimated() { return animated; } public void setVertexLayout(VertexLayout vertexLayout) { this.vertexLayout = vertexLayout; } }
mit
zhangqiang110/my4j
pms/src/main/java/com/swfarm/biz/aliexpress/bo/AliExpressOrderMessageWorkingFolder.java
5405
package com.swfarm.biz.aliexpress.bo; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import com.swfarm.biz.oa.bo.User; import com.swfarm.pub.utils.VelocityUtils; public class AliExpressOrderMessageWorkingFolder implements Serializable { private Long id; private String name; private String displayName; private String customerServiceName; private String accountNumber; private String filterRule; private Integer totalMessageCount; private Integer newMessageCount; private Integer oldMessageCount; private Set aliExpressOrderMessages = new HashSet(); private Set customerServiceUsers = new HashSet(); private Long[] customerServiceUserIds; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getCustomerServiceName() { return customerServiceName; } public void setCustomerServiceName(String customerServiceName) { this.customerServiceName = customerServiceName; } public String getAccountNumber() { return accountNumber; } public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; } public String getFilterRule() { return filterRule; } public void setFilterRule(String filterRule) { this.filterRule = filterRule; } public Integer getTotalMessageCount() { if (totalMessageCount == null) { totalMessageCount = 0; } return totalMessageCount; } public void setTotalMessageCount(Integer totalMessageCount) { this.totalMessageCount = totalMessageCount; } public Integer getNewMessageCount() { if (newMessageCount == null) { newMessageCount = 0; } return newMessageCount; } public void setNewMessageCount(Integer newMessageCount) { this.newMessageCount = newMessageCount; } public Integer getOldMessageCount() { if (oldMessageCount == null) { oldMessageCount = 0; } return oldMessageCount; } public void setOldMessageCount(Integer oldMessageCount) { this.oldMessageCount = oldMessageCount; } public Set getAliExpressOrderMessages() { if (aliExpressOrderMessages == null) { aliExpressOrderMessages = new HashSet(); } return aliExpressOrderMessages; } public void setAliExpressOrderMessages(Set ebayMessages) { this.aliExpressOrderMessages = ebayMessages; } public Set getCustomerServiceUsers() { if (customerServiceUsers == null) { customerServiceUsers = new HashSet(); } return customerServiceUsers; } public List getCustomerServiceUserList() { List customerServiceList = new ArrayList(); customerServiceList.addAll(this.getCustomerServiceUsers()); Collections.sort(customerServiceList, new Comparator() { public int compare(Object obj1, Object obj2) { User customerService1 = (User) obj1; User customerService2 = (User) obj2; return customerService1.getUsername().compareTo( customerService2.getUsername()); } }); return customerServiceList; } public void addCustomerServiceUser(User customerServiceUser) { if (!this.getCustomerServiceUsers().contains(customerServiceUser)) { this.customerServiceUsers.add(customerServiceUser); } } public void removeCustomerServiceUser(User customerServiceUser) { if (this.getCustomerServiceUsers().contains(customerServiceUser)) { this.customerServiceUsers.remove(customerServiceUser); } } public void setCustomerServiceUsers(Set customerServiceUsers) { this.customerServiceUsers = customerServiceUsers; } public Long[] getCustomerServiceUserIds() { return customerServiceUserIds; } public void setCustomerServiceUserIds(Long[] customerServiceUserIds) { this.customerServiceUserIds = customerServiceUserIds; } public Boolean filter(String accountNumber, String senderName, String content) { Map dataMap = new HashMap(); dataMap.put("accountNumber", accountNumber); dataMap.put("senderName", senderName); dataMap.put("senderNameFirstChar", "" + senderName.charAt(0)); dataMap.put("content", content); VelocityContext context = VelocityUtils.createVelocityContext(); for (Iterator iter = dataMap.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); context.put(key, entry.getValue()); } Template template = VelocityUtils.getTemplateFromString(filterRule); if (template != null) { String evalContent = VelocityUtils.mergeToString(context, template); if (StringUtils.isNotEmpty(evalContent) && "true".equals(evalContent.trim())) { return true; } } return false; } public static void main(String[] args) { System.out.println("test".charAt(0)); } }
mit
pavel-sedek/Cordova-BLE-Plugin
src/cz/cvut/sedekpav/cordova/bleplugin/BLEPlugin.java
1952
/* * 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 cz.cvut.sedekpav.cordova.bleplugin; import android.bluetooth.BluetoothDevice; import java.util.List; import org.apache.cordova.api.CallbackContext; import org.apache.cordova.api.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * * @author Root */ public class BLEPlugin extends CordovaPlugin { public static final String ACTION_LIST_DEVICES = "listDevices"; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { try { if (ACTION_LIST_DEVICES.equals(action)) { JSONObject arg_object = args.getJSONObject(0); BLE ble = new BLE(cordova.getActivity()); /* Intent calIntent = new Intent(Intent.ACTION_EDIT) .setType("vnd.android.cursor.item/event") .putExtra("beginTime", arg_object.getLong("startTimeMillis")) .putExtra("endTime", arg_object.getLong("endTimeMillis")) .putExtra("title", arg_object.getString("title")) .putExtra("description", arg_object.getString("description")) .putExtra("eventLocation", arg_object.getString("eventLocation")); this.cordova.getActivity().startActivity(calIntent);*/ List<BluetoothDevice> devs = ble.listBluetoothDevices(); JSONArray jArray = new JSONArray(); for (BluetoothDevice dev : devs) { JSONObject json = new JSONObject(); json.put("address", dev.getAddress().toString()); json.put("name", dev.getName()); jArray.put(json); } callbackContext.success(jArray); return true; } callbackContext.error("Invalid action"); return false; } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); callbackContext.error(e.getMessage()); return false; } } }
mit
DominikGebhart/jenkins-build-monitor-plugin
build-monitor-acceptance/src/main/java/net/serenitybdd/integration/jenkins/logging/LoggerOutputStream.java
740
package net.serenitybdd.integration.jenkins.logging; import java.io.IOException; import java.io.OutputStream; public class LoggerOutputStream extends OutputStream { private Witness witness; private String buffer; public LoggerOutputStream(Witness witness) { this.witness = witness; buffer = ""; } @Override public void write(int b) throws IOException { byte[] bytes = new byte[1]; bytes[0] = (byte) (b & 0xff); buffer = buffer + new String(bytes); if (buffer.endsWith("\n")) { buffer = buffer.substring(0, buffer.length() - 1); flush(); } } public void flush() { witness.note(buffer); buffer = ""; } }
mit
ddki/my_study_project
client/android/demos/FirstApp/app/src/androidTest/java/com/example/helloworld/yuer/firstapp/ApplicationTest.java
367
package com.example.helloworld.yuer.firstapp; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
mit
rentianhua/tsf_android
houseAd/HouseGo/src/util/PublicWay.java
455
package util; import java.io.File; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.graphics.BitmapFactory; /** * 存放所有的list在最后退出时一起关闭 * * @author king * @QQ:595163260 * @version 2014年10月18日 下午11:50:49 */ public class PublicWay { public static List<Activity> activityList = new ArrayList<Activity>(); public static int num = 9; }
mit
altanizio/Conceitos-de-Topografia
scripts/TextTabNivelIntro.java
2512
package com.lag.altanizio.conceitosdetopografia; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; /** * A simple {@link Fragment} subclass. */ public class TextTabNivelIntro extends Fragment { private TextView text; public ScrollView scroll; public ImageButton imgZ; public ImageButton img01; public ImageButton img02; public RelativeLayout layoutz; public TextTabNivelIntro() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_text_tab_nivel_intro, container, false); text = (TextView) view.findViewById(R.id.textTab); text.setText(R.string.nivel_intro01); text = (TextView) view.findViewById(R.id.textTab2); text.setText(R.string.nivel_intro02); scroll = (ScrollView) view.findViewById(R.id.scrollV); layoutz = (RelativeLayout)view.findViewById(R.id.layoutZ); imgZ = (ImageButton) view.findViewById(R.id.imgZoom); img01 = (ImageButton) view.findViewById(R.id.imgEst01); img02 = (ImageButton) view.findViewById(R.id.imgEst02); img01.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { imgZ.setVisibility(View.VISIBLE); imgZ.setImageDrawable(img01.getDrawable()); layoutz.setVisibility(View.VISIBLE); scroll.setVisibility(View.INVISIBLE); } }); img02.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { imgZ.setVisibility(View.VISIBLE); imgZ.setImageDrawable(img02.getDrawable()); layoutz.setVisibility(View.VISIBLE); scroll.setVisibility(View.INVISIBLE); } }); imgZ.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { imgZ.setVisibility(View.INVISIBLE); layoutz.setVisibility(View.INVISIBLE); scroll.setVisibility(View.VISIBLE); } }); return view; } }
mit
AndersonOdilo/Antropometria-Web
src/main/java/com/antropometria/dao/exceptions/IllegalOrphanException.java
565
package com.antropometria.dao.exceptions; import java.util.ArrayList; import java.util.List; public class IllegalOrphanException extends Exception { private List<String> messages; public IllegalOrphanException(List<String> messages) { super((messages != null && messages.size() > 0 ? messages.get(0) : null)); if (messages == null) { this.messages = new ArrayList<String>(); } else { this.messages = messages; } } public List<String> getMessages() { return messages; } }
mit
marszczybrew/Diorite
DioriteAPI/src/main/java/org/diorite/world/World.java
3691
package org.diorite.world; import java.io.File; import java.util.ArrayList; import java.util.Collection; import org.diorite.BlockLocation; import org.diorite.Difficulty; import org.diorite.Diorite; import org.diorite.GameMode; import org.diorite.ImmutableLocation; import org.diorite.Loc; import org.diorite.Particle; import org.diorite.entity.Player; import org.diorite.material.BlockMaterialData; import org.diorite.utils.math.DioriteRandom; import org.diorite.world.chunk.Chunk; import org.diorite.world.chunk.ChunkManager; import org.diorite.world.chunk.ChunkPos; import org.diorite.world.generator.WorldGenerator; public interface World { boolean isVanillaCompatible(); void loadChunk(Chunk chunk); void loadChunk(int x, int z); void loadChunk(ChunkPos pos); boolean loadChunk(int x, int z, boolean generate); boolean unloadChunk(Chunk chunk); boolean unloadChunk(int x, int z); boolean unloadChunk(int x, int z, boolean save); boolean unloadChunk(int x, int z, boolean save, boolean safe); boolean regenerateChunk(int x, int z); boolean refreshChunk(int x, int z); boolean isChunkLoaded(Chunk chunk); boolean isChunkLoaded(int x, int z); boolean isChunkInUse(int x, int z); /** * @return folder with world data (if used). */ File getWorldFile(); WorldGroup getWorldGroup(); DioriteRandom getRandom(); Dimension getDimension(); String getName(); ChunkManager getChunkManager(); long getSeed(); void setSeed(long seed); Difficulty getDifficulty(); void setDifficulty(Difficulty difficulty); HardcoreSettings getHardcore(); void setHardcore(HardcoreSettings hardcore); GameMode getDefaultGameMode(); void setDefaultGameMode(GameMode defaultGameMode); boolean isRaining(); void setRaining(boolean raining); boolean isThundering(); void setThundering(boolean thundering); int getClearWeatherTime(); void setClearWeatherTime(int clearWeatherTime); int getRainTime(); int getThunderTime(); ImmutableLocation getSpawn(); void setSpawn(Loc spawn); WorldGenerator getGenerator(); void setGenerator(WorldGenerator generator); Chunk getChunkAt(int x, int z); Chunk getChunkAt(ChunkPos pos); Block getBlock(int x, int y, int z); int getHighestBlockY(int x, int z); Block getHighestBlock(int x, int z); void setBlock(int x, int y, int z, BlockMaterialData material); void setBlock(BlockLocation location, BlockMaterialData material); int getMaxHeight(); long getTime(); void setTime(long time); void showParticle(Particle particle, boolean isLongDistance, int x, int y, int z, int offsetX, int offsetY, int offsetZ, int particleData, int particleCount, int... data); default Collection<Player> getPlayersInWorld() { // TODO: improve final Collection<Player> temp = new ArrayList<>(Diorite.getCore().getOnlinePlayers().size()); Diorite.getCore().getOnlinePlayers().forEach(player -> { if (player.getWorld().equals(this)) { temp.add(player); } }); return temp; } Biome getBiome(int x, int y, int z); void setBiome(int x, int y, int z, Biome biome); // y is ignored, added for future possible changes. boolean hasSkyLight(); boolean isNoUpdateMode(); void setNoUpdateMode(boolean noUpdateMode); byte getForceLoadedRadius(); void setForceLoadedRadius(byte forceLoadedRadius); boolean isAutoSave(); void setAutoSave(boolean value); void save(); void save(boolean async); }
mit
laidig/siri-20-java
src/uk/org/siri/siri/InfoLinkStructure.java
4478
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // 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: 2017.11.30 at 08:24:17 PM JST // package uk.org.siri.siri; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * Type for a general hyperlink. * * <p>Java class for InfoLinkStructure complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="InfoLinkStructure"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Uri" type="{http://www.w3.org/2001/XMLSchema}anyURI"/> * &lt;element name="Label" type="{http://www.siri.org.uk/siri}NaturalLanguageStringStructure" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="Image" type="{http://www.siri.org.uk/siri}ImageStructure" minOccurs="0"/> * &lt;element name="LinkContent" type="{http://www.siri.org.uk/siri}LinkContentEnumeration" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "InfoLinkStructure", propOrder = { "uri", "label", "image", "linkContent" }) public class InfoLinkStructure { @XmlElement(name = "Uri", required = true) @XmlSchemaType(name = "anyURI") protected String uri; @XmlElement(name = "Label") protected List<NaturalLanguageStringStructure> label; @XmlElement(name = "Image") protected ImageStructure image; @XmlElement(name = "LinkContent") @XmlSchemaType(name = "NMTOKEN") protected LinkContentEnumeration linkContent; /** * Gets the value of the uri property. * * @return * possible object is * {@link String } * */ public String getUri() { return uri; } /** * Sets the value of the uri property. * * @param value * allowed object is * {@link String } * */ public void setUri(String value) { this.uri = value; } /** * Gets the value of the label property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the label property. * * <p> * For example, to add a new item, do as follows: * <pre> * getLabel().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link NaturalLanguageStringStructure } * * */ public List<NaturalLanguageStringStructure> getLabel() { if (label == null) { label = new ArrayList<NaturalLanguageStringStructure>(); } return this.label; } /** * Gets the value of the image property. * * @return * possible object is * {@link ImageStructure } * */ public ImageStructure getImage() { return image; } /** * Sets the value of the image property. * * @param value * allowed object is * {@link ImageStructure } * */ public void setImage(ImageStructure value) { this.image = value; } /** * Gets the value of the linkContent property. * * @return * possible object is * {@link LinkContentEnumeration } * */ public LinkContentEnumeration getLinkContent() { return linkContent; } /** * Sets the value of the linkContent property. * * @param value * allowed object is * {@link LinkContentEnumeration } * */ public void setLinkContent(LinkContentEnumeration value) { this.linkContent = value; } }
mit
zhilianxinke/attendance
src/com/sincsmart/attendance/view/HandyTextView.java
600
package com.sincsmart.attendance.view; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; public class HandyTextView extends TextView { public HandyTextView(Context context) { super(context); } public HandyTextView(Context context, AttributeSet attrs) { super(context, attrs); } public HandyTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void setText(CharSequence text, BufferType type) { if (text == null) { text = ""; } super.setText(text, type); } }
mit
garganti/info2_oop_unibg
Temi d'esame/GargantiniAngelo_TE2013/src/pratiche/PraticaTribunale.java
778
package pratiche; import prog.utili.Data; // rapresenta le pratiche civile e penali // che hanno un grado di giudizio abstract public class PraticaTribunale extends PraticaLegale { /** * * @param c * @param d * @param u * @param nol * @param g grado di giudizio */ public PraticaTribunale(String c, String d, Data u, int nol, GradoGidizio g) { super(c, d, u, nol); grado = g; } // costo orario per queste pratiche private static final int COSTO_ORARIO = 100; // protected GradoGidizio grado; @Override int costo() { // dal grado di giudizio * per il numero di ore spese * 100 euro /h, return grado.fattoreCosto * numeroOre * COSTO_ORARIO; } @Override public String toString() { return super.toString() + " GRADO " + grado; } }
mit
Jiaran/Slogo
src/commandTests/RandomTest.java
873
package commandTests; import static org.junit.Assert.*; import model.Arg; import model.EnvironmentVariables; import model.State; import org.junit.Test; import commands.EvalCommands.Random; public class RandomTest { private Random r; private double exampleRandom; public RandomTest() { r = new Random(new State(new EnvironmentVariables())); } @Test public void testSum() { assertNotNull(r); } @Test public void testGetResult() { r = new Random(new State(new EnvironmentVariables())); r.addArg(new Arg(2)); assertTrue(r.doCommand()<2); r = new Random(new State(new EnvironmentVariables())); r.addArg(new Arg(50)); assertTrue(r.doCommand()<50); r = new Random(new State(new EnvironmentVariables())); r.addArg(new Arg(1)); assertTrue(r.doCommand()<1); } @Test public void testGetArgNum() { assertEquals(1, r.getArgNum()); } }
mit
Uniandes-MISO4203/turism-201620-2
turism-api/src/test/java/co/edu/uniandes/csw/turism/resources/QuestionResourceTest.java
2121
package co.edu.uniandes.csw.turism.resources; import co.edu.uniandes.csw.turism.api.IQuestionLogic; import co.edu.uniandes.csw.turism.entities.QuestionEntity; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static co.edu.uniandes.csw.turism.tests.Utils.aQuestionDetailDTO; import static co.edu.uniandes.csw.turism.tests.Utils.aQuestionEntity; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Mockito.*; /** * Created by TOSHIBA on 14/11/2016. */ public class QuestionResourceTest { @Mock private IQuestionLogic questionLogic = mock(IQuestionLogic.class); @InjectMocks private QuestionResource subject; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); when(questionLogic.getQuestion(anyLong())).thenReturn(aQuestionEntity()); } @Test public void shouldNotReturnNullWhenGetQuestions() throws Exception { Assert.assertNotNull(subject.getQuestions()); } @Test public void shouldNotReturnNullWhenGetQuestionById() throws Exception { Assert.assertNotNull(subject.getQuestion(Long.valueOf("0"))); } @Test public void shouldNotReturnNullWhenCreatingQuestion() throws Exception { when(questionLogic.createQuestion(anyLong(), any(QuestionEntity.class))).thenReturn(aQuestionEntity()); Assert.assertNotNull(subject.createQuestion(aQuestionDetailDTO())); } @Test public void shouldNotReturnNullWhenupdatingQuestion() throws Exception { when(questionLogic.updateQuestion(anyLong(), any(QuestionEntity.class))).thenReturn(aQuestionEntity()); Assert.assertNotNull(subject.updateQuestion(Long.valueOf("1"), aQuestionDetailDTO())); } @Test public void shouldDeleteQuestionById() throws Exception { Long questionId = Long.valueOf("1"); subject.deleteQuestion(questionId); verify(questionLogic).deleteQuestion(questionId); } }
mit
valerielashvili/SoftUni-Software-University
Java OOP Basics - October 2017/03.1. Inheritance - Exercises/src/p03_Mankind/Student.java
840
package p03_Mankind; class Student extends Human { private String facultyNumber; Student(String firstName, String lastName, String facultyNumber) { super(firstName, lastName); this.setFacultyNumber(facultyNumber); } private String getFacultyNumber() { return this.facultyNumber; } private void setFacultyNumber(String facultyNumber) { if (facultyNumber.length() < 5 || facultyNumber.length() > 10) { throw new IllegalArgumentException("Invalid faculty number!"); } this.facultyNumber = facultyNumber; } @Override public String toString() { StringBuilder sb = new StringBuilder("Faculty number: "); sb.append(this.getFacultyNumber()).append(System.lineSeparator()); return super.toString() + sb.toString(); } }
mit
catalinboja/cts-2016
1069_Seminar7_3/src/ro/ase/cts/observer/StatieMeteo.java
1078
package ro.ase.cts.observer; import java.util.ArrayList; import java.util.Random; public class StatieMeteo { //stare observabil String locatie; //lista observatori ArrayList<ClientMeteo> clienti = new ArrayList<>(); //interfata publica pt gestiunea observatorilor public void adaugaClient(ClientMeteo client){ this.clienti.add(client); } public void stergeClient(ClientMeteo client){ this.clienti.remove(client); } private void notificaClienti(StareVreme meteo){ if(this.clienti!=null){ for(ClientMeteo client : this.clienti) client.notificareMeteo(meteo); } } //metoda prin care se genereaza un eveniment public void inregistreazaDateMeteo(){ float temp = (new Random()).nextInt(45); float vant = (new Random()).nextInt(200); float umiditate = (new Random()).nextInt(100); StareVreme meteo = new StareVreme( temp, vant, umiditate, this.locatie); //notificare clienti this.notificaClienti(meteo); } public StatieMeteo(String locatie) { super(); this.locatie = locatie; } }
mit
Sreenu-Paila/devopsbuddy
src/main/java/com/devopsbuddy/web/controllers/CopyController.java
314
package com.devopsbuddy.web.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * * @author sreenu * */ @Controller public class CopyController { @RequestMapping("/about") public String about() { return "copy/about"; } }
mit
aaryn101/lol4j
src/main/java/lol4j/protocol/dto/lolstaticdata/RuneListDto.java
925
package lol4j.protocol.dto.lolstaticdata; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.HashMap; import java.util.Map; /** * Created by Aaron Corley on 3/18/14. */ @JsonIgnoreProperties(ignoreUnknown = true) public class RuneListDto { private BasicDataDto basic; private Map<String, BasicDataDto> data = new HashMap<>(); private String type; private String version; public BasicDataDto getBasic() { return basic; } public void setBasic(BasicDataDto basic) { this.basic = basic; } public Map<String, BasicDataDto> getData() { return data; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
mit
SpongeHistory/SpongeAPI-History
src/main/java/org/spongepowered/api/event/inventory/ItemDropEvent.java
1823
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered.org <http://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.event.inventory; import org.spongepowered.api.entity.Item; import org.spongepowered.api.event.GameEvent; import java.util.Collection; /** * Handles when any item or items are dropped on the ground. */ public interface ItemDropEvent extends GameEvent { /** * Gets the items that are being dropped. * * @return The dropped item entities */ Collection<Item> getDroppedItems(); /** * Checks if this is a flowerpot. * * @return Whether this is a flowerpot */ boolean isFlowerPot(); }
mit
Zocket/picoo
src/com/picoo/tutorial/Datetest.java
291
package com.picoo.tutorial; import java.util.Calendar; import java.util.Date; public class Datetest { public static void main(String[] args) { // TODO Auto-generated method stub Date now=Calendar.getInstance().getTime(); System.out.println(now.getTime()/1000); } }
mit
bg1bgst333/Sample
android/ConnectivityManager/ConnectivityManager/src/ConnectivityManager/ConnectivityManager_/gen/com/bgstation0/android/sample/connectivitymanager_/R.java
1913
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.bgstation0.android.sample.connectivitymanager_; public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class id { public static final int button1=0x7f060000; } public static final class layout { public static final int activity_main=0x7f030000; } public static final class string { public static final int app_name=0x7f040000; public static final int button1_text=0x7f040002; public static final int hello_world=0x7f040001; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f050000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f050001; } }
mit
Alex-Diez/data-structure-experiments
java-impl/queues/sequential-benchmarks/src/main/java/ua/ds/experiments/n05/PrimitiveVsBoxed.java
3308
package ua.ds.experiments.n05; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Setup; import ua.ds.QueueBenchmark; import ua.ds.array.boxed.BitMaskResizableNotShrinkArrayQueueBoxed; import ua.ds.array.primitive.BitMaskResizableNotShrinkArrayQueuePrimitive; import ua.ds.linked.boxed.LinkedQueueBoxed; import ua.ds.linked.primitive.LinkedQueuePrimitive; public class PrimitiveVsBoxed extends QueueBenchmark { private BitMaskResizableNotShrinkArrayQueuePrimitive primitiveResize; private BitMaskResizableNotShrinkArrayQueueBoxed boxedResize; private BitMaskResizableNotShrinkArrayQueueBoxed boxedResizeParallel; private BitMaskResizableNotShrinkArrayQueueBoxed boxedResizeCms; private LinkedQueueBoxed linkedQueueBoxed; private LinkedQueueBoxed linkedQueueBoxedParallel; private LinkedQueueBoxed linkedQueueBoxedCms; private LinkedQueuePrimitive linkedQueuePrimitive; private LinkedQueuePrimitive linkedQueuePrimitiveParallel; private LinkedQueuePrimitive linkedQueuePrimitiveCms; @Setup public void setUp() throws Exception { boxedResize = new BitMaskResizableNotShrinkArrayQueueBoxed(); boxedResizeParallel = new BitMaskResizableNotShrinkArrayQueueBoxed(); boxedResizeCms = new BitMaskResizableNotShrinkArrayQueueBoxed(); primitiveResize = new BitMaskResizableNotShrinkArrayQueuePrimitive(); linkedQueueBoxed = new LinkedQueueBoxed(); linkedQueueBoxedParallel = new LinkedQueueBoxed(); linkedQueueBoxedCms = new LinkedQueueBoxed(); linkedQueuePrimitive = new LinkedQueuePrimitive(); linkedQueuePrimitiveParallel = new LinkedQueuePrimitive(); linkedQueuePrimitiveCms = new LinkedQueuePrimitive(); } @Benchmark public int primitives_resize() { return dequeMany(enqueueMany(primitiveResize)); } @Benchmark @Fork(value = 3, jvmArgs = "-XX:+UseG1GC") public int boxed_resize_g1() { return dequeMany(enqueueMany(boxedResize)); } @Benchmark @Fork(value = 3, jvmArgs = "-XX:+UseParallelGC") public int boxed_resize_parallel() { return dequeMany(enqueueMany(boxedResizeParallel)); } @Benchmark @Fork(value = 3, jvmArgs = "-XX:+UseConcMarkSweepGC") public int boxed_resize_cms() { return dequeMany(enqueueMany(boxedResizeCms)); } @Benchmark @Fork(value = 3, jvmArgs = "-XX:+UseG1GC") public int primitives_linked_g1() { return dequeMany(enqueueMany(linkedQueuePrimitive)); } @Benchmark @Fork(value = 3, jvmArgs = "-XX:+UseParallelGC") public int primitives_linked_parallel() { return dequeMany(enqueueMany(linkedQueuePrimitiveParallel)); } @Benchmark @Fork(value = 3, jvmArgs = "-XX:+UseConcMarkSweepGC") public int primitives_linked_cms() { return dequeMany(enqueueMany(linkedQueuePrimitiveCms)); } @Benchmark @Fork(value = 3, jvmArgs = "-XX:+UseG1GC") public int boxed_linked_g1() { return dequeMany(enqueueMany(linkedQueueBoxed)); } @Benchmark @Fork(value = 3, jvmArgs = "-XX:+UseParallelGC") public int boxed_linked_parallel() { return dequeMany(enqueueMany(linkedQueueBoxedParallel)); } @Benchmark @Fork(value = 3, jvmArgs = "-XX:+UseConcMarkSweepGC") public int boxed_linked_cms() { return dequeMany(enqueueMany(linkedQueueBoxedCms)); } }
mit
fsautomata/azure-iot-sdks
java/device/iothub-java-client/src/main/java/com/microsoft/azure/iothub/transport/IotHubTransport.java
2577
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. package com.microsoft.azure.iothub.transport; import com.microsoft.azure.iothub.IotHubServiceboundMessage; import com.microsoft.azure.iothub.IotHubEventCallback; import java.io.IOException; import java.net.URISyntaxException; /** An interface for an IoT Hub transport. */ public interface IotHubTransport { /** * Establishes a communication channel with an IoT Hub. If a channel is * already open, the function shall do nothing. * * @throws IOException if a communication channel cannot be * established. */ void open() throws IOException; /** * Closes all resources used to communicate with an IoT Hub. Once {@code close()} is * called, the transport is no longer usable. If the transport is already * closed, the function shall do nothing. * * @throws IOException if an error occurs in closing the transport. */ void close() throws IOException; /** * Adds a message to the transport queue. * * @param msg the message to be sent. * @param callback the callback to be invoked when a response for the * message is received. * @param callbackContext the context to be passed in when the callback is * invoked. */ void addMessage(IotHubServiceboundMessage msg, IotHubEventCallback callback, Object callbackContext); /** * Sends all messages on the transport queue. If a previous send attempt had * failed, the function will attempt to resend the messages in the previous * attempt. * * @throws IOException if the server could not be reached. */ void sendMessages() throws IOException; /** Invokes the callbacks for all completed requests. */ void invokeCallbacks(); /** * <p> * Invokes the message callback if a message is found and * responds to the IoT Hub on how the processed message should be * handled by the IoT Hub. * </p> * If no message callback is set, the function will do nothing. * * @throws IOException if the server could not be reached. */ void handleMessage() throws IOException; /** * Returns {@code true} if the transport has no more messages to handle, * and {@code false} otherwise. * * @return {@code true} if the transport has no more messages to handle, * and {@code false} otherwise. */ boolean isEmpty(); }
mit
Krigu/bookstore
bookstore-jpa/src/main/java/org/books/data/mapper/AddressMapper.java
1165
package org.books.data.mapper; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.Converter; import org.books.data.dto.AddressDTO; import org.books.data.entity.Address; import java.lang.reflect.InvocationTargetException; public class AddressMapper { class DtoToEntityConverter<AddressDTO> implements Converter { @Override public <T> T convert(Class<T> aClass, Object o) { return (T) toDTO((Address) o); } } public static AddressDTO toDTO(Address address) { AddressDTO addressDTO = new AddressDTO(); try { BeanUtils.copyProperties(addressDTO, address); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } return addressDTO; } public static Address toEntity(AddressDTO addressDTO) { Address address = new Address(); try { BeanUtils.copyProperties(address, addressDTO); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } return address; } }
mit
bacta/swg
game-server/src/main/java/com/ocdsoft/bacta/swg/server/game/group/GroupStringId.java
3455
package com.ocdsoft.bacta.swg.server.game.group; import com.ocdsoft.bacta.swg.shared.localization.StringId; /** * Created by crush on 5/28/2016. * <p> * Just a class to give some type safety and maintainability to group {@link com.ocdsoft.bacta.swg.shared.localization.StringId} * references. */ public final class GroupStringId { public static final StringId MUST_BE_LEADER = new StringId("group", "must_be_leader"); public static final StringId FULL = new StringId("group", "full"); public static final StringId ALREADY_GROUPED = new StringId("group", "already_grouped"); public static final StringId CONSIDERING_YOUR_GROUP = new StringId("group", "considering_your_group"); public static final StringId CONSIDERING_OTHER_GROUP = new StringId("group", "considering_other_group"); public static final StringId INVITE_LEADER = new StringId("group", "invite_leader"); public static final StringId INVITE_TARGET = new StringId("group", "invite_target"); public static final StringId INVITE_NO_TARGET_SELF = new StringId("group", "invite_no_target_self"); public static final StringId MUST_BE_INVITED = new StringId("group", "must_be_invited"); public static final StringId DECLINE_SELF = new StringId("group", "decline_self"); public static final StringId DECLINE_LEADER = new StringId("group", "decline_leader"); public static final StringId UNINVITE_SELF = new StringId("group", "uninvite_self"); public static final StringId UNINVITE_TARGET = new StringId("group", "uninvite_target"); public static final StringId UNINVITE_NOT_INVITED = new StringId("group", "uninvite_not_invited"); public static final StringId UNINVITE_NO_TARGET_SELF = new StringId("group", "uninvite_no_target_self"); public static final StringId NEW_LEADER = new StringId("group", "new_leader"); public static final StringId NEW_MASTER_LOOTER = new StringId("group", "new_master_looter"); public static final StringId FORMED = new StringId("group", "formed_self"); public static final StringId JOIN = new StringId("group", "joined_self"); public static final StringId DISBANDED = new StringId("group", "disbanded"); public static final StringId REMOVED = new StringId("group", "removed"); public static final StringId MUST_EJECT_FIRST = new StringId("group", "must_eject_first"); public static final StringId ONLY_PLAYERS_IN_SPACE = new StringId("group", "only_players_in_space"); public static final StringId NO_DISBAND_OWNER = new StringId("group", "no_disband_owner"); public static final StringId NO_KICK_FROM_SHIP_OWNER = new StringId("group", "no_kick_from_ship_owner"); public static final StringId BEASTS_CANT_JOIN = new StringId("group", "beasts_cant_join"); public static final StringId EXISTING_GROUP_NOT_FOUND = new StringId("group", "existing_group_not_found"); public static final StringId JOIN_INVITER_NOT_LEADER = new StringId("group", "join_inviter_not_leader"); public static final StringId JOIN_FULL = new StringId("group", "join_full"); public static final StringId INVITE_IN_COMBAT = new StringId("group", "invite_in_combat"); public static final StringId INVITE_TARGET_IN_COMBAT = new StringId("group", "invite_target_in_combat"); public static final StringId JOIN_IN_COMBAT = new StringId("group", "join_in_combat"); public static final StringId JOIN_LEADER_IN_COMBAT = new StringId("group", "join_leader_in_combat"); }
mit
Azure/azure-sdk-for-java
sdk/batchai/azure-resourcemanager-batchai/src/main/java/com/azure/resourcemanager/batchai/models/FileServerListResult.java
1943
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.batchai.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.batchai.fluent.models.FileServerInner; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** Values returned by the File Server List operation. */ @Fluent public final class FileServerListResult { @JsonIgnore private final ClientLogger logger = new ClientLogger(FileServerListResult.class); /* * The collection of File Servers. */ @JsonProperty(value = "value") private List<FileServerInner> value; /* * The continuation token. */ @JsonProperty(value = "nextLink", access = JsonProperty.Access.WRITE_ONLY) private String nextLink; /** * Get the value property: The collection of File Servers. * * @return the value value. */ public List<FileServerInner> value() { return this.value; } /** * Set the value property: The collection of File Servers. * * @param value the value value to set. * @return the FileServerListResult object itself. */ public FileServerListResult withValue(List<FileServerInner> value) { this.value = value; return this; } /** * Get the nextLink property: The continuation token. * * @return the nextLink value. */ public String nextLink() { return this.nextLink; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (value() != null) { value().forEach(e -> e.validate()); } } }
mit
asavonic/DotsBoxes
src/dotsboxes/events/GameTurnEvent.java
974
package dotsboxes.events; import dotsboxes.game.TurnDesc; public class GameTurnEvent extends Event { boolean m_edge; // True if player mark edge. TurnDesc m_turnDesc; boolean m_switchTurn; public GameTurnEvent(EventType someThing, boolean edge, TurnDesc turnDesc, boolean switchTurn) { super(someThing); m_edge = edge; m_turnDesc = turnDesc; m_switchTurn = switchTurn; } public GameTurnEvent(EventType someThing, boolean edge, TurnDesc turnDesc) { super(someThing); m_edge = edge; m_turnDesc = turnDesc; m_switchTurn = true; } public boolean isEdgeChanged() { return m_edge; } public int getI() { return m_turnDesc.m_i; } public int getJ() { return m_turnDesc.m_j; } public boolean getVert() { return m_turnDesc.m_vert; } public int getPlrTag() { return m_turnDesc.m_player_tag; } public TurnDesc getTurnDesc() { return m_turnDesc; } public boolean isSwitchTurn() { return m_switchTurn; } }
mit
ExperisIT-rav/Bifhi-release
find-core/src/main/java/com/hp/autonomy/frontend/find/core/beanconfiguration/SecurityConfiguration.java
2213
/* * Copyright 2015 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ package com.hp.autonomy.frontend.find.core.beanconfiguration; import com.hp.autonomy.frontend.find.core.web.FindController; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { public static final String USER_ROLE = "PUBLIC"; public static final String ADMIN_ROLE = "ADMIN"; public static final String CONFIG_ROLE = "DEFAULT"; @Override public void configure(final WebSecurity web) { web.ignoring() .antMatchers("/static-*/**"); } @SuppressWarnings("ProhibitedExceptionDeclared") @Override protected void configure(final HttpSecurity http) throws Exception { final HttpSessionRequestCache requestCache = new HttpSessionRequestCache(); requestCache.setRequestMatcher(new AntPathRequestMatcher(FindController.PUBLIC_PATH)); http .authorizeRequests() .antMatchers("/api/public/**").hasRole(USER_ROLE) .antMatchers("/api/useradmin/**").hasRole(ADMIN_ROLE) .antMatchers("/api/config/**").hasRole(CONFIG_ROLE) .and() .requestCache() .requestCache(requestCache) .and() .csrf() .disable() .headers() .defaultsDisabled() .frameOptions() .sameOrigin(); } }
mit
rdshoep/AndroidDaggerFramework
app/src/main/java/com/rdshoep/android/study/fragment/FragmentProvidesInterface.java
388
package com.rdshoep.android.study.fragment; /* * @description * Please write the FragmentProvidesInterface module's description * @author Zhang (rdshoep@126.com) * http://www.rdshoep.com/ * @version * 1.0.0(11/10/2015) */ import com.rdshoep.android.study.activity.ActivityProvidesInterface; public interface FragmentProvidesInterface extends ActivityProvidesInterface { }
mit
hetmeter/awmm
fender-sb-bdd/src/fsb/semantics/naivepso/SharedResVal.java
3984
package fsb.semantics.naivepso; import java.util.Arrays; import java.util.HashSet; import java.util.WeakHashMap; import fsb.semantics.AbsSharedResVal; import fsb.tvl.ArithValue; import fsb.tvl.DetArithValue; import fsb.utils.Options; public class SharedResVal implements Cloneable, AbsSharedResVal { public enum validity {VALID, NOTVALID, TOP}; private static WeakHashMap<AbstractBuffer, AbstractBuffer> cachedBuffers = new WeakHashMap<AbstractBuffer, AbstractBuffer>(); public class AbstractBuffer implements Cloneable { HashSet<ArithValue> set; public AbstractBuffer() { set = new HashSet<ArithValue>(2); } @SuppressWarnings("unchecked") public AbstractBuffer(AbstractBuffer other) { set = (HashSet<ArithValue>) other.set.clone(); } public Object clone() { AbstractBuffer newbuffer = new AbstractBuffer(this); return newbuffer; } public boolean isEmpty() { return set.isEmpty(); } @Override public int hashCode() { return set.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof AbstractBuffer)) return false; AbstractBuffer other = (AbstractBuffer) obj; return (set.equals(other.set)); } } private ArithValue value; //TODO: Should be private AbstractBuffer buffer[]; SharedResVal(int numProcs, int init) { value = DetArithValue.getInstance(init); buffer = new AbstractBuffer[numProcs]; for (int i = 0; i < numProcs; i++) buffer[i] = new AbstractBuffer(); } public SharedResVal(SharedResVal other) { value = other.value; //Note this is NOT a deep copy. buffer = other.buffer.clone(); if (!Options.LAZY_COPY) { for (int i = 0; i < buffer.length; i++) buffer[i] = (AbstractBuffer) buffer[i].clone(); } } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof SharedResVal)) return false; SharedResVal other = (SharedResVal) obj; return (other.value == value) && (Arrays.equals(other.buffer, buffer)); } @Override public int hashCode() { final int prime = 31; int result = value.hashCode(); result = prime * result + Arrays.hashCode(buffer); return result; } @Override public String toString() { //TODO Fix up to use tail StringBuffer sb = new StringBuffer(); sb.append(value); sb.append(", [["); for (int i = 0; i < buffer.length; i++) { if (!buffer[i].isEmpty()) { sb.append(i); sb.append(": {"); sb.append(buffer[i].set); sb.append("}"); } } sb.append("]]"); return sb.toString(); } @Override public AbsSharedResVal clone() { SharedResVal newval = new SharedResVal(this); return newval; } public ArithValue getGlobalVal() { return value; } public void store(int pid, ArithValue val) { if (Options.LAZY_COPY) buffer[pid] = (AbstractBuffer) buffer[pid].clone(); AbstractBuffer buf = buffer[pid]; buf.set.add(val); AbstractBuffer cached = cachedBuffers.get(buf); if (cached == null) cachedBuffers.put(buf, buf); else buffer[pid] = cached; } public void clearBuffer(int pid) { if (Options.LAZY_COPY) buffer[pid] = (AbstractBuffer) buffer[pid].clone(); buffer[pid].set.clear(); AbstractBuffer cached = cachedBuffers.get(buffer[pid]); if (cached == null) cachedBuffers.put(buffer[pid], buffer[pid]); else buffer[pid] = cached; } public boolean isEmptySet(int pid) { return buffer[pid].set.isEmpty(); } public void directSetValue(ArithValue val) { value = val; } public ArithValue flushDestructive(int pid, ArithValue val) { if (Options.LAZY_COPY) buffer[pid] = (AbstractBuffer) buffer[pid].clone(); buffer[pid].set.remove(val); AbstractBuffer cached = cachedBuffers.get(buffer[pid]); if (cached == null) cachedBuffers.put(buffer[pid], buffer[pid]); else buffer[pid] = cached; return value; } }
mit
xibalbanus/PIA2
pia/phyutility/src/jebl/evolution/align/TracebackPlotter.java
315
package jebl.evolution.align; /** * * @author Alexei Drummond * * @version $Id: TracebackPlotter.java 185 2006-01-23 23:03:18Z rambaut $ * */ public interface TracebackPlotter { void newTraceBack(String sequence1, String sequence2); void traceBack(Traceback t); void finishedTraceBack(); }
mit
Microsoft/vso-httpclient-java
Rest/alm-releasemanagement-client/src/main/generated/com/microsoft/alm/visualstudio/services/releasemanagement/webapi/contracts/ReleaseDefinitionApprovals.java
1288
// @formatter:off /* * --------------------------------------------------------- * Copyright(C) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. See License.txt in the project root. * --------------------------------------------------------- * * --------------------------------------------------------- * Generated file, DO NOT EDIT * --------------------------------------------------------- * * See following wiki page for instructions on how to regenerate: * https://vsowiki.com/index.php?title=Rest_Client_Generation */ package com.microsoft.alm.visualstudio.services.releasemanagement.webapi.contracts; import java.util.ArrayList; /** */ public class ReleaseDefinitionApprovals { private ApprovalOptions approvalOptions; private ArrayList<ReleaseDefinitionApprovalStep> approvals; public ApprovalOptions getApprovalOptions() { return approvalOptions; } public void setApprovalOptions(final ApprovalOptions approvalOptions) { this.approvalOptions = approvalOptions; } public ArrayList<ReleaseDefinitionApprovalStep> getApprovals() { return approvals; } public void setApprovals(final ArrayList<ReleaseDefinitionApprovalStep> approvals) { this.approvals = approvals; } }
mit
buglabs/dweet-apps
Android/DweetLib/java/com/buglabs/dweetlib/DweetLib.java
7551
package com.buglabs.dweetlib; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.lang.reflect.Array; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.json.JSONObject; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.view.ViewParent; import com.buglabs.dweetsensorgateway.MainActivity; // // DweetLib Android // // Pre-Release version // // Created by Tim Buick on 2015-06-10. // Copyright (c) 2015 Bug Labs. All rights reserved. // public class DweetLib { // return codes public static Integer DWEET_STILL_PENDING=1; public static Integer DWEET_SUCCESS=0; public static Integer NO_NETWORK=-1; public static Integer COULD_NOT_CONNECT_TO_DWEETIO=-2; public static Integer DWEET_DID_NOT_RETURN_VALID_JSON=-3; public static Integer DWEET_JSON_FORMAT_UNEXPECTED=-4; public static Integer DWEET_RESPONSE_IS_FAILED=-5; public static Integer COULD_NOT_CONNECT_TO_LOCKED_THING=-6; public static Integer COULD_NOT_GENERATE_JSON_FROM_DATA=-7; public static Integer CONNECTION_ERROR=-8; private static DweetLib instance; HashMap<Object,Object> thingProcess; HashMap<Object,Object> thingProcessUrl; HashMap<Object,Object> thingProcessConnection; HashMap<Object,Object> thingProcessCallback; HashMap<Object,Object> thingProcessCaller; private static Context currentCtx; static { instance = new DweetLib(); } private DweetLib() { thingProcess = new HashMap<>(); thingProcessUrl = new HashMap<>(); thingProcessConnection = new HashMap<>(); thingProcessCallback = new HashMap<>(); thingProcessCaller = new HashMap<>(); } public static DweetLib getInstance(Context ctx) { currentCtx = ctx; return DweetLib.instance; } public interface DweetCallback { void callback(ArrayList<Object> ar); } public String sendDweet (JSONObject data,String thing,String key,Object caller,DweetCallback cb,boolean overwrite) { final String JSONString = data.toString(); final String urlstr = "http://dweet.io/dweet/for/" + thing; DweetTask dt = (DweetTask) thingProcess.get(urlstr); if (!isNetworkingAvailable(currentCtx)) { System.out.println("no network error"); if (caller!=null) { ArrayList ar = new ArrayList<>(); ar.add(NO_NETWORK); cb.callback(ar); } DweetTask x = (DweetTask)thingProcessUrl.get(urlstr); thingProcessUrl.remove(urlstr); thingProcess.remove(x); thingProcessConnection.remove(x); thingProcessCaller.remove(x); thingProcessCallback.remove(x); return ""; } if (dt != null) { System.out.println("still working"); if (overwrite) { System.out.println("overwriting data"); String u = (String) thingProcessUrl.get(dt); thingProcess.remove(u); HttpURLConnection c = (HttpURLConnection) thingProcessConnection.get(dt); thingProcessConnection.remove(dt); thingProcessCallback.remove(dt); thingProcessCaller.remove(dt); c.disconnect(); c = null; dt.cancel(true); thingProcessUrl.remove(dt); dt = null; } } if (dt==null) { System.out.println("starting new dt"); try { URL url = new URL(urlstr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(5000); // ms conn.setConnectTimeout(5000); // ms conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoInput(true); DweetTask x = (DweetTask) new DweetTask().execute(conn,JSONString); thingProcess.put(urlstr,x); thingProcessUrl.put(x, urlstr); thingProcessConnection.put(x, conn); if (caller!=null) thingProcessCaller.put(x,caller); if (cb!=null) thingProcessCallback.put(x,cb); System.out.println("conn:"+conn.hashCode()+", task:"+x.hashCode()); } catch (Exception e) { System.out.println("connection error"); if (caller!=null) { ArrayList ar = new ArrayList<>(); ar.add(CONNECTION_ERROR); cb.callback(ar); } DweetTask x = (DweetTask)thingProcessUrl.get(urlstr); thingProcessUrl.remove(urlstr); thingProcess.remove(x); thingProcessConnection.remove(x); thingProcessCaller.remove(x); thingProcessCallback.remove(x); } } return ""; } private class DweetTask extends AsyncTask<Object,String,Integer> { @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); System.out.println(this.hashCode() + " onPostExecute:" + result); HttpURLConnection c = (HttpURLConnection) thingProcessConnection.get(this); System.out.println("post conn:" + c.hashCode()); String urlstr = (String) thingProcessUrl.get(this); thingProcess.remove(urlstr); thingProcessUrl.remove(this); thingProcessConnection.remove(this); if (thingProcessCaller.get(this)!=null) { DweetCallback dc = (DweetCallback)thingProcessCallback.get(this); ArrayList ar = new ArrayList<>(); ar.add(result); dc.callback(ar); } thingProcessCallback.remove(this); thingProcessCaller.remove(this); } @Override protected Integer doInBackground(Object...params) { System.out.println(this.hashCode() + " doInBackground"); InputStream is = null; String rsp = null; HttpURLConnection conn = (HttpURLConnection) params[0]; String JSONString = (String) params[1]; try { OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(JSONString); wr.flush(); conn.connect(); int response = conn.getResponseCode(); System.out.println(this.hashCode()+" The response is: " + response); is = conn.getInputStream(); String contentAsString = convertStreamToString(is); if (contentAsString.contentEquals("err")) { return DWEET_DID_NOT_RETURN_VALID_JSON; } System.out.println(this.hashCode() + contentAsString); } catch (IOException e) { System.out.println(this.hashCode()+" IO Exception"); return COULD_NOT_CONNECT_TO_DWEETIO; } conn.disconnect(); return DWEET_SUCCESS; } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } } catch (IOException e) { e.printStackTrace(); return "err"; } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); return "err"; } } return sb.toString(); } } private static boolean isNetworkingAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); return (info.isAvailable() && info.isConnected()); } }
mit
VKCOM/vk-java-sdk
sdk/src/main/java/com/vk/api/sdk/exceptions/ApiAppsSubscriptionInvalidStatusException.java
328
// Autogenerated from vk-api-schema. Please don't edit it manually. package com.vk.api.sdk.exceptions; public class ApiAppsSubscriptionInvalidStatusException extends ApiException { public ApiAppsSubscriptionInvalidStatusException(String message) { super(1257, "Subscription is in invalid status", message); } }
mit
Lugribossk/dropwizard-experiment
common/common-server/src/main/java/bo/gotthardt/queue/WorkerConfiguration.java
435
package bo.gotthardt.queue; import lombok.Getter; /** * Configuration for a {@link bo.gotthardt.queue.QueueWorker} subclass that {@link WorkersCommand} should start. * * @author Bo Gotthardt */ @Getter public class WorkerConfiguration { /** The fully qualified class name of the worker. */ private Class<? extends QueueWorker> worker; /** How many threads to start with this worker. */ private int threads = 1; }
mit
TACTfactory/harmony-core
src/com/tactfactory/harmony/test/project/ProjectInitTest.java
5483
/** * This file is part of the Harmony package. * * (c) Mickael Gaillard <mickael.gaillard@tactfactory.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ package com.tactfactory.harmony.test.project; import static org.junit.Assert.assertEquals; import java.util.Collection; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import com.tactfactory.harmony.Harmony; import com.tactfactory.harmony.HarmonyContext; import com.tactfactory.harmony.command.ProjectCommand; import com.tactfactory.harmony.generator.ProjectGenerator; import com.tactfactory.harmony.meta.ApplicationMetadata; import com.tactfactory.harmony.test.CommonTest; /** * Test class for project initialization. */ @RunWith(Parameterized.class) public class ProjectInitTest extends CommonTest { public ProjectInitTest(ApplicationMetadata currentMetadata) throws Exception { super(currentMetadata); } /** * Initialization of the test. * @throws Exception if something bad happened. */ @BeforeClass public static void setUpBefore() { //CommonTest.setUpBefore(); } @Before @Override public final void setUp() throws RuntimeException { super.setUp(); } @After @Override public final void tearDown() throws RuntimeException { super.tearDown(); } @Override public void setUpBeforeNewParameter() throws Exception { super.setUpBeforeNewParameter(); //Force clean all files CommonTest.cleanAndroidFolder(false); } /** * Test the initialization of the android project. */ @Test public final void initAndroid() { System.out.println("\nTest Project init Android"); System.out.println(SHARP_DELIMITOR); // Generate Project CommonTest.getHarmony().findAndExecute(ProjectCommand.INIT_ANDROID, null, null); CommonTest.hasFindFile("android/app/src/main/AndroidManifest.xml"); CommonTest.hasFindFile("android/build.gradle"); CommonTest.hasFindFile("android/app/build.gradle"); //CommonTest.hasFindFile("android/lint.xml"); //this.isFindFile("android/local.properties"); CommonTest.hasFindFile("android/app/proguard-project.txt"); CommonTest.hasFindFile("android/app/src/main/"); CommonTest.hasFindFile(ANDROID_SRC_PATH); CommonTest.hasFindFile(ANDROID_SRC_PATH + this.currentMetadata.getProjectNameSpace().replace('.', '/')); CommonTest.hasFindFile(ANDROID_SRC_PATH + this.currentMetadata.getProjectNameSpace().replace('.', '/') + "/entity"); //this.isFindFile("android/res/"); CommonTest.hasFindFile("android/app/libs"); //CommonTest.hasFindFile("android/libs/android-support-v4.jar"); CommonTest.hasFindFile("android/app/libs/core-annotations.jar"); CommonTest.hasFindFile(ANDROID_RES_PATH); CommonTest.hasFindFile(ANDROID_RES_PATH + "values"); CommonTest.hasFindFile(ANDROID_RES_PATH + "values/configs.xml"); CommonTest.hasFindFile(ANDROID_RES_PATH + "values/strings.xml"); System.out.println("\nTest Update SDK Path"); System.out.println(SHARP_DELIMITOR); String currentSdkPath = ApplicationMetadata.getAndroidSdkPath(); String newSdkPath = "test-sdkpath/"; ApplicationMetadata.setAndroidSdkPath(newSdkPath); ProjectGenerator.updateSDKPath(); final String localProp = String.format("%s/%s", Harmony.getProjectAndroidPath(), "local.properties"); assertEquals(HarmonyContext.getSdkDirFromPropertiesFile(localProp), newSdkPath); ApplicationMetadata.setAndroidSdkPath(currentSdkPath); ProjectGenerator.updateSDKPath(); } /** * Test the initialization of the iPhone project. */ /*@Ignore @Test public final void initIphone() { System.out.println("\nTest Project init iphone"); System.out.println(SHARP_DELIMITOR); CommonTest.getHarmony().findAndExecute( ProjectCommand.INIT_IOS, null, null); // TODO add asserts (for folder/file exist..) }*/ /** * Test the initialization of the RIM project. */ /*@Ignore @Test public final void initRim() { System.out.println("\nTest Project init RIM"); System.out.println(SHARP_DELIMITOR); CommonTest.getHarmony().findAndExecute( ProjectCommand.INIT_RIM, null, null); // TODO add asserts (for folder/file exist..) }*/ /** * Test the initialization of the Windows Phone project. */ /*@Ignore @Test public final void initWindows() { System.out.println("\nTest Project init Windows Phone"); System.out.println(SHARP_DELIMITOR); CommonTest.getHarmony().findAndExecute(ProjectCommand.INIT_WINDOWS, null, null); // TODO add asserts (for folder/file exist..) }*/ @Parameters public static Collection<Object[]> getParameters() { return CommonTest.getParameters(); } }
mit
VunterSlaush/happy_testing
app/src/main/java/mota/dev/happytesting/Repositories/implementations/AppLocalImplementation.java
6687
package mota.dev.happytesting.repositories.implementations; import android.util.Log; import java.util.List; import io.reactivex.Observable; import io.reactivex.Observer; import io.realm.Realm; import io.realm.RealmResults; import mota.dev.happytesting.MyApplication; import mota.dev.happytesting.models.App; import mota.dev.happytesting.models.User; import mota.dev.happytesting.repositories.AppRepository; import mota.dev.happytesting.repositories.RealmRepository; import mota.dev.happytesting.utils.RealmTransactionHelper; /** * Created by Slaush on 29/05/2017. */ public class AppLocalImplementation extends RealmRepository<App> implements AppRepository { private static AppLocalImplementation instance; private AppLocalImplementation() {} public static AppLocalImplementation getInstance() { if (instance == null) instance = new AppLocalImplementation(); return instance; } @Override public Observable<App> create(final String name, final List<User> users) { return new Observable<App>() { @Override protected void subscribeActual(final Observer<? super App> observer) { RealmTransactionHelper.executeTransaction(new RealmTransactionHelper.OnResultTransaction<App>() { @Override public App action(Realm realm) { App app = realm.createObject(App.class, name); app.setUsers(users); final App localApp = new App(); localApp.copy(app); return localApp; } @Override public void onFinalize(App app) { observer.onNext(app); observer.onComplete(); } @Override public void error(Exception e) { Log.d("MOTA--->","ERRRO>"+e.getMessage()); observer.onError(new Throwable("Aplicacion Existente!")); } }); } }; } @Override public Observable<List<App>> getAll() { return new Observable<List<App>>() { @Override protected void subscribeActual(Observer<? super List<App>> observer) { Realm realm = Realm.getDefaultInstance(); RealmResults<App> results = realm.where(App.class).findAll(); List<App> list = realm.copyFromRealm(results); observer.onNext(list); observer.onComplete(); realm.close(); } }; } @Override public Observable<App> get(final int id, final String appName) { return new Observable<App>() { @Override protected void subscribeActual(Observer<? super App> observer) { Realm realm = Realm.getDefaultInstance(); App app = realm.where(App.class) .equalTo("id", id) .or().equalTo("name", appName) .findFirst(); App aux = new App(); aux.copy(app); realm.close(); if (app != null) { observer.onNext(aux); observer.onComplete(); Log.i("MOTA","App Conseguida!"); } else { observer.onError(new Throwable("Aplicacion no encontrada")); } // } }; } @Override public Observable<App> modifiy(final App app) { return new Observable<App>() { @Override protected void subscribeActual(final Observer<? super App> observer) { RealmTransactionHelper.executeTransaction(new RealmTransactionHelper.OnResultTransaction<App>() { @Override public App action(Realm realm) { realm.copyToRealmOrUpdate(app); App aux = new App(); aux.copy(app); //hate to make copies .. x_x hate realm at all .. return app; } @Override public void onFinalize(App app) { observer.onNext(app); observer.onComplete(); } @Override public void error(Exception e) { Log.i("MOTA--","Error on Modify:"+e.getMessage()); observer.onError(new Throwable("Error inesperado")); } }); } }; } @Override public Observable<Boolean> delete(final App app) { return new Observable<Boolean>() { @Override protected void subscribeActual(final Observer<? super Boolean> observer) { RealmTransactionHelper.executeTransaction(new RealmTransactionHelper.OnTransaction() { @Override public void action(Realm realm) { RealmResults<App> result = realm.where(App.class) .equalTo("name", app.getName()) .findAll(); result.deleteAllFromRealm(); observer.onNext(true); observer.onComplete(); } @Override public void error(Exception e) { observer.onNext(false); observer.onComplete(); } }); } }; } @Override public void updateApps(final List<App> apps) { deleteItemsIfNeeded(apps); RealmTransactionHelper.executeTransaction(new RealmTransactionHelper.OnTransaction() { @Override public void action(Realm realm) { for (App app : apps) { try { App appSaved = realm.where(App.class).equalTo("name", app.getName()).findFirst(); if (appSaved != null) appSaved.setId(app.getId()); else realm.copyToRealmOrUpdate(app); } catch (Exception e) { } } } @Override public void error(Exception e) { } }); } }
mit
emacslisp/Java
JSPMainProject/src/com/lab/test/package-info.java
59
/** * */ /** * @author ewu * */ package com.lab.test;
mit
Azure/azure-sdk-for-java
sdk/consumption/azure-resourcemanager-consumption/src/main/java/com/azure/resourcemanager/consumption/implementation/ReservationsDetailsImpl.java
3954
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.consumption.implementation; import com.azure.core.http.rest.PagedIterable; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.consumption.fluent.ReservationsDetailsClient; import com.azure.resourcemanager.consumption.fluent.models.ReservationDetailInner; import com.azure.resourcemanager.consumption.models.ReservationDetail; import com.azure.resourcemanager.consumption.models.ReservationsDetails; import com.fasterxml.jackson.annotation.JsonIgnore; public final class ReservationsDetailsImpl implements ReservationsDetails { @JsonIgnore private final ClientLogger logger = new ClientLogger(ReservationsDetailsImpl.class); private final ReservationsDetailsClient innerClient; private final com.azure.resourcemanager.consumption.ConsumptionManager serviceManager; public ReservationsDetailsImpl( ReservationsDetailsClient innerClient, com.azure.resourcemanager.consumption.ConsumptionManager serviceManager) { this.innerClient = innerClient; this.serviceManager = serviceManager; } public PagedIterable<ReservationDetail> listByReservationOrder(String reservationOrderId, String filter) { PagedIterable<ReservationDetailInner> inner = this.serviceClient().listByReservationOrder(reservationOrderId, filter); return Utils.mapPage(inner, inner1 -> new ReservationDetailImpl(inner1, this.manager())); } public PagedIterable<ReservationDetail> listByReservationOrder( String reservationOrderId, String filter, Context context) { PagedIterable<ReservationDetailInner> inner = this.serviceClient().listByReservationOrder(reservationOrderId, filter, context); return Utils.mapPage(inner, inner1 -> new ReservationDetailImpl(inner1, this.manager())); } public PagedIterable<ReservationDetail> listByReservationOrderAndReservation( String reservationOrderId, String reservationId, String filter) { PagedIterable<ReservationDetailInner> inner = this.serviceClient().listByReservationOrderAndReservation(reservationOrderId, reservationId, filter); return Utils.mapPage(inner, inner1 -> new ReservationDetailImpl(inner1, this.manager())); } public PagedIterable<ReservationDetail> listByReservationOrderAndReservation( String reservationOrderId, String reservationId, String filter, Context context) { PagedIterable<ReservationDetailInner> inner = this .serviceClient() .listByReservationOrderAndReservation(reservationOrderId, reservationId, filter, context); return Utils.mapPage(inner, inner1 -> new ReservationDetailImpl(inner1, this.manager())); } public PagedIterable<ReservationDetail> list(String scope) { PagedIterable<ReservationDetailInner> inner = this.serviceClient().list(scope); return Utils.mapPage(inner, inner1 -> new ReservationDetailImpl(inner1, this.manager())); } public PagedIterable<ReservationDetail> list( String scope, String startDate, String endDate, String filter, String reservationId, String reservationOrderId, Context context) { PagedIterable<ReservationDetailInner> inner = this.serviceClient().list(scope, startDate, endDate, filter, reservationId, reservationOrderId, context); return Utils.mapPage(inner, inner1 -> new ReservationDetailImpl(inner1, this.manager())); } private ReservationsDetailsClient serviceClient() { return this.innerClient; } private com.azure.resourcemanager.consumption.ConsumptionManager manager() { return this.serviceManager; } }
mit
tdelev/web-proceedings
src/main/java/org/ictact/webproceedings/service/impl/ConferenceMetaServiceImpl.java
803
package org.ictact.webproceedings.service.impl; import org.ictact.webproceedings.model.ConferenceMeta; import org.ictact.webproceedings.repository.ConferenceMetaRepository; import org.ictact.webproceedings.service.ConferenceMetaService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ConferenceMetaServiceImpl extends BaseEntityCrudServiceImpl<ConferenceMeta, ConferenceMetaRepository> implements ConferenceMetaService { @Autowired private ConferenceMetaRepository repository; @Override protected ConferenceMetaRepository getRepository() { return repository; } @Override public ConferenceMeta findByConferenceId(Long id) { return repository.findByConferenceId(id); } }
mit
a64adam/ulti
src/main/java/dto/staticdata/BasicData.java
3437
/* * The MIT License (MIT) * * Copyright (c) 2014 Adam Alyyan * * 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 dto.staticdata; import java.util.List; import java.util.Map; public class BasicData { private String colloq; private boolean consumeOnFull; private boolean consumed; private int depth; private String description; private List<String> from; private Gold gold; private String group; private boolean hideFromAll; private int id; private Image image; private boolean inStore; private List<String> into; private Map<String, Boolean> maps; private String name; private String plaintext; private String requiredChampion; private MetaData rune; private String sanitizedDescription; private int specialRecipe; private int stacks; private BasicDataStats stats; private List<String> tags; public String getColloq() { return colloq; } public boolean isConsumeOnFull() { return consumeOnFull; } public int getDepth() { return depth; } public boolean isConsumed() { return consumed; } public String getDescription() { return description; } public List<String> getFrom() { return from; } public Gold getGold() { return gold; } public String getGroup() { return group; } public boolean isHideFromAll() { return hideFromAll; } public int getId() { return id; } public Image getImage() { return image; } public boolean isInStore() { return inStore; } public List<String> getInto() { return into; } public Map<String, Boolean> getMaps() { return maps; } public String getName() { return name; } public String getRequiredChampion() { return requiredChampion; } public String getPlaintext() { return plaintext; } public MetaData getRune() { return rune; } public String getSanitizedDescription() { return sanitizedDescription; } public int getSpecialRecipe() { return specialRecipe; } public int getStacks() { return stacks; } public BasicDataStats getStats() { return stats; } public List<String> getTags() { return tags; } }
mit
SINTEF-9012/autorealspl
no.sintef.autorealspl.converter.parent/no.sintef.bvr.model/src/bvr/impl/CompoundNodeImpl.java
4934
/******************************************************************************* * Copyright (c) * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ /** */ package bvr.impl; import bvr.BvrPackage; import bvr.CompoundNode; import bvr.Target; import bvr.VNode; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Compound Node</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link bvr.impl.CompoundNodeImpl#getMember <em>Member</em>}</li> * <li>{@link bvr.impl.CompoundNodeImpl#getOwnedTargets <em>Owned Targets</em>}</li> * </ul> * </p> * * @generated */ public abstract class CompoundNodeImpl extends VNodeImpl implements CompoundNode { /** * The cached value of the '{@link #getMember() <em>Member</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMember() * @generated * @ordered */ protected EList<VNode> member; /** * The cached value of the '{@link #getOwnedTargets() <em>Owned Targets</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOwnedTargets() * @generated * @ordered */ protected EList<Target> ownedTargets; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CompoundNodeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return BvrPackage.Literals.COMPOUND_NODE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<VNode> getMember() { if (member == null) { member = new EObjectContainmentEList<VNode>(VNode.class, this, BvrPackage.COMPOUND_NODE__MEMBER); } return member; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Target> getOwnedTargets() { if (ownedTargets == null) { ownedTargets = new EObjectContainmentEList<Target>(Target.class, this, BvrPackage.COMPOUND_NODE__OWNED_TARGETS); } return ownedTargets; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case BvrPackage.COMPOUND_NODE__MEMBER: return ((InternalEList<?>)getMember()).basicRemove(otherEnd, msgs); case BvrPackage.COMPOUND_NODE__OWNED_TARGETS: return ((InternalEList<?>)getOwnedTargets()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case BvrPackage.COMPOUND_NODE__MEMBER: return getMember(); case BvrPackage.COMPOUND_NODE__OWNED_TARGETS: return getOwnedTargets(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case BvrPackage.COMPOUND_NODE__MEMBER: getMember().clear(); getMember().addAll((Collection<? extends VNode>)newValue); return; case BvrPackage.COMPOUND_NODE__OWNED_TARGETS: getOwnedTargets().clear(); getOwnedTargets().addAll((Collection<? extends Target>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case BvrPackage.COMPOUND_NODE__MEMBER: getMember().clear(); return; case BvrPackage.COMPOUND_NODE__OWNED_TARGETS: getOwnedTargets().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case BvrPackage.COMPOUND_NODE__MEMBER: return member != null && !member.isEmpty(); case BvrPackage.COMPOUND_NODE__OWNED_TARGETS: return ownedTargets != null && !ownedTargets.isEmpty(); } return super.eIsSet(featureID); } } //CompoundNodeImpl
mit
ArjanO/Purify
src/test/resources/callgraph/Demo2.java
1444
/** * Copyright (c) 2013 HAN University of Applied Sciences * Arjan Oortgiese * Boyd Hofman * Joëll Portier * Michiel Westerbeek * Tim Waalewijn * * 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. */ /** * This code file is used by CallGraphTest. * * @author Tim */ public class Demo2 { int i; public Demo2(String s) { new Demo1(); } public Demo3 dummymethod() { return null; } }
mit
llun/Tent
src/in/th/llun/tent/model/RemoteCollection.java
543
package in.th.llun.tent.model; import java.util.List; public class RemoteCollection<E extends RemoteObject> implements RemoteObject { protected List<E> mRaws; public RemoteCollection(List<E> raws) { mRaws = raws; } public List<E> collection() { return mRaws; } public String rawString() { StringBuilder builder = new StringBuilder("["); for (RemoteObject raw : mRaws) { builder.append(String.format("%s,", raw)); } builder.deleteCharAt(builder.length() - 1); builder.append("]"); return builder.toString(); } }
mit
climagiste/recursing-figures-java
submission-2/RecursiveFlowers.java
3903
/* * * Christopher Lirette clirett * * RecursiveFlowers.java * * This program draws several flowers by mapping a curve 360 degrees at * a center pivot point. * * The basic algorithm here is based on the Rose.java file from * the Java: Introduction to Computer Science textbook website, * introcs.cs.princeton.edu. This program helped me learn to manipulate * the scale of an image, as well as the way one can easily transform * one drawing to another by changing certain key parameters. Right now, * the program draws one certain flower (an "orchid"), but it could be * modified to draw different flowers with different shapes by requesting * the user's input, and storing it in the flowerName variable. * * THIS CODE IS MY OWN WORK, IT WAS WRITTEN WITHOUT CONSULTING * CODE WRITTEN BY OTHER STUDENTS. Christopher Lirette_ * */ import java.awt.*; public class RecursiveFlowers { // My own private green. private static Color VERT = new Color(163, 211, 156); private static int counter; // This method draws the flower. It also calls the flowerName to change // the parameters/draw new shapes, which indirectly recurses on flower public static void flower ( int N, double t, double x0, double y0, String flowerName ) { // This is the stop condition, which counts the number of stacks // before popping them off. I've limited it this way, because this // program becomes quickly capable of overflowing, and it gives me // more flexibility with types of flowers drawn if ( counter == 3000 ) return; // The math behind drawing a polar equation is best explained here: // http://jwilson.coe.uga.edu/EMT668/EMAT6680.2003.fall/Shiver/assignment11/PolarGraphs.htm double theta = Math.toRadians(t); double r = Math.sin( N * theta ); double x1 = r * Math.cos( theta ); double y1 = r * Math.sin( theta ); StdDraw.line( x0, y0, x1, y1 ); x0 = x1; y0 = y1; t += 0.99; counter += 1; // These if conditions create different drawings, calling specific // functions for each flower if (flowerName == "insideyellow") { insideyellow(N, t, x0, y0, flowerName); } if (flowerName == "orchid") { orchid(N, t, x0, y0, flowerName); } } // This draws the inside of a flower public static void insideyellow(int N, double t, double x1, double y1, String flowerName) { // Set out colors StdDraw.setPenColor(StdDraw.YELLOW); // Pass in these parameters for the "first" flower image if ( t <= 540) { StdDraw.setPenColor(StdDraw.YELLOW); flower ( N, t, x1 / .2, y1 / .2, flowerName ); } else { return; } } // This method calls the orchid public static void orchid(int N, double t, double x1, double y1, String flowerName ) { // draw this until 2000, then revert to the standard parameters if ( counter == 2000 ) return; // for the first 360, it is basically a 12 sided flower if ( t < 360 ) { StdDraw.setPenRadius(0.002); StdDraw.setPenColor(StdDraw.BOOK_RED); flower(N, t, x1 / 0.1, y1 / 0.1, flowerName); // then it adds something } else if ( t < 720 ) { StdDraw.setPenColor(Color.MAGENTA); flower(N - 1, 0, 7.5, 7.5, flowerName); } } public static void main( String[] args) { StdDraw.setXscale( -10, +10 ); StdDraw.setYscale( -10, + 10 ); StdDraw.clear(StdDraw.PINK); double x0 = 0, y0 = 0, t = 0; flower ( 6, t, x0, y0, "orchid" ); flower ( 6, .53, x0, y0, "insideyellow" ); } }
mit
Nihility-Ming/note_for_Java_EE
Spring_day01/src/com/itheima/c_inject/c_factory/TestFactory.java
831
package com.itheima.c_inject.c_factory; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestFactory { @Test public void demo01(){ //自定义实例工厂 //1 创建工厂 MyBeanFactory myBeanFactory = new MyBeanFactory(); //2 通过工厂实例,获得对象 UserService userService = myBeanFactory.createService(); userService.addUser(); } @Test public void demo02(){ //spring 工厂 String xmlPath = "com/itheima/c_inject/c_factory/beans.xml"; ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath); UserService userService = applicationContext.getBean("userServiceId" ,UserService.class); userService.addUser(); } }
mit
lakshmi-nair/mozu-java
mozu-java-core/src/main/java/com/mozu/api/clients/commerce/catalog/admin/MasterCatalogClient.java
7713
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.clients.commerce.catalog.admin; import java.util.List; import java.util.ArrayList; import com.mozu.api.MozuClient; import com.mozu.api.MozuClientFactory; import com.mozu.api.MozuUrl; import com.mozu.api.Headers; import org.joda.time.DateTime; import com.mozu.api.security.AuthTicket; import org.apache.commons.lang.StringUtils; /** <summary> * Use the Master Catalog resource to view details of the master catalogs associated with a tenant and to manage the product publishing mode for each master catalog. * </summary> */ public class MasterCatalogClient { /** * Retrieve the details of all master catalog associated with a tenant. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.MasterCatalogCollection> mozuClient=GetMasterCatalogsClient(); * client.setBaseAddress(url); * client.executeRequest(); * MasterCatalogCollection masterCatalogCollection = client.Result(); * </code></pre></p> * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.MasterCatalogCollection> * @see com.mozu.api.contracts.productadmin.MasterCatalogCollection */ public static MozuClient<com.mozu.api.contracts.productadmin.MasterCatalogCollection> getMasterCatalogsClient() throws Exception { return getMasterCatalogsClient( null); } /** * Retrieve the details of all master catalog associated with a tenant. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.MasterCatalogCollection> mozuClient=GetMasterCatalogsClient( responseFields); * client.setBaseAddress(url); * client.executeRequest(); * MasterCatalogCollection masterCatalogCollection = client.Result(); * </code></pre></p> * @param responseFields Use this field to include those fields which are not included by default. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.MasterCatalogCollection> * @see com.mozu.api.contracts.productadmin.MasterCatalogCollection */ public static MozuClient<com.mozu.api.contracts.productadmin.MasterCatalogCollection> getMasterCatalogsClient(String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.MasterCatalogUrl.getMasterCatalogsUrl(responseFields); String verb = "GET"; Class<?> clz = com.mozu.api.contracts.productadmin.MasterCatalogCollection.class; MozuClient<com.mozu.api.contracts.productadmin.MasterCatalogCollection> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.MasterCatalogCollection>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); return mozuClient; } /** * Retrieve the details of the master catalog specified in the request. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.MasterCatalog> mozuClient=GetMasterCatalogClient( masterCatalogId); * client.setBaseAddress(url); * client.executeRequest(); * MasterCatalog masterCatalog = client.Result(); * </code></pre></p> * @param masterCatalogId The unique identifier of the master catalog associated with the entity. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.MasterCatalog> * @see com.mozu.api.contracts.productadmin.MasterCatalog */ public static MozuClient<com.mozu.api.contracts.productadmin.MasterCatalog> getMasterCatalogClient(Integer masterCatalogId) throws Exception { return getMasterCatalogClient( masterCatalogId, null); } /** * Retrieve the details of the master catalog specified in the request. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.MasterCatalog> mozuClient=GetMasterCatalogClient( masterCatalogId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * MasterCatalog masterCatalog = client.Result(); * </code></pre></p> * @param masterCatalogId The unique identifier of the master catalog associated with the entity. * @param responseFields Use this field to include those fields which are not included by default. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.MasterCatalog> * @see com.mozu.api.contracts.productadmin.MasterCatalog */ public static MozuClient<com.mozu.api.contracts.productadmin.MasterCatalog> getMasterCatalogClient(Integer masterCatalogId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.MasterCatalogUrl.getMasterCatalogUrl(masterCatalogId, responseFields); String verb = "GET"; Class<?> clz = com.mozu.api.contracts.productadmin.MasterCatalog.class; MozuClient<com.mozu.api.contracts.productadmin.MasterCatalog> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.MasterCatalog>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); return mozuClient; } /** * Updates the product publishing mode for the master catalog specified in the request. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.MasterCatalog> mozuClient=UpdateMasterCatalogClient( masterCatalog, masterCatalogId); * client.setBaseAddress(url); * client.executeRequest(); * MasterCatalog masterCatalog = client.Result(); * </code></pre></p> * @param masterCatalogId * @param masterCatalog Properties of a master product catalog defined for a tenant. All catalogs and sites associated with a master catalog share product definitions. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.MasterCatalog> * @see com.mozu.api.contracts.productadmin.MasterCatalog * @see com.mozu.api.contracts.productadmin.MasterCatalog */ public static MozuClient<com.mozu.api.contracts.productadmin.MasterCatalog> updateMasterCatalogClient(com.mozu.api.contracts.productadmin.MasterCatalog masterCatalog, Integer masterCatalogId) throws Exception { return updateMasterCatalogClient( masterCatalog, masterCatalogId, null); } /** * Updates the product publishing mode for the master catalog specified in the request. * <p><pre><code> * MozuClient<com.mozu.api.contracts.productadmin.MasterCatalog> mozuClient=UpdateMasterCatalogClient( masterCatalog, masterCatalogId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * MasterCatalog masterCatalog = client.Result(); * </code></pre></p> * @param masterCatalogId * @param responseFields Use this field to include those fields which are not included by default. * @param masterCatalog Properties of a master product catalog defined for a tenant. All catalogs and sites associated with a master catalog share product definitions. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.productadmin.MasterCatalog> * @see com.mozu.api.contracts.productadmin.MasterCatalog * @see com.mozu.api.contracts.productadmin.MasterCatalog */ public static MozuClient<com.mozu.api.contracts.productadmin.MasterCatalog> updateMasterCatalogClient(com.mozu.api.contracts.productadmin.MasterCatalog masterCatalog, Integer masterCatalogId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.catalog.admin.MasterCatalogUrl.updateMasterCatalogUrl(masterCatalogId, responseFields); String verb = "PUT"; Class<?> clz = com.mozu.api.contracts.productadmin.MasterCatalog.class; MozuClient<com.mozu.api.contracts.productadmin.MasterCatalog> mozuClient = (MozuClient<com.mozu.api.contracts.productadmin.MasterCatalog>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(masterCatalog); return mozuClient; } }
mit
ngageoint/geopackage-android
geopackage-sdk/src/main/java/mil/nga/geopackage/user/custom/UserCustomCursor.java
2317
package mil.nga.geopackage.user.custom; import android.database.Cursor; import java.util.List; import mil.nga.geopackage.user.UserCursor; import mil.nga.geopackage.user.UserDao; import mil.nga.geopackage.user.UserInvalidCursor; /** * User Custom Cursor to wrap a database Cursor for tile queries * * @author osbornb * @since 3.0.1 */ public class UserCustomCursor extends UserCursor<UserCustomColumn, UserCustomTable, UserCustomRow> { /** * Constructor * * @param table user custom table * @param cursor cursor */ public UserCustomCursor(UserCustomTable table, Cursor cursor) { this(table, null, cursor); } /** * Constructor * * @param table user custom table * @param columns columns * @param cursor cursor * @since 3.5.0 */ public UserCustomCursor(UserCustomTable table, String[] columns, Cursor cursor) { super(table, columns, cursor); } /** * {@inheritDoc} */ @Override public UserCustomRow getRow(int[] columnTypes, Object[] values) { return new UserCustomRow(getTable(), getColumns(), columnTypes, values); } /** * {@inheritDoc} */ @Override public UserCustomColumns getColumns() { return (UserCustomColumns) super.getColumns(); } /** * Enable requery attempt of invalid rows after iterating through original query rows. * Only supported for {@link #moveToNext()} and {@link #getRow()} usage. * * @param dao data access object used to perform requery */ public void enableInvalidRequery(UserCustomDao dao) { super.enableInvalidRequery(dao); } /** * {@inheritDoc} */ @Override protected UserInvalidCursor<UserCustomColumn, UserCustomTable, UserCustomRow, ? extends UserCursor<UserCustomColumn, UserCustomTable, UserCustomRow>, ? extends UserDao<UserCustomColumn, UserCustomTable, UserCustomRow, ? extends UserCursor<UserCustomColumn, UserCustomTable, UserCustomRow>>> createInvalidCursor(UserDao dao, UserCursor cursor, List<Integer> invalidPositions, List<UserCustomColumn> blobColumns) { return new UserCustomInvalidCursor((UserCustomDao) dao, (UserCustomCursor) cursor, invalidPositions, blobColumns); } }
mit
desweemerl/erp-lib-server
src/main/java/com/erp/lib/server/exception/UnauthorizedException.java
96
package com.erp.lib.server.exception; public class UnauthorizedException extends Exception { }
mit
highj/highj
src/main/java/org/highj/data/structural/dual/DualMonoid.java
441
package org.highj.data.structural.dual; import org.derive4j.hkt.__2; import org.derive4j.hkt.__3; import org.highj.data.structural.Dual; import org.highj.typeclass0.group.Monoid; public interface DualMonoid<M, A, B> extends DualSemigroup<M, A, B>, Monoid<__3<Dual.µ, M, A, B>> { @Override Monoid<__2<M, B, A>> get(); @Override default __3<Dual.µ, M, A, B> identity() { return Dual.of(get().identity()); } }
mit
BitLimit/NPCs
src/main/java/com/bitlimit/NPCs/BlacksmithInteractBehavior.java
10711
package com.bitlimit.NPCs; import de.kumpelblase2.remoteentities.RemoteEntities; import de.kumpelblase2.remoteentities.api.DespawnReason; import de.kumpelblase2.remoteentities.api.RemoteEntity; import de.kumpelblase2.remoteentities.api.thinking.InteractBehavior; import de.kumpelblase2.remoteentities.api.thinking.goals.DesireLookAtNearest; import de.kumpelblase2.remoteentities.api.thinking.goals.DesireLookRandomly; import de.kumpelblase2.remoteentities.entities.RemotePlayer; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.event.weather.WeatherChangeEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; public class BlacksmithInteractBehavior extends InteractBehavior { private static Material defaultItem = Material.DIAMOND_AXE; private final Plugin plugin; public BlacksmithInteractBehavior(RemoteEntity inEntity) { super(inEntity); this.plugin = inEntity.getManager().getPlugin(); this.onEntityUpdate(); } public void onEntityUpdate() { if (this.m_entity.getBukkitEntity() == null) { return; } this.m_entity.setPushable(false); this.m_entity.setStationary(true); Player npc = (Player)this.m_entity.getBukkitEntity(); npc.setCanPickupItems(false); // Set tools and armor. ItemStack axe = new ItemStack(defaultItem); axe.addUnsafeEnchantment(Enchantment.SILK_TOUCH, 10); npc.setItemInHand(axe); // Armor ItemStack[] armor = new ItemStack[4]; armor[3] = new ItemStack(Material.LEATHER_HELMET); armor[2] = new ItemStack(Material.LEATHER_CHESTPLATE); armor[1] = new ItemStack(Material.IRON_LEGGINGS); armor[0] = new ItemStack(Material.LEATHER_BOOTS); // Set it backwards just for our own sanity. for (ItemStack itemStack : armor) itemStack.addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 10); // Give it that glowing feeling. npc.getInventory().setArmorContents(armor); // Set it. } public void onInteract(Player inPlayer) { } public void onRightClickInteractEventWithPlayer(Player player) { RemotePlayer behaviorEntity = (RemotePlayer) this.getRemoteEntity(); Player npc = behaviorEntity.getBukkitEntity(); ItemStack actionItem = player.getItemInHand(); if (actionItem.getType() == Material.NAME_TAG) { if (actionItem.getItemMeta().hasDisplayName()) { String previousName = behaviorEntity.getName(); behaviorEntity.setName(ChatColor.ITALIC + actionItem.getItemMeta().getDisplayName()); Bukkit.broadcastMessage(ChatColor.GOLD + previousName + " is now " + behaviorEntity.getName()); this.onEntityUpdate(); return; } else { player.sendMessage(ChatColor.GOLD + "This entity's ID is \"" + behaviorEntity.getID() + "\"."); return; } } if (npc.getItemInHand().getType() != defaultItem) { player.sendMessage(ChatColor.AQUA + npc.getDisplayName() + ChatColor.RED + " is busy!"); return; } else if (actionItem.getMaxStackSize() != 1) { return; } else if (actionItem.getType() == Material.POTION) { return; } else if (actionItem.getDurability() == 0) { player.sendMessage(ChatColor.RED + "Item is fully repaired."); return; } // Creative mode users will be using this as a utility. if (player.getGameMode() == GameMode.CREATIVE) { actionItem.setDurability((short)0); return; // Repair instantly and call it a day. } // Record where the player had the item for their convenience. int indexOfPreviouslyHeldItem = player.getInventory().getHeldItemSlot(); // Take the item from the player and put it in the NPC's hand. player.setItemInHand(new ItemStack(Material.AIR)); npc.setItemInHand(actionItem); // Capture the NPC's location and grab the closest anvil. Location npcLocation = npc.getLocation(); Location destination = closestLocation(npcLocation, Material.ANVIL); // Disable the NPC gazing around. DesireLookRandomly desireLookRandomly = behaviorEntity.getMind().getMovementDesire(DesireLookRandomly.class); desireLookRandomly.stopExecuting(); DesireLookAtNearest desireLookAtNearest = behaviorEntity.getMind().getMovementDesire(DesireLookAtNearest.class); behaviorEntity.move(destination); behaviorEntity.lookAt(destination); double distanceAway = npcLocation.distance(destination); class FinishRepairTrip implements Runnable { private final Player npc; private final Location gaze; public FinishRepairTrip(Player npc, Location gaze) { this.npc = npc; this.gaze = gaze; } public void run() { if (!this.gaze.equals(this.npc.getLocation())) // Pretend he's working at the anvil. npc.setSneaking(true); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { public void run() { npc.setSneaking(false); // Return to standing. npc.getWorld().playSound(npc.getLocation(), Sound.ANVIL_USE, 1F, 1F); // Simulate a repair. :P } }, 20L); } } Long wait = Math.round((distanceAway / 4) * 20); // Calculates the time needed to wait for the next operation (this is all async, so the delay isn't pre-factored. Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new FinishRepairTrip(npc, destination), wait); // Actually repair the item. actionItem.setDurability((short) 0); class ReturnNPC implements Runnable { private final Location returnLocation; private final RemotePlayer entity; private final Player toLookAt; public ReturnNPC(Location returnLocation, RemotePlayer entity, Player player) { this.returnLocation = returnLocation; this.entity = entity; this.toLookAt = player; } public void run() { // Walk the NPC back to its original location. this.entity.move(this.returnLocation); // Turn back to the player to correspond with te walking. entity.lookAt(this.toLookAt); } } Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new ReturnNPC(npcLocation, behaviorEntity, player), wait + 20L); // Ran once the NPC is actually back near the player. class ReturnItem implements Runnable { private final Player player; private final ItemStack item; private final Player npc; private final int attemptSlot; public ReturnItem(Player player, ItemStack item, Player npc, int attemptSlot) { this.player = player; this.item = item; this.npc = npc; this.attemptSlot = attemptSlot; } public void run() { if (this.player.getInventory().getItem(this.attemptSlot) == null && this.player.isOnline()) { // Called if the player still has a free slot where the item originated from. this.player.getInventory().setItem(this.attemptSlot, this.item); } else if (this.player.getInventory().firstEmpty() != -1 && this.player.isOnline()) { // Called if the player has a free space, but it's not the origin slot. this.player.getInventory().setItem(this.player.getInventory().firstEmpty(), this.item); } else { // Called only if the player isn't online or has a full inventory. Avoid if possible to prevent item destruction. npc.getLocation().getWorld().dropItem(npc.getLocation(), this.item); } // Display anvil-names, if it has one. if (item.getItemMeta().hasDisplayName()) { this.player.sendMessage(ChatColor.AQUA + this.npc.getDisplayName() + ChatColor.GREEN + " repaired " + ChatColor.YELLOW + item.getItemMeta().getDisplayName() + ChatColor.GREEN + "."); } else { this.player.sendMessage(ChatColor.AQUA + this.npc.getDisplayName() + ChatColor.GREEN + " repaired your " + ChatColor.YELLOW + item.getType().name().replace("_", " ").toLowerCase() + ChatColor.GREEN + "."); } // Put the blacksmith's default item back in his hand. ItemStack axe = new ItemStack(defaultItem); axe.addEnchantment(Enchantment.SILK_TOUCH, 1); npc.setItemInHand(axe); // Grab the RemoteEntity to perform logic operations. RemoteEntity entity = RemoteEntities.getRemoteEntityFromEntity(this.npc); // Restore normal livelihood into the blacksmith. DesireLookAtNearest desireLookAtNearest = entity.getMind().getMovementDesire(DesireLookAtNearest.class); DesireLookRandomly desireLookRandomly = entity.getMind().getMovementDesire(DesireLookRandomly.class); // desireLookAtNearest.setLookPossibility(1.0F); desireLookRandomly.startExecuting(); } } Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new ReturnItem(player, actionItem, npc, indexOfPreviouslyHeldItem), (wait * 2) + 20L); } // Grab the nearest location of a block with a certain material/type. private Location closestLocation(Location origin, Material type) { World world = origin.getWorld(); for (int x = origin.getBlockX() - 4; x <= origin.getBlockX() + 8; x = x + 1) { for (int z = origin.getBlockZ() - 4; z <= origin.getBlockZ() + 8; z = z + 1) { for (int y = origin.getBlockY() - 4; y <= origin.getBlockY() + 8; y = y + 1) { Block block = world.getBlockAt(x, y, z); if (block.getType() == type) return block.getLocation(); } } } return origin; } }
mit
iammck/ECalculon
app/src/main/java/com/mck/ecalculon/evaluator/Symbol.java
1755
package com.mck.ecalculon.evaluator; import android.util.Log; import java.util.ArrayList; /** * Created by mike on 5/11/2015. */ public abstract class Symbol implements Comparable<Symbol>{ protected final String token; protected final SymbolType type; protected final ArrayList<Symbol> resultList; protected final ArrayList<Symbol> pendingList; // enum of all symbol types. public enum SymbolType { number, addition, subtraction, multiplication, division, negation, lParenthesis, rParenthesis } public Symbol(String token, SymbolType type, ArrayList<Symbol> resultList, ArrayList<Symbol> pendingList) throws EvaluationException{ this.token = token; this.type = type; this.resultList = resultList; this.pendingList = pendingList; } /** * * @param another * @return a negative integer if this instance is less than another; * a positive integer if this instance is greater than another; * 0 if this instance has the same order as another. */ @Override public int compareTo(Symbol another) { Log.v("com.mck.binaryproblem", this.toString() + " compateTo() " + another.toString()); if (getGreaterThen().contains(another.type)) return 1; if (getEqualTo().contains(another.type)) return 0; // not greater or equal, must be less than. return -1; } public String toString(){ return token.toString(); } protected abstract ArrayList<SymbolType> getEqualTo(); protected abstract ArrayList<SymbolType> getGreaterThen(); public abstract boolean evaluate() throws EvaluationException; }
mit
gossi/eclipse-transpiler-plugin
si.gos.transpiler.core/src/si/gos/transpiler/core/transpiler/Option.java
1691
package si.gos.transpiler.core.transpiler; import java.util.LinkedList; import java.util.List; import org.eclipse.core.runtime.IConfigurationElement; public class Option { public static final String TYPE_BOOLEAN = "boolean"; public static final String TYPE_PARAM = "param"; public static final String TYPE_ENUM = "enum"; private String name; private String shortName; private String type; private String description; private List<String> values = new LinkedList<String>(); public Option() { } public Option(IConfigurationElement config) { name = config.getAttribute("name"); description = config.getAttribute("description") == null ? "" : config.getAttribute("description"); shortName = config.getAttribute("short"); type = config.getAttribute("type"); IConfigurationElement[] valueNodes = config.getChildren("value"); for (IConfigurationElement v : valueNodes) { values.add(v.getAttribute("name")); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getShort() { return shortName; } public void setShort(String shortName) { this.shortName = shortName; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isBoolean() { return type.equals(TYPE_BOOLEAN); } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } public String[] getValues() { return values.toArray(new String[]{}); } }
mit
gradleupdate/embulk-filter-row
src/main/java/org/embulk/filter/RowFilterPlugin.java
9517
package org.embulk.filter; import org.embulk.config.Config; import org.embulk.config.ConfigDefault; import org.embulk.config.ConfigDiff; import org.embulk.config.ConfigSource; import org.embulk.config.Task; import org.embulk.config.TaskSource; import java.util.List; import java.util.ArrayList; import java.util.HashMap; import com.google.common.collect.ImmutableList; import org.slf4j.Logger; import org.embulk.spi.type.Type; import org.embulk.spi.type.BooleanType; import org.embulk.spi.type.LongType; import org.embulk.spi.type.DoubleType; import org.embulk.spi.type.StringType; import org.embulk.spi.type.TimestampType; import org.embulk.spi.time.Timestamp; import org.embulk.spi.FilterPlugin; import org.embulk.spi.Exec; import org.embulk.spi.Page; import org.embulk.spi.PageBuilder; import org.embulk.spi.PageOutput; import org.embulk.spi.PageReader; import org.embulk.spi.Schema; import org.embulk.spi.SchemaConfig; import org.embulk.spi.Column; import org.embulk.spi.ColumnVisitor; import org.embulk.spi.time.TimestampParser; import org.embulk.filter.row.ConditionConfig; import org.embulk.filter.row.Condition; import org.embulk.filter.row.BooleanCondition; import org.embulk.filter.row.LongCondition; import org.embulk.filter.row.DoubleCondition; import org.embulk.filter.row.StringCondition; import org.embulk.filter.row.TimestampCondition; import org.embulk.filter.row.ConditionFactory; public class RowFilterPlugin implements FilterPlugin { private static final Logger logger = Exec.getLogger(RowFilterPlugin.class); public RowFilterPlugin() { } public interface PluginTask extends Task, TimestampParser.Task { @Config("conditions") public List<ConditionConfig> getConditions(); } @Override public void transaction(ConfigSource config, Schema inputSchema, FilterPlugin.Control control) { PluginTask task = config.loadConfig(PluginTask.class); Schema outputSchema = inputSchema; control.run(task.dump(), outputSchema); } @Override public PageOutput open(final TaskSource taskSource, final Schema inputSchema, final Schema outputSchema, final PageOutput output) { PluginTask task = taskSource.loadTask(PluginTask.class); final HashMap<String, List<Condition>> conditionMap = new HashMap<String, List<Condition>>(); for (Column column : outputSchema.getColumns()) { String columnName = column.getName(); conditionMap.put(columnName, new ArrayList<Condition>()); } for (ConditionConfig conditionConfig : task.getConditions()) { String columnName = conditionConfig.getColumn(); for (Column column : outputSchema.getColumns()) { if (columnName.equals(column.getName())) { ConditionFactory factory = new ConditionFactory(task.getJRuby(), column, conditionConfig); Condition condition = factory.createCondition(); conditionMap.get(columnName).add(condition); break; } } } return new PageOutput() { private PageReader pageReader = new PageReader(inputSchema); private PageBuilder pageBuilder = new PageBuilder(Exec.getBufferAllocator(), outputSchema, output); private boolean shouldAddRecord = true; @Override public void finish() { pageBuilder.finish(); } @Override public void close() { pageBuilder.close(); } @Override public void add(Page page) { pageReader.setPage(page); ColumnVisitorImpl visitor = new ColumnVisitorImpl(pageBuilder); while (pageReader.nextRecord()) { shouldAddRecord = true; inputSchema.visitColumns(visitor); if (shouldAddRecord) pageBuilder.addRecord(); } } class ColumnVisitorImpl implements ColumnVisitor { private final PageBuilder pageBuilder; ColumnVisitorImpl(PageBuilder pageBuilder) { this.pageBuilder = pageBuilder; } @Override public void booleanColumn(Column column) { if (!shouldAddRecord) return; List<Condition> conditionList = conditionMap.get(column.getName()); for (Condition _condition : conditionList) { BooleanCondition condition = (BooleanCondition)_condition; if (pageReader.isNull(column)) { if (!condition.compare(null)) { shouldAddRecord = false; break; } } else { boolean subject = pageReader.getBoolean(column); if (!condition.compare(subject)) { shouldAddRecord = false; break; } } } if (pageReader.isNull(column)) { pageBuilder.setNull(column); } else { pageBuilder.setBoolean(column, pageReader.getBoolean(column)); } } @Override public void longColumn(Column column) { if (!shouldAddRecord) return; List<Condition> conditionList = conditionMap.get(column.getName()); for (Condition _condition : conditionList) { LongCondition condition = (LongCondition)_condition; if (pageReader.isNull(column)) { if (!condition.compare(null)) { shouldAddRecord = false; break; } } else { long subject = pageReader.getLong(column); if (!condition.compare(subject)) { shouldAddRecord = false; break; } } } if (pageReader.isNull(column)) { pageBuilder.setNull(column); } else { pageBuilder.setLong(column, pageReader.getLong(column)); } } @Override public void doubleColumn(Column column) { if (!shouldAddRecord) return; List<Condition> conditionList = conditionMap.get(column.getName()); for (Condition _condition : conditionList) { DoubleCondition condition = (DoubleCondition)_condition; if (pageReader.isNull(column)) { if (!condition.compare(null)) { shouldAddRecord = false; break; } } else { double subject = pageReader.getDouble(column); if (!condition.compare(subject)) { shouldAddRecord = false; break; } } } if (pageReader.isNull(column)) { pageBuilder.setNull(column); } else { pageBuilder.setDouble(column, pageReader.getDouble(column)); } } @Override public void stringColumn(Column column) { if (!shouldAddRecord) return; List<Condition> conditionList = conditionMap.get(column.getName()); for (Condition _condition : conditionList) { StringCondition condition = (StringCondition)_condition; if (pageReader.isNull(column)) { if (!condition.compare(null)) { shouldAddRecord = false; break; } } else { String subject = pageReader.getString(column); if (!condition.compare(subject)) { shouldAddRecord = false; break; } } } if (pageReader.isNull(column)) { pageBuilder.setNull(column); } else { pageBuilder.setString(column, pageReader.getString(column)); } } @Override public void timestampColumn(Column column) { if (!shouldAddRecord) return; List<Condition> conditionList = conditionMap.get(column.getName()); for (Condition _condition : conditionList) { TimestampCondition condition = (TimestampCondition)_condition; if (pageReader.isNull(column)) { if (!condition.compare(null)) { shouldAddRecord = false; break; } } else { Timestamp subject = pageReader.getTimestamp(column); if (!condition.compare(subject)) { shouldAddRecord = false; break; } } } if (pageReader.isNull(column)) { pageBuilder.setNull(column); } else { pageBuilder.setTimestamp(column, pageReader.getTimestamp(column)); } } } }; } }
mit
FurryHead/Server
src/org/hyperion/rs2/model/content/skills/prayer/Prayer.java
475
package org.hyperion.rs2.model.content.skills.prayer; import org.hyperion.rs2.model.Player; import org.hyperion.rs2.model.Skills; import org.hyperion.rs2.model.content.skills.Skill; /** * The prayer skill. * @author Thomas Nappo */ public class Prayer extends Skill { /** * Constructs a new prayer skill. * @param the player who will be using the skill. */ public Prayer(Player player) { super(Skills.PRAYER); //Superconstruct with the prayer skill id. } }
mit
csalgadolizana/MisOfertasWebService
src/java/Entidades/InformeBi.java
3393
/* * 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 Entidades; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlRootElement; /** * * @author PC-Cristopher */ @Entity @Table(name = "INFORME_BI") @XmlRootElement @NamedQueries({ @NamedQuery(name = "InformeBi.findAll", query = "SELECT i FROM InformeBi i") , @NamedQuery(name = "InformeBi.findByIdInformeBi", query = "SELECT i FROM InformeBi i WHERE i.idInformeBi = :idInformeBi") , @NamedQuery(name = "InformeBi.findByFechaCreacion", query = "SELECT i FROM InformeBi i WHERE i.fechaCreacion = :fechaCreacion")}) public class InformeBi implements Serializable { private static final long serialVersionUID = 1L; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Id @Basic(optional = false) @NotNull @Column(name = "ID_INFORME_BI") private BigDecimal idInformeBi; @Column(name = "FECHA_CREACION") @Temporal(TemporalType.TIMESTAMP) private Date fechaCreacion; @JoinColumn(name = "USUARIO_ID_USUARIO", referencedColumnName = "ID_USUARIO") @ManyToOne private Usuario usuarioIdUsuario; public InformeBi() { } public InformeBi(BigDecimal idInformeBi) { this.idInformeBi = idInformeBi; } public BigDecimal getIdInformeBi() { return idInformeBi; } public void setIdInformeBi(BigDecimal idInformeBi) { this.idInformeBi = idInformeBi; } public Date getFechaCreacion() { return fechaCreacion; } public void setFechaCreacion(Date fechaCreacion) { this.fechaCreacion = fechaCreacion; } public Usuario getUsuarioIdUsuario() { return usuarioIdUsuario; } public void setUsuarioIdUsuario(Usuario usuarioIdUsuario) { this.usuarioIdUsuario = usuarioIdUsuario; } @Override public int hashCode() { int hash = 0; hash += (idInformeBi != null ? idInformeBi.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof InformeBi)) { return false; } InformeBi other = (InformeBi) object; if ((this.idInformeBi == null && other.idInformeBi != null) || (this.idInformeBi != null && !this.idInformeBi.equals(other.idInformeBi))) { return false; } return true; } @Override public String toString() { return "Entidades.InformeBi[ idInformeBi=" + idInformeBi + " ]"; } }
mit
patrickneubauer/XMLIntellEdit
xmlintelledit/intelledit/lib/MOEAFramework-2.12.tar/MOEAFramework-2.12/examples/org/moeaframework/examples/ga/onemax/OneMax.java
1956
/* Copyright 2009-2016 David Hadka * * This file is part of the MOEA Framework. * * The MOEA Framework is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * The MOEA Framework 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 the MOEA Framework. If not, see <http://www.gnu.org/licenses/>. */ package org.moeaframework.examples.ga.onemax; import org.moeaframework.core.Solution; import org.moeaframework.core.variable.BinaryVariable; import org.moeaframework.problem.AbstractProblem; /** * The one-max problem for maximizing the number of {@code 1} bits in a binary * string. The one-max problem is trivial for most GAs, and is often used to * measure the convergence speed of different crossover and mutation operators. */ public class OneMax extends AbstractProblem { /** * The number of bits in this OneMax problem instance. */ private final int numberOfBits; /** * Constructs the one-max problem with the specified number of bits. * * @param numberOfBits the number of bits in this instance */ public OneMax(int numberOfBits) { super(1, 1); this.numberOfBits = numberOfBits; } @Override public void evaluate(Solution solution) { BinaryVariable binary = (BinaryVariable)solution.getVariable(0); solution.setObjective(0, numberOfBits - binary.cardinality()); } @Override public Solution newSolution() { Solution solution = new Solution(1, 1); solution.setVariable(0, new BinaryVariable(numberOfBits)); return solution; } }
mit
solita/phantom-runner
src/main/java/fi/solita/phantomrunner/JavascriptTestInterpreterConfiguration.java
3413
/** * The MIT License (MIT) * * Copyright (c) 2012 Solita Oy * * 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 fi.solita.phantomrunner; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import fi.solita.phantomrunner.testinterpreter.JavascriptTestInterpreter; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Inherited public @interface JavascriptTestInterpreterConfiguration { /** * Interpreter class to be used for the test execution. This class with it's resource files provide * {@link PhantomRunner} way to execute and interpret JavaScript tests and binds them to JUnit test framework. * All implementations of {@link JavascriptTestInterpreter} provide a version of the actual testing library * JavaScript file but if the version used is old you may override the library file(s) with * {@link JavascriptTestInterpreterConfiguration#libraryFilePaths()}. Please note though that this <b>may</b> * break the interpreter if the semantics of the library have changed a lot. */ Class<? extends JavascriptTestInterpreter> interpreterClass(); /** * <p>Path where the used JavaScript test library should be looked for. By default all {@link JavascriptTestInterpreter} * instances know where to get their libraries but in case of old library you may override this by providing a * another library path here. Please note though that the Java code doesn't change and thus something may brake * if another version of the library is provided.</p> * * <p>Library paths follow the conventional Java resource loading mechanism with the additional support for * <i>classpath</i> protocol. Thus all of the following are valid paths:</p> * * <ul> * <li>file://./some/path/foo.js</li> * <li>classpath:some/path/foo.js</li> * <li>http://foobar.com/some/path/foo.js</li> * </ul> * * <p>All loaded resources are cached for the execution of {@link PhantomRunner}. This prevents both excessive * disc I/O and also network I/O in case of external network resources.</p> */ String[] libraryFilePaths() default ""; }
mit
jessezwd/Starriver
src/main/java/org/jessezhu/starriver/mapper/TaskMapper.java
1326
/* * The MIT License * * Copyright 2016 jesse.zwd@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 org.jessezhu.starriver.mapper; import org.jessezhu.starriver.model.Task; import org.jessezhu.starriver.util.MyMapper; public interface TaskMapper extends MyMapper<Task> { }
mit
hakanmhmd/algorithms-and-data-structures
src/main/java/Arrays/MaxDifference.java
920
package Arrays; /** * Given an array arr[] of integers, find out the difference between any two elements such that * larger element appears after the smaller number in arr[]. */ public class MaxDifference { public static void main(String[] args) throws Exception { int arr[] = {10, 2, 90, 10, 110, 1, 100}; System.out.println("Maximum differnce is " + maxDiff(arr, 5)); } private static int maxDiff(int[] arr, int i) throws Exception { if(arr.length < 2) { throw new Exception(); } int maxDiff = Integer.MIN_VALUE; int minElement = arr[0]; for (int j = 1; j < arr.length; j++) { if(arr[j] - minElement > maxDiff){ maxDiff = arr[j] - minElement; } if(arr[j] < minElement){ minElement = arr[j]; } } return maxDiff; } }
mit
ITSFactory/itsfactory.siri.bindings.v13
src/main/java/eu/datex2/schema/_1_0/_1_0/TPEGLoc01SimplePointLocationSubtypeEnum.java
1967
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-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: 2013.07.27 at 08:11:57 PM EEST // package eu.datex2.schema._1_0._1_0; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for TPEGLoc01SimplePointLocationSubtypeEnum. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="TPEGLoc01SimplePointLocationSubtypeEnum"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="intersection"/> * &lt;enumeration value="nonLinkedPoint"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "TPEGLoc01SimplePointLocationSubtypeEnum") @XmlEnum public enum TPEGLoc01SimplePointLocationSubtypeEnum { /** * An point on the road network at which one or more roads intersect. * */ @XmlEnumValue("intersection") INTERSECTION("intersection"), /** * A point on the road network which is not at a junction or intersection. * */ @XmlEnumValue("nonLinkedPoint") NON_LINKED_POINT("nonLinkedPoint"); private final String value; TPEGLoc01SimplePointLocationSubtypeEnum(String v) { value = v; } public String value() { return value; } public static TPEGLoc01SimplePointLocationSubtypeEnum fromValue(String v) { for (TPEGLoc01SimplePointLocationSubtypeEnum c: TPEGLoc01SimplePointLocationSubtypeEnum.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
mit
kamcio96/SpongeCommon
src/main/java/org/spongepowered/common/event/filter/delegate/RootCauseFilterSourceDelegate.java
3082
/* * This file is part of Sponge, 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.common.event.filter.delegate; import static org.objectweb.asm.Opcodes.ACONST_NULL; import static org.objectweb.asm.Opcodes.ALOAD; import static org.objectweb.asm.Opcodes.ARETURN; import static org.objectweb.asm.Opcodes.ASTORE; import static org.objectweb.asm.Opcodes.IFEQ; import static org.objectweb.asm.Opcodes.IFNE; import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.filter.cause.Root; import java.lang.reflect.Parameter; public class RootCauseFilterSourceDelegate extends CauseFilterSourceDelegate { public RootCauseFilterSourceDelegate(Root anno) { } @Override protected void insertCauseCall(MethodVisitor mv, Parameter param, Class<?> targetType) { mv.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Cause.class), "root", "()Ljava/lang/Object;", false); } @Override protected void insertCheck(MethodVisitor mv, Parameter param, Class<?> targetType, int local) { Label failure = new Label(); Label success = new Label(); mv.visitLdcInsn(Type.getType(targetType)); mv.visitVarInsn(ALOAD, local); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;", false); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "isAssignableFrom", "(Ljava/lang/Class;)Z", false); mv.visitJumpInsn(IFNE, success); mv.visitLabel(failure); mv.visitInsn(ACONST_NULL); mv.visitInsn(ARETURN); mv.visitLabel(success); } @Override protected void insertTransform(MethodVisitor mv, Parameter param, Class<?> targetType, int local) { } }
mit
matkluska/bsc-forms-server
reply-stats-service/src/main/java/io/kluska/bsc/forms/reply/stats/service/domain/model/replies/LinearScaleReply.java
1234
package io.kluska.bsc.forms.reply.stats.service.domain.model.replies; import io.kluska.bsc.forms.form.api.dto.QuestionDTO; import io.kluska.bsc.forms.form.api.dto.question.LinearScaleDTO; import io.kluska.bsc.forms.reply.stats.service.api.exception.BadReplyTypeException; import io.kluska.bsc.forms.reply.stats.service.api.exception.NotDefinedOptionException; import io.kluska.bsc.forms.reply.stats.service.domain.model.Reply; import lombok.Data; import lombok.EqualsAndHashCode; /** * @author Mateusz Kluska */ @Data @EqualsAndHashCode(callSuper = false) public class LinearScaleReply extends Reply { private int option; @Override public void validate(QuestionDTO questionDTO) { if (!(questionDTO instanceof LinearScaleDTO)) throw new BadReplyTypeException("Reply for question " + getQuestionId() + " should have type " + LinearScaleDTO.class.getSimpleName()); validateOption((LinearScaleDTO) questionDTO); } private void validateOption(LinearScaleDTO linearScaleQuestion) { if (option > linearScaleQuestion.getMax() || option < linearScaleQuestion.getMin()) throw new NotDefinedOptionException(option + " is out of the range."); } }
mit
etki/grac
src/main/java/me/etki/grac/Request.java
1744
package me.etki.grac; import me.etki.grac.common.Action; import java.util.List; import java.util.Map; import java.util.Optional; /** * @author Etki {@literal <etki@etki.name>} * @version %I%, %G% * @since 0.1.0 */ public class Request<T> { private String resource; private Action action; private Map<String, List<Object>> parameters; private Map<String, List<Object>> metadata; private T payload; public Request() { } public Request(String resource, Action action) { this.resource = resource; this.action = action; } public Request(String resource, Action action, T payload) { this.resource = resource; this.action = action; this.payload = payload; } public String getResource() { return resource; } public Request<T> setResource(String resource) { this.resource = resource; return this; } public Action getAction() { return action; } public Request<T> setAction(Action action) { this.action = action; return this; } public Map<String, List<Object>> getParameters() { return parameters; } public Request<T> setParameters(Map<String, List<Object>> parameters) { this.parameters = parameters; return this; } public Map<String, List<Object>> getMetadata() { return metadata; } public Request<T> setMetadata(Map<String, List<Object>> metadata) { this.metadata = metadata; return this; } public Optional<T> getPayload() { return Optional.ofNullable(payload); } public Request<T> setPayload(T payload) { this.payload = payload; return this; } }
mit
ButterFaces/ButterFaces
components/src/main/java/org/butterfaces/model/table/TableModel.java
1114
package org.butterfaces.model.table; /** * Just a table model wrapper to allow binding one attribute (model) to table component. Each specific table model * could be null. In this case corresponding feature is not available. */ public interface TableModel { /** * Only works if at least one f:ajax is used on table toolbar component. Maybe it is better to create custom * ajax event type for this model (like both other models have) but up to know no specific event type is needed. * * @return null if no sort model is used. This means sort cachedColumns is not available. */ TableRowSortingModel getTableRowSortingModel(); /** * Only works if f:ajax event="toggle" is used on table toolbar component. * * @return null if no column visibility (show and hide) is used. */ TableColumnVisibilityModel getTableColumnVisibilityModel(); /** * Only works if f:ajax event="order" is used on table toolbar component. * * @return null if no column ordering is used. */ TableColumnOrderingModel getTableColumnOrderingModel(); }
mit
servicosgoval/editor-de-servicos
src/main/java/br/gov/servicos/editor/config/WebMVCConfig.java
591
package br.gov.servicos.editor.config; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.xml.SourceHttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.util.List; @Configuration public class WebMVCConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new SourceHttpMessageConverter<>()); } }
mit
zndrk94/UserEngine
src/userEngine/controllers/login/LoginControllerResponse.java
776
package userEngine.controllers.login; import java.util.HashMap; import userEngine.controllers.abstractController.AbstractControllerResponse; public class LoginControllerResponse extends AbstractControllerResponse implements LoginControllerResponseInterface { public void setRefreshable(String refreshable) { this._controllerResponse.put("refreshable", refreshable); } public void setRefreshToken(String refreshToken) { this._controllerResponse.put("refreshToken", refreshToken); } public void setAccessToken(String accessToken) { this._controllerResponse.put("accessToken", accessToken); } public void setTimeout(String timeout) { this._controllerResponse.put("timeout", timeout); } }
mit
zellerdev/jabref
src/main/java/org/jabref/logic/integrity/BibtexKeyChecker.java
1336
package org.jabref.logic.integrity; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.integrity.IntegrityCheck.Checker; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.field.StandardField; import org.jabref.model.strings.StringUtil; /** * Currently only checks the key if there is an author, year, and title present. */ public class BibtexKeyChecker implements Checker { @Override public List<IntegrityMessage> check(BibEntry entry) { Optional<String> author = entry.getField(StandardField.AUTHOR); Optional<String> title = entry.getField(StandardField.TITLE); Optional<String> year = entry.getField(StandardField.YEAR); if (!author.isPresent() || !title.isPresent() || !year.isPresent()) { return Collections.emptyList(); } if (StringUtil.isBlank(entry.getCiteKeyOptional())) { String authorTitleYear = entry.getAuthorTitleYear(100); return Collections.singletonList(new IntegrityMessage( Localization.lang("empty BibTeX key") + ": " + authorTitleYear, entry, InternalField.KEY_FIELD)); } return Collections.emptyList(); } }
mit
IDepla/polibox_client
src/main/java/it/polito/ai/polibox/client/swing/panel/tab/CacheTabPanel.java
3433
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2015 Igor Deplano * * 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 it.polito.ai.polibox.client.swing.panel.tab; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Observable; import java.util.Observer; import java.util.ResourceBundle; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * la cache tiene dentro le notifiche che sono state spedite dal server. * * cancellarla significa eliminare queste notifiche. * * @author "Igor Deplano" * */ @Component public class CacheTabPanel extends JPanel implements ActionListener,InitializingBean,DisposableBean,Observer{ JLabel cacheName; JLabel cacheValue; JButton cacheErase; @Autowired private ResourceBundle resourceBoundle; //@Autowired // private SettingManagerInterface settingManager; /** * */ private static final long serialVersionUID = -6267661711329703389L; public CacheTabPanel() { super(true); cacheName=new JLabel(); add(cacheName); cacheValue=new JLabel(); cacheErase=new JButton(); cacheErase.addActionListener(this); add(cacheErase); //cacheValue.setText(""+settingManager.loadSettings().getCacheSpace()); } public ResourceBundle getResourceBoundle() { return resourceBoundle; } public void setResourceBoundle(ResourceBundle resourceBoundle) { this.resourceBoundle = resourceBoundle; } public void actionPerformed(ActionEvent e) { //TODO deve cancellare la cache. //settingManager.loadSettings().eraseCache(); } public void update(Observable o, Object arg) { // TODO Auto-generated method stub } public void destroy() throws Exception { // TODO Auto-generated method stub } public void afterPropertiesSet() throws Exception { cacheName.setText(resourceBoundle.getString("CacheTabPanel.afterPropertiesSet.cacheLabel")); cacheErase.setText(resourceBoundle.getString("CacheTabPanel.afterPropertiesSet.buttonEraseCache")); } }
mit
slagyr/limelight
src/limelight/styles/values/SimpleIntegerValue.java
684
//- Copyright © 2008-2011 8th Light, Inc. All Rights Reserved. //- Limelight and all included source files are distributed under terms of the MIT License. package limelight.styles.values; import limelight.styles.abstrstyling.IntegerValue; public class SimpleIntegerValue implements IntegerValue { private final int value; public SimpleIntegerValue(int value) { this.value = value; } public int getValue() { return value; } public String toString() { return "" + value; } public boolean equals(Object obj) { if(obj instanceof SimpleIntegerValue) { return value == ((SimpleIntegerValue)obj).value; } return false; } }
mit
hovsepm/azure-sdk-for-java
storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/StorageAccount.java
9331
/** * 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.storage.v2018_03_01_preview; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.arm.resources.models.Resource; import com.microsoft.azure.arm.resources.models.HasResourceGroup; import com.microsoft.azure.arm.model.Refreshable; import com.microsoft.azure.arm.model.Updatable; import com.microsoft.azure.arm.model.Appliable; import com.microsoft.azure.arm.model.Creatable; import com.microsoft.azure.arm.resources.models.GroupableResourceCore; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.storage.v2018_03_01_preview.implementation.StorageManager; import com.microsoft.azure.management.storage.v2018_03_01_preview.implementation.SkuInner; import org.joda.time.DateTime; import com.microsoft.azure.management.storage.v2018_03_01_preview.implementation.StorageAccountInner; /** * Type representing StorageAccount. */ public interface StorageAccount extends HasInner<StorageAccountInner>, Resource, GroupableResourceCore<StorageManager, StorageAccountInner>, HasResourceGroup, Refreshable<StorageAccount>, Updatable<StorageAccount.Update>, HasManager<StorageManager> { /** * @return the accessTier value. */ AccessTier accessTier(); /** * @return the creationTime value. */ DateTime creationTime(); /** * @return the customDomain value. */ CustomDomain customDomain(); /** * @return the enableHttpsTrafficOnly value. */ Boolean enableHttpsTrafficOnly(); /** * @return the encryption value. */ Encryption encryption(); /** * @return the identity value. */ Identity identity(); /** * @return the kind value. */ Kind kind(); /** * @return the lastGeoFailoverTime value. */ DateTime lastGeoFailoverTime(); /** * @return the networkRuleSet value. */ NetworkRuleSet networkRuleSet(); /** * @return the primaryEndpoints value. */ Endpoints primaryEndpoints(); /** * @return the primaryLocation value. */ String primaryLocation(); /** * @return the provisioningState value. */ ProvisioningState provisioningState(); /** * @return the secondaryEndpoints value. */ Endpoints secondaryEndpoints(); /** * @return the secondaryLocation value. */ String secondaryLocation(); /** * @return the sku value. */ Sku sku(); /** * @return the statusOfPrimary value. */ AccountStatus statusOfPrimary(); /** * @return the statusOfSecondary value. */ AccountStatus statusOfSecondary(); /** * The entirety of the StorageAccount definition. */ interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithKind, DefinitionStages.WithSku, DefinitionStages.WithCreate { } /** * Grouping of StorageAccount definition stages. */ interface DefinitionStages { /** * The first stage of a StorageAccount definition. */ interface Blank extends GroupableResourceCore.DefinitionWithRegion<WithGroup> { } /** * The stage of the StorageAccount definition allowing to specify the resource group. */ interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup<WithKind> { } /** * The stage of the storageaccount definition allowing to specify Kind. */ interface WithKind { /** * Specifies kind. */ WithSku withKind(Kind kind); } /** * The stage of the storageaccount definition allowing to specify Sku. */ interface WithSku { /** * Specifies sku. */ WithCreate withSku(SkuInner sku); } /** * The stage of the storageaccount update allowing to specify AccessTier. */ interface WithAccessTier { /** * Specifies accessTier. */ WithCreate withAccessTier(AccessTier accessTier); } /** * The stage of the storageaccount update allowing to specify CustomDomain. */ interface WithCustomDomain { /** * Specifies customDomain. */ WithCreate withCustomDomain(CustomDomain customDomain); } /** * The stage of the storageaccount update allowing to specify EnableHttpsTrafficOnly. */ interface WithEnableHttpsTrafficOnly { /** * Specifies enableHttpsTrafficOnly. */ WithCreate withEnableHttpsTrafficOnly(Boolean enableHttpsTrafficOnly); } /** * The stage of the storageaccount update allowing to specify Encryption. */ interface WithEncryption { /** * Specifies encryption. */ WithCreate withEncryption(Encryption encryption); } /** * The stage of the storageaccount update allowing to specify Identity. */ interface WithIdentity { /** * Specifies identity. */ WithCreate withIdentity(Identity identity); } /** * The stage of the storageaccount update allowing to specify NetworkRuleSet. */ interface WithNetworkRuleSet { /** * Specifies networkRuleSet. */ WithCreate withNetworkRuleSet(NetworkRuleSet networkRuleSet); } /** * The stage of the definition which contains all the minimum required inputs for * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ interface WithCreate extends Creatable<StorageAccount>, Resource.DefinitionWithTags<WithCreate>, DefinitionStages.WithAccessTier, DefinitionStages.WithCustomDomain, DefinitionStages.WithEnableHttpsTrafficOnly, DefinitionStages.WithEncryption, DefinitionStages.WithIdentity, DefinitionStages.WithNetworkRuleSet { } } /** * The template for a StorageAccount update operation, containing all the settings that can be modified. */ interface Update extends Appliable<StorageAccount>, Resource.UpdateWithTags<Update>, UpdateStages.WithAccessTier, UpdateStages.WithCustomDomain, UpdateStages.WithEnableHttpsTrafficOnly, UpdateStages.WithEncryption, UpdateStages.WithIdentity, UpdateStages.WithKind, UpdateStages.WithNetworkRuleSet, UpdateStages.WithSku { } /** * Grouping of StorageAccount update stages. */ interface UpdateStages { /** * The stage of the storageaccount {0} allowing to specify AccessTier. */ interface WithAccessTier { /** * Specifies accessTier. */ Update withAccessTier(AccessTier accessTier); } /** * The stage of the storageaccount {0} allowing to specify CustomDomain. */ interface WithCustomDomain { /** * Specifies customDomain. */ Update withCustomDomain(CustomDomain customDomain); } /** * The stage of the storageaccount {0} allowing to specify EnableHttpsTrafficOnly. */ interface WithEnableHttpsTrafficOnly { /** * Specifies enableHttpsTrafficOnly. */ Update withEnableHttpsTrafficOnly(Boolean enableHttpsTrafficOnly); } /** * The stage of the storageaccount {0} allowing to specify Encryption. */ interface WithEncryption { /** * Specifies encryption. */ Update withEncryption(Encryption encryption); } /** * The stage of the storageaccount {0} allowing to specify Identity. */ interface WithIdentity { /** * Specifies identity. */ Update withIdentity(Identity identity); } /** * The stage of the storageaccount {0} allowing to specify Kind. */ interface WithKind { /** * Specifies kind. */ Update withKind(Kind kind); } /** * The stage of the storageaccount {0} allowing to specify NetworkRuleSet. */ interface WithNetworkRuleSet { /** * Specifies networkRuleSet. */ Update withNetworkRuleSet(NetworkRuleSet networkRuleSet); } /** * The stage of the storageaccount {0} allowing to specify Sku. */ interface WithSku { /** * Specifies sku. */ Update withSku(SkuInner sku); } } }
mit
M123kumar1/online-shopping
ShoppingBackEnd/src/main/java/com/mk/shoppingbackend/dao/ProductDAO.java
521
package com.mk.shoppingbackend.dao; import java.util.List; import com.mk.shoppingbackend.dto.Product; import com.mk.shoppingbackend.dto.Product; public interface ProductDAO { Product get(int productId); List<Product> list(); boolean add(Product product); boolean update(Product product); boolean delete(Product product); //Business method List<Product> listActiveProducts(); List<Product> listActiveProductsByCategory(int categoryId); List<Product> getLatestActiveProducts(int count); }
mit
zhqhzhqh/FbreaderJ
app/src/main/java/org/geometerplus/android/fbreader/preferences/ZLIntegerRangePreference.java
1891
/* * Copyright (C) 2010-2015 FBReader.ORG Limited <contact@fbreader.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.android.fbreader.preferences; import android.content.Context; import android.preference.ListPreference; import org.geometerplus.zlibrary.core.resources.ZLResource; import org.geometerplus.zlibrary.core.options.ZLIntegerRangeOption; class ZLIntegerRangePreference extends ListPreference { private final ZLIntegerRangeOption myOption; ZLIntegerRangePreference(Context context, ZLResource resource, ZLIntegerRangeOption option) { super(context); myOption = option; setTitle(resource.getValue()); String[] entries = new String[option.MaxValue - option.MinValue + 1]; for (int i = 0; i < entries.length; ++i) { entries[i] = ((Integer)(i + option.MinValue)).toString(); } setEntries(entries); setEntryValues(entries); setValueIndex(option.getValue() - option.MinValue); setSummary(getValue()); } @Override protected void onDialogClosed(boolean result) { super.onDialogClosed(result); if (result) { final String value = getValue(); setSummary(value); myOption.setValue(myOption.MinValue + findIndexOfValue(value)); } } }
mit
mumblers/TRacers
client/src/mumblers/tracers/client/DisplayRenderer.java
236
package mumblers.tracers.client; import java.awt.Dimension; import java.awt.Graphics2D; /** * Created by Sinius on 16-7-2015. */ public interface DisplayRenderer { void render(Graphics2D g, Dimension size); void tick(); }
mit
accelazh/SynthesizerGroove
src/sound/CopyOfGroove.java
5804
package sound; import javax.sound.midi.*; import java.util.*; public class CopyOfGroove { public static final String[] INSTRUMENTS = { "Acoustic bass drum", "Bass drum 1", "Side stick", "Acoustic snare", "Hand clap", "Electric snare", "Low floor tom", "Closed hi-hat", "High floor tom", "Pedal hi-hat", "Low tom", "Open hi-hat", "Low-mid tom", "Hi-mid tom", "Crash cymbal 1", "High tom", "Ride cymbal 1", "Chinese cymbal", "Ride bell", "Tambourine", "Splash cymbal", "Cowbell", "Crash cymbal 2", "Vibraslap", "Ride cymbal 2", "Hi bongo", "Low bongo", "Mute hi conga", "Open hi conga", "Low conga", "High timbale", "Low timbale", "High agogo", "Low agogo", "Cabasa", "Maracas", "Short whistle", "Long whistle", "Short guiro", "Long guiro", "Claves", "Hi wood block", "Low wood block", "Mute cuica", "Open cuica", "Mute triangle", "Open triangle" }; private static final int INSTRUMENT_ID_OFFSET = 35; private Sequencer sequencer; private List<GrooveListener> listeners; public CopyOfGroove() { sequencer = null; listeners = new LinkedList<GrooveListener>(); } // ===================================´ò¿ªºÍ¹Ø±Õ=================================== public void open() throws MidiUnavailableException { if (sequencer != null) { throw new IllegalStateException("already opened"); } try { sequencer = MidiSystem.getSequencer(); sequencer.open(); sequencer.addMetaEventListener(new MetaEventListener() { public void meta(MetaMessage message) { GrooveEvent event = null; if (47 == message.getType()) // end of track { assert (!sequencer.isRunning()); event = new GrooveEvent(GrooveEvent.END_OF_PLAY); } else { // do nothing } for (GrooveListener l : listeners) { assert (l != null); l.handleEvent(event); } } }); } catch (MidiUnavailableException ex) { throw ex; } } public boolean isOpen() { return sequencer != null; } public void close() { if (sequencer != null) { sequencer.close(); } sequencer = null; } // =============================²¥·Å¹¦ÄÜ==================================== public void play(Composition comp, float tempoInBpm) throws InvalidMidiDataException { play(comp, false, tempoInBpm); } public void loop(Composition comp, float tempoInBpm) throws InvalidMidiDataException { play(comp, true, tempoInBpm); } public void play(Composition comp, boolean loop, float tempoInBpm) throws InvalidMidiDataException { if (null == comp) { throw new IllegalArgumentException("comp should not be null"); } if (tempoInBpm < 0) { throw new IllegalStateException("tempoInBpm should not be negative"); } if (!isOpen()) { throw new IllegalStateException("already closed"); } try { // create the track to play Sequence sequence = new Sequence(Sequence.PPQ, comp.getResolution()); Track track = sequence.createTrack(); for (Staff s : comp.getStaff()) { for (StaffData d : s.getData()) { track.add(createMidiEvent( d.isNoteOn() ? ShortMessage.NOTE_ON : ShortMessage.NOTE_OFF, d.getChannel(), s.getInstrument() + INSTRUMENT_ID_OFFSET, d.getVelocity(), d.getTick())); } } // play the track sequencer.setSequence(sequence); sequencer.setLoopCount(loop ? Integer.MAX_VALUE : 0); sequencer.start(); sequencer.setTempoInBPM(tempoInBpm); } catch (InvalidMidiDataException ex) { throw ex; } } private MidiEvent createMidiEvent(int type, int channel, int data, int velocity, long tick) throws InvalidMidiDataException { ShortMessage message = new ShortMessage(); message.setMessage(type, channel, data, velocity); MidiEvent event = new MidiEvent(message, tick); return event; } public void stop() { if (!isOpen()) { throw new IllegalStateException("already closed"); } sequencer.stop(); } public boolean isPlaying() { if (!isOpen()) { throw new IllegalStateException("already closed"); } return sequencer.isRunning(); } // =========================ʼþ»úÖÆ============================ public void addListener(GrooveListener l) { if (null == l) { throw new IllegalArgumentException("l should not be null"); } this.listeners.add(l); } public boolean removeListener(GrooveListener l) { if (null == l) { throw new IllegalArgumentException("l should not be null"); } return this.listeners.remove(l); } // =======================================²âÊÔ====================================== public static void main(String[] args) throws MidiUnavailableException, InvalidMidiDataException { CopyOfGroove groove = new CopyOfGroove(); groove.open(); // Ëæ»úÉú³ÉComposition java.util.Random rand = new java.util.Random(); Composition comp = new Composition(); for (int i_staff = 0; i_staff < 5; i_staff++) { Staff staff = new Staff(rand.nextInt(INSTRUMENTS.length)); final int TOTAL_TICK = 100; int numData = rand.nextInt(TOTAL_TICK); for (int i = 0; i < numData; i++) { staff.getData().add( new StaffData(rand.nextInt(), 90 + rand.nextInt(30), rand.nextInt(TOTAL_TICK), 9)); } comp.getStaff().add(staff); } System.out.println(comp.toString()); // ×¢²á¼àÌýÆ÷ groove.addListener(new GrooveListener() { public void handleEvent(GrooveEvent e) { System.out.println(e.getType()); } }); // Æô¶¯groove groove.loop(comp, 120); } }
mit
iyzico/iyzipay-java
src/test/java/com/iyzipay/sample/subscription/SubscriptionPricingPlanSample.java
5069
package com.iyzipay.sample.subscription; import com.iyzipay.IyzipayResource; import com.iyzipay.model.Currency; import com.iyzipay.model.Locale; import com.iyzipay.model.Status; import com.iyzipay.model.subscription.SubscriptionPricingPlan; import com.iyzipay.model.subscription.enumtype.SubscriptionPaymentInterval; import com.iyzipay.model.subscription.enumtype.SubscriptionPaymentType; import com.iyzipay.request.subscription.CreateSubscriptionPricingPlanRequest; import com.iyzipay.request.subscription.UpdateSubscriptionPricingPlanRequest; import com.iyzipay.sample.Sample; import org.junit.Test; import java.math.BigDecimal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class SubscriptionPricingPlanSample extends Sample { @Test public void should_create() { CreateSubscriptionPricingPlanRequest createSubscriptionPricingPlanRequest = new CreateSubscriptionPricingPlanRequest(); createSubscriptionPricingPlanRequest.setPlanPaymentType(SubscriptionPaymentType.RECURRING.name()); createSubscriptionPricingPlanRequest.setName("caner-pricing-plan-2"); createSubscriptionPricingPlanRequest.setPrice(BigDecimal.TEN); createSubscriptionPricingPlanRequest.setCurrencyCode(Currency.TRY.name()); createSubscriptionPricingPlanRequest.setPaymentInterval(SubscriptionPaymentInterval.WEEKLY.name()); createSubscriptionPricingPlanRequest.setPaymentIntervalCount(1); createSubscriptionPricingPlanRequest.setTrialPeriodDays(10); createSubscriptionPricingPlanRequest.setRecurrenceCount(9); createSubscriptionPricingPlanRequest.setLocale(Locale.TR.name()); createSubscriptionPricingPlanRequest.setConversationId("12345678"); SubscriptionPricingPlan response = SubscriptionPricingPlan.create("c777b5b0-bc79-4f3f-ac1f-71c064990939", createSubscriptionPricingPlanRequest, options); assertEquals(response.getStatus(), Status.SUCCESS.getValue()); assertNotNull(response.getSubscriptionPricingPlanData().getPlanPaymentType()); assertNotNull(response.getSubscriptionPricingPlanData().getName()); assertNotNull(response.getSubscriptionPricingPlanData().getPrice()); assertNotNull(response.getSubscriptionPricingPlanData().getCurrencyCode()); assertNotNull(response.getSubscriptionPricingPlanData().getPaymentInterval()); assertNotNull(response.getSubscriptionPricingPlanData().getPaymentIntervalCount()); assertNotNull(response.getSubscriptionPricingPlanData().getTrialPeriodDays()); assertNotNull(response.getSubscriptionPricingPlanData().getRecurrenceCount()); assertNotNull(response.getSubscriptionPricingPlanData().getReferenceCode()); assertNotNull(response.getSubscriptionPricingPlanData().getProductReferenceCode()); assertNotNull(response.getSubscriptionPricingPlanData().getCreatedDate()); } @Test public void should_update() { UpdateSubscriptionPricingPlanRequest updateSubscriptionPricingPlanRequest = new UpdateSubscriptionPricingPlanRequest(); updateSubscriptionPricingPlanRequest.setName("caner-pricing-plan"); updateSubscriptionPricingPlanRequest.setTrialPeriodDays(13); updateSubscriptionPricingPlanRequest.setLocale(Locale.TR.name()); updateSubscriptionPricingPlanRequest.setConversationId("12345678"); SubscriptionPricingPlan response = SubscriptionPricingPlan.update("553d006c-da91-46d3-81a4-8297881d6b9e", updateSubscriptionPricingPlanRequest, options); assertEquals(response.getStatus(), Status.SUCCESS.getValue()); assertEquals(response.getSubscriptionPricingPlanData().getTrialPeriodDays(), updateSubscriptionPricingPlanRequest.getTrialPeriodDays()); assertNotNull(response.getSubscriptionPricingPlanData().getCreatedDate()); assertNotNull(response.getSubscriptionPricingPlanData().getCurrencyCode()); assertNotNull(response.getSubscriptionPricingPlanData().getName()); assertNotNull(response.getSubscriptionPricingPlanData().getPaymentInterval()); assertNotNull(response.getSubscriptionPricingPlanData().getPaymentIntervalCount()); assertNotNull(response.getSubscriptionPricingPlanData().getPlanPaymentType()); assertNotNull(response.getSubscriptionPricingPlanData().getPrice()); assertNotNull(response.getSubscriptionPricingPlanData().getProductReferenceCode()); assertNotNull(response.getSubscriptionPricingPlanData().getRecurrenceCount()); } @Test public void should_retrieve() { SubscriptionPricingPlan response = SubscriptionPricingPlan.retrieve("553d006c-da91-46d3-81a4-8297881d6b9e", options); //then assertEquals(response.getStatus(), Status.SUCCESS.getValue()); } @Test public void should_delete() { IyzipayResource response = SubscriptionPricingPlan.delete("ffa7b210-7990-4a3b-ad2c-e57774e8ec24", options); assertEquals(response.getStatus(), Status.SUCCESS.getValue()); } }
mit
bq12345/Note
src/org/bq/db/Note.java
1519
package org.bq.db; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit. /** * Entity mapped to table NOTE. */ public class Note { private Long id; /** Not-null value. */ private String text; private Integer type; private Integer widget; private java.util.Date date; public Note() { this.date= new java.util.Date(); } public Note(Long id) { this.id = id; this.date= new java.util.Date(); } public Note(Long id, String text, Integer type, Integer widget, java.util.Date date) { this.id = id; this.text = text; this.type = type; this.widget = widget; this.date = date; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } /** Not-null value. */ public String getText() { return text; } /** Not-null value; ensure this value is available before it is saved to the database. */ public void setText(String text) { this.text = text; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getWidget() { return widget; } public void setWidget(Integer widget) { this.widget = widget; } public java.util.Date getDate() { return date; } public void setDate(java.util.Date date) { this.date = date; } }
mit
FanHuaRan/interview.algorithm
offerjava/牛客竞赛/牛客练习赛9/珂朵莉的假动态仙人掌/Main.java
365
import java.util.Scanner; public class Main{ public static void main(String...args){ Scanner scanner=new Scanner(System.in ); while(scanner.hasNext()){ int n=scanner.nextInt(); int total=n/3*2; if(n%3!=0){ total++; } System.out.println(total); } } }
mit
Mknsri/Drunk-Toss
core/src/com/mknsri/drunktoss/Loader/Art.java
6667
/* The MIT License (MIT) Copyright (c) 2015 Markus Mikonsaari 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.mknsri.drunktoss.Loader; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; public class Art { public static TextureRegion bg; public static TextureRegion titleLogo; public static TextureRegion angle; public static TextureRegion pommi1; public static TextureRegion pommi1r; public static TextureRegion[] bgSetDbl; public static TextureRegion ilpo; public static TextureRegion ilpoEnd; public static TextureRegion[] ilpoAndPoke; public static TextureRegion pokeBody; public static TextureRegion pokeBackArm; public static TextureRegion pokeFrontArm; public static TextureRegion ilpoDuck; public static TextureRegion[] ilpoFly; public static TextureRegion[] pummiIdle; public static TextureRegion[] pummiTriggered; public static TextureRegion[] groupFighting; public static TextureRegion groupIdle; public static TextureRegion groupEnd; public static TextureRegion[] menuBg; public static TextureRegion newgameB; public static TextureRegion newgameBA; public static TextureRegion optionsB; public static TextureRegion optionsBA; public static TextureRegion hiscoresB; public static TextureRegion hiscoresBA; public static TextureRegion quitB; public static TextureRegion quitBA; public static TextureRegion checkB; public static TextureRegion checkBA; public static TextureRegion optionsBg; public static TextureRegion okB; public static TextureRegion okBA; public static TextureRegion tut1; public static TextureRegion tut2; public static TextureRegion btnAllTime; public static TextureRegion btnAllTimeA; public static TextureRegion btnWeekly; public static TextureRegion btnWeeklyA; public static TextureRegion btnPersonal; public static TextureRegion btnPersonalA; public static TextureRegion uploadB; public static TextureRegion uploadBA; public static TextureRegion hiScoreMenu; public static TextureRegion hiScoreScreen; public static void loadArt() { titleLogo = loadSprite("data/title.png", 0, 0); angle = loadSprite("data/angle.png", 0, 0); ilpoFly = loadAnimation("data/ilponanim.png",70,58,3,1); ilpoDuck = loadSprite("data/ilponduck.png",0,0); ilpoEnd = loadSprite("data/nilpoend.png",0,0); pokeBody = loadSprite("data/npokebody.png",0,0); pokeFrontArm = loadSprite("data/pokefrontarm.png", 0,0); pokeBackArm = loadSprite("data/npokebackarm.png", 0,0); pummiIdle = loadAnimation("data/pumanim.png",100,50,2,1); pummiTriggered = loadAnimation("data/pumtriggered.png",100,50,2,1); groupFighting = loadAnimation("data/groupfight.png",150,150,3,1); groupIdle = loadSprite("data/shadygroup.png", 0, 0); groupEnd = loadSprite("data/shadygroupend.png", 0, 0); menuBg = loadAnimation("data/mmanim.png",320,240,3,1); optionsBg = loadSprite("data/optionsmenu.png",320,240); newgameB = loadSprite("data/newgameb.png",0,0); newgameBA = loadSprite("data/newgameba.png",0,0); optionsB = loadSprite("data/optionsb.png",0,0); optionsBA = loadSprite("data/optionsba.png",0,0); hiscoresB = loadSprite("data/hiscoresb.png",0,0); hiscoresBA = loadSprite("data/hiscoresba.png",0,0); quitB = loadSprite("data/quitb.png",0,0); quitBA = loadSprite("data/quitba.png",0,0); checkB = loadSprite("data/checkb.png",0,0); checkBA = loadSprite("data/checkba.png",0,0); okB = loadSprite("data/okb.png",0,0); okBA = loadSprite("data/okba.png",0,0); hiScoreScreen = loadSprite("data/hiscore.png",0,0); tut1 = loadSprite("data/tut1.png",0,0); tut2 = loadSprite("data/tut2.png",0,0); btnAllTime = loadSprite("data/lb_alltime.png",0,0); btnAllTimeA = loadSprite("data/lb_alltimea.png",0,0); btnWeekly = loadSprite("data/lb_weekly.png",0,0); btnWeeklyA = loadSprite("data/lb_weeklya.png",0,0); btnPersonal = loadSprite("data/lb_personal.png",0,0); btnPersonalA = loadSprite("data/lb_personala.png",0,0); uploadB = loadSprite("data/uploadb.png",0,0); uploadBA = loadSprite("data/uploadba.png",0,0); hiScoreMenu = loadSprite("data/leaderboardbg.png",0,0); // Load 1st set bgSetDbl = new TextureRegion[10]; for (int i = 0; i < 10; i++) { int x = i+1; bgSetDbl[i] = loadSprite("data/bg_" + x + ".png", 0, 0); } } public static TextureRegion loadSprite (String name, int width, int height) { Texture texture = new Texture(Gdx.files.internal(name)); if (width == 0) { width = texture.getWidth(); } if (height == 0) { height = texture.getHeight(); } TextureRegion region = new TextureRegion(texture, 0, 0, width, height); //region.flip(false, true); return region; } public static TextureRegion[] loadAnimation(String fileName, int width, int height, int frameCols, int frameRows) { TextureRegion img = loadSprite(fileName, width * frameCols, height * frameRows); TextureRegion[][] spritesheetTemp = img.split(width, height); TextureRegion[] spritesheet = new TextureRegion[frameRows*frameCols]; // Fix the indices frameCols--; frameRows--; for (int i = 0; i <= frameRows; i++) { for (int y = 0; y <= frameCols; y++) { spritesheet[i+y] = spritesheetTemp[i][y]; } } return spritesheet; } public static TextureRegion[] returnBgSet(String setName) { if (setName == "dbl") { return bgSetDbl; } else { return bgSetDbl; } } }
mit
451222664/coolweather
app/src/main/java/com/coolweather/android/gson/Forecast.java
489
package com.coolweather.android.gson; import com.google.gson.annotations.SerializedName; /** * Created by ronny on 2017/10/22. */ public class Forecast { public String date; @SerializedName("tmp") public Temperature temperature; @SerializedName("cond") public More more; public class Temperature { public String max; public String min; } public class More { @SerializedName("txt_d") public String info; } }
mit
RyanGraessle/movie-db
app/src/main/java/com/graessle/movie_db/ui/activity/MovieListingActivity.java
8881
package com.graessle.movie_db.ui.activity; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.percent.PercentRelativeLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.graphics.Palette; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.util.StringBuilderPrinter; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.graessle.movie_db.R; import com.graessle.movie_db.adapters.MovieDBPagerAdapter; import com.graessle.movie_db.adapters.MovieListingPagerAdapter; import com.graessle.movie_db.api.ApiClient; import com.graessle.movie_db.api.MovieCallback; import com.graessle.movie_db.api.call.MovieApi; import com.graessle.movie_db.model.Cast; import com.graessle.movie_db.model.CreditsResponse; import com.graessle.movie_db.model.Genre; import com.graessle.movie_db.model.Movie; import com.graessle.movie_db.model.MoviesResponse; import com.graessle.movie_db.utils.tab.SlidingTabLayout; import com.graessle.movie_db.utils.tab.SlidingTabStrip; import com.squareup.picasso.Picasso; import com.squareup.picasso.Target; import java.util.List; import java.util.UUID; import butterknife.Bind; import butterknife.ButterKnife; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Author: rgraessle * Created: 4/14/17. */ public class MovieListingActivity extends BaseActivityMenu { @Bind(R.id.BackdropImage) ImageView backdropImage; @Bind(R.id.PosterImage) ImageView posterImage; @Bind(R.id.Toolbar) Toolbar toolbar; @Bind(R.id.ToolbarTitle) TextView titleTxtView; @Bind(R.id.TitleCardView) PercentRelativeLayout titleCardView; @Bind(R.id.Tabs) SlidingTabLayout tabs; @Bind(R.id.MovieTitle) TextView movieTitle; @Bind(R.id.MovieGenre) TextView movieGenre; @Bind(R.id.LoginSignupPager) ViewPager viewPager; private static String TAG = MovieListingActivity.class.getSimpleName(); private ProgressDialog progressDialog; private static final String MOVIE_ID_KEY = "MOVIE_ID"; private int movieID; private List<Cast> castList; private Movie movieDetails; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_listing); ButterKnife.bind(this); Bundle extras = getIntent().getExtras(); if (extras != null) { movieID = extras.getInt(MOVIE_ID_KEY); } loadMovie(); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.getBackground().setAlpha(0); titleTxtView.setText(""); } public SlidingTabLayout.TabColorizer getTabColorizer() { return new SlidingTabLayout.TabColorizer() { @Override public int getIndicatorColor(final int position) { return getResources().getColor(R.color.black); } }; } private void loadCredits() { MovieApi.getCreditsByMovieId(this, movieID, getResources().getString(R.string.api_key), new MovieCallback() { @Override public void onSuccess(Response<?> response) { CreditsResponse moviesResponse = (CreditsResponse) response.body(); castList = moviesResponse.getCast(); setCast(castList); setData(); setTabs(); } @Override public void onFailure(int responseCode) { } }, UUID.randomUUID().toString()); } private void loadMovie() { MovieApi.getMovieById(this, movieID, getResources().getString(R.string.api_key), new MovieCallback() { @Override public void onSuccess(Response<?> response) { movieDetails = (Movie) response.body(); loadCredits(); } @Override public void onFailure(int responseCode) { Log.e(TAG, "Failue: " + responseCode); } }, UUID.randomUUID().toString()); } public void setData() { setMovieDetails(movieDetails); StringBuilder sb = new StringBuilder(); int i = 1; for(Genre genre : movieDetails.getGenres()) { sb.append(genre.getName()); if(i < movieDetails.getGenres().size()) { sb.append(", "); } i++; } movieTitle.setText(movieDetails.getTitle()); movieGenre.setText(sb); Target target = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { backdropImage.setImageBitmap(bitmap); Palette.from(bitmap) .generate(new Palette.PaletteAsyncListener() { @Override public void onGenerated(Palette palette) { Palette.Swatch textSwatch = palette.getMutedSwatch(); if(textSwatch == null) { titleCardView.setBackgroundColor(getResources().getColor(R.color.maximum_blue)); tabs.setBackgroundColor(getResources().getColor(R.color.maximum_blue)); return; } titleCardView.setBackgroundColor(textSwatch.getRgb()); tabs.setBackgroundColor(textSwatch.getRgb()); } }); } @Override public void onBitmapFailed(Drawable errorDrawable) { Log.e(TAG, errorDrawable.toString()); } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } }; backdropImage.setTag(target); if (!TextUtils.isEmpty(movieDetails.getBackdropPath())) { if(movieDetails.getBackdropPath() == null) { backdropImage.setBackgroundColor(getResources().getColor(R.color.cardview_dark_background)); titleCardView.setBackgroundColor(getResources().getColor(R.color.maximum_blue)); tabs.setBackgroundColor(getResources().getColor(R.color.maximum_blue)); } else { Picasso.with(this).load(getResources().getString(R.string.backdrop_link) + movieDetails.getBackdropPath()) .into(target); } } if (!TextUtils.isEmpty(movieDetails.getPosterPath())) { Picasso.with(this).load(getResources().getString(R.string.image_link) + movieDetails.getPosterPath()) .error(R.color.cardview_dark_background) .placeholder(R.color.cardview_dark_background) .into(posterImage); } } public void setTabs() { final CharSequence[] titles = getResources().getStringArray(R.array.movie_listing_tabs); MovieListingPagerAdapter mPagerAdapter = new MovieListingPagerAdapter(getSupportFragmentManager(), titles.length, titles); viewPager.setAdapter(mPagerAdapter); tabs.setDistributeEvenly(true); tabs.setCustomTabColorizer(getTabColorizer()); tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { SlidingTabStrip strip = (SlidingTabStrip) tabs.getChildAt(0); TextView selectedTv = (TextView) strip.getChildAt(position); selectedTv.setTextColor(getResources().getColor(R.color.black)); TextView unselectedTv = (TextView) strip.getChildAt((position + 1) % 2); unselectedTv.setTextColor(getResources().getColor(R.color.white)); } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } }); tabs.setViewPager(viewPager); } public void setMovieDetails(Movie movie) { this.movieDetails = movie; } public Movie getMovieDetails() { Log.i(TAG, "movie details called: " + movieDetails.toString()); return movieDetails; } public void setCast(List<Cast> cast) { this.castList = cast; } public List<Cast> getCast() { return castList; } }
mit
hunny/xplus
bootweb/trunk/bootweb-security/src/main/java/com/example/bootweb/security/web/AboutController.java
2381
package com.example.bootweb.security.web; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.bootweb.security.about.ApplicationAbout; @RestController @RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public class AboutController { private final Logger logger = LoggerFactory.getLogger(getClass()); @GetMapping("/about") public ResponseEntity<ApplicationAbout> getAbout() { logger.info("Receive about request."); return new ResponseEntity<ApplicationAbout>(ApplicationAbout.get(getClass()), HttpStatus.OK); } @GetMapping("/about/{id}") public ResponseEntity<Map<String, String>> getAboutId(@PathVariable("id") Integer id) { logger.info("Receive about request id {}.", id); Map<String, String> map = new HashMap<String, String>(); map.put("id", String.valueOf(id)); return new ResponseEntity<Map<String, String>>(map, HttpStatus.valueOf(id)); } // @RequestMapping(value="/logout", method = RequestMethod.GET) public void logoutPage(HttpServletRequest request, HttpServletResponse response) throws IOException { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { new SecurityContextLogoutHandler().logout(request, response, auth); } response.setStatus(401); response.getWriter().write("{status:401}"); response.getWriter().flush(); // return "redirect:/login?logout";//You can redirect wherever you want, but // generally it's a good practice to show login screen again. } }
mit
kohsuke/github-api
src/main/java/org/kohsuke/github/GHDiscussionBuilder.java
2529
package org.kohsuke.github; import java.io.IOException; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; /** * Base class for creating or updating a discussion. * * @param <S> * Intermediate return type for this builder returned by calls to {@link #with(String, Object)}. If {@link S} * the same as {@link GHLabel}, this builder will commit changes after each call to * {@link #with(String, Object)}. */ class GHDiscussionBuilder<S> extends AbstractBuilder<GHDiscussion, S> { private final GHTeam team; /** * * @param intermediateReturnType * Intermediate return type for this builder returned by calls to {@link #with(String, Object)}. If * {@link S} the same as {@link GHDiscussion}, this builder will commit changes after each call to * {@link #with(String, Object)}. * @param team * the GitHub team. Updates will be sent to the root of this team. * @param baseInstance * instance on which to base this builder. If {@code null} a new instance will be created. */ protected GHDiscussionBuilder(@Nonnull Class<S> intermediateReturnType, @Nonnull GHTeam team, @CheckForNull GHDiscussion baseInstance) { super(GHDiscussion.class, intermediateReturnType, team.root(), baseInstance); this.team = team; if (baseInstance != null) { requester.with("title", baseInstance.getTitle()); requester.with("body", baseInstance.getBody()); } } /** * Title for this discussion. * * @param value * title of discussion * @return either a continuing builder or an updated {@link GHDiscussion} * @throws IOException * if there is an I/O Exception */ @Nonnull public S title(String value) throws IOException { return with("title", value); } /** * Body content for this discussion. * * @param value * body of discussion* * @return either a continuing builder or an updated {@link GHDiscussion} * @throws IOException * if there is an I/O Exception */ @Nonnull public S body(String value) throws IOException { return with("body", value); } /** * {@inheritDoc} */ @Nonnull @Override public GHDiscussion done() throws IOException { return super.done().wrapUp(team); } }
mit
feltnerm/uwponopoly
src/dice/Dice.java
2373
package dice; import java.util.Random; /** * Simulates rolling two dice, as used in Monopoly. This gives it a range of * 2-12 for possible values. */ public class Dice { private static int HIGH_NUMBER = 6; // highest number on die private int dice1, dice2; private Random random; public int total; public boolean doubles; /** * Dice constructor. Rolls once to ensure first two die are not both 0. */ public Dice() { random = new Random(); roll(); // otherwise both die would be zeroes. } /** * Roll this dice. * * A note on the method used: * According to * http://docs.oracle.com/javase/6/docs/api/java/util/Random.html, * nextInt( n ) "returns a pseudorandom, uniformly distributed int value * between 0 (inclusive) * and the specified value (exclusive), drawn from this random number * generator's sequence." * Thus we add one to nextInt( 6 ) ( for a six-sided die ) to get a * random number 1-6. */ public void roll() { dice1 = random.nextInt(HIGH_NUMBER) + 1; dice2 = random.nextInt(HIGH_NUMBER) + 1; this.total = this.getTotal(); this.doubles = this.isDoubles(); } /** * @return The sum of the two dice. */ public int getTotal() { return dice1 + dice2; } /** * @return the values of each dice. */ public int[] toArray() { int[] dice = {dice1, dice2}; return dice; } /** * Copies the values of another dice to this dice. */ public void setEqualTo(Dice dice) { this.dice1 = dice.dice1; this.dice2 = dice.dice2; } /** * formats the dice as a Cartesian coordinate (x,y) */ @Override public String toString() { return "(" + dice1 + "," + dice2 + ")"; } /** * @return true if the roll is doubles */ public boolean isDoubles() { return dice1 == dice2; } /** * @return the value of the first die. */ public int getFirstDie() { return dice1; } /** * @return the value of the second die. */ public int getSecondDie() { return dice2; } // testbed main public static void main(String[] args) { // declare the test object Dice d = new Dice(); // print a banner System.out.println("Dice Testbed"); System.out.println("============"); // roll the dice and print the output for (int i = 0; i < 10; i++) { d.roll(); System.out.format( d.toString() + " | %2d | " + d.isDoubles() + "\n", d.getTotal()); } } }
mit
Steveice10/Peacecraft
PeacecraftBukkit/src/main/java/com/peacecraftec/bukkit/chat/listener/ChatListener.java
5058
package com.peacecraftec.bukkit.chat.listener; import com.peacecraftec.bukkit.chat.ChatPermissions; import com.peacecraftec.bukkit.chat.PeacecraftChat; import com.peacecraftec.bukkit.chat.util.ChatUtil; import com.peacecraftec.web.chat.data.ChannelData; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerQuitEvent; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.peacecraftec.bukkit.internal.util.SenderUtil.getDisplayName; import static com.peacecraftec.bukkit.internal.util.SenderUtil.sendMessage; public class ChatListener implements Listener { private static final SimpleDateFormat FORMAT = new SimpleDateFormat("HH:mm"); private PeacecraftChat module; public ChatListener(PeacecraftChat module) { this.module = module; } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerJoin(PlayerJoinEvent event) { // Make sure player has channels. this.module.getChannelData(event.getPlayer().getUniqueId()).getChannels(); this.module.getChannelData(event.getPlayer().getUniqueId()).getActiveChannel(); this.module.loadDisplayName(event.getPlayer()); this.module.addOnlinePlayer(event.getPlayer().getUniqueId()); event.setJoinMessage(event.getJoinMessage().replaceFirst(Pattern.quote(event.getPlayer().getName()), ChatColor.RESET + Matcher.quoteReplacement(event.getPlayer().getDisplayName()) + ChatColor.RESET + ChatColor.YELLOW)); this.module.broadcastWeb(event.getJoinMessage()); } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerQuit(PlayerQuitEvent event) { this.module.removeOnlinePlayer(event.getPlayer().getUniqueId()); event.setQuitMessage(event.getQuitMessage().replaceFirst(Pattern.quote(event.getPlayer().getName()), ChatColor.RESET + Matcher.quoteReplacement(event.getPlayer().getDisplayName()) + ChatColor.RESET + ChatColor.YELLOW)); this.module.broadcastWeb(event.getQuitMessage()); } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerKick(PlayerKickEvent event) { this.module.removeOnlinePlayer(event.getPlayer().getUniqueId()); event.setLeaveMessage(event.getLeaveMessage().replaceFirst(Pattern.quote(event.getPlayer().getName()), ChatColor.RESET + Matcher.quoteReplacement(event.getPlayer().getDisplayName()) + ChatColor.RESET + ChatColor.YELLOW)); } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerDeath(PlayerDeathEvent event) { StringBuilder msg = new StringBuilder(); for(String pt : event.getDeathMessage().split(" ")) { if(msg.length() > 0) { msg.append(" "); } else { msg.append(ChatColor.YELLOW); } Player p = Bukkit.getServer().getPlayerExact(pt); if(p != null) { msg.append(ChatColor.RESET).append(getDisplayName(p)).append(ChatColor.RESET).append(ChatColor.YELLOW); } else { msg.append(pt); } } event.setDeathMessage(msg.toString()); this.module.broadcastWeb(event.getDeathMessage()); } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerChat(AsyncPlayerChatEvent event) { Player player = event.getPlayer(); if(this.module.isMuted(player.getUniqueId())) { sendMessage(player, "chat.muted"); event.setCancelled(true); return; } if(player.hasPermission(ChatPermissions.CHAT_COLOR)) { event.setMessage(ChatUtil.translateColor(event.getMessage())); } if(player.hasPermission(ChatPermissions.CHAT_MAGIC)) { event.setMessage(event.getMessage().replaceAll("&[kK]", ChatColor.COLOR_CHAR + "k")); } if(player.hasPermission(ChatPermissions.CHAT_FORMAT)) { event.setMessage(ChatUtil.translateFormat(event.getMessage())); } if(ChatColor.stripColor(event.getMessage()).trim().equals("")) { event.setCancelled(true); return; } ChannelData data = this.module.getChannelData(player.getUniqueId()); event.setFormat(ChatColor.GRAY + "[" + FORMAT.format(new Date()) + "] " + ChatColor.RESET + "%1$s" + ChatColor.RESET + " " + ChatUtil.formatChannelName(data.getActiveChannel()) + ": %2$s"); this.module.sendToChannel(event.getPlayer().getUniqueId(), data.getActiveChannel(), String.format(event.getFormat(), getDisplayName(player), event.getMessage())); event.setCancelled(true); } }
mit
liamnickell/ap-cs
CodingBat/PlusOut.java
646
public class PlusOut { public static void main(String[] args) { System.out.println(plusOut("asdfasddasdfasdff", "as")); } public static String plusOut(String str, String word) { String newStr = ""; for(int i=0; i<str.length()-word.length()+1; i++) { if(str.substring(i, i+word.length()).equals(word)) { newStr += str.substring(i, i+word.length()); i += word.length()-1; } else { newStr += "+" } } while(newStr.length() < word.length()) { newStr += "+"; } return newStr; } }
mit
ceyhuno/react-native-navigation
lib/android/app/src/test/java/com/reactnativenavigation/viewcontrollers/bottomtabs/BottomTabsControllerTest.java
15846
package com.reactnativenavigation.viewcontrollers.bottomtabs; import android.app.Activity; import android.graphics.Color; import android.support.annotation.NonNull; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import com.reactnativenavigation.BaseTest; import com.reactnativenavigation.TestUtils; import com.reactnativenavigation.mocks.ImageLoaderMock; import com.reactnativenavigation.mocks.SimpleViewController; import com.reactnativenavigation.parse.Options; import com.reactnativenavigation.parse.params.Bool; import com.reactnativenavigation.parse.params.Colour; import com.reactnativenavigation.parse.params.Number; import com.reactnativenavigation.parse.params.Text; import com.reactnativenavigation.presentation.BottomTabPresenter; import com.reactnativenavigation.presentation.BottomTabsPresenter; import com.reactnativenavigation.presentation.Presenter; import com.reactnativenavigation.react.EventEmitter; import com.reactnativenavigation.utils.CommandListenerAdapter; import com.reactnativenavigation.utils.ImageLoader; import com.reactnativenavigation.utils.OptionHelper; import com.reactnativenavigation.utils.ViewUtils; import com.reactnativenavigation.viewcontrollers.ChildControllersRegistry; import com.reactnativenavigation.viewcontrollers.ParentController; import com.reactnativenavigation.viewcontrollers.ViewController; import com.reactnativenavigation.viewcontrollers.stack.StackController; import com.reactnativenavigation.views.BottomTabs; import com.reactnativenavigation.views.ReactComponent; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import edu.emory.mathcs.backport.java.util.Collections; import static com.reactnativenavigation.TestUtils.hideBackButton; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class BottomTabsControllerTest extends BaseTest { private Activity activity; private BottomTabs bottomTabs; private BottomTabsController uut; private Options initialOptions = new Options(); private ViewController child1; private ViewController child2; private ViewController child3; private StackController child4; private ViewController child5; private ViewController child6; private Options tabOptions = OptionHelper.createBottomTabOptions(); private ImageLoader imageLoaderMock = ImageLoaderMock.mock(); private EventEmitter eventEmitter; private ChildControllersRegistry childRegistry; private List<ViewController> tabs; private BottomTabsPresenter presenter; private BottomTabsAttacher tabsAttacher; @Override public void beforeEach() { activity = newActivity(); bottomTabs = spy(new BottomTabs(activity) { @Override public void superCreateItems() { } }); childRegistry = new ChildControllersRegistry(); eventEmitter = Mockito.mock(EventEmitter.class); child1 = spy(new SimpleViewController(activity, childRegistry, "child1", tabOptions)); child2 = spy(new SimpleViewController(activity, childRegistry, "child2", tabOptions)); child3 = spy(new SimpleViewController(activity, childRegistry, "child3", tabOptions)); child4 = spy(createStack("someStack")); child5 = spy(new SimpleViewController(activity, childRegistry, "child5", tabOptions)); child6 = spy(new SimpleViewController(activity, childRegistry, "child6", tabOptions)); when(child5.handleBack(any())).thenReturn(true); tabs = createTabs(); presenter = spy(new BottomTabsPresenter(tabs, new Options())); tabsAttacher = spy(new BottomTabsAttacher(tabs, presenter)); uut = createBottomTabs(); uut.setParentController(Mockito.mock(ParentController.class)); activity.setContentView(uut.getView()); } @Test public void containsRelativeLayoutView() { assertThat(uut.getView()).isInstanceOf(RelativeLayout.class); assertThat(uut.getView().getChildAt(0)).isInstanceOf(BottomTabs.class); } @Test(expected = RuntimeException.class) public void setTabs_ThrowWhenMoreThan5() { tabs.add(new SimpleViewController(activity, childRegistry, "6", tabOptions)); createBottomTabs(); } @Test public void parentControllerIsSet() { uut = createBottomTabs(); for (ViewController tab : tabs) { assertThat(tab.getParentController()).isEqualTo(uut); } } @Test public void setTabs_allChildViewsAreAttachedToHierarchy() { uut.onViewAppeared(); assertThat(uut.getView().getChildCount()).isEqualTo(6); for (ViewController child : uut.getChildControllers()) { assertThat(child.getView().getParent()).isNotNull(); } } @Test public void setTabs_firstChildIsVisibleOtherAreGone() { uut.onViewAppeared(); for (int i = 0; i < uut.getChildControllers().size(); i++) { assertThat(uut.getView().getChildAt(i + 1)).isEqualTo(tabs.get(i).getView()); assertThat(uut.getView().getChildAt(i + 1).getVisibility()).isEqualTo(i == 0 ? View.VISIBLE : View.INVISIBLE); } } @Test public void createView_layoutOptionsAreAppliedToTabs() { uut.ensureViewIsCreated(); for (int i = 0; i < tabs.size(); i++) { verify(presenter, times(1)).applyLayoutParamsOptions(any(), eq(i)); assertThat(childLayoutParams(i).width).isEqualTo(ViewGroup.LayoutParams.MATCH_PARENT); assertThat(childLayoutParams(i).height).isEqualTo(ViewGroup.LayoutParams.MATCH_PARENT); } } @Test public void onTabSelected() { uut.ensureViewIsCreated(); assertThat(uut.getSelectedIndex()).isZero(); assertThat(((ViewController) ((List) uut.getChildControllers()).get(0)).getView().getVisibility()).isEqualTo(View.VISIBLE); uut.onTabSelected(3, false); assertThat(uut.getSelectedIndex()).isEqualTo(3); assertThat(((ViewController) ((List) uut.getChildControllers()).get(0)).getView().getVisibility()).isEqualTo(View.INVISIBLE); assertThat(((ViewController) ((List) uut.getChildControllers()).get(3)).getView().getVisibility()).isEqualTo(View.VISIBLE); verify(eventEmitter, times(1)).emitBottomTabSelected(0, 3); } @Test public void onTabReSelected() { uut.ensureViewIsCreated(); assertThat(uut.getSelectedIndex()).isZero(); uut.onTabSelected(0, true); assertThat(uut.getSelectedIndex()).isEqualTo(0); assertThat(((ViewController) ((List) uut.getChildControllers()).get(0)).getView().getParent()).isNotNull(); verify(eventEmitter, times(1)).emitBottomTabSelected(0, 0); } @Test public void handleBack_DelegatesToSelectedChild() { uut.ensureViewIsCreated(); assertThat(uut.handleBack(new CommandListenerAdapter())).isFalse(); uut.selectTab(4); assertThat(uut.handleBack(new CommandListenerAdapter())).isTrue(); verify(child5, times(1)).handleBack(any()); } @Test public void applyOptions_bottomTabsOptionsAreClearedAfterApply() { ViewUtils.removeFromParent(uut.getView()); Options options = new Options(); options.bottomTabsOptions.backgroundColor = new Colour(Color.RED); child1.mergeOptions(options); uut.ensureViewIsCreated(); StackController stack = spy(createStack("stack")); stack.ensureViewIsCreated(); stack.push(uut, new CommandListenerAdapter()); child1.onViewAppeared(); ArgumentCaptor<Options> optionsCaptor = ArgumentCaptor.forClass(Options.class); ArgumentCaptor<ReactComponent> viewCaptor = ArgumentCaptor.forClass(ReactComponent.class); verify(stack, times(1)).applyChildOptions(optionsCaptor.capture(), viewCaptor.capture()); assertThat(viewCaptor.getValue()).isEqualTo(child1.getView()); assertThat(optionsCaptor.getValue().bottomTabsOptions.backgroundColor.hasValue()).isFalse(); } @Test public void applyOptions_bottomTabsCreateViewOnlyOnce() { verify(presenter).applyOptions(any()); verify(bottomTabs, times(2)).superCreateItems(); // first time when view is created, second time when options are applied } @Test public void mergeOptions_currentTabIndex() { uut.ensureViewIsCreated(); assertThat(uut.getSelectedIndex()).isZero(); Options options = new Options(); options.bottomTabsOptions.currentTabIndex = new Number(1); uut.mergeOptions(options); assertThat(uut.getSelectedIndex()).isOne(); verify(eventEmitter, times(0)).emitBottomTabSelected(any(Integer.class), any(Integer.class)); } @Test public void mergeOptions_drawBehind() { uut.ensureViewIsCreated(); child1.onViewAppeared(); uut.selectTab(0); assertThat(childLayoutParams(0).bottomMargin).isEqualTo(uut.getBottomTabs().getHeight()); Options o1 = new Options(); o1.bottomTabsOptions.drawBehind = new Bool(true); child1.mergeOptions(o1); assertThat(childLayoutParams(0).bottomMargin).isEqualTo(0); Options o2 = new Options(); o2.topBar.title.text = new Text("Some text"); child1.mergeOptions(o1); assertThat(childLayoutParams(0).bottomMargin).isEqualTo(0); } @Test public void applyChildOptions_resolvedOptionsAreUsed() { Options childOptions = new Options(); SimpleViewController pushedScreen = new SimpleViewController(activity, childRegistry, "child4.1", childOptions); disablePushAnimation(pushedScreen); child4 = createStack(pushedScreen); tabs = new ArrayList<>(Collections.singletonList(child4)); tabsAttacher = new BottomTabsAttacher(tabs, presenter); initialOptions.bottomTabsOptions.currentTabIndex = new Number(0); Options resolvedOptions = new Options(); uut = new BottomTabsController(activity, tabs, childRegistry, eventEmitter, imageLoaderMock, "uut", initialOptions, new Presenter(activity, new Options()), tabsAttacher, presenter, new BottomTabPresenter(activity, tabs, ImageLoaderMock.mock(), new Options())) { @Override public Options resolveCurrentOptions() { return resolvedOptions; } @NonNull @Override protected BottomTabs createBottomTabs() { return new BottomTabs(activity) { @Override protected void createItems() { } }; } }; activity.setContentView(uut.getView()); verify(presenter, times(2)).applyChildOptions(eq(resolvedOptions), any()); } @Test public void child_mergeOptions_currentTabIndex() { uut.ensureViewIsCreated(); assertThat(uut.getSelectedIndex()).isZero(); Options options = new Options(); options.bottomTabsOptions.currentTabIndex = new Number(1); child1.mergeOptions(options); assertThat(uut.getSelectedIndex()).isOne(); } @Test public void resolveCurrentOptions_returnsFirstTabIfInvokedBeforeViewIsCreated() { uut = createBottomTabs(); assertThat(uut.getCurrentChild()).isEqualTo(tabs.get(0)); } @Test public void buttonPressInvokedOnCurrentTab() { uut.ensureViewIsCreated(); uut.selectTab(4); uut.sendOnNavigationButtonPressed("btn1"); verify(child5, times(1)).sendOnNavigationButtonPressed("btn1"); } @Test public void push() { uut.ensureViewIsCreated(); uut.selectTab(3); SimpleViewController stackChild = new SimpleViewController(activity, childRegistry, "stackChild", new Options()); SimpleViewController stackChild2 = new SimpleViewController(activity, childRegistry, "stackChild", new Options()); disablePushAnimation(stackChild, stackChild2); hideBackButton(stackChild2); child4.push(stackChild, new CommandListenerAdapter()); assertThat(child4.size()).isOne(); child4.push(stackChild2, new CommandListenerAdapter()); assertThat(child4.size()).isEqualTo(2); } @Test public void deepChildOptionsAreApplied() { child6.options.topBar.drawBehind = new Bool(false); disablePushAnimation(child6); child4.push(child6, new CommandListenerAdapter()); assertThat(child4.size()).isOne(); assertThat(uut.getSelectedIndex()).isZero(); verify(child6, times(0)).onViewAppeared(); assertThat(child4.getTopBar().getHeight()) .isNotZero() .isEqualTo(((ViewGroup.MarginLayoutParams) child6.getView().getLayoutParams()).topMargin); } @Test public void oneTimeOptionsAreAppliedOnce() { Options options = new Options(); options.bottomTabsOptions.currentTabIndex = new Number(1); assertThat(uut.getSelectedIndex()).isZero(); uut.mergeOptions(options); assertThat(uut.getSelectedIndex()).isOne(); assertThat(uut.options.bottomTabsOptions.currentTabIndex.hasValue()).isFalse(); assertThat(uut.initialOptions.bottomTabsOptions.currentTabIndex.hasValue()).isFalse(); } @Test public void selectTab() { uut.selectTab(1); verify(tabsAttacher).onTabSelected(tabs.get(1)); } @Test public void destroy() { uut.destroy(); verify(tabsAttacher).destroy(); } @NonNull private List<ViewController> createTabs() { return Arrays.asList(child1, child2, child3, child4, child5); } private StackController createStack(String id) { return TestUtils.newStackController(activity) .setId(id) .setInitialOptions(tabOptions) .build(); } private StackController createStack(ViewController initialChild) { return TestUtils.newStackController(activity) .setInitialOptions(tabOptions) .setChildren(new ArrayList<>(Collections.singleton(initialChild))) .build(); } private ViewGroup.MarginLayoutParams childLayoutParams(int index) { return (ViewGroup.MarginLayoutParams) tabs.get(index).getView().getLayoutParams(); } private BottomTabsController createBottomTabs() { return new BottomTabsController(activity, tabs, childRegistry, eventEmitter, imageLoaderMock, "uut", initialOptions, new Presenter(activity, new Options()), tabsAttacher, presenter, new BottomTabPresenter(activity, tabs, ImageLoaderMock.mock(), new Options())) { @Override public void ensureViewIsCreated() { super.ensureViewIsCreated(); uut.getView().layout(0, 0, 1000, 1000); uut.getBottomTabs().layout(0, 0, 1000, 100); } @NonNull @Override protected BottomTabs createBottomTabs() { return bottomTabs; } }; } }
mit
elBroom/atom
lecture07/src/main/java/ru/atom/lecture07/server/ChatServer.java
2123
package ru.atom.lecture07.server; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.handler.ResourceHandler; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import ru.atom.lecture07.server.dao.Database; public class ChatServer { public static void main(String[] args) throws Exception { Database.setUp(); ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(new Handler[] { createChatContext(), createResourceContext() }); Server jettyServer = new Server(8080); jettyServer.setHandler(contexts); jettyServer.start(); } private static ServletContextHandler createChatContext() { ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/chat/*"); ServletHolder jerseyServlet = context.addServlet( org.glassfish.jersey.servlet.ServletContainer.class, "/*"); jerseyServlet.setInitOrder(0); jerseyServlet.setInitParameter( "jersey.config.server.provider.packages", "ru.atom.lecture07.server" ); jerseyServlet.setInitParameter( "com.sun.jersey.spi.container.ContainerResponseFilters", CrossBrowserFilter.class.getCanonicalName() ); return context; } private static ContextHandler createResourceContext() { ContextHandler context = new ContextHandler(); context.setContextPath("/"); ResourceHandler handler = new ResourceHandler(); handler.setWelcomeFiles(new String[]{"index.html"}); String serverRoot = ChatServer.class.getResource("/static").toString(); System.out.println(serverRoot); handler.setResourceBase(serverRoot); context.setHandler(handler); return context; } }
mit
alexborlis/pl_test
analyzer/src/main/java/net/smartrss/admin/model/entity/enumerated/FeedAccountStatus.java
159
package net.smartrss.admin.model.entity.enumerated; /** * Created by Alexander on 02.02.2016. */ public enum FeedAccountStatus { ACTIVE, INACTIVE }
mit
mkrmpotic/SignMeApp
src/eu/signme/app/EmailAlreadySentActivity.java
2542
package eu.signme.app; import java.io.UnsupportedEncodingException; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpHeaderParser; import com.google.gson.Gson; import eu.signme.app.api.SignMeAPI; import eu.signme.app.api.SignMeAPI.ResendEmailHandler; import eu.signme.app.api.response.ErrorResponse; import eu.signme.app.api.response.ResendEmailResponse; import eu.signme.app.util.Fonts; import eu.signme.app.util.NetworkUtil; public class EmailAlreadySentActivity extends SignMeActivity implements OnClickListener { private Button btnResend; private String email; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_email_already_sent); Intent i = getIntent(); email = i.getExtras().getString("email"); bindViews(); } private void bindViews() { btnResend = (Button) findViewById(R.id.btn_resend); TextView txtTitle = (TextView) findViewById(R.id.txt_title); TextView txtSubtitle = (TextView) findViewById(R.id.txt_subtitle); txtTitle.setTypeface(Fonts.getTypeface(this, Fonts.ROBOTO_BOLD)); txtSubtitle.setTypeface(Fonts.getTypeface(this, Fonts.ROBOTO_LIGHT)); btnResend.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_resend: if (NetworkUtil.getConnectivityStatus(this) != 0) SignMeAPI.resendEmail(email, new ResendEmailHandler() { @Override public void onSuccess(ResendEmailResponse response) { Intent intent = new Intent( EmailAlreadySentActivity.this, LoginActivity.class); startActivity(intent); finish(); } @Override public void onError(VolleyError error) { try { String json = new String( error.networkResponse.data, HttpHeaderParser .parseCharset(error.networkResponse.headers)); ErrorResponse errorObject = new Gson().fromJson( json, ErrorResponse.class); int stringResource = getResources().getIdentifier( "error_" + Integer.toString(errorObject .getStatus()), "string", getPackageName()); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); break; } } }
mit