repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
Techcable/JStruct | src/main/java/net/techcable/jstruct/visitor/PassByValueMethodVisitor.java | 6480 | package net.techcable.jstruct.visitor;
import net.techcable.jstruct.StructData;
import net.techcable.jstruct.StructManager;
import org.objectweb.asm.*;
import org.objectweb.asm.commons.AnalyzerAdapter;
import org.objectweb.asm.commons.InstructionAdapter;
import org.objectweb.asm.commons.LocalVariablesSorter;
import java.util.*;
public class PassByValueMethodVisitor extends InstructionAdapter {
private final StructManager structManager;
private final LocalVariablesSorter localVariables;
private final AnalyzerAdapter analyzer;
private final Type declaringType;
public PassByValueMethodVisitor(StructManager structManager, Type declaringType, MethodVisitor parent, LocalVariablesSorter localVariables, AnalyzerAdapter analyzer) {
super(parent);
this.structManager = structManager;
this.analyzer = analyzer;
this.localVariables = localVariables;
this.declaringType = declaringType;
}
@Override
public void invokevirtual(String owner, String name, String desc, boolean itf) {
String[] array = onInvoke(owner, name, desc);
owner = array[0];
name = array[1];
desc = array[2];
super.invokevirtual(owner, name, desc, itf);
}
@Override
public void invokestatic(String owner, String name, String desc, boolean itf) {
String[] array = onInvoke(owner, name, desc);
owner = array[0];
name = array[1];
desc = array[2];
super.invokestatic(owner, name, desc, itf);
}
@Override
public void invokeinterface(String owner, String name, String desc) {
String[] array = onInvoke(owner, name, desc);
owner = array[0];
name = array[1];
desc = array[2];
super.invokeinterface(owner, name, desc);
}
@Override
public void invokespecial(String owner, String name, String desc, boolean itf) {
String[] array = onInvoke(owner, name, desc);
owner = array[0];
name = array[1];
desc = array[2];
super.invokespecial(owner, name, desc, itf);
}
private String[] onInvoke(String owner, String name, String desc) {
if (structManager.isStruct(getTopOfStack())) {
// Do some sanity checks for structs
if ("wait".equals(name) || "notify".equals(name) && Type.getInternalName(Object.class).equals(owner)) {
throwNewException(UnsupportedOperationException.class, "Can't call " + name + " on a struct");
return new String[] {owner, name, desc};
}
}
Type methodType = Type.getMethodType(desc);
for (Type structType : methodType.getArgumentTypes()) {
if (!structManager.isStruct(structType)) continue;
int structVar = localVariables.newLocal(structType); // Create a local variable which will hold the struct
StructData structData = structManager.getStruct(structType);
for (StructData.FieldStructData fieldData : structData.getFieldTypes()) {
load(structVar, structType); // Load the struct onto the stack
Type fieldType = fieldData.getFieldType();
getfield(structType.getInternalName(), fieldData.getName(), fieldType.getDescriptor()); // Now get the field from the type
}
// Duplicate the fields on the stack
}
return new String[] {owner, name, desc};
}
@Override
public void monitorenter() {
if (structManager.isStruct(getTopOfStack())) throwNewException(UnsupportedOperationException.class, "Cant synchronize on a monitor");
}
@Override
public void ificmpeq(Label label) {
onCompare(label, true);
super.ificmpeq(label);
}
@Override
public void ificmpne(Label label) {
onCompare(label, false);
super.ificmpne(label);
}
private void onCompare(Label label, boolean equals) {
Queue<Type> stack = getStack();
boolean comparingStructs;
Type t = stack.poll();
comparingStructs = structManager.isStruct(t);
t = stack.poll(); // Right below the top
comparingStructs = comparingStructs || structManager.isStruct(t);
if (comparingStructs) throwNewException(UnsupportedOperationException.class, "Can't compare structs");
}
private void throwNewException(Class<? extends Throwable> exceptionType, String msg) {
throwNewException(Type.getType(exceptionType), msg);
}
private void throwNewException(Type exceptionType, String msg) {
anew(exceptionType);
Type desc = msg == null ? Type.getMethodType(Type.VOID_TYPE) : Type.getMethodType(Type.VOID_TYPE, Type.getType(String.class));
if (msg != null) {
aconst(msg);
}
invokespecial(exceptionType.getInternalName(), "<init>", desc.getDescriptor(), false); // Call the constructor
athrow();
}
private Type getTopOfStack() {
return getStack().poll();
}
private Queue<Type> getStack() {
List<Object> stackList = analyzer.stack;
Queue<Object> objStack = new LinkedList<>();
Collections.reverse(stackList); // bottom -> top, top -> bottom
stackList.forEach(objStack::add); // Since it is a FIFO queue, adding the top first will cause the top to be last out
Queue<Type> typeStack = new LinkedList<>();
Object obj;
while ((obj = objStack.poll()) != null) {
Type type;
if (obj instanceof Integer) {
int id = ((Integer) obj);
if (id == Opcodes.INTEGER) {
type = Type.INT_TYPE;
} else if (id == Opcodes.FLOAT) {
type = Type.FLOAT_TYPE;
} else if (id == Opcodes.LONG) {
type = Type.LONG_TYPE;
} else if (id == Opcodes.DOUBLE) {
type = Type.DOUBLE_TYPE;
} else if (id == Opcodes.NULL) {
type = null; //
} else if (id == Opcodes.UNINITIALIZED_THIS) {
type = declaringType;
} else continue; // Doesn't matter
} else if (obj instanceof String) {
String internalName = ((String) obj);
type = Type.getObjectType(internalName);
} else type = null; // Unknown type
typeStack.add(type);
}
return typeStack;
}
}
| mit |
dolphinzhang/framework | common/src/main/java/org/dol/json/JSON.java | 13362 | package org.dol.json;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.type.MapType;
import lombok.Data;
import org.dol.model.FieldProperty;
import org.dol.util.StringUtil;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public final class JSON {
public static final ObjectMapper DEFAULT_OBJECT_MAPPER;
static {
DEFAULT_OBJECT_MAPPER = createDefault();
}
public static ObjectMapper createDefault() {
ObjectMapper objectMapper = new ObjectMapper();
AnnotationIntrospector dimensionFieldSerializer = new CustomJacksonAnnotationIntrospector();
objectMapper.setAnnotationIntrospector(dimensionFieldSerializer);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
objectMapper.disable(SerializationFeature.FAIL_ON_SELF_REFERENCES);
objectMapper.disable(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS);
objectMapper.enable(JsonParser.Feature.ALLOW_MISSING_VALUES);
objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
objectMapper.enable(JsonParser.Feature.ALLOW_COMMENTS);
DeserializationConfig deserializationConfig = objectMapper.getDeserializationConfig().withHandler(BooleanDeserializationProblemHandler.INSTANCE);
objectMapper.setConfig(deserializationConfig);
return objectMapper;
}
public static <T> T parseObject(String json, Class<T> resultClazz) {
try {
return DEFAULT_OBJECT_MAPPER
.readerFor(resultClazz)
.readValue(json);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Object parseObject(String json, Type type) {
try {
JavaType javaType = DEFAULT_OBJECT_MAPPER.getTypeFactory().constructType(type);
return DEFAULT_OBJECT_MAPPER.readerFor(javaType).readValue(json);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> T parseObject(String json, Class<T> parametrized,
Class<?>... parameterClasses) {
try {
JavaType javaType = DEFAULT_OBJECT_MAPPER
.getTypeFactory()
.constructParametricType(parametrized, parameterClasses);
return DEFAULT_OBJECT_MAPPER.readerFor(javaType).readValue(json);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> T[] parseJavaArray(String json, Class<T> elementType) {
try {
JavaType javaType = DEFAULT_OBJECT_MAPPER.getTypeFactory().constructArrayType(elementType);
return DEFAULT_OBJECT_MAPPER.readerFor(javaType).readValue(json);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> List<T> parseArray(String json, Class<T> elementType) {
return parseList(json, elementType);
}
public static JSONArray parseArray(String json) {
List<Object> items = parseList(json, Object.class);
return new JSONArray(items);
}
public static String toJSONString(Object value) {
try {
return DEFAULT_OBJECT_MAPPER.writeValueAsString(value);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String toJSONString(Object value, boolean pretty) {
if (pretty) {
try {
return DEFAULT_OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(value);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return toJSONString(value);
}
public static <T> List<T> parseList(String json, Class<T> elementClass) {
try {
JavaType javaType = DEFAULT_OBJECT_MAPPER
.getTypeFactory()
.constructCollectionType(ArrayList.class, elementClass);
return DEFAULT_OBJECT_MAPPER.readValue(json, javaType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> List<T> parseList(String json) {
try {
JavaType javaType = DEFAULT_OBJECT_MAPPER
.getTypeFactory()
.constructCollectionType(ArrayList.class, Object.class);
return DEFAULT_OBJECT_MAPPER.readValue(json, javaType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <K, V> Map<K, V> parseMap(String json, Class<V> valueClass) {
try {
MapType mapType = DEFAULT_OBJECT_MAPPER.getTypeFactory().constructMapType(
HashMap.class,
String.class,
valueClass);
return DEFAULT_OBJECT_MAPPER.readValue(json, mapType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <K, V> Map<K, V> parseMap(String json, Class<? extends Map> mapClass, Class<String> keyClass, Class<V> valueClass) {
try {
MapType mapType = DEFAULT_OBJECT_MAPPER.getTypeFactory().constructMapType(
mapClass,
keyClass,
valueClass);
return DEFAULT_OBJECT_MAPPER.readValue(json, mapType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Map<String, Object> parseMap(String json) {
return parseMap(json, Object.class);
}
public static JSONObject parseObject(String json) {
Map<String, Object> stringObjectMap = parseMap(json);
return new JSONObject(stringObjectMap);
}
@Data
public static class TestData {
private String name;
}
public static class BooleanDeserializationProblemHandler extends DeserializationProblemHandler {
private static final BooleanDeserializationProblemHandler INSTANCE =
new BooleanDeserializationProblemHandler();
@Override
public Object handleWeirdStringValue(DeserializationContext ctxt,
Class<?> targetType,
String valueToConvert,
String failureMsg) throws IOException {
if (Boolean.class.equals(targetType)) {
return "1".equals(valueToConvert)
|| "true".equalsIgnoreCase(valueToConvert);
}
if (String.class.equals(targetType)) {
return "1".equals(valueToConvert) || "true".equalsIgnoreCase(valueToConvert);
}
return super.handleWeirdStringValue(ctxt, targetType, valueToConvert, failureMsg);
}
@Override
public Object handleWeirdNumberValue(DeserializationContext ctxt,
Class<?> targetType,
Number valueToConvert,
String failureMsg) throws IOException {
if (Boolean.class.equals(targetType)) {
return valueToConvert.equals(1);
} else if (String.class.equals(targetType)) {
return valueToConvert.equals(1);
}
return super.handleWeirdNumberValue(ctxt, targetType, valueToConvert, failureMsg);
}
@Override
public Object handleWeirdNativeValue(DeserializationContext ctxt,
JavaType targetType,
Object valueToConvert, JsonParser p) throws IOException {
return super.handleWeirdNativeValue(ctxt, targetType, valueToConvert, p);
}
@Override
public Object handleUnexpectedToken(DeserializationContext ctxt,
Class<?> targetType,
JsonToken t,
JsonParser p,
String failureMsg) throws IOException {
if (Boolean.class.equals(targetType)) {
if (t == JsonToken.VALUE_NUMBER_FLOAT) {
return p.getFloatValue() > 0;
}
}
return super.handleUnexpectedToken(ctxt, targetType, t, p, failureMsg);
}
}
public static class CustomJacksonAnnotationIntrospector extends JacksonAnnotationIntrospector {
public static String toJSONString(Object obj) {
try {
return DEFAULT_OBJECT_MAPPER.writeValueAsString(obj);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public PropertyName findNameForSerialization(Annotated a) {
PropertyName propertyName = getPropertyName(a);
return propertyName != null ? propertyName : super.findNameForSerialization(a);
}
@Override
public PropertyName findNameForDeserialization(Annotated a) {
PropertyName propertyName = getPropertyName(a);
return propertyName != null ? propertyName : super.findNameForDeserialization(a);
}
@Override
public boolean isAnnotationBundle(Annotation ann) {
Class<?> type = ann.annotationType();
Boolean b = _annotationsInside.get(type);
if (b == null) {
b = type.getAnnotation(JacksonAnnotationsInside.class) != null
|| type.getAnnotation(FieldProperty.class) != null;
_annotationsInside.putIfAbsent(type, b);
}
return b;
}
private PropertyName getPropertyName(Annotated a) {
FieldProperty FieldProperty = a.getAnnotation(FieldProperty.class);
if (FieldProperty != null && !FieldProperty.ignore()) {
if (StringUtil.notEmpty(FieldProperty.value())) {
return PropertyName.construct(FieldProperty.value());
}
if (StringUtil.notEmpty(FieldProperty.name())) {
return PropertyName.construct(FieldProperty.name());
}
}
return null;
}
@Override
public JsonProperty.Access findPropertyAccess(Annotated m) {
JsonProperty.Access propertyAccess = super.findPropertyAccess(m);
if (propertyAccess != null) {
return propertyAccess;
}
FieldProperty annotation = m.getAnnotation(FieldProperty.class);
if (annotation != null && !annotation.ignore()) {
if (!annotation.serialize() && annotation.deserialize()) {
return JsonProperty.Access.WRITE_ONLY;
} else if (annotation.serialize() && !annotation.deserialize()) {
return JsonProperty.Access.READ_ONLY;
}
}
return null;
}
@Override
protected boolean _isIgnorable(Annotated a) {
boolean ignorable = super._isIgnorable(a);
if (ignorable) {
return ignorable;
}
FieldProperty fieldProperty = a.getAnnotation(FieldProperty.class);
if (fieldProperty != null) {
return fieldProperty.ignore() || (!fieldProperty.serialize() && !fieldProperty.deserialize());
}
return ignorable;
}
@Override
public Object findDeserializer(Annotated a) {
Object deserializer = super.findDeserializer(a);
if (deserializer == null && (a instanceof AnnotatedMethod)) {
AnnotatedMethod method = (AnnotatedMethod) a;
if (method.getParameterCount() == 1 && method.getRawParameterType(0) == String.class) {
FieldProperty annRaw = _findAnnotation(a, FieldProperty.class);
if (annRaw != null && annRaw.rowString()) {
return JsonRawValueDeserializer.INSTANCE;
}
if (annRaw == null || annRaw.trim()) {
return TrimStringDeserializer.INSTANCE;
}
}
}
return null;
}
}
}
| mit |
7heaven/SHZoomView | app/src/main/java/com/sevenheaven/zoomviewtest/MidCircleView.java | 6738 | package com.sevenheaven.zoomviewtest;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
/**
* Created by caifangmao on 15/4/7.
*/
public class MidCircleView extends View {
private Bitmap cache;
private Canvas cacheCanvas;
private ArrayList<Point> cachePoint;
private int r = 35;
private int downX;
private int downY;
private int drawX;
private int drawY;
private int scale = 10;
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public MidCircleView(Context context) {
this(context, null);
}
public MidCircleView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MidCircleView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
cache = Bitmap.createBitmap(getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels, Bitmap.Config.ARGB_8888);
cacheCanvas = new Canvas(cache);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
downX = (int) event.getX();
downY = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
int cX = (int) event.getX();
int cY = (int) event.getY();
int dx = cX - downX;
int dy = cY - downY;
int distance = (int) Math.sqrt(dx * dx + dy * dy);
r = distance / scale;
drawX = downX / scale;
drawY = downY / scale;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
break;
}
invalidate();
return true;
}
private Point[] drawMidCircle(int centerX, int centerY, Canvas canvas, Paint paint) {
ArrayList<Point> cache = new ArrayList<>();
int x, y;
double d;
x = 0;
y = r;
// d = (float) 1.25 - r;
d = 0;
// int upperAlpha = (int) (255 - Math.abs(d) / (float) r * 255.0F) << 24;
// int lowerAlpha = 255 - upperAlpha;
int lowerAlpha = ((int) (255 * (1 - DC(r, x)))) << 24;
int upperAlpha = ((int) (255 * DC(r, x))) << 24;
int tx = x;
int ty = y - 1;
paint.setColor(lowerAlpha | (paint.getColor() & 0xFFFFFF));
canvas.drawRect(x + centerX, y + centerY, x + 1 + centerX, y + 1 + centerY, paint);
cache.add(new Point(x + centerX, y + centerY));
while (x < y) {
Log.d("d:" + d, "x:" + x + ",y:" + y);
Log.e("lowerAlpha" + lowerAlpha, "upperAlpha" + upperAlpha);
paint.setColor(lowerAlpha | (paint.getColor() & 0xFFFFFF));
canvas.drawRect(y + centerX, x + centerY, y + 1 + centerX, x + 1 + centerY, paint);
canvas.drawRect(y + centerX, -x + centerY, y + 1 + centerX, -x + 1 + centerY, paint);
canvas.drawRect(x + centerX, -y + centerY, x + 1 + centerX, -y + 1 + centerY, paint);
canvas.drawRect(-x + centerX, -y + centerY, -x + 1 + centerX, -y + 1 + centerY, paint);
canvas.drawRect(-y + centerX, -x + centerY, -y + 1 + centerX, -x + 1 + centerY, paint);
canvas.drawRect(-y + centerX, x + centerY, -y + 1 + centerX, x + 1 + centerY, paint);
canvas.drawRect(-x + centerX, y + centerY, -x + 1 + centerX, y + 1 + centerY, paint);
paint.setColor(upperAlpha | (paint.getColor() & 0xFFFFFF));
canvas.drawRect(ty + centerX, tx + centerY, ty + 1 + centerX, tx + 1 + centerY, paint);
canvas.drawRect(ty + centerX, -tx + centerY, ty + 1 + centerX, -tx + 1 + centerY, paint);
canvas.drawRect(tx + centerX, -ty + centerY, tx + 1 + centerX, -ty + 1 + centerY, paint);
canvas.drawRect(-tx + centerX, -ty + centerY, -tx + 1 + centerX, -ty + 1 + centerY, paint);
canvas.drawRect(-ty + centerX, -tx + centerY, -ty + 1 + centerX, -tx + 1 + centerY, paint);
canvas.drawRect(-ty + centerX, tx + centerY, -ty + 1 + centerX, tx + 1 + centerY, paint);
canvas.drawRect(-tx + centerX, ty + centerY, -tx + 1 + centerX, ty + 1 + centerY, paint);
cache.add(new Point(y + centerX, x + centerY));
cache.add(new Point(y + centerX, -x + centerY));
cache.add(new Point(x + centerX, -y + centerY));
cache.add(new Point(-x + centerX, -y + centerY));
cache.add(new Point(-y + centerX, -x + centerY));
cache.add(new Point(-y + centerX, x + centerY));
cache.add(new Point(-x + centerX, y + centerY));
// if (d < 0) {
// d += 2 * x + 3;
// } else {
// d += 2 * (x - y) + 5;
// y--;
// }
x++;
if(DC(r, x) < d){
y--;
}
// upperAlpha = (int) (255 - Math.abs(d) / (float) r * 255.0F) << 24;
// lowerAlpha = 255 - upperAlpha;
lowerAlpha = ((int) (255 * (1 - DC(r, x)))) << 24;
upperAlpha = ((int) (255 * DC(r, x))) << 24;
paint.setColor(lowerAlpha | (paint.getColor() & 0xFFFFFF));
canvas.drawRect(x + centerX, y + centerY, x + 1 + centerX, y + 1 + centerY, paint);
paint.setColor(upperAlpha | (paint.getColor() & 0xFFFFFF));
tx = x;
ty = y - 1;
canvas.drawRect(tx + centerX, ty + centerY, tx + 1 + centerX, ty + 1 + centerY, paint);
cache.add(new Point(x + centerX, y + centerY));
d = DC(r, x);
}
return cache.toArray(new Point[cache.size()]);
}
@Override
public void onDraw(Canvas canvas) {
paint.setColor(0xFFFFFFFF);
paint.setStrokeWidth(1);
cacheCanvas.drawRect(0, 0, cache.getWidth(), cache.getHeight(), paint);
paint.setColor(0xFF0099CC);
paint.setStyle(Paint.Style.STROKE);
cacheCanvas.drawCircle(drawX, drawY + 30, r, paint);
paint.setStyle(Paint.Style.FILL);
canvas.scale(scale, scale);
canvas.drawBitmap(cache, 0, 0, paint);
drawMidCircle(drawX, drawY, canvas, paint);
}
double DC(int r, int y){
double x = Math.sqrt(r * r - y * y);
return Math.ceil(x) - x;
}
}
| mit |
georgewfraser/vscode-javac | src/test/examples/maven-project/src/org/javacs/example/AutocompleteDocstring.java | 535 | package org.javacs.example;
/**
* A class
*/
public class AutocompleteDocstring {
public void members() {
this.;
}
public void statics() {
AutocompleteDocstring.;
}
/**
* A fieldStatic
*/
public static String fieldStatic;
/**
* A fields
*/
public String fields;
/**
* A methodStatic
*/
public static String methodStatic() {
return "foo";
}
/**
* A methods
*/
public String methods() {
return "foo";
}
} | mit |
Wirwing/TopicosWeb | KutzCarRentalApplication/src/java/KutzCarRental/WS/KutzCarRentalWS.java | 2666 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package KutzCarRental.WS;
import KutzCarRental.DB.DataBase;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.ejb.Stateless;
import KutzCarRental.Domain.Car;
import KutzCarRental.Domain.Reservation;
import KutzCarRental.Utils.Utils;
import java.text.ParseException;
import java.util.ArrayList;
/**
*
* @author Ileana Ontiveros
*/
@WebService(serviceName = "KutzCarRentalWS")
@Stateless()
public class KutzCarRentalWS {
/**
* Obtener una lista de autos para rentar
*/
@WebMethod(operationName = "getCars")
public ArrayList<Car> getCars() {
ArrayList<Car> cars = DataBase.getDB().getCarsTable();
return cars;
}
/**
* Obtener la lista de reservaciones
*/
@WebMethod(operationName = "getReservations")
public ArrayList<Reservation> getReservations() {
ArrayList<Reservation> reservations = DataBase.getDB().getReservationsTable();
return reservations;
}
/**
* Reservar un auto
*/
@WebMethod(operationName = "createReservation")
public Reservation createReservation(@WebParam(name = "rentalDate") String rentalDate,
@WebParam(name = "returnDate") String returnDate,
@WebParam(name = "idCar") int idCar) throws ParseException {
boolean isBooked = false;
Reservation reservation = new Reservation();
try {
Car car = DataBase.getDB().getCarById(idCar);
double pricePerDay = car.getPricePerDay();
int totalDays = new Utils().calculateDays(rentalDate, returnDate);
double priceTotal = totalDays*pricePerDay;
reservation = new Reservation(rentalDate, returnDate, car, priceTotal);
isBooked = DataBase.getDB().addReservation(reservation, idCar);
return reservation;
} catch (Exception e){
return reservation;
}
}
@WebMethod(operationName = "getReservation")
public Reservation getReservation(String reservationId) throws ParseException {
Reservation reservation = DataBase.getDB().getReservationById(reservationId);
return reservation;
}
/**
* Obtener un auto por id
*/
@WebMethod(operationName = "findCarById")
public Car findCarById(@WebParam(name = "idCar") int idCar) {
Car car = new Car();
try {
car = DataBase.getDB().getCarById(idCar);
return car;
} catch (Exception e){
return car;
}
}
}
| mit |
carlosdeveloper10/AdapterPatternExample | edu/cmsoft/adapterexample/CirclePlug.java | 614 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.cmsoft.adapterexample;
/**
*
* Represents a circle electric plug.
*
* @author carlos mario <carlos_programmer10@hotmail.com>
*
*/
public class CirclePlug{
public String connectToSCircleLeftInput() {
return "Circular side Left is connected...";
}
public String connectToCircleRightInput() {
return "Circular side right is connected...";
}
}
| mit |
WestwoodRobotics/FRC-2016 | 2016 FRC Java/src/org/usfirst/frc/team2583/robot/Robot.java | 3165 | package org.usfirst.frc.team2583.robot;
import org.usfirst.frc.team2583.robot.commands.JoystickDrive;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
Command autonomousCommand, drive;
SendableChooser chooser;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
chooser = new SendableChooser();
// chooser.addObject("My Auto", new MyAutoCommand());
SmartDashboard.putData("Auto mode", chooser);
}
/**
* This function is called once each time the robot enters Disabled mode.
* You can use it to reset any subsystem information you want to clear when
* the robot is disabled.
*/
public void disabledInit(){
}
public void disabledPeriodic() {
Scheduler.getInstance().run();
}
/**
* This autonomous (along with the chooser code above) shows how to select between different autonomous modes
* using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW
* Dashboard, remove all of the chooser code and uncomment the getString code to get the auto name from the text box
* below the Gyro
*
* You can add additional auto modes by adding additional commands to the chooser code above (like the commented example)
* or additional comparisons to the switch structure below with additional strings & commands.
*/
public void autonomousInit() {
autonomousCommand = (Command) chooser.getSelected();
if (autonomousCommand != null) autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != null) autonomousCommand.cancel();
drive = new JoystickDrive();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
if(!drive.isRunning())drive.start();
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
} | mit |
mwcaisse/CarTracker | CarTracker.Common/src/main/java/com/ricex/cartracker/common/util/JsonUserAdapter.java | 733 | package com.ricex.cartracker.common.util;
import java.lang.reflect.Type;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.ricex.cartracker.common.entity.auth.User;
import com.ricex.cartracker.common.viewmodel.auth.UserViewModel;
import com.ricex.cartracker.common.viewmodel.auth.UserViewModelImpl;
public class JsonUserAdapter implements JsonSerializer<User> {
public JsonElement serialize(User source, Type type, JsonSerializationContext context) {
return context.serialize(source.toViewModel());
}
}
| mit |
jacksingleton/campr-xss-workshop | src/main/java/com/thoughtworks/securityinourdna/JdbcInvoiceRepo.java | 1136 | package com.thoughtworks.securityinourdna;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class JdbcInvoiceRepo implements InvoiceRepo {
private final Connection connection;
public JdbcInvoiceRepo(Connection connection) {
this.connection = connection;
}
@Override
public void add(String invoiceText) throws Exception {
final String query = "insert into invoices values (?)";
final PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, invoiceText);
stmt.execute();
}
@Override
public List<String> all() throws Exception {
final String query = "select * from invoices";
final PreparedStatement stmt = connection.prepareStatement(query);
final ResultSet resultSet = stmt.executeQuery();
final List<String> invoices = new ArrayList<>();
while (resultSet.next()) {
invoices.add(resultSet.getString("text"));
}
return invoices;
}
}
| mit |
fabinhow12/provaSistemaVenda | sistemaVendaProva/src/telas/TelaEditarProduto.java | 11347 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package telas;
import dados.Produto;
import javax.swing.JOptionPane;
import repositorio.RepositorioProduto;
/**
*
* @author fabio
*/
public class TelaEditarProduto extends javax.swing.JFrame {
RepositorioProduto repositorioProduto ;
private Produto produto = null;
/** Creates new form TelaEditarProduto */
public TelaEditarProduto(Produto produto) {
initComponents();
this.produto = produto;
// atualiza os campos caso exista um Produto para editar
if (this.produto != null) {
jTextField1.setText(produto.getNome());
jTextField2.setText(produto.getDesc());
jTextField3.setText(String.valueOf(produto.getPrecoVenda()));
jTextField4.setText(String.valueOf(produto.getPrecoCusto()));
}
repositorioProduto = new RepositorioProduto();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Editar Produto");
setResizable(false);
jButton1.setText("Confirmar !");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Cancelar !");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel1.setText("Digite O Novo Nome : ");
jLabel2.setText("Digite A Nova Descrição : ");
jLabel3.setText("Digite O Novo Preço de Venda :");
jLabel4.setText("Digite O Novo Preço de Custo : ");
jLabel5.setFont(new java.awt.Font("Droid Sans", 3, 18)); // NOI18N
jLabel5.setText("Tela De Edição");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField2)
.addComponent(jTextField3)
.addComponent(jTextField4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(60, 60, 60))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(77, 77, 77)
.addComponent(jButton1)
.addGap(77, 77, 77)
.addComponent(jButton2))
.addGroup(layout.createSequentialGroup()
.addGap(173, 173, 173)
.addComponent(jLabel5)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5)
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 86, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
//Botão Para SAIR
this.dispose();
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// Botão Para Editar
if (jTextField1.getText().length() > 0 && jTextField2.getText().length() >0 && jTextField3.getText().length() >0 && jTextField4.getText().length() > 0){
String nome = jTextField1.getText();
String desc = jTextField2.getText();
double pv = Double.parseDouble(jTextField3.getText());
double pc = Double.parseDouble(jTextField4.getText());
if (this.produto != null) {
// atualizar o produto existente
this.produto.setNome(nome);
this.produto.setDesc(desc);
this.produto.setPrecoCusto(pc);
this.produto.setPrecoVenda(pv);
repositorioProduto.editarProduto(this.produto);
JOptionPane.showMessageDialog(this,"Clique Na Linha Respectiva Para Aparecer Os Novos Valores"+"\nAtualizado Com Sucesso");
this.dispose();
repositorioProduto.AtualizaTablep();
}
}else{
JOptionPane.showMessageDialog(this, "Campo(s) Em Branco");
}
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TelaEditarProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaEditarProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaEditarProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaEditarProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TelaEditarProduto(null).setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
// End of variables declaration//GEN-END:variables
}
| mit |
Crakens/jrpg | TheLordOfSouls/src/principal/peticiones/PeticionRegistro.java | 507 | package principal.peticiones;
import java.io.Serializable;
import principal.cs.*;
public class PeticionRegistro implements Serializable{
private String usuario;
private char[] password;
private String email;
public PeticionRegistro(String u, char[] p, String e) {
this.usuario = u;
this.password = p;
this.email = e;
}
public String getUsuario(){
return this.usuario;
}
public char[] getPassword(){
return this.password;
}
public String getEmail(){
return this.email;
}
} | mit |
kamcio96/SpongeCommon | src/main/java/org/spongepowered/common/registry/type/block/DoublePlantTypeRegistryModule.java | 2972 | /*
* 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.registry.type.block;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import net.minecraft.block.BlockDoublePlant;
import org.spongepowered.api.data.type.DoublePlantType;
import org.spongepowered.api.data.type.DoublePlantTypes;
import org.spongepowered.common.registry.CatalogRegistryModule;
import org.spongepowered.common.registry.util.RegisterCatalog;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
public final class DoublePlantTypeRegistryModule implements CatalogRegistryModule<DoublePlantType> {
@RegisterCatalog(DoublePlantTypes.class)
private final Map<String, DoublePlantType> doublePlantMappings = new ImmutableMap.Builder<String, DoublePlantType>()
.put("sunflower", (DoublePlantType) (Object) BlockDoublePlant.EnumPlantType.SUNFLOWER)
.put("syringa", (DoublePlantType) (Object) BlockDoublePlant.EnumPlantType.SYRINGA)
.put("grass", (DoublePlantType) (Object) BlockDoublePlant.EnumPlantType.GRASS)
.put("fern", (DoublePlantType) (Object) BlockDoublePlant.EnumPlantType.FERN)
.put("rose", (DoublePlantType) (Object) BlockDoublePlant.EnumPlantType.ROSE)
.put("paeonia", (DoublePlantType) (Object) BlockDoublePlant.EnumPlantType.PAEONIA)
.build();
@Override
public Optional<DoublePlantType> getById(String id) {
return Optional.ofNullable(this.doublePlantMappings.get(checkNotNull(id).toLowerCase()));
}
@Override
public Collection<DoublePlantType> getAll() {
return ImmutableList.copyOf(this.doublePlantMappings.values());
}
}
| mit |
polytomous/TerrariaClone | src/test/java/TerrariaClone/GameData/JsonBlockToolsProviderTest.java | 1606 | package TerrariaClone.GameData;
import TerrariaClone.BlockToolsProvider;
import TerrariaClone.HorrificBlockNameProvider;
import TerrariaClone.HorrificBlockToolsProvider;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
public class JsonBlockToolsProviderTest {
@Test
public void constantlyBootstrapBlockTools()
{
String[] blocknames = new HorrificBlockNameProvider().getBlockNames();
JsonBlockToolsProvider provider = new JsonBlockToolsProvider();
HorrificBlockToolsProvider horrible_provider = new HorrificBlockToolsProvider();
provider.createBlockToolsData(horrible_provider.getBlockToolsData());
}
@Test
public void getBlockTools() throws Exception {
String[] blocknames = new HorrificBlockNameProvider().getBlockNames();
BlockToolsProvider provider = new JsonBlockToolsProvider();
BlockToolsProvider horrible_provider = new HorrificBlockToolsProvider();
HashMap<Integer, Short[]> newData= provider.getBlockTools(blocknames);
HashMap<Integer, Short[]> originalData= provider.getBlockTools(blocknames);
assertMapWithArrayEqual(newData, originalData);
}
public static void assertMapWithArrayEqual(Map<Integer,Short[]> lhs, Map<Integer, Short[]> rhs)
{
assertArrayEquals("Map keys should be the same", lhs.keySet().toArray(), rhs.keySet().toArray());
for(Integer key : lhs.keySet())
{
assertArrayEquals("Inner arrays should be the same", lhs.get(key), rhs.get(key));
}
}
} | mit |
agileek/java-checksum-flyway-maven-plugin | src/test/java/io/github/agileek/maven/ChecksumFlywayMojoTest.java | 4274 | package io.github.agileek.maven;
import com.helger.jcodemodel.JCodeModel;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.project.MavenProject;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
public class ChecksumFlywayMojoTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExpectedException expectedException = ExpectedException.none();
private ChecksumFlywayMojo tested;
@Before
public void setUp() throws Exception {
tested = new ChecksumFlywayMojo();
}
@Test
public void shouldExecuteOnlyOneLocation() throws Exception {
tested.project = new MavenProject() {
@Override
public List<String> getCompileSourceRoots() {
List<String> files = new ArrayList<String>();
files.add("src/test/resources/java/");
return files;
}
};
tested.location = "db/migration";
tested.outputDirectory = temporaryFolder.newFolder().getAbsolutePath() + "insideFolder" + File.pathSeparator;
tested.execute();
assertThat(new File(tested.outputDirectory, "io/github/agileek/flyway/JavaMigrationChecksums.java"))
.hasSameContentAs(new File("src/test/resources/ExpectedJavaMigrationFile.java"));
}
@Test
public void shouldExecuteOnlyTwoLocations() throws Exception {
tested.project = new MavenProject() {
@Override
public List<String> getCompileSourceRoots() {
List<String> files = new ArrayList<String>();
files.add("src/test/resources/java/");
return files;
}
};
tested.locations = new String[] {"db/migration", "newdbpackage"};
tested.outputDirectory = temporaryFolder.newFolder().getAbsolutePath() + "insideFolder" + File.pathSeparator;
tested.execute();
assertThat(new File(tested.outputDirectory, "io/github/agileek/flyway/JavaMigrationChecksums.java"))
.hasSameContentAs(new File("src/test/resources/ExpectedJavaMigrationFileWithMultipleLocations.java"));
}
@Test
public void shouldGenerateFileChecksum() throws Exception {
List<File> files = new ArrayList<File>();
files.add(new File("src/test/resources/java/db/migration/Toto.java"));
JCodeModel actual = tested.generateEnumWithFilesChecksum(files);
File generatedJavaFolder = temporaryFolder.newFolder();
actual.build(generatedJavaFolder, (PrintStream) null);
assertThat(new File(generatedJavaFolder.getAbsolutePath(), "io/github/agileek/flyway/JavaMigrationChecksums.java"))
.hasSameContentAs(new File("src/test/resources/ExpectedJavaMigrationFile.java"));
}
@Test
public void shouldComputeFileChecksum() throws Exception {
int actual = tested.computeFileChecksum(new File("src/test/resources/java/db/migration/Toto.java"));
assertThat(actual).isEqualTo(-1927787285);
}
@Test
public void shouldComputeFileChecksum_failOnUnknownFile() throws Exception {
expectedException.expect(RuntimeException.class);
tested.computeFileChecksum(new File("src/test/resources/java/db/migration/Unknown.java"));
}
@Test
public void shouldGetJavaFilesFromSourceRoots() throws Exception {
List<String> compileSourceRoots = new ArrayList<String>();
compileSourceRoots.add("src/test/resources/java");
List<File> javaFiles = tested.getJavaFiles(compileSourceRoots, "/db/migration");
assertThat(javaFiles).containsExactly(new File("src/test/resources/java/db/migration/Toto.java"));
}
@Test
public void shouldGetJavaFilesFromSourceRoots_noFiles() throws Exception {
List<String> compileSourceRoots = new ArrayList<String>();
compileSourceRoots.add("src/test/resources/");
List<File> javaFiles = tested.getJavaFiles(compileSourceRoots, "/any");
assertThat(javaFiles).isEmpty();
}
} | mit |
AmityHighCSDevTeam/TerraGame | core/src/org/amityregion5/terragame/GameLoop.java | 1242 | package org.amityregion5.terragame;
public class GameLoop implements Runnable {
private void loop(double delta) {
}
@Override
public void run() {
long fpsTimer = System.currentTimeMillis();
int targetFPS = 30;
double nsPerUpdate = 1000000000.0 / targetFPS;
// last update
double then = System.nanoTime();
double unprocessed = 0;
boolean shouldLoop = false;
double lastUpdate = System.nanoTime();
while (true)
{
double now = System.nanoTime();
unprocessed += (now - then) / nsPerUpdate;
then = now;
// update
while (unprocessed >= 1)
{
// update++;
// update();
unprocessed--;
shouldLoop = true;
}
if (shouldLoop)
{
loop((now - lastUpdate) * targetFPS/1e9);
lastUpdate = now;
shouldLoop = false;
} else
{
try
{
Thread.sleep(1);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (System.currentTimeMillis() - fpsTimer > 1000)
{
// System.out.println("Update=" + update);
// System.out.println("FPS=" + fps);
// put code for processing fps data here!!!!
// update = 0;
fpsTimer = System.currentTimeMillis();
}
}
}
}
| mit |
n5xm/testspring | src/com/yiibaiMVC/Student.java | 447 | package com.yiibaiMVC;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
} | mit |
pworkshop/Peesdrq | tools/src/protocols/NEC/NECProtocolSpecScaled.java | 838 | package protocols.NEC;
import protocols.ProtocolSpecification;
import protocols.frame.FrameBitImpl;
/**
* Created by piotrek on 06.02.17.
*/
public class NECProtocolSpecScaled extends ProtocolSpecification {
private static final ProtocolSpecification metric =
NecProtocolSpecification.getInstance();
public NECProtocolSpecScaled(int scale) {
super(
metric.getStateShortTime()/scale,
metric.getStateLongTime()/scale,
metric.getCommandLen(),
metric.getAddressLen(),
metric.getPrefixPauseTime()/scale,
metric.getSufixPauseTime()/scale,
FrameBitImpl.vectorScalarDiv(metric.getPreamble(), scale),
FrameBitImpl.vectorScalarDiv(metric.getPostamble(),scale),
metric.getProtocolType()
);
}
}
| mit |
3203317/ppp | framework-core/src/main/java/com/xcysoft/framework/core/model/dbmeta/IErrorHandler.java | 201 | package com.xcysoft.framework.core.model.dbmeta;
/**
* 错误处理接口
*
* @author huangxin
*/
public interface IErrorHandler {
public abstract void onError(String s, Throwable throwable);
}
| mit |
boggad/jdk9-sample | sample-catalog/spring-jdk9/src/spring.aop/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java | 4235 | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.framework.autoproxy;
import java.util.ArrayList;
import java.util.List;
import org.springframework.aop.TargetSource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.util.Assert;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;
/**
* Auto proxy creator that identifies beans to proxy via a list of names.
* Checks for direct, "xxx*", and "*xxx" matches.
*
* <p>For configuration details, see the javadoc of the parent class
* AbstractAutoProxyCreator. Typically, you will specify a list of
* interceptor names to apply to all identified beans, via the
* "interceptorNames" property.
*
* @author Juergen Hoeller
* @since 10.10.2003
* @see #setBeanNames
* @see #isMatch
* @see #setInterceptorNames
* @see AbstractAutoProxyCreator
*/
@SuppressWarnings("serial")
public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator {
private List<String> beanNames;
/**
* Set the names of the beans that should automatically get wrapped with proxies.
* A name can specify a prefix to match by ending with "*", e.g. "myBean,tx*"
* will match the bean named "myBean" and all beans whose name start with "tx".
* <p><b>NOTE:</b> In case of a FactoryBean, only the objects created by the
* FactoryBean will get proxied. This default behavior applies as of Spring 2.0.
* If you intend to proxy a FactoryBean instance itself (a rare use case, but
* Spring 1.2's default behavior), specify the bean name of the FactoryBean
* including the factory-bean prefix "&": e.g. "&myFactoryBean".
* @see org.springframework.beans.factory.FactoryBean
* @see org.springframework.beans.factory.BeanFactory#FACTORY_BEAN_PREFIX
*/
public void setBeanNames(String... beanNames) {
Assert.notEmpty(beanNames, "'beanNames' must not be empty");
this.beanNames = new ArrayList<>(beanNames.length);
for (String mappedName : beanNames) {
this.beanNames.add(StringUtils.trimWhitespace(mappedName));
}
}
/**
* Identify as bean to proxy if the bean name is in the configured list of names.
*/
@Override
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource) {
if (this.beanNames != null) {
for (String mappedName : this.beanNames) {
if (FactoryBean.class.isAssignableFrom(beanClass)) {
if (!mappedName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
continue;
}
mappedName = mappedName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
}
if (isMatch(beanName, mappedName)) {
return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
}
BeanFactory beanFactory = getBeanFactory();
if (beanFactory != null) {
String[] aliases = beanFactory.getAliases(beanName);
for (String alias : aliases) {
if (isMatch(alias, mappedName)) {
return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
}
}
}
}
}
return DO_NOT_PROXY;
}
/**
* Return if the given bean name matches the mapped name.
* <p>The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches,
* as well as direct equality. Can be overridden in subclasses.
* @param beanName the bean name to check
* @param mappedName the name in the configured list of names
* @return if the names match
* @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
*/
protected boolean isMatch(String beanName, String mappedName) {
return PatternMatchUtils.simpleMatch(mappedName, beanName);
}
}
| mit |
vladimirivkovic/MBRS17 | XMI2NG/src/generator/model/FMClass.java | 3157 | package generator.model;
import generator.ParserEngine;
import generator.model.profile.Stereotype;
import generator.model.profile.UIClass;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class FMClass extends FMType {
private String visibility;
private List<FMProperty> properties = new ArrayList<FMProperty>();
private List<String> importedPackages = new ArrayList<String>();
private List<FMMethod> methods = new ArrayList<FMMethod>();
private List<FMConstraint> constraints = new ArrayList<FMConstraint>();
private String parentId = null;
private ArrayList<String> interfaceIds = new ArrayList<>();
private UIClass uIClass;
public FMClass(String name, String classPackage, String visibility) {
super(name, classPackage);
this.visibility = visibility;
}
public List<FMProperty> getProperties() {
return properties;
}
public Iterator<FMProperty> getPropertyIterator() {
return properties.iterator();
}
public void addProperty(FMProperty property) {
properties.add(property);
}
public int getPropertyCount() {
return properties.size();
}
public List<String> getImportedPackages() {
return importedPackages;
}
public Iterator<String> getImportedIterator() {
return importedPackages.iterator();
}
public void addImportedPackage(String importedPackage) {
importedPackages.add(importedPackage);
}
public int getImportedCount() {
return properties.size();
}
public String getVisibility() {
return visibility;
}
public void setVisibility(String visibility) {
this.visibility = visibility;
}
public List<FMMethod> getMethods() {
return methods;
}
public void addMethod(FMMethod method) {
methods.add(method);
}
public String getParent() {
return ParserEngine.getType(parentId);
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getLowerName() {
String s = this.getName();
return s.substring(0, 1).toLowerCase() + s.substring(1);
}
public UIClass getUIClass() {
return uIClass;
}
public void addConstraint(FMConstraint constraint)
{
constraints.add(constraint);
}
public List<FMConstraint> getConstraints() {
return constraints;
}
public void setConstraints(List<FMConstraint> constraints) {
this.constraints = constraints;
}
public void addInterfaceId(String interfaceId) {
interfaceIds.add(interfaceId);
}
public ArrayList<String> getInterfaceIds() {
return interfaceIds;
}
public ArrayList<String> getInterfaces() {
ArrayList<String> interfaces = new ArrayList<String>();
for (String interfaceId : interfaceIds) {
interfaces.add(ParserEngine.getType(interfaceId));
}
return interfaces;
}
@Override
public void addStereotype(Stereotype st) {
super.addStereotype(st);
if (st instanceof UIClass) {
uIClass = (UIClass) st;
}
}
public List<FMProperty> getLookupProperties() {
ArrayList<FMProperty> lookups = new ArrayList<FMProperty>();
for (FMProperty p : properties) {
if (p.getLookup() != null) {
lookups.add(p);
}
}
return lookups;
}
}
| mit |
tuura/workcraft | workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/CircuitComponent.java | 3235 | package org.workcraft.plugins.circuit;
import org.workcraft.annotations.VisualClass;
import org.workcraft.dom.math.MathGroup;
import org.workcraft.dom.references.FileReference;
import org.workcraft.observation.PropertyChangedEvent;
import org.workcraft.utils.Hierarchy;
import java.util.ArrayList;
import java.util.Collection;
@VisualClass(VisualCircuitComponent.class)
public class CircuitComponent extends MathGroup {
public static final String PROPERTY_MODULE = "Module";
public static final String PROPERTY_IS_ENVIRONMENT = "Treat as environment";
public static final String PROPERTY_REFINEMENT = "Refinement";
private String module = "";
private boolean isEnvironment = false;
private FileReference refinement = null;
public void setModule(String value) {
if (value == null) value = "";
if (!value.equals(module)) {
module = value;
sendNotification(new PropertyChangedEvent(this, PROPERTY_MODULE));
}
}
public String getModule() {
return module;
}
public boolean isMapped() {
return (module != null) && !module.isEmpty();
}
public void setIsEnvironment(boolean value) {
if (isEnvironment != value) {
isEnvironment = value;
sendNotification(new PropertyChangedEvent(this, PROPERTY_IS_ENVIRONMENT));
}
}
public FileReference getRefinement() {
return refinement;
}
public void setRefinement(FileReference value) {
if (refinement != value) {
refinement = value;
sendNotification(new PropertyChangedEvent(this, PROPERTY_REFINEMENT));
}
}
public boolean hasRefinement() {
return (refinement != null) && (refinement.getFile() != null);
}
public boolean getIsEnvironment() {
return isEnvironment;
}
public Collection<Contact> getContacts() {
return Hierarchy.filterNodesByType(getChildren(), Contact.class);
}
public Collection<Contact> getInputs() {
ArrayList<Contact> result = new ArrayList<>();
for (Contact contact: getContacts()) {
if (contact.isInput()) {
result.add(contact);
}
}
return result;
}
public Collection<Contact> getOutputs() {
ArrayList<Contact> result = new ArrayList<>();
for (Contact contact: getContacts()) {
if (contact.isOutput()) {
result.add(contact);
}
}
return result;
}
public Contact getFirstInput() {
Contact result = null;
for (Contact contact: getContacts()) {
if (contact.isInput()) {
result = contact;
break;
}
}
return result;
}
public Contact getFirstOutput() {
Contact result = null;
for (Contact contact: getContacts()) {
if (contact.isOutput()) {
result = contact;
break;
}
}
return result;
}
public boolean isSingleInputSingleOutput() {
return (getContacts().size() == 2) && (getFirstInput() != null) && (getFirstOutput() != null);
}
}
| mit |
chuckbuckethead/cypher | src/main/java/com/github/chuckbuckethead/cypher/keys/RSAKey.java | 6215 | /*
* Copyright (C) 2014 Carlos González.
* All rights reserved.
*
* The software in this package is published under the terms of the MIT
* license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on Jul 17, 2014 by Carlos González
*/
package com.github.chuckbuckethead.cypher.keys;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.encodings.PKCS1Encoding;
import org.bouncycastle.crypto.engines.RSABlindedEngine;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
/**
* Asymmetric cryptography implementation of the <code>CryptoKey</code>
* interface using the RSA encryption algorithm.
*
* @author Carlos González
*/
public class RSAKey extends AbstractCryptoKey implements CryptoKey
{
private String publicKey;
private String privateKey;
// Ciphers
private transient AsymmetricBlockCipher encodeCipher;
private transient AsymmetricBlockCipher decodeCipher;
public static final int MINIMUM_KEY_SIZE = 512;
/**
* Default
*/
public RSAKey()
{
}
/**
* @param publicKey
* @param privateKey
*/
public RSAKey(String publicKey, String privateKey)
{
this.publicKey = publicKey;
this.privateKey = privateKey;
}
/**
* @return the privateKey
*/
public String getPrivateKey()
{
return privateKey;
}
/**
* @param privateKey
* the privateKey to set
*/
public void setPrivateKey(String privateKey)
{
this.privateKey = privateKey;
}
/**
* @return the publicKey
*/
public String getPublicKey()
{
return publicKey;
}
/**
* @param publicKey
* the publicKey to set
*/
public void setPublicKey(String publicKey)
{
this.publicKey = publicKey;
}
/*
* (non-Javadoc)
*
* @see com.github.chuckbuckethead.cypher.keys.CryptoKey#getAlgorithmName()
*/
public String getAlgorithmName()
{
return CryptoKey.RSA_ALGORITHM;
}
/*
* (non-Javadoc)
*
* @see com.github.chuckbuckethead.cypher.keys.AbstractCryptoKey#getEncryptCipher()
*/
@Override
protected Cipher getEncryptCipher()
{
throw new UnsupportedOperationException("This method should never be called.");
}
/*
* (non-Javadoc)
*
* @see com.github.chuckbuckethead.cypher.keys.AbstractCryptoKey#getDecryptCipher()
*/
@Override
protected Cipher getDecryptCipher()
{
throw new UnsupportedOperationException("This method should never be called.");
}
/*
* (non-Javadoc)
*
* @see
* com.github.chuckbuckethead.cypher.keys.AbstractCryptoKey#decryptBytes(java.lang
* .String)
*/
@Override
public synchronized byte[] decryptBytes(String base64Str)
{
byte[] bytes = null;
try
{
byte[] dec = getEncoder().decode(base64Str);
// Decrypt
bytes = getRSADecryptCipher().processBlock(dec, 0, dec.length);
}
catch (InvalidCipherTextException e)
{
e.printStackTrace();
}
return bytes;
}
/*
* (non-Javadoc)
*
* @see
* com.github.chuckbuckethead.cypher.keys.AbstractCryptoKey#encryptBytes(byte[])
*/
@Override
public synchronized String encryptBytes(byte[] bytes)
{
String encryptedStr = null;
try
{
// Encrypt
byte[] enc = getRSAEncryptCipher().processBlock(bytes, 0,
bytes.length);
// Encode bytes to base64 to get a string
encryptedStr = getEncoder().encode(enc);
}
catch (InvalidCipherTextException e)
{
e.printStackTrace();
}
return encryptedStr;
}
/**
* @return an RSA decryption cipher
*/
protected synchronized AsymmetricBlockCipher getRSADecryptCipher()
{
if (decodeCipher == null)
{
try
{
byte[] bytes = getEncoder().decode(privateKey);
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PrivateKey key = keyFactory.generatePrivate(privateKeySpec);
this.decodeCipher = new PKCS1Encoding(new RSABlindedEngine());
decodeCipher.init(false, generatePrivateKeyParameter((RSAPrivateKey) key));
}
catch (Exception e)
{
throw new RuntimeException("Error constructing Cipher: ", e);
}
}
return decodeCipher;
}
/**
* @param key
* @return
*/
private static RSAKeyParameters generatePrivateKeyParameter(
RSAPrivateKey key)
{
RSAKeyParameters parameters = null;
if (key instanceof RSAPrivateCrtKey)
{
RSAPrivateCrtKey crtKey = (RSAPrivateCrtKey) key;
parameters = new RSAPrivateCrtKeyParameters(crtKey.getModulus(),
crtKey.getPublicExponent(), crtKey.getPrivateExponent(),
crtKey.getPrimeP(), crtKey.getPrimeQ(),
crtKey.getPrimeExponentP(), crtKey.getPrimeExponentQ(),
crtKey.getCrtCoefficient());
}
else
{
parameters = new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent());
}
return parameters;
}
/**
* @return
*/
protected synchronized AsymmetricBlockCipher getRSAEncryptCipher()
{
if (encodeCipher == null)
{
try
{
byte[] bytes = getEncoder().decode(publicKey);
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PublicKey key = keyFactory.generatePublic(publicKeySpec);
this.encodeCipher = new PKCS1Encoding(new RSABlindedEngine());
encodeCipher.init(true, generatePublicKeyParameter((RSAPublicKey) key));
}
catch (Exception e)
{
throw new RuntimeException("Error constructing Cipher: ", e);
}
}
return encodeCipher;
}
/**
* @param key
* @return
*/
private static RSAKeyParameters generatePublicKeyParameter(RSAPublicKey key)
{
return new RSAKeyParameters(false, key.getModulus(), key.getPublicExponent());
}
} | mit |
NomeAutomation/NomeAutomation | src/com/nomeautomation/utility/server/ServerCommands.java | 737 | package com.nomeautomation.utility.server;
/**
* All possible commands the device manager server can respond to
*
*/
public class ServerCommands{
public enum ServerCommand {
GET_HOUSE_CONSUMPTION,
GET_DAILY_CONSUMPTION,
GET_MONTHLY_CONSUMPTION,
GET_DEVICE_TOTAL_CONSUMPTION,
GET_ALL_DEVICES,
GET_DEVICE,
SEND_DEVICE_COMMAND,
CHANGE_DEVICE_NAME,
CHANGE_DEVICE_ROOM,
REMOVE_DEVICE,
GET_ALL_ROOMS,
ADD_ROOM,
CHANGE_ROOM_NAME,
REMOVE_ROOM,
ADD_UPDATE_SCHEDULE,
REMOVE_SCHEDULE,
GET_ALL_SCHEDULES,
ACTIVATE_SCHEDULE,
ACCEPT_SUGGESTION,
DECLINE_SUGGESTION,
HIDE_SUGGESTION,
GET_SIMULATED_SCHEDULES_POWER,
GET_SUGGESTIONS,
PASS,
FAIL,
UNKNOWN, ;
}
}
| mit |
alternet/alternet.ml | tools/src/test/java/org/example/conf/generated/test/Mail.java | 2100 | package org.example.conf.generated.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;
import javax.annotation.Generated;
import ml.alternet.properties.Binder;
/**
* Configuration structure for "mail.properties"
*
* DO NOT EDIT : this class has been generated !
*/
@Generated(value="ml.alternet.properties.Generator", date="2017-12-29")
public class Mail {
public Mail_ mail;
public static class Mail_ {
public Smtp smtp;
public static class Smtp {
public Starttls starttls;
public static class Starttls {
public boolean enable;
}
public boolean auth;
public String host;
public int port;
public Ssl ssl;
public static class Ssl {
public String trust;
}
}
}
public String username;
public char[] password;
public Name name;
public static class Name {
public String expediteur;
}
public static Mail unmarshall(InputStream properties) throws IOException {
return Binder.unmarshall(
properties,
Mail.class
);
}
public Mail update(InputStream properties) throws IOException {
return Binder.unmarshall(
properties,
this
);
}
public static Mail unmarshall(Reader properties) throws IOException {
return Binder.unmarshall(
properties,
Mail.class
);
}
public Mail update(Reader properties) throws IOException {
return Binder.unmarshall(
properties,
this
);
}
public static Mail unmarshall(Properties properties) throws IOException {
return Binder.unmarshall(
properties,
Mail.class
);
}
public Mail update(Properties properties) throws IOException {
return Binder.unmarshall(
properties,
this
);
}
}
| mit |
analogweb/servlet-plugin | src/main/java/org/analogweb/servlet/ServletComponentsValueResolver.java | 1117 | package org.analogweb.servlet;
import java.lang.annotation.Annotation;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import org.analogweb.InvocationMetadata;
import org.analogweb.RequestContext;
import org.analogweb.RequestValueResolver;
import org.analogweb.util.RequestContextResolverUtils;
/**
* @author y2k2mt
*/
public class ServletComponentsValueResolver implements RequestValueResolver {
@Override
public Object resolveValue(RequestContext request,
InvocationMetadata metadata, String query, Class<?> requiredType,
Annotation[] parameterAnnotations) {
ServletRequestContext src = RequestContextResolverUtils
.resolveRequestContext(request);
if (src == null) {
return null;
}
if (ServletRequest.class.isAssignableFrom(requiredType)) {
return src.getServletRequest();
} else if (HttpSession.class.isAssignableFrom(requiredType)) {
return src.getServletRequest().getSession(true);
} else if (ServletContext.class.isAssignableFrom(requiredType)) {
return src.getServletContext();
}
return null;
}
}
| mit |
arvjus/fintrack-java | fintrack-web/src/main/java/org/zv/fintrack/rest/Incomes.java | 2650 | package org.zv.fintrack.rest;
import java.util.List;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.Produces;
import org.zv.fintrack.pd.Income;
import org.zv.fintrack.pd.bean.SummaryBean;
import org.zv.fintrack.ejb.api.IncomeDao;
import org.zv.fintrack.util.JndiUtil;
@Path("/incomes")
public class Incomes {
private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
@POST
@Path("/new")
@Produces({"application/xml", "application/json"})
public Income addNew(@FormParam("createDate") String createDate, @FormParam("userId") String userId, @FormParam("amount") Float amount, @FormParam("descr") String descr) throws ParseException {
IncomeDao incomeDao = (IncomeDao)JndiUtil.lookup("ejb/IncomeDao");
Income income = new Income();
income.setCreateDate(simpleDateFormat.parse(createDate));
income.setUserId(userId);
income.setAmount(amount);
income.setDescr(descr);
income = incomeDao.save(income);
return income;
}
@GET
@Path("/latest-{max}")
@Produces({"application/xml", "application/json"})
public List<Income> getLatest(@PathParam("max") int max) {
IncomeDao incomeDao = (IncomeDao)JndiUtil.lookup("ejb/IncomeDao");
return incomeDao.getAll(max);
}
@POST
@Path("/list")
@Produces({"application/xml", "application/json"})
public List<Income> getList(@FormParam("dateFrom") String dateFrom, @FormParam("dateTo") String dateTo, @FormParam("userId") String userId) throws ParseException {
IncomeDao incomeDao = (IncomeDao)JndiUtil.lookup("ejb/IncomeDao");
return incomeDao.getPlain(simpleDateFormat.parse(dateFrom), simpleDateFormat.parse(dateTo), userId);
}
@POST
@Path("/summary/simple")
@Produces({"application/xml", "application/json"})
public List<SummaryBean> getSummarySimple(@FormParam("dateFrom") String dateFrom, @FormParam("dateTo") String dateTo) throws ParseException {
IncomeDao incomeDao = (IncomeDao)JndiUtil.lookup("ejb/IncomeDao");
return incomeDao.getSummarySimple(simpleDateFormat.parse(dateFrom), simpleDateFormat.parse(dateTo));
}
@POST
@Path("/summary/bymonth")
@Produces({"application/xml", "application/json"})
public List<SummaryBean> getSummaryMonth(@FormParam("dateFrom") String dateFrom, @FormParam("dateTo") String dateTo) throws ParseException {
IncomeDao incomeDao = (IncomeDao)JndiUtil.lookup("ejb/IncomeDao");
return incomeDao.getSummaryByMonth(simpleDateFormat.parse(dateFrom), simpleDateFormat.parse(dateTo));
}
}
| mit |
aenon/OnlineJudge | leetcode/1.Array_String/1.two-sum_brute_force.java | 455 | /* 1 Two Sum I
* O(n^2) runtime, O(n) space - Brute force
*/
public class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
int ni = nums[i];
for (int j = i + 1; j < nums.length; j++) {
int nj = nums[j];
if (ni + nj == target) {
return new int[] {i, j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
} | mit |
tmlewallen/Eevee | src/recognizer/Parser.java | 16717 | package recognizer;
import lexical_analysis.Lexeme;
import environment.Environment;
public class Parser {
Lexeme tree;
Environment e;
public Parser (Lexeme tree,Environment E){
this.tree = tree;
e = E;
getObjDecl(e,tree.getLeft().getLeft());
getMainDef(e,tree.getRight());
}
public Environment getEnvironment(){
return e;
}
public void getObjDecl(Environment e,Lexeme l){
if (l != null){
objDecl(e,l.getLeft());
getObjDecl(e,l.getRight());
}
}
public void objDecl(Environment e, Lexeme l){
if (l == null){
return;
}
Lexeme id = l.getRight();
Lexeme arg = id.getRight().getRight().getLeft();
Lexeme objDecl = id.getRight().getRight().getRight().getLeft();
Lexeme val = expr(e,arg);
// System.out.println("SETTING ENV FOR VAR " + id);
id.setObjEnv(initObjEnv(e,objDecl));
e.insert(id, val);
// System.out.println(e);
}
public void getMainDef(Environment e,Lexeme l){
//Skip main stuff
l = l.getRight().getRight().getRight().getRight().getRight().getRight().getRight().getLeft();
// System.out.println(l);
codeBlock(e,l);
}
public void statement(Environment e, Lexeme l){
if (l.type == Lexeme.Type.GLUE){
if (l.getLeft().type == Lexeme.Type.VAR || l.getLeft().type == Lexeme.Type.OS){ //CHANGE THIS LINE TO ACCEPT MORE TYPES
objDecl(e, l.getLeft());
}
else if (l.getLeft().type == Lexeme.Type.FUNC){
function(e,l);
}
else{expr(e,l.getLeft());}
}
else{
if (l.type == Lexeme.Type.WHILE){
whileLoop(e,l);
}
else{
conditional(e, l);
}
}
}
public Lexeme eval(Lexeme a, Lexeme operator, Lexeme b){
switch(operator.type){
case PLUS: //CONCAT for strings, ADDITION for ints
if (a.type == Lexeme.Type.STRING && b.type == Lexeme.Type.STRING){return new Lexeme(Lexeme.Type.STRING, a.sval + b.sval,operator.getLineNumber());} //STRING + STRING
else if (a.type == Lexeme.Type.STRING && b.type == Lexeme.Type.INTEGER){return new Lexeme(Lexeme.Type.STRING, a.sval + Integer.toString(b.ival),operator.getLineNumber());} //STRING + INT = STRING
else if (a.type == Lexeme.Type.INTEGER && b.type == Lexeme.Type.INTEGER){return new Lexeme(Lexeme.Type.INTEGER,a.ival + b.ival,operator.getLineNumber());}
else if (a.type == Lexeme.Type.OBRACKET){return append(a,operator,b);}
else if (a.type == Lexeme.Type.STRING && b.type == Lexeme.Type.FALSE){return new Lexeme(Lexeme.Type.STRING, a.sval + "FALSE", operator.getLineNumber());}
else if (a.type == Lexeme.Type.STRING && b.type == Lexeme.Type.TRUE){return new Lexeme(Lexeme.Type.STRING, a.sval + "TRUE", operator.getLineNumber());}
else{
FatalError_Parser("Cannot apply + operator to types " + Lexeme.typeToString(a.type) + " and " + Lexeme.typeToString(b.type), operator.getLineNumber());
}
case MINUS:
if (a.type == Lexeme.Type.INTEGER && b.type == Lexeme.Type.INTEGER){return new Lexeme(Lexeme.Type.INTEGER,a.ival - b.ival,operator.getLineNumber());}
else{
FatalError_Parser("Cannot apply - operator to types " + Lexeme.typeToString(a.type) + " and " + Lexeme.typeToString(b.type), operator.getLineNumber());
break;
}
case MULT:
if (a.type == Lexeme.Type.INTEGER && b.type == Lexeme.Type.INTEGER){return new Lexeme(Lexeme.Type.INTEGER,a.ival * b.ival,operator.getLineNumber());}
else{
FatalError_Parser("Cannot apply * operator to types " + Lexeme.typeToString(a.type) + " and " + Lexeme.typeToString(b.type), operator.getLineNumber());
break;
}
case DIV:
if (a.type == Lexeme.Type.INTEGER && b.type == Lexeme.Type.INTEGER){return new Lexeme(Lexeme.Type.INTEGER,a.ival / b.ival,operator.getLineNumber());}
else{
FatalError_Parser("Cannot apply / operator to types " + Lexeme.typeToString(a.type) + " and " + Lexeme.typeToString(b.type), operator.getLineNumber());
break;
}
case EXP:
if (a.type == Lexeme.Type.INTEGER && b.type == Lexeme.Type.INTEGER){return new Lexeme(Lexeme.Type.INTEGER, (int)Math.pow(a.ival, b.ival),operator.getLineNumber());}
else{
FatalError_Parser("Cannot apply + operator to types " + Lexeme.typeToString(a.type) + " and " + Lexeme.typeToString(b.type), operator.getLineNumber());
break;
}
default:
FatalError_Parser("Invalid Operator " +operator.sval, operator.getLineNumber());
break;
}
return null;
}
public Lexeme expr(Environment e, Lexeme l){ //Takes glue with expr at left
if (l == null){
// System.out.println("expr retuns NULL");
return new Lexeme(Lexeme.Type.NULL);
}
Lexeme operand = l.getLeft();
Lexeme operator = l.getLeft().getRight();
Lexeme val;
if (operand.type == Lexeme.Type.ID){ //If variable, get value;
Environment objEnv = e.getKey(operand).getObjEnv();
// System.out.println(objEnv);
//SET VAL BEGIN
if (operand.getLeft() != null && operand.getLeft().type == Lexeme.Type.OPAREN){ //If Function call...
// System.out.println();
Lexeme argList = argList(e, operand.getLeft());
val = functionCall(e,operand,argList);
if (operator != null && operator.type == Lexeme.Type.EQUALS){
FatalError_Parser("Cannot use assignment on Function Call to " + operand.sval, operand.getLineNumber());
}
}
else if (operand.getLeft() != null && operand.getLeft().type == Lexeme.Type.OBRACKET){ // If array access.....
Lexeme ndx = expr(e,operand.getLeft().getRight());
if (ndx.type != Lexeme.Type.INTEGER){
FatalError_Parser("Array must be integer, not "+ Lexeme.typeToString(ndx.type), operand.getLineNumber());
}
Lexeme element = e.getNdx(operand,ndx.ival);
element.setRight(ndx);
val = applyOverride(objEnv,"GETNDX",element);
if (operator != null && operator.type == Lexeme.Type.EQUALS){
Lexeme result = expr(e,l.getRight());
result.setRight(ndx);//Set right lexeme to ndx for dual argument calls to overrides
return applyOverride(objEnv,"GETNDX",e.updateNdx(operand,applyOverride(objEnv,"SETNDX",result),ndx.ival));
}
}
else{
val = applyOverride(objEnv,"GET",e.get(operand));
}
//SET VAL END
if (operator == null){
return val;
}
else if (operator.type == Lexeme.Type.EQUALS){ //If assignment...
Lexeme tempVal = applyOverride(objEnv,"SET",expr(e,l.getRight())); //Need to link new value to obj lexemes to keep obj stuff
// Lexeme object = e.get(operand).getRight();
// tempVal.setRight(object);
return applyOverride(objEnv,"GET",e.update(operand,tempVal)); //Will overwrite function calls...
}
else{
return eval(val,operator,expr(e,l.getRight()));
}
}
else{ //Is a literal
val = operand;
if (operand.type == Lexeme.Type.OBRACKET){
Lexeme elementPlaceholder = operand.getLeft();
val = new Lexeme(Lexeme.Type.OBRACKET);
val.setLeft(element(e,elementPlaceholder.getLeft()));
}
if (operator == null){
return val;
}
else{
return eval(val,operator,expr(e,l.getRight()));
}
}
}
public Lexeme element(Environment e, Lexeme l){
if (l == null){
return null;
}
l.setLeft(expr(e,l.getLeft())); //Eval this element
l.setRight(element(e,l.getRight())); //eval next element
return l;//return it
}
public Lexeme argList(Environment e, Lexeme l){//Take an arg list, including Parens, and evals each argument
// System.out.println("argList: " + l);//Debug calls. Should be (
Lexeme placeholder = l.getRight(); //Glue node
if (placeholder.type == Lexeme.Type.NULL){return null;} //No arguments to evaluate
else{
Lexeme argGlue = placeholder.getLeft();
Lexeme result = new Lexeme(Lexeme.Type.GLUE); //Lexeme tree we will return;
Lexeme rest = result;
Lexeme arg;
while (argGlue != null){
arg = argGlue.getLeft();
if (arg.getLeft().type == Lexeme.Type.FUNC){ //If its a func def, just pass, dont add to env
rest.setLeft(arg.getLeft().getRight().getRight()); //Copied from val arg in function()
}
else{
rest.setLeft(expr(e,arg));
}
argGlue = argGlue.getRight();
if (argGlue != null){
rest = rest.setAndAdvanceRight(new Lexeme(Lexeme.Type.GLUE));
}
}
return result;
}
}
public Lexeme functionCall(Environment callEnv, Lexeme signature, Lexeme args){//Takes the def env and lexeme that hold args
// System.out.println("Function Call: \n\tSignature: " + signature + "\n\tArgs: " + args);
// args = args.cloneTree(); //unnecessary since everything in environment is a copy of the actual lexeme (clone)
Lexeme definition = callEnv.get(signature);
Environment defEnv = definition.getObjEnv();
if (definition.type != Lexeme.Type.OPAREN){
FatalError_Parser("Attempt to call " + signature.sval + ", a non-function type as a function", signature.getLineNumber());
}
Environment local = new Environment(defEnv);
Lexeme parms = definition.getRight().getLeft(); //Placeholder -> acutual parm list
if (setParms(local, parms, args) == null){
FatalError_Parser("Incorrect number of arguments to function " + signature.sval, signature.getLineNumber());
}
Lexeme codePlaceholder = definition.getRight().getRight().getRight().getRight();// ( -> parms -> ) -> { -> codePlaceholder
Lexeme returnStatementPlaceholder = codePlaceholder.getRight(); // codePlaceholder -> returnStatementPlaceholder
if (codePlaceholder.type != Lexeme.Type.NULL){
codeBlock(local,codePlaceholder.getLeft());
}
if (returnStatementPlaceholder.type != Lexeme.Type.NULL){
return returnStatement(local,returnStatementPlaceholder.getLeft());
}
return null;
}
public Lexeme returnStatement(Environment e, Lexeme l){
Lexeme value = l.getRight();
return expr(e,value);
}
public Environment setParms(Environment e, Lexeme parms, Lexeme args){//Sets each parm to the provided args in the env provided. Ordered.
while (parms!= null && args != null){
if (parms.type == Lexeme.Type.COMMA){
parms = parms.getRight();
}
else{
e.insert(parms, args.getLeft());
parms = parms.getRight();
args = args.getRight();
}
}
if (args != null || parms != null){ //Make sure args !> parms
return null;
}
return e;
}
public Lexeme function(Environment e, Lexeme l){ //Takes glue that holds a function def
Lexeme signature = l.getLeft().getRight();
Lexeme body = l.getLeft().getRight().getRight();
body.setObjEnv(e); //Save defining environment for use in calls
return e.insert(signature,body);
}
public void conditional(Environment e, Lexeme l){
Environment local = new Environment(e);
Lexeme predicateGlue = l.getRight().getRight(); //if -> ( -> predicate Glue
Lexeme codePlaceholder = predicateGlue.getRight().getRight().getRight(); //predicateGlue -> ) -> { -> codePlaceholder
if (predicate(local,predicateGlue.getLeft()).type == Lexeme.Type.TRUE){
codeBlock(local, codePlaceholder.getLeft());
}
else{
Lexeme elseClause = codePlaceholder.getRight().getRight();
if (elseClause.type != Lexeme.Type.NULL){
codePlaceholder = elseClause.getLeft().getRight().getRight();
codeBlock(local,codePlaceholder.getLeft());
}
}
}
public void whileLoop(Environment e, Lexeme l){
Environment local = new Environment(e);
Lexeme predicateGlue = l.getRight().getRight(); //while -> ( -> predicate Glue
Lexeme codePlaceholder = predicateGlue.getRight().getRight().getRight(); //predicateGlue -> ) -> { -> codePlaceholder
while (predicate(local,predicateGlue.getLeft()).type == Lexeme.Type.TRUE){
codeBlock(local, codePlaceholder.getLeft());
}
}
public Lexeme predicate(Environment e, Lexeme l) {
Lexeme op = l.getLeft();
if (op.type == Lexeme.Type.NOT){
Lexeme result = predicate(e,l.getRight());
if (result.type == Lexeme.Type.TRUE){return new Lexeme(Lexeme.Type.FALSE);}
else{return new Lexeme(Lexeme.Type.TRUE);} //NOT BOOLEAN TYPES TRANSLATE TO FALSE
}
Lexeme val = op;
if (op.type == Lexeme.Type.ID){val = e.get(op);}
if (op.getRight() != null){
Lexeme operator1 = op.getRight();
Lexeme operator2 = operator1.getRight();
return predicateEval(val,operator1,operator2,predicate(e,l.getRight()));
}
else{
return val;
}
}
public Lexeme predicateEval(Lexeme a, Lexeme op1, Lexeme op2, Lexeme b){
switch(op1.type){
case AND:
if (a.type == Lexeme.Type.TRUE && b.type == Lexeme.Type.TRUE){return new Lexeme(Lexeme.Type.TRUE);}
else{return new Lexeme(Lexeme.Type.FALSE);}
case OR:
if (a.type == Lexeme.Type.TRUE || b.type == Lexeme.Type.TRUE){return new Lexeme(Lexeme.Type.TRUE);}
else{return new Lexeme(Lexeme.Type.FALSE);}
case EQUALS:
if (a.type != b.type){ return new Lexeme(Lexeme.Type.FALSE);}
else{
if (a.type == Lexeme.Type.INTEGER){
if (a.ival == b.ival){return new Lexeme(Lexeme.Type.TRUE);}
else{return new Lexeme(Lexeme.Type.FALSE);}
}
else if (a.type == Lexeme.Type.NULL){return new Lexeme(Lexeme.Type.TRUE);}
else{
if (a.sval.equals(b.sval)){return new Lexeme(Lexeme.Type.TRUE);}
else {return new Lexeme(Lexeme.Type.FALSE);}
}
}
case GT:
if (a.type != b.type || a.type != Lexeme.Type.INTEGER){ return new Lexeme(Lexeme.Type.FALSE);}
else{
if (op2 != null){
if (a.ival >= b.ival){return new Lexeme(Lexeme.Type.TRUE);}
else{return new Lexeme(Lexeme.Type.FALSE);}
}
else{
if (a.ival > b.ival){return new Lexeme(Lexeme.Type.TRUE);}
else{return new Lexeme(Lexeme.Type.FALSE);}
}
}
case LT:
if (a.type != b.type || a.type != Lexeme.Type.INTEGER){ return new Lexeme(Lexeme.Type.FALSE);}
else{
if (op2 != null){
if (a.ival <= b.ival){return new Lexeme(Lexeme.Type.TRUE);}
else{return new Lexeme(Lexeme.Type.FALSE);}
}
else{
if (a.ival < b.ival){return new Lexeme(Lexeme.Type.TRUE);}
else{return new Lexeme(Lexeme.Type.FALSE);}
}
}
default:
break;
}
return null;
}
public Environment initObjEnv(Environment e, Lexeme objDef){
Environment objLocal = new Environment(e); //Gonna return this once we set everything up
if (objDef == null){
return objLocal;
}
Lexeme objDeclPlaceholder = objDef.getRight();
if (objDeclPlaceholder.type == Lexeme.Type.GLUE){
getObjDecl(objLocal,objDeclPlaceholder.getLeft());
}
Lexeme overridesPlaceholder = objDeclPlaceholder.getRight();
if (overridesPlaceholder.type == Lexeme.Type.GLUE){
setOverrides(objLocal,overridesPlaceholder.getLeft());
}
Lexeme helperPlaceholder = overridesPlaceholder.getRight();
if (helperPlaceholder.type == Lexeme.Type.GLUE){
setHelpers(objLocal,helperPlaceholder.getLeft());
}
// System.out.println(objLocal);
return objLocal;
}
public Lexeme applyOverride(Environment e, String overrideType, Lexeme arg){
Lexeme signature = new Lexeme(Lexeme.Type.ID, overrideType, arg.getLineNumber());
if (e == null || !e.exists(signature)){return arg;}
Lexeme args = new Lexeme(Lexeme.Type.GLUE).setLeftReturnSelf(arg);
if (overrideType.equals("GETNDX") || overrideType.equals("SETNDX")){ //passing two arguments for GETNDX and SETNDX
args.setRight(new Lexeme(Lexeme.Type.GLUE).setLeftReturnSelf(arg.getRight()));
}
return functionCall(e,signature,args);
}
public void setOverrides(Environment e, Lexeme overrideList){
if (overrideList == null){
return;
}
Lexeme override = overrideList.getLeft();
Lexeme sig = new Lexeme(Lexeme.Type.ID, Lexeme.typeToString(override.type), override.getLineNumber());
Lexeme function = override.getRight().getRight();
Lexeme funcBody = function.getLeft().getRight().getRight();
funcBody.setObjEnv(e); //Set def env for overrides
e.insert(sig, funcBody);
setOverrides(e,overrideList.getRight());
}
public void setHelpers(Environment e, Lexeme helperList){
if (helperList == null){
return;
}
function(e,helperList.getLeft());
setHelpers(e, helperList.getRight());
}
public void codeBlock(Environment e, Lexeme l){
if (l == null){
return;
}
statement(e,l.getLeft());
if (l.getRight() != null){codeBlock(e,l.getRight());}
}
private void FatalError_Parser(String msg, Integer line){
System.out.println("FATAL ERROR in PARSER on line: " + line +" - " + msg);
System.exit(1);
}
public Lexeme append(Lexeme arr,Lexeme operator, Lexeme val){ //Takes operator for line number
if (arr.type != Lexeme.Type.OBRACKET){
FatalError_Parser("Attempted to get index of type " + Lexeme.typeToString(arr.type) + ". Dont do that.", operator.getLineNumber());
}
Lexeme element;
if (arr.getLeft() == null){
arr.setLeft(new Lexeme(Lexeme.Type.GLUE).setLeftReturnSelf(val));
return arr;
}
else{
element = arr.getLeft();
while (element.getRight() != null){
element = element.getRight();
}
element.setRight(new Lexeme(Lexeme.Type.GLUE).setLeftReturnSelf(val));
return arr;
}
}
}
| mit |
DamienFremont/blog | 20171119-springboot-datasource/springboot-datasource-2-semi_autoconfig/src/main/java/com/damienfremont/blog/Application.java | 356 | package com.damienfremont.blog;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
@SpringBootApplication( //
scanBasePackageClasses = { DataSourceConfig.class })
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| mit |
albu89/Hive2Hive-dev | org.hive2hive.core/src/main/java/org/hive2hive/core/events/framework/IEventGenerator.java | 124 | package org.hive2hive.core.events.framework;
public interface IEventGenerator {
// so far, just a marker interface
}
| mit |
arnaudroger/SimpleFlatMapper | sfm-converter-joda-time/src/main/java/org/simpleflatmapper/converter/joda/impl/CharSequenceToJodaLocalDateTimeConverter.java | 802 | package org.simpleflatmapper.converter.joda.impl;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormatter;
import org.simpleflatmapper.converter.Context;
import org.simpleflatmapper.converter.ContextualConverter;
public class CharSequenceToJodaLocalDateTimeConverter implements ContextualConverter<CharSequence, LocalDateTime> {
private final DateTimeFormatter dateTimeFormatter;
public CharSequenceToJodaLocalDateTimeConverter(DateTimeFormatter dateTimeFormatter) {
this.dateTimeFormatter = dateTimeFormatter;
}
@Override
public LocalDateTime convert(CharSequence in, Context context) throws Exception {
if (in == null || in.length() == 0) return null;
return dateTimeFormatter.parseLocalDateTime(String.valueOf(in));
}
}
| mit |
lmcgrath/sterling | sterling-lang/src/test/java/sterling/lang/expression/ConditionalTest.java | 1086 | package sterling.lang.expression;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static sterling.lang.expression.ExpressionFactory.conditional;
import static sterling.lang.expression.ExpressionFactory.constant;
import org.junit.Before;
import org.junit.Test;
import sterling.lang.SterlingException;
public class ConditionalTest {
private Expression trueConditional;
private Expression falseConditional;
@Before
public void setUp() {
trueConditional = conditional(constant(true), constant("apples"), constant("bananas"));
falseConditional = conditional(constant(false), constant("apples"), constant("bananas"));
}
@Test
public void shouldGiveApples_whenConditionalIsTrue() throws SterlingException {
assertThat(trueConditional.reduce(), equalTo((Expression) constant("apples")));
}
@Test
public void shouldGiveBananas_whenConditionalIsFalse() throws SterlingException {
assertThat(falseConditional.reduce(), equalTo((Expression) constant("bananas")));
}
}
| mit |
phorust/BitSlayer | angelgame/src/com/cal/angelgame/Decoration.java | 425 | package com.cal.angelgame;
public class Decoration extends GameObject {
/**
* Anything drawn to the screen that is not interactable
* wrapper for game object
*
* will have animation function: maybe
*
* @param x
* @param y
* @param width
* @param height
*/
public Decoration(float x, float y, float width, float height) {
super(x, y, width, height);
// TODO Auto-generated constructor stub
}
}
| mit |
cstudioteam/handywedge | handywedge-master/handywedge-core/src/main/java/com/handywedge/interceptor/FWTransactionManager.java | 468 | /*
* Copyright (c) 2019 Handywedge Co.,Ltd.
*
* This software is released under the MIT License.
*
* http://opensource.org/licenses/mit-license.php
*/
package com.handywedge.interceptor;
import jakarta.enterprise.context.RequestScoped;
@RequestScoped
public class FWTransactionManager {
private int layer = 0;
boolean isTopLayer() {
return layer == 0;
}
void incrementLayer() {
layer++;
}
void decrementLayer() {
layer--;
}
}
| mit |
chechiachang/booking-manager-maven | src/main/java/com/ccc/smartfloorplan/action/GetAllFloorAction.java | 5322 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ccc.smartfloorplan.action;
import com.ccc.smartfloorplan.entity.Floor;
import com.ccc.smartfloorplan.entity.JdbcConn;
import com.ccc.util.XmlMapping;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author davidchang
*/
@WebServlet(name = "GetAllFloorAction", urlPatterns = "{/GetAllFloorAction}")
public class GetAllFloorAction extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs;
try {
XmlMapping configXml = new XmlMapping(new File(getServletConfig().getServletContext().getRealPath("/WEB-INF/config.xml")));
Class.forName(configXml.LookupKey("DRIVER_MANAGER"));
conn = DriverManager.getConnection(configXml.LookupKey("DB_URL"), configXml.LookupKey("USER"), configXml.LookupKey("PASS"));
pstmt = conn.prepareStatement("SELECT `id`, `sort`, `disabled`, `name`, `adminId`, `imageUri` FROM `floors` WHERE `disabled` = 0 ORDER BY `id` ASC");
rs = pstmt.executeQuery();
List<Floor> floors = new ArrayList<>();
while (rs.next()) {
Floor floor = new Floor();
floor.setId(rs.getInt("id"));
floor.setSort(rs.getInt("sort"));
floor.setDisabled(rs.getInt("disabled"));
floor.setName(rs.getString("name"));
floor.setAdminId(rs.getInt("adminId"));
floor.setImageUri(rs.getString("imageUri"));
floors.add(floor);
}
HttpSession session = request.getSession();
session.setAttribute("floors", floors);
session.setMaxInactiveInterval(5 * 60);
} catch (ClassNotFoundException ex) {
Logger.getLogger(GetAllFloorAction.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(GetAllFloorAction.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| mit |
gems-uff/oceano | web/src/main/java/br/uff/ic/oceano/ostra/service/behaviortable/Behavior.java | 10770 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.uff.ic.oceano.ostra.service.behaviortable;
import br.uff.ic.oceano.util.NumberUtil;
import br.uff.ic.oceano.ostra.model.DataMiningPattern;
import br.uff.ic.oceano.ostra.model.DataMiningResult;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
*
* @author DanCastellani
*/
public class Behavior {
private DataMiningResult dataMiningResult;
private List<DataMiningPattern> rules = new ArrayList<DataMiningPattern>();
private String value = "";
private Double highestConfidence = 0D;
//prefix
private static final String PROPORTIONAL = "proportional_";
private static final String INVERSE = "inverse_";
private static final String NEUTRAL = "neutral";
//proportional
private static final String PROPORTIONAL_MINUS = PROPORTIONAL + "minus";
private static final String PROPORTIONAL_PLUS = PROPORTIONAL + "plus";
private static final String PROPORTIONAL_BOTH = PROPORTIONAL + "both";
//inverse
private static final String INVERSE_MINUS_PLUS = INVERSE + "minus_plus";
private static final String INVERSE_PLUS_MINUS = INVERSE + "plus_minus";
private static final String INVERSE_BOTH = INVERSE + "both";
private static final String INVERSE_NEUTRAL_MINUS = INVERSE + "neutral_minus";
private static final String INVERSE_NEUTRAL_PLUS = INVERSE + "neutral_plus";
//undefined
private static final String UNDEFINED = "undefined";
private static final String NO_BEHAVIOR = "no_behavior";
public String getFormatedRules() {
String s = "";
for (DataMiningPattern rule : rules) {
s += rule.toString() + "<br/>";
}
return s;
}
public String getBehaviorName() {
return getBehaviorName_Real();
}
public String getBehaviorName_Real() {
List<String> behaviors = new LinkedList<String>();
for (DataMiningPattern dataMiningPattern : rules) {
behaviors.add(getSimpleBehaviorName(dataMiningPattern));
}
final boolean hasNeutralBehavior = existsBehavior(behaviors, NEUTRAL);
final boolean hasProportionalBehavior = existsBehavior(behaviors, PROPORTIONAL);
final boolean hasInverseBehavior = existsBehavior(behaviors, INVERSE);
if (hasInverseBehavior && hasProportionalBehavior) {
return UNDEFINED;
}
if (hasInverseBehavior) {
if (hasNeutralBehavior) {
//because neutral is proportional (0 -> 0)
return UNDEFINED;
} else {
final boolean hasInverseMinusPlus = existsBehavior(behaviors, INVERSE_MINUS_PLUS);
final boolean hasInversePlusMinus = existsBehavior(behaviors, INVERSE_PLUS_MINUS);
final boolean hasInverseNeutralMinus = existsBehavior(behaviors, INVERSE_NEUTRAL_MINUS);
final boolean hasInverseNeutralPlus = existsBehavior(behaviors, INVERSE_NEUTRAL_PLUS);
// if (hasInverseMinusPlus && hasInversePlusMinus) {
// return INVERSE_BOTH;
// }
if (hasInverseMinusPlus) {
return INVERSE_MINUS_PLUS;
}
if (hasInversePlusMinus) {
return INVERSE_PLUS_MINUS;
}
if (hasInverseNeutralMinus && hasInverseNeutralPlus) {
DataMiningPattern betterPattern = null;
final String dataMiningMetricName = dataMiningResult.getRuleMetricName();
for (DataMiningPattern currentDataMiningPattern : rules) {
if (betterPattern == null) {
betterPattern = currentDataMiningPattern;
}
if (betterPattern.getMetricValue(dataMiningMetricName) < currentDataMiningPattern.getMetricValue(dataMiningMetricName)) {
betterPattern = currentDataMiningPattern;
} else if (betterPattern.getMetricValue(dataMiningMetricName) == currentDataMiningPattern.getMetricValue(dataMiningMetricName)) {
if (betterPattern.getSupport() < currentDataMiningPattern.getSupport()) {
betterPattern = currentDataMiningPattern;
}
}
}
return getSimpleBehaviorName(betterPattern);
// return INVERSE_BOTH;
}
if (hasInverseNeutralMinus) {
return INVERSE_NEUTRAL_MINUS;
}
if (hasInverseNeutralPlus) {
return INVERSE_NEUTRAL_PLUS;
}
}
} else if (hasProportionalBehavior) {
final boolean hasProportionalMinus = existsBehavior(behaviors, PROPORTIONAL_MINUS);
final boolean hasProportionalPlus = existsBehavior(behaviors, PROPORTIONAL_PLUS);
//as for proportional behavior, the neutral doesnt influence, we will ignore it.
if (hasProportionalMinus && hasProportionalPlus) {
DataMiningPattern betterPattern = null;
final String dataMiningMetricName = dataMiningResult.getRuleMetricName();
for (DataMiningPattern currentDataMiningPattern : rules) {
if (betterPattern == null) {
betterPattern = currentDataMiningPattern;
}
if (betterPattern.getMetricValue(dataMiningMetricName) < currentDataMiningPattern.getMetricValue(dataMiningMetricName)) {
betterPattern = currentDataMiningPattern;
} else if (betterPattern.getMetricValue(dataMiningMetricName) == currentDataMiningPattern.getMetricValue(dataMiningMetricName)) {
if (betterPattern.getSupport() < currentDataMiningPattern.getSupport()) {
betterPattern = currentDataMiningPattern;
}
}
}
return getSimpleBehaviorName(betterPattern);
// return PROPORTIONAL_BOTH;
}
if (hasProportionalMinus) {
return PROPORTIONAL_MINUS;
}
if (hasProportionalPlus) {
return PROPORTIONAL_PLUS;
}
} else if (hasNeutralBehavior) {
return NEUTRAL;
}
return NO_BEHAVIOR;
}
private String getSimpleBehaviorName(DataMiningPattern rule) {
final String behavior = getRuleBehavior(rule);
if (behavior.equals("--")) {
return PROPORTIONAL_MINUS;
} else if (behavior.equals("++")) {
return PROPORTIONAL_PLUS;
} else if (behavior.equals("00")) {
return NEUTRAL;
} else if (behavior.equals("-+")) {
return INVERSE_MINUS_PLUS;
} else if (behavior.equals("-0")) {
return INVERSE_NEUTRAL_MINUS;
} else if (behavior.equals("+-")) {
return INVERSE_PLUS_MINUS;
} else if (behavior.equals("+0")) {
return INVERSE_NEUTRAL_PLUS;
} else if (behavior.equals("0+")) {
return INVERSE_NEUTRAL_PLUS;
} else if (behavior.equals("0-")) {
return INVERSE_NEUTRAL_MINUS;
} else {
return NO_BEHAVIOR;
}
}
public Behavior(DataMiningResult dataMiningResult) {
this.dataMiningResult = dataMiningResult;
}
public Behavior(String value, DataMiningResult dataMiningResult) {
this.value = value;
this.dataMiningResult = dataMiningResult;
}
/**
* @return the rules
*/
public List<DataMiningPattern> getRules() {
return rules;
}
/**
* @param rules the rules to set
*/
public void setRules(List<DataMiningPattern> rules) {
this.rules = rules;
}
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @return the value
*/
public String getShortValue() {
if (value.length() >= 3) {
return value.substring(0, 3);
} else {
return value;
}
}
/**
* @param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
/**
* @return the highestConfidence
*/
public Double getHighestConfidence() {
return highestConfidence;
}
/**
* @return the highestConfidence
*/
public String getFormatedHighestConfidence() {
return NumberUtil.format(highestConfidence);
}
/**
* @param highestConfidence the highestConfidence to set
*/
public void setHighestConfidence(Double highestConfidence) {
this.highestConfidence = highestConfidence;
}
private static String getRuleBehavior(DataMiningPattern rule) {
return DataMiningPattern.getValue(rule.getPrecedent()) + DataMiningPattern.getValue(rule.getConsequent());
}
private boolean existsBehavior(List<String> behaviors, String prefix) {
for (String behavior : behaviors) {
if (behavior.startsWith(prefix)) {
return true;
}
}
return false;
}
public String getAverageSuport() {
double sum = 0;
for (DataMiningPattern rule : rules) {
sum += rule.getSupport()!=null?rule.getSupport():0.0;
}
return NumberUtil.format((rules != null && !rules.isEmpty()) ? sum / rules.size() : sum);
}
public String getAverageConfidence() {
double sum = 0;
for (DataMiningPattern rule : rules) {
sum += rule.getConfidence()!=null?rule.getConfidence():0.0;
}
return NumberUtil.format((rules != null && !rules.isEmpty()) ? sum / rules.size() : sum);
}
public String getAverageLift() {
double sum = 0;
for (DataMiningPattern rule : rules) {
sum += rule.getLift()!=null?rule.getLift():0.0;
}
return NumberUtil.format((rules != null && !rules.isEmpty()) ? sum / rules.size() : sum);
}
/**
* @return the dataMiningResult
*/
public DataMiningResult getDataMiningResult() {
return dataMiningResult;
}
/**
* @param dataMiningResult the dataMiningResult to set
*/
public void setDataMiningResult(DataMiningResult dataMiningResult) {
this.dataMiningResult = dataMiningResult;
}
}
| mit |
akyker20/Slogo_IDE | src/commandParsing/exceptions/RunTimeDivideByZeroException.java | 1002 | package commandParsing.exceptions;
import gui.factories.ErrorFactory;
import java.util.HashMap;
import java.util.Map;
import drawableobject.DrawableObject;
public class RunTimeDivideByZeroException extends SLOGOException {
private static final long serialVersionUID = 1L;
public RunTimeDivideByZeroException () {
super();
}
public RunTimeDivideByZeroException (String stringOfInterest) {
super(stringOfInterest);
}
public RunTimeDivideByZeroException (Throwable exception) {
super(exception);
}
public RunTimeDivideByZeroException (String stringOfInterest, Throwable cause) {
super(stringOfInterest, cause);
}
@Override
public DrawableObject generateErrorMessage () {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(ErrorFactory.ERROR_MESSAGE, "Error: divided by zero.");
return new DrawableObject(ErrorFactory.PARENT, ErrorFactory.TYPE, parameters);
}
}
| mit |
anba/es6draft | src/test/java/com/github/anba/es6draft/v8/TestingFunctions.java | 2712 | /**
* Copyright (c) André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.v8;
import com.github.anba.es6draft.Script;
import com.github.anba.es6draft.runtime.ExecutionContext;
import com.github.anba.es6draft.runtime.internal.Properties.Function;
import com.github.anba.es6draft.runtime.internal.Source;
import com.github.anba.es6draft.runtime.objects.intl.IntlAbstractOperations;
import com.github.anba.es6draft.runtime.objects.reflect.RealmObject;
/**
* Stub functions for tests.
*/
public final class TestingFunctions {
/** shell-function: {@code gc()} */
@Function(name = "gc", arity = 0)
public void gc() {
// empty
}
/**
* shell-function: {@code getDefaultLocale()}
*
* @param cx
* the execution context
* @return the default locale
*/
@Function(name = "getDefaultLocale", arity = 0)
public String getDefaultLocale(ExecutionContext cx) {
return IntlAbstractOperations.DefaultLocale(cx.getRealm());
}
/**
* shell-function: {@code getDefaultTimeZone()}
*
* @param cx
* the execution context
* @return the default timezone
*/
@Function(name = "getDefaultTimeZone", arity = 0)
public String getDefaultTimeZone(ExecutionContext cx) {
return IntlAbstractOperations.DefaultTimeZone(cx.getRealm());
}
/**
* shell-function: {@code getCurrentRealm()}
*
* @param cx
* the execution context
* @param caller
* the caller execution context
* @return the current realm object
*/
@Function(name = "getCurrentRealm", arity = 0)
public RealmObject getCurrentRealm(ExecutionContext cx, ExecutionContext caller) {
return caller.getRealm().getRealmObject();
}
/**
* shell-function: {@code evalInRealm(realm, sourceString)}
*
* @param cx
* the execution context
* @param caller
* the caller execution context
* @param realmObject
* the target realm
* @param sourceString
* the source string
* @return the evaluation result
*/
@Function(name = "evalInRealm", arity = 2)
public Object evalInRealm(ExecutionContext cx, ExecutionContext caller, RealmObject realmObject,
String sourceString) {
Source source = new Source(caller.sourceInfo(), "<evalInRealm>", 1);
Script script = realmObject.getRealm().getScriptLoader().script(source, sourceString);
return script.evaluate(realmObject.getRealm());
}
}
| mit |
streamj/JX | stream-eb/src/main/java/com/example/stream/eb/database/DatabaseManager.java | 1027 | package com.example.stream.eb.database;
import android.content.Context;
import org.greenrobot.greendao.database.Database;
/**
* Created by StReaM on 8/20/2017.
*/
public class DatabaseManager {
private DaoSession mDaoSession = null;
private UserProfileDao mDao = null;
private DatabaseManager() {
}
public DatabaseManager init(Context context) {
initDao(context);
return this;
}
private static final class Holder {
private static final DatabaseManager INSTANCE =
new DatabaseManager();
}
public static DatabaseManager getInstance (){
return Holder.INSTANCE;
}
private void initDao(Context context) {
final ReleaseOpenHelper helper = new ReleaseOpenHelper(context, "stream_eb.db");
final Database db = helper.getWritableDb();
mDaoSession = new DaoMaster(db).newSession();
mDao = mDaoSession.getUserProfileDao();
}
public final UserProfileDao getDao() {
return mDao;
}
}
| mit |
ndal-eth/topobench | src/main/java/ch/ethz/topobench/graph/patheval/generators/NeighborPathEvaluatorGenerator.java | 1132 | /* *******************************************************
* Released under the MIT License (MIT) --- see LICENSE
* Copyright (c) 2014 Ankit Singla, Sangeetha Abdu Jyothi,
* Chi-Yao Hong, Lucian Popa, P. Brighten Godfrey,
* Alexandra Kolla, Simon Kassing
* ******************************************************** */
package ch.ethz.topobench.graph.patheval.generators;
import ch.ethz.topobench.graph.SelectorResult;
import ch.ethz.topobench.graph.patheval.NeighborPathEvaluator;
import ch.ethz.topobench.graph.Graph;
import ch.ethz.topobench.graph.patheval.PathEvaluator;
import ch.ethz.topobench.graph.utility.CmdAssistant;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
public class NeighborPathEvaluatorGenerator implements PathEvaluatorGenerator {
@Override
public SelectorResult<PathEvaluator> generate(Graph graph, String[] args) {
// Parse the options
CommandLine cmd = CmdAssistant.parseOptions(new Options(), args, true);
// Return path evaluator
return new SelectorResult<>(new NeighborPathEvaluator(graph), cmd.getArgs());
}
}
| mit |
trydent-io/sales-taxes-problem | src/main/java/io/trydent/stp/item/ImportedItem.java | 310 | package io.trydent.stp.item;
public interface ImportedItem extends Item {
static ImportedItem of(final Price price) {
return new ImportedItemImpl(new ItemImpl(price.value()));
}
static <I extends TaxedItem & Item> ImportedItem fromTaxed(final I item) {
return new ImportedItemImpl(item);
}
}
| mit |
p-a/kickass-cruncher-plugins | src/main/java/net/magli143/exo/crunch_options.java | 1783 | package net.magli143.exo;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
/**
* <i>native declaration : exo_helper.h:919</i><br>
* This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
* a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br>
* For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>.
*/
public class crunch_options extends Structure {
/** C type : const char* */
public Pointer exported_encoding;
public int max_passes;
public int max_len;
public int max_offset;
public int use_literal_sequences;
public int use_imprecise_rle;
public crunch_options() {
super();
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("exported_encoding", "max_passes", "max_len", "max_offset", "use_literal_sequences", "use_imprecise_rle");
}
/** @param exported_encoding C type : const char* */
public crunch_options(Pointer exported_encoding, int max_passes, int max_len, int max_offset, int use_literal_sequences, int use_imprecise_rle) {
super();
this.exported_encoding = exported_encoding;
this.max_passes = max_passes;
this.max_len = max_len;
this.max_offset = max_offset;
this.use_literal_sequences = use_literal_sequences;
this.use_imprecise_rle = use_imprecise_rle;
}
public static class ByReference extends crunch_options implements Structure.ByReference {
};
public static class ByValue extends crunch_options implements Structure.ByValue {
};
}
| mit |
infsci2560fa16/full-stack-web-project-usernameoliver | src/main/java/edu/washington/cs/figer/ml/LRInference.java | 2410 | package edu.washington.cs.figer.ml;
import edu.washington.cs.figer.data.Instance;
import edu.washington.cs.figer.util.V;
import java.util.ArrayList;
/**
*
* @author Xiao Ling
*
*/
public class LRInference extends Inference {
/**
*
*/
private static final long serialVersionUID = 5056369182261762614L;
public LRInference() {
super();
}
public static double sigma = 1;
@Override
public Prediction findBestLabel(Instance x, Model m) {
LogisticRegression lr = (LogisticRegression) m;
LRParameter para = (LRParameter) lr.para;
int[] predictions = new int[lr.labelFactory.allLabels.size()];
double[] probs = new double[lr.labelFactory.allLabels.size()];
double[] origLambda = para.lambda;
{
int L = lr.labelFactory.allLabels.size();
int maxL = -1;
double max = -Double.MAX_VALUE;
ArrayList<Double> scores = new ArrayList<Double>();
for (int j = 0; j < L; j++) {
double score = 0;
int startpoint = lr.featureFactory.allFeatures.size() * j;
score += V.sumprod(x, para.lambda, startpoint);
scores.add(score);
if (score > max) {
maxL = j;
max = score;
}
}
double part = 0;
for (int i = 0; i < L; i++) {
part += Math.exp((scores.get(i) - max) / sigma);
}
predictions[maxL]++;
probs[maxL] += 1 / part;
}
int maxL = -1;
int max = -1;
for (int k = 0; k < predictions.length; k++) {
if (predictions[k] > max) {
maxL = k;
max = predictions[k];
} else if (predictions[k] == max && probs[k] > probs[maxL]) {
maxL = k;
max = predictions[k];
}
}
if (lr.voted) {
para.lambda = origLambda;
}
return new Prediction(lr.labelFactory.allLabels.get(maxL), probs[maxL]
/ max);
}
/**
* return predictions with scores
*/
@Override
public ArrayList<Prediction> findPredictions(Instance x, Model m) {
LogisticRegression lr = (LogisticRegression) m;
LRParameter para = (LRParameter) lr.para;
ArrayList<Prediction> preds = null;
int L = lr.labelFactory.allLabels.size();
int F = lr.featureFactory.allFeatures.size();
preds = new ArrayList<Prediction>();
for (int j = 0; j < L; j++) {
int startpoint = F * j;
double score = V.sumprod(x, para.lambda, startpoint);
preds.add(new Prediction(lr.labelFactory.allLabels.get(j), score));
}
return preds;
}
}
| mit |
alcir/mibe-dcm4chee | copy/var/tmp/dcm4chee-2.17.3-mysql/server/default/work/jboss.web/localhost/dcm4chee-web3/org/apache/jsp/login_jsp.java | 9975 | package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.net.InetAddress;
public final class login_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List _jspx_dependants;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.AnnotationProcessor _jsp_annotationprocessor;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
}
public void _jspDestroy() {
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n");
out.write("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
out.write("\r\n");
out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:wicket=\"http://wicket.apache.org\">\n");
out.write(" ");
org.dcm4chee.web.common.login.LoginResources login = null;
synchronized (request) {
login = (org.dcm4chee.web.common.login.LoginResources) _jspx_page_context.getAttribute("login", PageContext.REQUEST_SCOPE);
if (login == null){
login = new org.dcm4chee.web.common.login.LoginResources();
_jspx_page_context.setAttribute("login", login, PageContext.REQUEST_SCOPE);
}
}
out.write("\r\n");
out.write(" ");
String nodeInfo = System.getProperty("dcm4che.archive.nodename", InetAddress.getLocalHost().getHostName() );
Cookie[] cookies = request.getCookies();
String userName = "";
String focus = "self.focus();document.login.j_username.focus()";
if (cookies != null) {
int count = 0;
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("WEB3LOCALE")) {
login.setLocale(cookies[i].getValue());
count++;
if (count==2)
break;
}
if (cookies[i].getName().equals("signInPanel.signInForm.username")) {
userName = cookies[i].getValue();
if (userName!=null && userName.length()>0)
focus = "self.focus();document.login.j_username.value='"+userName+
"';document.login.j_password.focus()";
count++;
if (count==2)
break;
}
}
}
out.write("\r\n");
out.write(" <head>\n");
out.write("\t <title>");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${login.browser_title}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write(' ');
out.write('(');
out.print( nodeInfo );
out.write(")</title>\n");
out.write("\t <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n");
out.write(" <link rel=\"stylesheet\" type=\"text/css\" href=\"resources/org.dcm4chee.web.common.base.BaseWicketPage/base-style.css\" />\n");
out.write(" <script>\n");
out.write(" function login_init() {\n");
out.write(" \t");
out.print( focus );
out.write("\n");
out.write(" window.setTimeout(\"location.reload(true);\", ");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.session.maxInactiveInterval * 1000 - 5000}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write(");\n");
out.write(" }\n");
out.write(" </script>\n");
out.write(" </head>\n");
out.write(" <body onload=\"login_init();\">\n");
out.write(" <div class=\"tabpanel\">\n");
out.write(" <div class=\"module-selector\">\n");
out.write(" <div class=\"tab-row\">\n");
out.write("\t\t\t <ul>\n");
out.write("\t\t </ul>\n");
out.write(" </div>\n");
out.write("\t\t <div class=\"tab-logo\" style=\"float: right; margin-top: 15px; height: 43px; padding-right: 15px; padding-left: 15px;\">\n");
out.write("\t\t <img alt=\"dcm4che.org\" src=\"resources/org.dcm4chee.web.common.base.BaseWicketPage/images/logo.gif\" /><br/>\n");
out.write("\t\t </div>\n");
out.write("\t </div>\n");
out.write("\t <div class=\"module-panel\"></div>\n");
out.write(" </div>\n");
out.write(" <div class=\"signin\" style=\"padding-top: 160px;\">\n");
out.write(" ");
if (request.getParameter("loginFailed") == null) {
out.write("\n");
out.write("\t <span class=\"login-desc\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${login.loginLabel}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write(' ');
out.print( nodeInfo );
out.write("</span>\n");
out.write(" ");
} else {
out.write("\n");
out.write(" \t <span class=\"login-desc\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${login.loginFailed}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write(' ');
out.print( nodeInfo );
out.write("</span>\n");
out.write(" \t ");
}
out.write("\n");
out.write(" <div>\n");
out.write("\t\t <form action=\"j_security_check\" method=\"POST\" name=\"login\" >\r\n");
out.write("\t\t <table style=\"padding-top: 60px; padding-right: 90px; padding-bottom: 10px;\">\n");
out.write(" <tbody>\n");
out.write("\t\t\t <tr style=\"text-align: left;\">\n");
out.write("\t\t\t <td align=\"right\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${login.username}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("</td>\n");
out.write("\t\t\t <td>\n");
out.write("\t\t\t <input type=\"text\" name=\"j_username\" size=\"30\" />\n");
out.write("\t\t\t </td>\n");
out.write("\t\t\t </tr>\n");
out.write("\t\t\t <tr style=\"text-align: left;\">\n");
out.write("\t\t\t <td align=\"right\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${login.password}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("</td>\n");
out.write("\t\t\t <td>\n");
out.write("\t\t\t <input type=\"password\" name=\"j_password\" size=\"30\" />\n");
out.write("\t\t\t </td>\n");
out.write("\t\t\t </tr>\n");
out.write("\t\t\t <tr style=\"text-align: left;\">\n");
out.write("\t\t\t <td></td>\n");
out.write("\t\t\t <td>\n");
out.write("\t\t\t <input type=\"submit\" name=\"submit\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${login.submit}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("\" />\n");
out.write("\t\t\t <input type=\"reset\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${login.reset}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("\" onclick=\"document.login.j_username.focus()\"/>\n");
out.write("\t\t\t </td>\n");
out.write("\t\t\t </tr>\n");
out.write(" </tbody>\n");
out.write(" </table>\n");
out.write("\t\t </form>\n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| mit |
yixincai/CS201_FinalProject_SimCity | source/city/restaurant/yixin/Menu.java | 769 | package city.restaurant.yixin;
import java.util.*;
public class Menu {
public List<Food> menu = new ArrayList<Food>();
Menu(){
menu.add(new Food("Steak", 15.99));
menu.add(new Food("Chicken", 10.99));
menu.add(new Food("Salad", 5.99));
menu.add(new Food("Pizza", 8.99));
}
public void remove(String s){
for (int i=0; i<menu.size(); i++){
if (menu.get(i).name.equals(s)){
menu.remove(i);
return;
}
}
}
public double getPrice(String s){
for (int i=0; i<menu.size(); i++){
if (menu.get(i).name.compareTo(s) == 0){
return menu.get(i).price;
}
}
return 0;
}
public class Food{
public String name;
public double price;
Food(String name, double price){
this.name = name;
this.price = price;
}
}
}
| mit |
frie321984/eClipHistory | org.schertel.friederike.ecliphistory.application/src/org/schertel/friederike/ecliphistory/model/ClipboardHistoryEntry.java | 297 | package org.schertel.friederike.ecliphistory.model;
/**
* The POJO describing the entries for the history table.
*/
public class ClipboardHistoryEntry {
public int position;
public String content;
public ClipboardHistoryEntry(int pos, String txt) {
position = pos;
content = txt;
}
}
| mit |
Gchorba/NickleAndDimed | app/src/main/java/gk/nickles/ndimes/services/DebtCalculator.java | 2002 | package gk.nickles.ndimes.services;
import com.google.inject.Inject;
import java.util.LinkedList;
import java.util.List;
import gk.nickles.ndimes.dataaccess.AttendeeStore;
import gk.nickles.ndimes.dataaccess.ExpenseStore;
import gk.nickles.ndimes.dataaccess.ParticipantStore;
import gk.nickles.ndimes.dataaccess.UserStore;
import gk.nickles.ndimes.model.Debt;
import gk.nickles.ndimes.model.Event;
import gk.nickles.ndimes.model.Expense;
import gk.nickles.ndimes.model.Participant;
import gk.nickles.ndimes.model.User;
import static com.google.inject.internal.util.$Preconditions.checkNotNull;
public class DebtCalculator {
@Inject
private ExpenseStore expenseStore;
@Inject
private UserStore userStore;
@Inject
private ParticipantStore participantStore;
@Inject
private AttendeeStore attendeeStore;
@Inject
private DebtOptimizer debtOptimizer;
public List<Debt> calculateDebts(Event event) {
checkNotNull(event);
List<Debt> debts = getDebts(event);
return debtOptimizer.optimize(debts, event.getCurrency());
}
private List<Debt> getDebts(Event event) {
List<Debt> debts = new LinkedList<Debt>();
List<Expense> expenses = expenseStore.getExpensesOfEvent(event.getId());
for (Expense expense : expenses) {
Participant toParticipant = participantStore.getById(expense.getPayerId());
List<Participant> fromParticipants = attendeeStore.getAttendingParticipants(expense.getId());
int amount = expense.getAmount() / fromParticipants.size();
for (Participant fromParticipant : fromParticipants) {
User fromUser = userStore.getById(fromParticipant.getUserId());
User toUser = userStore.getById(toParticipant.getUserId());
if (fromUser.equals(toUser)) continue;
debts.add(new Debt(fromUser, toUser, amount, event.getCurrency()));
}
}
return debts;
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2019_11_01/src/main/java/com/microsoft/azure/management/network/v2019_11_01/OwaspCrsExclusionEntry.java | 3803 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_11_01;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Allow to exclude some variable satisfy the condition for the WAF check.
*/
public class OwaspCrsExclusionEntry {
/**
* The variable to be excluded. Possible values include:
* 'RequestHeaderNames', 'RequestCookieNames', 'RequestArgNames'.
*/
@JsonProperty(value = "matchVariable", required = true)
private OwaspCrsExclusionEntryMatchVariable matchVariable;
/**
* When matchVariable is a collection, operate on the selector to specify
* which elements in the collection this exclusion applies to. Possible
* values include: 'Equals', 'Contains', 'StartsWith', 'EndsWith',
* 'EqualsAny'.
*/
@JsonProperty(value = "selectorMatchOperator", required = true)
private OwaspCrsExclusionEntrySelectorMatchOperator selectorMatchOperator;
/**
* When matchVariable is a collection, operator used to specify which
* elements in the collection this exclusion applies to.
*/
@JsonProperty(value = "selector", required = true)
private String selector;
/**
* Get the variable to be excluded. Possible values include: 'RequestHeaderNames', 'RequestCookieNames', 'RequestArgNames'.
*
* @return the matchVariable value
*/
public OwaspCrsExclusionEntryMatchVariable matchVariable() {
return this.matchVariable;
}
/**
* Set the variable to be excluded. Possible values include: 'RequestHeaderNames', 'RequestCookieNames', 'RequestArgNames'.
*
* @param matchVariable the matchVariable value to set
* @return the OwaspCrsExclusionEntry object itself.
*/
public OwaspCrsExclusionEntry withMatchVariable(OwaspCrsExclusionEntryMatchVariable matchVariable) {
this.matchVariable = matchVariable;
return this;
}
/**
* Get when matchVariable is a collection, operate on the selector to specify which elements in the collection this exclusion applies to. Possible values include: 'Equals', 'Contains', 'StartsWith', 'EndsWith', 'EqualsAny'.
*
* @return the selectorMatchOperator value
*/
public OwaspCrsExclusionEntrySelectorMatchOperator selectorMatchOperator() {
return this.selectorMatchOperator;
}
/**
* Set when matchVariable is a collection, operate on the selector to specify which elements in the collection this exclusion applies to. Possible values include: 'Equals', 'Contains', 'StartsWith', 'EndsWith', 'EqualsAny'.
*
* @param selectorMatchOperator the selectorMatchOperator value to set
* @return the OwaspCrsExclusionEntry object itself.
*/
public OwaspCrsExclusionEntry withSelectorMatchOperator(OwaspCrsExclusionEntrySelectorMatchOperator selectorMatchOperator) {
this.selectorMatchOperator = selectorMatchOperator;
return this;
}
/**
* Get when matchVariable is a collection, operator used to specify which elements in the collection this exclusion applies to.
*
* @return the selector value
*/
public String selector() {
return this.selector;
}
/**
* Set when matchVariable is a collection, operator used to specify which elements in the collection this exclusion applies to.
*
* @param selector the selector value to set
* @return the OwaspCrsExclusionEntry object itself.
*/
public OwaspCrsExclusionEntry withSelector(String selector) {
this.selector = selector;
return this;
}
}
| mit |
vishalkuo/Kitchen-Ehhd | Android/Kitchen-Ehhd/app/src/main/java/com/kitchen_ehhd/Models/DrawerItem.java | 405 | package com.kitchen_ehhd.Models;
/**
* Created by yisen_000 on 2015-09-19.
*/
public class DrawerItem {
private String name;
private int drawerNum;
public DrawerItem(String name, int drawerNum) {
this.name = name;
this.drawerNum = drawerNum;
}
public String getName() {
return name;
}
public int getDrawerNum() {
return drawerNum;
}
}
| mit |
tnog2014/MockTemplateGenerator | src/mockgen/TemplateEngine.java | 1123 | package mockgen;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
public class TemplateEngine {
public static void main(String[] args) throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("name", "JJJJJ");
String res = new TemplateEngine().merge(map, "template/mytemplate.vm");
System.out.println(res);
}
public String merge(Map<String, String> map, String templatePath)
throws Exception {
Properties prop = new Properties();
prop.setProperty("input.encoding", "UTF-8");
prop.setProperty("output.encoding", "UTF-8");
Velocity.init(prop);
VelocityContext context = new VelocityContext();
for (Entry<String, String> entry : map.entrySet()) {
context.put(entry.getKey(), entry.getValue());
}
Template template = Velocity.getTemplate(templatePath);
StringWriter sw = new StringWriter();
template.merge(context, sw);
return sw.toString();
}
} | mit |
Azure/azure-sdk-for-java | sdk/iotcentral/azure-resourcemanager-iotcentral/src/samples/java/com/azure/resourcemanager/iotcentral/generated/AppsUpdateSamples.java | 1304 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.iotcentral.generated;
import com.azure.core.util.Context;
import com.azure.resourcemanager.iotcentral.models.App;
import com.azure.resourcemanager.iotcentral.models.SystemAssignedServiceIdentity;
import com.azure.resourcemanager.iotcentral.models.SystemAssignedServiceIdentityType;
/** Samples for Apps Update. */
public final class AppsUpdateSamples {
/*
* x-ms-original-file: specification/iotcentral/resource-manager/Microsoft.IoTCentral/stable/2021-06-01/examples/Apps_Update.json
*/
/**
* Sample code: Apps_Update.
*
* @param manager Entry point to IotCentralManager.
*/
public static void appsUpdate(com.azure.resourcemanager.iotcentral.IotCentralManager manager) {
App resource =
manager.apps().getByResourceGroupWithResponse("resRg", "myIoTCentralApp", Context.NONE).getValue();
resource
.update()
.withIdentity(
new SystemAssignedServiceIdentity().withType(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED))
.withDisplayName("My IoT Central App 2")
.apply();
}
}
| mit |
wordsaretoys/quencher | app/src/main/java/com/wordsaretoys/quencher/common/SettingsActivity.java | 2489 | package com.wordsaretoys.quencher.common;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceFragment;
import android.view.View;
import android.widget.Toast;
import com.wordsaretoys.quencher.R;
public class SettingsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = getLayoutInflater().inflate(R.layout.settings_main, null);
setContentView(view);
getActionBar().setTitle(R.string.prefsTitle);
}
public static class SettingsFragment extends PreferenceFragment {
public SettingsFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Resources res = getResources();
// set up range checks for preferences
Preference tuningReference = findPreference("pref_tuning_reference");
tuningReference.setOnPreferenceChangeListener(
new RangeCheckListener(
261.63f, 523.25f,
res.getString(R.string.prefsTuningReferenceRange)));
Preference tuningFrequency = findPreference("pref_tuning_frequency");
tuningFrequency.setOnPreferenceChangeListener(
new RangeCheckListener(
220, 880,
res.getString(R.string.prefsTuningFrequencyRange)));
Preference audioLatency = findPreference("pref_audio_latency");
audioLatency.setOnPreferenceChangeListener(
new RangeCheckListener(
1, 1000,
res.getString(R.string.prefsAudioLatencyRange)));
}
class RangeCheckListener implements OnPreferenceChangeListener {
String errMsg;
float lower;
float upper;
/**
* ctor
*
* @param l lower bound
* @param h upper bound
* @param msg error message if range check fails
*/
public RangeCheckListener(float l, float h, String msg) {
lower = l;
upper = h;
errMsg = msg;
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
float f = -1;
try {
f = Float.valueOf( (String) newValue);
} catch (Exception e) {
f = -1;
}
if (f < lower || f > upper) {
Toast.makeText(getActivity(), errMsg, Toast.LENGTH_LONG).show();
return false;
}
return true;
}
}
}
}
| mit |
whiskeysierra/primal | src/main/java/org/whiskeysierra/process/ManagedProcess.java | 1143 | package org.whiskeysierra.process;
import com.google.common.io.ByteSource;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;
// TODO specify IOException as exception of choice?!
public interface ManagedProcess {
// TODO find better name
ManagedProcess setExecutable(Path executable);
// TODO find better name
ManagedProcess setCommand(String command);
// TODO specify defensive-copy?
ManagedProcess parameterize(Object... arguments);
// TODO specify defensive-copy?
ManagedProcess parameterize(Iterable<?> arguments);
ManagedProcess in(Path directory);
ManagedProcess with(String variable, String value);
ManagedProcess with(Map<String, String> properties);
// TODO IAE on illegal combinations (input -> redirect to, output -> redirect from, output -> stderr)
ManagedProcess redirect(Stream stream, Redirection redirect);
ManagedProcess allow(int exitValue);
// TODO specify whether defensive copy or not
ManagedProcess allow(int... exitValues);
RunningProcess call() throws IOException;
ByteSource read() throws IOException;
}
| mit |
mkuokkanen/rest-freemarker-protos | quarkus/src/main/java/fi/mkuokkanen/webproto/quarkus/QResource.java | 667 | package fi.mkuokkanen.webproto.quarkus;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("/test")
public class QResource {
@Path("/hello")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getHello() {
return "hello world";
}
@Path("/json")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Person getJson(@DefaultValue("Matti") @QueryParam("name") String name,
@DefaultValue("36") @QueryParam("age") int age) {
return new Person(name, age);
}
}
| mit |
r24mille/IesoPublicReportBindings | src/main/java/ca/ieso/reports/schema/daadequacy/DocHeader.java | 4307 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.12.21 at 09:18:53 AM CST
//
package ca.ieso.reports.schema.daadequacy;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <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 ref="{http://www.ieso.ca/schema}DocTitle"/>
* <element ref="{http://www.ieso.ca/schema}DocRevision"/>
* <element ref="{http://www.ieso.ca/schema}DocConfidentiality"/>
* <element ref="{http://www.ieso.ca/schema}CreatedAt"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"docTitle",
"docRevision",
"docConfidentiality",
"createdAt"
})
@XmlRootElement(name = "DocHeader")
public class DocHeader {
@XmlElement(name = "DocTitle", required = true)
protected String docTitle;
@XmlElement(name = "DocRevision", required = true)
protected BigInteger docRevision;
@XmlElement(name = "DocConfidentiality", required = true)
protected DocConfidentiality docConfidentiality;
@XmlElement(name = "CreatedAt", required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar createdAt;
/**
* Gets the value of the docTitle property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDocTitle() {
return docTitle;
}
/**
* Sets the value of the docTitle property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDocTitle(String value) {
this.docTitle = value;
}
/**
* Gets the value of the docRevision property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getDocRevision() {
return docRevision;
}
/**
* Sets the value of the docRevision property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setDocRevision(BigInteger value) {
this.docRevision = value;
}
/**
* Gets the value of the docConfidentiality property.
*
* @return
* possible object is
* {@link DocConfidentiality }
*
*/
public DocConfidentiality getDocConfidentiality() {
return docConfidentiality;
}
/**
* Sets the value of the docConfidentiality property.
*
* @param value
* allowed object is
* {@link DocConfidentiality }
*
*/
public void setDocConfidentiality(DocConfidentiality value) {
this.docConfidentiality = value;
}
/**
* Gets the value of the createdAt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getCreatedAt() {
return createdAt;
}
/**
* Sets the value of the createdAt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setCreatedAt(XMLGregorianCalendar value) {
this.createdAt = value;
}
}
| mit |
adv0r/botcoin | Botcoin-javafx/src/com/fxexperience/javafx/animation/BounceInRightTransition.java | 2122 | package com.fxexperience.javafx.animation;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.TimelineBuilder;
import javafx.scene.Node;
import javafx.util.Duration;
/**
* Animate a bounce in right big effect on a node
*
* Port of BounceInRightBig from Animate.css http://daneden.me/animate by Dan Eden
*
* {@literal @}keyframes bounceInRight {
* 0% {
* opacity: 0;
* -webkit-transform: translateX(2000px);
* }
* 60% {
* opacity: 1;
* -webkit-transform: translateX(-30px);
* }
* 80% {
* -webkit-transform: translateX(10px);
* }
* 100% {
* -webkit-transform: translateX(0);
* }
* }
*
* @author Jasper Potts
*/
public class BounceInRightTransition extends CachedTimelineTransition {
/**
* Create new BounceInRightBigTransition
*
* @param node The node to affect
*/
public BounceInRightTransition(final Node node) {
super(node, null);
setCycleDuration(Duration.seconds(1));
setDelay(Duration.seconds(0.2));
}
@Override protected void starting() {
double startX = node.getScene().getWidth() - node.localToScene(0, 0).getX();
timeline = TimelineBuilder.create()
.keyFrames(
new KeyFrame(Duration.millis(0),
new KeyValue(node.opacityProperty(), 0, WEB_EASE),
new KeyValue(node.translateXProperty(), startX, WEB_EASE)
),
new KeyFrame(Duration.millis(600),
new KeyValue(node.opacityProperty(), 1, WEB_EASE),
new KeyValue(node.translateXProperty(), -30, WEB_EASE)
),
new KeyFrame(Duration.millis(800),
new KeyValue(node.translateXProperty(), 10, WEB_EASE)
),
new KeyFrame(Duration.millis(1000),
new KeyValue(node.translateXProperty(), 0, WEB_EASE)
)
)
.build();
super.starting();
}
}
| mit |
wolfgangimig/joa | java/joa/src-gen/com/wilutions/mslib/outlook/OlFormatInteger.java | 2302 | /* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.outlook;
import com.wilutions.com.*;
/**
* OlFormatInteger.
*
*/
@SuppressWarnings("all")
@CoInterface(guid="{00000000-0000-0000-0000-000000000000}")
public class OlFormatInteger implements ComEnum {
static boolean __typelib__loaded = __TypeLib.load();
// Typed constants
public final static OlFormatInteger olFormatIntegerPlain = new OlFormatInteger(1);
public final static OlFormatInteger olFormatIntegerComputer1 = new OlFormatInteger(2);
public final static OlFormatInteger olFormatIntegerComputer2 = new OlFormatInteger(3);
public final static OlFormatInteger olFormatIntegerComputer3 = new OlFormatInteger(4);
// Integer constants for bitsets and switch statements
public final static int _olFormatIntegerPlain = 1;
public final static int _olFormatIntegerComputer1 = 2;
public final static int _olFormatIntegerComputer2 = 3;
public final static int _olFormatIntegerComputer3 = 4;
// Value, readonly field.
public final int value;
// Private constructor, use valueOf to create an instance.
private OlFormatInteger(int value) { this.value = value; }
// Return one of the predefined typed constants for the given value or create a new object.
public static OlFormatInteger valueOf(int value) {
switch(value) {
case 1: return olFormatIntegerPlain;
case 2: return olFormatIntegerComputer1;
case 3: return olFormatIntegerComputer2;
case 4: return olFormatIntegerComputer3;
default: return new OlFormatInteger(value);
}
}
public String toString() {
switch(value) {
case 1: return "olFormatIntegerPlain";
case 2: return "olFormatIntegerComputer1";
case 3: return "olFormatIntegerComputer2";
case 4: return "olFormatIntegerComputer3";
default: {
StringBuilder sbuf = new StringBuilder();
sbuf.append("[").append(value).append("=");
if ((value & 1) != 0) sbuf.append("|olFormatIntegerPlain");
if ((value & 2) != 0) sbuf.append("|olFormatIntegerComputer1");
if ((value & 3) != 0) sbuf.append("|olFormatIntegerComputer2");
if ((value & 4) != 0) sbuf.append("|olFormatIntegerComputer3");
return sbuf.toString();
}
}
}
}
| mit |
AlmasB/FXTutorials | src/main/java/com/almasb/mp/MemoryPuzzleApp.java | 3420 | package com.almasb.mp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javafx.animation.FadeTransition;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
public class MemoryPuzzleApp extends Application {
private static final int NUM_OF_PAIRS = 72;
private static final int NUM_PER_ROW = 12;
private Tile selected = null;
private int clickCount = 2;
private Parent createContent() {
Pane root = new Pane();
root.setPrefSize(600, 600);
char c = 'A';
List<Tile> tiles = new ArrayList<>();
for (int i = 0; i < NUM_OF_PAIRS; i++) {
tiles.add(new Tile(String.valueOf(c)));
tiles.add(new Tile(String.valueOf(c)));
c++;
}
Collections.shuffle(tiles);
for (int i = 0; i < tiles.size(); i++) {
Tile tile = tiles.get(i);
tile.setTranslateX(50 * (i % NUM_PER_ROW));
tile.setTranslateY(50 * (i / NUM_PER_ROW));
root.getChildren().add(tile);
}
return root;
}
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(createContent()));
primaryStage.show();
}
private class Tile extends StackPane {
private Text text = new Text();
public Tile(String value) {
Rectangle border = new Rectangle(50, 50);
border.setFill(null);
border.setStroke(Color.BLACK);
text.setText(value);
text.setFont(Font.font(30));
setAlignment(Pos.CENTER);
getChildren().addAll(border, text);
setOnMouseClicked(this::handleMouseClick);
close();
}
public void handleMouseClick(MouseEvent event) {
if (isOpen() || clickCount == 0)
return;
clickCount--;
if (selected == null) {
selected = this;
open(() -> {});
}
else {
open(() -> {
if (!hasSameValue(selected)) {
selected.close();
this.close();
}
selected = null;
clickCount = 2;
});
}
}
public boolean isOpen() {
return text.getOpacity() == 1;
}
public void open(Runnable action) {
FadeTransition ft = new FadeTransition(Duration.seconds(0.5), text);
ft.setToValue(1);
ft.setOnFinished(e -> action.run());
ft.play();
}
public void close() {
FadeTransition ft = new FadeTransition(Duration.seconds(0.5), text);
ft.setToValue(0);
ft.play();
}
public boolean hasSameValue(Tile other) {
return text.getText().equals(other.text.getText());
}
}
public static void main(String[] args) {
launch(args);
}
}
| mit |
peichhorn/tinyaudioplayer | src/test/java/de/fips/plugin/tinyaudioplayer/view/playlist/PlaylistItemLabelProviderTest.java | 4591 | package de.fips.plugin.tinyaudioplayer.view.playlist;
import static de.fips.plugin.tinyaudioplayer.audio.PlaylistItemTag.playlistItemTag;
import static de.fips.plugin.tinyaudioplayer.view.playlist.PlaylistItemLabelProvider.GREY;
import static de.fips.plugin.tinyaudioplayer.view.playlist.PlaylistItemLabelProvider.WHITE;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import java.io.File;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.graphics.Color;
import org.junit.Test;
import de.fips.plugin.tinyaudioplayer.TinyAudioPlayer;
import de.fips.plugin.tinyaudioplayer.audio.Playlist;
import de.fips.plugin.tinyaudioplayer.audio.PlaylistItem;
import de.fips.plugin.tinyaudioplayer.audio.PlaylistItemTag;
import de.fips.plugin.tinyaudioplayer.view.playlist.PlaylistItemLabelProvider;
public class PlaylistItemLabelProviderTest {
@Test
public void whenInvoked_update_shouldUseDisplayNameAsText() throws Exception {
// setup
final TinyAudioPlayer player = mock(TinyAudioPlayer.class);
doReturn(mock(Playlist.class)).when(player).getPlaylist();
final PlaylistItemLabelProvider labelProvider = new PlaylistItemLabelProvider(player);
final PlaylistItem item = mock(PlaylistItem.class);
doReturn("Text").when(item).getDisplayableName();
final ViewerCell cell = mock(ViewerCell.class);
doReturn(item).when(cell).getElement();
// run
labelProvider.update(cell);
// assert
verify(cell).setText("Text");
}
@Test
public void whenInvokedWithCellOfCurrentTrack_update_shouldUseGreyBackground() throws Exception {
// setup
final TinyAudioPlayer player = mock(TinyAudioPlayer.class);
final PlaylistItem item = mock(PlaylistItem.class);
doReturn("Text").when(item).getDisplayableName();
final Playlist playlist = mock(Playlist.class);
doReturn(false).when(playlist).isEmpty();
doReturn(item).when(playlist).getCurrentTrack();
doReturn(playlist).when(player).getPlaylist();
final PlaylistItemLabelProvider labelProvider = new PlaylistItemLabelProvider(player);
final ViewerCell cell = mock(ViewerCell.class);
doReturn(item).when(cell).getElement();
// run
labelProvider.update(cell);
// assert
verify(cell).setBackground(eq(new Color(null, GREY)));
}
@Test
public void whenInvokedNormalCell_update_shouldUseWhiteBackground() throws Exception {
// setup
final TinyAudioPlayer player = mock(TinyAudioPlayer.class);
final PlaylistItem item = mock(PlaylistItem.class);
doReturn("Text").when(item).getDisplayableName();
final Playlist playlist = mock(Playlist.class);
doReturn(false).when(playlist).isEmpty();
doReturn(mock(PlaylistItem.class)).when(playlist).getCurrentTrack();
doReturn(playlist).when(player).getPlaylist();
final PlaylistItemLabelProvider labelProvider = new PlaylistItemLabelProvider(player);
final ViewerCell cell = mock(ViewerCell.class);
doReturn(item).when(cell).getElement();
// run
labelProvider.update(cell);
// assert
verify(cell).setBackground(eq(new Color(null, WHITE)));
}
@Test
public void test_getToolTipText() throws Exception {
// setup
final TinyAudioPlayer player = mock(TinyAudioPlayer.class);
final PlaylistItemTag tag = playlistItemTag() //
.channels(2) //
.samplingRate(44100) //
.bitRate(192000) //
.album("Album 01").genre("Audiobook").year("2002").build();
final PlaylistItem item = spy(new PlaylistItem("Track 01", new File("01 - Track 01.mp3").toURI(), 220));
doReturn(tag).when(item).getInfoTag();
final PlaylistItemLabelProvider labelProvider = new PlaylistItemLabelProvider(player);
// run
final String tooltip = labelProvider.getToolTipText(item);
// assert
assertThat(tooltip).isEqualTo("album: Album 01\n" + //
"genre: Audiobook\n" + //
"year: 2002\n" + //
"channels: stereo\n" + //
"sampling rate: 44100 Hz\n" + //
"bitrate: 192000 bit/s");
}
@Test
public void test_getToolTipText_unknown() throws Exception {
// setup
final TinyAudioPlayer player = mock(TinyAudioPlayer.class);
final PlaylistItem item = new PlaylistItem("Track 01", new File("01 - Track 01.mp3").toURI(), -1);
final PlaylistItemLabelProvider labelProvider = new PlaylistItemLabelProvider(player);
// run
final String tooltip = labelProvider.getToolTipText(item);
// assert
assertThat(tooltip).isEqualTo("channels: unknown\n" + //
"sampling rate: unknown\n" + //
"bitrate: unknown");
}
}
| mit |
hrgdavor/java-hipster-sql | sql/src/main/java/hr/hrg/hipster/sql/Key.java | 109 | package hr.hrg.hipster.sql;
public interface Key<K> {
public Class<K> getType();
public int ordinal();
}
| mit |
nbv3/voogasalad_CS308 | src/com/syntacticsugar/vooga/gameplayer/universe/map/tiles/effects/TileDamageTemporaryEffect.java | 2517 | package com.syntacticsugar.vooga.gameplayer.universe.map.tiles.effects;
import com.syntacticsugar.vooga.gameplayer.attribute.TimedDespawnAttribute;
import java.io.Serializable;
import com.syntacticsugar.vooga.gameplayer.event.implementations.HealthChangeEvent;
import com.syntacticsugar.vooga.gameplayer.event.implementations.ObjectSpawnEvent;
import com.syntacticsugar.vooga.gameplayer.objects.GameObject;
import com.syntacticsugar.vooga.gameplayer.objects.GameObjectType;
import com.syntacticsugar.vooga.gameplayer.objects.IGameObject;
import com.syntacticsugar.vooga.gameplayer.universe.IGameUniverse;
import com.syntacticsugar.vooga.gameplayer.universe.map.IGameMap;
public class TileDamageTemporaryEffect extends AbstractTileEffect implements Serializable {
private static final long serialVersionUID = 10L;
private Double myDamage;
private int myDelay;
private int myFrameCount;
private String myHitImagePath;
private int myImagePersistenceLength;
public TileDamageTemporaryEffect(Double d, int time) {
myDamage = d;
myDelay = time;
myFrameCount = 0;
myHitImagePath = null;
myImagePersistenceLength = 20;
}
@Override
protected void doEffect(IGameUniverse universe) {
if (myFrameCount >= myDelay) {
IGameMap map = universe.getMap();
for (IGameObject obj: universe.getGameObjects()){
if (map.getTile(obj.getBoundingBox().getPoint()).equals(myTile)) {
HealthChangeEvent health = new HealthChangeEvent(myDamage);
health.executeEvent(obj);
}
}
if (myHitImagePath != null) {
IGameObject obj = new GameObject(GameObjectType.ITEM, myTile.getPoint(), map.getTileSize(), map.getTileSize(), myHitImagePath);
TimedDespawnAttribute timer = new TimedDespawnAttribute();
timer.setTimeHere(myImagePersistenceLength);
obj.addAttribute(timer);
timer.setParent(obj);
ObjectSpawnEvent event = new ObjectSpawnEvent(obj);
universe.postEvent(event);
}
myTile.setTileEffect(null);
}
myFrameCount++;
}
@Override
public String getEffectName() {
return this.getClass().getSimpleName().substring(4, this.getClass().getSimpleName().length() - 6);
}
public String getHitImagePath() {
return myHitImagePath;
}
public void setHitImagePath(String hitImagePath) {
this.myHitImagePath = hitImagePath;
}
public int getImagePersistenceLength() {
return myImagePersistenceLength;
}
public void setImagePersistenceLength(int ImagePersistenceLength) {
this.myImagePersistenceLength = ImagePersistenceLength;
}
}
| mit |
umdk/UCDLive_Android | ulive-demo/src/main/java/com/ucloud/ulive/example/utils/AverageAudioMixer.java | 2131 | package com.ucloud.ulive.example.utils;
import android.util.Log;
import static android.content.ContentValues.TAG;
public class AverageAudioMixer {
public byte[] scale(byte[] orignBuff, int size, float volumeScale) {
for (int i = 0; i < size; i += 2) {
short origin = (short) (((orignBuff[i + 1] << 8) | orignBuff[i] & 0xff));
origin = (short) (origin * volumeScale);
orignBuff[i + 1] = (byte) (origin >> 8);
orignBuff[i] = (byte) (origin);
}
return orignBuff;
}
public byte[] mixRawAudioBytes(byte[][] bMulRoadAudioes) {
if (bMulRoadAudioes == null || bMulRoadAudioes.length == 0) {
return null;
}
byte[] realMixAudio = bMulRoadAudioes[0];
if (bMulRoadAudioes.length == 1) {
return realMixAudio;
}
for (int rw = 0; rw < bMulRoadAudioes.length; ++rw) {
if (bMulRoadAudioes[rw].length != realMixAudio.length) {
Log.e(TAG, "lifecycle->demo->AverageAudioMixer->column of the road of audio + " + rw + " is diffrent!");
return null;
}
}
int row = bMulRoadAudioes.length;
int column = realMixAudio.length / 2;
short[][] sMulRoadAudioes = new short[row][column];
for (int r = 0; r < row; ++r) {
for (int c = 0; c < column; ++c) {
sMulRoadAudioes[r][c] = (short) ((bMulRoadAudioes[r][c * 2] & 0xff) | (bMulRoadAudioes[r][c * 2 + 1] & 0xff) << 8);
}
}
short[] sMixAudio = new short[column];
int mixVal;
int sr;
for (int sc = 0; sc < column; ++sc) {
mixVal = 0;
sr = 0;
for (; sr < row; ++sr) {
mixVal += sMulRoadAudioes[sr][sc];
}
sMixAudio[sc] = (short) (mixVal / row);
}
for (sr = 0; sr < column; ++sr) {
realMixAudio[sr * 2] = (byte) (sMixAudio[sr] & 0x00FF);
realMixAudio[sr * 2 + 1] = (byte) ((sMixAudio[sr] & 0xFF00) >> 8);
}
return realMixAudio;
}
}
| mit |
wiseman33/prog_mobile_app_android_part1 | Permissions/Lab3b_DangerousApp/gen/course/labs/dangerousapp/R.java | 1579 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package course.labs.dangerousapp;
public final class R {
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
*/
public static final int activity_horizontal_margin=0x7f040000;
public static final int activity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f050000;
public static final int hello_world=0x7f050001;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
*/
public static final int AppBaseTheme=0x7f060000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
}
}
| mit |
byu-vv-lab/mercury | src/main/java/edu/byu/cs/vv/Parser/ProgramListener.java | 4182 | package edu.byu.cs.vv.Parser;
import edu.byu.cs.vv.Syntax.Operations.Operation;
import edu.byu.cs.vv.Syntax.Operations.Receive;
import edu.byu.cs.vv.Syntax.Operations.Send;
import edu.byu.cs.vv.Syntax.Program;
import org.antlr.v4.runtime.tree.ErrorNode;
import java.lang.*;
import java.util.HashMap;
import java.util.Map;
public class ProgramListener extends edu.byu.cs.vv.Parser.CTPParserBaseListener {
@Override
public void visitErrorNode(ErrorNode node) {
System.out.println("Error in syntax: " + node.toString());
throw new RuntimeException("Error in syntax: " + node.toString());
}
private ProgramBuilder programBuilder;
private ProcessBuilder processBuilder;
private Map<Integer, Integer> sends;
private int recv_rank;
public Program getProgram() {
return programBuilder.finish();
}
@Override
public void enterProgram(edu.byu.cs.vv.Parser.CTPParser.ProgramContext ctx) {
programBuilder = new ProgramBuilder();
super.enterProgram(ctx);
}
@Override
public void enterThread(edu.byu.cs.vv.Parser.CTPParser.ThreadContext ctx) {
processBuilder = new ProcessBuilder();
processBuilder.setRank(programBuilder.size());
sends = new HashMap<>();
recv_rank = 0;
super.enterThread(ctx);
}
@Override
public void enterThreadHeader(edu.byu.cs.vv.Parser.CTPParser.ThreadHeaderContext ctx) {
processBuilder.setName(ctx.children.get(1).getText());
super.enterThreadHeader(ctx);
}
@Override
public void exitThread(edu.byu.cs.vv.Parser.CTPParser.ThreadContext ctx) {
programBuilder.addProcess(processBuilder.finish());
super.exitThread(ctx);
}
// NOTE: This ignores the destination specified in the dsl for the receive, and assumes that the receive
// endpoint is the thread it is declared within.
@Override
public void enterReceive(edu.byu.cs.vv.Parser.CTPParser.ReceiveContext ctx) {
int source = Integer.parseInt(ctx.children.get(1).getText());
Operation op = new Receive(
processBuilder.rank() + "_" + processBuilder.size(), // Name
processBuilder.rank(), // Process Rank
recv_rank, // Operation Rank
source, // Source
processBuilder.rank(), // Destination
null, // Matching Send
null, // Nearest wait
true, // Blocking?
(source == -1)); // Wildcard?
processBuilder.addOperation(op);
recv_rank++;
super.enterReceive(ctx);
}
@Override
public void enterSend(edu.byu.cs.vv.Parser.CTPParser.SendContext ctx) {
int rank, destination = Integer.parseInt(ctx.children.get(1).getText());
if (sends.containsKey(destination)) {
rank = sends.get(destination);
} else {
rank = 0;
}
Operation op = new Send(
processBuilder.rank() + "_" + processBuilder.size(), // Name
processBuilder.rank(), // Process Rank
rank, // Operation rank
processBuilder.rank(), // Source
destination, // Destination
null, // Matching receive
Integer.parseInt(ctx.children.get(2).getText()), // Value
true, // Blocking?
null); // Nearest wait
processBuilder.addOperation(op);
sends.put(destination, rank + 1);
super.enterSend(ctx);
}
}
| mit |
jpasearch/jpasearch | src/main/java/jpasearch/repository/query/OrderByDirection.java | 85 | package jpasearch.repository.query;
public enum OrderByDirection {
ASC, DESC;
}
| mit |
GamrCorps/Mod | src/main/java/src/enigma/calin/armor/ArmorJihadVest.java | 344 | package src.enigma.calin.armor;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
/**
* Created by Calin on 8/17/2015.
*/
public class ArmorJihadVest extends Item
{
public ArmorJihadVest()
{
setCreativeTab(CreativeTabs.tabCombat);
setNoRepair();
this.maxStackSize = 1;
}
}
| mit |
7040210/SuperBoot | super-boot-utils/src/main/java/org/superboot/utils/IPUtils.java | 1101 | package org.superboot.utils;
import javax.servlet.http.HttpServletRequest;
/**
* <b> IP校验 </b>
* <p>
* 功能描述:
* </p>
*/
public class IPUtils {
public static String getClientAddress(HttpServletRequest request) {
if (request == null) {
return "unknown";
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
| mit |
kjhkit/Public-Stream-Rip | StreamRipper.java | 4459 | /* @Author: John McCain
* @Date: 11-30-15
* @Version 1.0
* @Description: Records an audio stream in one hour increments. Labels files.
* Note: lines that need to be modified are marked
*/
import java.net.URLConnection;
import java.net.URL;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class StreamRipper
{
static boolean firstHour;
static DateFormat dateFormat = new SimpleDateFormat("MM-dd-yy HHmm");
static DateFormat topOfHourFormat = new SimpleDateFormat("mm");
public static void main(String[] args)
{
final long MINUTE_IN_MS = 1000 * 60 * 60;
boolean errorOccurred = false;
Date errorDate = new Date();
while(true) //Master while loop, should only loop if there is an error
{
System.out.println("Starting the Stream Ripper...");
//Used to cut first export file short as to start on hour
firstHour = true;
if(errorOccurred)
{
Date compareDate = new Date(System.currentTimeMillis()-5*MINUTE_IN_MS);
if(errorDate.compareTo(compareDate)>=0)
{
Date nowDate = new Date();
System.out.println("An error occurred! This has happened recently, Stream Rip will wait 5 minutes before trying again. TIME: " + dateFormat.format(nowDate));
try
{
Thread.sleep(1000*60*5);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
System.out.println("An error occurred! We still gucci tho");
}
errorDate = new Date();
errorOccurred = false;
}
try
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY-3); //Sets priority to just below the maximum (Maximum is real time, which would be bad and starve everything else) (Java priority values range from 1 to 10)
//Connects to the stream
/********* PUT FULL URL OF DESIRED STREAM HERE *********/
URLConnection myConnection = new URL("YOUR_STREAM_URL_HERE").openConnection();
//Creates input stream to process the stream
InputStream instream = myConnection.getInputStream();
while(true)
{
//Get current date/time for timestamp in filename
Date date = new Date();
//Set output filename
/********* CHANGE .mp3 TO DESIRED FILE FORMAT IF NECESSARY *********/
String filename = "STRM" + dateFormat.format(date) + ".mp3";
/********* PUT TARGET DIRECTORY HERE *********/
//Note: format like so: "C:/SomeDirectory/Stream Rip/"
//This directory must already exist
String filepath = "YOUR_DIRECTORY_HERE" + filename;
//Creates output steam to export the stream to an mp3 file
OutputStream outstream = new FileOutputStream(new File(filepath));
//Buffer
byte[] buffer = new byte[16384];
//Stores length of the buffer in bytes
int len;
//Iterator to limit length of the exported file in bytes.
long t = 0;
//Make sure the buffer isn't empty
while(!(instream.read(buffer)>0))
{
//Chill
}
Thread.sleep(10);
//Writes the buffer to the output file when the buffer size is>0 and the length of the output file is < the specified limit and it is not both the top of the hour and the first export file in this succesful run
//Note: To calculate bit limit from time, take 128kbps/8bpB to get the number of Bytes per second. Multiply by the number of seconds desired. 57600000 is one hour.
while (((len = instream.read(buffer)) > 0 && ((t+=len)<57600000)) && !(firstHour && isOnHour()))
{
Thread.sleep(10);
outstream.write(buffer, 0, len);
}
outstream.close();
System.out.println("Just exported a file. It is " + t + " bytes and the file name is " + filename);
}
}
catch(Exception e)
{
e.printStackTrace();
errorOccurred = true;
}
}
}
//Pre: topOfHourFormat is a SimpleDateFormat of style "mm", firstHour is a declared boolean
//Post: firstHour is set to false if it is the top of the hour
//Returns: boolean, true if it is the top of the hour, false if it is not
static boolean isOnHour()
{
Date currentTime = new Date();
if(topOfHourFormat.format(currentTime).equals("00"))
{
firstHour = false;
System.out.println("Exporting a file early in order to start on the hour");
return true;
}
return false;
}
}
| mit |
hosuaby/example-restful-project | src/main/java/io/hosuaby/restful/services/TeapotCommandService.java | 4011 | package io.hosuaby.restful.services;
import io.hosuaby.restful.controllers.TeapotCommandController;
import io.hosuaby.restful.services.exceptions.teapots.TeapotNotConnectedException;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.socket.WebSocketSession;
/**
* Service that provides registration of teapots and communication with them via
* web socket sessions.
*/
public interface TeapotCommandService {
/**
* Registers a newly connected teapot with associated websocket connection.
*
* @param teapotId teapot id
* @param session teapot websocket session
*/
void register(String teapotId, WebSocketSession session);
/**
* Unregisters disconnected teapot. This method don't close teapot session.
* Teapot session must be closed prior to call of this method. Teapot must
* be registered prior to call of this method.
*
* @param teapotSession teapot websocket session
*/
void unregister(WebSocketSession teapotSession);
/**
* Shutdown the connected teapot. This method is called by
* {@link TeapotCommandController}.
*
* @param teapotId teapot id.
*
* @throws IOException
* failed to close teapot session
* @throws TeapotNotConnectedException
* teapot with defined id is not connected
*/
void shutdown(String teapotId) throws IOException,
TeapotNotConnectedException;
/**
* @return ids of registered teapots.
*/
String[] getRegisteredTeapotsIds();
/**
* Returns true if teapot with defined id is connected, and false if teapot
* is not connected.
*
* @param teapotId teapot id
*
* @return true if teapot is connected, false if not
*/
boolean isTeapotConnected(String teapotId);
/**
* Sends the message to the teapot from Ajax client. This method returns
* {@link DeferredResult} that will be fulfilled once teapot returns the
* answer. If any error occurs during processing deferred object is
* rejected with appropriate error code and message.
* For chaque Ajax request method generates unique clientId that will be
* transmitted to teapot.
*
* @param req ajax http request
* @param teapotId teapot id
* @param msg message to send
*
* @return deferred result
*/
DeferredResult<String> sendMessage(HttpServletRequest req, String teapotId,
String msg);
/**
* Submits response from the teapot to the client. Attribute
* <code>clientId</code> can reference unique request in case of Ajax
* request or websocket session if client is connected via websocket.
* If command was made by Ajax request, associated DeferredResult
* is fulfilled.
*
* @param clientId request or websocket session id
* @param msg message to send
*/
void submitResponse(String clientId, String msg);
/**
* Submits response from the teapot to the client. Attribute
* <code>clientId</code> can reference unique request in case of Ajax
* request or websocket session if client is connected via websocket.
* In the case of Ajax request, if <code>isLast</code> is set to
* <code>true</code> the message is appended to the buffer instead of
* immediate fulfill of the <code>DeferredResult</code> object.
*
* @param clientId request or websocket session id
* @param msg message to send
* @param isLast flag of the last message of the response
*/
void submitResponse(String clientId, String msg, boolean isLast);
/**
* Sends error message back to client.
*
* @param clientId request or websocket session id
* @param error error message
*/
void submitError(String clientId, String error);
}
| mit |
anton23/gpanalyser | src-pctmc/uk/ac/imperial/doc/pctmc/postprocessors/numerical/NumericalPostprocessorCI.java | 3999 | package uk.ac.imperial.doc.pctmc.postprocessors.numerical;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.jfree.data.xy.XYDataset;
import uk.ac.imperial.doc.jexpressions.constants.Constants;
import uk.ac.imperial.doc.jexpressions.expressions.AbstractExpression;
import uk.ac.imperial.doc.jexpressions.javaoutput.statements.AbstractExpressionEvaluator;
import uk.ac.imperial.doc.pctmc.analysis.AbstractPCTMCAnalysis;
import uk.ac.imperial.doc.pctmc.analysis.AnalysisUtils;
import uk.ac.imperial.doc.pctmc.analysis.plotexpressions.PlotDescription;
import uk.ac.imperial.doc.pctmc.charts.PCTMCChartUtilities;
import uk.ac.imperial.doc.pctmc.utils.FileUtils;
public abstract class NumericalPostprocessorCI extends NumericalPostprocessor {
public NumericalPostprocessorCI(double stopTime, double stepSize) {
super(stopTime, stepSize);
}
protected double[][][] absHalfCIWidth;
protected List<PlotDescription> plotDescriptions;
public void setPlotDescriptions(List<PlotDescription> plotDescriptions) {
this.plotDescriptions = plotDescriptions;
}
@Override
public final void postprocessAnalysis(Constants constants,
AbstractPCTMCAnalysis analysis,
List<PlotDescription> _plotDescriptions){
plotDescriptions = _plotDescriptions;
prepare(analysis, constants);
calculateDataPoints(constants);
if (dataPoints!=null)
{
results = new LinkedHashMap<PlotDescription, double[][]>();
resultsCI = new LinkedHashMap<PlotDescription, double[][]>();
int index=0;
for (PlotDescription pd:plotDescriptions)
{
double[][] ci = null;
if (absHalfCIWidth!=null)
{
ci = absHalfCIWidth[index++];
resultsCI.put(pd, ci);
}
double[][] data = plotData(analysis.toString(), constants, ci, pd.getExpressions(), pd.getFilename());
results.put(pd, data);
}
}
setResults(constants, _plotDescriptions);
}
public void setResults(Constants constants,
List<PlotDescription> _plotDescriptions) {
if (dataPoints!=null)
{
results = new LinkedHashMap<PlotDescription, double[][]>();
resultsCI = new LinkedHashMap<PlotDescription, double[][]>();
int index=0;
for (PlotDescription pd:plotDescriptions)
{
double[][] ci = null;
if (absHalfCIWidth!=null)
{
ci = absHalfCIWidth[index++];
resultsCI.put(pd, ci);
}
results.put(pd, evaluateExpressions(pd.getExpressions(), constants));
}
}
}
protected Map<PlotDescription, double[][]> resultsCI;
public Map<PlotDescription, double[][]> getResultsCI() {
return resultsCI;
}
public double[][] plotData(String analysisTitle,
Constants constants, double[][] dataCI, List<AbstractExpression> expressions,
String filename) {
if (dataCI == null)
{
return super.plotData(analysisTitle, constants, expressions, filename);
}
else
{
String[] names = new String[expressions.size()];
for (int i = 0; i < expressions.size(); i++) {
names[i] = expressions.get(i).toString();
}
double[][] data = evaluateExpressions(expressions, constants);
XYDataset dataset = AnalysisUtils.getDatasetFromArray(data, dataCI, stepSize, names);
PCTMCChartUtilities.drawDeviationChart(dataset, "time", "count", "", analysisTitle+this.toString());
if (filename != null && !filename.equals("")) {
List<String> labels = new LinkedList<String>();
for (AbstractExpression e : expressions) {
labels.add(e.toString());
}
FileUtils.writeGnuplotFile(filename, "", labels, "time", "count");
FileUtils.writeCSVfile(filename, dataset);
}
return data;
}
}
public double[] evaluateExpressions(AbstractExpressionEvaluator evaluator,final double[] data, int t, Constants constants){
//evaluator.setRates(constants.getFlatConstants());
double[] selectedData = new double[evaluator.getNumberOfExpressions()];
selectedData = evaluator.update(constants.getFlatConstants(),data, t * stepSize);
return selectedData;
}
}
| mit |
simon816/Mixin | src/ap/java/org/spongepowered/tools/obfuscation/struct/Message.java | 3695 | /*
* This file is part of Mixin, 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.tools.obfuscation.struct;
import javax.annotation.processing.Messager;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.tools.Diagnostic;
/**
* Wrapper for Annotation Processor messages, used to enable messages to be
* easily queued and manipulated
*/
public class Message {
private Diagnostic.Kind kind;
private CharSequence msg;
private final Element element;
private final AnnotationMirror annotation;
private final AnnotationValue value;
public Message(Diagnostic.Kind kind, CharSequence msg) {
this(kind, msg, null, null, null);
}
public Message(Diagnostic.Kind kind, CharSequence msg, Element element) {
this(kind, msg, element, null, null);
}
public Message(Diagnostic.Kind kind, CharSequence msg, Element element, AnnotationMirror annotation) {
this(kind, msg, element, annotation, null);
}
public Message(Diagnostic.Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, AnnotationValue value) {
this.kind = kind;
this.msg = msg;
this.element = element;
this.annotation = annotation;
this.value = value;
}
public Message sendTo(Messager messager) {
if (this.value != null) {
messager.printMessage(this.kind, this.msg, this.element, this.annotation, this.value);
} else if (this.annotation != null) {
messager.printMessage(this.kind, this.msg, this.element, this.annotation);
} else if (this.element != null) {
messager.printMessage(this.kind, this.msg, this.element);
} else {
messager.printMessage(this.kind, this.msg);
}
return this;
}
public Diagnostic.Kind getKind() {
return this.kind;
}
public Message setKind(Diagnostic.Kind kind) {
this.kind = kind;
return this;
}
public CharSequence getMsg() {
return this.msg;
}
public Message setMsg(CharSequence msg) {
this.msg = msg;
return this;
}
public Element getElement() {
return this.element;
}
public AnnotationMirror getAnnotation() {
return this.annotation;
}
public AnnotationValue getValue() {
return this.value;
}
}
| mit |
blutorange/lotsOfBSGdx | core/src/de/homelab/madgaksha/lotsofbs/entityengine/entitysystem/DamageSystem.java | 3092 | package de.homelab.madgaksha.lotsofbs.entityengine.entitysystem;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.IteratingSystem;
import com.badlogic.gdx.math.MathUtils;
import de.homelab.madgaksha.lotsofbs.entityengine.DefaultPriority;
import de.homelab.madgaksha.lotsofbs.entityengine.Mapper;
import de.homelab.madgaksha.lotsofbs.entityengine.component.DamageQueueComponent;
import de.homelab.madgaksha.lotsofbs.entityengine.component.DeathComponent;
import de.homelab.madgaksha.lotsofbs.entityengine.component.InactiveComponent;
import de.homelab.madgaksha.lotsofbs.entityengine.component.PainPointsComponent;
import de.homelab.madgaksha.lotsofbs.entityengine.component.VoiceComponent;
import de.homelab.madgaksha.lotsofbs.logging.Logger;
/**
* Updates an object's position its velocity over a small time step dt.
*
* @author madgaksha
*/
public class DamageSystem extends IteratingSystem {
@SuppressWarnings("unused")
private final static Logger LOG = Logger.getLogger(DamageQueueComponent.class);
public static final long MAX_PAIN_POINTS = 999999999999L; // 10^12-1
public static final int NUMBER_OF_DIGITS = 12;
/**
* In per-mille (0.001). If damage/maxHP is greater than this theshold,
* other voices will be played etc.
*/
public static final long THRESHOLD_LIGHT_HEAVY_DAMAGE = 10L;
public DamageSystem() {
this(DefaultPriority.damageSystem);
}
public DamageSystem(final int priority) {
super(Family.all(PainPointsComponent.class, DamageQueueComponent.class).exclude(InactiveComponent.class).get(),
priority);
}
@Override
protected void processEntity(final Entity entity, final float deltaTime) {
final PainPointsComponent ppc = Mapper.painPointsComponent.get(entity);
final DamageQueueComponent dqc = Mapper.damageQueueComponent.get(entity);
// Change pain points accordingly.
if (dqc.queuedDamage != 0L) {
// take damage
final VoiceComponent vc = Mapper.voiceComponent.get(entity);
ppc.painPoints = MathUtils.clamp(ppc.painPoints + dqc.queuedDamage, 0L, ppc.maxPainPoints);
if (dqc.keepOneHp) {
ppc.painPoints = Math.min(ppc.maxPainPoints - 1, ppc.painPoints);
dqc.keepOneHp = false;
}
ppc.updatePainPoints();
// Check if entity just died :(
if (ppc.painPoints == ppc.maxPainPoints) {
final DeathComponent dc = Mapper.deathComponent.get(entity);
if (dc != null && !dc.dead) {
if (vc != null && vc.voicePlayer != null)
vc.voicePlayer.playUnconditionally(vc.onDeath);
dc.reaper.kill(entity);
dc.dead = true;
}
}
// Otherwise, play sound on taking damage
else if (vc != null && vc.voicePlayer != null) {
if (dqc.queuedDamage > 0L) {
vc.voicePlayer.play((dqc.queuedDamage * 1000L < THRESHOLD_LIGHT_HEAVY_DAMAGE * ppc.maxPainPoints)
? vc.onLightDamage : vc.onHeavyDamage);
}
else {
vc.voicePlayer.play((-dqc.queuedDamage * 1000L < THRESHOLD_LIGHT_HEAVY_DAMAGE * ppc.maxPainPoints)
? vc.onLightHeal : vc.onHeavyHeal);
}
}
}
dqc.queuedDamage = 0L;
}
}
| cc0-1.0 |
adolfosbh/cs2as | uk.ac.york.cs.cs2as.dsl/src-gen/uk/ac/york/cs/cs2as/cs2as_dsl/ContributionsDef.java | 1310 | /**
*/
package uk.ac.york.cs.cs2as.cs2as_dsl;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Contributions Def</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link uk.ac.york.cs.cs2as.cs2as_dsl.ContributionsDef#getContributions <em>Contributions</em>}</li>
* </ul>
*
* @see uk.ac.york.cs.cs2as.cs2as_dsl.Cs2as_dslPackage#getContributionsDef()
* @model
* @generated
*/
public interface ContributionsDef extends EObject
{
/**
* Returns the value of the '<em><b>Contributions</b></em>' containment reference list.
* The list contents are of type {@link uk.ac.york.cs.cs2as.cs2as_dsl.Contribution}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Contributions</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Contributions</em>' containment reference list.
* @see uk.ac.york.cs.cs2as.cs2as_dsl.Cs2as_dslPackage#getContributionsDef_Contributions()
* @model containment="true"
* @generated
*/
EList<Contribution> getContributions();
} // ContributionsDef
| epl-1.0 |
rpau/AutoRefactor | plugin/src/main/java/org/autorefactor/jdt/internal/ui/fix/NewClassImportCleanUp.java | 9275 | /*
* AutoRefactor - Eclipse plugin to automatically refactor Java code bases.
*
* Copyright (C) 2019 Fabrice Tiercelin - initial API and implementation
*
* 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
* 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 under LICENSE-GNUGPL. If not, see
* <http://www.gnu.org/licenses/>.
*
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution under LICENSE-ECLIPSE, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.autorefactor.jdt.internal.ui.fix;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.autorefactor.jdt.core.dom.ASTRewrite;
import org.autorefactor.jdt.internal.corext.dom.InterruptibleVisitor;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ImportDeclaration;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.TypeDeclaration;
/**
* Handle the need to add an import for a class.
*/
public abstract class NewClassImportCleanUp extends AbstractCleanUpRule {
/**
* The class that does the cleanup when an import needs to be added.
*/
public abstract static class CleanUpWithNewClassImport extends ASTVisitor {
private Set<String> classesToUseWithImport= new HashSet<>();
private Set<String> importsToAdd= new HashSet<>();
/**
* The imports that need to be added.
*
* @return the importsToBeAdd
*/
public Set<String> getImportsToAdd() {
return importsToAdd;
}
/**
* The imports already existing.
*
* @return the already imported classes
*/
public Set<String> getClassesToUseWithImport() {
return classesToUseWithImport;
}
}
private static class LocalClassVisitor extends InterruptibleVisitor {
private Set<String> classnamesNeverUsedLocally= new HashSet<>();
/**
* LocalClassVisitor.
*
* @param classnamesNeverUsedLocally Classnames never used locally
*/
public LocalClassVisitor(final Set<String> classnamesNeverUsedLocally) {
this.classnamesNeverUsedLocally= classnamesNeverUsedLocally;
}
@Override
public boolean visit(final TypeDeclaration nestedClass) {
classnamesNeverUsedLocally.remove(nestedClass.getName().getIdentifier());
return !classnamesNeverUsedLocally.isEmpty() || interruptVisit();
}
@Override
public boolean visit(final SimpleType simpleName) {
if (simpleName.getName().isSimpleName()) {
classnamesNeverUsedLocally.remove(((SimpleName) simpleName.getName()).getIdentifier());
if (classnamesNeverUsedLocally.isEmpty()) {
return interruptVisit();
}
}
return true;
}
/**
* @return the classnamesNeverUsedLocally
*/
public Set<String> getClassnamesNeverUsedLocally() {
return classnamesNeverUsedLocally;
}
}
/**
* True if an import already exists for a class.
*
* @param node One node in the class file
* @return True if an import already exists for a class.
*/
public Set<String> getAlreadyImportedClasses(final ASTNode node) {
Set<String> alreadyImportedClasses= new HashSet<>();
CompilationUnit cu= (CompilationUnit) node.getRoot();
Set<String> classesToUse= getClassesToImport();
Map<String, String> importsByPackage= new HashMap<>();
for (String clazz : classesToUse) {
importsByPackage.put(getPackageName(clazz), clazz);
}
for (Object anObject : cu.imports()) {
ImportDeclaration anImport= (ImportDeclaration) anObject;
if (anImport.isOnDemand()) {
String fullName= importsByPackage.get(anImport.getName().getFullyQualifiedName());
if (fullName != null) {
alreadyImportedClasses.add(fullName);
}
} else if (classesToUse.contains(anImport.getName().getFullyQualifiedName())) {
alreadyImportedClasses.add(anImport.getName().getFullyQualifiedName());
}
}
return alreadyImportedClasses;
}
@Override
public boolean visit(final CompilationUnit node) {
if (!super.visit(node)) {
return false;
}
Set<String> classesToUse= getClassesToImport();
if (classesToUse.isEmpty()) {
return true;
}
Map<String, String> importsByClassname= new HashMap<>();
Map<String, String> importsByPackage= new HashMap<>();
for (String clazz : classesToUse) {
importsByClassname.put(getSimpleName(clazz), clazz);
importsByPackage.put(getPackageName(clazz), clazz);
}
Set<String> alreadyImportedClasses= new HashSet<>();
Set<String> classesToImport= new HashSet<>(classesToUse);
for (Object anObject : node.imports()) {
ImportDeclaration anImport= (ImportDeclaration) anObject;
if (!anImport.isStatic()) {
if (anImport.isOnDemand()) {
String fullName= importsByPackage.get(anImport.getName().getFullyQualifiedName());
if (fullName != null) {
alreadyImportedClasses.add(fullName);
}
} else if (classesToUse.contains(anImport.getName().getFullyQualifiedName())) {
alreadyImportedClasses.add(anImport.getName().getFullyQualifiedName());
classesToImport.remove(anImport.getName().getFullyQualifiedName());
} else if (importsByClassname.containsKey(getSimpleName(anImport.getName().getFullyQualifiedName()))) {
classesToImport
.remove(importsByClassname.get(getSimpleName(anImport.getName().getFullyQualifiedName())));
}
}
}
filterLocallyUsedNames(node, importsByClassname, classesToImport);
if (alreadyImportedClasses.size() < classesToUse.size() && !classesToImport.isEmpty()) {
CleanUpWithNewClassImport refactoringClass= getRefactoringClassInstance();
refactoringClass.getClassesToUseWithImport().addAll(alreadyImportedClasses);
refactoringClass.getClassesToUseWithImport().addAll(classesToImport);
node.accept(refactoringClass);
if (!refactoringClass.getImportsToAdd().isEmpty()) {
ASTRewrite rewrite= cuRewrite.getASTRewrite();
for (String importToAdd : refactoringClass.getImportsToAdd()) {
rewrite.getImportRewrite().addImport(importToAdd);
}
return false;
}
}
return true;
}
/**
* Add the class to the list of classes to import and return the name of the class.
*
* @param classToUse The class to use
* @param classesToUseWithImport The classes to use with import
* @param importsToAdd The imports to add
*
* @return the name of the class.
*/
public static String addImport(final Class<?> classToUse, final Set<String> classesToUseWithImport,
final Set<String> importsToAdd) {
if (classesToUseWithImport.contains(classToUse.getCanonicalName())) {
importsToAdd.add(classToUse.getCanonicalName());
return classToUse.getSimpleName();
}
return classToUse.getCanonicalName();
}
/**
* The simple name of the class.
*
* @param fullyQualifiedName The name of the class with packages.
* @return The simple name of the class.
*/
public String getSimpleName(final String fullyQualifiedName) {
return fullyQualifiedName.replaceFirst("^(?:.*\\.)?([^.]*)$", "$1"); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* The package of the class.
*
* @param fullyQualifiedName The name of the class with packages.
* @return The package of the class.
*/
public String getPackageName(final String fullyQualifiedName) {
return fullyQualifiedName.replaceFirst("^(.*)\\.[^.]+$", "$1"); //$NON-NLS-1$ //$NON-NLS-2$
}
private void filterLocallyUsedNames(final CompilationUnit node, final Map<String, String> importsByClassname,
final Set<String> classesToImport) {
LocalClassVisitor nestedClassVisitor= new LocalClassVisitor(importsByClassname.keySet());
nestedClassVisitor.visitNode(node);
Set<String> classnamesNeverUsedLocally= nestedClassVisitor.getClassnamesNeverUsedLocally();
Iterator<String> iterator= classesToImport.iterator();
while (iterator.hasNext()) {
String classToImport= iterator.next();
if (!classnamesNeverUsedLocally.contains(getSimpleName(classToImport))) {
iterator.remove();
}
}
}
/**
* The class that does the cleanup when an import needs to be added.
*
* @return The class that does the cleanup when an import needs to be added.
*/
public abstract CleanUpWithNewClassImport getRefactoringClassInstance();
/**
* The class names to import.
*
* @return The class names to import
*/
public abstract Set<String> getClassesToImport();
}
| epl-1.0 |
jmini/org.eclipsescout.rt.ui.fx | org.eclipsescout.rt.ui.fx/src/org/eclipsescout/rt/ui/fx/basic/chart/factory/AbstractFxScoutChartFactory.java | 6789 | /*******************************************************************************
* Copyright (c) 2014 BSI Business Systems Integration AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* BSI Business Systems Integration AG - initial API and implementation
******************************************************************************/
package org.eclipsescout.rt.ui.fx.basic.chart.factory;
import java.util.Collection;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.HPos;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.chart.Chart;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.control.TextField;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import org.eclipse.scout.rt.shared.TEXTS;
import org.eclipsescout.rt.ui.fx.FxStyleUtility;
import org.eclipsescout.rt.ui.fx.IFxEnvironment;
import org.eclipsescout.rt.ui.fx.basic.chart.FxScoutChartRowData;
/**
*
*/
public abstract class AbstractFxScoutChartFactory implements IFxScoutChartFactory {
private Chart m_chart;
private GridPane m_controlPanel;
private int m_controlRowCount;
private ObservableList<FxScoutChartRowData> m_data;
private ObservableList<String> m_columnTitles;
private ObservableList<String> m_categoryTitles;
private IFxEnvironment m_fxEnvironment;
private ChartProperties m_chartProperties;
private boolean m_isInverse = false;
public AbstractFxScoutChartFactory(ObservableList<FxScoutChartRowData> data, Collection<String> columns, ChartProperties chartProperties, IFxEnvironment fxEnvironment) {
m_controlPanel = new GridPane();
m_data = FXCollections.observableArrayList();
m_data.addAll(data);
m_columnTitles = FXCollections.observableArrayList(columns);
m_categoryTitles = FXCollections.observableArrayList();
for (FxScoutChartRowData row : data) {
m_categoryTitles.add(row.getRowName());
}
m_chartProperties = chartProperties;
m_fxEnvironment = fxEnvironment;
}
@Override
public Chart getChart() {
return m_chart;
}
public void setChart(Chart chart) {
m_chart = chart;
}
@Override
public Pane getControlPanel() {
return m_controlPanel;
}
public ObservableList<FxScoutChartRowData> getData() {
return m_data;
}
public ObservableList<String> getColumnTitles() {
return m_columnTitles;
}
public ObservableList<String> getCategoryTitles() {
return m_categoryTitles;
}
/**
* Should be implemented by overwritten charts to build the appropriate chart.
*/
protected abstract void buildChart();
protected abstract void buildData();
@Override
public void rebuildFromData(ObservableList<FxScoutChartRowData> data, Collection<String> columnTitles) {
m_columnTitles.setAll(columnTitles);
m_data.setAll(data);
m_categoryTitles.clear();
for (FxScoutChartRowData row : data) {
m_categoryTitles.add(row.getRowName());
}
buildData();
}
/**
* Should be overwritten if additional functionality will be provided. A super call as the first operation is
* mandatory.
*/
protected void buildControlPanel() {
m_controlPanel = new GridPane();
m_controlPanel.setHgap(10);
m_controlPanel.setVgap(5);
FxStyleUtility.setPadding(m_controlPanel, 5);
ColumnConstraints c1 = new ColumnConstraints();
c1.setHalignment(HPos.RIGHT);
ColumnConstraints c2 = new ColumnConstraints();
c2.setHalignment(HPos.LEFT);
m_controlPanel.getColumnConstraints().addAll(c1, c2);
m_controlRowCount = 0;
addSeparatorElement(TEXTS.get("GeneralControls"));
// legend side
ObservableList<Side> side = FXCollections.observableArrayList(Side.values());
ChoiceBox<Side> legendSide = new ChoiceBox<Side>(side);
// legend visible
CheckBox legendVisible = new CheckBox();
// title
TextField title = new TextField(getChart().getTitle());
title.setPromptText("title");
// title side
ChoiceBox<Side> titleSide = new ChoiceBox<Side>(side);
if (getChartProperties() != null) {
getChartProperties().bindToSettings(getChartProperties().legendSideProperty, getChart().legendSideProperty(), legendSide.valueProperty());
getChartProperties().bindToSettings(getChartProperties().legendVisibleProperty, getChart().legendVisibleProperty(), legendVisible.selectedProperty());
getChartProperties().bindToSettings(getChartProperties().titleSideProperty, getChart().titleSideProperty(), titleSide.valueProperty());
getChartProperties().bindToSettings(getChartProperties().titleProperty, getChart().titleProperty(), title.textProperty());
}
else {
legendSide.setValue(getChart().getLegendSide());
getChart().legendSideProperty().bind(legendSide.valueProperty());
legendVisible.setSelected(getChart().isLegendVisible());
getChart().legendVisibleProperty().bind(legendVisible.selectedProperty());
titleSide.setValue(getChart().getTitleSide());
getChart().titleSideProperty().bind(titleSide.valueProperty());
title.setText(getChart().getTitle());
getChart().titleProperty().bind(title.textProperty());
}
addControlElement(new Label(TEXTS.get("LegendSide")), legendSide);
addControlElement(new Label(TEXTS.get("LegendVisible")), legendVisible);
addControlElement(new Label(TEXTS.get("Title")), title);
addControlElement(new Label(TEXTS.get("TitleSide")), titleSide);
}
protected void addControlElement(Node... n) {
m_controlPanel.addRow(m_controlRowCount++, n);
}
protected void addSeparatorElement(String name) {
Label label = new Label(" " + name + " ");
Separator left = new Separator(Orientation.HORIZONTAL);
HBox.setHgrow(left, Priority.ALWAYS);
Separator right = new Separator(Orientation.HORIZONTAL);
HBox.setHgrow(right, Priority.ALWAYS);
HBox separator = new HBox(left, label, right);
separator.setAlignment(Pos.CENTER);
m_controlPanel.add(separator, 0, m_controlRowCount++, 3, 1);
}
@Override
public ChartProperties getChartProperties() {
return m_chartProperties;
}
public void inverseChart() {
m_isInverse = !m_isInverse;
}
public boolean isInverse() {
return m_isInverse;
}
}
| epl-1.0 |
LittleNoobLol/renren-crawler | renren-crawler/src/main/java/io/renren/common/aspect/SysLogAspect.java | 2563 | package io.renren.common.aspect;
import com.google.gson.Gson;
import io.renren.common.annotation.SysLog;
import io.renren.common.utils.HttpContextUtils;
import io.renren.common.utils.IPUtils;
import io.renren.modules.sys.entity.SysLogEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysLogService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
/**
* 系统日志,切面处理类
*
*/
@Aspect
@Component
public class SysLogAspect {
@Autowired
private SysLogService sysLogService;
@Pointcut("@annotation(io.renren.common.annotation.SysLog)")
public void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
//执行方法
Object result = point.proceed();
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//保存日志
saveSysLog(point, time);
return result;
}
private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
SysLogEntity sysLog = new SysLogEntity();
SysLog syslog = method.getAnnotation(SysLog.class);
if(syslog != null){
//注解上的描述
sysLog.setOperation(syslog.value());
}
//请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
sysLog.setMethod(className + "." + methodName + "()");
//请求的参数
Object[] args = joinPoint.getArgs();
try{
String params = new Gson().toJson(args[0]);
sysLog.setParams(params);
}catch (Exception e){
}
//获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//设置IP地址
sysLog.setIp(IPUtils.getIpAddr(request));
//用户名
String username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername();
sysLog.setUsername(username);
sysLog.setTime(time);
sysLog.setCreateDate(new Date());
//保存系统日志
sysLogService.save(sysLog);
}
}
| epl-1.0 |
michele-loreti/jResp | core/org.cmg.jresp.pastry/pastry-2.1/src/org/mpisws/p2p/transport/util/SocketWrapperSocket.java | 7716 | /*******************************************************************************
"FreePastry" Peer-to-Peer Application Development Substrate
Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute
for Software Systems. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of Rice University (RICE), Max Planck Institute for Software
Systems (MPI-SWS) nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
This software is provided by RICE, MPI-SWS and the contributors on an "as is"
basis, without any representations or warranties of any kind, express or implied
including, but not limited to, representations or warranties of
non-infringement, merchantability or fitness for a particular purpose. In no
event shall RICE, MPI-SWS or contributors be liable for any direct, indirect,
incidental, special, exemplary, or consequential damages (including, but not
limited to, procurement of substitute goods or services; loss of use, data, or
profits; or business interruption) however caused and on any theory of
liability, whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even if
advised of the possibility of such damage.
*******************************************************************************/
package org.mpisws.p2p.transport.util;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
import org.mpisws.p2p.transport.ErrorHandler;
import org.mpisws.p2p.transport.P2PSocket;
import org.mpisws.p2p.transport.P2PSocketReceiver;
import rice.environment.logging.Logger;
/**
* Just maps a socket from one form into another.
*
* @author Jeff Hoye
*
* @param <Identifier>
* @param <SubIdentifier>
*/
public class SocketWrapperSocket<Identifier, SubIdentifier> implements P2PSocket<Identifier>, P2PSocketReceiver<SubIdentifier> {
protected Identifier identifier;
protected P2PSocket<SubIdentifier> socket;
protected Logger logger;
protected Map<String, Object> options;
// TODO: make getters
protected P2PSocketReceiver<Identifier> reader, writer;
protected ErrorHandler<Identifier> errorHandler;
public SocketWrapperSocket(Identifier identifier, P2PSocket<SubIdentifier> socket, Logger logger, ErrorHandler<Identifier> errorHandler, Map<String, Object> options) {
this.identifier = identifier;
this.socket = socket;
this.logger = logger;
this.options = options;
this.errorHandler = errorHandler;
}
@Override
public Identifier getIdentifier() {
return identifier;
}
@Override
public void close() {
if (logger.level <= Logger.FINER) {
logger.logException("Closing "+this, new Exception("Stack Trace"));
} else if (logger.level <= Logger.FINE) logger.log("Closing "+this);
socket.close();
}
@Override
public long read(ByteBuffer dsts) throws IOException {
long ret = socket.read(dsts);
if (logger.level <= Logger.FINEST) logger.log(this+"read():"+ret);
return ret;
}
@Override
public void register(boolean wantToRead, boolean wantToWrite,
final P2PSocketReceiver<Identifier> receiver) {
// logger.log(this+"register("+wantToRead+","+wantToWrite+","+receiver+")");
if (logger.level <= Logger.FINEST) logger.log(this+"register("+wantToRead+","+wantToWrite+","+receiver+")");
if (wantToRead) {
if (reader != null && reader != receiver) throw new IllegalStateException("Already registered "+reader+" for reading. Can't register "+receiver);
reader = receiver;
}
if (wantToWrite) {
if (writer != null && writer != receiver) throw new IllegalStateException("Already registered "+reader+" for writing. Can't register "+receiver);
writer = receiver;
}
socket.register(wantToRead, wantToWrite, this);
// new P2PSocketReceiver<SubIdentifier>() {
// public void receiveSelectResult(P2PSocket<SubIdentifier> socket, boolean canRead,
// boolean canWrite) throws IOException {
// if (logger.level <= Logger.FINEST) logger.log(SocketWrapperSocket.this+"rsr("+socket+","+canRead+","+canWrite+")");
// receiver.receiveSelectResult(SocketWrapperSocket.this, canRead, canWrite);
// }
//
// public void receiveException(P2PSocket<SubIdentifier> socket, IOException e) {
// receiver.receiveException(SocketWrapperSocket.this, e);
// }
//
// public String toString() {
// return SocketWrapperSocket.this+"$1";
// }
// });
}
@Override
public void receiveSelectResult(P2PSocket<SubIdentifier> socket, boolean canRead,
boolean canWrite) throws IOException {
// logger.log(this+"rsr("+socket+","+canRead+","+canWrite+")");
if (logger.level <= Logger.FINEST) logger.log(this+"rsr("+socket+","+canRead+","+canWrite+")");
if (canRead && canWrite && (reader == writer)) {
P2PSocketReceiver<Identifier> temp = reader;
reader = null;
writer = null;
temp.receiveSelectResult(this, canRead, canWrite);
return;
}
if (canRead) {
P2PSocketReceiver<Identifier> temp = reader;
if (temp== null) {
if (logger.level <= Logger.WARNING) logger.log("no reader in "+this+".rsr("+socket+","+canRead+","+canWrite+")");
} else {
reader = null;
temp.receiveSelectResult(this, true, false);
}
}
if (canWrite) {
P2PSocketReceiver<Identifier> temp = writer;
if (temp == null) {
if (logger.level <= Logger.WARNING) logger.log("no writer in "+this+".rsr("+socket+","+canRead+","+canWrite+")");
} else {
writer = null;
temp.receiveSelectResult(this, false, true);
}
}
// receiver.receiveSelectResult(SocketWrapperSocket.this, canRead, canWrite);
}
@Override
public void receiveException(P2PSocket<SubIdentifier> socket, Exception e) {
// logger.log(this+".receiveException("+e+")");
if (writer != null) {
if (writer == reader) {
P2PSocketReceiver<Identifier> temp = writer;
writer = null;
reader = null;
temp.receiveException(this, e);
} else {
P2PSocketReceiver<Identifier> temp = writer;
writer = null;
temp.receiveException(this, e);
}
}
if (reader != null) {
P2PSocketReceiver<Identifier> temp = reader;
reader = null;
temp.receiveException(this, e);
}
if (reader == null && writer == null && errorHandler != null) errorHandler.receivedException(getIdentifier(), e);
// receiver.receiveException(SocketWrapperSocket.this, e);
}
@Override
public void shutdownOutput() {
socket.shutdownOutput();
}
@Override
public long write(ByteBuffer srcs) throws IOException {
long ret = socket.write(srcs);
if (logger.level <= Logger.FINEST) logger.log(this+"write():"+ret);
return ret;
}
@Override
public String toString() {
if (getIdentifier() == socket.getIdentifier()) return socket.toString();
return identifier+"-"+socket;
}
@Override
public Map<String, Object> getOptions() {
return options;
}
}
| epl-1.0 |
ghillairet/gmf-tooling-gwt-runtime | org.eclipse.gmf.runtime.lite.gwt/src/org/eclipse/gmf/runtime/gwt/ui/actions/DeleteViewAction.java | 1327 | /**
* Copyright (c) 2007 Borland Software Corporation
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* bblajer - initial API and implementation
*/
package org.eclipse.gmf.runtime.gwt.ui.actions;
import java.util.List;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gmf.runtime.gwt.requests.RequestConstants;
import org.eclipse.ui.IWorkbenchPart;
/**
* Action that deletes view only for shortcuts and children of non-canonical parents,
* and both the view and the model for children of canonical parents.
*/
public class DeleteViewAction extends DeleteAction {
public DeleteViewAction(IWorkbenchPart part) {
super(part);
}
@Override
protected void init() {
super.init();
setId(ActionIds.DELETE_VIEW);
setText("Delete From Diagram");
setToolTipText("Delete From Diagram");
}
@Override
public Command createDeleteCommand(List objects) {
if (objects.isEmpty()) {
return null;
}
if (!(objects.get(0) instanceof EditPart)) {
return null;
}
return createDeleteCommand(objects, RequestConstants.REQ_DELETE_VIEW);
}
}
| epl-1.0 |
mikera/magic | src/main/java/magic/Type.java | 3891 | package magic;
import magic.type.Intersection;
import magic.type.JavaType;
import magic.type.Union;
/**
* Abstract base class for Kiss types
*
* @author Mike
*
*/
public abstract class Type {
public static final Type[] EMPTY_TYPE_ARRAY = new Type[0];
/**
* Performs a runtime check if an object is an instance of this type
*
* @param o
* @return
*/
public abstract boolean checkInstance(Object o);
/**
* Returns the most specific Java class or interface that can represent all instances of this type
* @return
*/
public abstract Class<?> getJavaClass();
/**
* Returns true if this is a JVM primitive type
* @return
*/
public boolean isPrimitive() {
return false;
}
/**
* Return true if this type provably contains the null value
* @return
*/
public boolean canBeNull() {
return checkInstance(null);
}
/**
* Returns true if this type provably contains at least one truthy value
* @return
*/
public abstract boolean canBeTruthy();
/**
* Returns true if this type provably contains at least one falsey value
* @return
*/
public abstract boolean canBeFalsey();
/**
* Returns true if another type t is provably contained within this type.
*
* Equivalently this means:
* - t is a subtype of this type
* - every instance of t is an instance of this type
*
* If contains returns false, t may still be a subtype - it just can't be proven
*
* @param t
* @return
*/
public abstract boolean contains(Type t);
/**
* Returns the intersection of this type with another type
* @param t
* @return
*/
public Type intersection(Type t) {
return Intersection.create(this,t);
}
/**
* Returns the union of this type with another type
* @param t
* @return
*/
public Type union(Type t) {
return Union.create(this,t);
}
/**
* Returns true if this type can be proven to equal another type.
*
*/
@Override
public final boolean equals(Object o) {
if (o==this) return true;
if (!(o instanceof Type)) return false;
return equals((Type)o);
}
public boolean equals(Type t) {
return t.contains(this)&&this.contains(t);
}
public boolean equiv(Type t) {
// performance: check for immediate equality first
if (t.equals(this)) return true;
return t.contains(this)&&this.contains(t);
}
@Override
public int hashCode() {
return super.hashCode();
}
public Object cast(Object a) {
if (!checkInstance(a)) throw new ClassCastException("Can't cast value to type "+this.toString());
return a;
}
public abstract void validate();
public abstract Type inverse();
public boolean cannotBeNull() {
return !checkInstance(null);
}
public boolean cannotBeFalsey() {
return !(checkInstance(null)||checkInstance(Boolean.FALSE));
}
/**
* Returns true if the type provably cannot be a true value (i.e. must be null or Boolean.FALSE)
* @return
*/
public boolean cannotBeTruthy() {
return false;
}
@SuppressWarnings("unchecked")
public <T> JavaType<T> toJavaType() {
return (JavaType<T>) JavaType.create(this.getJavaClass());
}
/**
* Gets the return type of instances of this type
* Returns None if the Type does not represent a function
* @return
*/
public Type getReturnType() {
return Types.NONE;
}
/**
* Gets the variadic parameter type of instances of this type
* Returns None if the Type does not represent a function
* @return
*/
public Type getVariadicType() {
return Types.NONE;
}
/**
* Gets the variadic parameter type of instances of this type
* Returns None if the Type does not represent a function
* @return
*/
public Type getParamType(int i) {
return Types.NONE;
}
/**
* Returns true if this type potentially intersects another type
* @param type
* @return
*/
public boolean intersects(Type type) {
return !intersection(type).equals(Types.NONE);
}
}
| epl-1.0 |
nokiaeducationdelivery/ned-mobile-client | java/src/org/ned/client/view/style/NEDStyleToolbox.java | 1032 | /*******************************************************************************
* Copyright (c) 2011 Nokia Corporation
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Comarch team - initial API and implementation
*******************************************************************************/
package org.ned.client.view.style;
public class NEDStyleToolbox {
public static final int BACKGROUND_START_COLOR = 0x9fd056;
public static final int BACKGROUND_END_COLOR = 0x69b510;
public static final int MAIN_FONT_COLOR = 0x7b7b7b;
public static final int BLUE = 0x0000FF;
public static final int MAIN_BG_COLOR = 0xe1e1e1;
public static final int DARK_GREY = 0x7b7b7b;
public static final int WHITE = 0xffffff;
public static final int TRANSPARENT = 0x0;
}
| epl-1.0 |
JoaoHenrique60/Projeto-loja | Projeto-loja/src/br/com/projetoloja/uicontroller/ControllerPagamentoParcela.java | 2282 | package br.com.projetoloja.uicontroller;
import br.com.projetoloja.cliente.Cliente;
import br.com.projetoloja.conta.Conta;
import br.com.projetoloja.fachada.Fachada;
import br.com.projetoloja.ui.StartApp;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javax.swing.*;
/**
* Created by João Henrique on 18/01/2016.
*/
public class ControllerPagamentoParcela {
@FXML
private Label codBanco;
@FXML
private Label nomeBanco;
@FXML
private Label parcelaBanco;
@FXML
private Label valorBanco;
public static Cliente clienteParcela = null;
@FXML
private void initialize(){
try {
if(clienteParcela != null) {
Conta conta = Fachada.getInstance().recuperarConta(clienteParcela.getConta().getId());
codBanco.setText(String.valueOf(clienteParcela.getId()));
nomeBanco.setText(clienteParcela.getNome());
parcelaBanco.setText(String.valueOf(conta.getParcelaAtual()));
valorBanco.setText("R$: " + clienteParcela.getConta().getValorParcela());
}
} catch (Exception e) {
e.printStackTrace();
}
}
@FXML
private void cancelar() throws Exception {
clienteParcela = null;
StartApp.getInstance().telaCliente(new Stage());
StartApp.stagePagamentoParcela.close();
}
@FXML
private void finalizar(){
try {
Fachada.getInstance().pagamento(clienteParcela.getConta().getId());
if(clienteParcela.getConta().getQuantidadeParcelas() > clienteParcela.getConta().getParcelaAtual()){
JOptionPane.showMessageDialog(null,"Parcela Paga com sucesso...");
initialize();
}else{
JOptionPane.showMessageDialog(null,"Fim de conta...");
clienteParcela = null;
StartApp.getInstance().telaCliente(new Stage());
StartApp.stagePagamentoParcela.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| epl-1.0 |
cchabanois/mesfavoris | bundles/mesfavoris.java/src/mesfavoris/java/editor/JavaEditorBookmarkPropertiesProvider.java | 4045 | package mesfavoris.java.editor;
import static mesfavoris.bookmarktype.BookmarkPropertiesProviderUtil.getSelection;
import static mesfavoris.bookmarktype.BookmarkPropertiesProviderUtil.getTextEditor;
import static mesfavoris.java.JavaBookmarkProperties.PROP_LINE_NUMBER_INSIDE_ELEMENT;
import static mesfavoris.texteditor.TextEditorBookmarkProperties.PROP_LINE_CONTENT;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.texteditor.ITextEditor;
import mesfavoris.java.element.JavaTypeMemberBookmarkPropertiesProvider;
import mesfavoris.texteditor.TextEditorUtils;
public class JavaEditorBookmarkPropertiesProvider extends JavaTypeMemberBookmarkPropertiesProvider {
@Override
public void addBookmarkProperties(Map<String, String> bookmarkProperties, IWorkbenchPart part, ISelection selection,
IProgressMonitor monitor) {
ITextEditor editor = getTextEditor(part);
if (editor == null) {
return;
}
if (editor != part) {
selection = getSelection(editor);
}
if (!(selection instanceof ITextSelection)) {
return;
}
ITextSelection textSelection = (ITextSelection) selection;
int lineNumber = textSelection.getStartLine();
int offset = getOffset(editor, textSelection);
IJavaElement editorJavaElement = JavaUI.getEditorInputJavaElement(editor.getEditorInput());
if (editorJavaElement == null) {
return;
}
IJavaElement containingJavaElement = getContainingJavaElement(editorJavaElement, offset);
if (!(containingJavaElement instanceof IMember)) {
return;
}
IMember member = (IMember) containingJavaElement;
super.addMemberBookmarkProperties(bookmarkProperties, member);
addLineNumberInsideMemberProperty(bookmarkProperties, member, lineNumber);
addJavadocComment(bookmarkProperties, member, lineNumber);
addLineContent(bookmarkProperties, editor, lineNumber);
}
private int getOffset(ITextEditor textEditor, ITextSelection textSelection) {
try {
int offset = TextEditorUtils.getOffsetOfFirstNonWhitespaceCharAtLine(textEditor, textSelection.getStartLine());
return offset > textSelection.getOffset() ? offset : textSelection.getOffset();
} catch (BadLocationException e) {
return textSelection.getOffset();
}
}
private void addLineNumberInsideMemberProperty(Map<String, String> bookmarkProperties, IMember member,
int lineNumber) {
try {
int methodLineNumber = JavaEditorUtils.getLineNumber(member);
int lineNumberInsideMethod = lineNumber - methodLineNumber;
putIfAbsent(bookmarkProperties, PROP_LINE_NUMBER_INSIDE_ELEMENT, Integer.toString(lineNumberInsideMethod));
} catch (JavaModelException e) {
return;
}
}
private void addJavadocComment(Map<String, String> bookmarkProperties, IMember member,
int lineNumber) {
try {
if (JavaEditorUtils.getLineNumber(member) != lineNumber) {
return;
}
super.addJavadocComment(bookmarkProperties, member);
} catch (JavaModelException e) {
return;
}
}
private IJavaElement getContainingJavaElement(IJavaElement editorJavaElement, int offset) {
if (!(editorJavaElement instanceof ITypeRoot)) {
return null;
}
ITypeRoot compilationUnit = (ITypeRoot) editorJavaElement;
try {
IJavaElement selectedJavaElement = compilationUnit.getElementAt(offset);
return selectedJavaElement;
} catch (JavaModelException e) {
return null;
}
}
private void addLineContent(Map<String, String> properties, ITextEditor textEditor, int lineNumber) {
putIfAbsent(properties, PROP_LINE_CONTENT, () -> {
String content = TextEditorUtils.getLineContent(textEditor, lineNumber);
return content == null ? null : content.trim();
});
}
}
| epl-1.0 |
aschmois/ForgeEssentialsMain | src/main/java/com/forgeessentials/commands/item/CommandKit.java | 8111 | package com.forgeessentials.commands.item;
import java.util.ArrayList;
import java.util.List;
import com.forgeessentials.util.events.FEModuleEvent.FEModuleServerPostInitEvent;
import com.forgeessentials.util.events.FEPlayerEvent.NoPlayerInfoEvent;
import com.forgeessentials.util.questioner.Questioner;
import com.forgeessentials.util.questioner.QuestionerCallback;
import com.forgeessentials.util.questioner.QuestionerStillActiveException;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.permissions.PermissionsManager;
import net.minecraftforge.permissions.PermissionsManager.RegisteredPermValue;
import com.forgeessentials.api.APIRegistry;
import com.forgeessentials.commands.util.CommandDataManager;
import com.forgeessentials.commands.util.FEcmdModuleCommands;
import com.forgeessentials.commands.util.Kit;
import com.forgeessentials.core.misc.FECommandManager.ConfigurableCommand;
import com.forgeessentials.core.misc.TranslatedCommandException;
import com.forgeessentials.core.misc.Translator;
import com.forgeessentials.util.FunctionHelper;
import com.forgeessentials.util.OutputHandler;
/**
* Kit command with cooldown. Should also put armor in armor slots.
*
* @author Dries007
*/
public class CommandKit extends FEcmdModuleCommands implements ConfigurableCommand
{
public static final String PERM = COMMANDS_PERM + ".kit";
public static final String PERM_ADMIN = COMMANDS_PERM + ".admin";
public static final String PERM_BYPASS_COOLDOWN = PERM + ".bypasscooldown";
public static final String[] tabCompletionArg2 = new String[] { "set", "del" };
protected String kitForNewPlayers;
public CommandKit()
{
APIRegistry.getFEEventBus().register(this);
}
@Override
public String getCommandName()
{
return "kit";
}
@Override
public void processCommandPlayer(EntityPlayerMP sender, String[] args)
{
/*
* Print kits
*/
if (args.length == 0)
{
OutputHandler.chatNotification(sender, "Available kits:");
String msg = "";
for (Kit kit : CommandDataManager.kits.values())
{
if (PermissionsManager.checkPermission(sender, getPermissionNode() + "." + kit.getName()))
{
msg = kit.getName() + ", " + msg;
}
}
OutputHandler.chatNotification(sender, msg);
return;
}
/*
* Give kit
*/
if (args.length == 1)
{
if (!CommandDataManager.kits.containsKey(args[0].toLowerCase()))
throw new TranslatedCommandException("Kit %s does not exist.", args[0]);
if (!PermissionsManager.checkPermission(sender, getPermissionNode() + "." + args[0].toLowerCase()))
throw new TranslatedCommandException(
"You have insufficient permissions to do that. If you believe you received this message in error, please talk to a server admin.");
CommandDataManager.kits.get(args[0].toLowerCase()).giveKit(sender);
return;
}
/*
* Make kit
*/
if (args.length >= 2 && args[1].equalsIgnoreCase("set") && PermissionsManager.checkPermission(sender, getPermissionNode() + ".admin"))
{
if (!CommandDataManager.kits.containsKey(args[0].toLowerCase()))
{
int cooldown = -1;
if (args.length == 3)
{
cooldown = parseIntWithMin(sender, args[2], -1);
}
new Kit(sender, args[0].toLowerCase(), cooldown);
OutputHandler.chatConfirmation(sender,
Translator.format("Kit created successfully. %s cooldown.", FunctionHelper.formatDateTimeReadable(cooldown, true)));
}
else
{
try
{
Questioner.add(sender, Translator.format("Kit %s already exists. overwrite?", args[0].toLowerCase()), new HandleKitOverrides(sender, args));
}
catch (QuestionerStillActiveException e)
{
throw new QuestionerStillActiveException.CommandException();
}
}
return;
}
/*
* Delete kit
*/
if (args.length == 2 && args[1].equalsIgnoreCase("del") && PermissionsManager.checkPermission(sender, getPermissionNode() + ".admin"))
{
if (args.length == 2)
{
if (!CommandDataManager.kits.containsKey(args[0].toLowerCase()))
throw new TranslatedCommandException("Kit %s does not exist.", args[0]);
CommandDataManager.removeKit(CommandDataManager.kits.get(args[0].toLowerCase()));
OutputHandler.chatConfirmation(sender, "Kit removed.");
}
}
/*
* You're doing it wrong!
*/
throw new TranslatedCommandException(getCommandUsage(sender));
}
@Override
public boolean canConsoleUseCommand()
{
return false;
}
@Override
public void registerExtraPermissions()
{
APIRegistry.perms.registerPermission(PERM_ADMIN, RegisteredPermValue.OP);
APIRegistry.perms.registerPermission(PERM_BYPASS_COOLDOWN, RegisteredPermValue.OP);
}
@Override
public List<String> addTabCompletionOptions(ICommandSender sender, String[] args)
{
if (args.length == 0)
{
List<String> kits = new ArrayList<String>();
for (Kit kit : CommandDataManager.kits.values())
kits.add(kit.getName());
return getListOfStringsMatchingLastWord(args, kits);
}
else if (args.length == 1)
return getListOfStringsMatchingLastWord(args, tabCompletionArg2);
return null;
}
@Override
public RegisteredPermValue getDefaultPermission()
{
return RegisteredPermValue.TRUE;
}
@Override
public String getCommandUsage(ICommandSender sender)
{
return "/kit [name] OR [name] [set|del] <cooldown> Allows you to receive free kits which are pre-defined by the server owner.";
}
@Override
public void loadConfig(Configuration config, String category)
{
kitForNewPlayers = config.get(category, "kitForNewPlayers", "", "Name of kit to issue to new players. If this is left blank, it will be ignored.")
.getString();
}
@SubscribeEvent
public void checkKitExistence(FEModuleServerPostInitEvent e)
{
if (!CommandDataManager.kits.containsKey(kitForNewPlayers))
kitForNewPlayers = null;
}
@SubscribeEvent
public void issueWelcomeKit(NoPlayerInfoEvent e)
{
Kit kit = CommandDataManager.kits.get(kitForNewPlayers);
if (kit != null)
{
kit.giveKit(e.entityPlayer);
}
}
static class HandleKitOverrides implements QuestionerCallback
{
private String[] args;
private EntityPlayerMP sender;
private HandleKitOverrides(EntityPlayerMP sender, String[] args)
{
this.args = args;
this.sender = sender;
}
@Override
public void respond(Boolean response)
{
if (response != null && response == true)
{
int cooldown = -1;
if (args.length == 3)
{
cooldown = parseIntWithMin(sender, args[2], -1);
}
new Kit(sender, args[0].toLowerCase(), cooldown);
OutputHandler.chatConfirmation(sender,
Translator.format("Kit created successfully. %s cooldown.", FunctionHelper.formatDateTimeReadable(cooldown, true)));
}
}
}
}
| epl-1.0 |
RodriguesJ/Atem | src/com/runescape/server/revised/content/dialogue/impl/HansDialogue.java | 12043 | /**
* Eclipse Public License - v 1.0
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION
* OF THE
* PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* 1. DEFINITIONS
*
* "Contribution" means:
*
* a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
* b) in the case of each subsequent Contributor:
* i) changes to the Program, and
* ii) additions to the Program;
* where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution
* 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf.
* Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program
* under their own license agreement, and (ii) are not derivative works of the Program.
* "Contributor" means any person or entity that distributes the Program.
*
* "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone
* or when combined with the Program.
*
* "Program" means the Contributions distributed in accordance with this Agreement.
*
* "Recipient" means anyone who receives the Program under this Agreement, including all Contributors.
*
* 2. GRANT OF RIGHTS
*
* a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license
* to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor,
* if any, and such derivative works, in source code and object code form.
* b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license
* under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source
* code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the
* Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The
* patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
* c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided
* by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor
* disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise.
* As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other
* intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the
* Program, it is Recipient's responsibility to acquire that license before distributing the Program.
* d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright
* license set forth in this Agreement.
* 3. REQUIREMENTS
*
* A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
*
* a) it complies with the terms and conditions of this Agreement; and
* b) its license agreement:
* i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions
* of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
* ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and
* consequential damages, such as lost profits;
* iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
* iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner
* on or through a medium customarily used for software exchange.
* When the Program is made available in source code form:
*
* a) it must be made available under this Agreement; and
* b) a copy of this Agreement must be included with each copy of the Program.
* Contributors may not remove or alter any copyright notices contained within the Program.
*
* Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients
* to identify the originator of the Contribution.
*
* 4. COMMERCIAL DISTRIBUTION
*
* Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this
* license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering
* should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in
* a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor
* ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions
* brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in
* connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or
* Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly
* notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the
* Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim
* at its own expense.
*
* For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial
* Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims
* and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend
* claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay
* any damages as a result, the Commercial Contributor must pay those damages.
*
* 5. NO WARRANTY
*
* EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS
* FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and
* assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program
* errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
*
* 6. DISCLAIMER OF LIABILITY
*
* EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION
* OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* 7. GENERAL
*
* If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the
* remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum
* extent necessary to make such provision valid and enforceable.
*
* If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program
* itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's
* rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
*
* All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this
* Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights
* under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However,
* Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
*
* Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may
* only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this
* Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the
* initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate
* entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be
* distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is
* published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in
* Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement,
* whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
*
* This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to
* this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights
* to a jury trial in any resulting litigation.
*/
package com.runescape.server.revised.content.dialogue.impl;
import com.runescape.server.revised.content.dialogue.AbstractDialogue;
import com.runescape.server.revised.content.dialogue.DialogueEvent;
import com.runescape.server.revised.content.dialogue.DialogueType;
public class HansDialogue extends AbstractDialogue<DialogueType> {
@Override
public DialogueEvent executeDialogueEvent() {
return null;
}
}
| epl-1.0 |
kawasima/enkan | kotowari/src/test/java/kotowari/test/form/BadForm.java | 54 | package kotowari.test.form;
public class BadForm {
}
| epl-1.0 |
comutt/yukinoshita2 | src/org/unitarou/yukinoshita/model/cmd/CommandFactory.java | 2978 | /*
* Copyright 2004-2009 unitarou <boss@unitarou.org>.
* All rights reserved.
*
* This program and the accompanying materials are made available under the terms of
* the Common Public License v1.0 which accompanies this distribution,
* and is available at http://opensource.org/licenses/cpl.php
*
* Contributors:
* unitarou - initial API and implementation
*/
package org.unitarou.yukinoshita.model.cmd;
import org.unitarou.lang.ArgumentChecker;
import org.unitarou.lang.Strings;
import org.unitarou.sgf.CardinalityType;
import org.unitarou.sgf.Property;
import org.unitarou.sgf.SgfId;
import org.unitarou.yukinoshita.model.NodeView;
/**
* @author unitarou <boss@unitarou.org>
*/
public class CommandFactory {
/**
* {@link UpdateProperty}ð쬵ÄԵܷB<br>
* ±±ÅnewDatumªóÌêÍnodeView©çsgfTypeðí·éR}hÉÈèÜ·B<br>
* ܽnodeViewÌlÆnewDatumÉ·ª³¢êÍnullðԵܷB
*
* @param newDatum {@link Property#Property(SgfId, String)}ɼÚn³êé¶ñAó¶ÌêÍíðÓ¡µÜ·B
* <b>GXP[vÍÖ~Å·B</b>
* @param sgfId XVÎÛÆÈévpeBÌ^
* @param nodeView
* @param bindSameType trueÉÝè·éÆ{@link SgfId#propertyType()}ðÂNodeÜÅkÁÄA
* (øÌnodeViewÅÍÈ)»Ìm[hðXVµÜ·B
* @return 쬳ê½vpeBBNOT NULL
* @throws org.unitarou.lang.NullArgumentException øª<code>null</code>ÌêB
* @throws IllegalArgumentException sgfType ª{@link CardinalityType#SINGLE}ÈOÌlðÂB
*/
static public UpdateProperty createUpdateProperty(
String newDatum, SgfId sgfId, NodeView nodeView, boolean bindSameType)
{
ArgumentChecker.throwIfNull(newDatum, sgfId, nodeView);
if (!sgfId.cardinalityType().equals(CardinalityType.SINGLE)) {
throw new IllegalArgumentException("Bad carinality, property must be single: " + sgfId); //$NON-NLS-1$
}
Property property = bindSameType
? nodeView.findProperty(sgfId)
: nodeView.getProperty(sgfId);
String lastDatum = Strings.EMPTY;
if (property != null) {
lastDatum = property.getString();
}
if (newDatum.equals(lastDatum)) {
return null;
}
if (newDatum.equals(Strings.EMPTY)) { // í
// øÅGameInfoª éã¬ÌNodeÉXV·éæ¤Éwè
property = new Property(sgfId, lastDatum);
return new UpdateProperty(
(bindSameType) ? sgfId.propertyType() : null,
null,
property);
}
// øÅGameInfoª éã¬ÌNodeÉXV·éæ¤Éwè
property = new Property(sgfId, newDatum);
return new UpdateProperty(
(bindSameType) ? sgfId.propertyType() : null,
property);
}
/**
*
*/
protected CommandFactory() {
super();
}
}
| epl-1.0 |
sehrgut/minecraft-smp-mocreatures | moCreatures/client/core/sources/net/minecraft/src/Container.java | 11548 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode
package net.minecraft.src;
import java.util.*;
// Referenced classes of package net.minecraft.src:
// Slot, ItemStack, ICrafting, EntityPlayer,
// InventoryPlayer, IInventory
public abstract class Container
{
public Container()
{
field_20123_d = new ArrayList();
slots = new ArrayList();
windowId = 0;
field_20917_a = 0;
field_20121_g = new ArrayList();
field_20918_b = new HashSet();
}
protected void addSlot(Slot slot)
{
slot.slotNumber = slots.size();
slots.add(slot);
field_20123_d.add(null);
}
public void updateCraftingResults()
{
for(int i = 0; i < slots.size(); i++)
{
ItemStack itemstack = ((Slot)slots.get(i)).getStack();
ItemStack itemstack1 = (ItemStack)field_20123_d.get(i);
if(ItemStack.areItemStacksEqual(itemstack1, itemstack))
{
continue;
}
itemstack1 = itemstack != null ? itemstack.copy() : null;
field_20123_d.set(i, itemstack1);
for(int j = 0; j < field_20121_g.size(); j++)
{
((ICrafting)field_20121_g.get(j)).func_20159_a(this, i, itemstack1);
}
}
}
public Slot getSlot(int i)
{
return (Slot)slots.get(i);
}
public ItemStack getStackInSlot(int i)
{
Slot slot = (Slot)slots.get(i);
if(slot != null)
{
return slot.getStack();
} else
{
return null;
}
}
public ItemStack func_27280_a(int i, int j, boolean flag, EntityPlayer entityplayer)
{
ItemStack itemstack = null;
if(j == 0 || j == 1)
{
InventoryPlayer inventoryplayer = entityplayer.inventory;
if(i == -999)
{
if(inventoryplayer.getItemStack() != null && i == -999)
{
if(j == 0)
{
entityplayer.dropPlayerItem(inventoryplayer.getItemStack());
inventoryplayer.setItemStack(null);
}
if(j == 1)
{
entityplayer.dropPlayerItem(inventoryplayer.getItemStack().splitStack(1));
if(inventoryplayer.getItemStack().stackSize == 0)
{
inventoryplayer.setItemStack(null);
}
}
}
} else
if(flag)
{
ItemStack itemstack1 = getStackInSlot(i);
if(itemstack1 != null)
{
int k = itemstack1.stackSize;
itemstack = itemstack1.copy();
Slot slot1 = (Slot)slots.get(i);
if(slot1 != null && slot1.getStack() != null)
{
int l = slot1.getStack().stackSize;
if(l < k)
{
func_27280_a(i, j, flag, entityplayer);
}
}
}
} else
{
Slot slot = (Slot)slots.get(i);
if(slot != null)
{
slot.onSlotChanged();
ItemStack itemstack2 = slot.getStack();
ItemStack itemstack3 = inventoryplayer.getItemStack();
if(itemstack2 != null)
{
itemstack = itemstack2.copy();
}
if(itemstack2 == null)
{
if(itemstack3 != null && slot.isItemValid(itemstack3))
{
int i1 = j != 0 ? 1 : itemstack3.stackSize;
if(i1 > slot.getSlotStackLimit())
{
i1 = slot.getSlotStackLimit();
}
slot.putStack(itemstack3.splitStack(i1));
if(itemstack3.stackSize == 0)
{
inventoryplayer.setItemStack(null);
}
}
} else
if(itemstack3 == null)
{
int j1 = j != 0 ? (itemstack2.stackSize + 1) / 2 : itemstack2.stackSize;
ItemStack itemstack5 = slot.decrStackSize(j1);
inventoryplayer.setItemStack(itemstack5);
if(itemstack2.stackSize == 0)
{
slot.putStack(null);
}
slot.onPickupFromSlot(inventoryplayer.getItemStack());
} else
if(slot.isItemValid(itemstack3))
{
if(itemstack2.itemID != itemstack3.itemID || itemstack2.getHasSubtypes() && itemstack2.getItemDamage() != itemstack3.getItemDamage())
{
if(itemstack3.stackSize <= slot.getSlotStackLimit())
{
ItemStack itemstack4 = itemstack2;
slot.putStack(itemstack3);
inventoryplayer.setItemStack(itemstack4);
}
} else
{
int k1 = j != 0 ? 1 : itemstack3.stackSize;
if(k1 > slot.getSlotStackLimit() - itemstack2.stackSize)
{
k1 = slot.getSlotStackLimit() - itemstack2.stackSize;
}
if(k1 > itemstack3.getMaxStackSize() - itemstack2.stackSize)
{
k1 = itemstack3.getMaxStackSize() - itemstack2.stackSize;
}
itemstack3.splitStack(k1);
if(itemstack3.stackSize == 0)
{
inventoryplayer.setItemStack(null);
}
itemstack2.stackSize += k1;
}
} else
if(itemstack2.itemID == itemstack3.itemID && itemstack3.getMaxStackSize() > 1 && (!itemstack2.getHasSubtypes() || itemstack2.getItemDamage() == itemstack3.getItemDamage()))
{
int l1 = itemstack2.stackSize;
if(l1 > 0 && l1 + itemstack3.stackSize <= itemstack3.getMaxStackSize())
{
itemstack3.stackSize += l1;
itemstack2.splitStack(l1);
if(itemstack2.stackSize == 0)
{
slot.putStack(null);
}
slot.onPickupFromSlot(inventoryplayer.getItemStack());
}
}
}
}
}
return itemstack;
}
public void onCraftGuiClosed(EntityPlayer entityplayer)
{
InventoryPlayer inventoryplayer = entityplayer.inventory;
if(inventoryplayer.getItemStack() != null)
{
entityplayer.dropPlayerItem(inventoryplayer.getItemStack());
inventoryplayer.setItemStack(null);
}
}
public void onCraftMatrixChanged(IInventory iinventory)
{
updateCraftingResults();
}
public void putStackInSlot(int i, ItemStack itemstack)
{
getSlot(i).putStack(itemstack);
}
public void putStacksInSlots(ItemStack aitemstack[])
{
for(int i = 0; i < aitemstack.length; i++)
{
getSlot(i).putStack(aitemstack[i]);
}
}
public void func_20112_a(int i, int j)
{
}
public short func_20111_a(InventoryPlayer inventoryplayer)
{
field_20917_a++;
return field_20917_a;
}
public void func_20113_a(short word0)
{
}
public void func_20110_b(short word0)
{
}
public abstract boolean isUsableByPlayer(EntityPlayer entityplayer);
protected void func_28125_a(ItemStack itemstack, int i, int j, boolean flag)
{
int k = i;
if(flag)
{
k = j - 1;
}
if(itemstack.isStackable())
{
while(itemstack.stackSize > 0 && (!flag && k < j || flag && k >= i))
{
Slot slot = (Slot)slots.get(k);
ItemStack itemstack1 = slot.getStack();
if(itemstack1 != null && itemstack1.itemID == itemstack.itemID && (!itemstack.getHasSubtypes() || itemstack.getItemDamage() == itemstack1.getItemDamage()))
{
int i1 = itemstack1.stackSize + itemstack.stackSize;
if(i1 <= itemstack.getMaxStackSize())
{
itemstack.stackSize = 0;
itemstack1.stackSize = i1;
slot.onSlotChanged();
} else
if(itemstack1.stackSize < itemstack.getMaxStackSize())
{
itemstack.stackSize -= itemstack.getMaxStackSize() - itemstack1.stackSize;
itemstack1.stackSize = itemstack.getMaxStackSize();
slot.onSlotChanged();
}
}
if(flag)
{
k--;
} else
{
k++;
}
}
}
if(itemstack.stackSize > 0)
{
int l;
if(flag)
{
l = j - 1;
} else
{
l = i;
}
do
{
if((flag || l >= j) && (!flag || l < i))
{
break;
}
Slot slot1 = (Slot)slots.get(l);
ItemStack itemstack2 = slot1.getStack();
if(itemstack2 == null)
{
slot1.putStack(itemstack.copy());
slot1.onSlotChanged();
itemstack.stackSize = 0;
break;
}
if(flag)
{
l--;
} else
{
l++;
}
} while(true);
}
}
public List field_20123_d;
public List slots;
public int windowId;
private short field_20917_a;
protected List field_20121_g;
private Set field_20918_b;
}
| epl-1.0 |
kevinmcgoldrick/Tank | web/web_support/src/test/java/com/intuit/tank/project/DataFileBrowserTest.java | 24714 | package com.intuit.tank.project;
/*
* #%L
* JSF Support Beans
* %%
* Copyright (C) 2011 - 2015 Intuit Inc.
* %%
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* #L%
*/
import java.util.List;
import javax.faces.model.SelectItem;
import org.junit.*;
import static org.junit.Assert.*;
import com.intuit.tank.ModifiedDatafileMessage;
import com.intuit.tank.project.DataFile;
import com.intuit.tank.project.DataFileBrowser;
import com.intuit.tank.view.filter.ViewFilterType;
import com.intuit.tank.wrapper.SelectableWrapper;
/**
* The class <code>DataFileBrowserTest</code> contains tests for the class <code>{@link DataFileBrowser}</code>.
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
public class DataFileBrowserTest {
/**
* Run the DataFileBrowser() constructor test.
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testDataFileBrowser_1()
throws Exception {
DataFileBrowser result = new DataFileBrowser();
assertNotNull(result);
}
/**
* Run the boolean enablePrev() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testEnablePrev_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
boolean result = fixture.enablePrev();
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
assertTrue(result);
}
/**
* Run the boolean enablePrev() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testEnablePrev_2()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(0);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
boolean result = fixture.enablePrev();
assertTrue(!result);
}
/**
* Run the SelectItem[] getCreatorList() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testGetCreatorList_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
SelectItem[] result = fixture.getCreatorList();
}
/**
* Run the int getCurrentPage() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testGetCurrentPage_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
int result = fixture.getCurrentPage();
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
assertEquals(1, result);
}
/**
* Run the String getDataFileDownloadLink(DataFile) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testGetDataFileDownloadLink_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
DataFile dataFile = new DataFile();
String result = fixture.getDataFileDownloadLink(dataFile);
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
assertNotNull(result);
}
/**
* Run the String getDataFileDownloadLink(DataFile) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testGetDataFileDownloadLink_2()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
DataFile dataFile = null;
String result = fixture.getDataFileDownloadLink(dataFile);
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
assertNotNull(result);
}
/**
* Run the List<DataFile> getEntityList(ViewFilterType) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testGetEntityList_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
ViewFilterType viewFilter = ViewFilterType.ALL;
List<DataFile> result = fixture.getEntityList(viewFilter);
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
assertNotNull(result);
}
/**
* Run the List<DataFile> getEntityList(ViewFilterType) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testGetEntityList_2()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
ViewFilterType viewFilter = ViewFilterType.ALL;
List<DataFile> result = fixture.getEntityList(viewFilter);
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
assertNotNull(result);
}
/**
* Run the int getInputPage() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testGetInputPage_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper(new DataFile()));
int result = fixture.getInputPage();
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
assertEquals(1, result);
}
/**
* Run the int getNumEntriesToShow() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testGetNumEntriesToShow_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper(new DataFile()));
int result = fixture.getNumEntriesToShow();
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
assertEquals(1, result);
}
/**
* Run the SelectableWrapper<DataFile> getSelectedFile() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testGetSelectedFile_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
SelectableWrapper<DataFile> result = fixture.getSelectedFile();
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
assertNotNull(result);
}
/**
* Run the DataFile getViewDatafile() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testGetViewDatafile_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
DataFile result = fixture.getViewDatafile();
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
assertNotNull(result);
}
/**
* Run the void goToFirstPage() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testGoToFirstPage_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
fixture.goToFirstPage();
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
}
/**
* Run the boolean isCurrent() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testIsCurrent_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
boolean result = fixture.isCurrent();
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
assertTrue(result);
}
/**
* Run the boolean isCurrent() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testIsCurrent_2()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
boolean result = fixture.isCurrent();
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
assertTrue(result);
}
/**
* Run the void nextSetOfEntries() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testNextSetOfEntries_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
fixture.nextSetOfEntries();
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
}
/**
* Run the void prevSetOfEntries() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testPrevSetOfEntries_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
fixture.prevSetOfEntries();
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
}
/**
* Run the void setCurrentPage(int) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testSetCurrentPage_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
int currentPage = 1;
fixture.setCurrentPage(currentPage);
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
}
/**
* Run the void setInputPage(int) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testSetInputPage_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
int inputPage = 1;
fixture.setInputPage(inputPage);
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
}
/**
* Run the void setNumEntriesToShow(int) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testSetNumEntriesToShow_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
int numEntriesToShow = 1;
fixture.setNumEntriesToShow(numEntriesToShow);
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
}
/**
* Run the void setSelectedFile(SelectableWrapper<DataFile>) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testSetSelectedFile_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
SelectableWrapper<DataFile> selectedFile = new SelectableWrapper((Object) null);
fixture.setSelectedFile(selectedFile);
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
}
/**
* Run the void setViewDatafile(DataFile) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testSetViewDatafile_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
DataFile viewDatafile = new DataFile();
fixture.setViewDatafile(viewDatafile);
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
}
/**
* Run the void setViewDatafileId(int) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 12/15/14 3:54 PM
*/
@Test
public void testSetViewDatafileId_1()
throws Exception {
DataFileBrowser fixture = new DataFileBrowser();
fixture.setInputPage(1);
fixture.setNumEntriesToShow(1);
fixture.setViewDatafile(new DataFile());
fixture.setCurrentPage(1);
fixture.setSelectedFile(new SelectableWrapper((Object) null));
int viewDatafileId = 1;
fixture.setViewDatafileId(viewDatafileId);
// An unexpected exception was thrown in user code while executing this test:
// java.lang.NoClassDefFoundError: com_cenqua_clover/CoverageRecorder
// at com.intuit.tank.util.SelectionTracker.<init>(SelectionTracker.java:32)
// at com.intuit.tank.wrapper.SelectableBean.<init>(SelectableBean.java:32)
// at com.intuit.tank.project.DataFileBrowser.<init>(DataFileBrowser.java:43)
}
} | epl-1.0 |
RichardBirenheide/brainfuck | org.birenheide.bf.debug/src/org/birenheide/bf/debug/core/BfMemoryBlock.java | 2404 | package org.birenheide.bf.debug.core;
import org.birenheide.bf.InterpreterState;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.model.IMemoryBlock;
public class BfMemoryBlock extends BfDebugElement implements IMemoryBlock {
private final InterpreterState state;
private final long start;
private final long length;
private boolean createdbyUser = true;
BfMemoryBlock(BfDebugTarget parent, InterpreterState state, long start, long length) {
super(parent);
this.state = state;
long st = start;
long l = length;
if (st >= state.getDataSize()) {
st = state.getDataSize();
l = 0;
}
else if (st + l > state.getDataSize()) {
l = state.getDataSize() - st;
}
this.start = st;
this.length = l;
}
public boolean isUserCreated() {
return this.createdbyUser;
}
public void setUserCreated(boolean isUserCreated) {
this.createdbyUser = isUserCreated;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.createdbyUser ? 1231 : 1237);
result = prime * result + (int) (this.length ^ (this.length >>> 32));
result = prime * result + (int) (this.start ^ (this.start >>> 32));
result = prime * result + this.getDebugTarget().hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
BfMemoryBlock other = (BfMemoryBlock) obj;
if (!this.getDebugTarget().equals(other.getDebugTarget())) {
return false;
}
if (this.createdbyUser != other.createdbyUser) {
return false;
}
if (this.length != other.length) {
return false;
}
if (this.start != other.start) {
return false;
}
return true;
}
@Override
public long getStartAddress() {
return this.start;
}
public int getMemoryPointer() {
return this.getDebugTarget().getProcess().getProcessListener().getSuspendedState().dataPointer();
}
@Override
public long getLength() {
return this.length;
}
@Override
public byte[] getBytes() throws DebugException {
return this.state.dataSnapShot((int) this.start, (int) (this.start + this.length));
}
@Override
public boolean supportsValueModification() {
return false;
}
@Override
public void setValue(long offset, byte[] bytes) throws DebugException {
}
} | epl-1.0 |
fenecon/fenecon-openhab | addons/binding/org.openhab.binding.fems/src/main/java/org/openhab/binding/fems/internal/types/IODigitalInput.java | 1021 | /**
* Copyright (c) 2015 FENECON GmbH & Co. KG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.fems.internal.types;
import org.bulldog.core.gpio.DigitalInput;
import org.eclipse.smarthome.core.library.types.OpenClosedType;
import org.eclipse.smarthome.core.types.State;
/**
*
* @author Stefan Feilmeier
*/
public class IODigitalInput implements IO {
private DigitalInput pin;
public IODigitalInput(DigitalInput pin) {
this.pin = pin;
pin.setTeardownOnShutdown(true);
}
@Override
public State getState() {
if (pin.read().getBooleanValue()) {
return OpenClosedType.OPEN;
} else {
return OpenClosedType.CLOSED;
}
}
@Override
public void dispose() {
// nothing to do here
}
}
| epl-1.0 |
debabratahazra/DS | designstudio/components/page/ui/com.odcgroup.page.ui/src/main/java/com/odcgroup/page/ui/edit/ScrollableWidgetEditPart.java | 3822 | package com.odcgroup.page.ui.edit;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.DragTracker;
import org.eclipse.gef.Request;
import org.eclipse.gef.requests.SelectionRequest;
import com.odcgroup.page.ui.figure.scroll.ScrollableWidgetFigure;
import com.odcgroup.page.ui.figure.scroll.XScrollBar;
import com.odcgroup.page.ui.figure.scroll.XScrollBarDragTracker;
import com.odcgroup.page.ui.figure.scroll.YScrollBar;
import com.odcgroup.page.ui.figure.scroll.YScrollBarDragTracker;
/**
* An EditPart for Widgets which are not the root element of the diagram and contain ScrollBars.
* Note that we assume that the different containers use local coordinates.
*
* @author Gary Hayes
*/
public class ScrollableWidgetEditPart extends WidgetEditPart {
/**
* Overrides the base-class version to determine if we are selecting the Figure or the ScrollBar associated with it.
*
* @param request
* The request
* @return DragTracker The DragTracker
*/
public DragTracker getDragTracker(Request request) {
SelectionRequest sr = (SelectionRequest) request;
Point mp = sr.getLocation();
ScrollableWidgetFigure swf = (ScrollableWidgetFigure) getFigure();
if (hasClickedXThumb(swf, mp)) {
return new XScrollBarDragTracker(swf);
}
if (hasClickedYThumb(swf, mp)) {
return new YScrollBarDragTracker(swf);
}
return super.getDragTracker(request);
}
/**
* Returns true if the mouse was clicked over the X-ScrollBar's thumb.
*
* @param scrollableFigure The ScrollableWidgetFigure
* @param p The Point to test
* @return boolean True if the mouse was clicked over the X-ScrollBar's thumb
*/
private boolean hasClickedXThumb(ScrollableWidgetFigure scrollableFigure, Point p) {
XScrollBar xsb = scrollableFigure.getXScrollBar();
if (xsb == null) {
// No ScrollBar. The result is obviously false
return false;
}
return contains(scrollableFigure, xsb.getThumb().getBounds(), p);
}
/**
* Returns true if the mouse was clicked over the Y-ScrollBar's thumb.
*
* @param scrollableFigure The ScrollableWidgetFigure
* @param p The Point to test
* @return boolean True if the mouse was clicked over the Y-ScrollBar's thumb
*/
private boolean hasClickedYThumb(ScrollableWidgetFigure scrollableFigure, Point p) {
YScrollBar ysb = scrollableFigure.getYScrollBar();
if (ysb == null) {
// No ScrollBar. The result is obviously false
return false;
}
return contains(scrollableFigure, ysb.getThumb().getBounds(), p);
}
/**
* Returns true if the Rectanglwe contains the Point. This test
* is relative to the figure passed as an argument. The Rectangle
* is displaced relative to the absolute position of the Figure
* before performing the test.
*
* @param scrollableFigure The figure
* @param r The Rectangle
* @param p The Point to test
* @return boolean True if the Rectangle contains the Point
*/
private boolean contains(ScrollableWidgetFigure scrollableFigure, Rectangle r, Point p) {
Rectangle sb = r.getCopy();
Point sp = translatePointToAbsolute(scrollableFigure);
sb.x = sb.x + sp.x;
sb.y = sb.y + sp.y;
if (sb.contains(p)) {
return true;
}
return false;
}
/**
* Translates the point to absolute coordinates.
* Note that we assume that each container is using
* local coordinates.
*
* @param figure The figure containing the Point
* @return Point The translated Point
*/
private Point translatePointToAbsolute(IFigure figure) {
int x = 0;
int y = 0;
IFigure f = figure;
while (f.getParent() != null) {
Rectangle fb = f.getBounds();
x = x + fb.x;
y = y + fb.y;
f = f.getParent();
}
return new Point(x, y);
}
} | epl-1.0 |
ttimbul/eclipse.wst | bundles/org.eclipse.wst.html.core/src/org/eclipse/wst/html/core/internal/contentmodel/chtml/HedIMG.java | 2893 | /*******************************************************************************
* Copyright (c) 2004, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.html.core.internal.contentmodel.chtml;
import java.util.Arrays;
import org.eclipse.wst.xml.core.internal.contentmodel.CMAttributeDeclaration;
import org.eclipse.wst.xml.core.internal.contentmodel.CMDataType;
import org.eclipse.wst.xml.core.internal.contentmodel.CMNamedNodeMap;
/**
* IMG.
*/
final class HedIMG extends HedEmpty {
/**
*/
public HedIMG(ElementCollection collection) {
super(CHTMLNamespace.ElementName.IMG, collection);
layoutType = LAYOUT_OBJECT;
}
/**
* IMG.
* %attrs;
* (src %URI; #REQUIRED): should be defined locally.
* (alt %Text; #REQUIRED)
* (longdesc %URI; #IMPLIED)
* (name CDATA #IMPLIED)
* (height %Length; #IMPLIED)
* (width %Length; #IMPLIED)
* (usemap %URI; #IMPLIED)
* (ismap (ismap) #IMPLIED)
* (align %IAlign; #IMPLIED): should be defined locally.
* (border %Pixels; #IMPLIED)
* (hspace %Pixels; #IMPLIED)
* (vspace %Pixels; #IMPLIED)
* (mapfile %URI; #IMPLIED)
*/
protected void createAttributeDeclarations() {
if (attributes != null)
return; // already created.
if (attributeCollection == null)
return; // fatal
attributes = new CMNamedNodeMapImpl();
// %attrs;
attributeCollection.getAttrs(attributes);
// (src %URI; #REQUIRED): should be defined locally.
HTMLCMDataTypeImpl atype = null;
HTMLAttrDeclImpl attr = null;
atype = new HTMLCMDataTypeImpl(CMDataType.URI);
attr = new HTMLAttrDeclImpl(CHTMLNamespace.ATTR_NAME_SRC, atype, CMAttributeDeclaration.REQUIRED);
attributes.putNamedItem(CHTMLNamespace.ATTR_NAME_SRC, attr);
String[] names = {CHTMLNamespace.ATTR_NAME_ALT, CHTMLNamespace.ATTR_NAME_NAME, CHTMLNamespace.ATTR_NAME_HEIGHT, CHTMLNamespace.ATTR_NAME_WIDTH, CHTMLNamespace.ATTR_NAME_BORDER, CHTMLNamespace.ATTR_NAME_HSPACE, CHTMLNamespace.ATTR_NAME_VSPACE,};
attributeCollection.getDeclarations(attributes, Arrays.asList(names).iterator());
// align (local); should be defined locally.
attr = AttributeCollection.createAlignForImage();
attributes.putNamedItem(CHTMLNamespace.ATTR_NAME_ALIGN, attr);
}
/**
*/
public CMNamedNodeMap getProhibitedAncestors() {
if (prohibitedAncestors != null)
return prohibitedAncestors;
String[] names = {CHTMLNamespace.ElementName.PRE};
prohibitedAncestors = elementCollection.getDeclarations(names);
return prohibitedAncestors;
}
}
| epl-1.0 |
dkincaid/clumcl | src/generated/java/gov/nih/nlm/uts/webservice/metadata/GetAllSourceRelationLabels.java | 2008 |
package gov.nih.nlm.uts.webservice.metadata;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for getAllSourceRelationLabels complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="getAllSourceRelationLabels">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ticket" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="version" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getAllSourceRelationLabels", propOrder = {
"ticket",
"version"
})
public class GetAllSourceRelationLabels {
protected String ticket;
protected String version;
/**
* Gets the value of the ticket property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTicket() {
return ticket;
}
/**
* Sets the value of the ticket property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTicket(String value) {
this.ticket = value;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
return version;
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersion(String value) {
this.version = value;
}
}
| epl-1.0 |
ttimbul/eclipse.wst | bundles/org.eclipse.wst.xsd.ui/src-refactor/org/eclipse/wst/xsd/ui/internal/refactor/IReferenceUpdating.java | 1426 | /*******************************************************************************
* Copyright (c) 2005, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*
*******************************************************************************/
package org.eclipse.wst.xsd.ui.internal.refactor;
public interface IReferenceUpdating {
/**
* Checks if this refactoring object is capable of updating references to the renamed element.
*/
public boolean canEnableUpdateReferences();
/**
* If <code>canUpdateReferences</code> returns <code>true</code>, then this method is used to
* inform the refactoring object whether references should be updated.
* This call can be ignored if <code>canUpdateReferences</code> returns <code>false</code>.
*/
public void setUpdateReferences(boolean update);
/**
* If <code>canUpdateReferences</code> returns <code>true</code>, then this method is used to
* ask the refactoring object whether references should be updated.
* This call can be ignored if <code>canUpdateReferences</code> returns <code>false</code>.
*/
public boolean getUpdateReferences();
} | epl-1.0 |
NABUCCO/org.nabucco.framework.generator | org.nabucco.framework.generator.compiler/src/main/org/nabucco/framework/generator/compiler/transformation/java/view/NabuccoToJavaRcpViewVisitorSupportUtil.java | 9473 | /*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), Version 1.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.opensource.org/licenses/eclipse-1.0.php or
* http://www.nabucco.org/License.html
*
* 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.nabucco.framework.generator.compiler.transformation.java.view;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ImportReference;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference;
import org.eclipse.jdt.internal.compiler.ast.ReturnStatement;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.nabucco.framework.generator.compiler.constants.NabuccoJavaTemplateConstants;
import org.nabucco.framework.generator.compiler.transformation.common.annotation.NabuccoAnnotation;
import org.nabucco.framework.generator.compiler.transformation.common.annotation.NabuccoAnnotationMapper;
import org.nabucco.framework.generator.compiler.transformation.common.annotation.NabuccoAnnotationType;
import org.nabucco.framework.generator.compiler.transformation.java.common.ast.container.JavaAstContainter;
import org.nabucco.framework.generator.compiler.transformation.java.common.ast.container.JavaAstType;
import org.nabucco.framework.generator.compiler.transformation.java.constants.ViewConstants;
import org.nabucco.framework.generator.compiler.transformation.java.visitor.NabuccoToJavaVisitorContext;
import org.nabucco.framework.generator.compiler.transformation.util.NabuccoTransformationUtility;
import org.nabucco.framework.generator.compiler.visitor.NabuccoVisitorException;
import org.nabucco.framework.generator.parser.syntaxtree.AnnotationDeclaration;
import org.nabucco.framework.generator.parser.syntaxtree.SearchViewStatement;
import org.nabucco.framework.mda.logger.MdaLogger;
import org.nabucco.framework.mda.logger.MdaLoggingFactory;
import org.nabucco.framework.mda.model.java.JavaModelException;
import org.nabucco.framework.mda.model.java.ast.element.JavaAstElementFactory;
import org.nabucco.framework.mda.model.java.ast.element.discriminator.LiteralType;
import org.nabucco.framework.mda.model.java.ast.element.method.JavaAstMethodSignature;
import org.nabucco.framework.mda.model.java.ast.produce.JavaAstModelProducer;
/**
* NabuccoToJavaRcpViewVisitorSupportUtil
*
* @author Silas Schwarz PRODYNA AG
*/
public final class NabuccoToJavaRcpViewVisitorSupportUtil implements ViewConstants {
private static MdaLogger logger = MdaLoggingFactory.getInstance().getLogger(
NabuccoToJavaRcpViewVisitorSupportUtil.class);
private NabuccoToJavaRcpViewVisitorSupportUtil() {
}
public static final ImportReference getModelTypeImport(NabuccoToJavaVisitorContext visitorContext,
SearchViewStatement searchViewStatement) throws JavaModelException {
String pkg = visitorContext.getPackage().replace(UI, UI_RCP) + PKG_SEPARATOR + MODEL_PACKAGE;
String name = searchViewStatement.nodeToken2.tokenImage.replace(NabuccoJavaTemplateConstants.VIEW,
NabuccoJavaTemplateConstants.MODEL);
return JavaAstModelProducer.getInstance().createImportReference(pkg + PKG_SEPARATOR + name);
}
/**
* Swaps the field order so that the title field is defined after the id field since it depends
* on it
*
*/
public static void swapFieldOrder(TypeDeclaration type) {
int idPos = -1;
for (int i = 0; i < type.fields.length; i++) {
if (Arrays.equals(type.fields[i].name, ID.toCharArray())) {
idPos = i;
}
}
if (idPos != 0) {
FieldDeclaration currentFirst = type.fields[0];
type.fields[0] = type.fields[idPos];
type.fields[idPos] = currentFirst;
}
}
public static List<JavaAstContainter<? extends ASTNode>> getUiCommonElements(TypeDeclaration uIType,
TypeDeclaration type, AnnotationDeclaration annotations) throws JavaModelException {
List<JavaAstContainter<? extends ASTNode>> result = new ArrayList<JavaAstContainter<? extends ASTNode>>();
NabuccoAnnotation elementId = NabuccoAnnotationMapper.getInstance().mapToAnnotation(annotations,
NabuccoAnnotationType.CLIENT_ELEMENT_ID);
// Add the static final id field if we find a Id client element
// annotation (@id)
if (elementId != null && elementId.getValue() != null && !elementId.getValue().isEmpty()) {
JavaAstElementFactory javaFactory = JavaAstElementFactory.getInstance();
// create static field id
FieldDeclaration fieldID = javaFactory.getJavaAstType().getField(uIType, ID);
fieldID.initialization = JavaAstModelProducer.getInstance().createLiteral(elementId.getValue(),
LiteralType.STRING_LITERAL);
JavaAstContainter<FieldDeclaration> fieldContainer = new JavaAstContainter<FieldDeclaration>(fieldID,
JavaAstType.FIELD);
result.add(fieldContainer);
// select the method "getId()"
JavaAstMethodSignature signature = new JavaAstMethodSignature(GET_ID);
MethodDeclaration getIdMethod = (MethodDeclaration) javaFactory.getJavaAstType().getMethod(uIType,
signature);
JavaAstContainter<MethodDeclaration> methodContainer = new JavaAstContainter<MethodDeclaration>(
getIdMethod, JavaAstType.METHOD);
// set the returnStatement
((QualifiedNameReference) ((ReturnStatement) getIdMethod.statements[0]).expression).tokens[0] = type.name;
result.add(methodContainer);
} else {
logger.warning("@Id annotation is missing or could not be analized");
}
return result;
}
public static JavaAstContainter<FieldDeclaration> createStaticFinalField(String mappedFieldName)
throws JavaModelException {
JavaAstElementFactory javaFactory = JavaAstElementFactory.getInstance();
String mappedField = PROPERTY + UNDERSCORE + mappedFieldName.toUpperCase().replace(PKG_SEPARATOR, UNDERSCORE);
FieldDeclaration resultingField = JavaAstModelProducer.getInstance().createFieldDeclaration(mappedField);
javaFactory.getJavaAstField().setFieldType(resultingField,
JavaAstModelProducer.getInstance().createTypeReference(STRING, false));
String[] mappedFieldInit = mappedFieldName.split(FIELD_SEPARATOR);
// only if mapped field is a Basetype or Enumeration
if (mappedFieldName.split(FIELD_SEPARATOR).length <= 2) {
resultingField.initialization = JavaAstModelProducer.getInstance().createLiteral(
mappedFieldInit[0] + NabuccoTransformationUtility.firstToUpper(mappedFieldInit[1]),
LiteralType.STRING_LITERAL);
} else {
resultingField.initialization = JavaAstModelProducer.getInstance()
.createLiteral(
mappedFieldInit[0]
+ NabuccoTransformationUtility.firstToUpper(mappedFieldInit[1])
+ NabuccoTransformationUtility.firstToUpper(mappedFieldInit[2]),
LiteralType.STRING_LITERAL);
}
// make static final
javaFactory.getJavaAstField().addModifier(resultingField,
ClassFileConstants.AccStatic | ClassFileConstants.AccFinal);
// remove private
javaFactory.getJavaAstField().removeModifier(resultingField, ClassFileConstants.AccPrivate);
// add public
javaFactory.getJavaAstField().addModifier(resultingField, ClassFileConstants.AccPublic);
JavaAstContainter<FieldDeclaration> result = new JavaAstContainter<FieldDeclaration>(resultingField,
JavaAstType.FIELD);
return result;
}
public static JavaAstContainter<FieldDeclaration> createConstant(String name, String value) {
try {
name = name.toUpperCase();
JavaAstModelProducer producer = JavaAstModelProducer.getInstance();
int modifier = ClassFileConstants.AccStatic | ClassFileConstants.AccFinal | ClassFileConstants.AccPublic;
FieldDeclaration constant = producer.createFieldDeclaration(name, modifier);
constant.type = producer.createTypeReference(STRING, false);
constant.initialization = producer.createLiteral(value, LiteralType.STRING_LITERAL);
return new JavaAstContainter<FieldDeclaration>(constant, JavaAstType.FIELD);
} catch (JavaModelException e) {
throw new NabuccoVisitorException("Cannot create constant [" + name + "].", e);
}
}
}
| epl-1.0 |
brfeddersen/sadlos2 | sadl3/com.ge.research.sadl.parent/com.ge.research.sadl.ui/src/com/ge/research/sadl/ui/preferences/SadlRootPreferencePage.java | 2875 | package com.ge.research.sadl.ui.preferences;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.RadioGroupFieldEditor;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.xtext.ui.editor.preferences.LanguageRootPreferencePage;
import org.eclipse.xtext.ui.editor.preferences.fields.LabelFieldEditor;
import com.ge.research.sadl.preferences.SadlPreferences;
public class SadlRootPreferencePage extends LanguageRootPreferencePage {
@SuppressWarnings("restriction")
@Override
protected void createFieldEditors() {
addField(new LabelFieldEditor("General SADL Settings", getFieldEditorParent()));
addField(new StringFieldEditor(SadlPreferences.SADL_BASE_URI.getId(), "Base URI", getFieldEditorParent()));
addField(new RadioGroupFieldEditor("OWL_Format", "Saved OWL model format :", 5,
new String[][] {
{SadlPreferences.RDF_XML_ABBREV_FORMAT.getId(), SadlPreferences.RDF_XML_ABBREV_FORMAT.getId()},
{SadlPreferences.RDF_XML_FORMAT.getId(), SadlPreferences.RDF_XML_FORMAT.getId()},
{SadlPreferences.N3_FORMAT.getId(), SadlPreferences.N3_FORMAT.getId()},
{SadlPreferences.N_TRIPLE_FORMAT.getId(), SadlPreferences.N_TRIPLE_FORMAT.getId()},
{SadlPreferences.JENA_TDB.getId(), SadlPreferences.JENA_TDB.getId()},
},
getFieldEditorParent()));
addField(new RadioGroupFieldEditor("importBy", "Show import model list as:", 2,
new String[][] {{"Model Namespaces", SadlPreferences.MODEL_NAMESPACES.getId()}, {"SADL File Names", SadlPreferences.SADL_FILE_NAMES.getId()}}, getFieldEditorParent()));
addField(new BooleanFieldEditor(SadlPreferences.PREFIXES_ONLY_AS_NEEDED.getId(), "Show prefixes for imported concepts only when needed for disambiguation", getFieldEditorParent()));
addField(new BooleanFieldEditor(SadlPreferences.VALIDATE_BEFORE_TEST.getId(), "Validate before Testing", getFieldEditorParent()));
addField(new BooleanFieldEditor(SadlPreferences.NAMESPACE_IN_QUERY_RESULTS.getId(), "Show Namespaces in Query Results", getFieldEditorParent()));
addField(new BooleanFieldEditor(SadlPreferences.SHOW_TIMING_INFORMATION.getId(), "Show Timing Informaton (Build, Reasoning)", getFieldEditorParent()));
addField(new RadioGroupFieldEditor("dmyOrder", "Interpret Date 10/11/2012 as:", 2,
new String[][] {{"MM/DD/YYYY", SadlPreferences.DMY_ORDER_MDY.getId()},
{"DD/MM/YYYY", SadlPreferences.DMY_ORDER_DMY.getId()}}, getFieldEditorParent()));
addField(new BooleanFieldEditor(SadlPreferences.DEEP_VALIDATION_OFF.getId(), "Disable Deep Validation of Model", getFieldEditorParent()));
addField(new StringFieldEditor(SadlPreferences.GRAPH_VIZ_PATH.getId(), "GraphViz bin folder", getFieldEditorParent()));
}
}
| epl-1.0 |
shamsmahmood/priorityworkstealing | src/main/java/edu/rice/habanero/benchmarks/knapsack/ThreadPoolBenchmark.java | 994 | package edu.rice.habanero.benchmarks.knapsack;
import edu.rice.habanero.benchmarks.BenchmarkRunner;
import edu.rice.habanero.concurrent.executors.GenericTaskExecutor;
import edu.rice.habanero.concurrent.executors.TaskExecutor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu)
*/
public class ThreadPoolBenchmark extends AbstractBenchmark {
public static void main(final String[] args) {
BenchmarkRunner.runBenchmark(args, new ThreadPoolBenchmark());
}
@Override
protected TaskExecutor createTaskExecutor() {
final ExecutorService executorService = Executors.newFixedThreadPool(BenchmarkRunner.numThreads());
final int minPriorityInc = BenchmarkRunner.minPriority();
final int maxPriorityInc = BenchmarkRunner.maxPriority();
return new GenericTaskExecutor(minPriorityInc, maxPriorityInc, executorService);
}
}
| epl-1.0 |
asupdev/asup | org.asup.db.server.test/src/org/asup/db/server/store/QStoreFactory.java | 1237 | /**
*/
package org.asup.db.server.store;
import org.eclipse.emf.ecore.EFactory;
/**
* <!-- begin-user-doc -->
* The <b>Factory</b> for the model.
* It provides a create method for each non-abstract class of the model.
* <!-- end-user-doc -->
* @see org.asup.db.server.store.QStorePackage
* @generated
*/
public interface QStoreFactory extends EFactory {
/**
* The singleton instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
QStoreFactory eINSTANCE = org.asup.db.server.store.impl.StoreFactoryImpl.init();
/**
* Returns a new object of class '<em>User</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>User</em>'.
* @generated
*/
QUser createUser();
/**
* Returns a new object of class '<em>Workstation</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Workstation</em>'.
* @generated
*/
QWorkstation createWorkstation();
/**
* Returns the package supported by this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the package supported by this factory.
* @generated
*/
QStorePackage getStorePackage();
} //QStoreFactory
| epl-1.0 |
AchimHentschel/smarthome | bundles/core/org.eclipse.smarthome.core.voice/src/main/java/org/eclipse/smarthome/core/voice/text/ExpressionSequence.java | 2583 | /**
* Copyright (c) 2014-2017 by the respective copyright holders.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.core.voice.text;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;
/**
* Expression that successfully parses, if a sequence of given expressions is matching. This class is immutable.
*
* @author Tilman Kamp - Initial contribution and API
*
*/
public final class ExpressionSequence extends Expression {
private List<Expression> subExpressions;
/**
* Constructs a new instance.
*
* @param subExpressions the sub expressions that are parsed in the given order
*/
public ExpressionSequence(Expression... subExpressions) {
super();
this.subExpressions = Collections
.unmodifiableList(Arrays.asList(Arrays.copyOf(subExpressions, subExpressions.length)));
}
@Override
ASTNode parse(ResourceBundle language, TokenList tokenList) {
TokenList list = tokenList;
int l = subExpressions.size();
ASTNode node = new ASTNode(), cr;
ASTNode[] children = new ASTNode[l];
Object[] values = new Object[l];
for (int i = 0; i < l; i++) {
cr = children[i] = subExpressions.get(i).parse(language, list);
if (!cr.isSuccess()) {
return node;
}
values[i] = cr.getValue();
list = cr.getRemainingTokens();
}
node.setChildren(children);
node.setRemainingTokens(list);
node.setSuccess(true);
node.setValue(values);
generateValue(node);
return node;
}
@Override
List<Expression> getChildExpressions() {
return subExpressions;
}
@Override
boolean collectFirsts(ResourceBundle language, HashSet<String> firsts) {
boolean blocking = false;
for (Expression e : subExpressions) {
if ((blocking = e.collectFirsts(language, firsts)) == true) {
break;
}
}
return blocking;
}
@Override
public String toString() {
String s = null;
for (Expression e : subExpressions) {
s = s == null ? e.toString() : (s + ", " + e.toString());
}
return "seq(" + s + ")";
}
} | epl-1.0 |
sonatype/nexus-public | components/nexus-orient/src/main/java/org/sonatype/nexus/orient/DatabaseCheckpointSupport.java | 3928 | /*
* Sonatype Nexus (TM) Open Source Version
* Copyright (c) 2008-present Sonatype, Inc.
* All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions.
*
* This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0,
* which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html.
*
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks
* of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the
* Eclipse Foundation. All other trademarks are the property of their respective owners.
*/
package org.sonatype.nexus.orient;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import javax.inject.Provider;
import org.sonatype.goodies.common.ComponentSupport;
import org.sonatype.nexus.common.app.ApplicationDirectories;
import org.sonatype.nexus.common.upgrade.Checkpoint;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* Support for upgrade checkpoint of OrientDB databases.
*
* @since 3.1
*/
public abstract class DatabaseCheckpointSupport
extends ComponentSupport
implements Checkpoint
{
private final String databaseName;
private final Provider<DatabaseInstance> databaseInstance;
private final ApplicationDirectories appDirectories;
private File upgradeDir;
private File backupZip;
private File failedZip;
protected DatabaseCheckpointSupport(final String databaseName,
final Provider<DatabaseInstance> databaseInstance,
final ApplicationDirectories appDirectories)
{
this.databaseName = checkNotNull(databaseName);
this.databaseInstance = checkNotNull(databaseInstance);
this.appDirectories = checkNotNull(appDirectories);
}
@Override
public void begin(String version) throws Exception {
upgradeDir = appDirectories.getWorkDirectory("upgrades/" + databaseName);
String timestampSuffix = String.format("-%1$tY%1$tm%1$td-%1$tH%1$tM%1$tS", System.currentTimeMillis());
backupZip = new File(upgradeDir, databaseName + "-" + version + timestampSuffix + "-backup.zip");
failedZip = new File(upgradeDir, databaseName + "-failed.zip");
log.debug("Backing up database to {}", backupZip);
try (OutputStream out = new FileOutputStream(backupZip)) {
databaseInstance.get().externalizer().backup(out);
}
}
@Override
public void commit() throws Exception {
// no-op
}
@Override
public void rollback() throws Exception {
checkState(failedZip != null);
checkState(backupZip != null);
log.debug("Exporting failed database to {}", failedZip);
try (OutputStream out = new FileOutputStream(failedZip)) {
databaseInstance.get().externalizer().backup(out);
}
finally {
log.debug("Restoring original database from {}", backupZip);
try (InputStream in = new FileInputStream(backupZip)) {
databaseInstance.get().externalizer().restore(in, true);
}
}
}
@Override
public void end() {
checkState(upgradeDir != null);
checkState(backupZip != null);
log.debug("Deleting backup from {}", upgradeDir);
try {
Files.delete(backupZip.toPath());
Files.delete(upgradeDir.toPath());
}
catch (IOException e) { // NOSONAR
log.warn("Could not delete backup of {} database, please delete {} manually. Error: {}", databaseName, upgradeDir,
e.toString());
}
backupZip = null;
failedZip = null;
upgradeDir = null;
}
}
| epl-1.0 |