repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
cthiemann/SPaTo_Visual_Explorer | lib/src/core/src/processing/core/PConstants.java | 15928 | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-08 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
import java.awt.Cursor;
import java.awt.event.KeyEvent;
/**
* Numbers shared throughout processing.core.
* <P>
* An attempt is made to keep the constants as short/non-verbose
* as possible. For instance, the constant is TIFF instead of
* FILE_TYPE_TIFF. We'll do this as long as we can get away with it.
*
* @usage Web & Application
*/
public interface PConstants {
static public final int X = 0; // model coords xyz (formerly MX/MY/MZ)
static public final int Y = 1;
static public final int Z = 2;
static public final int R = 3; // actual rgb, after lighting
static public final int G = 4; // fill stored here, transform in place
static public final int B = 5; // TODO don't do that anymore (?)
static public final int A = 6;
static public final int U = 7; // texture
static public final int V = 8;
static public final int NX = 9; // normal
static public final int NY = 10;
static public final int NZ = 11;
static public final int EDGE = 12;
// stroke
/** stroke argb values */
static public final int SR = 13;
static public final int SG = 14;
static public final int SB = 15;
static public final int SA = 16;
/** stroke weight */
static public final int SW = 17;
// transformations (2D and 3D)
static public final int TX = 18; // transformed xyzw
static public final int TY = 19;
static public final int TZ = 20;
static public final int VX = 21; // view space coords
static public final int VY = 22;
static public final int VZ = 23;
static public final int VW = 24;
// material properties
// Ambient color (usually to be kept the same as diffuse)
// fill(_) sets both ambient and diffuse.
static public final int AR = 25;
static public final int AG = 26;
static public final int AB = 27;
// Diffuse is shared with fill.
static public final int DR = 3; // TODO needs to not be shared, this is a material property
static public final int DG = 4;
static public final int DB = 5;
static public final int DA = 6;
// specular (by default kept white)
static public final int SPR = 28;
static public final int SPG = 29;
static public final int SPB = 30;
static public final int SHINE = 31;
// emissive (by default kept black)
static public final int ER = 32;
static public final int EG = 33;
static public final int EB = 34;
// has this vertex been lit yet
static public final int BEEN_LIT = 35;
static public final int VERTEX_FIELD_COUNT = 36;
// renderers known to processing.core
static final String P2D = "processing.core.PGraphics2D";
static final String P3D = "processing.core.PGraphics3D";
static final String JAVA2D = "processing.core.PGraphicsJava2D";
static final String OPENGL = "processing.opengl.PGraphicsOpenGL";
static final String PDF = "processing.pdf.PGraphicsPDF";
static final String DXF = "processing.dxf.RawDXF";
// platform IDs for PApplet.platform
static final int OTHER = 0;
static final int WINDOWS = 1;
static final int MACOSX = 2;
static final int LINUX = 3;
static final String[] platformNames = {
"other", "windows", "macosx", "linux"
};
static final float EPSILON = 0.0001f;
// max/min values for numbers
/**
* Same as Float.MAX_VALUE, but included for parity with MIN_VALUE,
* and to avoid teaching static methods on the first day.
*/
static final float MAX_FLOAT = Float.MAX_VALUE;
/**
* Note that Float.MIN_VALUE is the smallest <EM>positive</EM> value
* for a floating point number, not actually the minimum (negative) value
* for a float. This constant equals 0xFF7FFFFF, the smallest (farthest
* negative) value a float can have before it hits NaN.
*/
static final float MIN_FLOAT = -Float.MAX_VALUE;
/** Largest possible (positive) integer value */
static final int MAX_INT = Integer.MAX_VALUE;
/** Smallest possible (negative) integer value */
static final int MIN_INT = Integer.MIN_VALUE;
// useful goodness
/**
* PI is a mathematical constant with the value 3.14159265358979323846.
* It is the ratio of the circumference of a circle to its diameter.
* It is useful in combination with the trigonometric functions <b>sin()</b> and <b>cos()</b>.
*
* @webref constants
* @see processing.core.PConstants#HALF_PI
* @see processing.core.PConstants#TWO_PI
* @see processing.core.PConstants#QUARTER_PI
*
*/
static final float PI = (float) Math.PI;
/**
* HALF_PI is a mathematical constant with the value 1.57079632679489661923.
* It is half the ratio of the circumference of a circle to its diameter.
* It is useful in combination with the trigonometric functions <b>sin()</b> and <b>cos()</b>.
*
* @webref constants
* @see processing.core.PConstants#PI
* @see processing.core.PConstants#TWO_PI
* @see processing.core.PConstants#QUARTER_PI
*/
static final float HALF_PI = PI / 2.0f;
static final float THIRD_PI = PI / 3.0f;
/**
* QUARTER_PI is a mathematical constant with the value 0.7853982.
* It is one quarter the ratio of the circumference of a circle to its diameter.
* It is useful in combination with the trigonometric functions <b>sin()</b> and <b>cos()</b>.
*
* @webref constants
* @see processing.core.PConstants#PI
* @see processing.core.PConstants#TWO_PI
* @see processing.core.PConstants#HALF_PI
*/
static final float QUARTER_PI = PI / 4.0f;
/**
* TWO_PI is a mathematical constant with the value 6.28318530717958647693.
* It is twice the ratio of the circumference of a circle to its diameter.
* It is useful in combination with the trigonometric functions <b>sin()</b> and <b>cos()</b>.
*
* @webref constants
* @see processing.core.PConstants#PI
* @see processing.core.PConstants#HALF_PI
* @see processing.core.PConstants#QUARTER_PI
*/
static final float TWO_PI = PI * 2.0f;
static final float DEG_TO_RAD = PI/180.0f;
static final float RAD_TO_DEG = 180.0f/PI;
// angle modes
//static final int RADIANS = 0;
//static final int DEGREES = 1;
// used by split, all the standard whitespace chars
// (also includes unicode nbsp, that little bostage)
static final String WHITESPACE = " \t\n\r\f\u00A0";
// for colors and/or images
static final int RGB = 1; // image & color
static final int ARGB = 2; // image
static final int HSB = 3; // color
static final int ALPHA = 4; // image
static final int CMYK = 5; // image & color (someday)
// image file types
static final int TIFF = 0;
static final int TARGA = 1;
static final int JPEG = 2;
static final int GIF = 3;
// filter/convert types
static final int BLUR = 11;
static final int GRAY = 12;
static final int INVERT = 13;
static final int OPAQUE = 14;
static final int POSTERIZE = 15;
static final int THRESHOLD = 16;
static final int ERODE = 17;
static final int DILATE = 18;
// blend mode keyword definitions
// @see processing.core.PImage#blendColor(int,int,int)
public final static int REPLACE = 0;
public final static int BLEND = 1 << 0;
public final static int ADD = 1 << 1;
public final static int SUBTRACT = 1 << 2;
public final static int LIGHTEST = 1 << 3;
public final static int DARKEST = 1 << 4;
public final static int DIFFERENCE = 1 << 5;
public final static int EXCLUSION = 1 << 6;
public final static int MULTIPLY = 1 << 7;
public final static int SCREEN = 1 << 8;
public final static int OVERLAY = 1 << 9;
public final static int HARD_LIGHT = 1 << 10;
public final static int SOFT_LIGHT = 1 << 11;
public final static int DODGE = 1 << 12;
public final static int BURN = 1 << 13;
// colour component bitmasks
public static final int ALPHA_MASK = 0xff000000;
public static final int RED_MASK = 0x00ff0000;
public static final int GREEN_MASK = 0x0000ff00;
public static final int BLUE_MASK = 0x000000ff;
// for messages
static final int CHATTER = 0;
static final int COMPLAINT = 1;
static final int PROBLEM = 2;
// types of projection matrices
static final int CUSTOM = 0; // user-specified fanciness
static final int ORTHOGRAPHIC = 2; // 2D isometric projection
static final int PERSPECTIVE = 3; // perspective matrix
// shapes
// the low four bits set the variety,
// higher bits set the specific shape type
//static final int GROUP = (1 << 2);
static final int POINT = 2; // shared with light (!)
static final int POINTS = 2;
static final int LINE = 4;
static final int LINES = 4;
static final int TRIANGLE = 8;
static final int TRIANGLES = 9;
static final int TRIANGLE_STRIP = 10;
static final int TRIANGLE_FAN = 11;
static final int QUAD = 16;
static final int QUADS = 16;
static final int QUAD_STRIP = 17;
static final int POLYGON = 20;
static final int PATH = 21;
static final int RECT = 30;
static final int ELLIPSE = 31;
static final int ARC = 32;
static final int SPHERE = 40;
static final int BOX = 41;
// shape closing modes
static final int OPEN = 1;
static final int CLOSE = 2;
// shape drawing modes
/** Draw mode convention to use (x, y) to (width, height) */
static final int CORNER = 0;
/** Draw mode convention to use (x1, y1) to (x2, y2) coordinates */
static final int CORNERS = 1;
/** Draw mode from the center, and using the radius */
static final int RADIUS = 2;
/** @deprecated Use RADIUS instead. */
static final int CENTER_RADIUS = 2;
/**
* Draw from the center, using second pair of values as the diameter.
* Formerly called CENTER_DIAMETER in alpha releases.
*/
static final int CENTER = 3;
/**
* Synonym for the CENTER constant. Draw from the center,
* using second pair of values as the diameter.
*/
static final int DIAMETER = 3;
/** @deprecated Use DIAMETER instead. */
static final int CENTER_DIAMETER = 3;
// vertically alignment modes for text
/** Default vertical alignment for text placement */
static final int BASELINE = 0;
/** Align text to the top */
static final int TOP = 101;
/** Align text from the bottom, using the baseline. */
static final int BOTTOM = 102;
// uv texture orientation modes
/** texture coordinates in 0..1 range */
static final int NORMAL = 1;
/** @deprecated use NORMAL instead */
static final int NORMALIZED = 1;
/** texture coordinates based on image width/height */
static final int IMAGE = 2;
// text placement modes
/**
* textMode(MODEL) is the default, meaning that characters
* will be affected by transformations like any other shapes.
* <p/>
* Changed value in 0093 to not interfere with LEFT, CENTER, and RIGHT.
*/
static final int MODEL = 4;
/**
* textMode(SHAPE) draws text using the the glyph outlines of
* individual characters rather than as textures. If the outlines are
* not available, then textMode(SHAPE) will be ignored and textMode(MODEL)
* will be used instead. For this reason, be sure to call textMode()
* <EM>after</EM> calling textFont().
* <p/>
* Currently, textMode(SHAPE) is only supported by OPENGL mode.
* It also requires Java 1.2 or higher (OPENGL requires 1.4 anyway)
*/
static final int SHAPE = 5;
// text alignment modes
// are inherited from LEFT, CENTER, RIGHT
// stroke modes
static final int SQUARE = 1 << 0; // called 'butt' in the svg spec
static final int ROUND = 1 << 1;
static final int PROJECT = 1 << 2; // called 'square' in the svg spec
static final int MITER = 1 << 3;
static final int BEVEL = 1 << 5;
// lighting
static final int AMBIENT = 0;
static final int DIRECTIONAL = 1;
//static final int POINT = 2; // shared with shape feature
static final int SPOT = 3;
// key constants
// only including the most-used of these guys
// if people need more esoteric keys, they can learn about
// the esoteric java KeyEvent api and of virtual keys
// both key and keyCode will equal these values
// for 0125, these were changed to 'char' values, because they
// can be upgraded to ints automatically by Java, but having them
// as ints prevented split(blah, TAB) from working
static final char BACKSPACE = 8;
static final char TAB = 9;
static final char ENTER = 10;
static final char RETURN = 13;
static final char ESC = 27;
static final char DELETE = 127;
// i.e. if ((key == CODED) && (keyCode == UP))
static final int CODED = 0xffff;
// key will be CODED and keyCode will be this value
static final int UP = KeyEvent.VK_UP;
static final int DOWN = KeyEvent.VK_DOWN;
static final int LEFT = KeyEvent.VK_LEFT;
static final int RIGHT = KeyEvent.VK_RIGHT;
// key will be CODED and keyCode will be this value
static final int ALT = KeyEvent.VK_ALT;
static final int CONTROL = KeyEvent.VK_CONTROL;
static final int SHIFT = KeyEvent.VK_SHIFT;
// cursor types
static final int ARROW = Cursor.DEFAULT_CURSOR;
static final int CROSS = Cursor.CROSSHAIR_CURSOR;
static final int HAND = Cursor.HAND_CURSOR;
static final int MOVE = Cursor.MOVE_CURSOR;
static final int TEXT = Cursor.TEXT_CURSOR;
static final int WAIT = Cursor.WAIT_CURSOR;
// hints - hint values are positive for the alternate version,
// negative of the same value returns to the normal/default state
static final int DISABLE_OPENGL_2X_SMOOTH = 1;
static final int ENABLE_OPENGL_2X_SMOOTH = -1;
static final int ENABLE_OPENGL_4X_SMOOTH = 2;
static final int ENABLE_NATIVE_FONTS = 3;
static final int DISABLE_DEPTH_TEST = 4;
static final int ENABLE_DEPTH_TEST = -4;
static final int ENABLE_DEPTH_SORT = 5;
static final int DISABLE_DEPTH_SORT = -5;
static final int DISABLE_OPENGL_ERROR_REPORT = 6;
static final int ENABLE_OPENGL_ERROR_REPORT = -6;
static final int ENABLE_ACCURATE_TEXTURES = 7;
static final int DISABLE_ACCURATE_TEXTURES = -7;
static final int HINT_COUNT = 10;
// error messages
static final String ERROR_BACKGROUND_IMAGE_SIZE =
"background image must be the same size as your application";
static final String ERROR_BACKGROUND_IMAGE_FORMAT =
"background images should be RGB or ARGB";
static final String ERROR_TEXTFONT_NULL_PFONT =
"A null PFont was passed to textFont()";
static final String ERROR_PUSHMATRIX_OVERFLOW =
"Too many calls to pushMatrix().";
static final String ERROR_PUSHMATRIX_UNDERFLOW =
"Too many calls to popMatrix(), and not enough to pushMatrix().";
}
| gpl-3.0 |
kerwinxu/barcodeManager | zxing/core/src/com/google/zxing/oned/rss/expanded/decoders/DecodedObject.java | 1292 | /*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* These authors would like to acknowledge the Spanish Ministry of Industry,
* Tourism and Trade, for the support in the project TSI020301-2008-2
* "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled
* Mobile Dynamic Environments", led by Treelogic
* ( http://www.treelogic.com/ ):
*
* http://www.piramidepse.com/
*/
package com.google.zxing.oned.rss.expanded.decoders;
/**
* @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es)
*/
abstract class DecodedObject {
private final int newPosition;
DecodedObject(int newPosition){
this.newPosition = newPosition;
}
final int getNewPosition() {
return this.newPosition;
}
}
| bsd-2-clause |
suzukaze/butterknife | butterknife/src/main/java/butterknife/ImmutableList.java | 680 | package butterknife;
import java.util.AbstractList;
import java.util.RandomAccess;
/**
* An immutable list of views which is lighter than {@code
* Collections.unmodifiableList(new ArrayList<>(Arrays.asList(foo, bar)))}.
*/
final class ImmutableList<T> extends AbstractList<T> implements RandomAccess {
private final T[] views;
ImmutableList(T[] views) {
this.views = views;
}
@Override public T get(int index) {
return views[index];
}
@Override public int size() {
return views.length;
}
@Override public boolean contains(Object o) {
for (T view : views) {
if (view == o) {
return true;
}
}
return false;
}
}
| apache-2.0 |
Rygbee/elasticsearch | core/src/test/java/org/elasticsearch/index/fielddata/DuelFieldDataTests.java | 32762 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.fielddata;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import com.carrotsearch.randomizedtesting.generators.RandomStrings;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.CompositeReaderContext;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.RandomAccessOrds;
import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.English;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.unit.DistanceUnit.Distance;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import static org.hamcrest.Matchers.*;
public class DuelFieldDataTests extends AbstractFieldDataTestCase {
@Override
protected FieldDataType getFieldDataType() {
return null;
}
@Test
public void testDuelAllTypesSingleValue() throws Exception {
final String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("bytes").field("type", "string").field("index", "not_analyzed").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("byte").field("type", "byte").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("short").field("type", "short").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("integer").field("type", "integer").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("long").field("type", "long").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("float").field("type", "float").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("double").field("type", "double").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.endObject().endObject().endObject().string();
final DocumentMapper mapper = mapperService.documentMapperParser().parse(mapping);
Random random = getRandom();
int atLeast = scaledRandomIntBetween(200, 1500);
for (int i = 0; i < atLeast; i++) {
String s = Integer.toString(randomByte());
XContentBuilder doc = XContentFactory.jsonBuilder().startObject();
for (String fieldName : Arrays.asList("bytes", "byte", "short", "integer", "long", "float", "double")) {
doc = doc.field(fieldName, s);
}
doc = doc.endObject();
final ParsedDocument d = mapper.parse("test", "type", Integer.toString(i), doc.bytes());
writer.addDocument(d.rootDoc());
if (random.nextInt(10) == 0) {
refreshReader();
}
}
LeafReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<>();
typeMap.put(new FieldDataType("string", Settings.builder().put("format", "paged_bytes")), Type.Bytes);
typeMap.put(new FieldDataType("byte", Settings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("short", Settings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("int", Settings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("long", Settings.builder().put("format", "array")), Type.Long);
typeMap.put(new FieldDataType("double", Settings.builder().put("format", "array")), Type.Double);
typeMap.put(new FieldDataType("float", Settings.builder().put("format", "array")), Type.Float);
typeMap.put(new FieldDataType("byte", Settings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("short", Settings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("int", Settings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("long", Settings.builder().put("format", "doc_values")), Type.Long);
typeMap.put(new FieldDataType("double", Settings.builder().put("format", "doc_values")), Type.Double);
typeMap.put(new FieldDataType("float", Settings.builder().put("format", "doc_values")), Type.Float);
typeMap.put(new FieldDataType("string", Settings.builder().put("format", "doc_values")), Type.Bytes);
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<>(typeMap.entrySet());
Preprocessor pre = new ToDoublePreprocessor();
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexFieldData<?> leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexFieldData<?> rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
duelFieldDataBytes(random, context, leftFieldData, rightFieldData, pre);
duelFieldDataBytes(random, context, rightFieldData, leftFieldData, pre);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<LeafReaderContext> leaves = composite.leaves();
for (LeafReaderContext atomicReaderContext : leaves) {
duelFieldDataBytes(random, atomicReaderContext, leftFieldData, rightFieldData, pre);
}
}
}
@Test
public void testDuelIntegers() throws Exception {
final String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("byte").field("type", "byte").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("short").field("type", "short").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("integer").field("type", "integer").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("long").field("type", "long").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.endObject().endObject().endObject().string();
final DocumentMapper mapper = mapperService.documentMapperParser().parse(mapping);
Random random = getRandom();
int atLeast = scaledRandomIntBetween(200, 1500);
final int maxNumValues = randomBoolean() ? 1 : randomIntBetween(2, 10);
byte[] values = new byte[maxNumValues];
for (int i = 0; i < atLeast; i++) {
int numValues = randomInt(maxNumValues);
// FD loses values if they are duplicated, so we must deduplicate for this test
Set<Byte> vals = new HashSet<Byte>();
for (int j = 0; j < numValues; ++j) {
vals.add(randomByte());
}
numValues = vals.size();
int upto = 0;
for (Byte bb : vals) {
values[upto++] = bb.byteValue();
}
XContentBuilder doc = XContentFactory.jsonBuilder().startObject();
for (String fieldName : Arrays.asList("byte", "short", "integer", "long")) {
doc = doc.startArray(fieldName);
for (int j = 0; j < numValues; ++j) {
doc = doc.value(values[j]);
}
doc = doc.endArray();
}
doc = doc.endObject();
final ParsedDocument d = mapper.parse("test", "type", Integer.toString(i), doc.bytes());
writer.addDocument(d.rootDoc());
if (random.nextInt(10) == 0) {
refreshReader();
}
}
LeafReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<>();
typeMap.put(new FieldDataType("byte", Settings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("short", Settings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("int", Settings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("long", Settings.builder().put("format", "array")), Type.Long);
typeMap.put(new FieldDataType("byte", Settings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("short", Settings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("int", Settings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("long", Settings.builder().put("format", "doc_values")), Type.Long);
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<>(typeMap.entrySet());
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexNumericFieldData leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexNumericFieldData rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
duelFieldDataLong(random, context, leftFieldData, rightFieldData);
duelFieldDataLong(random, context, rightFieldData, leftFieldData);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<LeafReaderContext> leaves = composite.leaves();
for (LeafReaderContext atomicReaderContext : leaves) {
duelFieldDataLong(random, atomicReaderContext, leftFieldData, rightFieldData);
}
}
}
@Test
public void testDuelDoubles() throws Exception {
final String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("float").field("type", "float").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("double").field("type", "double").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.endObject().endObject().endObject().string();
final DocumentMapper mapper = mapperService.documentMapperParser().parse(mapping);
Random random = getRandom();
int atLeast = scaledRandomIntBetween(200, 1500);
final int maxNumValues = randomBoolean() ? 1 : randomIntBetween(2, 10);
float[] values = new float[maxNumValues];
for (int i = 0; i < atLeast; i++) {
int numValues = randomInt(maxNumValues);
float def = randomBoolean() ? randomFloat() : Float.NaN;
// FD loses values if they are duplicated, so we must deduplicate for this test
Set<Float> vals = new HashSet<Float>();
for (int j = 0; j < numValues; ++j) {
if (randomBoolean()) {
vals.add(def);
} else {
vals.add(randomFloat());
}
}
numValues = vals.size();
int upto = 0;
for (Float f : vals) {
values[upto++] = f.floatValue();
}
XContentBuilder doc = XContentFactory.jsonBuilder().startObject().startArray("float");
for (int j = 0; j < numValues; ++j) {
doc = doc.value(values[j]);
}
doc = doc.endArray().startArray("double");
for (int j = 0; j < numValues; ++j) {
doc = doc.value(values[j]);
}
doc = doc.endArray().endObject();
final ParsedDocument d = mapper.parse("test", "type", Integer.toString(i), doc.bytes());
writer.addDocument(d.rootDoc());
if (random.nextInt(10) == 0) {
refreshReader();
}
}
LeafReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<>();
typeMap.put(new FieldDataType("double", Settings.builder().put("format", "array")), Type.Double);
typeMap.put(new FieldDataType("float", Settings.builder().put("format", "array")), Type.Float);
typeMap.put(new FieldDataType("double", Settings.builder().put("format", "doc_values")), Type.Double);
typeMap.put(new FieldDataType("float", Settings.builder().put("format", "doc_values")), Type.Float);
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<>(typeMap.entrySet());
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexNumericFieldData leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexNumericFieldData rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
duelFieldDataDouble(random, context, leftFieldData, rightFieldData);
duelFieldDataDouble(random, context, rightFieldData, leftFieldData);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<LeafReaderContext> leaves = composite.leaves();
for (LeafReaderContext atomicReaderContext : leaves) {
duelFieldDataDouble(random, atomicReaderContext, leftFieldData, rightFieldData);
}
}
}
@Test
public void testDuelStrings() throws Exception {
Random random = getRandom();
int atLeast = scaledRandomIntBetween(200, 1500);
for (int i = 0; i < atLeast; i++) {
Document d = new Document();
d.add(new StringField("_id", "" + i, Field.Store.NO));
if (random.nextInt(15) != 0) {
int[] numbers = getNumbers(random, Integer.MAX_VALUE);
for (int j : numbers) {
final String s = English.longToEnglish(j);
d.add(new StringField("bytes", s, Field.Store.NO));
d.add(new SortedSetDocValuesField("bytes", new BytesRef(s)));
}
if (random.nextInt(10) == 0) {
d.add(new StringField("bytes", "", Field.Store.NO));
d.add(new SortedSetDocValuesField("bytes", new BytesRef()));
}
}
writer.addDocument(d);
if (random.nextInt(10) == 0) {
refreshReader();
}
}
LeafReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<>();
typeMap.put(new FieldDataType("string", Settings.builder().put("format", "paged_bytes")), Type.Bytes);
typeMap.put(new FieldDataType("string", Settings.builder().put("format", "doc_values")), Type.Bytes);
// TODO add filters
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<>(typeMap.entrySet());
Preprocessor pre = new Preprocessor();
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexFieldData<?> leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexFieldData<?> rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
duelFieldDataBytes(random, context, leftFieldData, rightFieldData, pre);
duelFieldDataBytes(random, context, rightFieldData, leftFieldData, pre);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<LeafReaderContext> leaves = composite.leaves();
for (LeafReaderContext atomicReaderContext : leaves) {
duelFieldDataBytes(random, atomicReaderContext, leftFieldData, rightFieldData, pre);
}
perSegment.close();
}
}
public void testDuelGlobalOrdinals() throws Exception {
Random random = getRandom();
final int numDocs = scaledRandomIntBetween(10, 1000);
final int numValues = scaledRandomIntBetween(10, 500);
final String[] values = new String[numValues];
for (int i = 0; i < numValues; ++i) {
values[i] = new String(RandomStrings.randomAsciiOfLength(random, 10));
}
for (int i = 0; i < numDocs; i++) {
Document d = new Document();
final int numVals = randomInt(3);
for (int j = 0; j < numVals; ++j) {
final String value = RandomPicks.randomFrom(random, Arrays.asList(values));
d.add(new StringField("string", value, Field.Store.NO));
d.add(new SortedSetDocValuesField("bytes", new BytesRef(value)));
}
writer.addDocument(d);
if (randomInt(10) == 0) {
refreshReader();
}
}
refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<FieldDataType, DuelFieldDataTests.Type>();
typeMap.put(new FieldDataType("string", Settings.builder().put("format", "paged_bytes")), Type.Bytes);
typeMap.put(new FieldDataType("string", Settings.builder().put("format", "doc_values")), Type.Bytes);
for (Map.Entry<FieldDataType, Type> entry : typeMap.entrySet()) {
ifdService.clear();
IndexOrdinalsFieldData fieldData = getForField(entry.getKey(), entry.getValue().name().toLowerCase(Locale.ROOT));
RandomAccessOrds left = fieldData.load(readerContext).getOrdinalsValues();
fieldData.clear();
RandomAccessOrds right = fieldData.loadGlobal(topLevelReader).load(topLevelReader.leaves().get(0)).getOrdinalsValues();
assertEquals(left.getValueCount(), right.getValueCount());
for (long ord = 0; ord < left.getValueCount(); ++ord) {
assertEquals(left.lookupOrd(ord), right.lookupOrd(ord));
}
}
}
public void testDuelGeoPoints() throws Exception {
final String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("geopoint").field("type", "geo_point").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.endObject().endObject().endObject().string();
final DocumentMapper mapper = mapperService.documentMapperParser().parse(mapping);
Random random = getRandom();
int atLeast = scaledRandomIntBetween(200, 1500);
int maxValuesPerDoc = randomBoolean() ? 1 : randomIntBetween(2, 10);
// to test deduplication
double defaultLat = randomDouble() * 180 - 90;
double defaultLon = randomDouble() * 360 - 180;
for (int i = 0; i < atLeast; i++) {
final int numValues = randomInt(maxValuesPerDoc);
XContentBuilder doc = XContentFactory.jsonBuilder().startObject().startArray("geopoint");
for (int j = 0; j < numValues; ++j) {
if (randomBoolean()) {
doc.startObject().field("lat", defaultLat).field("lon", defaultLon).endObject();
} else {
doc.startObject().field("lat", randomDouble() * 180 - 90).field("lon", randomDouble() * 360 - 180).endObject();
}
}
doc = doc.endArray().endObject();
final ParsedDocument d = mapper.parse("test", "type", Integer.toString(i), doc.bytes());
writer.addDocument(d.rootDoc());
if (random.nextInt(10) == 0) {
refreshReader();
}
}
LeafReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<>();
final Distance precision = new Distance(1, randomFrom(DistanceUnit.values()));
typeMap.put(new FieldDataType("geo_point", Settings.builder().put("format", "array")), Type.GeoPoint);
typeMap.put(new FieldDataType("geo_point", Settings.builder().put("format", "doc_values")), Type.GeoPoint);
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<>(typeMap.entrySet());
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexGeoPointFieldData leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexGeoPointFieldData rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
duelFieldDataGeoPoint(random, context, leftFieldData, rightFieldData, precision);
duelFieldDataGeoPoint(random, context, rightFieldData, leftFieldData, precision);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<LeafReaderContext> leaves = composite.leaves();
for (LeafReaderContext atomicReaderContext : leaves) {
duelFieldDataGeoPoint(random, atomicReaderContext, leftFieldData, rightFieldData, precision);
}
perSegment.close();
}
}
@Override
public void testEmpty() throws Exception {
// No need to test empty usage here
}
private int[] getNumbers(Random random, int margin) {
if (random.nextInt(20) == 0) {
int[] num = new int[1 + random.nextInt(10)];
for (int i = 0; i < num.length; i++) {
int v = (random.nextBoolean() ? -1 * random.nextInt(margin) : random.nextInt(margin));
num[i] = v;
}
return num;
}
return new int[]{(random.nextBoolean() ? -1 * random.nextInt(margin) : random.nextInt(margin))};
}
private static void duelFieldDataBytes(Random random, LeafReaderContext context, IndexFieldData<?> left, IndexFieldData<?> right, Preprocessor pre) throws Exception {
AtomicFieldData leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
AtomicFieldData rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);
int numDocs = context.reader().maxDoc();
SortedBinaryDocValues leftBytesValues = leftData.getBytesValues();
SortedBinaryDocValues rightBytesValues = rightData.getBytesValues();
BytesRefBuilder leftSpare = new BytesRefBuilder();
BytesRefBuilder rightSpare = new BytesRefBuilder();
for (int i = 0; i < numDocs; i++) {
leftBytesValues.setDocument(i);
rightBytesValues.setDocument(i);
int numValues = leftBytesValues.count();
assertThat(numValues, equalTo(rightBytesValues.count()));
BytesRef previous = null;
for (int j = 0; j < numValues; j++) {
rightSpare.copyBytes(rightBytesValues.valueAt(j));
leftSpare.copyBytes(leftBytesValues.valueAt(j));
if (previous != null) {
assertThat(pre.compare(previous, rightSpare.get()), lessThan(0));
}
previous = BytesRef.deepCopyOf(rightSpare.get());
pre.toString(rightSpare.get());
pre.toString(leftSpare.get());
assertThat(pre.toString(leftSpare.get()), equalTo(pre.toString(rightSpare.get())));
}
}
}
private static void duelFieldDataDouble(Random random, LeafReaderContext context, IndexNumericFieldData left, IndexNumericFieldData right) throws Exception {
AtomicNumericFieldData leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
AtomicNumericFieldData rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);
int numDocs = context.reader().maxDoc();
SortedNumericDoubleValues leftDoubleValues = leftData.getDoubleValues();
SortedNumericDoubleValues rightDoubleValues = rightData.getDoubleValues();
for (int i = 0; i < numDocs; i++) {
leftDoubleValues.setDocument(i);
rightDoubleValues.setDocument(i);
int numValues = leftDoubleValues.count();
assertThat(numValues, equalTo(rightDoubleValues.count()));
double previous = 0;
for (int j = 0; j < numValues; j++) {
double current = rightDoubleValues.valueAt(j);
if (Double.isNaN(current)) {
assertTrue(Double.isNaN(leftDoubleValues.valueAt(j)));
} else {
assertThat(leftDoubleValues.valueAt(j), closeTo(current, 0.0001));
}
if (j > 0) {
assertThat(Double.compare(previous,current), lessThan(0));
}
previous = current;
}
}
}
private static void duelFieldDataLong(Random random, LeafReaderContext context, IndexNumericFieldData left, IndexNumericFieldData right) throws Exception {
AtomicNumericFieldData leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
AtomicNumericFieldData rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);
int numDocs = context.reader().maxDoc();
SortedNumericDocValues leftLongValues = leftData.getLongValues();
SortedNumericDocValues rightLongValues = rightData.getLongValues();
for (int i = 0; i < numDocs; i++) {
leftLongValues.setDocument(i);
rightLongValues.setDocument(i);
int numValues = leftLongValues.count();
long previous = 0;
assertThat(numValues, equalTo(rightLongValues.count()));
for (int j = 0; j < numValues; j++) {
long current;
assertThat(leftLongValues.valueAt(j), equalTo(current = rightLongValues.valueAt(j)));
if (j > 0) {
assertThat(previous, lessThan(current));
}
previous = current;
}
}
}
private static void duelFieldDataGeoPoint(Random random, LeafReaderContext context, IndexGeoPointFieldData left, IndexGeoPointFieldData right, Distance precision) throws Exception {
AtomicGeoPointFieldData leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
AtomicGeoPointFieldData rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);
int numDocs = context.reader().maxDoc();
MultiGeoPointValues leftValues = leftData.getGeoPointValues();
MultiGeoPointValues rightValues = rightData.getGeoPointValues();
for (int i = 0; i < numDocs; ++i) {
leftValues.setDocument(i);
final int numValues = leftValues.count();
rightValues.setDocument(i);;
assertEquals(numValues, rightValues.count());
List<GeoPoint> leftPoints = new ArrayList<>();
List<GeoPoint> rightPoints = new ArrayList<>();
for (int j = 0; j < numValues; ++j) {
GeoPoint l = leftValues.valueAt(j);
leftPoints.add(new GeoPoint(l.getLat(), l.getLon()));
GeoPoint r = rightValues.valueAt(j);
rightPoints.add(new GeoPoint(r.getLat(), r.getLon()));
}
for (GeoPoint l : leftPoints) {
assertTrue("Couldn't find " + l + " among " + rightPoints, contains(l, rightPoints, precision));
}
for (GeoPoint r : rightPoints) {
assertTrue("Couldn't find " + r + " among " + leftPoints, contains(r, leftPoints, precision));
}
}
}
private static boolean contains(GeoPoint point, List<GeoPoint> set, Distance precision) {
for (GeoPoint r : set) {
final double distance = GeoDistance.PLANE.calculate(point.getLat(), point.getLon(), r.getLat(), r.getLon(), DistanceUnit.METERS);
if (new Distance(distance, DistanceUnit.METERS).compareTo(precision) <= 0) {
return true;
}
}
return false;
}
private static class Preprocessor {
public String toString(BytesRef ref) {
return ref.utf8ToString();
}
public int compare(BytesRef a, BytesRef b) {
return a.compareTo(b);
}
}
private static class ToDoublePreprocessor extends Preprocessor {
@Override
public String toString(BytesRef ref) {
assertTrue(ref.length > 0);
return Double.toString(Double.parseDouble(super.toString(ref)));
}
@Override
public int compare(BytesRef a, BytesRef b) {
Double _a = Double.parseDouble(super.toString(a));
return _a.compareTo(Double.parseDouble(super.toString(b)));
}
}
private static enum Type {
Float, Double, Integer, Long, Bytes, GeoPoint;
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/ExpandToLevel5Action.java | 786 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.folding.impl.actions;
public class ExpandToLevel5Action extends BaseExpandToLevelAction {
public ExpandToLevel5Action() {
super(5, false);
}
}
| apache-2.0 |
Lekanich/intellij-community | java/typeMigration/testData/refactoring/typeMigrationByAtomic/reverseIncrementDecrement/before/Test.java | 293 | import java.util.concurrent.atomic.AtomicInteger;
class Test {
AtomicInteger i;
void foo() {
i.getAndIncrement();
i.incrementAndGet();
i.getAndDecrement();
i.decrementAndGet();
System.out.println(i.getAndIncrement());
System.out.println(i.decrementAndGet());
}
} | apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/test/javax/accessibility/6986385/bug6986385.java | 1763 | /*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 6986385
@summary JLayer should implement accessible interface
@author Alexander Potochkin
@run main bug6986385
*/
import javax.swing.*;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;
public class bug6986385 {
public static void main(String... args) throws Exception {
JLayer l = new JLayer();
AccessibleContext acc = l.getAccessibleContext();
if (acc == null) {
throw new RuntimeException("JLayer's AccessibleContext is null");
}
if (acc.getAccessibleRole() != AccessibleRole.PANEL) {
throw new RuntimeException("JLayer's AccessibleRole must be PANEL");
}
}
}
| mit |
alsmadi/CSCI-6617 | src/main/java/org/openflow/protocol/factory/OFActionFactoryAware.java | 1078 | /**
* Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior
* University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package org.openflow.protocol.factory;
/**
* Objects implementing this interface are expected to be instantiated with an
* instance of an OFActionFactory
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public interface OFActionFactoryAware {
/**
* Sets the OFActionFactory
* @param actionFactory
*/
public void setActionFactory(OFActionFactory actionFactory);
}
| apache-2.0 |
asedunov/intellij-community | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/InferenceWithBoxingCovariant.java | 333 | import java.util.*;
class Test {
static class Pair<A, B> {
Pair(A a, B b) {
}
static <A, B> Pair<A, B> create(A a, B b) {
return new Pair<A, B>(a, b);
}
}
public static void getWordsWithOffset(String s, int startInd, final List<Pair<String, Integer>> res) {
res.add(Pair.create(s, startInd));
}
} | apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/test/java/math/BigInteger/UnicodeConstructor.java | 1879 | /*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4040456
* @summary Test biginteger constructor with i18n string
*/
import java.math.*;
/**
* This class tests to see if creating a biginteger with an
* unicode japanese zero and one succeeds
*
*/
public class UnicodeConstructor {
public static void main(String args[]) {
try {
// the code for japanese zero
BigInteger b1 = new BigInteger("\uff10");
System.err.println(b1.toString());
// Japanese 1010
BigInteger b2 = new BigInteger("\uff11\uff10\uff11\uff10");
System.err.println(b2.toString());
}
catch (ArrayIndexOutOfBoundsException e) {
throw new RuntimeException(
"BigInteger is not accepting unicode initializers.");
}
}
}
| mit |
gndpig/hadoop | src/core/org/apache/hadoop/io/compress/CompressionOutputStream.java | 1993 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.io.compress;
import java.io.IOException;
import java.io.OutputStream;
/**
* A compression output stream.
*/
public abstract class CompressionOutputStream extends OutputStream {
/**
* The output stream to be compressed.
*/
protected final OutputStream out;
/**
* Create a compression output stream that writes
* the compressed bytes to the given stream.
* @param out
*/
protected CompressionOutputStream(OutputStream out) {
this.out = out;
}
public void close() throws IOException {
finish();
out.close();
}
public void flush() throws IOException {
out.flush();
}
/**
* Write compressed bytes to the stream.
* Made abstract to prevent leakage to underlying stream.
*/
public abstract void write(byte[] b, int off, int len) throws IOException;
/**
* Finishes writing compressed data to the output stream
* without closing the underlying stream.
*/
public abstract void finish() throws IOException;
/**
* Reset the compression to the initial state.
* Does not reset the underlying stream.
*/
public abstract void resetState() throws IOException;
}
| apache-2.0 |
lindzh/jenkins | core/src/main/java/hudson/model/Saveable.java | 2024 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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 hudson.model;
import hudson.BulkChange;
import hudson.model.listeners.SaveableListener;
import java.io.IOException;
/**
* Object whose state is persisted to XML.
*
* @author Kohsuke Kawaguchi
* @see BulkChange
* @since 1.249
*/
public interface Saveable {
/**
* Persists the state of this object into XML.
*
* <p>
* For making a bulk change efficiently, see {@link BulkChange}.
*
* <p>
* To support listeners monitoring changes to this object, call {@link SaveableListener#fireOnChange}
* @throws IOException
* if the persistence failed.
*/
void save() throws IOException;
/**
* {@link Saveable} that doesn't save anything.
* @since 1.301.
*/
Saveable NOOP = new Saveable() {
public void save() throws IOException {
}
};
}
| mit |
coderczp/camel | components/camel-dns/src/main/java/org/apache/camel/component/dns/DnsLookupProducer.java | 2412 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.dns;
import org.apache.camel.CamelException;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.impl.DefaultProducer;
import org.apache.camel.util.ObjectHelper;
import org.xbill.DNS.DClass;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Type;
/**
* A producer to manage lookup operations, using the API from dnsjava.
*/
public class DnsLookupProducer extends DefaultProducer {
public DnsLookupProducer(Endpoint endpoint) {
super(endpoint);
}
@Override
public void process(Exchange exchange) throws Exception {
String dnsName = exchange.getIn().getHeader(DnsConstants.DNS_NAME, String.class);
ObjectHelper.notEmpty(dnsName, "Header " + DnsConstants.DNS_NAME);
Object type = exchange.getIn().getHeader(DnsConstants.DNS_TYPE);
Integer dnsType = null;
if (type != null) {
dnsType = Type.value(String.valueOf(type));
}
Object dclass = exchange.getIn().getHeader(DnsConstants.DNS_CLASS);
Integer dnsClass = null;
if (dclass != null) {
dnsClass = DClass.value(String.valueOf(dclass));
}
Lookup lookup = (dnsClass == null)
? (dnsType == null ? new Lookup(dnsName) : new Lookup(dnsName, dnsType))
: new Lookup(dnsName, dnsType, dnsClass);
lookup.run();
if (lookup.getAnswers() != null) {
exchange.getIn().setBody(lookup.getAnswers());
} else {
throw new CamelException(lookup.getErrorString());
}
}
}
| apache-2.0 |
prayuditb/tryout-01 | websocket/client/Client/node_modules/react-native/ReactAndroid/src/main/java/com/facebook/react/animation/Animation.java | 3540 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.animation;
import javax.annotation.Nullable;
import android.view.View;
import com.facebook.infer.annotation.Assertions;
/**
* Base class for various catalyst animation engines. Subclasses of this class should implement
* {@link #run} method which should bootstrap the animation. Then in each animation frame we expect
* animation engine to call {@link #onUpdate} with a float progress which then will be transferred
* to the underlying {@link AnimationPropertyUpdater} instance.
*
* Animation engine should support animation cancelling by monitoring the returned value of
* {@link #onUpdate}. In case of returning false, animation should be considered cancelled and
* engine should not attempt to call {@link #onUpdate} again.
*/
public abstract class Animation {
private final int mAnimationID;
private final AnimationPropertyUpdater mPropertyUpdater;
private volatile boolean mCancelled = false;
private volatile boolean mIsFinished = false;
private @Nullable AnimationListener mAnimationListener;
private @Nullable View mAnimatedView;
public Animation(int animationID, AnimationPropertyUpdater propertyUpdater) {
mAnimationID = animationID;
mPropertyUpdater = propertyUpdater;
}
public void setAnimationListener(AnimationListener animationListener) {
mAnimationListener = animationListener;
}
public final void start(View view) {
mAnimatedView = view;
mPropertyUpdater.prepare(view);
run();
}
public abstract void run();
/**
* Animation engine should call this method for every animation frame passing animation progress
* value as a parameter. Animation progress should be within the range 0..1 (the exception here
* would be a spring animation engine which may slightly exceed start and end progress values).
*
* This method will return false if the animation has been cancelled. In that case animation
* engine should not attempt to call this method again. Otherwise this method will return true
*/
protected final boolean onUpdate(float value) {
Assertions.assertCondition(!mIsFinished, "Animation must not already be finished!");
if (!mCancelled) {
mPropertyUpdater.onUpdate(Assertions.assertNotNull(mAnimatedView), value);
}
return !mCancelled;
}
/**
* Animation engine should call this method when the animation is finished. Should be called only
* once
*/
protected final void finish() {
Assertions.assertCondition(!mIsFinished, "Animation must not already be finished!");
mIsFinished = true;
if (!mCancelled) {
if (mAnimatedView != null) {
mPropertyUpdater.onFinish(mAnimatedView);
}
if (mAnimationListener != null) {
mAnimationListener.onFinished();
}
}
}
/**
* Cancels the animation.
*
* It is possible for this to be called after finish() and should handle that gracefully.
*/
public final void cancel() {
if (mIsFinished || mCancelled) {
// If we were already finished, ignore
return;
}
mCancelled = true;
if (mAnimationListener != null) {
mAnimationListener.onCancel();
}
}
public int getAnimationID() {
return mAnimationID;
}
}
| mit |
ChiMarvine/chartreuse-triceratops | youwont/plugins/cordova-plugin-file/src/android/FileExistsException.java | 1050 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.file;
@SuppressWarnings("serial")
public class FileExistsException extends Exception {
public FileExistsException(String msg) {
super(msg);
}
}
| mit |
atomicint/aj8 | server/src/main/java/org/apollo/game/model/region/Region.java | 4167 | package org.apollo.game.model.region;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import org.apollo.game.model.Entity;
import org.apollo.game.model.Entity.EntityCategory;
import org.apollo.game.model.Position;
/**
* Represents a single region.
*
* @author Ryley Kimmel <ryley.kimmel@live.com>
*/
public final class Region {
/**
* The size of one side of the region array.
*/
public static final int SIZE = 256;
/**
* The size of a region.
*/
public static final int REGION_SIZE = 64;
/**
* The maximum level a floor can be.
*/
public static final int MAXIMUM_HEIGHT_LEVEL = 4;
/**
* The tiles within the region.
*/
private final Tile[][] tiles = new Tile[MAXIMUM_HEIGHT_LEVEL][REGION_SIZE * REGION_SIZE];
/**
* A set of entities within this region.
*/
private final Set<Entity> entities = new HashSet<>();
/**
* Constructs a new {@link Region}.
*/
protected Region() {
for (int height = 0; height < MAXIMUM_HEIGHT_LEVEL; height++) {
for (int regionId = 0; regionId < REGION_SIZE * REGION_SIZE; regionId++) {
tiles[height][regionId] = new Tile();
}
}
}
/**
* Adds an {@link Entity} to this region.
*
* @param entity The entity to add.
*/
public void addEntity(Entity entity) {
entities.add(entity);
}
/**
* Removes an {@link Entity} from this region.
*
* @param entity The entity to remove.
*/
public void removeEntity(Entity entity) {
entities.remove(entity);
}
/**
* Tests whether or not the {@link #entities} {@link Set} contains the
* specified {@link Entity}.
*
* @param entity The entity.
* @return {@code true} if and only if the entities set contains the
* specified entity otherwise {@code false}.
*/
public boolean contains(Entity entity) {
return entities.contains(entity);
}
/**
* Gets the entities within this region.
*
* @return A {@link Set} of entities in this region.
*/
@SuppressWarnings("unchecked")
public <T extends Entity> Set<T> getEntities() {
return (Set<T>) entities;
}
/**
* Gets the entities of the specified {@link EntityCategory} within this
* region.
*
* @param category The category of entity to get.
* @return A {@link Set} of entities in this region.
*/
public <T extends Entity> Set<T> getEntities(EntityCategory category) {
Set<T> entities = getEntities();
return entities.stream().filter(e -> e.getCategory() == category).collect(Collectors.toSet());
}
/**
* Gets the entities on the specified {@link Position}.
*
* @param position The position.
* @return A {@link Set} of entities on the specified position.
*/
public <T extends Entity> Set<T> getEntities(Position position) {
Set<T> entities = getEntities();
return entities.stream().filter(e -> e.getPosition().equals(position)).collect(Collectors.toSet());
}
/**
* Gets the entities on the specified {@link Position} if they meet the
* specified {@link EntityCategory}.
*
* @param position The position.
* @param category The category of the entity.
* @return A {@link Set} of entities on the specified position.
*/
public <T extends Entity> Set<T> getEntities(Position position, EntityCategory category) {
Set<T> entities = getEntities(position);
return entities.stream().filter(e -> e.getCategory() == category).collect(Collectors.toSet());
}
/**
* Gets a single tile in this region from the specified height, x and y
* coordinates.
*
* @param height The height.
* @param x The x coordinate.
* @param y The y coordinate.
* @return The tile in this region for the specified attributes.
*/
public Tile getTile(int height, int x, int y) {
return tiles[height][x + y * REGION_SIZE];
}
@Override
public int hashCode() {
int result = 31 + entities.hashCode();
result = 31 * result + Arrays.hashCode(tiles);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Region)) {
return false;
}
Region other = (Region) obj;
return entities.equals(other.entities) && !Arrays.deepEquals(tiles, other.tiles);
}
} | isc |
io7m/smf | com.io7m.smfj.format.binary2/src/main/java/com/io7m/smfj/format/binary2/internal/serial/le/WriterLESigned2_16.java | 1456 | /*
* Copyright © 2017 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.smfj.format.binary2.internal.serial.le;
import com.io7m.jbssio.api.BSSWriterSequentialType;
import com.io7m.smfj.core.SMFAttribute;
import com.io7m.smfj.format.binary2.internal.serial.WriterBase;
import java.io.IOException;
public final class WriterLESigned2_16 extends WriterBase
{
public WriterLESigned2_16(
final BSSWriterSequentialType in_writer,
final SMFAttribute in_attribute)
{
super(in_writer, in_attribute);
}
@Override
public void serializeValueIntegerSigned2(
final long x,
final long y)
throws IOException
{
super.writer().writeS16LE((int) x);
super.writer().writeS16LE((int) y);
}
}
| isc |
Giszmo/Shufflepuff | shuffler/src/main/java/com/shuffle/monad/Summable.java | 605 | /**
*
* Copyright © 2016 Mycelium.
* Use of this source code is governed by an ISC
* license that can be found in the LICENSE file.
*
*/
package com.shuffle.monad;
/**
* Created by DanielKrawisz on 3/2/16.
*/
public interface Summable<X> {
interface SummableElement<X> {
X value();
SummableElement<X> plus(SummableElement<X> x);
}
abstract class Zero<X> implements SummableElement<X> {
@Override
public SummableElement<X> plus(SummableElement<X> x) {
return x;
}
}
Zero<X> zero();
SummableElement<X> make(X x);
}
| isc |
MrZoraman/Homes | src/main/java/com/lagopusempire/homes/commands/admin/GoToOthersHomeCommand.java | 1874 | package com.lagopusempire.homes.commands.admin;
import com.lagopusempire.homes.HomeManager;
import com.lagopusempire.homes.HomesPlugin;
import com.lagopusempire.homes.commands.CommandBase;
import com.lagopusempire.homes.config.ConfigKeys;
import com.lagopusempire.homes.config.PluginConfig;
import com.lagopusempire.homes.jobs.admin.GoToOthersHomeJob;
import com.lagopusempire.homes.messages.MessageKeys;
import com.lagopusempire.homes.messages.Messages;
import com.lagopusempire.homes.permissions.Permissions;
import org.bukkit.entity.Player;
/**
*
* @author MrZoraman
*/
public class GoToOthersHomeCommand extends CommandBase
{
public GoToOthersHomeCommand(HomesPlugin plugin, HomeManager homeManager)
{
super(plugin, homeManager, Permissions.GO_HOME_OTHER);
}
@Override
protected boolean onCommand(Player player, String[] args)
{
String targetName = null;
boolean usingExplicitHome = false;
String homeName = null;
switch (args.length)
{
default:
homeName = args[1];
usingExplicitHome = true;
//FALL THROUGH
case 1:
if(homeName == null)
homeName = PluginConfig.getString(ConfigKeys.IMPLICIT_HOME_NAME);
targetName = args[0];
break;
case 0:
final String message = Messages.getMessage(MessageKeys.MUST_SPECIFY_PLAYER).colorize().toString();
player.sendMessage(message);
return true;
}
final HomeAdjustment adjustment = adjustHomeName(homeName, usingExplicitHome);
final GoToOthersHomeJob job = new GoToOthersHomeJob(plugin, homeManager, player, targetName, adjustment.homeName, adjustment.explicit);
job.run();
return true;
}
}
| isc |
Juriy/masterhack | server/src/main/java/mastercard/mcwallet/sdk/xml/switchapiservices/AuthorizePairingResponse.java | 2615 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
// 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: 2014.08.21 at 12:22:14 PM CDT
//
package mastercard.mcwallet.sdk.xml.switchapiservices;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for AuthorizePairingResponse complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="AuthorizePairingResponse">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="VerifierToken" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="ExtensionPoint" type="{}ExtensionPoint" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AuthorizePairingResponse", propOrder = {
"verifierToken",
"extensionPoint"
})
public class AuthorizePairingResponse {
@XmlElement(name = "VerifierToken", required = true)
protected String verifierToken;
@XmlElement(name = "ExtensionPoint")
protected ExtensionPoint extensionPoint;
/**
* Gets the value of the verifierToken property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVerifierToken() {
return verifierToken;
}
/**
* Sets the value of the verifierToken property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVerifierToken(String value) {
this.verifierToken = value;
}
/**
* Gets the value of the extensionPoint property.
*
* @return
* possible object is
* {@link ExtensionPoint }
*
*/
public ExtensionPoint getExtensionPoint() {
return extensionPoint;
}
/**
* Sets the value of the extensionPoint property.
*
* @param value
* allowed object is
* {@link ExtensionPoint }
*
*/
public void setExtensionPoint(ExtensionPoint value) {
this.extensionPoint = value;
}
}
| isc |
nwillc/fun-jdbc | src/test/java/com/github/nwillc/funjdbc/utils/ResultSetStreamTest.java | 1058 | /*
* Copyright (c) 2018, nwillc@gmail.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
package com.github.nwillc.funjdbc.utils;
import com.github.nwillc.contracts.UtilityClassContract;
/**
*
*/
public class ResultSetStreamTest extends UtilityClassContract {
@Override
public Class<?> getClassToTest() {
return ResultSetStream.class;
}
}
| isc |
Demannu/hackwars-classic | src/classes/Hacktendo/Viewport.java | 7856 | package Hacktendo;
/*
Porgrammer: Ben Coe.(2007)<br />
The viewport that an experiment takes place in.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import util.*;
import java.io.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.util.concurrent.Semaphore;
import GUI.Sound;
import javax.imageio.*;
import GUI.ImageLoader;
import GUI.Hacker;
import View.*;
import Assignments.*;
import java.util.*;
import GUI.*;
public class Viewport extends JComponent implements Runnable,FocusListener,MouseListener{
/////////////////////
// Data.
private int width;//Width of Viewport.
private int height;//Height of Viewport.
private String fileName="";//The name of the current game that's running.
private GraphicsConfiguration GC=null;//Parent's graphics configuration.
private BufferedImage BackBuffer=null;//The volatile back buffer.
private BufferedImage Background=null;//The Volatile Background.
private ImageHandler MyImageHandler=null;
private RenderEngine MyRenderEngine=null;
private BufferedImage image=null;
private Thread MyThread=null;
private boolean running=true;
private Time MyTime=new Time();
private long sleepTime=50;
private long startTime;
private final Semaphore available = new Semaphore(1, true);//Make it thread safe.
private Color bgColor=null;//The Background Color.
private Hacker hacker;
/**
Is the game currently running in debug mode?
*/
public void setDebug(boolean debug){
MyRenderEngine.setDebug(debug);
}
/**
Set the file name associated with the current game that's running.
*/
public void setFileName(String fileName){
this.fileName=fileName;
}
/**
Set the load file associated with this game, e.g., the saved instance of the previous game.
*/
public void setLoadFile(HashMap LoadFile){
MyRenderEngine.setLoadFile(LoadFile);
}
/**
Intialize the viewport with the given width/height background-color and graphics configuration.
*/
public Viewport(Color bgColor,GraphicsConfiguration GC,Hacker hacker){
MyImageHandler=new ImageHandler(GC);
MyRenderEngine=new RenderEngine(MyImageHandler,this,hacker);
this.hacker=hacker;
this.GC=GC;
this.width=288;
this.height=256;
this.setDoubleBuffered(false);
this.setLayout(null);//Use X,Y coordinates for layout.
//this.setOpaque(false);//Widget is transparent.
this.setSize(width*2,height*2);//Set the size of the widget.
this.setVisible(true);//Initially visible.
//this.setIgnoreRepaint(true);
this.enableInputMethods(true);
//Add Listeners.
addKeyListener(MyRenderEngine);
addMouseListener(this);
super.setFocusable(true);
this.setBorder(null);
//Set the Background Color.
if(bgColor!=null){
Background=GC.createCompatibleImage(width,height,Transparency.BITMASK);//Create the back buffer.
Graphics G=Background.getGraphics();
G.setColor(bgColor);
G.fillRect(0,0,width,height);
G.dispose();
}
//Create a fast back buffer for drawing.
//BackBuffer=new BufferedImage(width,height,BufferedImage.TYPE_BYTE_INDEXED,new IndexColorModel(8,256,ImageHandler.r,ImageHandler.g,ImageHandler.b));
BackBuffer=GC.createCompatibleImage(width,height,Transparency.BITMASK);//Create the back buffer.
width=width*2;
height=height*2;
addFocusListener(this);
}
/**
Stop the thread associated with this viewport.
*/
public void stop(){
running=false;
MyThread=null;
MyRenderEngine.cleanLevel();
MyRenderEngine.resetGlobals();
Object[] fireWatch = MyRenderEngine.getFireWatch();
MyRenderEngine.setFireWatch(null);
//Fire a watch on the game maker's computer.
if(fireWatch!=null){
//System.out.println("Sending Trigger");
String note = (String)fireWatch[0];
HashMap HM = (HashMap)fireWatch[1];
HM.put("username",hacker.getUsername());
View MyView = hacker.getView();
Object[] send = new Object[]{note,HM,hacker.getUsername(),MyRenderEngine.getIP()};
MyView.addFunctionCall(new RemoteFunctionCall(Hacker.HACKTENDO_PLAYER,"requesttrigger",send));
}
//Save to a file on the player's computer.
if(MyRenderEngine.getSaveFile()!=null&&!fileName.equals("")){
//Also save stuff to a player's local hard-drive.
View MyView = hacker.getView();
Object[] send = new Object[]{fileName,MyRenderEngine.getSaveFile(),hacker.getIP()};
MyView.addFunctionCall(new RemoteFunctionCall(Hacker.HACKTENDO_PLAYER,"requestsave",send));
MyRenderEngine.setSaveFile(null);
}
//If this game was played as part of a quest we need to tell the server it was beaten.
//System.out.println(MyRenderEngine.getTaskName()+" >> "+MyRenderEngine.getQuestID());
if(MyRenderEngine.getTaskName()!=""){
if(MyRenderEngine.getBeat()){
//Also save stuff to a player's local hard-drive.
View MyView = hacker.getView();
Object[] send = new Object[]{fileName,MyRenderEngine.getQuestID(),MyRenderEngine.getTaskName(),hacker.getIP()};
MyView.addFunctionCall(new RemoteFunctionCall(Hacker.HACKTENDO_PLAYER,"requesttask",send));
}
}
System.gc();
started=false;
}
/**
Start animating the viewport.
*/
public void start(){
running=true;
MyThread=new Thread(this);
MyThread.start();
}
public void paintComponent(Graphics g){
if(image!=null){
g.drawImage(image,0,0,width,height,null);
}else
try{
available.acquire();
g.drawImage(BackBuffer,0,0,width,height,null);
available.release();
}catch(Exception e){
available.release();
}
}
/**
Re-draw the experimental environment at a given frame-rate.
*/
private Graphics2D ComponentGraphics2D=null;
private Graphics ComponentGraphics=null;
private Graphics BackBufferGraphics=null;
private AffineTransform xform=null;
int i=0;
int totaltime=0;
public void run(){
if(image!=null){
try{
Thread.sleep(1000);
image=null;
}catch(Exception e){
}
}
while(running){
try{
available.acquire();
long startTime=MyTime.getCurrentTime();
if(BackBufferGraphics==null)
BackBufferGraphics=BackBuffer.getGraphics();
BackBufferGraphics.drawImage(Background,0,0,this);
MyRenderEngine.updateScreen(BackBufferGraphics);
available.release();
long endTime=MyTime.getCurrentTime();
if(sleepTime-(endTime-startTime)>0){
MyThread.sleep(sleepTime-(endTime-startTime));
}else{
}
}catch(Exception e){
e.printStackTrace();
}
repaint();
i++;
}
}
boolean started=false;
public synchronized void loadGame(String xml){
if(!started&&xml!=null&&xml.length()>0){
try{
//System.out.println("Loading Logi Image");
image = ImageIO.read(ImageLoader.getFile("images/logo.png"));
repaint();
start();
}catch(Exception e){e.printStackTrace();}
MyRenderEngine.loadGame(xml);
//System.out.println("Setting image to null");
started=true;
}
}
//Testing main.
public static void main(String args[]){
JFrame JF=new JFrame("Testing Suite");
JF.setSize(576,512);
Viewport AwesomeViewMax=new Viewport(Color.BLACK,JF.getGraphicsConfiguration(),null);
AwesomeViewMax.start();
JF.add(AwesomeViewMax);
JF.setVisible(true);
try{
String xml="";
BufferedReader BR=new BufferedReader(new FileReader("game.xml"));
String s;
while((s=BR.readLine())!=null)
xml+=s;
AwesomeViewMax.loadGame(xml);
}catch(Exception e){
e.printStackTrace();
}
}
public void focusLost(FocusEvent fe){
}
public void mouseExited(MouseEvent me){}
public void mouseEntered(MouseEvent me){}
public void mouseReleased(MouseEvent me){}
public void mousePressed(MouseEvent me){}
public void mouseClicked(MouseEvent me){
super.requestFocus();
super.requestFocusInWindow();
}
public void focusGained(FocusEvent fe){
super.requestFocus();
super.requestFocusInWindow();
}
}//END.
| isc |
carsonreinke/mozu-java-sdk | src/main/java/com/mozu/api/urls/commerce/catalog/storefront/ProductUrl.java | 5278 | /**
* This code was auto-generated by a tool.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.urls.commerce.catalog.storefront;
import com.mozu.api.MozuUrl;
import com.mozu.api.utils.UrlFormatter;
public class ProductUrl
{
/**
* Get Resource Url for GetProducts
* @param filter A set of expressions that consist of a field, operator, and value and represent search parameter syntax when filtering results of a query. Valid operators include equals (eq), does not equal (ne), greater than (gt), less than (lt), greater than or equal to (ge), less than or equal to (le), starts with (sw), or contains (cont). For example - "filter=IsDisplayed+eq+true"
* @param pageSize The number of results to display on each page when creating paged results from a query. The maximum value is 200.
* @param sortBy
* @param startIndex
* @return String Resource Url
*/
public static MozuUrl getProductsUrl(String filter, Integer pageSize, String sortBy, Integer startIndex)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/storefront/products/?filter={filter}&startIndex={startIndex}&pageSize={pageSize}&sortBy={sortBy}");
formatter.formatUrl("filter", filter);
formatter.formatUrl("pageSize", pageSize);
formatter.formatUrl("sortBy", sortBy);
formatter.formatUrl("startIndex", startIndex);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
}
/**
* Get Resource Url for GetProductInventory
* @param locationCodes Array of location codes for which to retrieve product inventory information.
* @param productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only.
* @return String Resource Url
*/
public static MozuUrl getProductInventoryUrl(String locationCodes, String productCode)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/storefront/products/{productCode}/locationinventory?locationCodes={locationCodes}");
formatter.formatUrl("locationCodes", locationCodes);
formatter.formatUrl("productCode", productCode);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
}
/**
* Get Resource Url for GetProduct
* @param allowInactive If true, returns an inactive product as part of the query.
* @param productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only.
* @param skipInventoryCheck
* @param variationProductCode Merchant-created code associated with a specific product variation. Variation product codes maintain an association with the base product code.
* @return String Resource Url
*/
public static MozuUrl getProductUrl(Boolean allowInactive, String productCode, Boolean skipInventoryCheck, String variationProductCode)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/storefront/products/{productCode}?variationProductCode={variationProductCode}&allowInactive={allowInactive}&skipInventoryCheck={skipInventoryCheck}");
formatter.formatUrl("allowInactive", allowInactive);
formatter.formatUrl("productCode", productCode);
formatter.formatUrl("skipInventoryCheck", skipInventoryCheck);
formatter.formatUrl("variationProductCode", variationProductCode);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
}
/**
* Get Resource Url for ConfiguredProduct
* @param includeOptionDetails If true, the response returns details about the product. If false, returns a product summary such as the product name, price, and sale price.
* @param productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only.
* @param skipInventoryCheck
* @return String Resource Url
*/
public static MozuUrl configuredProductUrl(Boolean includeOptionDetails, String productCode, Boolean skipInventoryCheck)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/storefront/products/{productCode}/configure?includeOptionDetails={includeOptionDetails}&skipInventoryCheck={skipInventoryCheck}");
formatter.formatUrl("includeOptionDetails", includeOptionDetails);
formatter.formatUrl("productCode", productCode);
formatter.formatUrl("skipInventoryCheck", skipInventoryCheck);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
}
/**
* Get Resource Url for ValidateProduct
* @param productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only.
* @param skipInventoryCheck
* @return String Resource Url
*/
public static MozuUrl validateProductUrl(String productCode, Boolean skipInventoryCheck)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/storefront/products/{productCode}/validate?skipInventoryCheck={skipInventoryCheck}");
formatter.formatUrl("productCode", productCode);
formatter.formatUrl("skipInventoryCheck", skipInventoryCheck);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
}
}
| mit |
jyotikamboj/container | pf-framework/src/play-java-jdbc/src/main/java/play/db/package-info.java | 141 | /*
* Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
*/
/**
* Provides the JDBC database access API.
*/
package play.db; | mit |
BJ-Wumpus-And-Company/wumpus-world | src/org.bjwumpusandcompany.hunter.keyboardcontrolled/src/main/java/org/bjwumpusandcompany/hunter/keyboardcontrolled/App.java | 211 | package org.bjwumpusandcompany.hunter.keyboardcontrolled;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
| mit |
SpongePowered/SpongeCommon | src/main/java/org/spongepowered/common/item/inventory/lens/MutableLensCollection.java | 1790 | /*
* 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.item.inventory.lens;
import org.spongepowered.api.item.inventory.InventoryProperty;
import java.util.Collection;
import java.util.List;
/**
* A type of Lens collection whose members are fully mutable and also supports
* all aspects of the {@link Collection} interface.
*/
public interface MutableLensCollection extends List<Lens>, DynamicLensCollection {
void add(Lens lens, InventoryProperty<?, ?>... properties);
void add(int index, Lens lens, InventoryProperty<?, ?>... properties);
}
| mit |
Beanstream-DRWP/beanstream-java | src/main/java/com/beanstream/data/Records.java | 172 | package com.beanstream.data;
import java.util.List;
import com.beanstream.domain.TransactionRecord;
public class Records
{
public List<TransactionRecord> records;
}
| mit |
CS2103AUG2016-W13-C1/main | src/main/java/seedu/todo/commons/util/StringUtil.java | 1191 | package seedu.todo.commons.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;
/**
* Helper functions for handling strings.
*/
public class StringUtil {
public static boolean containsIgnoreCase(String source, String query) {
String[] split = source.toLowerCase().split("\\s+");
List<String> strings = Arrays.asList(split);
return strings.stream().filter(s -> s.equals(query.toLowerCase())).count() > 0;
}
/**
* Returns a detailed message of the t, including the stack trace.
*/
public static String getDetails(Throwable t){
assert t != null;
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return t.getMessage() + "\n" + sw.toString();
}
/**
* Returns true if s represents an unsigned integer e.g. 1, 2, 3, ... <br>
* Will return false for null, empty string, "-1", "0", "+1", and " 2 " (untrimmed) "3 0" (contains whitespace).
* @param s Should be trimmed.
*/
public static boolean isUnsignedInteger(String s){
return s != null && s.matches("^0*[1-9]\\d*$");
}
}
| mit |
sel-utils/java | src/main/java/sul/protocol/java340/clientbound/ResourcePackSend.java | 2030 | /*
* This file was automatically generated by sel-utils and
* released under the MIT License.
*
* License: https://github.com/sel-project/sel-utils/blob/master/LICENSE
* Repository: https://github.com/sel-project/sel-utils
* Generated from https://github.com/sel-project/sel-utils/blob/master/xml/protocol/java340.xml
*/
package sul.protocol.java340.clientbound;
import java.nio.charset.StandardCharsets;
import sul.utils.*;
public class ResourcePackSend extends Packet {
public static final int ID = (int)52;
public static final boolean CLIENTBOUND = true;
public static final boolean SERVERBOUND = false;
@Override
public int getId() {
return ID;
}
public String url;
public String hash;
public ResourcePackSend() {}
public ResourcePackSend(String url, String hash) {
this.url = url;
this.hash = hash;
}
@Override
public int length() {
return Buffer.varuintLength(url.getBytes(StandardCharsets.UTF_8).length) + url.getBytes(StandardCharsets.UTF_8).length + Buffer.varuintLength(hash.getBytes(StandardCharsets.UTF_8).length) + hash.getBytes(StandardCharsets.UTF_8).length + 1;
}
@Override
public byte[] encode() {
this._buffer = new byte[this.length()];
this.writeVaruint(ID);
byte[] dj=url.getBytes(StandardCharsets.UTF_8); this.writeVaruint((int)dj.length); this.writeBytes(dj);
byte[] afa=hash.getBytes(StandardCharsets.UTF_8); this.writeVaruint((int)afa.length); this.writeBytes(afa);
return this.getBuffer();
}
@Override
public void decode(byte[] buffer) {
this._buffer = buffer;
this.readVaruint();
int bvdj=this.readVaruint(); url=new String(this.readBytes(bvdj), StandardCharsets.UTF_8);
int bvafa=this.readVaruint(); hash=new String(this.readBytes(bvafa), StandardCharsets.UTF_8);
}
public static ResourcePackSend fromBuffer(byte[] buffer) {
ResourcePackSend ret = new ResourcePackSend();
ret.decode(buffer);
return ret;
}
@Override
public String toString() {
return "ResourcePackSend(url: " + this.url + ", hash: " + this.hash + ")";
}
} | mit |
LawnboyMax/concurrent_jcrawler | src/main/java/lawnbway/jcrawler/UserAgentManagerSingleton.java | 4882 | package lawnbway.jcrawler;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.RandomAccessFile;
import java.util.concurrent.ThreadLocalRandom;
/**
* UserAgentManagerSingleton is a singleton that keeps open the file with available user agents ("usr_agents")
* and provides random user agent strings (names) to CrawlJob instances that request user agent change.
*
* enum type fields are compile time constants and are constructed when the type is referenced for the
* first time. Therefore multiple instantiations are not possible.
*/
public enum UserAgentManagerSingleton {
INSTANCE;
private FileReader fr;
private int usrAgentNum;
private RandomAccessFile raf;
volatile private String usrAgentName;
private static final String USR_AGENTS_NAME = "usr_agents";
private static final String USR_AGENTS_RELATIVE_PATH = "src/main/resources/";
private static final int DEFAULT_PROBABILITY = 30;
/**
* Instantiates the class by opening the file with user agents
* and counting the number of user agents in the file.
* Also, randomly chooses a user agent from the file, so it is available for CrawlJob to take.
*
* @param fileName the file with available user agent strings ("user_agents" by default) with one user agent per line
* @throws IOException if there is a problem with opening the file containing user agents
*/
private UserAgentManagerSingleton() {
try {
fr = new FileReader(USR_AGENTS_RELATIVE_PATH + USR_AGENTS_NAME);
LineNumberReader lnr = new LineNumberReader(fr);
lnr.skip(Long.MAX_VALUE);
setUsrAgentNum(lnr.getLineNumber());
lnr.close();
raf = new RandomAccessFile(USR_AGENTS_RELATIVE_PATH + USR_AGENTS_NAME, "r");
} catch (IOException e) {
System.out.println("ERROR! There is a problem opening file containing user agents.");
e.printStackTrace();
System.exit(1);
}
this.setRandom();
}
/**
* Chooses a random user agent from the file.
*
*/
public synchronized void setRandom() {
int usrAgentNum = getUsrAgentNum();
int randomLine = ThreadLocalRandom.current().nextInt(0, usrAgentNum + 1);
try {
raf.seek(0); // move RAF pointer to the beginning
for(int i = 1; i < randomLine; i++)
raf.readLine();
setName(raf.readLine()); // set user agent to user agent #randomLine from usr_agents file
} catch (IOException e) {
System.out.println("There is a problem reading file containing user agents.");
e.printStackTrace();
System.exit(1);
}
}
/**
* Changes user agent with a certain probability (from 0 to 100).
* Uses DEFAULT_PROBABILITY if the provided parameter is not a valid probability.
*
* @param probability the probability that the user agent will be changed at this method invocation
*/
public void changeUserAgent(int probability) {
if (!isValidProbability(probability))
probability = DEFAULT_PROBABILITY;
int chance = ThreadLocalRandom.current().nextInt(0, 100 + 1); // Get random number from 0 to 100 (inclusive; this is why +1)
if (chance < probability || probability == 100) {
UserAgentManagerSingleton.INSTANCE.setRandom(); // Switch to random user agent if the chance falls within the chosen probability
}
setName(UserAgentManagerSingleton.INSTANCE.getName());
}
/**
* Validates the probability that the changeUserAgent method uses.
*
* @param probability the probability to be validated
* @return true if the probability is valid, false if it is invalid
*/
private boolean isValidProbability(int probability) {
return (probability >= 0 && probability <= 100);
}
/**
* Sets the name of the currently selected user agent.
*
* @param name name of the selected user agent
*/
private void setName(String name) {
usrAgentName = name;
}
/**
* Gets the name of the currently selected user agent.
*
* @return name of the selected user agent
*/
public String getName() {
return usrAgentName;
}
/**
* Sets the number of available user agents from the user agent file.
*
* @param usrAgentNum the number of available user agents
*/
private void setUsrAgentNum(int usrAgentNum) {
if(usrAgentNum < 0) {
System.out.println("ERROR! " + USR_AGENTS_NAME + "cannot have negative number of lines.");
System.exit(1);
}
this.usrAgentNum = usrAgentNum;
}
/**
* Gets the number of lines (corresponding to the number of user agents) from the user agent file.
*
* @return the number of available user agents
*/
private int getUsrAgentNum() {
return usrAgentNum;
}
/**
* Closes file streams used by this class.
* To be invoked just before the program termination.
*/
public void cleanup() {
try {
raf.close();
fr.close();
} catch (IOException e) {
System.out.println("ERROR! UserAgent cleanup failed.");
e.printStackTrace();
}
}
} | mit |
rsky/logbook-kai-plugins | commons/src/main/java/plugins/util/ConfigLoader.java | 693 | package plugins.util;
import logbook.internal.Config;
import java.util.function.Supplier;
/**
* クラスローダーの違いでClassNotFoundExceptionが発生するのを防止するためのユーティリティ
*/
public class ConfigLoader {
public static <T> T load(Class<T> clazz, Supplier<T> def) {
ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
ClassLoader newLoader = clazz.getClassLoader();
Thread.currentThread().setContextClassLoader(newLoader);
try {
return Config.getDefault().get(clazz, def);
} finally {
Thread.currentThread().setContextClassLoader(oldLoader);
}
}
}
| mit |
EdSergeev/TextFloatingActionButton | testapp/src/main/java/com/example/testapp/MainActivity.java | 1723 | package com.example.testapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.github.edsergeev.TextFloatingActionButton;
public class MainActivity extends AppCompatActivity {
private int counter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final TextFloatingActionButton fab = (TextFloatingActionButton) findViewById(R.id.fab);
fab.setText(String.valueOf(++counter));
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fab.setText(String.valueOf(++counter));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| mit |
Ashald/EnvFile | modules/platform/src/main/java/net/ashald/envfile/platform/EnvFileSettings.java | 1522 | package net.ashald.envfile.platform;
import java.util.Collections;
import java.util.List;
public class EnvFileSettings {
private final boolean pluginEnabled;
private final boolean envVarsSubstitutionEnabled;
private final boolean pathMacroSupported;
private final boolean ignoreMissing;
private final boolean enableExperimentalIntegrations;
private final List<EnvFileEntry> entries;
public EnvFileSettings(
boolean isEnabled,
boolean substituteVars,
boolean pathMacroSupported,
List<EnvFileEntry> envFileEntries,
boolean ignoreMissing,
boolean experimentalInegrations
) {
pluginEnabled = isEnabled;
envVarsSubstitutionEnabled = substituteVars;
this.pathMacroSupported = pathMacroSupported;
this.ignoreMissing = ignoreMissing;
entries = envFileEntries;
enableExperimentalIntegrations = experimentalInegrations;
}
public boolean isEnabled() {
return pluginEnabled;
}
public boolean isSubstituteEnvVarsEnabled() {
return envVarsSubstitutionEnabled;
}
public boolean isPathMacroSupported() {
return pathMacroSupported;
}
public boolean isIgnoreMissing() {
return ignoreMissing;
}
public boolean isEnableExperimentalIntegrations() {
return enableExperimentalIntegrations;
}
public List<EnvFileEntry> getEntries() {
return Collections.unmodifiableList(entries);
}
}
| mit |
owenbutler/gamedev | jGameEngine/src/main/java/org/jgameengine/input/LWJGLInputManager.java | 8048 | package org.jgameengine.input;
import org.apache.log4j.Logger;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Controller;
import org.lwjgl.input.Controllers;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import java.util.ArrayList;
import java.util.List;
public class LWJGLInputManager
implements InputManager {
private static final Logger logger = Logger.getLogger(LWJGLInputManager.class.getName());
private List<MovementListener> movementListeners = new ArrayList<>();
private List<MouseListener> mouseListeners = new ArrayList<>();
private List<MouseListener> addedMouseListeners = new ArrayList<>();
private List<MouseListener> removedMouseListeners = new ArrayList<>();
private List<PauseListener> pauseListeners = new ArrayList<>();
private int mouseVerticalSize;
private boolean paused = false;
public void initInput() {
try {
Controllers.create();
int numberOfControllers = Controllers.getControllerCount();
logger.debug("found (" + numberOfControllers + ") controllers");
for (int i = 0; i < numberOfControllers; i++) {
Controller c = Controllers.getController(i);
logger.debug("c.getName() = " + c.getName());
}
} catch (LWJGLException e) {
throw new IllegalStateException(e);
}
// flush the mouse queue?
// was seeing about 50 mouse button events before anything happend, run this loop to
// absorb those events before the main game loop starts
while (Mouse.next()) {
// ignore event
}
}
public void processInput() {
processKeyboardInput();
processMouseInput();
processControllerInput();
}
private void processControllerInput() {
while (Controllers.next()) {
Controller source = Controllers.getEventSource();
if (Controllers.isEventButton()) {
System.out.println("Event was from " + source.getName() + " and was from button " + Controllers.getEventControlIndex());
}
if (Controllers.isEventAxis()) {
System.out.println("Event was from " + source.getName() + " and was from axis " + Controllers.getEventControlIndex());
}
}
}
private void processKeyboardInput() {
Keyboard.poll();
while (Keyboard.next()) {
processKey();
}
}
private void processMouseInput() {
mouseListeners.addAll(addedMouseListeners);
addedMouseListeners.clear();
while (Mouse.next()) {
int mouseEventX = Mouse.getEventX();
int mouseEventY = mouseVerticalSize - Mouse.getEventY();
int mouseButton = Mouse.getEventButton();
for (MouseListener mouseListener : mouseListeners) {
// if this is not a mouse button event, it must be a movement event, so call that
if (mouseButton == -1) {
mouseListener.mouseEvent(mouseEventX, mouseEventY);
} else {
boolean mouseButtonState = Mouse.getEventButtonState();
// decide which mouse button event to trigger
if (!mouseButtonState) {
switch (mouseButton) {
case 0:
mouseListener.button0Up();
break;
case 1:
mouseListener.button1Up();
break;
case 2:
mouseListener.button2Up();
break;
default:
}
} else {
switch (mouseButton) {
case 0:
mouseListener.button0Down();
break;
case 1:
mouseListener.button1Down();
break;
case 2:
mouseListener.button2Down();
break;
default:
}
}
}
}
}
mouseListeners.removeAll(removedMouseListeners);
removedMouseListeners.clear();
}
private void processKey() {
int key = Keyboard.getEventKey();
boolean keyState = Keyboard.getEventKeyState();
processMovementKey(key, keyState);
}
private boolean processMovementKey(int key, boolean keyState) {
boolean foundKey = true;
int magnitude = keyState ? 1 : 0;
switch (key) {
case Keyboard.KEY_W:
inputUp(magnitude);
break;
case Keyboard.KEY_UP:
inputUp(magnitude);
break;
case Keyboard.KEY_S:
inputDown(magnitude);
break;
case Keyboard.KEY_DOWN:
inputDown(magnitude);
break;
case Keyboard.KEY_A:
inputLeft(magnitude);
break;
case Keyboard.KEY_LEFT:
inputLeft(magnitude);
break;
case Keyboard.KEY_D:
inputRight(magnitude);
break;
case Keyboard.KEY_RIGHT:
inputRight(magnitude);
break;
case Keyboard.KEY_P:
inputPause(magnitude);
break;
case Keyboard.KEY_Z:
if (magnitude == 1) {
}
default:
foundKey = false;
}
return foundKey;
}
private void inputPause(int magnitude) {
if (magnitude == 1) {
if (paused) {
paused = false;
for (PauseListener pauseListener : pauseListeners) {
pauseListener.unPause();
}
} else {
for (PauseListener pauseListener : pauseListeners) {
pauseListener.pause();
}
paused = true;
}
}
}
private void inputUp(int magnitude) {
for (MovementListener listener : movementListeners) {
listener.inputUp(magnitude);
}
}
private void inputDown(int magnitude) {
for (MovementListener listener : movementListeners) {
listener.inputDown(magnitude);
}
}
private void inputLeft(int magnitude) {
for (MovementListener listener : movementListeners) {
listener.inputLeft(magnitude);
}
}
private void inputRight(int magnitude) {
for (MovementListener listener : movementListeners) {
listener.inputRight(magnitude);
}
}
public void addMovementListener(MovementListener listener) {
movementListeners.add(listener);
}
public void addMouseListener(MouseListener listener) {
logger.debug("adding mouse listener " + listener);
addedMouseListeners.add(listener);
}
public void removeMouseListener(MouseListener listener) {
removedMouseListeners.add(listener);
}
public void addPauseListener(PauseListener listener) {
pauseListeners.add(listener);
}
public void removePauseListener(PauseListener listener) {
pauseListeners.remove(listener);
}
public void addInputEventListener(InputListener listener) {
}
public void removeInputEventListener(InputListener listener) {
}
public int getMouseVerticalSize() {
return mouseVerticalSize;
}
public void setMouseVerticalSize(int mouseVerticalSize) {
this.mouseVerticalSize = mouseVerticalSize;
}
}
| mit |
Sledro/College-Programs | Year-1/Java/Single Class Programs/Jlab35.java | 2012 | class Jlab35
// Student Name : Daniel Hayden
// Student Id Number : C00137009
// Date : 9/10/14
// Purpose : 4) Write a program to find the largest, smallest and average value in a collection of N numbers.
/// (Run the program numbers.exe on the Common Disk to see how it should work)
{
public static void main(String[] args)
{
int num;
int num1;
int largest;
int smallest;
double average=0;
int count=1;
int count2=1;
int count3=1;
boolean exit = false;
double newAve;
System.out.println("Enter 0 at anytime to exit. ");
System.out.print("Enter your first number from your list: ");
num1 = EasyIn.getInt();
largest=num1;
smallest=num1;
average = average + num1;
while(exit == false)
{
System.out.print("\nEnter the next number form your list: ");
num = EasyIn.getInt();
if (num == 0)
{
exit = true;
}
else if(num > largest)
{
largest = num;
}
else if(num < smallest)
{
smallest = num;
}
if (num == largest)
{
count2++; // Count the number of times the LARGEST number is entered.
}
if (num == smallest)
{
count3++; // Count the number of times the SMALLEST number is entered.
}
count++; // Count the number of numbers entered.
average = average + num;
newAve = average / count;
System.out.println("\n------------------------------------------------");
System.out.println("The largest number entered is: " + largest + " and has been entered " + count2 + " times" );
System.out.println("The smallest entered: " + smallest + " and has been entered " + count3 + " times" );
System.out.println("The average of the numbers entered is: " + newAve );
System.out.println("--------------------------------------------------");
}
}
}
| mit |
Fun2LearnCode/Java | topics/control-structures/loops/ForEachLoop.java | 196 | public class ForEachLoop{
public static void main(String args[]){
int[] foo = {0,1,2,3,4,5,6,7,8,9};
for(int bar : foo){
System.out.println(bar);
}
}
}
| mit |
imallett/FlashBang | app/src/main/java/imallett/FlashBang/Views/ViewGraphBase.java | 2927 | package imallett.FlashBang.Views;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import imallett.FlashBang.Config;
import imallett.FlashBang.DataStream;
import imallett.FlashBang.R;
public class ViewGraphBase extends SurfaceView implements SurfaceHolder.Callback {
protected Paint paint;
private class Point {
float x, y;
@Override public String toString() { return "(x,y)=("+x+","+y+")"; }
}
private Point[] _points = new Point[DataStream.N];
public float scale = 1.0f;
protected ViewGraphBase(Context context) {
super(context); _init();
}
protected ViewGraphBase(Context context, AttributeSet attrs) {
super(context,attrs); _init();
}
protected ViewGraphBase(Context context, AttributeSet attrs, int defStyleAttr) {
super(context,attrs,defStyleAttr); _init();
}
private void _init() {
setWillNotDraw(false);
setWillNotCacheDrawing(true);
getHolder().addCallback(this);
for (int i=0;i<DataStream.N;++i) _points[i]=new Point();
paint = new Paint();
paint.setAntiAlias(true);
}
protected void _drawBackground(Canvas canvas, boolean valid) {
if (valid) {
canvas.drawColor( ContextCompat.getColor(getContext(), R.color.color_good) );
} else {
canvas.drawColor( ContextCompat.getColor(getContext(), R.color.color_bad) );
}
}
protected void _drawAxes(Canvas canvas) {
int w = canvas.getWidth();
int h = canvas.getHeight();
paint.setColor(Color.BLACK);
canvas.drawLine(0,h-6, w-1,h-6, paint);
canvas.drawLine(w-1,h-1, w-1,0, paint);
}
protected void _drawGraph(Canvas canvas, DataStream data,int attrib_index) {
int w = canvas.getWidth();
int h = canvas.getHeight();
long tn = data.t1_last;
long t0 = tn - (DataStream.N-1)* Config.BUCKET_NS;
long tr = System.nanoTime();
long tl = tr - (DataStream.N-1)*Config.BUCKET_NS;
long t;
float sc = (h-5)*scale;
for (int i=0;i<DataStream.N;++i) {
t = t0 + i*Config.BUCKET_NS;
float part = (float)( (double)(t-tl) / (double)(tr-tl) );
_points[i].x = part*w;
_points[i].y = h-6 - sc*data.buckets[i].data[attrib_index];
}
paint.setColor(Color.RED);
boolean prev_okay = data.buckets[0].valid[attrib_index];
float x0 = _points[0].x;
float y0 = _points[0].y;
for (int i=1;i<DataStream.N;++i) {
float x1=_points[i].x, y1=_points[i].y;
boolean this_okay = data.buckets[i].valid[attrib_index];
if (prev_okay && this_okay) {
canvas.drawLine( x0,y0, x1,y1, paint );
}
prev_okay=this_okay; x0=x1; y0=y1;
}
}
@Override public void surfaceCreated(SurfaceHolder holder) {}
@Override public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {}
@Override public void surfaceDestroyed(SurfaceHolder holder) {}
}
| mit |
Willie1234/Inforvellor | src/main/java/com/njyb/gbdbase/service/alldb/convertdata/EcuadorEConvertModel.java | 1414 | package com.njyb.gbdbase.service.alldb.convertdata;
import java.io.Serializable;
import com.njyb.gbdbase.model.alldb.commonrightlibrary.AllDBModel;
import com.njyb.gbdbase.model.datasearch.ecuador.EcuadorExportModel;
/**
* 厄瓜多尔 出口
* @author WangBo
* 2015年6月1日
* EcuadorEConvertModel.java
*/
public class EcuadorEConvertModel extends AllDBModel implements Serializable{
private static final long serialVersionUID = 1L;
private EcuadorEConvertModel() {
}
private static EcuadorEConvertModel argentina = null;
/**
* 转换厄瓜多尔数据
* @param argentinaExport
* @param country
* @return
*/
public static EcuadorEConvertModel getEcuadorEConvertModel(EcuadorExportModel ecuadorExportModel,String country){
argentina = new EcuadorEConvertModel();
if (null != ecuadorExportModel) {
argentina.setWeight(0);
argentina.setId(ecuadorExportModel.getEcuadorExportId());
argentina.setDate(ecuadorExportModel.getDate());
argentina.setCountNum(ecuadorExportModel.getQuantity());
argentina.setCountry(country);
argentina.setGoodsdescription(ecuadorExportModel.getGoodsDesc());
argentina.setHscode(ecuadorExportModel.getHscode());
argentina.setImporter(ecuadorExportModel.getImporter());
argentina.setTotalprice(0);
argentina.setUnitprice(ecuadorExportModel.getFobValue());
}
return argentina;
}
} | mit |
ericlink/adms-server | playframework-dist/play-1.1/samples-and-tests/i-am-a-developer/i-am-working-here/yop/app/controllers/Application.java | 215 | package controllers;
import play.*;
import play.mvc.*;
import java.util.*;
import models.*;
public class Application extends Controller {
public static void index(String name) {
render(name);
}
} | mit |
Gsantomaggio/turtle | src/main/java/io/turtle/metrics/impl/DropwizardTCounter.java | 932 | package io.turtle.metrics.impl;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import io.turtle.metrics.TCounter;
/**
* Created by gabriele on 20/03/15.
*/
public class DropwizardTCounter implements TCounter {
private Counter internalCounter;
private MetricRegistry metrics = DropwizardMetrics.getInstance().getTurtleMetrics();
@Override
public void inc() {
internalCounter.inc();
}
@Override
public void inc(long value) {
internalCounter.inc(value);
}
@Override
public void dec() {
internalCounter.dec();
}
@Override
public void dec(long value) {
internalCounter.dec(value);
}
@Override
public void register(String counterName) {
internalCounter = metrics.counter(counterName);
}
@Override
public long getCount() {
return internalCounter.getCount();
}
}
| mit |
ThorbenKuck/NetCom2 | _main/src/main/java/com/github/thorbenkuck/netcom2/pipeline/OnReceivePredicateWrapper.java | 2128 | package com.github.thorbenkuck.netcom2.pipeline;
import com.github.thorbenkuck.keller.annotations.APILevel;
import com.github.thorbenkuck.keller.annotations.Synchronized;
import com.github.thorbenkuck.netcom2.interfaces.ReceivePipeline;
import com.github.thorbenkuck.netcom2.interfaces.TriPredicate;
import com.github.thorbenkuck.netcom2.shared.Session;
import com.github.thorbenkuck.netcom2.utils.NetCom2Utils;
import com.github.thorbenkuck.network.connection.ConnectionContext;
import java.util.function.BiPredicate;
/**
* This Class is part of the Wrapper bundle and wraps a BiPredicate into an TriPredicate. It is used to make the
* CommunicationRegistration easier to use.
* This class is not meant for use outside of NetCom2. It is an internal component and only used by the {@link ReceivePipeline}
*
* @param <T> the Object, which will be received over the network and handled at either the ClientStartup or ServerStartup.
* @version 1.0
* @since 1.0
*/
@APILevel
@Synchronized
class OnReceivePredicateWrapper<T> implements TriPredicate<ConnectionContext, Session, T> {
private final BiPredicate<Session, T> biPredicate;
@APILevel
OnReceivePredicateWrapper(final BiPredicate<Session, T> biPredicate) {
NetCom2Utils.assertNotNull(biPredicate);
this.biPredicate = biPredicate;
}
/**
* {@inheritDoc}
*/
@Override
public final boolean test(final ConnectionContext connectionContext, final Session session, final T t) {
NetCom2Utils.parameterNotNull(session, t);
return biPredicate.test(session, t);
}
/**
* {@inheritDoc}
*/
@Override
public final int hashCode() {
return biPredicate.hashCode();
}
/**
* {@inheritDoc}
*/
@Override
public final boolean equals(final Object o) {
if (o == null) {
return false;
}
if (o instanceof com.github.thorbenkuck.netcom2.pipeline.OnReceivePredicateWrapper) {
return biPredicate.equals(((com.github.thorbenkuck.netcom2.pipeline.OnReceivePredicateWrapper) o).biPredicate);
}
return biPredicate.equals(o);
}
/**
* {@inheritDoc}
*/
@Override
public final String toString() {
return biPredicate.toString();
}
}
| mit |
Wbondar/propitious-octo-waddle | propitious-octo-waddle-web/src/main/java/pl/lubcode/propitious_octo_waddle/propitious_octo_waddle_web/OptionUpdate.java | 1087 | package pl.lubcode.propitious_octo_waddle.propitious_octo_waddle_web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pl.lubcode.propitious_octo_waddle.propitious_octo_waddle_domain.Account;
import pl.lubcode.propitious_octo_waddle.propitious_octo_waddle_domain.Option;
import javax.servlet.annotation.WebServlet;
@WebServlet(name="OptionUpdate",urlPatterns={"/options/update"})
public final class OptionUpdate extends ApplicationServlet {
/**
*
*/
private static final long serialVersionUID = 5916595302878749055L;
@Override
public void doPost (HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
String idOfOptionToUpdate = request.getParameter("id");
Option optionToUpdate = Option.getInstance(idOfOptionToUpdate);
String updatedDescription = request.getParameter("description");
Account updator = getUserAccount(request);
optionToUpdate.updateDescription(updator, updatedDescription);
}
}
| mit |
jglrxavpok/OurCraft | src/main/java/org/craft/client/render/OffsettedOpenGLBuffer.java | 947 | package org.craft.client.render;
public class OffsettedOpenGLBuffer extends OpenGLBuffer
{
/**
* Offset in indices list
*/
private int offset;
/**
* Max index registred
*/
private int max = 0;
public void addIndex(int index)
{
super.addIndex(this.offset + index);
if(index > max)
max = index;
}
/**
* Sets offset of this buffer
*/
public void setOffset(int index)
{
this.offset = index;
}
/**
* Gets current offset in indices list
*/
public int getOffset()
{
return offset;
}
/**
* Sets current offset at the end of the indices list
*/
public void setOffsetToEnd()
{
setOffset(offset + max + 1);
max = 0;
}
/**
* Increments the offset by given amount
*/
public void incrementOffset(int amount)
{
offset += amount;
}
}
| mit |
cloverfisher/SoundToHeartRateMonitor | src/shiyaoyu/me/soundtoheartratemonitor/MainActivity.java | 1368 | package shiyaoyu.me.soundtoheartratemonitor;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mainToRecordButton = (Button)findViewById(R.id.btnMainToRecord);
mainToRecordButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,RecordDisplayActivity.class);
startActivity(intent );
}
});
Button mainToListViewButton = (Button)findViewById(R.id.buttonListView);
mainToListViewButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListViewActivity.class);
startActivity(intent);
}
});
mainToListViewButton.setEnabled(false);
mainToListViewButton.setVisibility(4);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| mit |
collinbachi/slogo | src/slogo/Main.java | 247 | package slogo;
import javafx.application.Application;
public class Main {
public static void main (String[] args) {
// just contains a main method. This will call a SlogoApplication
Application.launch(SLOGOApplication.class,args);
}
} | mit |
BurnGames/BGDCore | src/main/java/me/paulbgd/bgdcore/BGDCore.java | 9220 | package me.paulbgd.bgdcore;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;
import lombok.Getter;
import me.paulbgd.bgdcore.commands.def.ItemData;
import me.paulbgd.bgdcore.commands.def.ReloadConfigCommand;
import me.paulbgd.bgdcore.configuration.ConfigurationFile;
import me.paulbgd.bgdcore.configuration.CoreConfiguration;
import me.paulbgd.bgdcore.io.json.JSONInputStream;
import me.paulbgd.bgdcore.listeners.PlayerListener;
import me.paulbgd.bgdcore.nms.NMSManager;
import me.paulbgd.bgdcore.player.PlayerWrapper;
import me.paulbgd.bgdcore.player.PluginPlayerData;
import net.minidev.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
public class BGDCore extends JavaPlugin {
@Getter
private static final List<ConfigurationFile> configurations = new ArrayList<>();
private static final Map<JavaPlugin, Class<? extends PluginPlayerData>> playerData = new HashMap<JavaPlugin, Class<? extends PluginPlayerData>>();
private static final ConcurrentHashMap<UUID, PlayerWrapper> wrappers = new ConcurrentHashMap<>();
@Getter
private static Logger logging;
@Getter
private static File playerFolder;
@Override
public void onEnable() {
// set some defaults
logging = this.getLogger();
// setup our folder
if (!getDataFolder().exists() && !getDataFolder().mkdir()) {
logging.warning("Failed to create data folder! Will continue on..");
}
playerFolder = new File(getDataFolder(), "players");
if (!playerFolder.exists() && !playerFolder.mkdir()) {
logging.warning("Failed to create player data folder! Will continue on..");
}
// register our own configuration
registerConfiguration(new CoreConfiguration(new File(getDataFolder(), "config.json")));
// load nms
new NMSManager();
// register our own commands
new ReloadConfigCommand(this);
new ItemData(this);
// register our own listeners
getServer().getPluginManager().registerEvents(new PlayerListener(), this);
// in the case of a reload, let's load our player wrappers
for (Player player : Bukkit.getOnlinePlayers()) {
addPlayerWrapper(player.getUniqueId(), loadPlayerWrapper(player));
}
}
@Override
public void onDisable() {
// to hack our JSONOutputStream back in
/*try {
ClassLoader classLoader = new URLClassLoader(new URL[]{getFile().toURI().toURL()});
classLoader.loadClass("me.paulbgd.bgdcore.io.json.JSONOutputStream");
} catch (ClassNotFoundException | MalformedURLException e) {
e.printStackTrace();
}*/
for (PlayerWrapper playerWrapper : wrappers.values()) {
savePlayerWrapper(playerWrapper);
}
}
@Override
public void reloadConfig() {
super.reloadConfig();
for (ConfigurationFile configuration : configurations) {
try {
configuration.update();
} catch (Exception e) {
logging.log(Level.SEVERE, "Failed to reload configuration \"" + configuration.getFile().getAbsolutePath() + "\"!");
e.printStackTrace();
}
}
}
@Override
public void saveConfig() {
super.saveConfig();
for (ConfigurationFile configuration : configurations) {
try {
configuration.update();
} catch (Exception e) {
logging.log(Level.SEVERE, "Failed to save configuration \"" + configuration.getFile().getAbsolutePath() + "\"!");
e.printStackTrace();
}
}
}
public static void registerConfiguration(ConfigurationFile configurationFile) {
if (configurations.contains(configurationFile)) {
throw new IllegalArgumentException("Configuration file \"" + configurationFile.getFile().getAbsolutePath() + "\" has already been registered!");
}
configurations.add(configurationFile);
}
public static void registerPluginPlayerData(JavaPlugin plugin, Class<? extends PluginPlayerData> data) {
playerData.put(plugin, data);
for (PlayerWrapper wrapper : wrappers.values()) {
try {
wrapper.load(plugin, data.getConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
}
}
public static PlayerWrapper getPlayerWrapper(Player player) {
return getPlayerWrapper(player.getUniqueId());
}
public static PlayerWrapper getPlayerWrapper(UUID uuid) {
if (!wrappers.containsKey(uuid)) {
wrappers.put(uuid, loadPlayerWrapper(uuid));
}
return wrappers.get(uuid);
}
public static void addPlayerWrapper(UUID uuid, PlayerWrapper playerWrapper) {
wrappers.put(uuid, playerWrapper);
}
public static void removePlayerWrapper(UUID uuid) {
wrappers.remove(uuid);
}
public static PlayerWrapper loadPlayerWrapper(Player player) {
return loadPlayerWrapper(player.getUniqueId());
}
@Deprecated
public static PlayerWrapper loadPlayerWrapper(UUID uniqueId, String name) {
return loadPlayerWrapper(uniqueId);
}
public static PlayerWrapper loadPlayerWrapper(UUID uniqueId) {
PlayerWrapper playerWrapper = new PlayerWrapper(uniqueId);
try {
File file = new File(playerFolder, getUUIDHash(uniqueId));
if (file.exists()) {
JSONInputStream jsonInputStream = new JSONInputStream(new FileInputStream(file));
JSONObject jsonObject = jsonInputStream.readObject();
IOUtils.closeQuietly(jsonInputStream);
playerWrapper.putAll(jsonObject);
}
} catch (IOException e) {
// neither of these should happen, but oh well
e.printStackTrace();
}
for (Map.Entry<JavaPlugin, Class<? extends PluginPlayerData>> entry : playerData.entrySet()) {
try {
playerWrapper.load(entry.getKey(), entry.getValue().getConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
}
return playerWrapper;
}
public static void savePlayerWrapper(final PlayerWrapper playerWrapper) {
if (Bukkit.isPrimaryThread() && BGDCore.getPlugin(BGDCore.class).isEnabled()) {
try {
new BukkitRunnable() {
@Override
public void run() {
savePlayerWrapper(playerWrapper);
}
}.runTaskAsynchronously(getPlugin(BGDCore.class));
return;
} catch (Exception e) {
// disabling!
}
}
playerWrapper.save();
Validate.notNull(playerWrapper);
debug("Saving " + playerWrapper.getUniqueId());
try {
File file = new File(playerFolder, getUUIDHash(playerWrapper.getUniqueId()));
GZIPOutputStream jsonOutputStream = new GZIPOutputStream(new FileOutputStream(file));
IOUtils.write(playerWrapper.toJSONString(), jsonOutputStream);
jsonOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getUUIDHash(UUID uniqueId) {
return uniqueId.toString() + ".bgd";
}
public static List<PlayerWrapper> loadAllWrappers() {
List<PlayerWrapper> wrappers = new ArrayList<>();
if (playerFolder != null && playerFolder.isDirectory()) {
for (String file : playerFolder.list()) {
wrappers.add(loadPlayerWrapper(UUID.fromString(file.split("\\.")[0])));
}
}
return wrappers;
}
public static String getCachedUsername(UUID uuid) {
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid);
if (offlinePlayer != null) {
return offlinePlayer.getName();
}
return null;
}
public static void debug(String message) {
if (CoreConfiguration.debugMode) {
if (logging == null) {
System.out.println("[BGDCore][Debug] " + message);
} else {
getLogging().severe(message);
}
}
}
}
| mit |
VDuda/SyncRunner-Pub | src/API/amazon/mws/xml/JAXB/CurrentDimension.java | 2402 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-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: 2014.05.03 at 03:15:27 PM EDT
//
package API.amazon.mws.xml.JAXB;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java class for CurrentDimension complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="CurrentDimension">
* <simpleContent>
* <extension base="<>Dimension">
* <attribute name="unitOfMeasure" use="required" type="{}CurrentUnitOfMeasure" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CurrentDimension", propOrder = {
"value"
})
public class CurrentDimension {
@XmlValue
protected BigDecimal value;
@XmlAttribute(name = "unitOfMeasure", required = true)
protected CurrentUnitOfMeasure unitOfMeasure;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setValue(BigDecimal value) {
this.value = value;
}
/**
* Gets the value of the unitOfMeasure property.
*
* @return
* possible object is
* {@link CurrentUnitOfMeasure }
*
*/
public CurrentUnitOfMeasure getUnitOfMeasure() {
return unitOfMeasure;
}
/**
* Sets the value of the unitOfMeasure property.
*
* @param value
* allowed object is
* {@link CurrentUnitOfMeasure }
*
*/
public void setUnitOfMeasure(CurrentUnitOfMeasure value) {
this.unitOfMeasure = value;
}
}
| mit |
wolfogre/AndroidProgramming | DataStorage/FileIOSample/src/main/java/com/example/me/fileiosample/SecondActivity.java | 5417 | package com.example.me.fileiosample;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* Created by Administrator on 2015/12/28.
*/
public class SecondActivity extends AppCompatActivity {
/** Called when the activity is first created. */
private boolean mExternalStorageAvailable = false;
private boolean mExternalStorageWriteable = false;
private String mSDPath ;
private String mFilePath;
private TextView mTvContent;
private Button mBtAdd,mBtDel;
private EditText mEtContent, mEtFilename;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
mTvContent=(TextView)this.findViewById(R.id.tvcontent);
mBtAdd=(Button)this.findViewById(R.id.btadd);
mBtDel=(Button)this.findViewById(R.id.btdelete);
mEtContent=(EditText)this.findViewById(R.id.etcontent);
mEtFilename=(EditText)this.findViewById(R.id.etfilename);
mBtAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
testAddOrOpenFile(mEtFilename.getText().toString(),mEtContent.getText().toString());
mTvContent.setText(readFile(mEtFilename.getText().toString()));
Toast.makeText(getApplicationContext(), "new file be added,path is" + mFilePath, Toast.LENGTH_LONG).show();
}catch(IOException e){
e.printStackTrace();
}
}
});
mBtDel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
testDeleteFile(mEtFilename.getText().toString());
mTvContent.setText("no file");
Toast.makeText(getApplicationContext(), "file be deleteed,path is" + mFilePath, Toast.LENGTH_LONG).show();
}
});
}
/*
*
* 检查SD卡状态
*/
private void checkExternalStorageState(){
String state = Environment.getExternalStorageState();
mSDPath = Environment.getExternalStorageDirectory().getPath();
mFilePath= getFilesDir().getPath();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
}
/*
* 创建一个文件并且在文件中输入些内容,BufferedOutputStream是个带缓存的FileOutputStream的包装
*/
private boolean testAddOrOpenFile(String filename ,String filecontent) throws IOException {
checkExternalStorageState();
if(mExternalStorageWriteable){
OutputStream out = null;
File file = new File(mSDPath + "//" + filename);
try{
if (!file.exists()) {
file.createNewFile();
}
out = new BufferedOutputStream(new FileOutputStream(file));
out.write(filecontent.getBytes());
return true;
}catch(IOException e){
return false;
} finally {
if (out != null) {
out.close();
}
}
}
return false;
}
/*
* 删除文件测试
*
*/
private boolean testDeleteFile(String filename){
checkExternalStorageState();
if(mExternalStorageWriteable){
File file = new File(mSDPath + "//" + filename);
if (file == null || !file.exists() || file.isDirectory())
return false;
return file.delete();
}
return false;
}
/*
* 读取文件测试
*/
private String readFile(String filename){
checkExternalStorageState();
if(mExternalStorageWriteable){
StringBuffer sb = new StringBuffer();
File file = new File(mSDPath + "//" + filename);
try {
FileInputStream fis = new FileInputStream(file);
int c;
while ((c = fis.read()) != -1) {
sb.append((char) c);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
return null;
}
}
| mit |
codingchili/chili-core | core/main/java/com/codingchili/core/testing/MockLogListener.java | 156 | package com.codingchili.core.testing;
/**
* A mock class for the log listener.
*/
public interface MockLogListener {
void onLogged(String logged);
}
| mit |
jwiesel/sfdcCommander | sfdcCommander/src/main/java/com/sforce/soap/_2006/_04/metadata/TestLevel.java | 3098 | /**
* TestLevel.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.sforce.soap._2006._04.metadata;
public class TestLevel implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected TestLevel(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _NoTestRun = "NoTestRun";
public static final java.lang.String _RunSpecifiedTests = "RunSpecifiedTests";
public static final java.lang.String _RunLocalTests = "RunLocalTests";
public static final java.lang.String _RunAllTestsInOrg = "RunAllTestsInOrg";
public static final TestLevel NoTestRun = new TestLevel(_NoTestRun);
public static final TestLevel RunSpecifiedTests = new TestLevel(_RunSpecifiedTests);
public static final TestLevel RunLocalTests = new TestLevel(_RunLocalTests);
public static final TestLevel RunAllTestsInOrg = new TestLevel(_RunAllTestsInOrg);
public java.lang.String getValue() { return _value_;}
public static TestLevel fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
TestLevel enumeration = (TestLevel)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static TestLevel fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(TestLevel.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "TestLevel"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
| mit |
Flipkart/stag-java | integration-test-java/src/main/java/com/vimeo/sample_java_model/RawGenericField.java | 305 | package com.vimeo.sample_java_model;
import com.vimeo.stag.UseStag;
/**
* Model which references a generically typed object without generic bounds (i.e., as a raw
* type).
*/
@UseStag
public class RawGenericField {
@SuppressWarnings("rawtypes")
public ExternalModelGeneric rawTypedField;
}
| mit |
restsql/restsql-test | src/org/restsql/core/RequestUtilTest.java | 8694 | package org.restsql.core;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class RequestUtilTest {
@Test
public void testConvertToStandardInternetMediaType() {
assertEquals("application/json", RequestUtil.convertToStandardInternetMediaType("application/json"));
assertEquals("application/json", RequestUtil.convertToStandardInternetMediaType("json"));
assertEquals("application/json", RequestUtil.convertToStandardInternetMediaType("JSON"));
assertEquals("application/xml", RequestUtil.convertToStandardInternetMediaType("application/xml"));
assertEquals("application/xml", RequestUtil.convertToStandardInternetMediaType("xml"));
assertEquals("application/xml", RequestUtil.convertToStandardInternetMediaType("XML"));
}
@Test
public void testGetRequestMediaType() {
assertEquals(null, RequestUtil.getRequestMediaType(null));
assertEquals(null, RequestUtil.getRequestMediaType(""));
assertEquals("unknown", RequestUtil.getRequestMediaType("unknown"));
assertEquals("application/unknown", RequestUtil.getRequestMediaType("application/unknown"));
assertEquals("application/json", RequestUtil.getRequestMediaType("application/json"));
assertEquals("application/json", RequestUtil.getRequestMediaType("application/json; charset=UTF-8"));
assertEquals("application/xml", RequestUtil.getRequestMediaType("application/xml"));
assertEquals("application/xml", RequestUtil.getRequestMediaType("application/xml; charset=UTF-8"));
assertEquals("application/x-www-form-urlencoded", RequestUtil.getRequestMediaType("application/x-www-form-urlencoded"));
assertEquals("application/x-www-form-urlencoded", RequestUtil.getRequestMediaType("application/x-www-form-urlencoded; charset=UTF-8"));
assertEquals("application/json", RequestUtil.getRequestMediaType("application/json;q=0.9,application/xml;q=0.8"));
assertEquals("application/xml", RequestUtil.getRequestMediaType("application/json;q=0.9,application/xml"));
}
@Test
public void testGetResponseMediaType_WithParamsAndRequestMediaType() {
List<RequestValue> params = new ArrayList<RequestValue>();
String mediaType = RequestUtil.getResponseMediaType(params, null, null);
assertEquals(HttpRequestAttributes.DEFAULT_MEDIA_TYPE, mediaType);
assertEquals(0, params.size());
RequestValue param1 = new RequestValue("test", "123");
params.add(param1);
mediaType = RequestUtil.getResponseMediaType(params, null, null);
assertEquals(HttpRequestAttributes.DEFAULT_MEDIA_TYPE, mediaType);
assertEquals(1, params.size());
RequestValue param2 = new RequestValue("test2", "12345");
params.add(param2);
mediaType = RequestUtil.getResponseMediaType(params, "application/json", null);
assertEquals("application/json", mediaType);
assertEquals(2, params.size());
mediaType = RequestUtil.getResponseMediaType(params, "application/x-www-form-urlencoded", null);
assertEquals("application/xml", mediaType);
assertEquals(2, params.size());
params.add(new RequestValue(Request.PARAM_NAME_OUTPUT, "application/json"));
mediaType = RequestUtil.getResponseMediaType(params, null, null);
assertEquals("application/json", mediaType);
assertEquals(2, params.size());
assertEquals(param1, params.get(0));
assertEquals(param2, params.get(1));
params.add(new RequestValue(Request.PARAM_NAME_OUTPUT, "application/xml"));
mediaType = RequestUtil.getResponseMediaType(params, "application/json", null);
assertEquals("application/xml", mediaType);
assertEquals(2, params.size());
assertEquals(param1, params.get(0));
assertEquals(param2, params.get(1));
params.add(new RequestValue(Request.PARAM_NAME_OUTPUT, "application/xml"));
mediaType = RequestUtil.getResponseMediaType(params, "application/x-www-form-urlencoded", null);
assertEquals("application/xml", mediaType);
assertEquals(2, params.size());
assertEquals(param1, params.get(0));
assertEquals(param2, params.get(1));
}
@Test
public void testGetResponseMediaType_WithParamsAndResponseMediaType() {
List<RequestValue> params = new ArrayList<RequestValue>();
RequestValue param1 = new RequestValue("test", "123");
params.add(param1);
String mediaType = RequestUtil.getResponseMediaType(params, null, "application/json");
assertEquals("application/json", mediaType);
assertEquals(1, params.size());
RequestValue param2 = new RequestValue("test2", "12345");
params.add(param2);
mediaType = RequestUtil.getResponseMediaType(params, "application/json", "application/json");
assertEquals("application/json", mediaType);
assertEquals(2, params.size());
mediaType = RequestUtil.getResponseMediaType(params, "application/xml", "application/json");
assertEquals("application/json", mediaType);
assertEquals(2, params.size());
mediaType = RequestUtil.getResponseMediaType(params, "application/x-www-form-urlencoded", "application/json");
assertEquals("application/json", mediaType);
assertEquals(2, params.size());
// Parameter overrides accept media type
params.add(new RequestValue(Request.PARAM_NAME_OUTPUT, "application/xml"));
mediaType = RequestUtil.getResponseMediaType(params, "application/x-www-form-urlencoded", "application/json");
assertEquals("application/xml", mediaType);
assertEquals(2, params.size());
assertEquals(param1, params.get(0));
assertEquals(param2, params.get(1));
// Parameter overrides accept media type
params.add(new RequestValue(Request.PARAM_NAME_OUTPUT, "application/xml"));
mediaType = RequestUtil.getResponseMediaType(params, "application/json", "application/json");
assertEquals("application/xml", mediaType);
assertEquals(2, params.size());
assertEquals(param1, params.get(0));
assertEquals(param2, params.get(1));
}
@Test
public void testGetResponseMediaType_WithComplexAcceptHeader() {
List<RequestValue> params = new ArrayList<RequestValue>();
RequestValue param1 = new RequestValue("test", "123");
params.add(param1);
String acceptMediaType = "application/xml";
assertEquals("application/xml", RequestUtil.getResponseMediaType(params, null, acceptMediaType));
acceptMediaType = "application/xml; charset=UTF-8";
assertEquals("application/xml", RequestUtil.getResponseMediaType(params, null, acceptMediaType));
acceptMediaType = "application/json";
assertEquals("application/json", RequestUtil.getResponseMediaType(params, null, acceptMediaType));
acceptMediaType = "application/json; charset=UTF-8";
assertEquals("application/json", RequestUtil.getResponseMediaType(params, null, acceptMediaType));
acceptMediaType = "*/*";
assertEquals("application/xml", RequestUtil.getResponseMediaType(params, null, acceptMediaType));
acceptMediaType = "application/*";
assertEquals("application/xml", RequestUtil.getResponseMediaType(params, null, acceptMediaType));
acceptMediaType = "application/json;q=0.9,application/xml;q=0.8";
assertEquals("application/json", RequestUtil.getResponseMediaType(params, null, acceptMediaType));
acceptMediaType = "application/json;q=0.9,application/xml";
assertEquals("application/xml", RequestUtil.getResponseMediaType(params, null, acceptMediaType));
// Chrome
acceptMediaType = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
assertEquals("application/xml", RequestUtil.getResponseMediaType(params, null, acceptMediaType));
// Firefox
acceptMediaType = "text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8, image/png,*/*;q=0.5";
assertEquals("application/xml", RequestUtil.getResponseMediaType(params, null, acceptMediaType));
//IE
acceptMediaType = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, */*";
assertEquals("application/xml", RequestUtil.getResponseMediaType(params, null, acceptMediaType));
}
@Test
public void testGetResponseMediaType_WithInvalidAcceptHeader() {
List<RequestValue> params = new ArrayList<RequestValue>();
RequestValue param1 = new RequestValue("test", "123");
params.add(param1);
String acceptMediaType = null;
assertEquals("application/xml", RequestUtil.getResponseMediaType(params, null, acceptMediaType));
acceptMediaType = "";
assertEquals("application/xml", RequestUtil.getResponseMediaType(params, null, acceptMediaType));
acceptMediaType = "application/unknown";
assertEquals("application/unknown", RequestUtil.getResponseMediaType(params, null, acceptMediaType));
}
}
| mit |
zimory/jpaunit | core/src/main/java/com/zimory/jpaunit/core/serialization/TypedScalarSerializer.java | 332 | package com.zimory.jpaunit.core.serialization;
public abstract class TypedScalarSerializer<T> implements YamlScalarSerializer<T> {
private final Class<T> type;
public TypedScalarSerializer(final Class<T> type) {
this.type = type;
}
@Override
public Class<T> getType() {
return type;
}
}
| mit |
ljtfreitas/java-restify | java-restify-oauth2-authentication/src/main/java/com/github/ljtfreitas/restify/http/client/request/authentication/oauth2/ResourceOwner.java | 2509 | /*******************************************************************************
*
* MIT License
*
* Copyright (c) 2016 Tiago de Freitas Lima
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
package com.github.ljtfreitas.restify.http.client.request.authentication.oauth2;
import static com.github.ljtfreitas.restify.util.Preconditions.nonNull;
import java.security.Principal;
import java.util.Objects;
import com.github.ljtfreitas.restify.http.client.request.authentication.Credentials;
public class ResourceOwner implements Principal {
private final Credentials credentials;
public ResourceOwner(String username, String password) {
this(new Credentials(username, password));
}
public ResourceOwner(Credentials credentials) {
this.credentials = nonNull(credentials, "Credentials are required.");
}
public String username() {
return credentials.username();
}
public String password() {
return credentials.password();
}
@Override
public String getName() {
return credentials.username();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ResourceOwner) {
ResourceOwner that = (ResourceOwner) obj;
return this.credentials.equals(that.credentials);
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hash(credentials);
}
@Override
public String toString() {
return credentials.toString();
}
}
| mit |
georgewfraser/vscode-javac | src/main/java/org/javacs/debug/proto/ScopesArguments.java | 182 | package org.javacs.debug.proto;
/** Arguments for 'scopes' request. */
public class ScopesArguments {
/** Retrieve the scopes for this stackframe. */
public long frameId;
}
| mit |
wulczer/PhotoToDucksboard | src/com/ducksboard/photo/SendInfo.java | 303 | package com.ducksboard.photo;
import android.net.Uri;
public class SendInfo {
public Uri uri;
public String apiKey;
public String label;
public SendInfo(Uri uri, String apiKey, String label) {
this.uri = uri;
this.apiKey = apiKey;
this.label = label;
}
}
| mit |
CS2103JAN2017-W09-B2/main | src/test/java/seedu/typed/testutil/TypicalTestTasks.java | 3748 | package seedu.typed.testutil;
import java.time.Month;
import seedu.typed.commons.exceptions.IllegalValueException;
import seedu.typed.model.TaskManager;
import seedu.typed.model.task.DateTime;
import seedu.typed.model.task.Task;
import seedu.typed.model.task.UniqueTaskList;
/**
*
*/
public class TypicalTestTasks {
public TestTask alice, benson, carl, daniel, elle, fiona, george, hoon, ida;
public DateTime testDate1 = DateTime.getDateTime(2018, Month.JANUARY, 1, 1, 0);
public DateTime testDate2 = DateTime.getDateTime(2018, Month.JANUARY, 2, 2, 0);
public DateTime testDate3 = DateTime.getDateTime(2018, Month.JANUARY, 3, 3, 0);
public DateTime testDate4 = DateTime.getDateTime(2018, Month.JANUARY, 4, 4, 0);
public DateTime testDate5 = DateTime.getDateTime(2018, Month.JANUARY, 5, 5, 0);
public DateTime testDate6 = DateTime.getDateTime(2018, Month.JANUARY, 6, 6, 0);
public DateTime testDate7 = DateTime.getDateTime(2018, Month.JANUARY, 7, 7, 0);
public DateTime testDate8 = DateTime.getDateTime(2018, Month.JANUARY, 8, 8, 0);
public DateTime testDate9 = DateTime.getDateTime(2018, Month.JANUARY, 9, 9, 0);
public TypicalTestTasks() {
try {
//@@author A0141094M
alice = new TaskBuilder().withName("Meet Alice Pauline").withDeadline(testDate1)
.withNotes("").withTags("friends").build();
benson = new TaskBuilder().withName("Meet Benson Meier").withDeadline(testDate2)
.withNotes("").withTags("owesMoney", "friends").build();
carl = new TaskBuilder().withName("Meet Carl Kurz").withDeadline(testDate3)
.withNotes("").build();
daniel = new TaskBuilder().withName("Meet Daniel Meier").withDeadline(testDate4)
.withNotes("").build();
elle = new TaskBuilder().withName("Meet Elle Meyer").withDeadline(testDate5)
.withNotes("").build();
fiona = new TaskBuilder().withName("Meet Fiona Kunz").withDeadline(testDate6)
.withNotes("").build();
george = new TaskBuilder().withName("Meet George Best").withDeadline(testDate7)
.withNotes("").build();
// Manually added
hoon = new TaskBuilder().withName("Meet Hoon Meier").withDeadline(testDate8)
.withNotes("").build();
ida = new TaskBuilder().withName("Meet Ida Mueller").withDeadline(testDate9)
.withNotes("").build();
//@@author
} catch (IllegalValueException e) {
e.printStackTrace();
assert false : "not possible";
}
}
public static void loadTaskManagerWithSampleData(TaskManager tm) {
for (TestTask task : new TypicalTestTasks().getTypicalTasks()) {
try {
//@@author A0141094M
Task toAdd = new Task(task.getName(), task.getNotes(), task.getSE(),
task.getTags(), false);
//@@author
tm.addTask(toAdd);
} catch (UniqueTaskList.DuplicateTaskException e) {
assert false : "not possible";
}
}
}
public TestTask[] getTypicalTasks() {
return new TestTask[] { alice, benson, carl, daniel, elle, fiona, george };
}
public TestTask[] getTypicalTasksReverse() {
return new TestTask[] { george, fiona, elle, daniel, carl, benson, alice };
}
public TestTask[] getEmpty() {
return new TestTask[] {};
}
public TaskManager getTypicalTaskManager() {
TaskManager tm = new TaskManager();
loadTaskManagerWithSampleData(tm);
return tm;
}
}
| mit |
ReneMuetti/RFTools | src/main/java/mcjty/rftools/blocks/spaceprojector/SpaceProjectorTileEntity.java | 12467 | package mcjty.rftools.blocks.spaceprojector;
import cpw.mods.fml.common.Optional;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.peripheral.IPeripheral;
import li.cil.oc.api.machine.Arguments;
import li.cil.oc.api.machine.Callback;
import li.cil.oc.api.machine.Context;
import li.cil.oc.api.network.SimpleComponent;
import mcjty.container.InventoryHelper;
import mcjty.entity.GenericEnergyReceiverTileEntity;
import mcjty.rftools.blocks.RedstoneMode;
import mcjty.network.Argument;
import mcjty.varia.Coordinate;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.util.Constants;
import java.util.Map;
@Optional.InterfaceList({
@Optional.Interface(iface = "li.cil.oc.api.network.SimpleComponent", modid = "OpenComputers"),
@Optional.Interface(iface = "dan200.computercraft.api.peripheral.IPeripheral", modid = "ComputerCraft")})
public class SpaceProjectorTileEntity extends GenericEnergyReceiverTileEntity implements ISidedInventory, SimpleComponent, IPeripheral {
public static final String COMPONENT_NAME = "space_projector";
public static final String CMD_RSMODE = "rsMode";
public static final String CMD_PROJECT = "project";
private InventoryHelper inventoryHelper = new InventoryHelper(this, SpaceProjectorContainer.factory, 1);
private RedstoneMode redstoneMode = RedstoneMode.REDSTONE_IGNORED;
private int powered = 0;
private Coordinate minBox = null;
private Coordinate maxBox = null;
public SpaceProjectorTileEntity() {
super(SpaceProjectorConfiguration.SPACEPROJECTOR_MAXENERGY, SpaceProjectorConfiguration.SPACEPROJECTOR_RECEIVEPERTICK);
}
@Override
@Optional.Method(modid = "ComputerCraft")
public String getType() {
return COMPONENT_NAME;
}
@Override
@Optional.Method(modid = "ComputerCraft")
public String[] getMethodNames() {
return new String[] { "hasCard", "getRedstoneMode", "setRedstoneMode" };
}
@Override
@Optional.Method(modid = "ComputerCraft")
public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws LuaException, InterruptedException {
switch (method) {
case 0: return new Object[] { hasCard() != null };
case 1: return new Object[] { getRedstoneMode().getDescription() };
case 2: return setRedstoneMode((String) arguments[0]);
}
return new Object[0];
}
@Override
@Optional.Method(modid = "ComputerCraft")
public void attach(IComputerAccess computer) {
}
@Override
@Optional.Method(modid = "ComputerCraft")
public void detach(IComputerAccess computer) {
}
@Override
@Optional.Method(modid = "ComputerCraft")
public boolean equals(IPeripheral other) {
return false;
}
@Override
@Optional.Method(modid = "OpenComputers")
public String getComponentName() {
return COMPONENT_NAME;
}
@Callback
@Optional.Method(modid = "OpenComputers")
public Object[] hasCard(Context context, Arguments args) throws Exception {
return new Object[] { hasCard() != null };
}
@Callback
@Optional.Method(modid = "OpenComputers")
public Object[] getRedstoneMode(Context context, Arguments args) throws Exception {
return new Object[] { getRedstoneMode().getDescription() };
}
@Callback
@Optional.Method(modid = "OpenComputers")
public Object[] setRedstoneMode(Context context, Arguments args) throws Exception {
String mode = args.checkString(0);
return setRedstoneMode(mode);
}
private NBTTagCompound hasCard() {
ItemStack itemStack = inventoryHelper.getStackInSlot(0);
if (itemStack == null || itemStack.stackSize == 0) {
return null;
}
NBTTagCompound tagCompound = itemStack.getTagCompound();
return tagCompound;
}
@Override
public void setPowered(int powered) {
if (this.powered != powered) {
this.powered = powered;
markDirty();
}
}
public RedstoneMode getRedstoneMode() {
return redstoneMode;
}
private Object[] setRedstoneMode(String mode) {
RedstoneMode redstoneMode = RedstoneMode.getMode(mode);
if (redstoneMode == null) {
throw new IllegalArgumentException("Not a valid mode");
}
setRedstoneMode(redstoneMode);
return null;
}
public void setRedstoneMode(RedstoneMode redstoneMode) {
this.redstoneMode = redstoneMode;
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
markDirty();
}
public void unproject() {
if (minBox == null) {
return;
}
for (int x = minBox.getX() ; x <= maxBox.getX() ; x++) {
for (int y = minBox.getY() ; y <= maxBox.getY() ; y++) {
for (int z = minBox.getZ() ; z <= maxBox.getZ() ; z++) {
Block block = worldObj.getBlock(x, y, z);
if (block.equals(SpaceProjectorSetup.proxyBlock)) {
worldObj.setBlockToAir(x, y, z);
}
}
}
}
minBox = null;
maxBox = null;
markDirty();
}
private void project() {
if (minBox != null) {
unproject();
}
NBTTagCompound tc = hasCard();
if (tc == null) {
return;
}
int channel = tc.getInteger("channel");
if (channel == -1) {
return;
}
SpaceChamberRepository repository = SpaceChamberRepository.getChannels(worldObj);
SpaceChamberRepository.SpaceChamberChannel chamberChannel = repository.getChannel(channel);
if (chamberChannel == null) {
return;
}
Coordinate minCorner = chamberChannel.getMinCorner();
Coordinate maxCorner = chamberChannel.getMaxCorner();
if (minCorner == null || maxCorner == null) {
return;
}
int dimension = chamberChannel.getDimension();
World world = DimensionManager.getWorld(dimension);
int dx = xCoord + 1 - minCorner.getX();
int dy = yCoord + 1 - minCorner.getY();
int dz = zCoord + 1 - minCorner.getZ();
minBox = new Coordinate(minCorner.getX() + dx, minCorner.getY() + dy, minCorner.getZ() + dz);
maxBox = new Coordinate(maxCorner.getX() + dx, maxCorner.getY() + dy, maxCorner.getZ() + dz);
for (int x = minCorner.getX() ; x <= maxCorner.getX() ; x++) {
for (int y = minCorner.getY() ; y <= maxCorner.getY() ; y++) {
for (int z = minCorner.getZ() ; z <= maxCorner.getZ() ; z++) {
Block block = world.getBlock(x, y, z);
if (block != null && !block.isAir(world, x, y, z)) {
worldObj.setBlock(dx + x, dy + y, dz + z, SpaceProjectorSetup.proxyBlock, world.getBlockMetadata(x, y, z), 3);
ProxyBlockTileEntity proxyBlockTileEntity = (ProxyBlockTileEntity) worldObj.getTileEntity(dx + x, dy + y, dz + z);
proxyBlockTileEntity.setCamoBlock(Block.blockRegistry.getIDForObject(block));
proxyBlockTileEntity.setOrigCoordinate(new Coordinate(x, y, z), dimension);
}
}
}
}
markDirty();
}
@Override
protected void checkStateServer() {
if (minBox != null) {
NBTTagCompound tc = hasCard();
if (tc == null) {
unproject();
}
}
}
@Override
public int[] getAccessibleSlotsFromSide(int side) {
return SpaceProjectorContainer.factory.getAccessibleSlots();
}
@Override
public boolean canInsertItem(int index, ItemStack item, int side) {
return SpaceProjectorContainer.factory.isInputSlot(index);
}
@Override
public boolean canExtractItem(int index, ItemStack item, int side) {
return SpaceProjectorContainer.factory.isOutputSlot(index);
}
@Override
public int getSizeInventory() {
return inventoryHelper.getCount();
}
@Override
public ItemStack getStackInSlot(int index) {
return inventoryHelper.getStackInSlot(index);
}
@Override
public ItemStack decrStackSize(int index, int amount) {
return inventoryHelper.decrStackSize(index, amount);
}
@Override
public ItemStack getStackInSlotOnClosing(int index) {
return null;
}
@Override
public void setInventorySlotContents(int index, ItemStack stack) {
inventoryHelper.setInventorySlotContents(getInventoryStackLimit(), index, stack);
}
@Override
public String getInventoryName() {
return "Space Projector";
}
@Override
public boolean hasCustomInventoryName() {
return false;
}
@Override
public int getInventoryStackLimit() {
return 1;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
return true;
}
@Override
public void openInventory() {
}
@Override
public void closeInventory() {
}
@Override
public boolean isItemValidForSlot(int index, ItemStack stack) {
return true;
}
@Override
public void readFromNBT(NBTTagCompound tagCompound) {
super.readFromNBT(tagCompound);
powered = tagCompound.getByte("powered");
minBox = Coordinate.readFromNBT(tagCompound, "minBox");
maxBox = Coordinate.readFromNBT(tagCompound, "maxBox");
}
@Override
public void readRestorableFromNBT(NBTTagCompound tagCompound) {
super.readRestorableFromNBT(tagCompound);
readBufferFromNBT(tagCompound);
int m = tagCompound.getByte("rsMode");
redstoneMode = RedstoneMode.values()[m];
}
private void readBufferFromNBT(NBTTagCompound tagCompound) {
NBTTagList bufferTagList = tagCompound.getTagList("Items", Constants.NBT.TAG_COMPOUND);
for (int i = 0 ; i < bufferTagList.tagCount() ; i++) {
NBTTagCompound nbtTagCompound = bufferTagList.getCompoundTagAt(i);
inventoryHelper.setStackInSlot(i, ItemStack.loadItemStackFromNBT(nbtTagCompound));
}
}
@Override
public void writeToNBT(NBTTagCompound tagCompound) {
super.writeToNBT(tagCompound);
tagCompound.setByte("powered", (byte) powered);
Coordinate.writeToNBT(tagCompound, "minBox", minBox);
Coordinate.writeToNBT(tagCompound, "maxBox", maxBox);
}
@Override
public void writeRestorableToNBT(NBTTagCompound tagCompound) {
super.writeRestorableToNBT(tagCompound);
writeBufferToNBT(tagCompound);
tagCompound.setByte("rsMode", (byte) redstoneMode.ordinal());
}
private void writeBufferToNBT(NBTTagCompound tagCompound) {
NBTTagList bufferTagList = new NBTTagList();
for (int i = 0 ; i < inventoryHelper.getCount() ; i++) {
ItemStack stack = inventoryHelper.getStackInSlot(i);
NBTTagCompound nbtTagCompound = new NBTTagCompound();
if (stack != null) {
stack.writeToNBT(nbtTagCompound);
}
bufferTagList.appendTag(nbtTagCompound);
}
tagCompound.setTag("Items", bufferTagList);
}
@Override
public boolean execute(EntityPlayerMP playerMP, String command, Map<String, Argument> args) {
boolean rc = super.execute(playerMP, command, args);
if (rc) {
return true;
}
if (CMD_RSMODE.equals(command)) {
String m = args.get("rs").getString();
setRedstoneMode(RedstoneMode.getMode(m));
return true;
} else if (CMD_PROJECT.equals(command)) {
project();
return true;
}
return false;
}
}
| mit |
Skrethel/simple-config-retrofit | src/test/java/com/github/skrethel/simple/config/retrofit/SchemaGeneratorTest.java | 2275 | package com.github.skrethel.simple.config.retrofit;
import com.github.skrethel.simple.config.retrofit.exception.GeneratorException;
import com.github.skrethel.simple.config.retrofit.exception.GetException;
import com.github.skrethel.simple.config.retrofit.exception.WriteException;
import com.github.skrethel.simple.config.retrofit.io.ConfigSource;
import com.github.skrethel.simple.config.retrofit.io.SchemaWriter;
import com.github.skrethel.simple.config.retrofit.schema.ConfigSchema;
import com.github.skrethel.simple.config.retrofit.workers.Generator;
import org.ini4j.Ini;
import org.junit.Test;
import static com.github.skrethel.simple.config.retrofit.TestUtils.*;
import static org.junit.Assert.*;
public class SchemaGeneratorTest implements ConfigSource, SchemaWriter {
private Ini inputConfig;
private ConfigSchema outputSchema;
@Test(expected = GeneratorException.class)
public void testEmptySchema() throws Exception {
inputConfig = new Ini();
Generator generator = new Generator();
generator.generate(this, this);
}
@Test
public void testSchemaGeneration() throws Exception {
inputConfig = new Ini();
String group1 = "group1";
String name1 = "name1";
String value1 = "value1";
String comment1 = "comment1";
addIniItem(inputConfig, group1, name1, value1, comment1);
String group2 = "group2";
String name2 = "name2";
String value2 = "value2";
String comment2 = "comment2";
addIniItem(inputConfig, group2, name2, value2, comment2);
String group3 = "group3";
String name3 = "name3";
String value3 = "value3";
addIniItem(inputConfig, group3, name3, value3, null);
Generator generator = new Generator();
generator.generate(this, this);
assertTrue(outputSchema.contains(group1, name1));
assertTrue(outputSchema.contains(group2, name2));
assertTrue(outputSchema.contains(group3, name3));
assertEquals(comment1, outputSchema.get(group1, name1).getDescription());
assertEquals(comment2, outputSchema.get(group2, name2).getDescription());
assertNull(outputSchema.get(group3, name3).getDescription());
}
@Override public Ini getConfig() throws GetException {
return inputConfig;
}
@Override public void write(ConfigSchema configSchema) throws WriteException {
outputSchema = configSchema;
}
} | mit |
dom96/BrokenBonez | BrokenBonez/app/src/main/java/com/dragonfruitstudios/brokenbonez/ParticleSystem/ParticleManager.java | 2518 | package com.dragonfruitstudios.brokenbonez.ParticleSystem;
import android.graphics.Bitmap;
import com.dragonfruitstudios.brokenbonez.AssetLoading.AssetLoader;
import com.dragonfruitstudios.brokenbonez.Game.GameObject;
import com.dragonfruitstudios.brokenbonez.Game.GameView;
import com.dragonfruitstudios.brokenbonez.GameSceneManager;
import com.dragonfruitstudios.brokenbonez.Input.TouchHandler;
import com.dragonfruitstudios.brokenbonez.Math.VectorF;
import com.dragonfruitstudios.brokenbonez.Menu.Settings;
import com.dragonfruitstudios.brokenbonez.Menu.SettingsState;
public class ParticleManager implements GameObject{
private AssetLoader assetLoader;
private GameSceneManager gameSceneManager;
private Settings settings;
private Bitmap[] smokeParticles;
private ParticleSystem smokeParticleSystem;
private int i = 0;
private int j = 2;
public ParticleManager(AssetLoader assetLoader, GameSceneManager gameSceneManager){
this.gameSceneManager = gameSceneManager;
// Load assets.
this.assetLoader = assetLoader;
this.assetLoader.AddAssets(new String[]{"particlesystem/smoke1.png", "particlesystem/smoke2.png", "particlesystem/smoke3.png", "particlesystem/smoke4.png"});
this.smokeParticles = new Bitmap[]{assetLoader.getBitmapByName("particlesystem/smoke1.png"),
assetLoader.getBitmapByName("particlesystem/smoke2.png"),
assetLoader.getBitmapByName("particlesystem/smoke3.png"),
assetLoader.getBitmapByName("particlesystem/smoke4.png")};
settings = new Settings(gameSceneManager);
}
public void draw(GameView view){
if(settings.isBoolParticlesEnabled() && ! ( smokeParticleSystem == null)) {
smokeParticleSystem.doDraw(view);
}
}
public void update(float lastUpdate, VectorF bikePos) {
if(TouchHandler.cIA == TouchHandler.ControlIsActive.ACTION_GAS_DOWN){
i = 1;
i++;
if(i > 3){
i = 0;
}
j = 1;
} else {
i = 0;
i++;
if(i > 1){
i = 0;
}
j = 1;
}
this.smokeParticleSystem = new ParticleSystem((int) bikePos.y - 25, 790, 100, 1, 10, smokeParticles[i], j, gameSceneManager);
}
public void update(float lastUpdate) {
smokeParticleSystem.updatePhysics((int) lastUpdate);
}
public void updateSize(int width, int height) {
}
} | mit |
karim/adila | database/src/main/java/adila/db/mooncake2_mtag20281.java | 202 | // This file is automatically generated.
package adila.db;
/*
* ZTE
*
* DEVICE: mooncake2
* MODEL: Mtag 281
*/
final class mooncake2_mtag20281 {
public static final String DATA = "ZTE||";
}
| mit |
Chris-crisur/AutoLam | Calculator/source/Engine.java | 7935 | /* */ package lambda;
/* */
/* */ import javax.swing.JTextArea;
/* */
/* */ class Engine
/* */ {
/* 7 */ private static int RUNNER_IDLE = 0;
/* 8 */ private static int RUNNER_REQUEST_READY = 1;
/* 9 */ private static int RUNNER_COMPUTING = 2;
/* 10 */ private static int RUNNER_REQUEST_MADE = 3;
/* 11 */ private static int RUNNER_CANCELED = 4;
/* */
/* 13 */ private class Runner extends Thread { Runner(Engine.1 param1) { this(); }
/* 14 */ int state = Engine.RUNNER_IDLE;
/* */ String name;
/* */ String expr;
/* */
/* */ public void run()
/* */ {
/* */ for (;;)
/* */ {
/* */ String str1;
/* */ String str2;
/* 24 */ synchronized (this) {
/* */ continue;
/* 26 */ try { wait();
/* */ }
/* */ catch (InterruptedException localInterruptedException1) {}
/* 25 */ if (this.state != Engine.RUNNER_REQUEST_READY) {
/* */ continue;
/* */ }
/* 28 */ str1 = this.name;
/* 29 */ str2 = this.expr;
/* 30 */ this.state = Engine.RUNNER_COMPUTING;
/* */ }
/* */
/* 33 */ Expr localExpr = Engine.this.process(str2);
/* */
/* 35 */ synchronized (this) {
/* 36 */ while (this.state == Engine.RUNNER_REQUEST_MADE)
/* 37 */ try { wait();
/* */ } catch (InterruptedException localInterruptedException2) {}
/* 39 */ if ((this.state != Engine.RUNNER_CANCELED) && (!str1.equals("")) && (localExpr != null))
/* */ {
/* 41 */ Engine.this.gui.getContext().put(str1, localExpr);
/* */ }
/* 43 */ this.name = null;
/* 44 */ this.expr = null;
/* 45 */ this.state = Engine.RUNNER_IDLE;
/* 46 */ notifyAll();
/* */ }
/* */ }
/* */ }
/* */
/* */ void requestProcessing(String paramString1, String paramString2) {
/* 52 */ int i = 0;
/* 53 */ synchronized (this) {
/* 54 */ if ((this.name != null) && (paramString1.equals(this.name)) && (paramString2.equals(this.expr)))
/* */ {
/* 56 */ return;
/* */ }
/* 58 */ if (this.state == Engine.RUNNER_COMPUTING) {
/* 59 */ this.state = Engine.RUNNER_REQUEST_MADE;
/* 60 */ i = 1;
/* */ }
/* */ }
/* */
/* 64 */ if (i != 0) {
/* 65 */ ??? = new Object[] { "Cancel Computation", "Cancel Request" };
/* */
/* 67 */ int j = javax.swing.JOptionPane.showOptionDialog(Engine.this.gui, "Cannot process request while computation is already in progress.", "Cannot Process Request", -1, 3, null, (Object[])???, ???[0]);
/* */
/* */
/* */
/* */
/* */
/* 73 */ synchronized (this) {
/* 74 */ if (j == 0) {
/* 75 */ this.state = Engine.RUNNER_CANCELED;
/* 76 */ notifyAll();
/* */ } else {
/* 78 */ this.state = Engine.RUNNER_COMPUTING;
/* 79 */ notifyAll();
/* 80 */ return;
/* */ }
/* */ }
/* */ }
/* */
/* 85 */ synchronized (this) {
/* 86 */ while (this.state != Engine.RUNNER_IDLE)
/* 87 */ try { wait();
/* */ } catch (InterruptedException localInterruptedException) {}
/* 89 */ this.name = paramString1;
/* 90 */ this.expr = paramString2;
/* 91 */ this.state = Engine.RUNNER_REQUEST_READY;
/* 92 */ notifyAll();
/* */ } }
/* */
/* */ private Runner() {} }
/* */
/* */ private Gui gui;
/* 98 */ private Runner runner = null;
/* */
/* */ Engine(Gui paramGui) {
/* 101 */ this.gui = paramGui;
/* */ }
/* */
/* */ void addDefinition(String paramString1, String paramString2) {
/* 105 */ if (this.runner == null) {
/* 106 */ this.runner = new Runner(null);
/* 107 */ this.runner.start();
/* */ }
/* 109 */ this.runner.requestProcessing(paramString1, paramString2);
/* */ }
/* */
/* */ private Expr process(String paramString) {
/* 113 */ JTextArea localJTextArea = this.gui.getOutputArea();
/* 114 */ Context localContext1 = this.gui.getContext();
/* */
/* 116 */ Context localContext2 = null;
/* 117 */ if (Options.getSubstituteSymbolsOption().getValue()) {
/* 118 */ localContext2 = localContext1;
/* */ }
/* 120 */ boolean bool1 = Options.getVaryParenthesesOption().getValue();
/* */
/* 122 */ boolean bool2 = Options.getShowIntermediateOption().getValue();
/* */
/* 124 */ int i = Options.getMaxLengthOption().getValue();
/* */
/* */
/* */ try
/* */ {
/* 129 */ localObject1 = Parser.parse(paramString);
/* */ } catch (Parser.ParseException localParseException) {
/* 131 */ localJTextArea.setText(localParseException.getMessage());
/* 132 */ return null;
/* */ }
/* 134 */ if (this.runner.state == RUNNER_CANCELED) { return null;
/* */ }
/* */
/* 137 */ Object localObject1 = localContext1.substitute((Expr)localObject1);
/* 138 */ localJTextArea.setText(((Expr)localObject1).toStringSubstituteBelow(localContext2, i, bool1));
/* */
/* 140 */ Object localObject2 = localObject1;
/* 141 */ Object localObject3 = localObject1;
/* 142 */ int j = ((Expr)localObject1).size();
/* 143 */ Expr localExpr = Simplify.simplify((Expr)localObject1);
/* 144 */ java.util.HashSet localHashSet = new java.util.HashSet();
/* 145 */ Expr[] arrayOfExpr = new Expr[100];
/* 146 */ int k = -1;
/* 147 */ int m = 0;
/* 148 */ while (localExpr != localObject1) {
/* 149 */ localObject1 = localExpr;
/* 150 */ if (bool2) {
/* 151 */ localJTextArea.append("\n = ");
/* 152 */ localJTextArea.append(((Expr)localObject1).toString(localContext2, i, bool1));
/* */ }
/* */
/* 155 */ int n = ((Expr)localObject1).size();
/* 156 */ ExprWrapper localExprWrapper = new ExprWrapper((Expr)localObject1);
/* */
/* */
/* 159 */ m++;
/* 160 */ if ((this.runner.state == RUNNER_CANCELED) || (m > Options.getMaxReductionsOption().getValue()) || (localHashSet.contains(localExprWrapper)))
/* */ {
/* */
/* 163 */ localJTextArea.append("\n = ... ");
/* 164 */ localObject1 = localObject3;
/* 165 */ localJTextArea.append(((Expr)localObject1).toString(localContext2, i, bool1));
/* */
/* 167 */ break;
/* */ }
/* */
/* */
/* 171 */ k++;
/* 172 */ if (k == arrayOfExpr.length) k = 0;
/* 173 */ if (arrayOfExpr[k] != null) {
/* 174 */ localHashSet.remove(arrayOfExpr[k]);
/* */ }
/* 176 */ arrayOfExpr[k] = localObject1;
/* 177 */ localHashSet.add(localExprWrapper);
/* 178 */ if (n < j) {
/* 179 */ localObject3 = localObject1;
/* 180 */ j = n;
/* */ }
/* */
/* */
/* 184 */ localExpr = Simplify.simplify((Expr)localObject1);
/* */ }
/* 186 */ if (!bool2) {
/* 187 */ localJTextArea.append("\n = ");
/* 188 */ localJTextArea.append(((Expr)localObject1).toString(localContext2, i, bool1));
/* */ }
/* 190 */ return (Expr)localObject1;
/* */ }
/* */ }
/* Location: C:\Users\Chris\Google Drive\University\2015 - 3rd Year UCT\CSC\3003S\Capstone\Lambda\examples\lambda.jar!\lambda\Engine.class
* Java compiler version: 2 (46.0)
* JD-Core Version: 0.7.1
*/ | mit |
LuigiPower/iotremote | app/src/main/java/it/giuggi/iotremote/ui/adapter/DrawerItem.java | 301 | package it.giuggi.iotremote.ui.adapter;
/**
* Created by Federico Giuggioloni on 05/05/16.
* Se aggiungo questa riga magari
* AndroidStudio smette di lamentarsi...
*/
public class DrawerItem
{
protected String name;
public DrawerItem(String name)
{
this.name = name;
}
}
| mit |
mikepenz/Gitskarios | app/src/main/java/com/alorma/github/ui/activity/PurchasesFragment.java | 4648 | package com.alorma.github.ui.activity;
import android.app.Activity;
import android.app.Fragment;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import com.android.vending.billing.IInAppBillingService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.UUID;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by bernat.borras on 24/10/15.
*/
public class PurchasesFragment extends Fragment {
private static final String SKU_MULTI_ACCOUNT = "com.alorma.github.multiaccount";
private IInAppBillingService mService;
ServiceConnection mServiceConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
private String purchaseId;
private PurchasesCallback purchasesCallback;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createBillingService();
}
private void createBillingService() {
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
if (mService == null) {
getActivity().bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
}
public void checkSku(PurchasesCallback purchasesCallback) {
this.purchasesCallback = purchasesCallback;
SKUTask task = new SKUTask();
task.execute(SKU_MULTI_ACCOUNT);
}
public void finishPurchase(int requestCode, int resultCode, Intent data,
PurchasesCallback callback) {
if (requestCode == 1001) {
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
if (resultCode == Activity.RESULT_OK) {
try {
JSONObject jo = new JSONObject(purchaseData);
String sku = jo.getString("productId");
String developerPayload = jo.getString("developerPayload");
if (callback != null) {
boolean purchased =
developerPayload.equals(purchaseId) && SKU_MULTI_ACCOUNT.equals(sku);
callback.onMultiAccountPurchaseResult(purchased);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
int response_code = data.getIntExtra("RESPONSE_CODE", 0);
if (callback != null) {
callback.onMultiAccountPurchaseResult(response_code == 6);
}
}
}
}
public void showDialogBuyMultiAccount() {
try {
purchaseId = UUID.randomUUID().toString();
Bundle buyIntentBundle =
mService.getBuyIntent(3, getActivity().getPackageName(), SKU_MULTI_ACCOUNT, "inapp",
purchaseId);
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(),
0, 0, 0);
} catch (RemoteException | IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
public interface PurchasesCallback {
void onMultiAccountPurchaseResult(boolean multiAccountPurchased);
}
private class SKUTask extends AsyncTask<String, Void, Bundle> {
@Override
protected Bundle doInBackground(String... strings) {
if (strings != null) {
ArrayList<String> skuList = new ArrayList<>();
Collections.addAll(skuList, strings);
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
try {
return mService.getPurchases(3, getActivity().getPackageName(), "inapp", null);
} catch (RemoteException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Bundle ownedItems) {
super.onPostExecute(ownedItems);
if (ownedItems != null) {
int response = ownedItems.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
if (ownedSkus != null && purchasesCallback != null) {
purchasesCallback.onMultiAccountPurchaseResult(!ownedSkus.isEmpty());
}
}
}
}
}
}
| mit |
yaqwsx/nativescript-simple-networking | SimpleNetworking/library/src/main/java/cz/honzamrazek/simplenetworking/UdpServer.java | 3589 | package cz.honzamrazek.simplenetworking;
import android.util.Log;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import cz.honzamrazek.simplenetworking.UdpListener;
public class UdpServer {
private UdpListener mListener;
private ExecutorService mExecutor;
private DatagramSocket mSocket;
private AtomicInteger mId;
private byte[] mBuffer;
public UdpServer(UdpListener listener) {
mListener = listener;
mId = new AtomicInteger();
}
public DatagramSocket getNativeSocket() {
return mSocket;
}
public int start(final int port) {
final int id = mId.getAndIncrement();
mBuffer = new byte[64 * 1024 * 1024];
mExecutor = Executors.newFixedThreadPool(2);
mExecutor.submit(new Runnable() {
@Override
public void run() {
try {
mSocket = new DatagramSocket(port);
mExecutor.submit(new Runnable() {
@Override
public void run() {
receiveDatagram();
}
});
mListener.onFinished(id);
}
catch(SocketException e) {
mListener.onError(id, e.getMessage());
}
}
});
return id;
}
public int stop() {
final int id = mId.getAndIncrement();
mExecutor.submit(new Runnable() {
@Override
public void run() {
if (mSocket == null)
return;
mSocket.close();
mSocket = null;
mListener.onFinished(id);
}
});
return id;
}
public int send(final InetAddress address, final String message) {
final int id = mId.getAndIncrement();
mExecutor.submit(new Runnable() {
@Override
public void run() {
try {
byte[] buffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length,
address, mSocket.getLocalPort());
mSocket.send(packet);
mListener.onFinished(id);
}
catch(IOException e) {
mListener.onError(id, e.getMessage());
}
}
});
return id;
}
private void receiveDatagram() {
final int id = mId.getAndIncrement();
mExecutor.submit(new Runnable() {
@Override
public void run() {
try {
DatagramPacket packet = new DatagramPacket(mBuffer, mBuffer.length);
mSocket.receive(packet);
byte [] sub = Arrays.copyOfRange(packet.getData(), 0, packet.getLength());
String data = new String(sub);
InetAddress address = packet.getAddress();
mListener.onPacket(address, data);
receiveDatagram();
}
catch (IOException e) {
mListener.onError(id, e.getMessage());
}
}
});
}
} | mit |
mcunning/ACTUALLYCOSC | src/main/java/chat/ActuallyChat.java | 1303 | package main.java.chat;
import java.util.Scanner;
public class ActuallyChat implements Chat
{
boolean chat;
Responder responder;
Scanner scan;
public ActuallyChat()
{
chat = true;
scan = new Scanner( System.in );
// TODO
}//Constructor
@Override
public void initialize( Responder responderIn )
{
responder = responderIn;
responder.readConfigFile();
}//initialize
@Override
public String getSentence()
{
return scan.nextLine();
}//getSentence()
private void print( String string )
{
System.out.println( string );
}//print
@Override
public void chat()
{
//greet;
print( "Welcome to Chat." );
//chat
while( chat )
{
String sentence = getSentence();
try{
String output=responder.respond(sentence);
System.out.println(output);
}catch(IllegalArgumentException x){
System.out.println("I don't understand how to respond: an IllegalArgument keeps calling me.");
}catch(NullPointerException x){
System.out.println("I missed that. Let's pretend that last thing was null.");
}//try/catch
}//while
}//chat
}
| mit |
Nocket/nocket | src/java/org/nocket/gen/GenericMenuItem.java | 946 | package org.nocket.gen;
import java.io.Serializable;
import org.nocket.NocketWebApplication;
import org.nocket.component.menu.MenuItem;
import org.nocket.page.FactoryHelper;
// TODO: Auto-generated Javadoc
/**
* Specialized menu item class which allows to register <i>domain classes</i>
* rather than <i>page classes</i> in the application's main menu. If in-memory
* compilation and on-the-fly HTML creation is configured, neither the page
* class nor the corresponding HTML must exist in advance. See
* {@link NocketWebApplication} how to enable these features.
*
* @author less02
*/
public class GenericMenuItem extends MenuItem {
/**
* Instantiates a new generic menu item.
*
* @param label the label
* @param domainClass the domain class
*/
public GenericMenuItem(String label, Class<? extends Serializable> domainClass) {
super(label, FactoryHelper.getPageClass(domainClass));
}
}
| mit |
cab404/Chumroll | chumroll-example/src/main/java/com/cab404/chumroll/example/PagerTestFragment.java | 1113 | package com.cab404.chumroll.example;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.cab404.chumroll.ChumrollAdapter;
import com.cab404.chumroll.proxies.ChumrollPagerAdapter;
/**
* ViewPager test fragment
*
* @author cab404
*/
public class PagerTestFragment extends ChumrollTestFragment {
ChumrollPagerAdapter proxy = new ChumrollPagerAdapter();
ChumrollAdapter adapter = proxy.getAdapter();
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_pager, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((ViewPager) view.findViewById(R.id.pager)).setAdapter(proxy);
}
@Override
public ChumrollAdapter getAdapter() {
return adapter;
}
}
| mit |
SRM-Hackathon/haasil | Haasil/sdkui/src/main/java/com/payu/payuui/Adapter/PagerAdapter.java | 4674 | package com.payu.payuui.Adapter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.payu.india.Model.PayuResponse;
import com.payu.india.Payu.PayuConstants;
import com.payu.payuui.Fragment.CreditDebitFragment;
import com.payu.payuui.Fragment.LazyPayFragment;
import com.payu.payuui.Fragment.NetBankingFragment;
import com.payu.payuui.Fragment.PayuMoneyFragment;
import com.payu.payuui.Fragment.SavedCardsFragment;
import com.payu.payuui.Fragment.UPIFragment;
import com.payu.payuui.SdkuiUtil.SdkUIConstants;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by piyush on 29/7/15.
*/
public class PagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<String> mTitles;
private PayuResponse payuResponse;
private PayuResponse valueAddedResponse;
private HashMap<String, String> oneClickCardTokens;
private HashMap<Integer, Fragment> mPageReference = new HashMap<Integer, Fragment>();
public PagerAdapter(FragmentManager fragmentManager, ArrayList<String> titles, PayuResponse payuResponse, PayuResponse valueAddedResponse, HashMap<String, String> oneClickCardTokens) {
super(fragmentManager);
this.mTitles = titles;
this.payuResponse = payuResponse;
this.valueAddedResponse = valueAddedResponse;
this.oneClickCardTokens = oneClickCardTokens;
}
@Override
public Fragment getItem(int i) {
Fragment fragment = null;
Bundle bundle = new Bundle();
switch (mTitles.get(i)){
case SdkUIConstants.SAVED_CARDS :
fragment = new SavedCardsFragment();
bundle.putParcelableArrayList(PayuConstants.STORED_CARD, payuResponse.getStoredCards());
bundle.putSerializable(SdkUIConstants.VALUE_ADDED, valueAddedResponse.getIssuingBankStatus());
bundle.putInt(SdkUIConstants.POSITION, i);
bundle.putSerializable(PayuConstants.ONE_CLICK_CARD_TOKENS, oneClickCardTokens);
fragment.setArguments(bundle);
mPageReference.put(i, fragment);
return fragment;
case SdkUIConstants.CREDIT_DEBIT_CARDS:
fragment = new CreditDebitFragment();
bundle.putParcelableArrayList(PayuConstants.CREDITCARD, payuResponse.getCreditCard());
bundle.putParcelableArrayList(PayuConstants.DEBITCARD, payuResponse.getDebitCard());
bundle.putSerializable(SdkUIConstants.VALUE_ADDED, valueAddedResponse.getIssuingBankStatus());
bundle.putInt(SdkUIConstants.POSITION, i);
fragment.setArguments(bundle);
mPageReference.put(i, fragment);
return fragment;
case SdkUIConstants.NET_BANKING:
fragment = new NetBankingFragment();
bundle.putParcelableArrayList(PayuConstants.NETBANKING, payuResponse.getNetBanks());
bundle.putSerializable(SdkUIConstants.VALUE_ADDED, valueAddedResponse.getNetBankingDownStatus());
fragment.setArguments(bundle);
mPageReference.put(i, fragment);
return fragment;
case SdkUIConstants.UPI:
fragment = new UPIFragment();
bundle.putParcelableArrayList(PayuConstants.NETBANKING, payuResponse.getNetBanks());
bundle.putSerializable(SdkUIConstants.VALUE_ADDED, valueAddedResponse.getNetBankingDownStatus());
fragment.setArguments(bundle);
mPageReference.put(i, fragment);
return fragment;
case SdkUIConstants.PAYU_MONEY:
fragment = new PayuMoneyFragment();
bundle.putParcelableArrayList(PayuConstants.PAYU_MONEY, payuResponse.getPaisaWallet());
mPageReference.put(i, fragment);
return fragment;
case SdkUIConstants.LAZY_PAY:
fragment = new LazyPayFragment();
bundle.putParcelableArrayList(PayuConstants.LAZYPAY, payuResponse.getLazyPay());
mPageReference.put(i, fragment);
return fragment;
default:
return null;
}
}
@Override
public int getCount() {
if(mTitles != null)
return mTitles.size();
return 0;
}
@Override
public CharSequence getPageTitle(int position) {
return mTitles.get(position);
}
public Fragment getFragment(int key){
return mPageReference.get(key);
}
}
| mit |
christoandrew/BaalaV2 | app/src/main/java/com/iconasystems/christo/baalafinal/LoginActivity.java | 7484 | package com.iconasystems.christo.baalafinal;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.plus.PlusClient;
import com.iconasystems.christo.utils.JSONParser;
import com.iconasystems.christo.utils.SessionManager;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LoginActivity extends Activity implements PlusClient.ConnectionCallbacks, PlusClient.OnConnectionFailedListener{
private Button loginButton;
private EditText usernameField;
private EditText passwordField;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
private SignInButton mSignInButton;
private TextView mDisplayNameTextView;
private static final int DIALOG_GET_GOOGLE_PLAY_SERVICES = 1;
private static final int REQUEST_CODE_SIGN_IN = 1;
private static final int REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES = 2;
private ProgressDialog progressDialog;
private static String TAG_USERNAME = "username";
private static String TAG_PASSWORD = "password";
private static String TAG_SUCCESS = "success";
private static String TAG_MESSAGE = "message";
private static String TAG_USER_ID = "user_id";
private SessionManager session;
private JSONParser jsonParser = new JSONParser();
/*private static final String url_login = "http://api.baala-online.netii.net/login.php";*/
private static final String url_login = "http://10.0.3.2/baala/login.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
session = new SessionManager(getApplicationContext());
usernameField = (EditText) findViewById(R.id.username);
passwordField = (EditText) findViewById(R.id.password);
loginButton = (Button) findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new Login().execute();
}else {
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onDisconnected() {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public class Login extends AsyncTask<String, String, String> {
@Override
public void onPreExecute(){
super.onPreExecute();
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Signing In Please...Wait");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
public String doInBackground(String... params) {
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
List<NameValuePair> credentials = new ArrayList<NameValuePair>();
credentials.add(new BasicNameValuePair("username", username));
credentials.add(new BasicNameValuePair("password", password));
JSONObject jsonObject = jsonParser.makeHttpRequest(url_login,"POST", credentials);
Log.d("Baala Login", jsonObject.toString());
try {
int success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
final String user_id = jsonObject.getString(TAG_USER_ID);
session.createLoginSession(username,password,user_id);
Intent i = new Intent(LoginActivity.this, HomeActivity.class);
i.putExtra(TAG_USER_ID, user_id);
startActivity(i);
} else if (success == 0) {
final String message = jsonObject.getString(TAG_MESSAGE);
runOnUiThread(
new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), message , Toast.LENGTH_LONG).show();
}
}
);
} else if (success == 2) {
final String message = jsonObject.getString(TAG_MESSAGE);
runOnUiThread(
new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), message , Toast.LENGTH_LONG).show();
}
}
);
} else if (success == 3) {
final String message = jsonObject.getString(TAG_MESSAGE);
runOnUiThread(
new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), message , Toast.LENGTH_LONG).show();
}
}
);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
public void onPostExecute(String result) {
progressDialog.dismiss();
}
}
}
| mit |
Hexeption/Youtube-Hacked-Client-1.8 | minecraft/net/minecraft/client/gui/ScaledResolution.java | 1790 | package net.minecraft.client.gui;
import net.minecraft.client.Minecraft;
import net.minecraft.util.MathHelper;
public class ScaledResolution
{
private final double scaledWidthD;
private final double scaledHeightD;
private int scaledWidth;
private int scaledHeight;
private int scaleFactor;
private static final String __OBFID = "CL_00000666";
public ScaledResolution(Minecraft mcIn, int p_i46324_2_, int p_i46324_3_)
{
this.scaledWidth = p_i46324_2_;
this.scaledHeight = p_i46324_3_;
this.scaleFactor = 1;
boolean var4 = mcIn.isUnicode();
int var5 = mcIn.gameSettings.guiScale;
if (var5 == 0)
{
var5 = 1000;
}
while (this.scaleFactor < var5 && this.scaledWidth / (this.scaleFactor + 1) >= 320 && this.scaledHeight / (this.scaleFactor + 1) >= 240)
{
++this.scaleFactor;
}
if (var4 && this.scaleFactor % 2 != 0 && this.scaleFactor != 1)
{
--this.scaleFactor;
}
this.scaledWidthD = (double)this.scaledWidth / (double)this.scaleFactor;
this.scaledHeightD = (double)this.scaledHeight / (double)this.scaleFactor;
this.scaledWidth = MathHelper.ceiling_double_int(this.scaledWidthD);
this.scaledHeight = MathHelper.ceiling_double_int(this.scaledHeightD);
}
public int getScaledWidth()
{
return this.scaledWidth;
}
public int getScaledHeight()
{
return this.scaledHeight;
}
public double getScaledWidth_double()
{
return this.scaledWidthD;
}
public double getScaledHeight_double()
{
return this.scaledHeightD;
}
public int getScaleFactor()
{
return this.scaleFactor;
}
}
| mit |
indiecastfm/react-native-audio-streamer | android/src/main/java/fm/indiecast/rnaudiostreamer/RNAudioStreamerPackage.java | 1029 |
package fm.indiecast.rnaudiostreamer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNAudioStreamerPackage implements ReactPackage {
private Class<?> clsActivity;
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new RNAudioStreamerModule(reactContext));
return modules;
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList();
}
} | mit |
mmnaseri/spring-data-mock | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/repository/DefaultJpaRepositoryTest.java | 5834 | package com.mmnaseri.utils.spring.data.repository;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableRepositoryMetadata;
import com.mmnaseri.utils.spring.data.domain.impl.key.UUIDKeyGenerator;
import com.mmnaseri.utils.spring.data.error.EntityMissingKeyException;
import com.mmnaseri.utils.spring.data.sample.mocks.Operation;
import com.mmnaseri.utils.spring.data.sample.mocks.SpyingDataStore;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.repositories.SimplePersonRepository;
import com.mmnaseri.utils.spring.data.store.DataStore;
import com.mmnaseri.utils.spring.data.store.impl.MemoryDataStore;
import org.hamcrest.Matchers;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import static com.mmnaseri.utils.spring.data.utils.TestUtils.iterableToList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/11/16, 1:16 PM)
*/
public class DefaultJpaRepositoryTest {
private RepositoryMetadata repositoryMetadata;
private DefaultJpaRepository repository;
private DataStore<String, Person> dataStore;
@BeforeMethod
public void setUp() {
repositoryMetadata = new ImmutableRepositoryMetadata(String.class, Person.class, SimplePersonRepository.class,
"id");
dataStore = new MemoryDataStore<>(Person.class);
repository = new DefaultJpaRepository();
repository.setDataStore(dataStore);
repository.setRepositoryMetadata(repositoryMetadata);
repository.setKeyGenerator(new UUIDKeyGenerator());
}
@Test
public void testFlushing() {
final DefaultJpaRepository repository = new DefaultJpaRepository();
repository.setKeyGenerator(new UUIDKeyGenerator());
repository.setRepositoryMetadata(repositoryMetadata);
final SpyingDataStore<Object, Object> dataStore = new SpyingDataStore<>(null, new AtomicLong());
repository.setDataStore(dataStore);
repository.flush();
assertThat(dataStore.getRequests(), hasSize(1));
assertThat(dataStore.getRequests().get(0).getOperation(), is(Operation.FLUSH));
}
@Test
public void testDeleteInBatch() {
dataStore.save("1", new Person());
dataStore.save("2", new Person());
dataStore.save("3", new Person());
dataStore.save("4", new Person());
final List<String> existingIds = Arrays.asList("2", "3");
final List<String> missingIds = Arrays.asList("5", "6");
final List<Person> request = new ArrayList<>();
for (String id : existingIds) {
request.add(new Person().setId(id));
}
for (String id : missingIds) {
request.add(new Person().setId(id));
}
final List<Person> expected = new ArrayList<>();
for (String id : existingIds) {
expected.add(dataStore.retrieve(id));
}
for (String existingId : existingIds) {
assertThat(dataStore.hasKey(existingId), is(true));
}
final List<?> deleted = iterableToList(repository.deleteInBatch(request));
assertThat(deleted, hasSize(existingIds.size()));
for (Object item : deleted) {
assertThat(item, is(instanceOf(Person.class)));
assertThat((Person) item, isIn(expected));
}
}
@Test(expectedExceptions = EntityMissingKeyException.class)
public void testDeleteInBatchWhenIdIsNull() {
repository.deleteInBatch(Collections.singleton(new Person()));
}
@Test
public void testDeleteAllInBatch() {
dataStore.save("1", new Person());
dataStore.save("2", new Person());
dataStore.save("3", new Person());
dataStore.save("4", new Person());
assertThat(dataStore.keys(), hasSize(4));
repository.deleteAllInBatch();
assertThat(dataStore.keys(), is(empty()));
}
@Test
public void testDeleteInBatchWithQueueing() {
final SpyingDataStore<String, Person> dataStore = new SpyingDataStore<>(
new MemoryDataStore<>(Person.class), new AtomicLong());
dataStore.save("1", new Person());
dataStore.save("2", new Person());
dataStore.save("3", new Person());
dataStore.save("4", new Person());
repository.setDataStore(dataStore);
assertThat(dataStore.keys(), hasSize(4));
repository.deleteAllInBatch();
assertThat(dataStore.keys(), is(empty()));
}
@Test
public void testGetOne() {
final String key = "1234";
assertThat(repository.getOne(key), is(nullValue()));
final Person person = new Person();
dataStore.save("1234", person);
assertThat(repository.getOne(key), Matchers.is(person));
}
@Test
public void testSaveAndFlush() {
final DefaultJpaRepository repository = new DefaultJpaRepository();
repository.setKeyGenerator(new UUIDKeyGenerator());
repository.setRepositoryMetadata(repositoryMetadata);
final SpyingDataStore<String, Person> dataStore = new SpyingDataStore<>(this.dataStore, new AtomicLong());
repository.setDataStore(dataStore);
final Person entity = new Person().setId("1");
repository.saveAndFlush(entity);
assertThat(dataStore.getRequests().get(dataStore.getRequests().size() - 1).getOperation(), is(Operation.FLUSH));
assertThat(dataStore.retrieve("1"), is(entity));
}
} | mit |
myid999/struts2demo | s2ia/src/manning/chapterSeven/ViewPortfolio.java | 2783 | package manning.chapterSeven;
import manning.chapterSeven.utils.Portfolio;
import manning.chapterSeven.utils.PortfolioService;
import manning.chapterSeven.utils.User;
import com.opensymphony.xwork2.ActionSupport;
/*
* This action retrieves the data model for viewing a particular portfolio.
*/
public class ViewPortfolio extends ActionSupport {
public String execute(){
/*
* Create and move the data onto our application domain object, user.
*/
portfolio = getPortfolioService().getPortfolio ( getUsername(), getPortfolioName() );
return SUCCESS;
}
/* JavaBeans Properties to Receive Request Parameters */
private String username;
private String portfolioName;
private Portfolio portfolio;
public String getPortfolioName() {
return portfolioName;
}
public void setPortfolioName(String portfolioName) {
this.portfolioName = portfolioName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Portfolio getPortfolio(){
return portfolio;
}
/* Validateable Implmentation
*
* The validate method validates, invoked by the validation intercptor in
* the default stack, will validate the data already set on the action
* by the params interceptor, also in the default stack.
*
* If this method finds problems in validation it stores error messages via
* the methods exposed by the ValidationAware interface -- already implemented
* by the ActionSupport class that this action extends. To complete the
* the validation process, the workflow interceptor fires next in the default
* stack. It checks for error messages on the action, and if it finds them
* it diverts workflow back to the input page where the error messages are
* displayed to the user. In this case, the execute method of the action
* will not be called because the workflow was diverted, due to validation
* problems, before execution reached the action itself.
*
* */
public void validate(){
/* Retrieve our simple portfolio service object. */
PortfolioService ps = getPortfolioService();
if ( getUsername().length() == 0 ){
addFieldError( "username", getText("username.required") );
}
if ( getPortfolioName().length() == 0 ){
addFieldError( "portfolioName", getText( "portfolioName.required" ));
}
}
/*
* Simple way to retrieve our business logic and data peristence
* object. Late versions of the portfolio app will intergrate with
* more sophisticated technologies for these services.
*/
public PortfolioService getPortfolioService( ) {
return new PortfolioService();
}
}
| mit |
edwise/java-pocs | springboot-series-actuator/src/main/java/com/edwise/springbootseries/actuator/Application.java | 408 | package com.edwise.springbootseries.actuator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| mit |
indiecastfm/react-native-audio-streamer | android/src/test/java/fm/indiecast/rnaudiostreamer/ExampleUnitTest.java | 406 | package fm.indiecast.rnaudiostreamer;
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 |
jayhorn/jayhorn | jayhorn/src/test/resources/horn-encoding/backlog/SatDilligAbduction01.java | 190 | public class SatDilligAbduction01 {
public static void main(String[] args) {
int x=0;
int y=0;
int n = args.length;
while(x<n) {
x+=1;
y+=2;
}
assert(x+y==3*n);
}
}
| mit |
QubeX2/JavaGames | MgNet/src/com/magegrid/net/StreamManager.java | 770 | package com.magegrid.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class StreamManager {
public void sendBytes(OutputStream output, byte[] buf) {
try {
byte[] bufSend = new byte[buf.length+1];
bufSend[0] = (byte)buf.length;
for(int i=0;i<buf.length;i++)
bufSend[i+1] = buf[i];
output.write(bufSend);
} catch (IOException e) {
}
}
public byte[] getBytes(InputStream input) {
byte[] buf = new byte[0];
try {
int l = input.read();
buf = new byte[l];
int off = 0;
for(int i=0;i<(l);i++){
buf[off++] = (byte)input.read();
}
} catch (IOException e) {
} catch (NegativeArraySizeException e) {
}
return buf;
}
}
| mit |
tfunato/vicuna | src/main/java/jp/canetrash/vicuna/entity/DamagePortalEntity.java | 1504 | package jp.canetrash.vicuna.entity;
import java.io.Serializable;
import java.util.Date;
/**
* @author tfunato
*
*/
public class DamagePortalEntity implements Serializable {
/** serialVersionUID */
private static final long serialVersionUID = 6742715802503773598L;
private String messageId;
private Integer seq;
private String portalId;
private Date createDate;
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public Integer getSeq() {
return seq;
}
public void setSeq(Integer seq) {
this.seq = seq;
}
public String getPortalId() {
return portalId;
}
public void setPortalId(String portalId) {
this.portalId = portalId;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public DamagePortalKey getPrimaryKey() {
return new DamagePortalKey(messageId, seq);
}
public class DamagePortalKey implements Serializable {
private static final long serialVersionUID = 1L;
private String messageId;
private Integer seq;
public DamagePortalKey(String messageId, Integer seq) {
this.messageId = messageId;
this.seq = seq;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public Integer getSeq() {
return seq;
}
public void setSeq(Integer seq) {
this.seq = seq;
}
}
}
| mit |
metricAppTeam/metricapp-server | src/main/java/metricapp/dto/team/TeamMap.java | 605 | package metricapp.dto.team;
import org.modelmapper.PropertyMap;
import metricapp.entity.stakeholders.Team;
public class TeamMap extends PropertyMap<Team, TeamDTO>{
@Override
protected void configure() {
map().setId(source.getId());
//map().setExpert(source.getExpert());
//map().setMetricators(source.getMetricators());
map().setGridName(source.getGridName());
map().setName(source.getName());
//map().setQuestioners(source.getQuestioners());
//map().setTsCreate(source.getTsCreate());
//map().setTsUpdate(source.getTsUpdate());
map().setExtrauser(source.getExtrauser());
}
}
| mit |
gdcpljh/the-tech-frontier-app | src/com/tech/frontier/models/entities/Article.java | 1354 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 Umeng, Inc
*
* 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.tech.frontier.models.entities;
public class Article {
public String title;
public String publishTime;
public String author;
public String post_id;
public int category ;
}
| mit |
LCA311/leoapp-sources | app/src/main/java/de/slgdev/it_problem/task/SynchronizerDownstreamTask.java | 4525 | package de.slgdev.it_problem.task;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Hashtable;
import de.slgdev.it_problem.utility.datastructure.DecisionTree;
import de.slgdev.leoapp.sqlite.SQLiteConnectorITProblem;
import de.slgdev.leoapp.task.general.TaskStatusListener;
import de.slgdev.leoapp.utility.NetworkUtils;
import de.slgdev.leoapp.utility.Utils;
import de.slgdev.leoapp.utility.datastructure.List;
public class SynchronizerDownstreamTask extends AsyncTask<String, Void, Void> {
private Hashtable<String, DecisionTree> decisionTreeMap;
private List<TaskStatusListener> listeners;
public SynchronizerDownstreamTask(Hashtable<String, DecisionTree> decisionTreeMap) {
this.decisionTreeMap = decisionTreeMap;
listeners = new List<>();
}
@Override
protected Void doInBackground(String... subjects) {
Utils.logError("BACKGROUND START");
SQLiteConnectorITProblem db = new SQLiteConnectorITProblem(Utils.getContext());
if (NetworkUtils.isNetworkAvailable()) {
SQLiteDatabase dbh = db.getWritableDatabase();
for (String subject : subjects) {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new URL(
Utils.DOMAIN_DEV + "itbaum/" +
"get.php?" +
"subject=" + subject
)
.openConnection()
.getInputStream(),
"UTF-8"
)
);
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
builder.append(line);
reader.close();
String result = builder.toString();
if (result.startsWith("-"))
continue;
dbh.insertWithOnConflict(
SQLiteConnectorITProblem.TABLE_DECISIONS,
null,
db.getContentValues(
subject,
result.substring(
0,
result.length() - 1
)
),
SQLiteDatabase.CONFLICT_REPLACE
);
} catch (IOException e) {
e.printStackTrace();
}
}
dbh.close();
}
SQLiteDatabase dbh = db.getReadableDatabase();
Cursor c = dbh.rawQuery("SELECT "
+ SQLiteConnectorITProblem.DECISION_SUBJECT
+ ", "
+ SQLiteConnectorITProblem.DECISIONS_CONTENT
+ " FROM "
+ SQLiteConnectorITProblem.TABLE_DECISIONS,
null
);
c.moveToFirst();
while (!c.isAfterLast()) {
decisionTreeMap.put(
c.getString(0),
new DecisionTree(
c.getString(1)
)
);
c.moveToNext();
}
c.close();
fillMissingTrees(subjects);
return null;
}
@Override
public void onPostExecute(Void result) {
Utils.logError("FINISHED TASK");
for (TaskStatusListener listener : listeners)
listener.taskFinished();
}
public SynchronizerDownstreamTask addListener(TaskStatusListener listener) {
listeners.append(listener);
return this;
}
private void fillMissingTrees(String[] subjects) {
Utils.logError("FILLED");
for (String cur : subjects) {
if (decisionTreeMap.get(cur) == null) {
decisionTreeMap.put(cur, new DecisionTree());
}
Utils.logError(cur + ": " + decisionTreeMap.get(cur));
}
}
}
| mit |
djkeyes/battlecode2015bot | Battlecode/teams/soldierrush/RobotPlayer.java | 231 | package soldierrush;
import battlecode.common.RobotController;
public class RobotPlayer {
public static void run(RobotController rc) {
BaseRobotHandler myHandler = BaseRobotHandler.createHandler(rc);
myHandler.run();
}
}
| mit |
tylerchen/springmvc-mybatis-v1.0-project | src/main/java/org/iff/infra/util/ValidateHelper.java | 1235 | /*******************************************************************************
* Copyright (c) 2014-10-10 @author <a href="mailto:iffiff1@gmail.com">Tyler Chen</a>.
* All rights reserved.
*
* Contributors:
* <a href="mailto:iffiff1@gmail.com">Tyler Chen</a> - initial API and implementation
******************************************************************************/
package org.iff.infra.util;
import java.util.regex.Pattern;
/**
* A validate helper provides a set of utility methods to validate the data.
* @author <a href="mailto:iffiff1@gmail.com">Tyler Chen</a>
* @since 2014-10-10
*/
public class ValidateHelper {
/** Email regex **/
private static final String regex_email = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
/** Email pattern **/
private static final Pattern pattern_email = Pattern.compile(regex_email);
/**
* Verify whether the input is Email
* @param email
* @return
* @author <a href="mailto:iffiff1@gmail.com">Tyler Chen</a>
* @since 2015-2-6
*/
public static boolean email(CharSequence email) {
return pattern_email.matcher(email).matches();
}
}
| mit |
cucumber/cucumber-jvm | java8/src/main/java/io/cucumber/java8/Java8ParameterInfo.java | 621 | package io.cucumber.java8;
import io.cucumber.core.backend.ParameterInfo;
import io.cucumber.core.backend.TypeResolver;
import java.lang.reflect.Type;
final class Java8ParameterInfo implements ParameterInfo {
private final LambdaTypeResolver typeResolver;
Java8ParameterInfo(LambdaTypeResolver typeResolver) {
this.typeResolver = typeResolver;
}
public Type getType() {
return typeResolver.getType();
}
@Override
public boolean isTransposed() {
return false;
}
@Override
public TypeResolver getTypeResolver() {
return typeResolver;
}
}
| mit |
mes32/plot-1d | src/plot1d/gui/BorderBox.java | 2437 | /*
BorderBox.java
This class is part of the program plot-1d
*/
package plot1d.gui;
import java.awt.*;
/**
* This represents a rectangular region with a border inside the main GUI panel. This rectangular
* box encloses the plotted data points and the plot axes. Additional annotation of the plot (title,
* axes labels, unit labels, etc) occupy other areas of the GUI panel surrounding this box.
*/
public class BorderBox {
private static final Color BORDER_COLOR = Color.black;
private static final int MARGIN_TOP = 10;
private static final int MARGIN_BOTTOM = 80;
private static final int MARGIN_LEFT = 80;
private static final int MARGIN_RIGHT = 10;
private int x;
private int y;
private int height;
private int width;
public BorderBox(Dimension panelSize) {
int panelWidth = (int)panelSize.getWidth();
int panelHeight = (int)panelSize.getHeight();
width = panelWidth - MARGIN_RIGHT - MARGIN_LEFT;
height = panelHeight - MARGIN_TOP - MARGIN_BOTTOM;
x = MARGIN_LEFT;
y = MARGIN_TOP;
}
/**
* Returns the width in pixels of the rectanglar region enclosed by this border box
*/
public int getWidth() {
return width;
}
/**
* Returns the height in pixels of the rectanglar region enclosed by this border box
*/
public int getHeight() {
return height;
}
/**
* Returns the top-most position of this rectanglar region. This position is in pixels relative
* to the enclosing frame.
*/
public int getTop() {
return y;
}
/**
* Returns the bottom-most position of this rectanglar region. This position is in pixels
* relative to the enclosing frame.
*/
public int getBottom() {
return y + height;
}
/**
* Returns the left-most position of this rectanglar region. This position is in pixels relative
* to the enclosing frame.
*/
public int getLeft() {
return x;
}
/**
* Returns the right-most position of this rectanglar region. This position is in pixels
* relative to the enclosing frame.
*/
public int getRight() {
return x + width;
}
/**
* Draws this box with a border onto the GUI
*/
public void draw(Graphics g) {
g.setColor(BORDER_COLOR);
g.drawRect(x, y, width, height);
}
}
| mit |
LevonTopakbashyan/SoftUni | Java/Java_Programming_Basics/src/ArraysExercises/p07_MostMetElement.java | 1396 | package ArraysExercises;
import java.util.Scanner;
public class p07_MostMetElement {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int n = console.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = console.nextInt();
}
for (int i = 0; i < numbers.length -1; i++) {
int index = i;
for (int j = i+1; j < numbers.length; j++) {
if (numbers[j] < numbers[index]){
index = j;
}
}
int smallerNumber = numbers[index];
numbers[index] = numbers[i];
numbers[i] = smallerNumber;
}
int currentLength = 1;
int bestLength = 1;
int position = 0;
int bestPosition = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] == numbers[i-1]){
currentLength++;
if (currentLength > bestLength){
bestLength = currentLength;
bestPosition = position;
}
}else {
currentLength = 1;
position = i;
}
}
System.out.println("Element is: " + numbers[bestPosition]);
System.out.println(bestLength + " times");
}
}
| mit |
thibaultCha/TweetStats | TweetStats/src/test/java/fr/ece/tweetstats/core/serviceapi/FetchServiceTest.java | 3003 | package fr.ece.tweetstats.core.serviceapi;
import fr.ece.tweetstats.core.domain.Fetch;
import fr.ece.tweetstats.core.serviceapi.FetchService;
import java.util.List;
import java.util.Set;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sculptor.framework.accessimpl.mongodb.DbManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
/**
* Spring based test with MongoDB.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext-test.xml" })
public class FetchServiceTest extends AbstractJUnit4SpringContextTests implements FetchServiceTestBase {
@Autowired
private DbManager dbManager;
@Autowired
private FetchService fetchService;
private Fetch fetch;
private String fetchId;
@Before
public void initTestData() {
fetch = new Fetch();
fetch.setBrand("RATP");
fetch.setAdjective("grève");
fetch.setLastFetchDate(new LocalDate());
fetch.setLastId(1L);
fetchService.save(fetch);
fetchId = fetch.getId();
}
@Before
public void initDbManagerThreadInstance() throws Exception {
// to be able to do lazy loading of associations inside test class
DbManager.setThreadInstance(dbManager);
}
@After
public void dropDatabase() {
Set<String> names = dbManager.getDB().getCollectionNames();
for (String each : names) {
if (!each.startsWith("system")) {
dbManager.getDB().getCollection(each).drop();
}
}
dbManager.getDB().dropDatabase();
}
private int countRowsInDBCollection(String name) {
return (int) dbManager.getDBCollection(name).getCount();
}
@Test
public void testGetFetchesWithBrandAndAdjective() throws Exception {
List<Fetch> fetches = fetchService.getFetchesWithBrandAndAdjective("RATP", "grève");
assertTrue(fetches instanceof List);
assertEquals(1, fetches.size());
}
@Test
public void testFindById() throws Exception {
Fetch findFetch = fetchService.findById(fetchId);
assertEquals("RATP", findFetch.getBrand());
}
@Test
public void testFindAll() throws Exception {
List<Fetch> fetches = fetchService.findAll();
assertTrue(fetches instanceof List);
}
@Test
public void testSave() throws Exception {
Fetch savedFetch = new Fetch();
savedFetch.setBrand("Alloresto");
savedFetch.setAdjective("retard");
savedFetch.setLastFetchDate(new LocalDate());
savedFetch.setLastId(1L);
fetchService.save(savedFetch);
assertNotEquals(savedFetch.getId(), null);
}
@Test
public void testDelete() throws Exception {
fetchService.delete(fetch);
List<Fetch> fetches = fetchService.findAll();
assertEquals(0, fetches.size());
}
}
| mit |
AndreasKl/spring-playground | spring-boot-batch-sample/src/main/java/net/andreaskluth/batch/WriterConfiguration.java | 765 | package net.andreaskluth.batch;
import java.util.List;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WriterConfiguration {
@Bean
@StepScope
public ItemWriter<String> writer(@Value("#{jobParameters[hello]}") String text) {
System.out.println("Writer JobParam: " + text);
return new ItemWriter<String>() {
@Override
public void write(List<? extends String> value) throws Exception {
System.out.println("From Reader: " + value);
}
};
}
}
| mit |
bedisdover/ESS | application/src/main/java/cn/edu/nju/dao/examDAO/StudentDAOImpl.java | 1893 | package cn.edu.nju.dao.examDAO;
import cn.edu.nju.dao.DataException;
import cn.edu.nju.mapper.examMapper.StudentMapper;
import cn.edu.nju.model.examModel.StudentModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by Jiayiwu on 17/11/13.
* Mail:wujiayi@lgdreamer.com
* Change everywhere
*/
@Service(value = "studentDAO")
public class StudentDAOImpl implements IStudentDAO {
private final StudentMapper studentMapper;
@Autowired
public StudentDAOImpl(@Qualifier("studentMapper") StudentMapper studentMapper) {
this.studentMapper = studentMapper;
}
@Override
public List<StudentModel> getCourseStudents(
int courseId) throws DataException {
try {
return studentMapper.getCourseStudents(courseId);
} catch (Exception e) {
throw new DataException("该课程不存在");
}
}
@Override
public void deleteCourseStudents(
int courseId, List<String> emails) throws Exception {
studentMapper.deleteCourseStudents(courseId, emails);
}
@Override
public List<StudentModel> getExamStudents(
int examId, int courseId) throws DataException {
try {
return studentMapper.getExamStudents(examId, courseId);
} catch (Exception e) {
throw new DataException("该考试不存在");
}
}
@Override
public boolean isStudentFileMD5Exist(String md5Value) {
return studentMapper.getStudentMD5Count(md5Value) > 0;
}
@Override
public void updateStudents(List<StudentModel> students) throws Exception {
for (StudentModel student : students) {
studentMapper.updateStudent(student);
}
}
}
| mit |
dranawhite/test-java | test-basic/test-algorithm/src/main/java/com/dranawhite/algorithm/pseudo/PseudoRandomSequence.java | 448 | package com.dranawhite.algorithm.pseudo;
/**
* 伪随机序列
*
* @author liangyq
* @version [1.0, 2018/4/24 10:52]
*/
public class PseudoRandomSequence {
/**
* 平方取中法
* <pre>
* 输入一个4位十进制,平方后,补足8位,取中间4位输出
* </pre>
*
* @param rand 初始值
*
* @return 随机数
*/
public int getMiddleSquare(int rand) {
rand = rand * rand;
return rand / 100 % 10000;
}
}
| mit |
talandar/ManaFluidics | src/main/java/derpatiel/manafluidics/spell/cantrip/CreateWater.java | 1217 | package derpatiel.manafluidics.spell.cantrip;
import derpatiel.manafluidics.spell.BlockTargetedSpell;
import derpatiel.manafluidics.spell.SpellAttribute;
import derpatiel.manafluidics.spell.parameters.SpellParameterChoices;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import java.util.Collection;
public class CreateWater extends BlockTargetedSpell {
public CreateWater() {
super("createwater", 0, 1, SpellAttribute.CONJURATION,SpellAttribute.WATER);
}
@Override
public boolean doCastOnHit(BlockPos hitBlock, EnumFacing hitFace, World world, EntityPlayer player, boolean boosted, Collection<SpellParameterChoices> parameters) {
BlockPos adjBlockPos = hitBlock.offset(hitFace);
IBlockState state = world.getBlockState(adjBlockPos);
if (state.getMaterial() == Material.AIR) {
world.setBlockState(adjBlockPos, Blocks.WATER.getDefaultState(), 3);
return true;
}
return false;
}
}
| mit |
venanciolm/afirma-ui-miniapplet_x_x | afirma_ui_miniapplet/src/main/java/es/gob/jmulticard/jse/provider/ceres/CeresProvider.java | 6619 | package es.gob.jmulticard.jse.provider.ceres;
import java.security.Provider;
import java.security.ProviderException;
import es.gob.jmulticard.apdu.connection.ApduConnection;
import es.gob.jmulticard.card.fnmt.ceres.Ceres;
/** Proveedor criptográfico JCA para tarjeta FNMT-RCM.CERES.
* Crea dos servicios:
* <dl>
* <dt><code>KeyStore</code></dt>
* <dd><i>CERES</i></dd>
* <dt><code>Signature</code></dt>
* <dd><i>SHA1withRSA</i>, <i>SHA256withRSA</i>, <i>SHA384withRSA</i>, <i>SHA512withRSA</i></dd>
* </dl>
* @author Tomás García-Merás */
public final class CeresProvider extends Provider {
private static final String SHA512WITH_RSA = "SHA512withRSA"; //$NON-NLS-1$
private static final String SHA384WITH_RSA = "SHA384withRSA"; //$NON-NLS-1$
private static final String SHA256WITH_RSA = "SHA256withRSA"; //$NON-NLS-1$
private static final String SHA1WITH_RSA = "SHA1withRSA"; //$NON-NLS-1$
private static final String ES_GOB_JMULTICARD_CARD_CERES_PRIVATE_KEY = "es.gob.jmulticard.jse.provider.ceres.CeresPrivateKey"; //$NON-NLS-1$
private static final long serialVersionUID = -1046745919235177156L;
private static final String INFO = "Proveedor para tarjeta FNMT-RCM-CERES"; //$NON-NLS-1$
private static final double VERSION = 0.1d;
private static final String NAME = "CeresJCAProvider"; //$NON-NLS-1$
private static ApduConnection defaultConnection = null;
/** Obtiene de forma estática el tipo de conexión de APDU que debe usar el <i>keyStore</i>.
* Si es nula (se ha invocado al constructor por defecto), es el propio <code>KeyStore</code> el que decide que
* conexión usar.
* @return Conexión por defecto */
static ApduConnection getDefaultApduConnection() {
return defaultConnection;
}
/** Crea un proveedor JCA para tarjeta FNMT-RCM-CERES con la conexión por defecto. */
public CeresProvider() {
this(null);
}
/** Crea un proveedor JCA para tarjeta FNMT-RCM-CERES.
* @param conn Conexión a usar para el envío y recepción de APDU. */
public CeresProvider(final ApduConnection conn) {
super(NAME, VERSION, INFO);
try {
defaultConnection = conn == null ?
(ApduConnection) Class.forName("es.gob.jmulticard.jse.smartcardio.SmartcardIoConnection").newInstance() : //$NON-NLS-1$
conn;
}
catch (final Exception e) {
throw new ProviderException(
"No se ha proporcionado una conexion con un lector y no ha podido instanciarse la por defecto: " + e, e //$NON-NLS-1$
);
}
try {
Ceres.connect(defaultConnection);
defaultConnection.close();
}
catch (final Exception e) {
throw new ProviderException(
"No se ha podido conectar con la tarjeta CERES: " + e, e //$NON-NLS-1$
);
}
// KeyStore
put("KeyStore.CERES", "es.gob.jmulticard.jse.provider.ceres.CeresKeyStoreImpl"); //$NON-NLS-1$ //$NON-NLS-2$
// Motores de firma
put("Signature.SHA1withRSA", "es.gob.jmulticard.jse.provider.ceres.CeresSignatureImpl$Sha1"); //$NON-NLS-1$ //$NON-NLS-2$
put("Signature.SHA256withRSA", "es.gob.jmulticard.jse.provider.ceres.CeresSignatureImpl$Sha256"); //$NON-NLS-1$ //$NON-NLS-2$
put("Signature.SHA384withRSA", "es.gob.jmulticard.jse.provider.ceres.CeresSignatureImpl$Sha384"); //$NON-NLS-1$ //$NON-NLS-2$
put("Signature.SHA512withRSA", "es.gob.jmulticard.jse.provider.ceres.CeresSignatureImpl$Sha512"); //$NON-NLS-1$ //$NON-NLS-2$
// Claves soportadas
put("Signature.SHA1withRSA SupportedKeyClasses", CeresProvider.ES_GOB_JMULTICARD_CARD_CERES_PRIVATE_KEY); //$NON-NLS-1$
put("Signature.SHA256withRSA SupportedKeyClasses", CeresProvider.ES_GOB_JMULTICARD_CARD_CERES_PRIVATE_KEY); //$NON-NLS-1$
put("Signature.SHA384withRSA SupportedKeyClasses", CeresProvider.ES_GOB_JMULTICARD_CARD_CERES_PRIVATE_KEY); //$NON-NLS-1$
put("Signature.SHA512withRSA SupportedKeyClasses", CeresProvider.ES_GOB_JMULTICARD_CARD_CERES_PRIVATE_KEY); //$NON-NLS-1$
// Alias de los nombres de algoritmos de firma
put("Alg.Alias.Signature.1.2.840.113549.1.1.5", CeresProvider.SHA1WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.5", CeresProvider.SHA1WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.1.3.14.3.2.29", CeresProvider.SHA1WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHAwithRSA", CeresProvider.SHA1WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-1withRSA", CeresProvider.SHA1WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA1withRSAEncryption", CeresProvider.SHA1WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-1withRSAEncryption", CeresProvider.SHA1WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.1.2.840.113549.1.1.11", CeresProvider.SHA256WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.11", CeresProvider.SHA256WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-256withRSA", CeresProvider.SHA256WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-256withRSAEncryption", CeresProvider.SHA256WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA256withRSAEncryption", CeresProvider.SHA256WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.1.2.840.113549.1.1.12", CeresProvider.SHA384WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.12", CeresProvider.SHA384WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-384withRSA", CeresProvider.SHA384WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-384withRSAEncryption", CeresProvider.SHA384WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA384withRSAEncryption", CeresProvider.SHA384WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.1.2.840.113549.1.1.13", CeresProvider.SHA512WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.13", CeresProvider.SHA512WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-512withRSA", CeresProvider.SHA512WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA-512withRSAEncryption", CeresProvider.SHA512WITH_RSA); //$NON-NLS-1$
put("Alg.Alias.Signature.SHA512withRSAEncryption", CeresProvider.SHA512WITH_RSA); //$NON-NLS-1$
}
} | mit |
ahuh/subzero | subzero-core/src/main/java/org/subzero/core/plugin/SubLeecherAddicted.java | 11231 | package org.subzero.core.plugin;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.IllegalCharsetNameException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.subzero.core.bean.SubSearchResult;
import org.subzero.core.bean.SubTitleInfo;
import org.subzero.core.bean.TvShowInfo;
import org.subzero.core.helper.TvShowInfoHelper;
import org.subzero.core.subleecher.SubLeecherBase;
import org.subzero.core.subleecher.SubLeecherHelper;
/**
* SubLeecher plugin for web site http://www.addic7ed.com
* @author Julien
*
*/
public class SubLeecherAddicted extends SubLeecherBase {
/**
* Logger
*/
private static Logger log = Logger.getLogger(SubLeecherAddicted.class);
// Constants
private static final String SITE_NAME = "Addicted";
private static final String ADDIC7ED_URL = "http://www.addic7ed.com";
private static final int QUERY_TIME_OUT = 30000;
private static final String ALT_DOWNLOAD_CHARSET = "UTF-8";
/**
* Extract the number of download from the search results description
* @param description Addicted description example : 48 times edited · 52 Downloads · 979 sequences
* @return
*/
private int extractNbDownloads(String description)
{
if (description == null || description.equals("")) {
return 0;
}
// Iterate through parts of descriptions delimited by "·"
for (String descriptionPart : description.split("·"))
{
if (SubLeecherHelper.looseMatchContains(descriptionPart, "downloads")) {
// Return the number if part contains "Downloads"
return Integer.parseInt(SubLeecherHelper.keepOnlyDigits(descriptionPart));
}
}
return 0;
}
/**
* Leech the subtitles of the TV show from the web site
* @return Output file name and language of the leeched subtitle or null if no subtitle found
*
*/
@Override
public SubTitleInfo leechSub()
{
try
{
log.debug(String.format("SubLeecher %s - Start - File='%s' ; Language='%s'", SITE_NAME, this.tvShowInfo.getInputVideoFileName(), this.subLanguage));
String episode = TvShowInfoHelper.getShortNameTypeX(this.tvShowInfo);
// ********************************************
// 1 - Search Page
// Connect to search page & search the episode
String searchUrl = ADDIC7ED_URL + "/search.php?search=" + episode;
log.debug(String.format("Search for episode '%s' at URL '%s' ...", episode, searchUrl));
Response respSearch = Jsoup.connect(searchUrl)
.followRedirects(false)
.timeout(QUERY_TIME_OUT)
.ignoreHttpErrors(true)
.execute();
//.get();
String redirectLocation = respSearch.header("Location");
if (redirectLocation != null) {
// Direct access to episode page
searchUrl = ADDIC7ED_URL + "/" + redirectLocation;
log.debug(String.format("Redirect to episode direct access at URL '%s' ...", searchUrl));
respSearch = Jsoup.connect(searchUrl)
.timeout(QUERY_TIME_OUT)
.execute();
}
Document docSearch = null;
Document docEpisode = null;
String episodeUrl = null;
String respSearchUrl = respSearch.url().toString();
if (respSearchUrl.contains("/search.php")) {
// Search result page
docSearch = respSearch.parse();
// Iterative through search results
Element aEpisodeMatch = null;
for (Element aEpisode : docSearch.select("a[href^=serie/]"))
{
String aText = aEpisode.text();
TvShowInfo aEpisodeInfo = TvShowInfoHelper.populateTvShowInfoFromFreeText(aText, true);
// Check if the result text :
// - starts with the desired serie name
// - has the season search
// - has at least one episode search
// => select the first one matching only
if (aEpisodeInfo != null
&& SubLeecherHelper.looseMatchStartsWith(aEpisodeInfo.getSerie(), this.tvShowInfo.getSerie(), true)
&& aEpisodeInfo.getSeason() == this.tvShowInfo.getSeason()
&& TvShowInfoHelper.testIfOneEpisodeMatches(this.tvShowInfo.getEpisodes(), aEpisodeInfo.getEpisodes()))
{
log.debug(String.format("> Matching result found : '%s'", aText));
aEpisodeMatch = aEpisode;
break;
}
else {
log.debug(String.format("> Non matching result : '%s'", aText));
}
}
if (aEpisodeMatch == null) {
// No episode found => end
log.debug("> No match in result !");
return null;
}
// Get the episode URL from link
episodeUrl = ADDIC7ED_URL + "/" + aEpisodeMatch.attr("href");
// ********************************************
// 2 - Episode Page
// Connect to episode page
log.debug(String.format("Search for subtitles for episode '%s' at URL '%s' ...", episode, episodeUrl));
docEpisode = Jsoup.connect(episodeUrl)
.timeout(QUERY_TIME_OUT)
.header("Referer", searchUrl)
.get();
}
else {
// Direct access to episode page
log.debug(String.format("Search for subtitles for episode '%s' in direct access ...", episode));
docEpisode = respSearch.parse();
episodeUrl = respSearchUrl.toString();
}
// Browse lines in subtitles table
Elements tdLanguageList = docEpisode.select("td[class=language]");
List<SubSearchResult> subSearchResults = new ArrayList<SubSearchResult>();
for (Element tdLanguage : tdLanguageList)
{
String tdLanguageText = tdLanguage.text();
if (!SubLeecherHelper.looseMatchContains(tdLanguageText, this.subLanguage)) {
// Language mismatch => next line
continue;
}
Element tdStatus = tdLanguage.nextElementSibling();
String tdStatusText = tdStatus.text();
if (!SubLeecherHelper.looseMatchStartsWith(tdStatusText, "completed", false)) {
// Language present but not Completed => next line
continue;
}
Element tdDownload = tdStatus.nextElementSibling();
if (tdDownload == null) {
// No download button for language => next line
continue;
}
Element aDownloadMatch = null;
Elements aDownloads = tdDownload.select("a[class=buttonDownload]");
if (aDownloads == null || aDownloads.size() == 0) {
// No download button for language => next line
continue;
}
else {
// Download buttons found for language
// - Try to get the button entitled "Download" ...
aDownloadMatch = aDownloads.select("a:contains(download)").first();
if (aDownloadMatch == null) {
// - Try to get the button entitled "most updated" ...
aDownloadMatch = aDownloads.select("a:contains(most updated)").first();
}
if (aDownloadMatch == null) {
// - Take the first button available
aDownloadMatch = aDownloads.first();
}
}
// Get the download URL
String downloadUrl = ADDIC7ED_URL + aDownloadMatch.attr("href");
// Get the episode Release (OPTIONAL)
// => in first line of the table
// => example : Version FoV, 387.00 MBs
Element tdRelease = aDownloadMatch.parent().parent().parent().select("td[class=NewsTitle]").first();
String episodeRelease = "";
if (tdRelease != null) {
// Remove prefix "Version " before group name
episodeRelease = tdRelease.text().replace("Version ", "");
// Remove all characters after "," (size)
int commaPosRelease = episodeRelease.indexOf(",");
if (commaPosRelease > -1) {
episodeRelease = episodeRelease.substring(0, commaPosRelease);
episodeRelease = TvShowInfoHelper.cleanReleaseGroupNamingPart(episodeRelease);
}
}
// Get the description (contains number of download) (OPTIONAL)
// => in next line of the table
int episodeNbDownload = 0;
Element tdDescription = aDownloadMatch.parent().parent().nextElementSibling().select("td[class=newsDate]").first();
if (tdDescription != null) {
episodeNbDownload = extractNbDownloads(tdDescription.text());
}
subSearchResults.add(new SubSearchResult(downloadUrl, tdLanguageText, episodeNbDownload, episodeRelease));
}
// Evaluate the matching score and sort the subtitle results !
List<SubSearchResult> scoredSubs = SubLeecherHelper.evaluateScoreAndSort(
subSearchResults,
this.tvShowInfo.getCleanedReleaseGroup(),
this.releaseGroupMatchRequired);
if (scoredSubs == null || scoredSubs.size() == 0) {
log.debug("> No matching result");
return null;
}
for (SubSearchResult scoredSub : scoredSubs)
{
// ********************************************
// 3 - Download Page
// Connection to download page
String downloadUrl = scoredSub.getUrl();
log.debug(String.format("Try to download subtitle at URL '%s' ...", downloadUrl));
byte[] bytes = null;
String content = "";
try {
bytes = Jsoup.connect(downloadUrl)
.timeout(QUERY_TIME_OUT)
.header("Referer", episodeUrl)
.ignoreContentType(true)
.execute()
.bodyAsBytes();
content = new String(bytes);
}
catch (IllegalCharsetNameException ex) {
// Charset not detect : try to force download with charset UTF-8
log.debug(String.format("> Charset not detect : try to force download with charset '%s' ...", ALT_DOWNLOAD_CHARSET));
URL url = new URL(downloadUrl);
URLConnection connection = url.openConnection();
connection.setRequestProperty("Referer", episodeUrl);
InputStream stream = connection.getInputStream();
bytes = IOUtils.toByteArray(stream);
content = new String(bytes, ALT_DOWNLOAD_CHARSET);
}
if (content.toLowerCase().contains("<html xmlns=\"http://www.w3.org/1999/xhtml\">".toLowerCase())
|| content.toLowerCase().contains("Addic7ed.com - Sorry, download limit exceeded".toLowerCase()))
{
// Download page is HTML or daily download limit exceeded => next line
log.debug("> Download not available : daily download limit exceeded... try tomorrow");
continue;
}
// Save subtitle file to working folder
String subFileName = TvShowInfoHelper.prepareSubtitleFileName(this.tvShowInfo, this.subLanguage, "srt");
String subPath = this.workingFolderPath + "/" + subFileName;
FileOutputStream fos = new FileOutputStream(subPath);
fos.write(bytes);
fos.close();
log.info(String.format("> SubLeecher %s - Subtitle found : Video File='%s' ; Language='%s' ; Subtitle File='%s'",
SITE_NAME,
this.tvShowInfo.getInputVideoFileName(),
this.subLanguage,
subFileName));
return new SubTitleInfo(subFileName, this.subLanguage);
}
// No subtitle found => end
log.debug("No subtitle downloaded");
return null;
}
catch (Exception e)
{
log.error("Error while trying to sub-leech files with " + SITE_NAME, e);
return null;
}
finally
{
log.debug(String.format("SubLeecher %s - End - File='%s' ; Language='%s'", SITE_NAME, this.tvShowInfo.getInputVideoFileName(), this.subLanguage));
}
}
}
| mit |
axboot/ax-boot-framework | ax-boot-core/src/main/java/com/chequer/axboot/core/mybatis/typehandler/LocalTimeTypeHandler.java | 2521 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Vladislav Zablotsky
*
* 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.chequer.axboot.core.mybatis.typehandler;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import java.sql.*;
import java.time.LocalTime;
/**
* Map Java 8 LocalTime <-> java.sql.Time
*/
@MappedTypes(LocalTime.class)
public class LocalTimeTypeHandler extends BaseTypeHandler<LocalTime> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, LocalTime parameter, JdbcType jdbcType) throws SQLException {
ps.setTime(i, Time.valueOf(parameter));
}
@Override
public LocalTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
Time time = rs.getTime(columnName);
if (time != null) {
return time.toLocalTime();
}
return null;
}
@Override
public LocalTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
Time time = rs.getTime(columnIndex);
if (time != null) {
return time.toLocalTime();
}
return null;
}
@Override
public LocalTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
Time time = cs.getTime(columnIndex);
if (time != null) {
return time.toLocalTime();
}
return null;
}
}
| mit |
amujika/TAIA-AgentParty | src/utils/AudioPlayer.java | 2452 | /** Copyright (C) 2013 Alexander Mariel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Autor: Alexander Mariel
* Modified by: Asier Mujika
* Trabajo para la asignatura TAIA
* Practica individual con agentes en la plataforma JADE
*/
package utils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
/**
* This class plays/stops/pauses an audio clip loaded from the file system
*
* @author Alex
*
*/
public class AudioPlayer
{
private Clip sound;
private AudioInputStream ais;
/**
* Constructor, loads the audio clip with the given name
* @param pFileName audio clip name
*/
public AudioPlayer(String pFileName)
{
try
{
//Open file
File f = new File(pFileName);
//Read data
sound = AudioSystem.getClip();
ais = AudioSystem.getAudioInputStream(f);
//Get file format
AudioFormat format = ais.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
sound = (Clip)AudioSystem.getLine(info);
sound.open(ais);
}
catch (LineUnavailableException | IOException | UnsupportedAudioFileException e)
{
e.printStackTrace();
}
}
/**
* Plays a sound from the beginning
*/
public void startSound()
{
sound.setFramePosition(0);
playSound();
sound.loop(10);
}
/**
* Plays a sound from the point where it was stopped
*/
public void playSound()
{
sound.start();
}
/**
* Stops a sound
*/
public void pauseSound()
{
sound.stop();
}
} | mit |
SergioLarios/tuts-flow | tf-web/src/main/java/org/tutsflow/json/service/UserJService.java | 2839 | package org.tutsflow.json.service;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.tutsflow.local.service.UserLocalService;
import org.tutsflow.model.User;
import org.tutsflow.view.PaginationJsonView;
import static org.tutsflow.constant.Services.*;
@Controller
public class UserJService {
/* *******************************************************
* *** USER find all : /service/user/{page}/{size} *****
* *******************************************************/
@RequestMapping(value = USER_FIND_ALL, method = RequestMethod.GET, produces = {TXT_P, APP_J})
@ResponseBody
public String findAllPageable(@PathVariable int page, @PathVariable int size,
HttpServletRequest request, HttpServletResponse response) {
// User list
Page<User> usersP = userLocalService.findAll(new PageRequest(page, size));
List<User> users = usersP.getContent();
int totalElements = (int)usersP.getTotalElements();
// Pages Text
int rowsTo = size * (page + 1);
int rowsFrom = (rowsTo - size) + 1;
if (rowsTo > totalElements) {rowsTo = totalElements;}
// View creation
PaginationJsonView<User> output = new PaginationJsonView<>();
output.setData(users);
output.setTotalEntries(totalElements);
output.setTotalPages(usersP.getTotalPages());
output.setPageText( messageSource.getMessage(
"cp.pages.text",
new Object[]{rowsFrom, rowsTo, output.getTotalEntries()},
localeResolver.resolveLocale(request)));
return output.toJSONString();
}
/* *******************************
******* Injected objects ********
****************************** */
private UserLocalService userLocalService;
private ReloadableResourceBundleMessageSource messageSource;
private SessionLocaleResolver localeResolver;
/* *******************************
********** Constructor **********
******************************* */
@Autowired
public UserJService(UserLocalService userLocalService,
ReloadableResourceBundleMessageSource messageSource,
SessionLocaleResolver localeResolver) {
this.userLocalService = userLocalService;
this.messageSource = messageSource;
this.localeResolver = localeResolver;
}
}
| mit |
lenciel/robolectric | src/main/java/com/xtremelabs/robolectric/shadows/ShadowFragment.java | 2646 | package com.xtremelabs.robolectric.shadows;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.View;
import com.xtremelabs.robolectric.internal.Implementation;
import com.xtremelabs.robolectric.internal.Implements;
@Implements(Fragment.class)
public class ShadowFragment {
protected View view;
protected FragmentActivity activity;
private String tag;
private Bundle savedInstanceState;
private int containerViewId;
private boolean shouldReplace;
private Bundle arguments;
public void setView(View view) {
this.view = view;
}
public void setActivity(FragmentActivity activity) {
this.activity = activity;
}
@Implementation
public View getView() {
return view;
}
@Implementation
public FragmentActivity getActivity() {
return activity;
}
@Implementation
public void startActivity(Intent intent) {
new FragmentActivity().startActivity(intent);
}
@Implementation
public void startActivityForResult(Intent intent, int requestCode) {
activity.startActivityForResult(intent, requestCode);
}
@Implementation
final public FragmentManager getFragmentManager() {
return activity.getSupportFragmentManager();
}
@Implementation
public String getTag() {
return tag;
}
@Implementation
public Resources getResources() {
if (activity == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
return activity.getResources();
}
public void setTag(String tag) {
this.tag = tag;
}
public void setSavedInstanceState(Bundle savedInstanceState) {
this.savedInstanceState = savedInstanceState;
}
public Bundle getSavedInstanceState() {
return savedInstanceState;
}
public void setContainerViewId(int containerViewId) {
this.containerViewId = containerViewId;
}
public int getContainerViewId() {
return containerViewId;
}
public void setShouldReplace(boolean shouldReplace) {
this.shouldReplace = shouldReplace;
}
public boolean getShouldReplace() {
return shouldReplace;
}
@Implementation
public Bundle getArguments() {
return arguments;
}
@Implementation
public void setArguments(Bundle arguments) {
this.arguments = arguments;
}
}
| mit |
fvasquezjatar/fermat-unused | DMP/plugin/composite_wallet/fermat-dmp-plugin-composite-wallet-multi-account-wallet-bitdubai/src/main/java/com/bitdubai/fermat_dmp_plugin/layer/composite_wallet/multi_account_wallet/developer/bitdubai/version_1/MultiAccountWalletCompositeWalletPluginRoot.java | 4959 | package com.bitdubai.fermat_dmp_plugin.layer.composite_wallet.multi_account_wallet.developer.bitdubai.version_1;
import com.bitdubai.fermat_api.CantStartPluginException;
import com.bitdubai.fermat_api.Plugin;
import com.bitdubai.fermat_api.Service;
import com.bitdubai.fermat_api.layer.dmp_world.crypto_index.CryptoIndexManager;
import com.bitdubai.fermat_api.layer.dmp_world.crypto_index.DealsWithCryptoIndex;
import com.bitdubai.fermat_api.layer.dmp_basic_wallet.discount_wallet.interfaces.DiscountWallet;
import com.bitdubai.fermat_api.layer.all_definition.enums.ServiceStatus;
import com.bitdubai.fermat_api.layer.osa_android.file_system.DealsWithPluginFileSystem;
import com.bitdubai.fermat_api.layer.osa_android.file_system.PluginFileSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DealsWithPluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.DealsWithErrors;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.ErrorManager;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.event_manager.interfaces.DealsWithEvents;
import com.bitdubai.fermat_api.layer.all_definition.events.interfaces.FermatEventListener;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.event_manager.interfaces.EventManager;
import java.util.*;
/**
* Created by ciencias on 20.01.15.
*/
/**
* This plug-in handles the relationship between fiat currency an crypto currency. In this way the en user can be using
* fiat over crypto.
*/
public class MultiAccountWalletCompositeWalletPluginRoot implements Service, DealsWithCryptoIndex, DealsWithEvents, DealsWithErrors, DealsWithPluginFileSystem, DealsWithPluginDatabaseSystem, Plugin {
/**
* Service Interface member variables.
*/
private ServiceStatus serviceStatus = ServiceStatus.CREATED;
private List<FermatEventListener> listenersAdded = new ArrayList<>();
/**
* WalletManager Interface member variables.
*/
private final String WALLET_IDS_FILE_NAME = "walletsIds";
private DiscountWallet currentDiscountWallet;
private Map<UUID, UUID> walletIds = new HashMap();
/**
* DealsWithCryptoIndex Interface member variables.
*/
private CryptoIndexManager cryptoIndexManager;
/**
* DealsWithPluginFileSystem Interface member variables.
*/
private PluginFileSystem pluginFileSystem;
/**
* DealsWithPluginDatabaseSystem Interface member variables.
*/
private PluginDatabaseSystem pluginDatabaseSystem;
/**
* DealWithEvents Interface member variables.
*/
private EventManager eventManager;
/**
* Plugin Interface member variables.
*/
private UUID pluginId;
/**
* Service Interface implementation.
*/
@Override
public void start() throws CantStartPluginException {
this.serviceStatus = ServiceStatus.STARTED;
}
@Override
public void pause() {
this.serviceStatus = ServiceStatus.PAUSED;
}
@Override
public void resume() {
this.serviceStatus = ServiceStatus.STARTED;
}
@Override
public void stop() {
/**
* I will remove all the event listeners registered with the event manager.
*/
for (FermatEventListener fermatEventListener : listenersAdded) {
eventManager.removeListener(fermatEventListener);
}
listenersAdded.clear();
this.serviceStatus = ServiceStatus.STOPPED;
}
@Override
public ServiceStatus getStatus() {
return this.serviceStatus;
}
/**
* DealsWithCryptoIndex Interface member variables.
*/
@Override
public void setCryptoIndexManager(CryptoIndexManager cryptoIndexManager) {
this.cryptoIndexManager = cryptoIndexManager;
}
/**
* DealsWithPluginFileSystem Interface implementation.
*/
@Override
public void setPluginFileSystem(PluginFileSystem pluginFileSystem) {
this.pluginFileSystem = pluginFileSystem;
}
/**
* DealsWithPluginDatabaseSystem Interface implementation.
*/
@Override
public void setPluginDatabaseSystem(PluginDatabaseSystem pluginDatabaseSystem) {
this.pluginDatabaseSystem = pluginDatabaseSystem;
}
/**
* DealWithEvents Interface implementation.
*/
@Override
public void setEventManager(EventManager eventManager) {
this.eventManager = eventManager;
}
/**
*DealWithErrors Interface implementation.
*/
@Override
public void setErrorManager(ErrorManager errorManager) {
}
/**
* DealsWithPluginIdentity methods implementation.
*/
@Override
public void setId(UUID pluginId) {
this.pluginId = pluginId;
}
}
| mit |
digitalheir/java-wetten-nl-library | src/main/java/nl/wetten/bwbng/wti/Opmerkingen.java | 5627 | //
// 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: 2015.10.21 at 02:36:51 PM CEST
//
package nl.wetten.bwbng.wti;
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.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="opmerking" maxOccurs="unbounded">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice maxOccurs="unbounded" minOccurs="0">
* <element ref="{}al"/>
* </choice>
* <attribute name="type" type="{http://www.w3.org/2001/XMLSchema}NCName" />
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"opmerking"
})
@XmlRootElement(name = "opmerkingen")
public class Opmerkingen {
@XmlElement(required = true)
protected List<Opmerkingen.Opmerking> opmerking;
/**
* Gets the value of the opmerking 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 opmerking property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getOpmerking().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Opmerkingen.Opmerking }
*
*
*/
public List<Opmerkingen.Opmerking> getOpmerking() {
if (opmerking == null) {
opmerking = new ArrayList<Opmerkingen.Opmerking>();
}
return this.opmerking;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice maxOccurs="unbounded" minOccurs="0">
* <element ref="{}al"/>
* </choice>
* <attribute name="type" type="{http://www.w3.org/2001/XMLSchema}NCName" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"content"
})
public static class Opmerking {
@XmlElementRef(name = "al", type = Al.class, required = false)
@XmlMixed
protected List<Object> content;
@XmlAttribute(name = "type")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NCName")
protected String type;
/**
* Gets the value of the content 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 content property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getContent().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
* {@link Al }
*
*
*/
public List<Object> getContent() {
if (content == null) {
content = new ArrayList<Object>();
}
return this.content;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
}
}
| mit |