repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
Lord-Nazdar/Conquest
src/com/nasser/poulet/conquest/astar/Node.java
12861
package com.nasser.poulet.conquest.astar; import java.util.ArrayList; import com.nasser.poulet.conquest.model.Board; import com.nasser.poulet.conquest.model.State; import com.nasser.poulet.conquest.model.Loyalty; public class Node implements Comparable<Node> { State state; double weight; // 1 if normal, 3 if water, 10 if ennemy double G; // Distance from start node double F; // Heuristic distance to the goal public double getF() { return F; } public void setF(double f) { F = f; } Node parent = null; public Node(){ state = null; weight = 1; G = Integer.MAX_VALUE; } public Node(State state){ this.state = state; this.weight = 0; G = Integer.MAX_VALUE; } public Node(State state, int weight) { this(state); this.weight = weight; } public State getState() { return state; } @Override public boolean equals(Object arg) { if (this.getState().getPosX() == ((Node) arg).getState().getPosX() && this.getState().getPosY() == ((Node) arg).getState().getPosY()) { return true; } else { return false; } } public void setState(State state) { this.state = state; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public double getG() { return G; } public void setG(double g) { G = g; } public Node getParent() { return parent; } public void setParent(Node parent) { this.parent = parent; } public int compareTo(Node otherNode) { double thisTotalDistanceFromGoal = F + G; double otherTotalDistanceFromGoal = otherNode.getF() + otherNode.getG(); if (thisTotalDistanceFromGoal < otherTotalDistanceFromGoal) { return -1; } else if (thisTotalDistanceFromGoal > otherTotalDistanceFromGoal) { return 1; } else { return 0; } } public int computeWeight(State state) { Loyalty nodeLoyalty = this.getState().getLoyalty(); Loyalty neighborLoyalty = state.getLoyalty(); if(neighborLoyalty == Loyalty.NONE) { return 3; } else if(neighborLoyalty == Loyalty.EMPTY) { return 1; } else if(neighborLoyalty == nodeLoyalty && state.canHostUnit()) { return 1; } else{ return 10; } } public ArrayList<Node> getNeighbor(Board board) { ArrayList<Node> neighbourANode = new ArrayList<Node>(); // We look if it's in the middle of the map if(this.getState().getPosX() > 0 && this.getState().getPosX() < board.getBoardWidth()-1) { if(this.getState().getPosY() > 0 && this.getState().getPosY() < board.getBoardHeight()-1) { neighbourANode.clear(); neighbourANode.add(new Node(board.getState(this.getState().getPosX(), this.getState().getPosY() - 1), computeWeight(board.getState(this.getState().getPosX(), this.getState().getPosY() - 1)))); // UP neighbourANode.add(new Node(board.getState(this.getState().getPosX() - 1, this.getState().getPosY()), computeWeight(board.getState(this.getState().getPosX() - 1, this.getState().getPosY())))); // LEFT neighbourANode.add(new Node(board.getState(this.getState().getPosX(), this.getState().getPosY() + 1), computeWeight(board.getState(this.getState().getPosX(), this.getState().getPosY() + 1)))); // DOWN neighbourANode.add(new Node(board.getState(this.getState().getPosX() + 1, this.getState().getPosY()), computeWeight(board.getState(this.getState().getPosX() + 1, this.getState().getPosY())))); // RIGHT neighbourANode.add(new Node(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() - 1), computeWeight(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() - 1)))); // UP LEFT neighbourANode.add(new Node(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() + 1), computeWeight(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() + 1)))); // DOWN LEFT neighbourANode.add(new Node(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() - 1), computeWeight(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() - 1)))); // UP RIGHT neighbourANode.add(new Node(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() + 1), computeWeight(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() + 1)))); // DOWN RIGHT } } // We look if it's in the left upper corner if(this.getState().getPosX() == 0 && this.getState().getPosY() == 0) { neighbourANode.clear(); neighbourANode.add(new Node(board.getState(this.getState().getPosX() + 1, this.getState().getPosY()), computeWeight(board.getState(this.getState().getPosX() + 1, this.getState().getPosY())))); // RIGHT neighbourANode.add(new Node(board.getState(this.getState().getPosX(), this.getState().getPosY() + 1), computeWeight(board.getState(this.getState().getPosX(), this.getState().getPosY() + 1)))); // DOWN neighbourANode.add(new Node(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() + 1), computeWeight(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() + 1)))); // DOWN RIGHT } // We look if it's in right upper corner if(this.getState().getPosX() == board.getBoardWidth()-1 && this.getState().getPosY() == 0) { neighbourANode.clear(); neighbourANode.add(new Node(board.getState(this.getState().getPosX() - 1, this.getState().getPosY()), computeWeight(board.getState(this.getState().getPosX() - 1, this.getState().getPosY())))); // LEFT neighbourANode.add(new Node(board.getState(this.getState().getPosX(), this.getState().getPosY() + 1), computeWeight(board.getState(this.getState().getPosX(), this.getState().getPosY() + 1)))); // DOWN neighbourANode.add(new Node(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() + 1), computeWeight(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() + 1)))); // DOWN LEFT } // We look if it's in the left down corner if(this.getState().getPosX() == 0 && this.getState().getPosY() == board.getBoardHeight()-1) { neighbourANode.clear(); neighbourANode.add(new Node(board.getState(this.getState().getPosX(), this.getState().getPosY() - 1), computeWeight(board.getState(this.getState().getPosX(), this.getState().getPosY() - 1)))); // UP neighbourANode.add(new Node(board.getState(this.getState().getPosX() + 1, this.getState().getPosY()), computeWeight(board.getState(this.getState().getPosX() + 1, this.getState().getPosY())))); // RIGHT neighbourANode.add(new Node(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() - 1), computeWeight(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() - 1)))); // UP RIGHT } // We look if it's in the right down corner if(this.getState().getPosX() == board.getBoardWidth()-1 && this.getState().getPosY() == board.getBoardHeight()-1) { neighbourANode.clear(); neighbourANode.add(new Node(board.getState(this.getState().getPosX() - 1, this.getState().getPosY()), computeWeight(board.getState(this.getState().getPosX() - 1, this.getState().getPosY())))); // LEFT neighbourANode.add(new Node(board.getState(this.getState().getPosX(), this.getState().getPosY() - 1), computeWeight(board.getState(this.getState().getPosX(), this.getState().getPosY() - 1)))); // UP neighbourANode.add(new Node(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() - 1), computeWeight(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() - 1)))); // UP LEFT } // We look if it's in the upper part if(this.getState().getPosX() > 0 && this.getState().getPosX() < board.getBoardWidth() - 1 && this.getState().getPosY() == 0) { neighbourANode.clear(); neighbourANode.add(new Node(board.getState(this.getState().getPosX() - 1, this.getState().getPosY()), computeWeight(board.getState(this.getState().getPosX() - 1, this.getState().getPosY())))); // LEFT neighbourANode.add(new Node(board.getState(this.getState().getPosX(), this.getState().getPosY() + 1), computeWeight(board.getState(this.getState().getPosX(), this.getState().getPosY() + 1)))); // DOWN neighbourANode.add(new Node(board.getState(this.getState().getPosX() + 1, this.getState().getPosY()), computeWeight(board.getState(this.getState().getPosX() + 1, this.getState().getPosY())))); // RIGHT neighbourANode.add(new Node(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() + 1), computeWeight(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() + 1)))); // DOWN LEFT neighbourANode.add(new Node(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() + 1), computeWeight(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() + 1)))); // DOWN RIGHT } // We look if it's in lower part if(this.getState().getPosX() > 0 && this.getState().getPosX() < board.getBoardWidth() - 1 && this.getState().getPosY() == board.getBoardHeight() - 1) { neighbourANode.clear(); neighbourANode.add(new Node(board.getState(this.getState().getPosX() - 1, this.getState().getPosY()), computeWeight(board.getState(this.getState().getPosX() - 1, this.getState().getPosY())))); // LEFT neighbourANode.add(new Node(board.getState(this.getState().getPosX(), this.getState().getPosY() - 1), computeWeight(board.getState(this.getState().getPosX(), this.getState().getPosY() - 1)))); // UP neighbourANode.add(new Node(board.getState(this.getState().getPosX() + 1, this.getState().getPosY()), computeWeight(board.getState(this.getState().getPosX() + 1, this.getState().getPosY())))); // RIGHT neighbourANode.add(new Node(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() - 1), computeWeight(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() - 1)))); // UP LEFT neighbourANode.add(new Node(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() - 1), computeWeight(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() - 1)))); // UP RIGHT } // We look if it's in the left part if(this.getState().getPosY() > 0 && this.getState().getPosY() < board.getBoardHeight() - 1 && this.getState().getPosX() == 0) { neighbourANode.clear(); neighbourANode.add(new Node(board.getState(this.getState().getPosX(), this.getState().getPosY() - 1), computeWeight(board.getState(this.getState().getPosX(), this.getState().getPosY() - 1)))); // UP neighbourANode.add(new Node(board.getState(this.getState().getPosX() + 1, this.getState().getPosY()), computeWeight(board.getState(this.getState().getPosX() + 1, this.getState().getPosY())))); // RIGHT neighbourANode.add(new Node(board.getState(this.getState().getPosX(), this.getState().getPosY() + 1), computeWeight(board.getState(this.getState().getPosX(), this.getState().getPosY() + 1)))); // DOWN neighbourANode.add(new Node(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() - 1), computeWeight(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() - 1)))); // UP RIGHT neighbourANode.add(new Node(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() + 1), computeWeight(board.getState(this.getState().getPosX() + 1, this.getState().getPosY() + 1)))); // DOWN RIGHT } // We look if it's in the right part if(this.getState().getPosY() > 0 && this.getState().getPosY() < board.getBoardHeight() - 1 && this.getState().getPosX() == board.getBoardWidth() - 1) { neighbourANode.clear(); neighbourANode.add(new Node(board.getState(this.getState().getPosX(), this.getState().getPosY() - 1), computeWeight(board.getState(this.getState().getPosX(), this.getState().getPosY() - 1)))); // UP neighbourANode.add(new Node(board.getState(this.getState().getPosX() - 1, this.getState().getPosY()), computeWeight(board.getState(this.getState().getPosX() - 1, this.getState().getPosY())))); // LEFT neighbourANode.add(new Node(board.getState(this.getState().getPosX(), this.getState().getPosY() + 1), computeWeight(board.getState(this.getState().getPosX(), this.getState().getPosY() + 1)))); // DOWN neighbourANode.add(new Node(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() - 1), computeWeight(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() - 1)))); // UP LEFT neighbourANode.add(new Node(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() + 1), computeWeight(board.getState(this.getState().getPosX() - 1, this.getState().getPosY() + 1)))); // DOWN LEFT } return neighbourANode; } }
mit
vitrivr/cineast
cineast-core/src/main/java/org/vitrivr/cineast/core/extraction/metadata/MetadataExtractor.java
1263
package org.vitrivr.cineast.core.extraction.metadata; import java.nio.file.Path; import java.util.List; import org.vitrivr.cineast.core.data.entities.MediaObjectMetadataDescriptor; public interface MetadataExtractor { /** * Initializes the extractor. The default implementation does nothing. */ default void init() { // As a default do nothing } /** * Extracts the metadata from the specified path and returns a List of MediaObjectMetadataDescriptor objects (one for each metadata entry). * * @param objectId ID of the multimedia object for which metadata will be generated. * @param path Path to the file for which metadata should be extracted. * @return List of MultimediaMetadataDescriptors. The list may be empty but must always be returned! */ List<MediaObjectMetadataDescriptor> extract(String objectId, Path path); /** * Closes and cleans up the extractor. The default implementation does nothing. */ default void finish() { // As a default do nothing } /** * Returns a name that helps to identify the metadata domain. E.g. EXIF for EXIF metadata or DC for Dublin Core. * * @return Name of the metadata domain for which this extractor returns metadata. */ String domain(); }
mit
JeffreyFalgout/junit5-extensions
mockito-extension/src/main/java/name/falgout/jeffrey/testing/junit/mockito/CaptorParameterFactory.java
757
package name.falgout.jeffrey.testing.junit.mockito; import com.google.common.reflect.TypeToken; import java.lang.reflect.Parameter; import org.mockito.ArgumentCaptor; /** * Processes parameters of type {@link ArgumentCaptor}. */ final class CaptorParameterFactory implements ParameterFactory { @Override public boolean supports(Parameter parameter) { return parameter.getType() == ArgumentCaptor.class; } @Override public Object getParameterValue(Parameter parameter) { TypeToken<?> parameterType = TypeToken.of(parameter.getParameterizedType()); TypeToken<?> captorParameter = parameterType.resolveType(ArgumentCaptor.class.getTypeParameters()[0]); return ArgumentCaptor.forClass(captorParameter.getRawType()); } }
mit
CS2103AUG2016-W09-C1/main
src/main/java/seedu/oneline/commons/util/UrlUtil.java
635
package seedu.oneline.commons.util; import java.net.URL; /** * A utility class for URL */ public class UrlUtil { /** * Returns true if both URLs have the same base URL */ public static boolean compareBaseUrls(URL url1, URL url2) { if (url1 == null || url2 == null) { return false; } return url1.getHost().toLowerCase().replaceFirst("www.", "") .equals(url2.getHost().replaceFirst("www.", "").toLowerCase()) && url1.getPath().replaceAll("/", "").toLowerCase() .equals(url2.getPath().replaceAll("/", "").toLowerCase()); } }
mit
tlbdk/copybook4java
copybook4java/src/test/java/dk/nversion/copybook/serializers/CopyBookFullLastArrayShortSerializerTest.java
5280
/* * Copyright (c) 2015. Troels Liebe Bentsen <tlb@nversion.dk> * Licensed under the MIT license (LICENSE.txt) */ package dk.nversion.copybook.serializers; import dk.nversion.copybook.CopyBookSerializer; import dk.nversion.copybook.annotations.CopyBook; import dk.nversion.copybook.annotations.CopyBookLine; import java.math.BigDecimal; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.assertArrayEquals; public class CopyBookFullLastArrayShortSerializerTest { @CopyBook(type = FullLastArrayShortMapper.class) static public class StringFieldOccursTwoTimes { @CopyBookLine("01 COUNT PIC 9.") public int fields_count; @CopyBookLine("01 FIELDS OCCURS 10 TIMES PIC X(4).") public String[] fields; } @org.junit.Test public void testStringFieldOccursTwoTimes() throws Exception { CopyBookSerializer serializer = new CopyBookSerializer(StringFieldOccursTwoTimes.class); StringFieldOccursTwoTimes test = new StringFieldOccursTwoTimes(); test.fields = new String[] {"abcd", "1234"}; test.fields_count = test.fields.length; byte[] testBytes = serializer.serialize(test); assertEquals(1 + 4 * test.fields_count, testBytes.length); StringFieldOccursTwoTimes test2 = serializer.deserialize(testBytes, StringFieldOccursTwoTimes.class); assertArrayEquals(test.fields, test2.fields); } @CopyBook(type = FullLastArrayShortMapper.class) static public class IntFieldOccursTwoTimes { @CopyBookLine("01 COUNT PIC 9.") public int fields_count; @CopyBookLine("01 FIELDS OCCURS 10 TIMES PIC 9(4).") public int[] fields; } @org.junit.Test public void testIntFieldOccursTwoTimes() throws Exception { CopyBookSerializer serializer = new CopyBookSerializer(IntFieldOccursTwoTimes.class); IntFieldOccursTwoTimes test = new IntFieldOccursTwoTimes(); test.fields = new int[] {1, 2}; test.fields_count = test.fields.length; byte[] testBytes = serializer.serialize(test); assertEquals(1 + 4 * test.fields_count, testBytes.length); IntFieldOccursTwoTimes test2 = serializer.deserialize(testBytes, IntFieldOccursTwoTimes.class); assertArrayEquals(test.fields, test2.fields); } @CopyBook(type = FullLastArrayShortMapper.class) static public class SignedIntFieldOccursTwoTimes { @CopyBookLine("01 COUNT PIC 9.") public int fields_count; @CopyBookLine("01 FIELDS OCCURS 10 TIMES PIC S9(4).") public int[] fields; } @org.junit.Test public void testSignedIntFieldOccursTwoTimes() throws Exception { CopyBookSerializer serializer = new CopyBookSerializer(SignedIntFieldOccursTwoTimes.class); SignedIntFieldOccursTwoTimes test = new SignedIntFieldOccursTwoTimes(); test.fields = new int[] {-1, -2}; test.fields_count = test.fields.length; byte[] testBytes = serializer.serialize(test); assertEquals(1 + 4 * test.fields_count, testBytes.length); SignedIntFieldOccursTwoTimes test2 = serializer.deserialize(testBytes, SignedIntFieldOccursTwoTimes.class); assertArrayEquals(test.fields, test2.fields); } @CopyBook(type = FullLastArrayShortMapper.class) static public class DecimalFieldOccursTwoTimes { @CopyBookLine("01 COUNT PIC 9.") public int fields_count; @CopyBookLine("01 FIELDS OCCURS 10 TIMES PIC 9(3)V9(2).") public BigDecimal[] fields; } @org.junit.Test public void testDecimalFieldOccursTwoTimes() throws Exception { CopyBookSerializer serializer = new CopyBookSerializer(DecimalFieldOccursTwoTimes.class); DecimalFieldOccursTwoTimes test = new DecimalFieldOccursTwoTimes(); test.fields = new BigDecimal[] {new BigDecimal("1.00"), new BigDecimal("2.00")}; test.fields_count = test.fields.length; byte[] testBytes = serializer.serialize(test); assertEquals(1 + 5 * test.fields_count, testBytes.length); DecimalFieldOccursTwoTimes test2 = serializer.deserialize(testBytes, DecimalFieldOccursTwoTimes.class); assertArrayEquals(test.fields, test2.fields); } @CopyBook(type = FullLastArrayShortMapper.class) static public class SignedDecimalFieldOccursTwoTimes { @CopyBookLine("01 COUNT PIC 9.") public int fields_count; @CopyBookLine("01 FIELDS OCCURS 10 TIMES PIC S9(3)V9(2).") public BigDecimal[] fields; } @org.junit.Test public void testSignedDecimalFieldOccursTwoTimes() throws Exception { CopyBookSerializer serializer = new CopyBookSerializer(SignedDecimalFieldOccursTwoTimes.class); SignedDecimalFieldOccursTwoTimes test = new SignedDecimalFieldOccursTwoTimes(); test.fields = new BigDecimal[] {new BigDecimal("-1.00"), new BigDecimal("-2.00")}; test.fields_count = test.fields.length; byte[] testBytes = serializer.serialize(test); assertEquals(1 + 5 * test.fields_count, testBytes.length); SignedDecimalFieldOccursTwoTimes test2 = serializer.deserialize(testBytes, SignedDecimalFieldOccursTwoTimes.class); assertArrayEquals(test.fields, test2.fields); } }
mit
RaTTiE/grails-es-common-core
src/java/org/eldersoftware/common/util/text/ByteSizeFormatUtil.java
3268
/** * <p>Elder Software CommonLib * バイトサイズフォーマットクラス * * @since 2010/08/28 * @author RaTTiE */ package org.eldersoftware.common.util.text; import java.text.DecimalFormat; // 共通ライブラリと銘打ちつつ、割と特殊なフォーマットやってるので、 // その辺りの制御は外出しできる様にした方がよさげ…。 public class ByteSizeFormatUtil { // 表示単位省略時のデフォルト単位 private static final String DEFAULT_UNITS[] = { " bytes", "KB", "MB", "GB", "TB", "PB" }; /** * <p>バイトサイズのフォーマットを行い、単位を付加する。<br> * <p>キロバイトは10000を下回るまで、以降は1000を下回るまで値を割り続ける。<br> * また、値を割る除数は1024ではなく1000とする。 * <p>小数表示はキロバイトまでは3桁、以降は2桁表示する。 * * @param value フォーマット対象の値。 * @param units * 表示単位の配列を{@code String}の配列で指定する。<br> * 指定した単位で表現可能でかつ最小の値となるようフォーマットされる。 * 省略時は{@code DEFAULT_UNITS}を表示単位として指定する。 * * @return フォーマット結果の文字列。 */ public String format(long value, String units[]) { // 表示単位の配列 // 表示単位が有効なところまでフォーマットする if (units == null) units = ByteSizeFormatUtil.DEFAULT_UNITS; DecimalFormat nf; double result = value; int pow = 0; String unit = ""; // 最大単位まで値を計算し続ける for (pow = 0; pow < units.length; pow++) { unit = units[pow]; if (pow < 1) { // KBまでは10000バイト単位で if (value >= 10000) { result = value / Math.pow(1000, pow); } if (result < 10000) break; } else { // MB以降は1000バイト単位で if (value >= 1000) { result = value / Math.pow(1000, pow); } if (result < 1000) break; } } int scale; Double d = new Double(result); if (pow >= 2) { // MB以降は小数表示を1桁まで scale = 1; } else if (pow > 0) { // KBは小数表示を2桁まで scale = 2; } else { // Bは小数表示なし scale = 0; } // フォーマットを作成 if (scale > 0) { nf = new DecimalFormat( "#,##0." + String.format("%0" + String.valueOf(scale) + "d", 0) ); // 有効桁数以下を切り捨て result = Math.floor(result * Math.pow(10, scale)) / Math.pow(10, scale); } else { nf = new DecimalFormat("#,##0"); } // フォーマット結果に単位を付加して返す return nf.format(result) + unit; } /** * <p>バイトサイズのフォーマットを行い、単位を付加する。<br> * <p>キロバイトは10000を下回るまで、以降は1000を下回るまで値を割り続ける。<br> * また、値を割る除数は1024ではなく1000とする。 * <p>小数表示はキロバイトまでは3桁、以降は2桁表示する。 * * @param value フォーマット対象の値。 * * @return フォーマット結果の文字列。 */ public String format(long value) { return format(value, null); } }
mit
karim/adila
database/src/main/java/adila/db/j3xlte_sm2dj320g.java
244
// This file is automatically generated. package adila.db; /* * Samsung Galaxy J3 (2016) * * DEVICE: j3xlte * MODEL: SM-J320G */ final class j3xlte_sm2dj320g { public static final String DATA = "Samsung|Galaxy J3 (2016)|Galaxy J"; }
mit
jwiesel/sfdcCommander
sfdcCommander/src/main/java/com/sforce/soap/_2006/_04/metadata/LogCategoryLevel.java
3625
/** * LogCategoryLevel.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.sforce.soap._2006._04.metadata; public class LogCategoryLevel implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected LogCategoryLevel(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _None = "None"; public static final java.lang.String _Finest = "Finest"; public static final java.lang.String _Finer = "Finer"; public static final java.lang.String _Fine = "Fine"; public static final java.lang.String _Debug = "Debug"; public static final java.lang.String _Info = "Info"; public static final java.lang.String _Warn = "Warn"; public static final java.lang.String _Error = "Error"; public static final LogCategoryLevel None = new LogCategoryLevel(_None); public static final LogCategoryLevel Finest = new LogCategoryLevel(_Finest); public static final LogCategoryLevel Finer = new LogCategoryLevel(_Finer); public static final LogCategoryLevel Fine = new LogCategoryLevel(_Fine); public static final LogCategoryLevel Debug = new LogCategoryLevel(_Debug); public static final LogCategoryLevel Info = new LogCategoryLevel(_Info); public static final LogCategoryLevel Warn = new LogCategoryLevel(_Warn); public static final LogCategoryLevel Error = new LogCategoryLevel(_Error); public java.lang.String getValue() { return _value_;} public static LogCategoryLevel fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { LogCategoryLevel enumeration = (LogCategoryLevel) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static LogCategoryLevel fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumSerializer( _javaType, _xmlType); } public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(LogCategoryLevel.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "LogCategoryLevel")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
mit
krzysztof-chmielewski/Spring-Advanced
09 Spring tests/src/test/java/io/kch/sda/spring/springtests09/player/InternetRadioTest.java
1589
package io.kch.sda.spring.springtests09.player; import io.kch.sda.spring.springtests09.player.InternetRadio; import io.kch.sda.spring.springtests09.song.Song; import org.junit.Test; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; public class InternetRadioTest { private final InternetRadio internetRadio = new InternetRadio(); @Test public void noSongsArePlayedAtTheBeginning() throws Exception { assertThat(internetRadio.playedSongs()).isEqualTo(Collections.emptyList()); assertThat(internetRadio.currentSong()).isNull(); } @Test public void playingOneSongsAddsItToTheListOfSongs() throws Exception { Song song = new Song("Artist", "Album", "Title"); internetRadio.playSong(song); assertThat(internetRadio.playedSongs()).contains(song); assertThat(internetRadio.playedSongs()).hasSize(1); assertThat(internetRadio.currentSong()).isEqualTo(song); } @Test public void playingThreeSongsAddsThemToTheListOfSongs() throws Exception { Song first = new Song("Artist", "Album", "Title"); Song second = new Song("Artist2", "Album2", "Title2"); Song third = new Song("Artist3", "Album3", "Title2"); internetRadio.playSong(first); internetRadio.playSong(second); internetRadio.playSong(third); assertThat(internetRadio.playedSongs()).contains(first, second, third); assertThat(internetRadio.playedSongs()).hasSize(3); assertThat(internetRadio.currentSong()).isEqualTo(third); } }
mit
djabber/Dashboard
java/SysMonitor/src/sysmonitor/TimeConverter.java
474
package sysmonitor; public class TimeConverter extends AbstractSIConverter{ private long start, end, current, runtime; public TimeConverter(){ super("second"); start = getCurrent(); } public long getCurrent(){ return System.currentTimeMillis(); } public long getStart(){ return start; } public long getEnd(){ return end = getCurrent(); } public long getRuntime(){ return (getEnd() - getStart()); } }
mit
keilw/JStrava
src/org/jstrava/entities/activity/Activity.java
10131
package org.jstrava.entities.activity; import org.jstrava.entities.segment.SegmentEffort; import org.jstrava.entities.athlete.Athlete; import java.util.ArrayList; import java.util.List; import com.google.gson.annotations.SerializedName; /** * Created by roberto on 12/26/13. */ public class Activity { private int id; private int resource_state; private String external_id; private int upload_id; private Athlete athlete;/*Simple Athlete representation with just id*/ private String name; private float distance; private int moving_time; private int elapsed_time; private float total_elevation_gain; private String type; private String start_date; private String start_date_local; private String timezone; private String[] start_latlng; private String[] end_latlng; private String location_city; private String location_state; private int achievement_count; private int kudos_count; private int comment_count; private int athlete_count; private int photo_count; private Polyline map; private boolean trainer; private boolean commute; private boolean manual; @SerializedName("private") private boolean PRIVATE; private boolean flagged; private String gear_id; private float average_speed; private float max_speed; private float average_cadence; private int average_temp; private float average_watts; private float kilojoules; private float average_heartrate; private float max_heartrate; private float calories; private int truncated; private boolean has_kudoed; private List<SegmentEffort> segment_efforts=new ArrayList<>(); private List<SplitsMetric> splits_metric=new ArrayList<>(); private List<SplitsStandard> splits_standard=new ArrayList<>(); private List<SegmentEffort> best_efforts=new ArrayList<>(); @Override public String toString() { return name; } public Activity() { } public Activity(int id) { this.id = id; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getResource_state() { return resource_state; } public void setResource_state(int resource_state) { this.resource_state = resource_state; } public String getExternal_id() { return external_id; } public void setExternal_id(String external_id) { this.external_id = external_id; } public Athlete getAthlete() { return athlete; } public void setAthlete(Athlete athlete) { this.athlete = athlete; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getDistance() { return distance; } public void setDistance(float distance) { this.distance = distance; } public int getMoving_time() { return moving_time; } public void setMoving_time(int moving_time) { this.moving_time = moving_time; } public int getElapsed_time() { return elapsed_time; } public void setElapsed_time(int elapsed_time) { this.elapsed_time = elapsed_time; } public float getTotal_elevation_gain() { return total_elevation_gain; } public void setTotal_elevation_gain(float total_elevation_gain) { this.total_elevation_gain = total_elevation_gain; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getStart_date() { return start_date; } public void setStart_date(String start_date) { this.start_date = start_date; } public boolean isTrainer() { return trainer; } public boolean isCommute() { return commute; } public boolean isManual() { return manual; } public boolean isPRIVATE() { return PRIVATE; } public boolean isFlagged() { return flagged; } public boolean isHas_kudoed() { return has_kudoed; } public String getStart_date_local() { return start_date_local; } public void setStart_date_local(String start_date_local) { this.start_date_local = start_date_local; } public String getTime_zone() { return timezone; } public void setTime_zone(String timezone) { this.timezone = timezone; } public String[] getStart_latlng() { return start_latlng; } public void setStart_latlng(String[] start_latlng) { this.start_latlng = start_latlng; } public String[] getEnd_latlng() { return end_latlng; } public void setEnd_latlng(String[] end_latlng) { this.end_latlng = end_latlng; } public String getLocation_city() { return location_city; } public void setLocation_city(String location_city) { this.location_city = location_city; } public String getLocation_state() { return location_state; } public void setLocation_state(String location_state) { this.location_state = location_state; } public int getAchievement_count() { return achievement_count; } public void setAchievement_count(int achievement_count) { this.achievement_count = achievement_count; } public int getKudos_count() { return kudos_count; } public void setKudos_count(int kudos_count) { this.kudos_count = kudos_count; } public int getComment_count() { return comment_count; } public void setComment_count(int comment_count) { this.comment_count = comment_count; } public int getAthlete_count() { return athlete_count; } public void setAthlete_count(int athlete_count) { this.athlete_count = athlete_count; } public int getPhoto_count() { return photo_count; } public void setPhoto_count(int photo_count) { this.photo_count = photo_count; } public Polyline getMap() { return map; } public void setMap(Polyline map) { this.map = map; } public boolean getTrainer() { return trainer; } public void setTrainer(boolean trainer) { this.trainer = trainer; } public boolean getCommute() { return commute; } public void setCommute(boolean commute) { this.commute = commute; } public boolean getManual() { return manual; } public void setManual(boolean manual) { this.manual = manual; } public boolean getPRIVATE() { return PRIVATE; } public void setPRIVATE(boolean PRIVATE) { this.PRIVATE = PRIVATE; } public boolean getFlagged() { return flagged; } public void setFlagged(boolean flagged) { this.flagged = flagged; } public String getGear_id() { return gear_id; } public void setGear_id(String gear_id) { this.gear_id = gear_id; } public float getAverage_speed() { return average_speed; } public void setAverage_speed(float average_speed) { this.average_speed = average_speed; } public float getMax_speed() { return max_speed; } public void setMax_speed(float max_speed) { this.max_speed = max_speed; } public float getAverage_cadence() { return average_cadence; } public void setAverage_cadence(float average_cadence) { this.average_cadence = average_cadence; } public int getAverage_temp() { return average_temp; } public void setAverage_temp(int average_temp) { this.average_temp = average_temp; } public float getAverage_watts() { return average_watts; } public void setAverage_watts(float average_watts) { this.average_watts = average_watts; } public float getKilojoules() { return kilojoules; } public void setKilojoules(float kilojoules) { this.kilojoules = kilojoules; } public float getAverage_heartrate() { return average_heartrate; } public void setAverage_heartrate(float average_heartrate) { this.average_heartrate = average_heartrate; } public float getMax_heartrate() { return max_heartrate; } public void setMax_heartrate(float max_heartrate) { this.max_heartrate = max_heartrate; } public float getCalories() { return calories; } public void setCalories(float calories) { this.calories = calories; } public int getTruncated() { return truncated; } public void setTruncated(int truncated) { this.truncated = truncated; } public boolean getHas_kudoed() { return has_kudoed; } public void setHas_kudoed(boolean has_kudoed) { this.has_kudoed = has_kudoed; } public List<SegmentEffort> getSegment_efforts() { return segment_efforts; } public void setSegment_efforts(List<SegmentEffort> segment_efforts) { this.segment_efforts = segment_efforts; } public List<SplitsMetric> getSplits_metric() { return splits_metric; } public void setSplits_metric(List<SplitsMetric> splits_metric) { this.splits_metric = splits_metric; } public List<SplitsStandard> getSplits_standard() { return splits_standard; } public void setSplits_standard(List<SplitsStandard> splits_standard) { this.splits_standard = splits_standard; } public List<SegmentEffort> getBest_efforts() { return best_efforts; } public void setBest_efforts(List<SegmentEffort> best_efforts) { this.best_efforts = best_efforts; } public int getUpload_id() { return upload_id; } public void setUpload_id(int upload_id) { this.upload_id = upload_id; } }
mit
mfoschi/jmAtaxx
src/org/foschi/jmataxx/Prefs.java
4868
/* * Prefs.java * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Initial Developer of the Original Code is Marcello Foschi. * Portions created by the Initial Developer are Copyright (C) 2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * ***** END LICENSE BLOCK ***** * */ package org.foschi.jmataxx; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import javax.microedition.rms.RecordStore; import javax.microedition.rms.RecordStoreNotFoundException; /** * * @author Marcello Foschi */ public class Prefs { private RecordStore rs = null; private final static int maxLevel = 5; private int level = 1; // 0: BT, 1: easy, 2: medium, 3+: hard (depth level-3) private String playerName = "Player"; private byte[] played = null; private byte[] victories = null; /** Singleton instance */ private static Prefs instance = null; private Prefs() { played = new byte[maxLevel+1]; victories = new byte[maxLevel+1]; loadPrefs(); } public static Prefs getInstance() { if (instance == null) instance = new Prefs(); return instance; } public String getPlayerName() { return playerName; } public void setPlayerName(String _playerName) { playerName = _playerName; } public int getLevel() { return level; } public void setLevel(int _level) { level = _level; } public void addPlayed() { played[level]++; } public void addVictory() { victories[level]++; } String[] getScores() { String[] scores = new String[maxLevel+1]; for (int i=0; i<=maxLevel; i++) scores[i] = victories[i]+" / "+played[i]; return scores; } // PERSISTENCE private void loadPrefs() { try { rs = RecordStore.openRecordStore("Ataxx", false); if (rs.getNumRecords() != 3) return; // livello corrente e nome giocatore ByteArrayInputStream bais = new ByteArrayInputStream(rs.getRecord(1)); DataInputStream inStream = new DataInputStream(bais); level = inStream.readInt(); if (level > maxLevel) level = maxLevel; playerName = inStream.readUTF(); inStream.close(); bais.close(); // numero partite giocate/vinte rs.getRecord(2, played, 0); rs.getRecord(3, victories, 0); } catch (RecordStoreNotFoundException ex) { // If not existings simply skip reading rs = null; } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (rs != null) rs.closeRecordStore(); } catch (Exception ex) { ex.printStackTrace(); } } } public void savePrefs() { try { rs = RecordStore.openRecordStore("Ataxx", true); // livello corrente e nome giocatore ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outStream = new DataOutputStream(baos); outStream.writeInt(level); outStream.writeUTF(playerName); byte[] temp = baos.toByteArray(); outStream.close(); baos.close(); if (rs.getNumRecords() == 0) { // CREATE new records rs.addRecord(temp, 0, temp.length); rs.addRecord(played, 0, maxLevel+1); rs.addRecord(victories, 0, maxLevel+1); } else { // UPDATE existing records rs.setRecord(1, temp, 0, temp.length); rs.setRecord(2, played, 0, maxLevel+1); rs.setRecord(3, victories, 0, maxLevel+1); } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (rs != null) rs.closeRecordStore(); } catch (Exception ex) { ex.printStackTrace(); } } } }
mit
danteteam/VKUniversity-Android-App
app/src/main/java/com/dantelab/testvkapplication/common/utils/Utils.java
721
package com.dantelab.testvkapplication.common.utils; import com.vk.sdk.api.model.VKApiMessage; import com.vk.sdk.api.model.VKApiPhoto; import java.lang.ref.WeakReference; import java.util.Objects; /** * Created by ivanbrazhnikov on 20.01.16. */ public final class Utils { public static <T> WeakReference<T> weak(T object){ return new WeakReference<T>(object); } public static VKApiPhoto messageFirstPhoto(VKApiMessage message) { if (!message.attachments.isEmpty()) { for (Object att : message.attachments) { if (att instanceof VKApiPhoto) { return (VKApiPhoto) att; } } } return null; } }
mit
albu89/Hive2Hive-dev
org.hive2hive.core/src/main/java/org/hive2hive/core/processes/files/update/CleanupChunksStep.java
2189
package org.hive2hive.core.processes.files.update; import java.security.KeyPair; import java.util.List; import org.hive2hive.core.api.configs.FileConfiguration; import org.hive2hive.core.model.MetaChunk; import org.hive2hive.core.network.data.IDataManager; import org.hive2hive.core.processes.context.UpdateFileProcessContext; import org.hive2hive.core.processes.files.delete.DeleteSingleChunkStep; import org.hive2hive.processframework.abstracts.ProcessComponent; import org.hive2hive.processframework.abstracts.ProcessStep; import org.hive2hive.processframework.decorators.AsyncComponent; import org.hive2hive.processframework.exceptions.InvalidProcessStateException; import org.hive2hive.processframework.exceptions.ProcessExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Initializes all {@link DeleteSingleChunkStep} to delete the chunks that are not used anymore. These are the * ones exceeding the limits at the {@link FileConfiguration}. * * @author Nico, Seppi */ public class CleanupChunksStep extends ProcessStep { private static final Logger logger = LoggerFactory.getLogger(CleanupChunksStep.class); private final UpdateFileProcessContext context; private final IDataManager dataManager; public CleanupChunksStep(UpdateFileProcessContext context, IDataManager dataManager) { this.context = context; this.dataManager = dataManager; } @Override protected void doExecute() throws InvalidProcessStateException, ProcessExecutionException { List<MetaChunk> chunksToDelete = context.getChunksToDelete(); KeyPair protectionKeys = context.consumeProtectionKeys(); logger.debug("Cleaning {} old file chunks.", chunksToDelete.size()); int counter = 0; ProcessComponent prev = this; for (MetaChunk metaChunk : chunksToDelete) { logger.debug("Delete chunk {} of {}.", counter++, chunksToDelete.size()); DeleteSingleChunkStep deleteStep = new DeleteSingleChunkStep(metaChunk.getChunkId(), protectionKeys, dataManager); // make async, insert it as next step AsyncComponent asyncDeletion = new AsyncComponent(deleteStep); getParent().insertNext(asyncDeletion, prev); prev = asyncDeletion; } } }
mit
smaltby/ZArena
src/main/java/com/github/zarena/signs/ZTollSign.java
12693
package com.github.zarena.signs; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.*; import java.util.logging.Level; import net.minecraft.server.v1_7_R1.BlockDoor; import net.minecraft.server.v1_7_R1.BlockTrapdoor; import net.minecraft.server.v1_7_R1.EntityPlayer; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Sign; import org.bukkit.craftbukkit.v1_7_R1.CraftWorld; import org.bukkit.craftbukkit.v1_7_R1.entity.CraftPlayer; import org.bukkit.entity.Player; import com.github.zarena.ZArena; import com.github.zarena.ZLevel; import com.github.zarena.utils.LocationSer; import com.github.zarena.utils.StringEnums; public class ZTollSign extends ZSign implements Externalizable { private static final long serialVersionUID = "ZTOLLSIGN".hashCode(); // DO NOT CHANGE private static final int VERSION = 4; private LocationSer costBlockLocation; //The location of the block that costs money to be used private boolean useableOnce; //Whether or not this sign can only be used once private boolean opposite; //The sign's costblock starts out open/on, as opposed to closed/off private boolean noReset; //The sign's costblock doesn't reset, staying the same across multiple games private boolean active; private String name; public List<String> zSpawns = new ArrayList<String>(); //List of zSpawn names that are only active when this sign is active public List<LocationSer> oldZSpawns; /** * Empty constructor for externalization. */ public ZTollSign() { resetCostBlock(); } public ZTollSign(ZLevel level, Location location, LocationSer costBlockLocation, int price, String name, String[] flags) { super(level, LocationSer.convertFromBukkitLocation(location), price); this.costBlockLocation = costBlockLocation; this.name = name; active = false; for(String flag : flags) { try { switch(StringEnums.valueOf(flag.toUpperCase().replaceAll("-", ""))) { case UO: case USABLEONCE: setUseableOnce(true); break; case OP: case OPPOSITE: setOpposite(true); break; case NR: case NORESET: setNoReset(true); break; default: } //Catch nonexistent flags } catch(Exception e){} } } public static ZTollSign attemptCreateSign(ZLevel level, Location location, String[] lines) { int price; try { price = Integer.parseInt(lines[1]); } catch(NumberFormatException e) //Second line isn't a number, and can't have a price put to it { return null; } LocationSer costBlockLocation = getTollableBlock(ZSign.getBlockOn(location).getLocation()); if(costBlockLocation == null) costBlockLocation = getTollableBlock(location); if(costBlockLocation == null) return null; String[] flags = lines[2].split("\\s"); if(lines[3] == null) return null; return new ZTollSign(level, location, costBlockLocation, price, lines[3], flags); } private boolean canBeUsed() { boolean usable = true; if(active && !opposite && useableOnce) usable = false; else if(!active && opposite && useableOnce) usable = false; return usable; } public Block getCostBlock() { if(costBlockLocation != null) return LocationSer.convertToBukkitLocation(costBlockLocation).getBlock(); return null; } public String getName() { return name; } private static LocationSer getTollableBlock(Location pos) { BlockFace[] verticalFaces = new BlockFace[] {BlockFace.UP, BlockFace.SELF, BlockFace.DOWN}; BlockFace[] horizontalFaces = new BlockFace[] {BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.SELF}; for (BlockFace bf : verticalFaces) { Block current = pos.getBlock().getRelative(bf); for (BlockFace bf2 : horizontalFaces) { if (current.getRelative(bf2).getType() == Material.LEVER || current.getRelative(bf2).getType() == Material.WOODEN_DOOR || current.getRelative(bf2).getType() == Material.TRAP_DOOR || current.getRelative(bf2).getType() == Material.WOOD_BUTTON || current.getRelative(bf2).getType() == Material.STONE_BUTTON || current.getRelative(bf2).getType() == Material.IRON_DOOR_BLOCK) { return LocationSer.convertFromBukkitLocation(current.getRelative(bf2).getLocation()); } } } return null; } @Override public boolean executeClick(Player player) { Block costBlock = getCostBlock(); net.minecraft.server.v1_7_R1.World nmsWorld = ((CraftWorld) costBlock.getWorld()).getHandle(); net.minecraft.server.v1_7_R1.Block nmsBlock = nmsWorld.getType(costBlock.getX(), costBlock.getY(), costBlock.getZ()); EntityPlayer nmsPlayer = ((CraftPlayer) player).getHandle(); switch(costBlock.getType()) { case WOODEN_DOOR: case IRON_DOOR: case IRON_DOOR_BLOCK: if(!active && canBeUsed()) { ((BlockDoor) nmsBlock).setDoor(nmsWorld, costBlock.getX(), costBlock.getY(), costBlock.getZ(), true); active = true; } else if(active && canBeUsed()) { ((BlockDoor) nmsBlock).setDoor(nmsWorld, costBlock.getX(), costBlock.getY(), costBlock.getZ(), false); active = false; } else return false; return true; case TRAP_DOOR: if(!active && canBeUsed()) { ((BlockTrapdoor) nmsBlock).setOpen(nmsWorld, costBlock.getX(), costBlock.getY(), costBlock.getZ(), true); active = true; } else if(active && canBeUsed()) { ((BlockTrapdoor) nmsBlock).setOpen(nmsWorld, costBlock.getX(), costBlock.getY(), costBlock.getZ(), false); active = false; } else return false; return true; case LEVER: if(!active && canBeUsed()) { nmsBlock.interact(nmsWorld, costBlock.getX(), costBlock.getY(), costBlock.getZ(), nmsPlayer, 0, 0f, 0f, 0f); active = true; } else if(active && canBeUsed()) { nmsBlock.interact(nmsWorld, costBlock.getX(), costBlock.getY(), costBlock.getZ(), nmsPlayer, 0, 0f, 0f, 0f); active = false; } else return false; return true; case STONE_BUTTON: case WOOD_BUTTON: if(canBeUsed()) { nmsBlock.interact(nmsWorld, costBlock.getX(), costBlock.getY(), costBlock.getZ(), nmsPlayer, 0, 0f, 0f, 0f); active = true; } else return false; return true; default: return false; } } public boolean isActive() { return active; } public boolean isOpposite() { return opposite; } public boolean isNoReset() { return noReset; } public boolean isUseableOnce() { return useableOnce; } public void reload() { if(!(getLocation().getBlock().getState() instanceof Sign)) { ZArena.log(Level.INFO, "The sign at "+location.toString()+" has been removed due to it's sign having been removed;"); getLevel().removeZSign(this); return; } if(getCostBlock() == null) { costBlockLocation = getTollableBlock(ZSign.getBlockOn(getSign().getLocation()).getLocation()); if(getCostBlock() == null) costBlockLocation = getTollableBlock(getLocation()); if(getCostBlock() == null) { ZArena.log(Level.INFO, "The sign at "+location.toString()+" has been removed due to the block it tolls having been removed."); getLevel().removeZSign(this); } } } public void resetCostBlock() { if(noReset) return; Block costBlock = getCostBlock(); if(costBlock == null) return; net.minecraft.server.v1_7_R1.World nmsWorld = ((CraftWorld) costBlock.getWorld()).getHandle(); net.minecraft.server.v1_7_R1.Block nmsBlock = nmsWorld.getType(costBlock.getX(), costBlock.getY(), costBlock.getZ()); switch(costBlock.getType()) { case WOODEN_DOOR: case IRON_DOOR: case IRON_DOOR_BLOCK: ((BlockDoor) nmsBlock).setDoor(nmsWorld, costBlock.getX(), costBlock.getY(), costBlock.getZ(), opposite); active = opposite; break; case TRAP_DOOR: ((BlockTrapdoor) nmsBlock).setOpen(nmsWorld, costBlock.getX(), costBlock.getY(), costBlock.getZ(), opposite); active = opposite; break; case LEVER: if(8 - (nmsWorld.getData(costBlock.getX(), costBlock.getY(), costBlock.getZ()) & 8) != 8 && !opposite) nmsBlock.interact(nmsWorld, costBlock.getX(), costBlock.getY(), costBlock.getZ(), null, 0, 0f, 0f, 0f); else if(8 - (nmsWorld.getData(costBlock.getX(), costBlock.getY(), costBlock.getZ()) & 8) == 8 && opposite) nmsBlock.interact(nmsWorld, costBlock.getX(), costBlock.getY(), costBlock.getZ(), null, 0, 0f, 0f, 0f); active = opposite; break; case STONE_BUTTON: case WOOD_BUTTON: active = opposite; break; default: } } public void setNoReset(boolean noReset) { this.noReset = noReset; } public void setOpposite(boolean opposite) { this.opposite = opposite; } public void setUseableOnce(boolean usable) { useableOnce = usable; } @SuppressWarnings("unchecked") @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); int ver = in.readInt(); if(ver == 0) { costBlockLocation = (LocationSer) in.readObject(); active = false; name = generateString(new Random(), "abcdefghigsadjas", 10); zSpawns = new ArrayList<String>(); useableOnce = false; } else if(ver == 1) { costBlockLocation = (LocationSer) in.readObject(); active = in.readBoolean(); name = in.readUTF(); zSpawns = new ArrayList<String>(); useableOnce = false; } else if(ver == 2) { costBlockLocation = (LocationSer) in.readObject(); active = in.readBoolean(); name = in.readUTF(); oldZSpawns = (List<LocationSer>) in.readObject(); zSpawns = new ArrayList<String>(); useableOnce = false; } else if(ver == 3) { costBlockLocation = (LocationSer) in.readObject(); active = in.readBoolean(); name = in.readUTF(); oldZSpawns = (List<LocationSer>) in.readObject(); zSpawns = new ArrayList<String>(); useableOnce = in.readBoolean(); } else if(ver == 4) { costBlockLocation = (LocationSer) in.readObject(); active = in.readBoolean(); name = in.readUTF(); zSpawns = (List<String>) in.readObject(); useableOnce = in.readBoolean(); } else { ZArena.log(Level.WARNING, "An unsupported version of a ZTollSign failed to load."); ZArena.log(Level.WARNING, "The ZSign at: "+location.toString()+" may not be operational."); } } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeInt(VERSION); out.writeObject(costBlockLocation); out.writeBoolean(active); out.writeUTF(name); out.writeObject(zSpawns); out.writeBoolean(useableOnce); } private static String generateString(Random rng, String characters, int length) { char[] text = new char[length]; for (int i = 0; i < length; i++) { text[i] = characters.charAt(rng.nextInt(characters.length())); } return new String(text); } @Override public Map<String, Object> serialize() { Map<String, Object> map = super.serialize(); map.put("Name", name); map.put("Tolled Block Location", costBlockLocation); map.put("Useable Once", useableOnce); map.put("Opposite", opposite); map.put("No Reset", noReset); map.put("Active", active); String allZSpawns = ""; for(String name : zSpawns) { allZSpawns += name + ","; } if(!allZSpawns.isEmpty()) allZSpawns = allZSpawns.substring(0, allZSpawns.length() - 1); map.put("ZSpawns", allZSpawns); map.put("Class", ZTollSign.class.getName()); return map; } @SuppressWarnings("unchecked") public static ZTollSign deserialize(Map<String, Object> map) { ZTollSign tollSign = new ZTollSign(); tollSign.level = (String) map.get("Level"); tollSign.location = (LocationSer) map.get("Location"); tollSign.price = (Integer) map.get("Price"); tollSign.name = (String) map.get("Name"); tollSign.costBlockLocation = (LocationSer) map.get("Tolled Block Location"); tollSign.useableOnce = (Boolean) map.get("Useable Once"); tollSign.opposite = (Boolean) map.get("Opposite"); tollSign.noReset = (Boolean) map.get("No Reset"); tollSign.active = (Boolean) map.get("Active"); String allZSpawns = (String) map.get("ZSpawns"); for(String zSpawn : allZSpawns.split(",")) { tollSign.zSpawns.add(zSpawn); } return tollSign; } }
mit
openforis/calc
calc-core/unused/AoiDimensionRecord.java
531
package org.openforis.calc.persistence.jooq.rolap; /** * * @author G. Miceli * */ public abstract class AoiDimensionRecord extends HierarchicalDimensionRecord<AoiDimensionRecord> { private static final long serialVersionUID = 1L; AoiDimensionRecord(AoiDimensionTable table) { super(table); } public Integer getParentId() { return getValue(((AoiDimensionTable)getTable()).PARENT_ID); } public void setParentId(Integer id) { setValue(((AoiDimensionTable)getTable()).PARENT_ID, id); } }
mit
QVDev/BlendleSDK
Android/SDK/blendleandroidsdk/src/main/java/com/sdk/blendle/models/generated/user/Follows.java
1270
package com.sdk.blendle.models.generated.user; import javax.annotation.Generated; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; @Generated("org.jsonschema2pojo") public class Follows { @SerializedName("href") @Expose private String href; /** * * @return * The href */ public String getHref() { return href; } /** * * @param href * The href */ public void setHref(String href) { this.href = href; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } @Override public int hashCode() { return new HashCodeBuilder().append(href).toHashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other instanceof Follows) == false) { return false; } Follows rhs = ((Follows) other); return new EqualsBuilder().append(href, rhs.href).isEquals(); } }
mit
rchumarin/java-course-ee
Spring/GS_Spring_9_Resource/src/main/java/edu/javacourse/spring/resource/SimpleBean.java
305
package edu.javacourse.spring.resource; import org.springframework.core.io.Resource; public class SimpleBean { private Resource template; public Resource getTemplate() { return template; } public void setTemplate(Resource template) { this.template = template; } }
mit
jonathansotoan/RealidadAumentada
src/realidadaumentada/SmoothMatrix.java
1790
package realidadaumentada; // SmoothMatrix.java // Andrew Davison, ad@fivedots.coe.psu.ac.th, April 2010 /* To reduce shaking of model due to slight variations in calculaed rotations and positions in the transformation matrix. */ import java.util.*; import javax.media.j3d.*; import javax.vecmath.*; import jp.nyatla.nyartoolkit.core.transmat.NyARTransMatResult; public class SmoothMatrix { private final static int MAX_SIZE = 10; private ArrayList<Matrix4d> matsStore; private int numMats = 0; public SmoothMatrix() { matsStore = new ArrayList<Matrix4d>(); } // end of SmoothMatrix() public boolean add(NyARTransMatResult transMat) { Matrix4d mat = new Matrix4d(-transMat.m00, -transMat.m01, -transMat.m02, -transMat.m03, -transMat.m10, -transMat.m11, -transMat.m12, -transMat.m13, transMat.m20, transMat.m21, transMat.m22, transMat.m23, 0, 0, 0, 1 ); Transform3D t3d = new Transform3D(mat); int flags = t3d.getType(); if ((flags & Transform3D.AFFINE) == 0) { System.out.println("Not adding a non-affine matrix"); return false; } else { if (numMats == MAX_SIZE) { matsStore.remove(0); // remove oldest numMats--; } matsStore.add(mat); // add at end of list numMats++; return true; } } // end of add() public Matrix4d get() // average matricies in store { if (numMats == 0) return null; Matrix4d avMat = new Matrix4d(); for(Matrix4d mat : matsStore) avMat.add(mat); avMat.mul( 1.0/numMats ); return avMat; } // end of get() } // end of SmoothMatrix class
mit
banadiga/sandbox
concurrent/src/main/java/com/banadiga/concurrent/invoke/FixedThreadPool.java
1225
package com.banadiga.concurrent.invoke; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class FixedThreadPool implements IExecutor { private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2); private Set<Callable<String>> callables = new HashSet<Callable<String>>(); public FixedThreadPool() { callables.add(new MyInvokeCallable("c-01")); callables.add(new MyInvokeCallable("c-02")); callables.add(new MyInvokeCallable("c-03")); callables.add(new MyInvokeCallable("c-04")); callables.add(new MyInvokeCallable("c-05")); callables.add(new MyInvokeCallable("c-06")); } @Override public String runAny() throws ExecutionException, InterruptedException { return fixedThreadPool.invokeAny(callables); } @Override public List<Future<String>> runAll() throws ExecutionException, InterruptedException { return fixedThreadPool.invokeAll(callables); } @Override public void close() { fixedThreadPool.shutdown(); } }
mit
caricsvk/sb-utils
src/main/java/milo/utils/eventstore/models/IncomingEvent.java
634
package milo.utils.eventstore.models; import milo.utils.rest.jaxbadapters.LocalDateTimeToString; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.time.LocalDateTime; public abstract class IncomingEvent implements Event { private LocalDateTime created; public IncomingEvent() { created = LocalDateTime.now(); } @Override public String getEventName() { return this.getClass().getSimpleName(); } @Override @XmlJavaTypeAdapter(LocalDateTimeToString.class) public LocalDateTime getCreated() { return created; } public void setCreated(LocalDateTime created) { this.created = created; } }
mit
karim/adila
database/src/main/java/adila/db/ns2dp10a6100_ns2dp10a6100.java
245
// This file is automatically generated. package adila.db; /* * Insignia NS-P10A6100 * * DEVICE: NS-P10A6100 * MODEL: NS-P10A6100 */ final class ns2dp10a6100_ns2dp10a6100 { public static final String DATA = "Insignia|NS-P10A6100|"; }
mit
karim/adila
database/src/main/java/adila/db/on7xelte_sm2dg610f.java
234
// This file is automatically generated. package adila.db; /* * Samsung Galaxy On Nxt * * DEVICE: on7xelte * MODEL: SM-G610F */ final class on7xelte_sm2dg610f { public static final String DATA = "Samsung|Galaxy On Nxt|"; }
mit
ivelin1936/Studing-SoftUni-
Java Fundamentals/Java OOP Advanced/Exercises - Reflection/src/pr0304Barracks/core/commands/RetireCommand.java
731
package pr0304Barracks.core.commands; import pr0304Barracks.contracts.Executable; import pr0304Barracks.contracts.Repository; import pr0304Barracks.core.annotations.Inject; public class RetireCommand implements Executable { private final String UNIT_RETIRED_MSG = "%s retired!"; @Inject private String[] data; @Inject private Repository repository; public RetireCommand() { } @Override public String execute() { String unitType = this.data[1]; try { this.repository.removeUnit(unitType); } catch (IllegalArgumentException iae) { return iae.getLocalizedMessage(); } return String.format(UNIT_RETIRED_MSG, unitType); } }
mit
Jivings/doppio
test/Dup.java
1079
package test; public class Dup { public static void main(String[] args) { // do it twice so we know the adding was done correctly in the first call System.out.println(dup2()); System.out.println(dup2()); DupMore d = new DupMore(); System.out.println(d.dup2_x1()); System.out.println(d.dup2_x1()); System.out.println(d.dup2_x2()); System.out.println(d.dup2_x2()); System.out.println(d.dup_x2()); System.out.println(d.dup_x2()); } private static long longValue = 5; // this function generates the dup2 instruction public static long dup2() { return longValue++; } } class DupMore { private long longValue = 4; private long[] longArr = { 1 }; // since this is not static, the 'this' operand causes javac to generate dup_x1 public long dup2_x1() { return longValue++; } void popLong(long a) {} // the array ref operand makes this a dup_x2 public long dup2_x2() { return longArr[0]++; } private static int intArr[] = { 4 }; public static int dup_x2() { return intArr[0]++; } }
mit
fundacionjala/enforce-sonarqube-plugin
sonar-apex-plugin/src/test/java/org/fundacionjala/enforce/sonarqube/apex/ApexTest.java
1205
/* * Copyright (c) Fundacion Jala. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ package org.fundacionjala.enforce.sonarqube.apex; import com.google.common.collect.Maps; import org.junit.Before; import org.junit.Test; import org.sonar.api.config.Settings; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class ApexTest { private Apex apexLanguage; @Before public void setup() { apexLanguage = new Apex(new Settings()); } @Test public void testApexProperties() { assertThat(apexLanguage.getKey(), is("apex")); assertThat(apexLanguage.getName(), is("Apex")); assertThat(apexLanguage.getFileSuffixes(), is(new String[]{"cls", "trigger"})); } @Test public void testCustomFileSuffixes() { Map<String, String> props = Maps.newHashMap(); props.put(Apex.FILE_SUFFIXES_KEY, "cls,apex"); Settings settings = new Settings(); settings.addProperties(props); assertThat(apexLanguage.getFileSuffixes(), is(new String[]{"cls", "trigger"})); } }
mit
palatable/lambda
src/test/java/com/jnape/palatable/lambda/functions/builtin/fn8/LiftA7Test.java
529
package com.jnape.palatable.lambda.functions.builtin.fn8; import org.junit.Test; import static com.jnape.palatable.lambda.adt.Maybe.just; import static com.jnape.palatable.lambda.functions.builtin.fn8.LiftA7.liftA7; import static org.junit.Assert.assertEquals; public class LiftA7Test { @Test public void lifting() { assertEquals(just(28), liftA7((a, b, c, d, e, f, g) -> a + b + c + d + e + f + g, just(1), just(2), just(3), just(4), just(5), just(6), just(7))); } }
mit
Azure/azure-sdk-for-java
sdk/recoveryservices/azure-resourcemanager-recoveryservices/src/main/java/com/azure/resourcemanager/recoveryservices/fluent/package-info.java
326
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. /** Package containing the service clients for RecoveryServicesManagementClient. Recovery Services Client. */ package com.azure.resourcemanager.recoveryservices.fluent;
mit
eekie/bpm-poc
bpm-test/src/test/java/org/tails/bpm/test/ProcessIT.java
7070
package org.tails.bpm.test; import org.tails.bpm.test.conf.ApplicationConfiguration; import org.tails.bpmdsl.BpmAssertBuilderFactory; import org.activiti.engine.HistoryService; import org.activiti.engine.RuntimeService; import org.activiti.engine.history.HistoricActivityInstance; import org.activiti.engine.history.HistoricActivityInstanceQuery; import org.activiti.engine.history.HistoricProcessInstance; import org.activiti.engine.history.HistoricProcessInstanceQuery; import org.activiti.engine.runtime.Execution; import org.activiti.engine.runtime.ProcessInstance; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.concurrent.Callable; import java.util.function.BiConsumer; import java.util.function.Function; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { ApplicationConfiguration.class }) public class ProcessIT { @Autowired private RuntimeService runtimeService; @Autowired private HistoryService historyService; @Autowired private BpmTestUtil bpmTestUtil; private static final Logger logger = LoggerFactory.getLogger(ProcessIT.class); @Autowired private BpmAssertBuilderFactory bpmAssertFactory; @Before public void setup() { bpmTestUtil.deployProcess("/bpm", "MyProcess.bpmn20.xml", "myProcess"); bpmTestUtil.deployProcess("/bpm", "parentProcess.bpmn20.xml", "parentProcess"); } // https://community.alfresco.com/thread/216417-queries-from-start-executionlistener-on-first-user-task @Test public void testProcessIT() throws Exception { BiConsumer<String, Callable> waitWithElapsed = (label, callable) -> { Instant b = Instant.now(); try { callable.call(); } catch (Exception e) { e.printStackTrace(); } Instant e = Instant.now(); Duration timeElapsed = Duration.between(b, e); logger.info("waiting for {} took {} milliseconds", label, timeElapsed.toMillis()); }; logger.info("invoke process"); Instant b = Instant.now(); ProcessInstance pi = runtimeService.startProcessInstanceByKey("myProcess"); final String pid = pi.getId(); Assertions.assertThat(pi).isNotNull(); waitWithElapsed.accept("exclusivegateway2", () -> bpmTestUtil.waitForExecutionElementUnderProcess("exclusivegateway2", pid)); // waitWithElapsed.accept("servicetask1", () -> bpmTestUtil.waitForExecutionElementUnderProcess("servicetask1", pid)); // Assertions.assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId(pi.getId()).activityId("servicetask1").list()).hasSize(1); waitWithElapsed.accept("servicetask2",() -> bpmTestUtil.waitForExecutionElementUnderProcess("servicetask2", pid)); Assertions.assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId(pi.getId()).activityId("servicetask2").list()).hasSize(1); ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(pid).singleResult(); Execution execution = runtimeService.createExecutionQuery().processInstanceId(pid).singleResult(); logger.info(execution.toString()); // bpmTestUtil.waitForProcessInstanceToComplete(pid); // Instant e = Instant.now(); // Duration timeElapsed = Duration.between(b, e); // logger.info("process elapsed time: " + timeElapsed.toMillis()); } @Test public void testParentProcess() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("parentProcess"); final String pid = pi.getId(); logger.info("invoked parent process with pid " + pid); Assertions.assertThat(pi).isNotNull(); ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().superProcessInstanceId(pid).singleResult(); logger.info(""); } @Test public void testWithDsl() throws Exception { //List<Execution> servicetask1 = runtimeService.createExecutionQuery().processInstanceId(pi.getId()) .activityId("servicetask1").list(); //LOG.info(servicetask1.toString()); //servicetask1 = runtimeService.createExecutionQuery().processInstanceId(pi.getId()).activityId("servicetask1").list(); // ResponseEntity<RSResponse> rsResponseResponseEntity = supplyEndService.startSupplyEnd(createSupplyEndRequest(false)); // String processInstanceId = rsResponseResponseEntity.getBody().getBpmRequestId(); ProcessInstance pi = runtimeService.startProcessInstanceByKey("myProcess"); String pid = pi.getId(); //bpmTestUtil.waitForProcessInstanceToComplete(pid); // 1 bpmAssertFactory.instance() .queryProcess() .byProcessInstanceId(pid) .result() .assertSize(1) .assertEnded(); // // 1.1 Function<HistoricProcessInstanceQuery, List<HistoricProcessInstance>> pQry = qry -> qry.list(); Function<HistoricActivityInstanceQuery, List<HistoricActivityInstance>> aQry = qry -> qry.list(); List<HistoricProcessInstance> apply = pQry.apply(historyService.createHistoricProcessInstanceQuery().processInstanceId(pid)); // List<HistoricProcessInstance> apply1 = pQry.apply(historyService.createHistoricProcessInstanceQuery().superProcessInstanceId(pid)); // List<HistoricActivityInstance> apply2 = aQry.apply(historyService.createHistoricActivityInstanceQuery().processInstanceId(apply1.get(0).getId())); // System.out.println(apply2.size()); // bpmAssertFactory.instance().processQrySupplier.get().processInstanceId(pid); // // // 2 List<HistoricProcessInstance> result = bpmAssertFactory.instance() .queryProcess() .byProcessInstanceId(pid) .listHistoricProceses(); Assertions.assertThat(result) .hasSize(1) .extracting(historicProcessInstance -> historicProcessInstance.getEndTime() != null); // // List<HistoricProcessInstance> subprocesses = bpmAssertFactory.instance() // .queryProcess() // .subprocessesFor(processInstanceId) // .listHistoricProceses(); // // Assertions.assertThat(subprocesses) // .hasSize(1) // .filteredOn(historicProcessInstance -> historicProcessInstance.getProcessDefinitionKey().equals(PROCESS_ENERGYCOMM_SUPPLY_END_REQUEST) ) // .isNotEmpty() // .extracting(HistoricProcessInstance::getEndTime).containsNull() // // open process // ; } }
mit
Volune/java-functions
src/main/java/net/volune/functions/Consumers.java
2995
package net.volune.functions; import java.util.function.BiConsumer; import java.util.function.Consumer; /** * Provides utility functions for method references that are intended not to return anything. */ public class Consumers { //Not instantiable private Consumers() { } /** * Reorder arguments of the given method reference <code>arg1,arg2 -&gt; arg1,arg2</code>. * <p> * Does actually nothing because the arguments are still used in the same order. * * @param consumer the method reference to be wrapped * @return the given consumer */ public static <T> BiConsumer<T, T> apply12(BiConsumer<T, T> consumer) { return consumer; } /** * Reorder arguments of the given method reference <code>arg1,arg2 -&gt; arg2,arg1</code>. * <p> * Arguments are swapped. * * @param consumer the method reference to be wrapped * @return a new method reference that calls the given one with rearranged arguments */ public static <T> BiConsumer<T, T> apply21(BiConsumer<T, T> consumer) { return (arg1, arg2) -> consumer.accept(arg2, arg1); } /** * Reorder arguments of the given method reference <code>arg1,arg2 -&gt; arg1,arg1</code>. * <p> * The second argument is ignored. * * @param consumer the method reference to be wrapped * @return a new method reference that calls the given one with rearranged arguments */ public static <T> BiConsumer<T, T> apply11(BiConsumer<T, T> consumer) { return (arg1, arg2) -> consumer.accept(arg1, arg1); } /** * Reorder arguments of the given method reference <code>arg1,arg2 -&gt; arg2,arg2</code>. * <p> * The first argument is ignored. * * @param consumer the method reference to be wrapped * @return a new method reference that calls the given one with rearranged arguments */ public static <T> BiConsumer<T, T> apply22(BiConsumer<T, T> consumer) { return (arg1, arg2) -> consumer.accept(arg2, arg2); } /** * Bind a given value as the first argument of a given method reference. * * @param consumer the method reference to be wrapped * @param arg1 the value to bind as the first argument * @return a new method reference that calls the given one with a bound argument */ public static <T, U, A1 extends T> Consumer<U> bind1(BiConsumer<T, U> consumer, A1 arg1) { return (arg2) -> consumer.accept(arg1, arg2); } /** * Bind a given value as the second argument of a given method reference. * * @param consumer the method reference to be wrapped * @param arg2 the value to bind as the second argument * @return a new method reference that calls the given one with a bound argument */ public static <T, U, A2 extends U> Consumer<T> bind2(BiConsumer<T, U> consumer, A2 arg2) { return (arg1) -> consumer.accept(arg1, arg2); } }
mit
hitchh1k3r/JavaGameEngine
src/com/hitchh1k3rsguide/gameEngine/utilities/physics/AxisAlignedBoundingBox.java
2007
package com.hitchh1k3rsguide.gameEngine.utilities.physics; public class AxisAlignedBoundingBox extends AbstractBoundingVolume { Vec2d center, radius; public AxisAlignedBoundingBox(double x, double y, double width, double height) { center = new Vec2d(x, y); radius = new Vec2d(width / 2, height / 2); } @Override public AxisAlignedBoundingBox getSweepBounds() { return this; } public double getMinX() { return center.x - radius.x; } public double getMaxX() { return center.x + radius.x; } public double getMinY() { return center.y - radius.y; } public double getMaxY() { return center.y + radius.y; } public boolean isColliding(AxisAlignedBoundingBox other) { return (Math.abs(center.x - other.center.x) < radius.x + other.radius.x) && (Math.abs(center.y - other.center.y) < radius.y + other.radius.y); } public boolean isInside(Vec2d point) { return (Math.abs(center.x - point.x) < radius.x) && (Math.abs(center.y - point.y) < radius.y); } public OrientedBoundingBox toOBB() { return new OrientedBoundingBox(center.x, center.y, radius.x * 2, radius.y * 2, 0); } public Vec2d getCorner(int i) // 0 TL, 1 TR, 2 BR, 3 BL { switch (i) { case 0: return new Vec2d(center.x - radius.x, center.y - radius.y); case 1: return new Vec2d(center.x + radius.x, center.y - radius.y); case 2: return new Vec2d(center.x + radius.x, center.y + radius.y); case 3: return new Vec2d(center.x - radius.x, center.y + radius.y); } return null; } public void setCenter(double x, double y) { center.x = x; center.y = y; } public void setCenter(Vec2d center) { this.center = center; } }
mit
rails-school/tiramisu
app/src/main/java/org/railsschool/tiramisu/views/helpers/AnimationHelper.java
418
package org.railsschool.tiramisu.views.helpers; import android.view.View; import com.daimajia.androidanimations.library.Techniques; import com.daimajia.androidanimations.library.YoYo; /** * @class AnimationHelper * @brief */ public class AnimationHelper { public static void pressed(View view) { YoYo .with(Techniques.Pulse) .duration(500) .playOn(view); } }
mit
Nexters/Templater
Templater/src/main/java/com/templater/test/TestRepository.java
387
package com.templater.test; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository public interface TestRepository extends JpaRepository<TestEntity, Integer>{ @Query(value="select t from TestEntity t") List<TestEntity> findTest(); }
mit
ydasilva/Gavel
Gavel-Project/app/src/test/java/com/psyphertxt/gavel_project/ExampleUnitTest.java
321
package com.psyphertxt.gavel_project; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
mit
piotrkot/XCompiler
server/src/main/java/com/github/piotrkot/core/Maven.java
4282
/** * The MIT License (MIT) * * Copyright (c) 2015 piotrkot * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.piotrkot.core; import com.github.piotrkot.api.PersistentLogs; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Optional; import lombok.extern.slf4j.Slf4j; import org.apache.maven.shared.invoker.DefaultInvocationRequest; import org.apache.maven.shared.invoker.DefaultInvoker; import org.apache.maven.shared.invoker.InvocationRequest; import org.apache.maven.shared.invoker.InvocationResult; import org.apache.maven.shared.invoker.Invoker; import org.apache.maven.shared.invoker.MavenInvocationException; /** * Maven build. * @author Piotr Kotlicki (piotr.kotlicki@gmail.com) * @version $Id$ * @since 1.0 */ @Slf4j public final class Maven { /** * Maven project directory. */ private final transient Path dir; /** * Persistent log messages. */ private final transient PersistentLogs logs; /** * Request id. */ private final transient int rqst; /** * Class constructor. * @param dblogs DB log messages. * @param request Request id. * @param directory Maven project directory. */ public Maven(final PersistentLogs dblogs, final int request, final Path directory) { this.logs = dblogs; this.rqst = request; this.dir = directory; } /** * Build of maven project. * @return Result of the build. */ public Optional<InvocationResult> build() { Optional<InvocationResult> result = Optional.empty(); final InvocationRequest request = new DefaultInvocationRequest(); if (this.pomFile().isPresent()) { request.setPomFile(this.pomFile().get().toFile()); request.setGoals(Collections.singletonList("test")); try { final Invoker invoker = new DefaultInvoker(); invoker.setOutputHandler( line -> this.logs.append(this.rqst, line) ); invoker.setErrorHandler( line -> this.logs.append(this.rqst, line) ); result = Optional.of(invoker.execute(request)); } catch (final MavenInvocationException ex) { log.error("Maven invocation failed", ex); this.logs.append(this.rqst, ex); } } else { final String mesg = "POM file not found"; log.info(mesg); this.logs.append(this.rqst, mesg); } return result; } /** * Searches for pom.xml file in the, presumably, project. * @return Path of pom.xml file. */ private Optional<Path> pomFile() { Optional<Path> pom = Optional.empty(); try { pom = Files.find( this.dir, Integer.MAX_VALUE, (path, attributes) -> "pom.xml".equals(path.toFile().getName()) ).findFirst(); } catch (final IOException ex) { log.error("Corrupted maven project", ex); this.logs.append(this.rqst, ex); } return pom; } }
mit
feroult/yawp
yawp-core/src/main/java/io/yawp/repository/FutureObjectHook.java
110
package io.yawp.repository; public interface FutureObjectHook<T> { void apply(Repository r, T object); }
mit
georghinkel/ttc2017smartGrids
solutions/ModelJoin/src/main/java/CIM/IEC61970/Meas/CurrentTransformer.java
8807
/** */ package CIM.IEC61970.Meas; import CIM.IEC61970.Core.Equipment; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Current Transformer</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link CIM.IEC61970.Meas.CurrentTransformer#getMaxRatio <em>Max Ratio</em>}</li> * <li>{@link CIM.IEC61970.Meas.CurrentTransformer#getCoreCount <em>Core Count</em>}</li> * <li>{@link CIM.IEC61970.Meas.CurrentTransformer#getCtClass <em>Ct Class</em>}</li> * <li>{@link CIM.IEC61970.Meas.CurrentTransformer#getUsage <em>Usage</em>}</li> * <li>{@link CIM.IEC61970.Meas.CurrentTransformer#getAccuracyLimit <em>Accuracy Limit</em>}</li> * <li>{@link CIM.IEC61970.Meas.CurrentTransformer#getAccuracyClass <em>Accuracy Class</em>}</li> * </ul> * * @see CIM.IEC61970.Meas.MeasPackage#getCurrentTransformer() * @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Instrument transformer used to measure electrical qualities of the circuit that is being protected and/or monitored. Typically used as current transducer for the purpose of metering or protection. A typical secondary current rating would be 5A.'" * annotation="http://langdale.com.au/2005/UML Profile\040documentation='Instrument transformer used to measure electrical qualities of the circuit that is being protected and/or monitored. Typically used as current transducer for the purpose of metering or protection. A typical secondary current rating would be 5A.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Instrument transformer used to measure electrical qualities of the circuit that is being protected and/or monitored. Typically used as current transducer for the purpose of metering or protection. A typical secondary current rating would be 5A.' Profile\040documentation='Instrument transformer used to measure electrical qualities of the circuit that is being protected and/or monitored. Typically used as current transducer for the purpose of metering or protection. A typical secondary current rating would be 5A.'" * @generated */ public interface CurrentTransformer extends Equipment { /** * Returns the value of the '<em><b>Max Ratio</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Max Ratio</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Max Ratio</em>' attribute. * @see #setMaxRatio(float) * @see CIM.IEC61970.Meas.MeasPackage#getCurrentTransformer_MaxRatio() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='For multi-ratio CT\'s, the maximum permissable ratio attainable.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='For multi-ratio CT\'s, the maximum permissable ratio attainable.'" * @generated */ float getMaxRatio(); /** * Sets the value of the '{@link CIM.IEC61970.Meas.CurrentTransformer#getMaxRatio <em>Max Ratio</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Max Ratio</em>' attribute. * @see #getMaxRatio() * @generated */ void setMaxRatio(float value); /** * Returns the value of the '<em><b>Core Count</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Core Count</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Core Count</em>' attribute. * @see #setCoreCount(int) * @see CIM.IEC61970.Meas.MeasPackage#getCurrentTransformer_CoreCount() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Number of cores.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Number of cores.'" * @generated */ int getCoreCount(); /** * Sets the value of the '{@link CIM.IEC61970.Meas.CurrentTransformer#getCoreCount <em>Core Count</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Core Count</em>' attribute. * @see #getCoreCount() * @generated */ void setCoreCount(int value); /** * Returns the value of the '<em><b>Ct Class</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Ct Class</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Ct Class</em>' attribute. * @see #setCtClass(String) * @see CIM.IEC61970.Meas.MeasPackage#getCurrentTransformer_CtClass() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='CT classification; i.e. class 10P.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='CT classification; i.e. class 10P.'" * @generated */ String getCtClass(); /** * Sets the value of the '{@link CIM.IEC61970.Meas.CurrentTransformer#getCtClass <em>Ct Class</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Ct Class</em>' attribute. * @see #getCtClass() * @generated */ void setCtClass(String value); /** * Returns the value of the '<em><b>Usage</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Usage</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Usage</em>' attribute. * @see #setUsage(String) * @see CIM.IEC61970.Meas.MeasPackage#getCurrentTransformer_Usage() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Intended usage of the CT; i.e. metering, protection.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Intended usage of the CT; i.e. metering, protection.'" * @generated */ String getUsage(); /** * Sets the value of the '{@link CIM.IEC61970.Meas.CurrentTransformer#getUsage <em>Usage</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Usage</em>' attribute. * @see #getUsage() * @generated */ void setUsage(String value); /** * Returns the value of the '<em><b>Accuracy Limit</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Accuracy Limit</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Accuracy Limit</em>' attribute. * @see #setAccuracyLimit(String) * @see CIM.IEC61970.Meas.MeasPackage#getCurrentTransformer_AccuracyLimit() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Percent of rated current for which the CT remains accurate within specified limits.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Percent of rated current for which the CT remains accurate within specified limits.'" * @generated */ String getAccuracyLimit(); /** * Sets the value of the '{@link CIM.IEC61970.Meas.CurrentTransformer#getAccuracyLimit <em>Accuracy Limit</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Accuracy Limit</em>' attribute. * @see #getAccuracyLimit() * @generated */ void setAccuracyLimit(String value); /** * Returns the value of the '<em><b>Accuracy Class</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Accuracy Class</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Accuracy Class</em>' attribute. * @see #setAccuracyClass(String) * @see CIM.IEC61970.Meas.MeasPackage#getCurrentTransformer_AccuracyClass() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='CT accuracy classification.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='CT accuracy classification.'" * @generated */ String getAccuracyClass(); /** * Sets the value of the '{@link CIM.IEC61970.Meas.CurrentTransformer#getAccuracyClass <em>Accuracy Class</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Accuracy Class</em>' attribute. * @see #getAccuracyClass() * @generated */ void setAccuracyClass(String value); } // CurrentTransformer
mit
Stoyicker/agile_group2
AgileAppModule/src/main/java/org/arnolds/agileappproject/agileappmodule/ui/frags/ArnoldSupportFragment.java
682
package org.arnolds.agileappproject.agileappmodule.ui.frags; import android.app.Activity; import android.support.v4.app.Fragment; import org.arnolds.agileappproject.agileappmodule.ui.activities.DrawerLayoutFragmentActivity; import org.arnolds.agileappproject.agileappmodule.utils.IRepositorySelectionSensitiveFragment; public abstract class ArnoldSupportFragment extends Fragment { private final int menuIndex; protected ArnoldSupportFragment(int _menuIndex) { menuIndex = _menuIndex; } public void onAttach(Activity activity) { super.onAttach(activity); ((DrawerLayoutFragmentActivity) activity).onSectionAttached(menuIndex); } }
mit
jwiesel/sfdcCommander
sfdcCommander/src/main/java/com/sforce/soap/partner/SetPassword.java
4756
/** * SetPassword.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.sforce.soap.partner; public class SetPassword implements java.io.Serializable { private java.lang.String userId; private java.lang.String password; public SetPassword() { } public SetPassword( java.lang.String userId, java.lang.String password) { this.userId = userId; this.password = password; } /** * Gets the userId value for this SetPassword. * * @return userId */ public java.lang.String getUserId() { return userId; } /** * Sets the userId value for this SetPassword. * * @param userId */ public void setUserId(java.lang.String userId) { this.userId = userId; } /** * Gets the password value for this SetPassword. * * @return password */ public java.lang.String getPassword() { return password; } /** * Sets the password value for this SetPassword. * * @param password */ public void setPassword(java.lang.String password) { this.password = password; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof SetPassword)) return false; SetPassword other = (SetPassword) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.userId==null && other.getUserId()==null) || (this.userId!=null && this.userId.equals(other.getUserId()))) && ((this.password==null && other.getPassword()==null) || (this.password!=null && this.password.equals(other.getPassword()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getUserId() != null) { _hashCode += getUserId().hashCode(); } if (getPassword() != null) { _hashCode += getPassword().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(SetPassword.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", ">setPassword")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("userId"); elemField.setXmlName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "userId")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("password"); elemField.setXmlName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "password")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
mit
rjwboys/General
src/net/craftstars/general/items/Items.java
19117
package net.craftstars.general.items; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.material.MaterialData; import org.bukkit.potion.Potion; import org.bukkit.potion.Potion.Tier; import org.bukkit.potion.PotionType; import net.craftstars.general.General; import net.craftstars.general.option.Options; import net.craftstars.general.text.LanguageText; import net.craftstars.general.text.Messaging; import net.craftstars.general.util.Toolbox; import net.craftstars.general.util.range.IntRange; import net.craftstars.general.util.range.Range; public final class Items { private static FileConfiguration config; private static File configFile; private static HashMap<String, ItemID> aliases; private static HashMap<ItemID, String> names; private static HashMap<String, ItemID> hooks; private static ConfigurationSection potions; private Items() {} public static void save() { for(String alias : aliases.keySet()) { ItemID item = aliases.get(alias); String code = Integer.toString(item.getId()); if(item.getData() != null) code += "/" + item.getData(); config.set("aliases." + alias, code); } HashMap<Integer, TreeSet<ItemID>> tmpList = new HashMap<Integer, TreeSet<ItemID>>(); for(ItemID item : names.keySet()) { int id = item.getId(); if(!tmpList.containsKey(id)) { tmpList.put(id, new TreeSet<ItemID>()); } tmpList.get(id).add(item); } for(int id : tmpList.keySet()) { String key = "names.item" + id; if(tmpList.get(id).size() == 1) config.set(key, names.get(tmpList.get(id).first())); else { HashMap<String,String> theseNames = new HashMap<String,String>(); for(ItemID item : tmpList.get(id)) { if(item.getData() == null) { theseNames.put("generic",names.get(item)); break; // even if there are further entries, they are anomalies and we don't care about them // Actually, having further entries at this point would be a bug since IDs with null data // compare higher than IDs with non-null data. } else theseNames.put("data" + item.getData(), names.get(item)); } config.set(key, theseNames); } } final int NAME = 0, TYPE = 1; for(String hook : hooks.keySet()) { String[] split = hook.split(":"); String key = "hooks." + split[NAME] + "." + split[TYPE]; ItemID item = hooks.get(hook); String code = Integer.toString(item.getId()); if(item.getData() != null) code += "/" + item.getData(); config.set(key, code); } config.set("names.potions", potions); try { config.save(configFile); } catch(IOException e) { e.printStackTrace(); } } private static void loadConfig() { try { File dataFolder = General.plugin.getDataFolder(); if(!dataFolder.exists()) dataFolder.mkdirs(); configFile = new File(dataFolder, "items.yml"); if(!configFile.exists()) General.createDefaultConfig(configFile); config = YamlConfiguration.loadConfiguration(configFile); } catch(Exception ex) { General.logger.warn(LanguageText.LOG_CONFIG_ERROR.value("file", "items.yml"), ex); } } public static void setup() { loadConfig(); aliases = new HashMap<String, ItemID>(); names = new HashMap<ItemID, String>(); // This loads in the item names from items.yml loadItemNames(); // try { loadItemAliases(); // } catch(Exception x) { // General.logger.error(x.getMessage()); // } // Load the "hooks" as well. loadHooks(); potions = config.getConfigurationSection("names.potions"); // Check if classes have been overridden. for(Material mat : Material.values()) { int id = mat.getId(); String clsName = config.getString("variants.item" + id + ".class"); if(clsName != null) { try { Class<?> cls = Class.forName(clsName); if(cls != null && ItemData.class.isAssignableFrom(cls)) { @SuppressWarnings("unchecked") Class<? extends ItemData> dataClass = (Class<? extends ItemData>)cls; ItemData.register(mat, dataClass); } } catch(ClassNotFoundException e) { //e.printStackTrace(); } } } } private static void loadHooks() { hooks = new HashMap<String, ItemID>(); try { for(String key : config.getConfigurationSection("hooks").getKeys(false)) { for(String val : config.getConfigurationSection("hooks." + key).getKeys(false)) { String x = config.getConfigurationSection("hooks." + key).getString(val); ItemID thisItem = Items.validate(x); if(thisItem == null) { General.logger.warn(LanguageText.LOG_ITEM_BAD_HOOK.value("hook", x)); } else { hooks.put(key + ":" + val, thisItem); } } } } catch(NullPointerException x) { General.logger.warn(LanguageText.LOG_ITEM_NO_HOOKS.value()); } } private static Pattern itemPat = Pattern.compile("([0-9]+)(?:[.,:/|]([0-9]+))?"); private static void loadItemAliases() { ConfigurationSection aliasSection = config.getConfigurationSection("aliases"); if(aliasSection == null) { General.logger.warn(LanguageText.LOG_ITEM_NO_ALIASES.value()); return; } Set<String> ymlAliases = aliasSection.getKeys(false); for(String alias : ymlAliases) { ItemID val; String code = config.getString("aliases." + alias); if(code == null) { General.logger.warn(LanguageText.LOG_ITEM_BAD_KEY.value()); continue; } Matcher m = itemPat.matcher(code); if(!m.matches()) continue; int num = 0, data; boolean problem = false; try { num = Integer.valueOf(m.group(1)); } catch(NumberFormatException x) { problem = true; } if(m.groupCount() > 1 && m.group(2) != null) { try { data = Integer.valueOf(m.group(2)); } catch(NumberFormatException x) { General.logger.warn(LanguageText.LOG_ITEM_BAD_ALIAS.value("alias", m.group(1) + ":" + m.group(2))); continue; } val = new ItemID(num, data); } else if(problem) { General.logger.warn(LanguageText.LOG_ITEM_BAD_ALIAS.value("alias", m.group(1))); continue; } else val = new ItemID(num, null); aliases.put(alias, val); } } private static void loadItemNames() { int invalids = 0; String lastInvalid = null; Set<String> keys; try { keys = config.getConfigurationSection("names").getKeys(false); } catch(NullPointerException x) { General.logger.warn(LanguageText.LOG_ITEM_NO_NAMES.value()); return; } if(keys == null) { General.logger.warn(LanguageText.LOG_ITEM_BAD_NAMES.value()); } else { for(String id : keys) { if(!id.matches("xp|potions|(item|ench)[0-9]+")) { lastInvalid = id; invalids++; continue; } if(!id.startsWith("item")) continue; int num; ItemID key; String name; try { num = Integer.valueOf(id.substring(4)); } catch(NumberFormatException x) { lastInvalid = id; invalids++; continue; } String path = "names." + id; Object node = config.get(path); if(node instanceof String) { name = config.getString(path); key = new ItemID(num, null); names.put(key, name); } else { Set<String> list = config.getConfigurationSection(path).getKeys(false); for(String data : list) { name = config.getString(path + "." + data); if(data.matches("data[0-9]+")) { int d = Integer.parseInt(data.substring(4)); key = new ItemID(num, d); names.put(key, name); } else if(data.equals("generic")) { key = new ItemID(num, null); names.put(key, name); } } } } } if(invalids > 0) General.logger.warn(LanguageText.LOG_ITEM_BAD_NAME.value("count", invalids, "name", lastInvalid)); } public static String name() { return config.getString("names.xp", "xp"); } public static String name(Material item) { if(item == null) return ""; return name(ItemID.bare(item.getId(), null)); } public static String name(MaterialData item) { if(item == null) return ""; return name(ItemID.bare(item.getItemTypeId(), (int)item.getData())); } public static String name(ItemStack item) { if(item == null) return ""; return name(ItemID.bare(item.getTypeId(), (int)item.getDurability())); } /** * Returns the name of the item stored in the hashmap or the item name stored in the items.txt file in the hMod * folder. * * @param longKey The item ID and data * @return Canonical name */ public static String name(ItemID longKey) { if(longKey == null) return ""; if(names.containsKey(longKey)) { return names.get(longKey); } if(longKey.getMaterial() == Material.POTION && longKey.getData() != null) { return potionName(longKey.getData()); } // This is a redundant lookup if longKey already has null data, but that shouldn't create significant // overhead ItemID shortKey = longKey.clone().setData(null); if(names.containsKey(shortKey)) { return names.get(shortKey); } for(Material item : Material.values()) { if(item.getId() == longKey.getId()) { return Toolbox.formatItemName(item.toString()); } } return longKey.toString(); } public static String potionName(int data) { try { return name(Potion.fromDamage(data)); } catch(IllegalArgumentException e) { String name = potions.getString("name" + (data & 63), potions.getString("generic")); return formatPotionName(name, Tier.ONE, (data & 0x4000) > 0, (data & 0x40) > 0); } } public static String name(Potion potion) { PotionType type = potion.getType(), match = null; int i = 0; while(type != match) match = PotionType.getByDamageValue(++i); return formatPotionName(potions.getString("type" + i), potion.getTier(), potion.isSplash(), potion.hasExtendedDuration()); } private static String formatPotionName(String name, Tier tier, boolean splash, boolean extend) { name += potions.getString("tier" + (1 + tier.ordinal()), ""); if(extend) name += potions.getString("extend", ""); return Messaging.format(name, "potion", potions.getString(splash ? "splash" : "generic", "")); } public static String name(Enchantment ench) { String name = config.getString("names.ench" + ench.getId()); if(name == null) return ench.getName(); return name; } /** * Validate the string for an item * * Valid formats: * <ul> * <li>[ID]</li> * <li>[alias]</li> * <li>[richalias]</li> * <li>[ID]:[data]</li> * <li>[alias]:[data]</li> * <li>[ID]:[variant]</li> * <li>[alias]:[variant]</li> * <li>[hook]:[subset]</li> * </ul> * * Where : can be any of .,:/| and the variables are as follows: * <dl> * <dt>[ID]</dt> * <dd>the numeric ID of an item</dd> * <dt>[alias]</dt> * <dd>an alias for the item, as defined in items.db</dd> * <dt>[richalias]</dt> * <dd>an alias for the item combined with a data value, as defined in items.db</dd> * <dt>[data]</dt> * <dd>the numeric data value for the item</dd> * <dt>[variant]</dt> * <dd>a variant name for the item, as defined in the variants section of items.yml</dd> * <dt>[hook]</dt> * <dd>a hook name, as defined in the hooks section of items.yml</dd> * <dt>[subset]</dt> * <dd>a subset name, as defined in the hooks section of items.yml</dd> * </dl> * * @param item A string representing an item, either by name or by ID. * @return null if false, the 2-part ID if true; a data value of -1 if the item is valid but the data isn't */ public static ItemID validate(String item) { ItemID ret; // First figure out what the data and ID are. if(Pattern.matches("([a-zA-Z0-9_'-]+)", item)) { ret = validateShortItem(item); if(ret == null) throw new InvalidItemException(LanguageText.GIVE_BAD_ID); } else { try { String[] parts = item.split("[.,:/\\|]"); ret = validateLongItem(parts[0], parts[1]); } catch(ArrayIndexOutOfBoundsException x) { throw new InvalidItemException(LanguageText.GIVE_BAD_DATA, "data", "", "item", item.substring(0, item.length() - 1)); } } // Make sure it's the ID of a valid item. ret.validateId(); // Make sure the damage value is valid. ret.validateData(); return ret; } private static ItemID validateLongItem(String item, String data) { ItemID ret = validateShortItem(item); if(ret == null) { // If it wasn't valid as a short item, check the hooks. String key = item + ":" + data; if(hooks.containsKey(key)) { return hooks.get(key); } } else if(ret.getData() != null) { // This means a "richalias" was used, which includes the data value. // No data value is valid with a "richalias". throw new InvalidItemException(LanguageText.GIVE_BAD_DATA, "data", ret.getDataType().getParsed(), "item", ret.getName(null)); } else ret.setData(ret.getDataType().fromName(data)); if(ret == null) throw new InvalidItemException(LanguageText.GIVE_BAD_ID); return ret; } private static ItemID validateShortItem(String item) { ItemID ret = null; try { ret = new ItemID(Integer.valueOf(item)); } catch(NumberFormatException x) { if(aliases == null) General.logger.error("aliases is null"); else for(String alias : aliases.keySet()) { if(!alias.equalsIgnoreCase(item)) continue; ret = aliases.get(alias).clone(); } if(ret == null) { for(Material material : Material.values()) { String mat = material.toString(); if(mat.equalsIgnoreCase(item) || mat.replace("_", "-").equalsIgnoreCase(item) || mat.replace("_", "").equalsIgnoreCase(item)) { ret = new ItemID(material); } } } } if(ret == null) { // It might be xp List<String> xp = variantNames("xp"); for(String name : xp) { if(name.equalsIgnoreCase(item)) return ItemID.experience(); } } return ret; } public static int maxStackSize(int id) { return Material.getMaterial(id).getMaxStackSize(); } public static void giveItem(Player who, ItemID x, Integer amount, Map<Enchantment,Integer> ench) { if(x.getId() == ItemID.EXP) { who.giveExp(amount); return; } PlayerInventory i = who.getInventory(); HashMap<Integer, ItemStack> excess = i.addItem(x.getStack(amount, who, ench)); for(ItemStack leftover : excess.values()) who.getWorld().dropItemNaturally(who.getLocation(), leftover); } public static void setItemName(ItemID id, String name) { names.put(id, name); } public static List<String> variantNames(ItemID id) { if(id != null && id.getData() != null) return config.getStringList("variants.item" + id.getId() + ".type" + id.getData()); return null; } public static List<String> variantNames(String key) { if(key == null) return null; return config.getStringList("special." + key); } public static List<String> variantNames(String key, int data) { if(key != null) return config.getStringList("special." + key + ".type" + data); return null; } public static void addVariantName(ItemID id, String name) { if(id != null && id.getData() != null) { List<String> variants = variantNames(id); variants.add(name); setVariantNames(id, variants); } } public static void removeVariantName(ItemID id, String name) { if(id != null && id.getData() != null) { List<String> variants = variantNames(id); variants.remove(name); setVariantNames(id, variants); } } public static void setVariantNames(ItemID id, List<String> variants) { config.set("variants.item" + id.getId() + ".type" + id.getData(), variants); } public static void addAlias(String name, ItemID id) { aliases.put(name, id); } public static void removeAlias(String name) { aliases.remove(name); } public static ItemID getAlias(String name) { for(String x : aliases.keySet()) { if(x.equalsIgnoreCase(name)) return aliases.get(x); } return null; } public static ItemID getHook(String main, String sub) { return hooks.get(main + ":" + sub); } public static void setHook(String main, String sub, ItemID id) { hooks.put(main + ":" + sub, id); } public static boolean dataEquiv(ItemID id, int data) { if(ToolDamage.isDamageable(id.getId())) return true; if(id.getData() == null) return true; return data == id.getData(); } public static String getPersistentName(ItemID id) { Material material = Material.getMaterial(id.getId()); String itemName = material.toString(); if(id.getData() == null) return itemName; ItemData data = ItemData.getData(material); String dataName = data.getName(id.getData()); if(dataName.equals("0")) return itemName; return itemName + '/' + dataName; } public static List<String> setGroupItems(String groupName, List<String> groupItems) { ArrayList<Integer> items = new ArrayList<Integer>(); ArrayList<String> bad = new ArrayList<String>(); for(String item : groupItems) { try { ItemID thisItem = validate(item); items.add(thisItem.getId()); } catch(InvalidItemException e) { bad.add(item); } } Options.GROUP(groupName).set(items); return bad; } public static List<Integer> groupItems(String groupName) { return Options.GROUP(groupName).get(); } public static boolean addGroupItem(String groupName, String item) { List<Integer> group = groupItems(groupName); ItemID thisItem = validate(item); try { group.add(thisItem.getId()); } catch(InvalidItemException e) { return false; } Options.GROUP(groupName).set(group); return true; } public static boolean removeGroupItem(String groupName, String item) { List<Integer> group = groupItems(groupName); ItemID thisItem = validate(item); try { group.remove(thisItem.getId()); } catch(InvalidItemException e) { return false; } Options.GROUP(groupName).set(group); return true; } public static List<String> getPotions(String key) { return config.getStringList("variants." + key); } public static int getMaxData(Material mat) { int data = config.getInt("variants.item" + mat.getId() + ".max", -1); if(data == -1) return mat.getMaxDurability(); return 0; } public static Range<Integer> getDataRange(Material mat) { String range = config.getString("variants.item" + mat.getId() + ".range"); if(range == null) return null; return IntRange.parse(range); } public static List<Range<Integer>> getDataRanges(Material mat) { List<String> list = config.getStringList("variants.item" + mat.getId() + ".range"); if(list == null || list.isEmpty()) return null; List<Range<Integer>> ranges = new ArrayList<Range<Integer>>(); for(String range : list) { try { int n = Integer.parseInt(range); ranges.add(new IntRange(n)); } catch(NumberFormatException e) { ranges.add(IntRange.parse(range)); } } return ranges; } }
mit
tanmayghosh2507/LeetCode_Problems
src/backbrack/CombinationSum3.java
1001
package backbrack; import java.util.ArrayList; import java.util.List; public class CombinationSum3 { public static void main(String[] args) { CombinationSum3 combinationSum3 = new CombinationSum3(); List<Integer> temp = new ArrayList<Integer>(); List<List<Integer>> fin = new ArrayList<>(); temp.add(2); temp.add(4); fin.add(temp); combinationSum3.combinationSum3(1, 2); // Driver function. Show the results. } public List<List<Integer>> combinationSum3(int k, int n) { List<Integer> temp = new ArrayList<Integer>(); List<List<Integer>> fin = new ArrayList<>(); combinationRec(fin, temp, k, 1, n); return fin; } private void combinationRec(List<List<Integer>> fin, List<Integer> temp, int k, int start, int n) { if (temp.size() == k && n == 0) { List<Integer> li = new ArrayList<>(temp); fin.add(li); return; } for (int i = start; i <= 9; i++) { temp.add(i); combinationRec(fin, temp, k, i + 1, n - i); temp.remove(temp.size() - 1); } } }
mit
nico01f/z-pec
ZimbraSelenium/src/java/com/zimbra/qa/selenium/projects/desktop/tests/briefcase/file/OpenFile.java
3052
package com.zimbra.qa.selenium.projects.desktop.tests.briefcase.file; import org.testng.annotations.Test; import com.zimbra.qa.selenium.framework.items.FileItem; import com.zimbra.qa.selenium.framework.items.FolderItem; import com.zimbra.qa.selenium.framework.items.FolderItem.SystemFolder; import com.zimbra.qa.selenium.framework.ui.Action; import com.zimbra.qa.selenium.framework.ui.Button; import com.zimbra.qa.selenium.framework.util.GeneralUtility; import com.zimbra.qa.selenium.framework.util.HarnessException; import com.zimbra.qa.selenium.framework.util.ZAssert; import com.zimbra.qa.selenium.framework.util.ZimbraAccount; import com.zimbra.qa.selenium.framework.util.ZimbraSeleniumProperties; import com.zimbra.qa.selenium.projects.desktop.core.AjaxCommonTest; import com.zimbra.qa.selenium.projects.desktop.ui.briefcase.DocumentBriefcaseOpen; public class OpenFile extends AjaxCommonTest { public OpenFile() { logger.info("New " + OpenFile.class.getCanonicalName()); super.startingPage = app.zPageBriefcase; super.startingAccountPreferences = null; } @Test(description = "Upload file through RestUtil - open & verify through GUI", groups = { "smoke" }) public void OpenFile_01() throws HarnessException { ZimbraAccount account = app.zGetActiveAccount(); FolderItem briefcaseFolder = FolderItem.importFromSOAP(account, SystemFolder.Briefcase); // Create file item String filePath = ZimbraSeleniumProperties.getBaseDirectory() + "/data/public/other/testtextfile.txt"; FileItem fileItem = new FileItem(filePath); String fileName = fileItem.getName(); final String fileText = "test"; // Upload file to server through RestUtil String attachmentId = account.uploadFile(filePath); // Save uploaded file to briefcase through SOAP account.soapSend("<SaveDocumentRequest xmlns='urn:zimbraMail'>" + "<doc l='" + briefcaseFolder.getId() + "'><upload id='" + attachmentId + "'/></doc></SaveDocumentRequest>"); // refresh briefcase page app.zTreeBriefcase.zTreeItem(Action.A_LEFTCLICK, briefcaseFolder, true); // Click on created file GeneralUtility.syncDesktopToZcsWithSoap(app.zGetActiveAccount()); app.zPageBriefcase.zListItem(Action.A_LEFTCLICK, fileItem); // Click on open in a separate window icon in toolbar DocumentBriefcaseOpen documentBriefcaseOpen = (DocumentBriefcaseOpen) app.zPageBriefcase .zToolbarPressButton(Button.B_OPEN_IN_SEPARATE_WINDOW, fileItem); app.zPageBriefcase.isOpenFileLoaded(fileName, fileText); String text = ""; // Select document opened in a separate window try { app.zPageBriefcase.zSelectWindow(fileName); text = documentBriefcaseOpen.retriveFileText(); // close app.zPageBriefcase.zSelectWindow(fileName); app.zPageBriefcase.closeWindow(); } finally { app.zPageBriefcase.zSelectWindow("Zimbra: Briefcase"); } ZAssert.assertStringContains(text, fileText, "Verify document text through GUI"); // delete file upon test completion app.zPageBriefcase.deleteFileByName(fileItem.getName()); } }
mit
GaloisInc/Votail
external_tools/JML/org/jmlspecs/jmlunit/strategies/FloatAbstractFilteringStrategyDecorator.java
2988
// @(#)$Id: floatAbstractFilteringStrategyDecorator.java-generic,v 1.7 2005/12/24 21:20:31 chalin Exp $ // Copyright (C) 2005 Iowa State University // // This file is part of the runtime library of the Java Modeling Language. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2.1, // of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with JML; see the file LesserGPL.txt. If not, write to the Free // Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA // 02110-1301 USA. package org.jmlspecs.jmlunit.strategies; /** A decorator for strategies that filters out data that is not approved. * * @author Gary T. Leavens */ // FIXME: adapt this file to non-null-by-default and remove the following modifier. /*@ nullable_by_default @*/ public abstract class FloatAbstractFilteringStrategyDecorator extends FloatAbstractStrategy { /** The test data */ private final /*@ spec_public non_null@*/ FloatStrategyType rawData; //@ in objectState; maps rawData.objectState \into objectState; //@ public normal_behavior //@ requires strat != null; //@ assignable rawData; //@ ensures rawData == strat; public FloatAbstractFilteringStrategyDecorator (FloatStrategyType strat) { rawData = strat; } // doc comment and specification inherited public /*@ non_null @*/ FloatIterator floatIterator() { /** The filtering iterator to return, defined to allow for an * explicit constructor. */ class NewIter extends FloatAbstractFilteringIteratorDecorator { /** Initialize this iterator in two steps, to avoid downcalls * during initialization that lead to null pointer exceptions. */ //@ assignable rawElems, objectState, dented, owner; //@ ensures !dented; public NewIter(FloatIterator iter) { super(iter, (float)0); super.initialize(); } // doc comment and specification inherited public /*@ pure @*/ boolean approve(float elem) { return FloatAbstractFilteringStrategyDecorator .this.approve(elem); } } return new NewIter(rawData.floatIterator()); } /** Return true if the element is to be returned by the * getFloat() method. */ //@ public normal_behavior //@ assignable \nothing; public abstract /*@ pure @*/ boolean approve(float elem); }
mit
ampotty/uip-pc2
Ejemplos/ejemplo51/Main.java
1119
public class Main { public static void main(String[] args) { // Impresion en consola System.out.println("Bievenidos a PC2"); /* Numeros Enteros byte, short, int, long */ byte a1; a1 = 10; short a2 = 15; int a3 = 20; long a4 = 25; System.out.println("Enteros: " + a1 + " " + a2 + " " + a3 + " " + a4); /* Numeros Decimales float, double */ float b1 = 0.000005f; double b2 = 150.150; System.out.println("Decimales: " + b1 + " " + b2); // Caracteres char sexo1 = 'M'; // Cadenas String sexo2 = "M"; System.out.println("Caracteres: " + sexo1); System.out.println("Cadenas: " + sexo2); // Booleanos boolean esAdmin = true; System.out.println("Booleano: " + esAdmin); // Operadores Aritmeticos System.out.println( 1+2 ); System.out.println( 2-1 ); System.out.println( 2*2 ); System.out.println( 5/2.0 ); System.out.println( 5%2 ); } }
mit
recurly/recurly-client-android
recurly-android-sdk/recurly-android-sdk/src/main/java/com/recurly/android/model/Tax.java
1854
/* * The MIT License * Copyright (c) 2014-2015 Recurly, Inc. * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.recurly.android.model; public class Tax extends BaseModel { public static final Tax NO_TAX = new Tax("all", 0); private String type; private float rate; public Tax(String type, float rate) { this.type = type; this.rate = rate; } public String getType() { return type; } public void setType(String type) { this.type = type; } public float getRate() { return rate; } public void setRate(float rate) { this.rate = rate; } @Override public String toString() { return "Tax{" + "type='" + type + '\'' + ", rate=" + rate + '}'; } }
mit
katzenpapst/amunra
src/main/java/de/katzenpapst/amunra/block/ore/SubBlockOre.java
1538
package de.katzenpapst.amunra.block.ore; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import de.katzenpapst.amunra.block.SubBlockDropItem; public class SubBlockOre extends SubBlockDropItem { protected String[] oredictNames = {}; protected ItemStack smeltItem = null; public SubBlockOre setOredictNames(String... newNames) { this.oredictNames = newNames; return this; } public String[] getOredictNames() { return this.oredictNames; } public ItemStack getSmeltItem() { return smeltItem; } public SubBlockOre setSmeltItem(Item item, int num, int metadata) { smeltItem = new ItemStack(item, num, metadata); return this; } public SubBlockOre setSmeltItem(Item item, int num) { smeltItem = new ItemStack(item, num, 0); return this; } public SubBlockOre setSmeltItem(ItemStack stack) { smeltItem = stack; return this; } public SubBlockOre(String name, String texture) { super(name, texture); this.isValuable = true; } public SubBlockOre(String name, String texture, String tool, int harvestLevel) { super(name, texture, tool, harvestLevel); this.isValuable = true; } public SubBlockOre(String name, String texture, String tool, int harvestLevel, float hardness, float resistance) { super(name, texture, tool, harvestLevel, hardness, resistance); this.isValuable = true; } }
mit
kheo-ops/kheo-core
kheo-api/src/main/java/com/migibert/kheo/exception/mapping/ServerNotFoundExceptionMapper.java
508
package com.migibert.kheo.exception.mapping; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import com.migibert.kheo.exception.ServerNotFoundException; @Provider public class ServerNotFoundExceptionMapper implements ExceptionMapper<ServerNotFoundException> { @Override public Response toResponse(ServerNotFoundException arg0) { return Response.status(Status.NOT_FOUND).build(); } }
mit
harrystech/hyppo-source-api
source-api/src/main/java/com/harrys/hyppo/source/api/task/CreateIngestionTasks.java
1741
package com.harrys.hyppo.source.api.task; import com.harrys.hyppo.source.api.model.DataIngestionJob; import com.harrys.hyppo.source.api.model.IngestionSource; import com.harrys.hyppo.source.api.model.TaskBuilder; import com.typesafe.config.Config; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigValueFactory; import java.util.Map; /** * Created by jpetty on 7/17/15. */ public final class CreateIngestionTasks { private static final Config sharedEmptyConfig = ConfigFactory.empty(); private final DataIngestionJob job; private final TaskBuilder builder; public CreateIngestionTasks(final DataIngestionJob job){ this.job = job; this.builder = new TaskBuilder(); } public final IngestionSource getSource(){ return this.getJob().getIngestionSource(); } public final DataIngestionJob getJob(){ return this.job; } public final TaskBuilder getTaskBuilder(){ return this.builder; } public final CreateIngestionTasks createTaskWithArgs(final Config arguments){ this.builder.addTask(arguments); return this; } public final CreateIngestionTasks createTaskWithArgs(final Map<String, Object> arguments){ final Config value; try { value = ConfigValueFactory.fromMap(arguments).toConfig(); } catch (ConfigException ce) { throw new IllegalArgumentException("Can't create a Config object from arguments!", ce); } return this.createTaskWithArgs(value); } public final CreateIngestionTasks createTaskWithoutArgs(){ return this.createTaskWithArgs(sharedEmptyConfig); } }
mit
CorwinJV/MobTotems
src/main/java/com/corwinjv/mobtotems/interfaces/IChargeableTileEntity.java
319
package com.corwinjv.mobtotems.interfaces; /** * Created by CorwinJV on 1/23/2017. */ public interface IChargeableTileEntity { int getChargeLevel(); void setChargeLevel(int chargeLevel); void decrementChargeLevel(int amount); void incrementChargeLevel(int amount); int getMaxChargeLevel(); }
mit
FutureProcessing/document-juggler
src/test/java/com/futureprocessing/documentjuggler/read/command/BasicReadCommandTest.java
2194
package com.futureprocessing.documentjuggler.read.command; import com.futureprocessing.documentjuggler.exception.FieldNotLoadedException; import com.mongodb.BasicDBObject; import org.junit.Test; import java.util.Set; import static com.futureprocessing.documentjuggler.helper.Sets.asSet; import static java.util.Arrays.asList; import static java.util.Collections.emptySet; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class BasicReadCommandTest { private static final String FIELD = "testField"; private static final String VALUE = "SomeValue"; private ReadCommand command = new BasicReadCommand(FIELD); @Test public void shouldThrowFieldNotLoadedExceptionWhenAccessingNotLoadedField() { // given BasicDBObject document = new BasicDBObject(); Set<String> queriedFields = asSet("otherField"); // when try { command.read(document, queriedFields); } catch (FieldNotLoadedException e) { // then return; } fail("Should thrown exception"); } @Test public void shouldReadValueWhenNoProjectionSpecified() { // given BasicDBObject document = new BasicDBObject(FIELD, VALUE); Set<String> queriedFields = emptySet(); // when Object value = command.read(document, queriedFields); // then assertThat(value).isEqualTo(VALUE); } @Test public void shouldReadValueWhenProjectionSpecified() { // given BasicDBObject document = new BasicDBObject(FIELD, VALUE); Set<String> queriedFields = asSet(FIELD); // when Object value = command.read(document, queriedFields); // then assertThat(value).isEqualTo(VALUE); } @Test public void shouldReadValueListOfStrings() { // given BasicDBObject document = new BasicDBObject(FIELD, asList(VALUE)); Set<String> queriedFields = emptySet(); // when Object value = command.read(document, queriedFields); // then assertThat(value).isEqualTo(asList(VALUE)); } }
mit
haducloc/appslandia-plum
src/main/java/com/appslandia/plum/jsp/OptionTag.java
2375
// The MIT License (MIT) // Copyright © 2015 AppsLandia. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.appslandia.plum.jsp; import java.io.IOException; import javax.servlet.jsp.JspContext; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.JspFragment; import javax.servlet.jsp.tagext.JspTag; import javax.servlet.jsp.tagext.SimpleTag; import com.appslandia.common.utils.AssertUtils; /** * * @author <a href="mailto:haducloc13@gmail.com">Loc Ha</a> * */ @Tag(name = "option", dynamicAttributes = false) public class OptionTag implements SimpleTag { protected JspTag parent; protected String value; protected Object name; @Override public void doTag() throws JspException, IOException { AssertUtils.assertNotNull(this.parent); ((SelectTag) this.parent).putOption(this.value, this.name); } @Attribute(required = true, rtexprvalue = false) public void setValue(String value) { this.value = value; } @Attribute(required = false, rtexprvalue = true) public void setName(Object name) { this.name = name; } @Override public void setParent(JspTag parent) { this.parent = parent; } @Override public JspTag getParent() { return this.parent; } @Override public void setJspContext(JspContext pc) { } @Override public void setJspBody(JspFragment jspBody) { } }
mit
Dexter245/JTetris
core/src/com/dextersLaboratory/jtetris/view/SimpleGameView.java
4351
package com.dextersLaboratory.jtetris.view; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.dextersLaboratory.jtetris.model.GameModel; import com.dextersLaboratory.jtetris.model.GameState; public class SimpleGameView implements IGameView { @SuppressWarnings("unused") private static final int SCREEN_WIDTH = 640; private static final int SCREEN_HEIGHT = 480; private static final int CELL_WIDTH = 21; private static final int CELL_HEIGHT = 21; private static final int NUM_CELLS_X = 10; private static final int NUM_CELLS_Y = 20; private ShapeRenderer shapeRenderer = new ShapeRenderer(1000); private SpriteBatch batch = new SpriteBatch(); private BitmapFont stdFont = new BitmapFont(); private GameModel model; public SimpleGameView(GameModel model){ this.model = model; stdFont.setColor(Color.BLACK); } @Override public void render() { Gdx.gl.glClearColor(1f, 1f, 1f, 1f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); renderGameArea(); renderInterface(); } private void renderInterface(){ //game area bounds shapeRenderer.begin(ShapeType.Line); shapeRenderer.setColor(Color.BLACK); shapeRenderer.rect(20, 20, (CELL_WIDTH+1)*NUM_CELLS_X, (CELL_HEIGHT+1)*NUM_CELLS_Y); //seperator lines shapeRenderer.setColor(Color.LIGHT_GRAY); //horizontal lines for(int i = 1; i < 20; i++){ int y = 20 + i*(CELL_HEIGHT+1); shapeRenderer.line(20, y, 10*(CELL_WIDTH+1) + 20 - 1, y); } //vertical lines for(int i = 1; i < 10; i++){ int x = 20 + i*(CELL_WIDTH+1); shapeRenderer.line(x, 21, x, 20*(CELL_HEIGHT+1) + 20); } shapeRenderer.end(); //info text batch.begin(); stdFont.draw(batch, "Time played: " + (int) model.getTimePlayed(), 250, SCREEN_HEIGHT - 20); stdFont.draw(batch, "Lines cleared: " + model.getLinesCleared(), 250, SCREEN_HEIGHT - 40); stdFont.draw(batch, "Score: " + model.getScore(), 250, SCREEN_HEIGHT - 60); stdFont.draw(batch, "Speed: " + model.getSpeed(), 250, SCREEN_HEIGHT - 80); stdFont.draw(batch, "Steptime: " + model.getSteptime(), 250, SCREEN_HEIGHT - 100); //controls stdFont.draw(batch, "Controls:", 250, SCREEN_HEIGHT - 140); stdFont.draw(batch, "W/Up: Rotate", 250, SCREEN_HEIGHT - 160); stdFont.draw(batch, "S/Down: Drop block", 250, SCREEN_HEIGHT - 180); stdFont.draw(batch, "A/Left: Move left", 250, SCREEN_HEIGHT - 200); stdFont.draw(batch, "D/Right: Move right", 250, SCREEN_HEIGHT - 220); stdFont.draw(batch, "P/Enter: Pause, new game", 250, SCREEN_HEIGHT - 240); if(model.getGameState() == GameState.paused){ stdFont.draw(batch, "Paused", 100, SCREEN_HEIGHT/2.0f); } else if(model.getGameState() == GameState.gameOver){ stdFont.draw(batch, "Press enter to start a new game", 26, SCREEN_HEIGHT/2.0f); } batch.end(); } private void renderGameArea(){ shapeRenderer.begin(ShapeType.Filled); //blocks that have fallen down for(int x = 0; x < NUM_CELLS_X; x++){ for(int y = 0; y < NUM_CELLS_Y; y++){ if(model.getGridCell(x, y) && model.getGridCellColor(x, y) != null){ shapeRenderer.setColor(model.getGridCellColor(x, y)); shapeRenderer.rect(x*(CELL_WIDTH+1)+20, y*(CELL_HEIGHT+1)+21, CELL_WIDTH, CELL_HEIGHT); } } } //current block if(model.getCurrentBlock() != null){ boolean[][] blockGrid = model.getCurrentBlock().getGrid(); int blockPosX = model.getCurrentBlockPosX(); int blockPosY = model.getCurrentBlockPosY(); int rectX = 0, rectY = 0; shapeRenderer.setColor(model.getCurrentBlock().getColor()); for(int x = 0; x < blockGrid.length; x++){ for(int y = 0; y < blockGrid[x].length; y++){ if(blockGrid[x][y]){ rectX = (blockPosX + x) * (CELL_WIDTH+1) + 20; rectY = (blockPosY + y) * (CELL_HEIGHT+1) + 21; shapeRenderer.rect(rectX, rectY, CELL_WIDTH, CELL_HEIGHT); } } } } shapeRenderer.end(); } @Override public void dispose(){ batch.dispose(); shapeRenderer.dispose(); stdFont.dispose(); } }
mit
jblindsay/jblindsay.github.io
ghrg/Whitebox/WhiteboxGAT-linux/resources/plugins/source_files/ImageRectificationPanel.java
37372
/* * Copyright (C) 2013 Dr. John Lindsay <jlindsay@uoguelph.ca> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package plugins; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.event.*; import javax.swing.table.DefaultTableModel; import javax.swing.event.ChangeListener; import java.awt.Dimension; import java.text.DecimalFormat; import java.util.Date; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.TableModelEvent; import javax.swing.table.*; import javax.swing.event.TableModelListener; import org.apache.commons.math3.linear.*; import whitebox.geospatialfiles.ShapeFile; import whitebox.geospatialfiles.WhiteboxRaster; import whitebox.geospatialfiles.shapefile.*; import static whitebox.geospatialfiles.shapefile.ShapeType.POINT; import static whitebox.geospatialfiles.shapefile.ShapeType.POINTM; import static whitebox.geospatialfiles.shapefile.ShapeType.POINTZ; import whitebox.interfaces.WhiteboxPluginHost; import whitebox.structures.XYPoint; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ResourceBundle; /** * Can't find * @author Dr. John Lindsay email: jlindsay@uoguelph.ca */ public class ImageRectificationPanel extends JPanel implements ActionListener, ChangeListener, TableModelListener, PropertyChangeListener, MouseListener { // global variables private String inputImageFile; private String imageGCPFile; private String mapGCPFile; private String outputImageFile; private int polyOrder = 1; private double[] forwardRegressCoeffX; private double[] forwardRegressCoeffY; private double[] backRegressCoeffX; private double[] backRegressCoeffY; private int numCoefficients; private double[] imageGCPsXCoords; private double[] imageGCPsYCoords; private double[] mapGCPsXCoords; private double[] mapGCPsYCoords; private double[] residualsXY; private boolean[] useGCP; private double imageXMin; private double imageYMin; private double mapXMin; private double mapYMin; private WhiteboxPluginHost myHost; private JSpinner polyOrderSpinner; private JTable dataTable; private JProgressBar progressBar; private Task task; private JLabel cancel; private ResourceBundle bundle; private ResourceBundle messages; // constructors public ImageRectificationPanel() { // no-args constructor } public ImageRectificationPanel(String inputImageFile, String imageGCPFile, String mapGCPFile, String outputImageFile, WhiteboxPluginHost host) { this.imageGCPFile = imageGCPFile; this.inputImageFile = inputImageFile; this.mapGCPFile = mapGCPFile; this.outputImageFile = outputImageFile; this.myHost = host; this.bundle = host.getGuiLabelsBundle(); this.messages = host.getMessageBundle(); readFiles(); createGui(); } // properties public String getInputImageFile() { return inputImageFile; } public void setInputImageFile(String inputImageFile) { this.inputImageFile = inputImageFile; } public String getImageGCPFile() { return imageGCPFile; } public void setImageGCPFile(String imageGCPFile) { this.imageGCPFile = imageGCPFile; } public String getMapGCPFile() { return mapGCPFile; } public void setMapGCPFile(String mapGCPFile) { this.mapGCPFile = mapGCPFile; } public String getOutputImageFile() { return outputImageFile; } public void setOutputImageFile(String outputImageFile) { this.outputImageFile = outputImageFile; } public int getPolyOrder() { return polyOrder; } public void setPolyOrder(int polyOrder) { this.polyOrder = polyOrder; } // methods public final void createGui() { this.removeAll(); if (imageGCPsXCoords == null) { return; } int i; int newN = 0; for (i = 0; i < imageGCPsXCoords.length; i++) { if (useGCP[i]) { newN++; } } double[] X1 = new double[newN]; double[] Y1 = new double[newN]; double[] X2 = new double[newN]; double[] Y2 = new double[newN]; int j = 0; for (i = 0; i < imageGCPsXCoords.length; i++) { if (useGCP[i]) { X1[j] = imageGCPsXCoords[i]; Y1[j] = imageGCPsYCoords[i]; X2[j] = mapGCPsXCoords[i]; Y2[j] = mapGCPsYCoords[i]; j++; } } calculateEquations(X1, Y1, X2, Y2); // gui stuff this.setLayout(new BorderLayout()); DecimalFormat df = new DecimalFormat("###,###,##0.000"); JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); JButton btnOK = createButton(bundle.getString("OK"), bundle.getString("OK"), "ok"); JButton btnExit = createButton(bundle.getString("Close"), bundle.getString("Close"), "close"); //JButton btnRefresh = createButton("Cancel", "Cancel"); buttonPane.add(Box.createHorizontalStrut(10)); buttonPane.add(btnOK); buttonPane.add(Box.createHorizontalStrut(5)); //buttonPane.add(btnRefresh); buttonPane.add(Box.createHorizontalStrut(5)); buttonPane.add(btnExit); buttonPane.add(Box.createHorizontalGlue()); progressBar = new JProgressBar(0, 100); buttonPane.add(progressBar); buttonPane.add(Box.createHorizontalStrut(5)); cancel = new JLabel(bundle.getString("Cancel")); cancel.setForeground(Color.BLUE.darker()); cancel.addMouseListener(this); buttonPane.add(cancel); buttonPane.add(Box.createHorizontalStrut(10)); this.add(buttonPane, BorderLayout.SOUTH); Box mainBox = Box.createVerticalBox(); mainBox.add(Box.createVerticalStrut(10)); Box box1 = Box.createHorizontalBox(); box1.add(Box.createHorizontalStrut(10)); box1.add(new JLabel(bundle.getString("PolynomialOrder") + ": ")); SpinnerModel model = new SpinnerNumberModel(polyOrder, //initial value 1, //min 5, //max 1); //step polyOrderSpinner = new JSpinner(model); polyOrderSpinner.setPreferredSize(new Dimension(15, polyOrderSpinner.getPreferredSize().height)); polyOrderSpinner.addChangeListener(this); JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) polyOrderSpinner.getEditor(); editor.getTextField().setEnabled(true); editor.getTextField().setEditable(false); box1.add(polyOrderSpinner); box1.add(Box.createHorizontalGlue()); JLabel label = new JLabel("RMSE: " + df.format(overallRMSE)); box1.add(label); box1.add(Box.createHorizontalStrut(10)); mainBox.add(box1); mainBox.add(Box.createVerticalStrut(10)); // Create columns names int numPoints = imageGCPsXCoords.length; Object dataValues[][] = new Object[numPoints][7]; j = 0; for (i = 0; i < numPoints; i++) { dataValues[i][0] = i + 1; dataValues[i][1] = df.format(imageGCPsXCoords[i]); dataValues[i][2] = df.format(imageGCPsYCoords[i]); dataValues[i][3] = df.format(mapGCPsXCoords[i]); dataValues[i][4] = df.format(mapGCPsYCoords[i]); if (useGCP[i]) { dataValues[i][5] = df.format(residualsXY[j]); j++; } else { dataValues[i][5] = null; } dataValues[i][6] = useGCP[i]; } String columnNames[] = {"GCP", bundle.getString("Image") + " X", bundle.getString("Image") + " Y", bundle.getString("Map") + " X", bundle.getString("Map") + " Y", messages.getString("Error"), "Use"}; DefaultTableModel tableModel = new DefaultTableModel(dataValues, columnNames); dataTable = new JTable(tableModel) { private static final long serialVersionUID = 1L; @Override public Class getColumnClass(int column) { switch (column) { case 0: return Integer.class; case 1: return String.class; //Double.class; case 2: return String.class; //Double.class; case 3: return String.class; //Double.class; case 4: return String.class; //Double.class; case 5: return String.class; //Double.class; case 6: return Boolean.class; default: return String.class; //Double.class; } } @Override public Component prepareRenderer(TableCellRenderer renderer, int index_row, int index_col) { Component comp = super.prepareRenderer(renderer, index_row, index_col); //even index, selected or not selected if (index_row % 2 == 0) { comp.setBackground(Color.WHITE); comp.setForeground(Color.BLACK); } else { comp.setBackground(new Color(225, 245, 255)); //new Color(210, 230, 255)); comp.setForeground(Color.BLACK); } if (isCellSelected(index_row, index_col)) { comp.setForeground(Color.RED); } return comp; } }; tableModel.addTableModelListener(this); TableCellRenderer rend = dataTable.getTableHeader().getDefaultRenderer(); TableColumnModel tcm = dataTable.getColumnModel(); //for (int j = 0; j < tcm.getColumnCount(); j += 1) { TableColumn tc = tcm.getColumn(0); TableCellRenderer rendCol = tc.getHeaderRenderer(); // likely null if (rendCol == null) { rendCol = rend; } Component c = rendCol.getTableCellRendererComponent(dataTable, tc.getHeaderValue(), false, false, 0, 0); tc.setPreferredWidth(35); tc = tcm.getColumn(6); rendCol = tc.getHeaderRenderer(); // likely null if (rendCol == null) { rendCol = rend; } c = rendCol.getTableCellRendererComponent(dataTable, tc.getHeaderValue(), false, false, 0, 6); tc.setPreferredWidth(35); JScrollPane scroll = new JScrollPane(dataTable); mainBox.add(scroll); this.add(mainBox, BorderLayout.CENTER); this.validate(); } private JButton createButton(String buttonLabel, String toolTip, String actionCommand) { JButton btn = new JButton(buttonLabel); btn.addActionListener(this); btn.setActionCommand(actionCommand); btn.setToolTipText(toolTip); return btn; } private void readFiles() { try { if (imageGCPFile == null || mapGCPFile == null) { return; } int i; ShapeFile imageGCPs = new ShapeFile(imageGCPFile); ShapeFile mapGCPs = new ShapeFile(mapGCPFile); int n = imageGCPs.getNumberOfRecords(); if (n != mapGCPs.getNumberOfRecords()) { showFeedback("Shapefiles must have the same number of GCPs."); return; } if (imageGCPs.getShapeType().getBaseType() != ShapeType.POINT || mapGCPs.getShapeType().getBaseType() != ShapeType.POINT) { showFeedback("Shapefiles must be of Point ShapeType. \n" + "The operation will not continue."); return; } // Read the GCP data imageGCPsXCoords = new double[n]; imageGCPsYCoords = new double[n]; mapGCPsXCoords = new double[n]; mapGCPsYCoords = new double[n]; i = 0; for (ShapeFileRecord record : imageGCPs.records) { double[][] vertices = new double[1][1]; ShapeType shapeType = record.getShapeType(); switch (shapeType) { case POINT: whitebox.geospatialfiles.shapefile.Point recPoint = (whitebox.geospatialfiles.shapefile.Point) (record.getGeometry()); vertices = recPoint.getPoints(); break; case POINTZ: PointZ recPointZ = (PointZ) (record.getGeometry()); vertices = recPointZ.getPoints(); break; case POINTM: PointM recPointM = (PointM) (record.getGeometry()); vertices = recPointM.getPoints(); break; default: showFeedback("Shapefiles must be of Point ShapeType. \n" + "The operation will not continue."); return; } imageGCPsXCoords[i] = vertices[0][0];// - imageXMin; imageGCPsYCoords[i] = vertices[0][1];// - imageYMin; i++; } i = 0; for (ShapeFileRecord record : mapGCPs.records) { double[][] vertices = new double[1][1]; ShapeType shapeType = record.getShapeType(); switch (shapeType) { case POINT: whitebox.geospatialfiles.shapefile.Point recPoint = (whitebox.geospatialfiles.shapefile.Point) (record.getGeometry()); vertices = recPoint.getPoints(); break; case POINTZ: PointZ recPointZ = (PointZ) (record.getGeometry()); vertices = recPointZ.getPoints(); break; case POINTM: PointM recPointM = (PointM) (record.getGeometry()); vertices = recPointM.getPoints(); break; default: showFeedback("Shapefiles must be of Point ShapeType. \n" + "The operation will not continue."); return; } mapGCPsXCoords[i] = vertices[0][0];// - mapXMin; mapGCPsYCoords[i] = vertices[0][1];// - mapYMin; i++; } useGCP = new boolean[n]; for (i = 0; i < n; i++) { useGCP[i] = true; } } catch (OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch (Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in ImageRectification", e); } } double overallRMSE = 0.0; public void calculateEquations(double[] imageX, double[] imageY, double[] mapX, double[] mapY) { try { int m, i, j, k; int n = mapX.length; // How many coefficients are there? numCoefficients = 0; for (j = 0; j <= polyOrder; j++) { for (k = 0; k <= (polyOrder - j); k++) { numCoefficients++; } } for (i = 0; i < n; i++) { imageX[i] -= imageXMin; imageY[i] -= imageYMin; mapX[i] -= mapXMin; mapY[i] -= mapYMin; } // Solve the forward transformation equations double[][] forwardCoefficientMatrix = new double[n][numCoefficients]; for (i = 0; i < n; i++) { m = 0; for (j = 0; j <= polyOrder; j++) { for (k = 0; k <= (polyOrder - j); k++) { forwardCoefficientMatrix[i][m] = Math.pow(imageX[i], j) * Math.pow(imageY[i], k); m++; } } } RealMatrix coefficients = new Array2DRowRealMatrix(forwardCoefficientMatrix, false); //DecompositionSolver solver = new SingularValueDecomposition(coefficients).getSolver(); DecompositionSolver solver = new QRDecomposition(coefficients).getSolver(); // do the x-coordinate first RealVector constants = new ArrayRealVector(mapX, false); RealVector solution = solver.solve(constants); forwardRegressCoeffX = new double[n]; for (int a = 0; a < numCoefficients; a++) { forwardRegressCoeffX[a] = solution.getEntry(a); } double[] residualsX = new double[n]; double SSresidX = 0; for (i = 0; i < n; i++) { double yHat = 0.0; for (j = 0; j < numCoefficients; j++) { yHat += forwardCoefficientMatrix[i][j] * forwardRegressCoeffX[j]; } residualsX[i] = mapX[i] - yHat; SSresidX += residualsX[i] * residualsX[i]; } double sumX = 0; double SSx = 0; for (i = 0; i < n; i++) { SSx += mapX[i] * mapX[i]; sumX += mapX[i]; } double varianceX = (SSx - (sumX * sumX) / n) / n; double SStotalX = (n - 1) * varianceX; double rsqX = 1 - SSresidX / SStotalX; //System.out.println("x-coordinate r-square: " + rsqX); // now the y-coordinate constants = new ArrayRealVector(mapY, false); solution = solver.solve(constants); forwardRegressCoeffY = new double[numCoefficients]; for (int a = 0; a < numCoefficients; a++) { forwardRegressCoeffY[a] = solution.getEntry(a); } double[] residualsY = new double[n]; residualsXY = new double[n]; double SSresidY = 0; for (i = 0; i < n; i++) { double yHat = 0.0; for (j = 0; j < numCoefficients; j++) { yHat += forwardCoefficientMatrix[i][j] * forwardRegressCoeffY[j]; } residualsY[i] = mapY[i] - yHat; SSresidY += residualsY[i] * residualsY[i]; residualsXY[i] = Math.sqrt(residualsX[i] * residualsX[i] + residualsY[i] * residualsY[i]); } double sumY = 0; double sumR = 0; double SSy = 0; double SSr = 0; for (i = 0; i < n; i++) { SSy += mapY[i] * mapY[i]; SSr += residualsXY[i] * residualsXY[i]; sumY += mapY[i]; sumR += residualsXY[i]; } double varianceY = (SSy - (sumY * sumY) / n) / n; double varianceResiduals = (SSr - (sumR * sumR) / n) / n; double SStotalY = (n - 1) * varianceY; double rsqY = 1 - SSresidY / SStotalY; overallRMSE = Math.sqrt(varianceResiduals); //System.out.println("y-coordinate r-square: " + rsqY); // // Print the residuals. // System.out.println("\nResiduals:"); // for (i = 0; i < n; i++) { // System.out.println("Point " + (i + 1) + "\t" + residualsX[i] // + "\t" + residualsY[i] + "\t" + residualsXY[i]); // } // Solve the backward transformation equations double[][] backCoefficientMatrix = new double[n][numCoefficients]; for (i = 0; i < n; i++) { m = 0; for (j = 0; j <= polyOrder; j++) { for (k = 0; k <= (polyOrder - j); k++) { backCoefficientMatrix[i][m] = Math.pow(mapX[i], j) * Math.pow(mapY[i], k); m++; } } } coefficients = new Array2DRowRealMatrix(backCoefficientMatrix, false); //DecompositionSolver solver = new SingularValueDecomposition(coefficients).getSolver(); solver = new QRDecomposition(coefficients).getSolver(); // do the x-coordinate first constants = new ArrayRealVector(imageX, false); solution = solver.solve(constants); backRegressCoeffX = new double[numCoefficients]; for (int a = 0; a < numCoefficients; a++) { backRegressCoeffX[a] = solution.getEntry(a); } // now the y-coordinate constants = new ArrayRealVector(imageY, false); solution = solver.solve(constants); backRegressCoeffY = new double[n]; for (int a = 0; a < numCoefficients; a++) { backRegressCoeffY[a] = solution.getEntry(a); } } catch (OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch (Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in ImageRectification", e); } } private XYPoint getForwardCoordinates(double x, double y) { XYPoint ret; int j, k, m; double x_transformed = 0; //mapXMin; double y_transformed = 0; //mapYMin; double term; m = 0; for (j = 0; j <= polyOrder; j++) { for (k = 0; k <= (polyOrder - j); k++) { term = Math.pow(x, j) * Math.pow(y, k); x_transformed += term * forwardRegressCoeffX[m]; y_transformed += term * forwardRegressCoeffY[m]; m++; } } ret = new XYPoint(x_transformed, y_transformed); return ret; } private XYPoint getBackwardCoordinates(double x, double y) { XYPoint ret; int j, k, m; double x_transformed = 0; //imageXMin; double y_transformed = 0; //imageYMin; double term; m = 0; for (j = 0; j <= polyOrder; j++) { for (k = 0; k <= (polyOrder - j); k++) { term = Math.pow(x, j) * Math.pow(y, k); x_transformed += term * backRegressCoeffX[m]; y_transformed += term * backRegressCoeffY[m]; m++; } } ret = new XYPoint(x_transformed, y_transformed); return ret; } /** * Used to communicate feedback pop-up messages between a plugin tool and * the main Whitebox user-interface. * * @param feedback String containing the text to display. */ private void showFeedback(String feedback) { if (myHost != null) { myHost.showFeedback(feedback); } else { System.out.println(feedback); } } /** * Used to communicate a return object from a plugin tool to the main * Whitebox user-interface. * * @return Object, such as an output WhiteboxRaster. */ private void returnData(Object ret) { if (myHost != null) { myHost.returnData(ret); } } /** * Used to communicate a progress update between a plugin tool and the main * Whitebox user interface. * * @param progressLabel A String to use for the progress label. * @param progress Float containing the progress value (between 0 and 100). */ private void updateProgress(String progressLabel, int progress) { if (myHost != null) { myHost.updateProgress(progressLabel, progress); } else { System.out.println(progressLabel + " " + progress + "%"); } } /** * Used to communicate a progress update between a plugin tool and the main * Whitebox user interface. * * @param progress Float containing the progress value (between 0 and 100). */ private void updateProgress(int progressVal) { progressBar.setValue(progressVal); // if (myHost != null) { // myHost.updateProgress(progress); // } else { // System.out.println("Progress: " + progress + "%"); // } } private boolean cancelOp = false; /** * Used to communicate a cancel operation from the Whitebox GUI. * * @param cancel Set to true if the plugin should be canceled. */ public void setCancelOp(boolean cancel) { cancelOp = cancel; } private void cancelOperation() { showFeedback("Operation cancelled."); //updateProgress("Progress: ", 0); } //This method is only used during testing. public static void main(String[] args) { try { // int polyOrder = 4; //// String inputGCPFile1 = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/tiepoints 15-16 image 15.shp"; //// String inputRasterFile1 = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/A19411_15_Blue.dep"; //// String inputGCPFile2 = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/tiepoints 15-16 image 16.shp"; //// String inputRasterFile2 = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/A19411_16_Blue.dep"; //// String outputRasterFile = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/16 registered.dep"; // //// String inputGCPFile1 = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/tiepoints final image 15-16.shp"; //// String inputRasterFile1 = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/tmp6.dep"; //// String inputGCPFile2 = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/tiepoints final image 17.shp"; //// String inputRasterFile2 = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/17 adjusted.dep"; //// String outputRasterFile = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/17 registered.dep"; // //// String inputGCPFile1 = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/image 15 GCPs map.shp"; //// String inputRasterFile1 = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/A19411_15_Blue.dep"; //// String inputGCPFile2 = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/image 15 GCPs.shp"; //// String outputRasterFile = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/15 registered to map1.dep"; // // String inputGCPFile1 = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/image 16 GCPs map.shp"; // String inputRasterFile1 = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/A19411_16_Blue.dep"; // String inputGCPFile2 = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/image 16 GCPs.shp"; // String outputRasterFile = "/Users/johnlindsay/Documents/Data/Guelph Photomosaic/16 registered to map1.dep"; // // // args = new String[5]; // args[0] = inputGCPFile1; // args[1] = inputRasterFile1; // args[2] = inputGCPFile2; // args[3] = outputRasterFile; // args[4] = String.valueOf(polyOrder); // // TiePointTransformation tpt = new TiePointTransformation(); // tpt.setArgs(args); // tpt.run(); } catch (Exception e) { System.err.println(e.getMessage()); } } boolean isRunning = false; @Override public void actionPerformed(ActionEvent e) { String ac = e.getActionCommand().toLowerCase(); switch (ac) { case "close": JDialog d = (JDialog) SwingUtilities.getAncestorOfClass(JDialog.class, this); d.dispose(); cancelOp = true; break; case "ok": if (!isRunning) { // you only want one of these threads running at a time. cancelOp = false; task = new Task(); task.addPropertyChangeListener(this); task.execute(); } break; case "cancel": cancelOp = true; break; } } @Override public void stateChanged(ChangeEvent e) { SpinnerModel model = polyOrderSpinner.getModel(); if (model instanceof SpinnerNumberModel) { polyOrder = (int) (((SpinnerNumberModel) model).getValue()); createGui(); } } @Override public void tableChanged(TableModelEvent e) { if (e.getType() == TableModelEvent.UPDATE) { int column = e.getColumn(); if (column == 6) { int row = e.getFirstRow(); useGCP[row] = (boolean) (dataTable.getValueAt(row, column)); createGui(); } } } /** * Invoked when task's progress property changes. */ @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("progress")) { int progress = (Integer) evt.getNewValue(); progressBar.setValue(progress); } } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { cancel.setForeground(Color.RED.darker()); } @Override public void mouseReleased(MouseEvent e) { cancel.setForeground(Color.BLUE.darker()); cancelOp = true; } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } class Task extends SwingWorker<Void, Void> { /* * Main task. Executed in background thread. */ @Override public Void doInBackground() { try { WhiteboxRaster inputImage = new WhiteboxRaster(inputImageFile, "r"); double image2North = inputImage.getNorth(); double image2South = inputImage.getSouth(); double image2West = inputImage.getWest(); double image2East = inputImage.getEast(); XYPoint topLeftCorner = getForwardCoordinates(image2West, image2North); XYPoint topRightCorner = getForwardCoordinates(image2East, image2North); XYPoint bottomLeftCorner = getForwardCoordinates(image2West, image2South); XYPoint bottomRightCorner = getForwardCoordinates(image2East, image2South); // figure out the grid resolution double vertCornerDist = Math.sqrt((topLeftCorner.x - bottomLeftCorner.x) * (topLeftCorner.x - bottomLeftCorner.x) + (topLeftCorner.y - bottomLeftCorner.y) * (topLeftCorner.y - bottomLeftCorner.y)); double horizCornerDist = Math.sqrt((topLeftCorner.x - topRightCorner.x) * (topLeftCorner.x - topRightCorner.x) + (topLeftCorner.y - topRightCorner.y) * (topLeftCorner.y - topRightCorner.y)); double avgGridRes = (vertCornerDist / inputImage.getNumberRows() + horizCornerDist / inputImage.getNumberColumns()) / 2.0; double outputNorth = Double.NEGATIVE_INFINITY; double outputSouth = Double.POSITIVE_INFINITY; double outputEast = Double.NEGATIVE_INFINITY; double outputWest = Double.POSITIVE_INFINITY; if (topLeftCorner.y > outputNorth) { outputNorth = topLeftCorner.y; } if (topLeftCorner.y < outputSouth) { outputSouth = topLeftCorner.y; } if (topLeftCorner.x > outputEast) { outputEast = topLeftCorner.x; } if (topLeftCorner.x < outputWest) { outputWest = topLeftCorner.x; } if (topRightCorner.y > outputNorth) { outputNorth = topRightCorner.y; } if (topRightCorner.y < outputSouth) { outputSouth = topRightCorner.y; } if (topRightCorner.x > outputEast) { outputEast = topRightCorner.x; } if (topRightCorner.x < outputWest) { outputWest = topRightCorner.x; } if (bottomLeftCorner.y > outputNorth) { outputNorth = bottomLeftCorner.y; } if (bottomLeftCorner.y < outputSouth) { outputSouth = bottomLeftCorner.y; } if (bottomLeftCorner.x > outputEast) { outputEast = bottomLeftCorner.x; } if (bottomLeftCorner.x < outputWest) { outputWest = bottomLeftCorner.x; } if (bottomRightCorner.y > outputNorth) { outputNorth = bottomRightCorner.y; } if (bottomRightCorner.y < outputSouth) { outputSouth = bottomRightCorner.y; } if (bottomRightCorner.x > outputEast) { outputEast = bottomRightCorner.x; } if (bottomRightCorner.x < outputWest) { outputWest = bottomRightCorner.x; } double nsRange = outputNorth - outputSouth; double ewRange = outputEast - outputWest; int nRows = (int) (nsRange / avgGridRes); int nCols = (int) (ewRange / avgGridRes); WhiteboxRaster output = new WhiteboxRaster(outputImageFile, outputNorth, outputSouth, outputEast, outputWest, nRows, nCols, inputImage.getDataScale(), inputImage.getDataType(), inputImage.getNoDataValue(), inputImage.getNoDataValue()); double outputX, outputY; double inputX, inputY; int inputCol, inputRow; XYPoint point; double z; int oldProgress = -1; int progress; for (int row = 0; row < nRows; row++) { for (int col = 0; col < nCols; col++) { outputX = output.getXCoordinateFromColumn(col); outputY = output.getYCoordinateFromRow(row); // back transform them into image 2 coordinates. point = getBackwardCoordinates(outputX, outputY); inputX = point.x; inputY = point.y; inputCol = inputImage.getColumnFromXCoordinate(inputX); inputRow = inputImage.getRowFromYCoordinate(inputY); z = inputImage.getValue(inputRow, inputCol); output.setValue(row, col, z); } if (cancelOp) { cancelOperation(); return null; } progress = (int) (100f * row / (nRows - 1)); if (progress != oldProgress) { setProgress(progress); } } output.addMetadataEntry("Created by the " + "ImageRectification tool."); output.addMetadataEntry("Created on " + new Date()); output.close(); returnData(outputImageFile); return null; } catch (Exception e) { return null; } finally { isRunning = false; } } /* * Executed in event dispatching thread */ @Override public void done() { setProgress(0); } } }
mit
reactivesw/customer_server
src/main/java/io/reactivesw/customer/customer/application/model/action/CustomerUpdateAction.java
474
package io.reactivesw.customer.customer.application.model.action; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; /** * Created by umasuo on 16/12/22. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "action") @JsonSubTypes( { @JsonSubTypes.Type(value = SetCustomerPaymentId.class, name = "setCustomerPaymentId"), }) public interface CustomerUpdateAction { }
mit
tgquintela/Blocksworld_problem_with_goal-stack_planer_solver
BlocksWorld (WithConstraints)/src/blocksworld/PredicatesList.java
5639
package blocksworld; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class PredicatesList { // Definition of the class PredicatesList which is a class of list of classes predicate ///////////////// // Inputs: // ** ///////////////// // Outputs: // ** The definition of the class ///////////////// // Author: 'Toño G. Quintela' tgq.spm@gmail.com with the unaffordable help of C.Levinas private List<Predicate> predicateList; public PredicatesList() { this.predicateList = new ArrayList<Predicate>(); } public PredicatesList(List<Predicate> predicateList) { this.predicateList = predicateList; Collections.sort(predicateList, new PredicateComparator()); } public List<Predicate> getAll() { return this.predicateList; } public void add(Predicate predicate) { this.predicateList.add(predicate); Collections.sort(predicateList, new PredicateComparator()); } public void remove(Predicate predicate) { this.predicateList.remove(predicate); } public boolean contains(PredicatesList target) { for (Predicate predicate : target.getAll()) { if (!this.predicateList.contains(predicate)) { return false; } } return true; } public boolean contains(Predicate target) { for (Predicate predicate : this.predicateList) { if (predicate.equals(target)) { return true; } } return false; } public int size() { return this.predicateList.size(); } public boolean isEmpty() { return this.predicateList.isEmpty(); } public Instances instantiate(PredicatesList currentState, Block keepFree, Block dontStack) { boolean freeYcase = false; Instances instances = new Instances(); for (Predicate predicate : this.predicateList) { switch (predicate.getPredicateName()) { case free: // stack(X,Y) yields picked_up(X) free(Y), which is problematic because we can't solve Y. if ((predicate.getBlock1() != null) && predicate.getBlock1().equals(Planner.Y)) { freeYcase = true; } break; case on_table: // No easy way to know which one to choose... break; case picked_up: if (!predicate.getBlock1().isInstantiated()) { List<Predicate> pickedUpPredicates = currentState.getMatches(PredicateName.picked_up); if (pickedUpPredicates.size() == 1) { instances.instance1 = pickedUpPredicates.get(0).getBlock1(); } } break; case on: if (!predicate.getBlock1().isInstantiated() || !predicate.getBlock2().isInstantiated()) { List<Predicate> onPredicates = currentState.getMatches(PredicateName.on); for (Predicate onPredicate : onPredicates) { if ((predicate.getBlock1().equals(onPredicate.getBlock1())) && !predicate.getBlock2().isInstantiated()) { instances.instance2 = onPredicate.getBlock2(); } if ((predicate.getBlock2().equals(onPredicate.getBlock2())) && !predicate.getBlock1().isInstantiated()) { instances.instance1 = onPredicate.getBlock1(); } } } break; case free_arm: reak; } } if (freeYcase && (instances.instance2 == null)) { if (instances.instance1 == null) { return null; // This is utter failure! } List<Predicate> predicates = currentState.getMatches(PredicateName.free); List<Predicate> pickedup = currentState.getMatches(PredicateName.picked_up); if (!pickedup.isEmpty()) { Predicate toRemove = null; for (Predicate predicate : predicates) { if (predicate.getBlock1().equals(pickedup.get(0).getBlock1())) { toRemove = predicate; } } if (toRemove != null) { predicates.remove(toRemove); } } BlocksList alternatives = new BlocksList(); for (Predicate predicate : predicates) { if (predicate.getBlock1().equals(instances.instance1)) { continue; } if (predicate.getBlock1().equals(keepFree)) { continue; } if (predicate.getBlock1().equals(dontStack)) { continue; } if (predicate.getBlock1().getWeight() > instances.instance1.getWeight()) { alternatives.add(predicate.getBlock1()); } } if (alternatives.isEmpty()) { return null; // We could not resolve instance2 } else { instances.instance2 = alternatives.getLighter(); instances.mustSeekAlternative = (alternatives.size() == 1); return instances; } } return instances; } public int getNumColumns() { int numColumns = 0; for (Predicate predicate : this.predicateList) { if (predicate.getPredicateName() == PredicateName.on_table) { numColumns++; } } return numColumns; } public List<Predicate> getMatches(PredicateName predicateName) { List<Predicate> onPredicates = new ArrayList<Predicate>(); for (Predicate predicate : this.predicateList) { if (predicate.getPredicateName() == predicateName) { onPredicates.add(predicate); } } return onPredicates; } class PredicateComparator implements Comparator<Predicate> { @Override public int compare(Predicate o1, Predicate o2) { if ((o1.getPredicateName() == o2.getPredicateName()) && (o1.getPredicateName() == PredicateName.on)) { // Heuristics. 'On' predicates sorted by weight so we solve heavier ones first. return o1.getBlock1().getWeight() > o2.getBlock1().getWeight() ? 1 : -1; } else { // Heuristics. Order predicates according to enum, which ensures best solving order. return o1.getPredicateName().compareTo(o2.getPredicateName()); } } } }
mit
vasttrafik/wso2-community-api
java/src/main/java/org/vasttrafik/wso2/carbon/community/api/resources/Topics.java
4537
package org.vasttrafik.wso2.carbon.community.api.resources; import javax.validation.Valid; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.vasttrafik.wso2.carbon.community.api.beans.Topic; import org.vasttrafik.wso2.carbon.community.api.impl.TopicsApiServiceImpl; import org.vasttrafik.wso2.carbon.community.api.impl.utils.CacheControl; /** * * @author Lars Andersson * */ @Path("/topics") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public final class Topics { private final TopicsApiServiceImpl delegate = new TopicsApiServiceImpl(); @SuppressWarnings("unused") private static final Log log = LogFactory.getLog(Topics.class); @GET @CacheControl("no-cache") public Response getTopics( @QueryParam("label") final String label, @QueryParam("query") final String query, @QueryParam("offset") @Min(1) @DefaultValue("1") final Integer offset, @QueryParam("limit") @Min(1) @Max(100) @DefaultValue("10") final Integer limit, @QueryParam("setInfo") @DefaultValue("false") final boolean setInfo ) throws ClientErrorException { return delegate.getTopics(label, query, offset, limit, setInfo); } @POST public Response postTopic( @NotNull(message= "{assertion.notnull}") @HeaderParam("X-JWT-Assertion") final String authorization, @NotNull(message= "{topic.notnull}") @Valid final Topic topic ) throws ClientErrorException { return delegate.createTopic(authorization, topic); } @GET @Path("/{id}") @CacheControl("no-cache") public Response getTopic(@PathParam("id") final Long id, @QueryParam("includePosts") @DefaultValue("true") final boolean includePosts) throws ClientErrorException { return delegate.getTopic(id, includePosts); } @PUT @Path("/{id}") public Response putTopic( @NotNull(message= "{assertion.notnull}") @HeaderParam("X-JWT-Assertion") final String authorization, @PathParam("id") final Long id, @QueryParam("action") final String action, @NotNull(message= "{topic.notnull}") @Valid final Topic topic ) throws ClientErrorException { return delegate.updateTopic(authorization, id, action, topic); } @DELETE @Path("/{id}") public Response deleteTopic( @NotNull(message= "{assertion.notnull}") @HeaderParam("X-JWT-Assertion") final String authorization, @PathParam("id") final Long id ) throws ClientErrorException { return delegate.deleteTopic(authorization, id); } @GET @Path("/{id}/posts") @CacheControl("no-cache") public Response getTopicPosts( @HeaderParam("If-Modified-Since") final String ifModifiedSince, @PathParam("id") final Long topicId, @QueryParam("offset") @Min(1) @DefaultValue("1") final Integer offset, @QueryParam("limit") @Min(1) @Max(50) @DefaultValue("10") final Integer limit ) throws ClientErrorException { return delegate.getPosts(ifModifiedSince, topicId, offset, limit); } @GET @Path("/{id}/votes") @CacheControl("no-cache") public Response getTopicVotes( @NotNull(message= "{assertion.notnull}") @HeaderParam("X-JWT-Assertion") final String authorization, @PathParam("id") final Long topicId, @QueryParam("memberId") final Integer memberId) throws ClientErrorException { return delegate.getVotes(authorization, topicId, memberId); } @POST @Path("/{id}/watches") public Response postTopicWatch( @NotNull(message= "{assertion.notnull}") @HeaderParam("X-JWT-Assertion") final String authorization, @PathParam("id") final Long topicId) throws ClientErrorException { return delegate.createWatch(authorization, topicId); } @DELETE @Path("/{id}/watches/{watchId}") public Response deleteTopicWatch( @NotNull(message= "{assertion.notnull}") @HeaderParam("X-JWT-Assertion") final String authorization, @PathParam("id") final Long id, @PathParam("watchId") final Long watchId) throws ClientErrorException { return delegate.deleteWatch(authorization, watchId); } }
mit
oop-khpi/kit26a
pavlova-maryia/src/ua/khpi/oop/pavlova10/package-info.java
82
/** * */ /** * @author pavlova-mv * */ package ua.khpi.oop.pavlova10;
mit
jklingsporn/vertx-push-onesignal
src/main/java/io/github/jklingsporn/vertx/push/OneSignalResponseException.java
276
package io.github.jklingsporn.vertx.push; import io.vertx.core.json.JsonArray; /** * Created by jensklingsporn on 02.01.17. */ public class OneSignalResponseException extends Exception { public OneSignalResponseException(String cause) { super(cause); } }
mit
luisfontes19/ActiveSQL
src/main/java/org/fatal/activesql/utils/Utilities.java
1689
/* * The MIT License * * Copyright 2016 luisfontes19. * * 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.fatal.activesql.utils; /** * * @author luisfontes19 */ public class Utilities { public static String joinArray(Object[] a) { return joinArray(a, ","); } public static String joinArray(Object[] a, String separator) { if(a == null || a.length == 0) return ""; String r = ""; for(int i=0; i<a.length-1; i++) { r += a[i]; r += separator; } r += a[a.length-1]; return r; } }
mit
pingw33n/malle
modules/freemarker/src/main/java/net/emphased/malle/template/freemarker/MailDirective.java
15941
package net.emphased.malle.template.freemarker; import freemarker.core.Environment; import freemarker.template.*; import net.emphased.malle.*; import net.emphased.malle.support.InputStreamSuppliers; import javax.annotation.Nullable; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; class MailDirective implements TemplateDirectiveModel { public static final String NAME = "mail"; private enum TrimMode { none, leading, trailing, both } private static final Map<String, Handler> CMD_HANDLERS; static { Map<String, Handler> m = new HashMap<>(); m.put("from", new AddressHandler(AddressType.FROM)); m.put("to", new AddressHandler(AddressType.TO)); m.put("cc", new AddressHandler(AddressType.CC)); m.put("bcc", new AddressHandler(AddressType.BCC)); m.put("priority", new PriorityHandler()); m.put("subject", new SubjectHandler()); m.put("plain", new BodyHandler(BodyType.PLAIN)); m.put("html", new BodyHandler(BodyType.HTML)); m.put("attachment", new AttachmentHandler(false)); m.put("inline", new AttachmentHandler(true)); m.put("settings", new SettingsHandler()); CMD_HANDLERS = Collections.unmodifiableMap(m); } private static final Map<String, Encoding> STR_TO_ENCODING; static { Map<String, Encoding> m = new HashMap<>(); m.put("base64", Encoding.BASE64); m.put("quoted-printable", Encoding.QUOTED_PRINTABLE); m.put("8bit", Encoding.EIGHT_BIT); m.put("7bit", Encoding.SEVEN_BIT); m.put("binary", Encoding.BINARY); if (Encoding.values().length != m.size()) { throw new AssertionError("Not all Encoding values have mappings in STR_TO_ENCODING"); } m.put("auto", null); STR_TO_ENCODING = Collections.unmodifiableMap(m); } @Override @SuppressWarnings("unchecked") public void execute(Environment env, Map params, TemplateModel[] loopVars, @Nullable TemplateDirectiveBody body) throws TemplateException, IOException { doExecute(env, params, loopVars, body); } private void doExecute(Environment env, Map<String, Object> params, TemplateModel[] loopVars, @Nullable TemplateDirectiveBody body) throws TemplateException, IOException { if (loopVars.length != 0) { throw new TemplateModelException("'mail' directive doesn't allow loop variables"); } params = new HashMap<>(params); String cmd = getStringParam(params, "cmd"); Handler handler = CMD_HANDLERS.get(cmd); if (handler == null) { throw new TemplateModelException("Unknown command passed to 'mail' directive: " + cmd); } String bodyStr = body != null ? renderBody(body) : null; TrimMode defaultTrimMode; if (handler instanceof BodyHandler && ((BodyHandler) handler).getType() == BodyType.PLAIN) { defaultTrimMode = TrimMode.trailing; } else if (handler instanceof AttachmentHandler) { defaultTrimMode = TrimMode.none; } else { defaultTrimMode = TrimMode.both; } TrimMode trimMode = getEnumParam(params, "trim", TrimMode.class, defaultTrimMode); if (bodyStr != null) { bodyStr = trim(bodyStr, trimMode); } Mail m = getMessage(env); handler.handle(cmd, m, bodyStr, params); if (!params.isEmpty()) { throw new TemplateModelException("Unknown parameters passed to 'mail' (cmd = '" + cmd + "') directive: " + params.keySet()); } } private String trim(String value, TrimMode mode) { switch (mode) { case none: return trimFirstLineEndings(value, TrimMode.trailing); case both: return value.trim(); case leading: return trimFirstLineEndings(value.replaceFirst("^\\s+", ""), TrimMode.trailing); case trailing: return value.replaceFirst("\\s+$", ""); default: throw new AssertionError("Unhandled mode: " + mode); } } private String trimFirstLineEndings(String s, TrimMode mode) { if (mode == TrimMode.both || mode == TrimMode.leading) { int i = 0; if (s.startsWith("\r\n")) { i += 2; } else if (s.startsWith("\r") || s.startsWith("\n")) { i++; } s = s.substring(i); } if (mode == TrimMode.both || mode == TrimMode.trailing) { int i = s.length(); if (s.endsWith("\r\n")) { i -= 2; } else if (s.endsWith("\r") || s.endsWith("\n")) { i -= 1; } s = s.substring(0, i); } return s; } private static String getStringParam(Map<String, ?> params, String name, @Nullable String defaultValue) throws TemplateModelException { Object o = params.remove(name); if (o == null) { return defaultValue; } if (!(o instanceof SimpleScalar)) { throw new TemplateModelException("'mail' directive requires '" + name + "' parameter to be a string"); } return ((SimpleScalar) o).getAsString(); } private static String getStringParam(Map<String, ?> params, String name) throws TemplateModelException { return checkParamPresent(getStringParam(params, name, null), name); } private static Integer getIntParam(Map<String, ?> params, String name, @Nullable Integer defaultValue) throws TemplateModelException { String s = getStringParam(params, name, null); if (s == null) { return defaultValue; } try { return Integer.valueOf(s); } catch (NumberFormatException e) { throw new TemplateModelException("'mail' directive requires '" + name + "' parameter to be a valid integer", e); } } private static int getIntParam(Map<String, ?> params, String name) throws TemplateModelException { return checkParamPresent(getIntParam(params, name, null), name); } private static <T extends Enum<T>> T getEnumParam(Map<String, ?> params, String name, Class<T> type, @Nullable T defaultValue) throws TemplateModelException { String s = getStringParam(params, name, null); if (s == null) { return defaultValue; } try { return Enum.valueOf(type, s); } catch (IllegalArgumentException e) { throw new TemplateModelException("'mail' directive requires '" + name + "' parameter to be one of: " + Arrays.toString(type.getEnumConstants()), e); } } private static <T extends Enum<T>> T getEnumParam(Map<String, ?> params, String name, Class<T> type) throws TemplateModelException { return checkParamPresent(getEnumParam(params, name, type, null), name); } private static <T> T checkParamPresent(T value, String name) throws TemplateModelException { if (value == null) { throw new TemplateModelException("'mail' directive requires '" + name + "' parameter to be present"); } return value; } private static Encoding getEncodingParam(Map<String, ?> params, String name, @Nullable Encoding defaultValue) throws TemplateModelException { String s = getStringParam(params, name, null); if (s == null) { return defaultValue; } Encoding r = STR_TO_ENCODING.get(s); if (r == null) { throw new TemplateModelException("'mail' directive requires '" + name + "' parameter to be one of: " + STR_TO_ENCODING.keySet()); } return r; } private static Charset getCharsetParam(Map<String, ?> params, String name) throws TemplateModelException { return checkParamPresent(getCharsetParam(params, name, null), name); } private static Charset getCharsetParam(Map<String, ?> params, String name, @Nullable Charset defaultValue) throws TemplateModelException { String s = getStringParam(params, name, null); if (s == null) { return defaultValue; } try { return Charset.forName(s); } catch (UnsupportedCharsetException e) { throw new TemplateModelException("'mail' directive requires '" + name + "' parameter to be a valid charset"); } } private static Encoding getEncodingParam(Map<String, ?> params, String name) throws TemplateModelException { return checkParamPresent(getEncodingParam(params, name, null), name); } private Mail getMessage(Environment env) throws TemplateModelException { return (Mail) ((ObjectModel) env.getDataModel().get(FreemarkerTemplateEngine.MESSAGE_VAR)).getObject(); } private String renderBody(TemplateDirectiveBody body) throws IOException, TemplateException { StringWriter content = new StringWriter(); body.render(content); return content.toString(); } private interface Handler { void handle(String cmd, Mail m, @Nullable String body, Map<String, ?> params) throws TemplateModelException; } private static class SettingsHandler implements Handler { @Override public void handle(String cmd, Mail m, @Nullable String body, Map<String, ?> params) throws TemplateModelException { Charset charset = getCharsetParam(params, "charset", null); if (charset != null) { m.charset(charset); } Encoding bodyEncoding = getEncodingParam(params, "body_encoding", Mail.DEFAULT_BODY_ENCODING); if (bodyEncoding != null) { m.bodyEncoding(bodyEncoding); } Encoding attachmentEncoding = getEncodingParam(params, "attachment_encoding", Mail.DEFAULT_BODY_ENCODING); if (attachmentEncoding != null) { m.attachmentEncoding(bodyEncoding); } } } private static class SubjectHandler implements Handler { @Override public void handle(String cmd, Mail m, @Nullable String body, Map<String, ?> params) throws TemplateModelException { String subject = getStringParam(params, "value"); m.subject(subject); } } private static class BodyHandler implements Handler { private final BodyType type; public BodyHandler(BodyType type) { this.type = type; } public BodyType getType() { return type; } @Override public void handle(String cmd, Mail m, @Nullable String body, Map<String, ?> params) throws TemplateModelException { m.body(type, body != null ? body : ""); } } private static class PriorityHandler implements Handler { @Override public void handle(String cmd, Mail m, @Nullable String body, Map<String, ?> params) throws TemplateModelException { int priority = getIntParam(params, "value"); m.priority(priority); } } private static class AddressHandler implements Handler { private final AddressType type; public AddressHandler(AddressType type) { this.type = type; } @Override public void handle(String cmd, Mail m, @Nullable String body, Map<String, ?> params) throws TemplateModelException { String address = getStringParam(params, "address", null); String personal = getStringParam(params, "personal", null); if (address != null) { if (body != null) { throw new TemplateModelException("'mail' directive: 'address' parameter and body can't be both present"); } m.address(type, address, personal); } else { if (body == null) { throw new TemplateModelException("'mail' directive: body must be present when 'address' parameter is omitted"); } if (personal != null) { throw new TemplateModelException("'mail' directive: 'personal' parameter may not be specified when there's no 'address' parameter"); } m.address(type, body); } } } private static class AttachmentHandler implements Handler { private interface ISSFactory { InputStreamSupplier create(String param); } private static final Map<String, ISSFactory> ISS_FACTORIES; static { HashMap<String, ISSFactory> m = new HashMap<>(); m.put("file", new FileISSFactory()); m.put("resource", new ResourceISSFactory()); m.put("url", new UrlISSFactory()); ISS_FACTORIES = Collections.unmodifiableMap(m); } private final boolean inline; public AttachmentHandler(boolean inline) { this.inline = inline; } @Override public void handle(String cmd, Mail m, @Nullable String body, Map<String, ?> params) throws TemplateModelException { String nameOrId = getStringParam(params, inline ? "id" : "name"); String type = getStringParam(params, "type", null); if (body != null) { throw new TemplateModelException("'mail' directive doesn't support embedded attachment content"); } String issFactoryName = null; InputStreamSupplier content = null; for (Map.Entry<String, ISSFactory> issFactory: ISS_FACTORIES.entrySet()) { String param = getStringParam(params, issFactory.getKey(), null); if (param == null) { continue; } if (issFactoryName != null) { throw new TemplateModelException("'mail' directive can't have both '" + issFactoryName + "' and '" + issFactory.getKey() + "' parameters set"); } issFactoryName = issFactory.getKey(); content = issFactory.getValue().create(param); } if (content == null) { throw new TemplateModelException("'mail' directive: one of 'file', 'resource' or 'url' parameters must be present"); } if (inline) { m.inline(content, nameOrId, type); } else { m.attachment(content, nameOrId, type); } } private static class FileISSFactory implements ISSFactory { @Override public InputStreamSupplier create(String param) { return InputStreamSuppliers.file(param); } } private static class ResourceISSFactory implements ISSFactory { @Override public InputStreamSupplier create(String param) { return InputStreamSuppliers.resource(param); } } private static class UrlISSFactory implements ISSFactory { @Override public InputStreamSupplier create(String param) { return InputStreamSuppliers.url(param); } } } }
mit
InnovateUKGitHub/innovation-funding-service
common/ifs-data-service-notifications/src/main/java/org/innovateuk/ifs/sil/email/service/RestSilEmailEndpoint.java
1772
package org.innovateuk.ifs.sil.email.service; import org.innovateuk.ifs.commons.error.Error; import org.innovateuk.ifs.commons.service.AbstractRestTemplateAdaptor; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.sil.email.resource.SilEmailMessage; import org.innovateuk.ifs.util.Either; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.EMAILS_NOT_SENT_MULTIPLE; import static org.innovateuk.ifs.commons.service.ServiceResult.*; /** * A REST-based implementation of the SIL email endpoint */ @Component public class RestSilEmailEndpoint implements SilEmailEndpoint { @Autowired @Qualifier("sil_adaptor") private AbstractRestTemplateAdaptor adaptor; @Value("${sil.rest.baseURL}") private String silRestServiceUrl; @Value("${sil.rest.sendmail}") private String silSendmailPath; @Override public ServiceResult<SilEmailMessage> sendEmail(SilEmailMessage message) { return handlingErrors(() -> { final Either<ResponseEntity<Void>, ResponseEntity<Void>> response = adaptor.restPostWithEntity(silRestServiceUrl + silSendmailPath, message, Void.class, Void.class, HttpStatus.ACCEPTED); return response.mapLeftOrRight( failure -> serviceFailure(new Error(EMAILS_NOT_SENT_MULTIPLE, failure.getStatusCode())), success -> serviceSuccess(message)); }); } }
mit
rajat-bhatnagar/demystify-springDataJPA
src/main/java/com/thoughtworks/db/config/JpaConfiguration.java
1877
package com.thoughtworks.db.config; import java.util.HashMap; import java.util.Map; import org.hibernate.dialect.H2Dialect; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; @Configuration public class JpaConfiguration { @Value("#{dataSource}") private javax.sql.DataSource dataSource; @Bean public Map<String, Object> jpaProperties() { Map<String, Object> props = new HashMap<String, Object>(); props.put("hibernate.dialect", H2Dialect.class.getName()); // props.put("hibernate.cache.provider_class", HashtableCacheProvider.class.getName()); return props; } @Bean public JpaVendorAdapter jpaVendorAdapter() { HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter(); hibernateJpaVendorAdapter.setShowSql(true); hibernateJpaVendorAdapter.setGenerateDdl(true); hibernateJpaVendorAdapter.setDatabase(Database.H2); return hibernateJpaVendorAdapter; } @Bean public PlatformTransactionManager transactionManager() { return new JpaTransactionManager( entityManagerFactory().getObject() ); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean(); lef.setDataSource(this.dataSource); lef.setJpaPropertyMap(this.jpaProperties()); lef.setJpaVendorAdapter(this.jpaVendorAdapter()); return lef; } }
mit
tanguygiga/dta-formation
DTA-Chat/src/dta/chat/model/ChatMessage.java
424
package dta.chat.model; import java.io.Serializable; public class ChatMessage implements Serializable { private static final long serialVersionUID = 12L; private String login; private String text; public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
mit
dbathon/gvds
src/test/java/dbathon/web/gvds/util/StringToBytesTest.java
475
package dbathon.web.gvds.util; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import java.util.UUID; import org.junit.Test; public class StringToBytesTest { @Test public void roundTripTest() { final String[] tests = { "test", "random-" + UUID.randomUUID().toString() }; for (final String test : tests) { assertThat(test, equalTo(StringToBytes.toString(StringToBytes.toBytes(test)))); } } }
mit
bwyap/java-engine-lwjgl
src/com/bwyap/engine/gui/element/vector/VectorTextBox.java
750
package com.bwyap.engine.gui.element.vector; import com.bwyap.engine.gui.element.base.TextBox; import com.bwyap.engine.gui.element.properties.VectorShapeColourProperties; import com.bwyap.engine.gui.interfaces.IColouredVectorShape; /** * A text box with a vector drawn background. * See {@link TextBox}. * @author bwyap * */ public abstract class VectorTextBox extends TextBox implements IColouredVectorShape { protected final VectorShapeColourProperties colours; public VectorTextBox(float x, float y, float width, float height, float padding) { super(x, y, width, height, padding); this.colours = new VectorShapeColourProperties(); } @Override public VectorShapeColourProperties colourProperties() { return colours; } }
mit
paine1690/cdp4j
src/main/java/io/webfolder/cdp/type/indexeddb/ObjectStoreIndex.java
2342
/** * The MIT License * Copyright © 2017 WebFolder OÜ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.webfolder.cdp.type.indexeddb; /** * Object store index */ public class ObjectStoreIndex { private String name; private KeyPath keyPath; private Boolean unique; private Boolean multiEntry; /** * Index name. */ public String getName() { return name; } /** * Index name. */ public void setName(String name) { this.name = name; } /** * Index key path. */ public KeyPath getKeyPath() { return keyPath; } /** * Index key path. */ public void setKeyPath(KeyPath keyPath) { this.keyPath = keyPath; } /** * If true, index is unique. */ public Boolean isUnique() { return unique; } /** * If true, index is unique. */ public void setUnique(Boolean unique) { this.unique = unique; } /** * If true, index allows multiple entries for a key. */ public Boolean isMultiEntry() { return multiEntry; } /** * If true, index allows multiple entries for a key. */ public void setMultiEntry(Boolean multiEntry) { this.multiEntry = multiEntry; } }
mit
bnguyen82/stuff-projects
design/src/chain/standard/Approver.java
296
package chain.standard; public abstract class Approver { private Approver successor; protected abstract void approve(ApprovalRequest request); protected void setSuccessor(Approver successor) { this.successor = successor; } protected Approver getSuccessor() { return successor; } }
mit
nomolosvulgaris/tictactoe
boards/Move.java
200
package boards; public class Move { public int col; public int row; public int state; public Move(int row, int col, int state) { this.row = row; this.col = col; this.state = state; } }
mit
Buchenherz/2nd-semester
Programmiermethodik/SheetTen/Task 3/src/CustomObserver.java
146
/** * Created by clemenspfister on 16/06/2017. */ abstract class CustomObserver { protected Game game; public abstract void update(); }
mit
openforis/collect
collect-rdb/src/main/java/org/openforis/collect/relational/model/AncestorKeyColumn.java
499
/** * */ package org.openforis.collect.relational.model; import org.openforis.collect.relational.sql.RDBJdbcType; import org.openforis.idm.metamodel.FieldDefinition; import org.openforis.idm.path.Path; /** * @author S. Ricci * */ public class AncestorKeyColumn extends DataColumn { AncestorKeyColumn(String name, FieldDefinition<?> defn, Path relPath) { super(name, RDBJdbcType.fromType(defn.getValueType()), defn, relPath, getFieldLength(defn), true); } }
mit
Sixish/Chess
src/com/bbdr/chess/Moveable.java
280
package com.bbdr.chess; public interface Moveable { public boolean isValidMove(int relX, int relY); public boolean canMoveTo(int x, int y, Board board); public void moveTo(int x, int y); public int getX(); public int getY(); public int getPlayer(); }
mit
belatrix/AndroidAllStars
app/src/main/java/com/belatrixsf/connect/ui/login/LoginPresenter.java
3541
/* The MIT License (MIT) * Copyright (c) 2016 BELATRIX * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.belatrixsf.connect.ui.login; import com.belatrixsf.connect.R; import com.belatrixsf.connect.entities.SiteInfo; import com.belatrixsf.connect.managers.EmployeeManager; import com.belatrixsf.connect.ui.common.BelatrixConnectPresenter; import javax.inject.Inject; /** * Created by gyosida on 4/12/16. */ public class LoginPresenter extends BelatrixConnectPresenter<LoginView> { private EmployeeManager employeeManager; @Inject public LoginPresenter(LoginView view, EmployeeManager employeeManager) { super(view); this.employeeManager = employeeManager; } public void checkIfInputsAreValid(String username, String password) { view.enableLogin(areFieldsFilled(username, password)); } public void init() { view.enableLogin(false); } public void login(String username, String password) { if (areFieldsFilled(username, password)) { view.showProgressDialog(); employeeManager.login(username, password, new PresenterCallback<EmployeeManager.AccountState>() { @Override public void onSuccess(EmployeeManager.AccountState accountState) { view.dismissProgressDialog(); switch (accountState) { case PROFILE_COMPLETE: view.goHome(); break; case PROFILE_INCOMPLETE: view.goEditProfile(); break; case PASSWORD_RESET_INCOMPLETE: view.goResetPassword(); break; } } }); } else { showError(R.string.error_incorrect_fields); } } private boolean areFieldsFilled(String username, String password) { return username != null && password != null && !username.isEmpty() && !password.isEmpty(); } @Override public void cancelRequests() { } public void getDefaultDomain() { view.showProgressDialog(); employeeManager.getSiteInfo(new PresenterCallback<SiteInfo>() { @Override public void onSuccess(SiteInfo siteInfo) { view.setDefaultDomain("@" + siteInfo.getEmail_domain()); view.dismissProgressDialog(); } }); } }
mit
cipherkit/externalBrain
src/test/java/com/squire/glue/FileCopier.java
1949
package com.squire.glue; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.EnumSet; /** * Created by Matthew Squire on 8/15/17. */ public class FileCopier { private static final Logger log = LogManager.getLogger("FileCopier"); public FileCopier(File source, File target) throws IOException { final Path sourceDir = source.toPath(); final Path targetDir = target.toPath(); if (!Files.exists(targetDir)) { log.debug("Directory " + targetDir + " selected for deletion does not exist."); boolean successful = new File(targetDir.toString()).mkdirs(); if(!successful) { log.error("Failed to create target " + targetDir.toString() + "directory."); return; } } Files.walkFileTree(sourceDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path target = targetDir.resolve(sourceDir.relativize(dir)); try { Files.copy(dir, target); } catch (FileAlreadyExistsException e) { if (!Files.isDirectory(target)) throw e; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.copy(file, targetDir.resolve(sourceDir.relativize(file))); return FileVisitResult.CONTINUE; } }); } }
mit
7jx/Shopping
Shopping/src/com/wy/webtier/SmallTypeAction.java
5997
package com.wy.webtier; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForm; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForward; import com.wy.domain.SmallTypeForm; import org.apache.struts.action.Action; import com.wy.dao.SmallTypeDao; import java.util.List; //ÉÌÆ·Ð¡Àà±ðÐÅÏ¢ public class SmallTypeAction extends Action { private int action; private SmallTypeDao dao = null; public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { action = Integer.parseInt(request.getParameter("action")); dao = new SmallTypeDao(); switch (action) { case 0: { return smallTypeSelect(mapping, form, request, response); //È«²¿²éѯСÀà±ðÐÅÏ¢ } case 2: { return smallTypeInsert(mapping, form, request, response); //Ìí¼ÓСÀà±ðÐÅÏ¢ } case 3: { return smallTypeDelete(mapping, form, request, response); //ɾ³ýСÀà±ðÐÅÏ¢ } case 4: { return smallTypeSelectOne(mapping, form, request, response); //ÒÔÊý¾Ý¿âÁ÷Ë®ºÅΪÌõ¼þ²éѯСÀà±ðÐÅÏ¢ } case 5: { return smallTypeUpdate(mapping, form, request, response); //ÒÔÊý¾Ý¿âÁ÷Ë®ºÅΪÌõ¼þÐÞ¸ÄСÀà±ðÐÅÏ¢ } case 6: { return smallTypeSelectBigId(mapping, form, request, response); //ÒÔÍâ¼ü±àºÅΪÌõ¼þÐÞ¸ÄСÀà±ðÐÅÏ¢ } } throw new java.lang.UnsupportedOperationException( "Method $execute() not yet implemented."); } //ÒÔÍâ¼ü±àºÅΪÌõ¼þÐÞ¸ÄСÀà±ðÐÅÏ¢ public ActionForward smallTypeSelectBigId(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { List list = dao.selectOneBigId(Integer.valueOf(request.getParameter("bigId"))); int pageNumber = list.size(); //¼ÆËã³öÓжàÉÙÌõ¼Ç¼ int maxPage = pageNumber; //¼ÆËãÓжàÉÙÒ³Êý String number = request.getParameter("i"); if (maxPage % 6 == 0) { maxPage = maxPage / 6; } else { maxPage = maxPage / 6 + 1; } if (number == null) { number = "0"; } request.setAttribute("number", String.valueOf(number)); request.setAttribute("maxPage", String.valueOf(maxPage)); request.setAttribute("pageNumber", String.valueOf(pageNumber)); request.setAttribute("list", list); return mapping.findForward("smallTypeSelect"); } //ÒÔÊý¾Ý¿âÁ÷Ë®ºÅΪÌõ¼þÐÞ¸ÄСÀà±ðÐÅÏ¢ public ActionForward smallTypeUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { SmallTypeForm smallTypeForm = (SmallTypeForm) form; smallTypeForm.setBigId(Integer.valueOf(request.getParameter("bigId"))); smallTypeForm.setId(Integer.valueOf(request.getParameter("id"))); smallTypeForm.setSmallName(request.getParameter("name")); dao.updateSmall(smallTypeForm); request.setAttribute("success", "ÐÞ¸ÄСÀà±ðÐÅÏ¢³É¹¦"); return mapping.findForward("smallTypeOperation"); } //ÒÔÊý¾Ý¿âÁ÷Ë®ºÅΪÌõ¼þ²éѯСÀà±ðÐÅÏ¢ public ActionForward smallTypeSelectOne(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { request.setAttribute("small", dao.selectOneBig(Integer.valueOf(request. getParameter("id")))); return mapping.findForward("smallTypeSelectOne"); } //ɾ³ýСÀà±ðÐÅÏ¢ public ActionForward smallTypeDelete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { if (dao.deleteSmall(Integer.valueOf(request.getParameter("id")))) { request.setAttribute("result", "ɾ³ýСÀà±ðÐÅÏ¢³É¹¦£¡"); }else { request.setAttribute("result", "ÉÌÆ·ÐÅÏ¢»¹´æÔÚ´ËÀà±ð£¬ÇëÏÈɾ³ýÉÌÆ·ÐÅÏ¢£¡£¡£¡"); } return mapping.findForward("smallTypeOperation"); } //Ìí¼ÓСÀà±ðÐÅÏ¢ public ActionForward smallTypeInsert(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { SmallTypeForm smallTypeForm = (SmallTypeForm) form; smallTypeForm.setBigId(Integer.valueOf(request.getParameter("bigId"))); smallTypeForm.setSmallName(request.getParameter("name")); dao.insertSmall(smallTypeForm); request.setAttribute("result", "Ìí¼ÓСÀà±ðÐÅÏ¢³É¹¦"); return mapping.findForward("smallTypeOperation"); } //È«²¿²éѯСÀà±ðÐÅÏ¢ public ActionForward smallTypeSelect(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { List list = dao.selectSmall(); int pageNumber = list.size(); //¼ÆËã³öÓжàÉÙÌõ¼Ç¼ int maxPage = pageNumber; //¼ÆËãÓжàÉÙÒ³Êý String number = request.getParameter("i"); if (maxPage % 6 == 0) { maxPage = maxPage / 6; } else { maxPage = maxPage / 6 + 1; } if (number == null) { number = "0"; } request.setAttribute("number", String.valueOf(number)); request.setAttribute("maxPage", String.valueOf(maxPage)); request.setAttribute("pageNumber", String.valueOf(pageNumber)); request.setAttribute("list", list); return mapping.findForward("smallTypeSelect"); } }
mit
Samuel-Oliveira/Java_NFe
src/main/java/br/com/swconsultoria/nfe/util/NFCeUtil.java
3357
package br.com.swconsultoria.nfe.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * * @author Samuel Oliveira */ public class NFCeUtil { /** * * Funcao Responsavel por Devolver o QrCode já no padrão da Nota. * * @param chave : Chave de Acesso da NFCe * @param ambiente : Identificação do Ambiente (1 – Produção, 2 – Homologação) * @param idToken : Identificador do CSC – Código de Segurança do Contribuinte no Banco de Dados da SEFAZ * @param CSC : Código de Segurança do Contribuinte (antigo Token) * @param urlConsulta : Url De Consulta da Nfc-e do Estado * * @return String do QrCode */ public static String getCodeQRCode(String chave, String ambiente, String idToken, String CSC, String urlConsulta) throws NoSuchAlgorithmException { StringBuilder value = new StringBuilder(); value.append(chave); value.append("|").append("2"); value.append("|").append(ambiente); value.append("|").append(Integer.valueOf(idToken)); String cHashQRCode = getHexa(getHash(value.toString() + CSC)).toUpperCase(); return urlConsulta + "?p=" + value + "|" + cHashQRCode; } /** * Funcao Responsavel por Devolver o QrCode já no padrão da Nota. * * @param chave : Chave de Acesso da NFCe * @param ambiente : Identificação do Ambiente (1 – Produção, 2 – Homologação) * @param idToken : Identificador do CSC – Código de Segurança do Contribuinte no Banco de Dados da SEFAZ * @param CSC : Código de Segurança do Contribuinte (antigo Token) * @param urlConsulta : Url De Consulta da Nfc-e do Estado * @return String do QrCode */ public static String getCodeQRCodeContingencia(String chave, String ambiente, String dhEmi, String valorNF, String digVal, String idToken, String CSC, String urlConsulta) throws NoSuchAlgorithmException { StringBuilder value = new StringBuilder(); value.append(chave); value.append("|").append("2"); value.append("|").append(ambiente); value.append("|").append(dhEmi, 8, 10); value.append("|").append(valorNF); value.append("|").append(getHexa(digVal)); value.append("|").append(Integer.valueOf(idToken)); String cHashQRCode = getHexa(getHash(value.toString() + CSC)).toUpperCase(); return urlConsulta + "?p=" + value + "|" + cHashQRCode; } /** * @param valor * @return */ private static byte[] getHash(String valor) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(valor.getBytes()); return md.digest(); } private static String getHexa(String valor) { return getHexa(valor.getBytes()); } private static String getHexa(byte[] bytes) { StringBuilder s = new StringBuilder(); for (byte aByte : bytes) { int parteAlta = ((aByte >> 4) & 0xf) << 4; int parteBaixa = aByte & 0xf; if (parteAlta == 0) { s.append('0'); } s.append(Integer.toHexString(parteAlta | parteBaixa)); } return s.toString(); } }
mit
mzhu22/CellSociety
src/frontEnd/AnimatorLoop.java
6543
package frontEnd; import java.io.File; import java.util.HashMap; import java.util.Map; import javafx.animation.KeyFrame; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.paint.Color; import javafx.scene.shape.Polygon; import javafx.util.Duration; import shapeFactories.Hexagon; import shapeFactories.Rectangle; import shapeFactories.ShapeFactory; import shapeFactories.Triangle; import backEnd.GameOfLife; import backEnd.Patch; import backEnd.PredatorPrey; import backEnd.RuleSet; import backEnd.Segregation; import backEnd.SpreadingFire; import backEnd.SugarScape; public class AnimatorLoop { // Used for menu bars public static final int HEIGHT_OFFSET = 112; public static final int WIDTH_OFFSET = 190; public static final int GRID_BORDER_WIDTH = 1; private CASettings mySettings; private static final double V_PAD = 0; private static final double H_PAD = 0; private double PADDED_WIDTH; private double PADDED_HEIGHT; private int HEIGHT; private int WIDTH; private int NUM_ROWS; private int NUM_COLS; private Group myNodes; private ShapeFactory myShapeBuilder; private static Map<String, ShapeFactory> myImplementedShapeFactories; private static Map<String, RuleSet> myImplementedRulesets; public RuleSet myRuleSet; private boolean initialized = false; private Polygon[][] myGUICells; private Patch[][] myPatches; /* * These constants constants are set when the XML file is read, specifying * the size of the CA sim board. They will be used to determine the size of * each Cell in the grid. */ /** * Constructor * * @param width * = width of stage in pixels * @param height * = height of stage MINUS height of the menu on the top */ public AnimatorLoop(int width, int height) { WIDTH = width - WIDTH_OFFSET; HEIGHT = height - HEIGHT_OFFSET; PADDED_WIDTH = WIDTH - 2 * H_PAD; PADDED_HEIGHT = HEIGHT - 2 * V_PAD; makePossibleShapeFactories(); makePossibleRules(); } /** * Create the game's frame */ public KeyFrame start() { return new KeyFrame(Duration.millis(1000), oneFrame); } /** * Function to do each game frame */ private EventHandler<ActionEvent> oneFrame = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent evt) { updateCells(); } }; private void updateCells() { if (initialized) { myPatches = myRuleSet.update(); updateGUICells(); } } /** * Change the colors of the Polygon representations of Cells to animate them */ private void updateGUICells() { for (int i = 0; i < myPatches.length; i++) { for (int j = 0; j < myPatches[0].length; j++) { /* * TODO Don't have this intentionally null. Make "Empty" state * instead @Brian Bolze */ if (myPatches[i][j].getCell() == null) myGUICells[i][j].setFill(Color.WHITE); else { Color color = myPatches[i][j].getCell().getColor(); myGUICells[i][j].setFill(color); } } } } /** * Create the game's scene */ public Group initGridPane(int gridRows, int gridCols, String[][] gridArray) { NUM_ROWS = gridRows; NUM_COLS = gridCols; myNodes = new Group(); addCellsToGrid(gridArray); return myNodes; } private Group addCellsToGrid(String[][] gridArray) { myShapeBuilder = myImplementedShapeFactories .get(mySettings.myGridShape); for (int row = 0; row < NUM_ROWS; row++) { for (int col = 0; col < NUM_COLS; col++) { Polygon patch = myShapeBuilder.makeShape(PADDED_HEIGHT, PADDED_WIDTH, NUM_ROWS, NUM_COLS); myShapeBuilder.move(patch, row, col, V_PAD, H_PAD); patch.setFill(Color.WHITE); /* * TODO : Add in ability to turn on/off gridlines */ patch.setStroke(Color.GREY); myNodes.getChildren().add(patch); myGUICells[row][col] = patch; } } return myNodes; } public Group readXMLAndInitializeGrid(File XMLFile) { XMLHandler reader = new XMLHandler(); mySettings = reader.read(XMLFile); if (checkBadXMLFileData()) return null; myGUICells = new Polygon[mySettings.getRows()][mySettings.getColumns()]; myNodes = initGridPane(mySettings.getRows(), mySettings.getColumns(), mySettings.getGrid()); myPatches = new Patch[NUM_ROWS][NUM_COLS]; myRuleSet = myImplementedRulesets.get(mySettings.getType()); myRuleSet.setParams(mySettings.getParameters()); initGrid(); myRuleSet.addGrid(myPatches); initialized = true; return myNodes; } private boolean checkBadXMLFileData() { if (!myImplementedRulesets.containsKey(mySettings.getType())) { Main.showPopupMessage("Invalid Simulation Type"); return true; } return false; } private void initGrid() { String[][] grid = mySettings.getGrid(); for (int i = 0; i < myPatches.length; i++) { for (int j = 0; j < myPatches[0].length; j++) { myPatches[i][j] = myRuleSet.initializePatch(i, j, grid[i][j]); //myPatches[i][j] = myRuleSet.initializeRandom(i, j); } } } public void writeToXML() { XMLHandler writer = new XMLHandler(); String type = mySettings.getType(); Map<String, Object> params = mySettings.getParameters(); Integer rows = mySettings.getRows(); Integer cols = mySettings.getColumns(); String[][] gridString = gridPatchToString(); CASettings currentSettings = new CASettings(type, params, rows, cols, gridString); writer.write(currentSettings); } private String[][] gridPatchToString(){ String[][] gridString = new String[myPatches.length][myPatches[0].length]; for(int i=0; i<myPatches.length; i++){ for(int j=0; j<myPatches[0].length; j++){ if(!myPatches[i][j].containsCell()){ gridString[i][j] = "."; } else{ gridString[i][j] = myPatches[i][j].getCell().getState().getIndex().toString(); } } } return gridString; } private void makePossibleShapeFactories() { myImplementedShapeFactories = new HashMap<String, ShapeFactory>(); myImplementedShapeFactories.put("Rectangular", new Rectangle()); myImplementedShapeFactories.put("Triangular", new Triangle()); myImplementedShapeFactories.put("Hexagonal", new Hexagon()); } private void makePossibleRules() { myImplementedRulesets = new HashMap<>(); myImplementedRulesets.put("PredatorPrey", new PredatorPrey()); myImplementedRulesets.put("SpreadingFire", new SpreadingFire()); myImplementedRulesets.put("GameOfLife", new GameOfLife()); myImplementedRulesets.put("Segregation", new Segregation()); myImplementedRulesets.put("SugarScape", new SugarScape()); } }
mit
cacheflowe/haxademic
src/com/haxademic/core/draw/filters/pshader/GlitchSuite.java
6939
package com.haxademic.core.draw.filters.pshader; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import com.haxademic.core.app.P; import com.haxademic.core.math.MathUtil; import com.haxademic.core.math.easing.LinearFloat; import com.haxademic.core.math.easing.Penner; import processing.core.PGraphics; public class GlitchSuite { protected LinearFloat glitchProgress = new LinearFloat(0, 0.015f); protected GlitchMode glitchMode; public enum GlitchMode { Pixelate2, ShaderA, PixelSorting, Shake, ImageGlitcher, Invert, HFlip, Edges, Repeat, Mirror, ColorDistortion, BadTV2, Grain, Slide, ColorSweep, }; // funky enum randomization helper private static final List<GlitchMode> VALUES = Collections.unmodifiableList(Arrays.asList(GlitchMode.values())); private static final int SIZE = VALUES.size(); private static final Random RANDOM = new Random(); public static GlitchMode randomGlitchMode() { return VALUES.get(RANDOM.nextInt(SIZE)); } // optional subset of glitch modes protected GlitchMode[] modes = null; public GlitchSuite() { this(null); } public GlitchSuite(GlitchMode[] modes) { this.modes = modes; } public void newGlitchMode() { if(this.modes == null) { startGlitchMode(randomGlitchMode()); // random from all mode enums } else { startGlitchMode(this.modes[MathUtil.randRange(0, modes.length - 1)]); // random mode from user-define subset } } public void startGlitchMode(GlitchMode newGlitchMode) { // reset glitch progress glitchProgress.setCurrent(0); glitchProgress.setTarget(1); // select a glitch mode glitchMode = newGlitchMode; setModeConfig(); // change glitchProgress increment for different speeds glitchProgress.setInc(MathUtil.randRangeDecimal(0.007f, 0.03f)); } protected void setModeConfig() { switch (glitchMode) { case Pixelate2: // Pixelate2Filter.instance(P.p).applyTo(buffer); break; case Shake: GlitchShakeFilter.instance(P.p).setGlitchSpeed(MathUtil.randRangeDecimal(0.25f, 0.65f)); GlitchShakeFilter.instance(P.p).setSubdivide1(64f); GlitchShakeFilter.instance(P.p).setSubdivide2(64f); break; case ImageGlitcher: GlitchImageGlitcherFilter.instance(P.p).setColorSeparation(MathUtil.randBoolean()); GlitchImageGlitcherFilter.instance(P.p).setBarSize(MathUtil.randRangeDecimal(0.25f, 0.75f)); GlitchImageGlitcherFilter.instance(P.p).setGlitchSpeed(MathUtil.randRangeDecimal(0.25f, 0.75f)); GlitchImageGlitcherFilter.instance(P.p).setNumSlices(MathUtil.randRangeDecimal(10, 30)); break; case Repeat: // RepeatFilter.instance(P.p).applyTo(buffer); break; case Mirror: ReflectFilter.instance(P.p).setHorizontal(MathUtil.randBoolean()); ReflectFilter.instance(P.p).setReflectPosition(MathUtil.randBoolean() ? 0.5f : MathUtil.randRangeDecimal(0.2f, 0.8f)); break; case BadTV2: BadTVLinesFilter.instance(P.p).setGrayscale(0); BadTVLinesFilter.instance(P.p).setCountS(4096.0f / 4f); break; case ColorSweep: LumaColorReplaceFilter.instance(P.p).setTargetColor(MathUtil.randRangeDecimal(0, 1), MathUtil.randRangeDecimal(0, 1), MathUtil.randRangeDecimal(0, 1), 1f); LumaColorReplaceFilter.instance(P.p).setDiffRange(MathUtil.randRangeDecimal(0.05f, 0.2f)); break; default: break; } } public void applyTo(PGraphics buffer) { // update glitch progress glitchProgress.update(); boolean isGlitching = glitchProgress.value() > 0 && glitchProgress.value() < 1; if(isGlitching == false) return; float progressInverse = 1f - glitchProgress.value(); float shaderTime = P.p.frameCount * 0.01f; float shaderTimeStepped = P.floor(P.p.frameCount/5) * 0.01f; // apply glitchy filters to buffer switch (glitchMode) { case Pixelate2: Pixelate2Filter.instance(P.p).setDivider(10f * progressInverse); Pixelate2Filter.instance(P.p).applyTo(buffer); break; case ShaderA: GlitchShaderAFilter.instance(P.p).setTime(shaderTimeStepped); GlitchShaderAFilter.instance(P.p).setAmp(P.constrain(progressInverse, 0.1f, 1f)); GlitchShaderAFilter.instance(P.p).applyTo(buffer); break; case PixelSorting: GlitchPseudoPixelSortingFilter.instance(P.p).setThresholdThresholdsCurved(progressInverse); GlitchPseudoPixelSortingFilter.instance(P.p).applyTo(buffer); break; case Shake: GlitchShakeFilter.instance(P.p).setTime(shaderTimeStepped); GlitchShakeFilter.instance(P.p).setAmp(progressInverse); GlitchShakeFilter.instance(P.p).setCrossfade(1f); GlitchShakeFilter.instance(P.p).applyTo(buffer); break; case ImageGlitcher: GlitchImageGlitcherFilter.instance(P.p).setTime(shaderTimeStepped); GlitchImageGlitcherFilter.instance(P.p).setAmp(progressInverse); GlitchImageGlitcherFilter.instance(P.p).setCrossfade(1f); GlitchImageGlitcherFilter.instance(P.p).applyTo(buffer); break; case Invert: InvertFilter.instance(P.p).applyTo(buffer); break; case HFlip: FlipHFilter.instance(P.p).applyTo(buffer); break; case Edges: EdgesFilter.instance(P.p).applyTo(buffer); break; case Repeat: float progressInverseEased = Penner.easeInExpo(progressInverse); RepeatFilter.instance(P.p).setZoom(1f + 5f * progressInverseEased); RepeatFilter.instance(P.p).applyTo(buffer); break; case Mirror: ReflectFilter.instance(P.p).applyTo(buffer); break; case ColorDistortion: ColorDistortionFilter.instance(P.p).setAmplitude(progressInverse * 4f); ColorDistortionFilter.instance(P.p).setTime(shaderTime * 1f); ColorDistortionFilter.instance(P.p).applyTo(buffer); break; case BadTV2: BadTVLinesFilter.instance(P.p).setTime(shaderTime); BadTVLinesFilter.instance(P.p).setIntensityN(progressInverse); BadTVLinesFilter.instance(P.p).setIntensityS(progressInverse); BadTVLinesFilter.instance(P.p).applyTo(buffer); break; case Grain: GrainFilter.instance(P.p).setTime(shaderTime); GrainFilter.instance(P.p).setCrossfade(progressInverse * 0.5f); GrainFilter.instance(P.p).applyTo(buffer); break; case Slide: float xSlide = progressInverse * (-1f + 2f * P.p.noise(P.p.frameCount * 0.002f)); float ySlide = progressInverse * (-1f + 2f * P.p.noise((P.p.frameCount + 10000) * 0.002f)); RepeatFilter.instance(P.p).setOffset(xSlide, ySlide); RepeatFilter.instance(P.p).applyTo(buffer); break; case ColorSweep: // LumaColorReplaceFilter.instance(P.p).setLumaTarget(3f * progressInverse - 1f); // slide from 2 -> -1 LumaColorReplaceFilter.instance(P.p).setLumaTarget(progressInverse); LumaColorReplaceFilter.instance(P.p).applyTo(buffer); break; default: // P.out("No glitch filter selected!"); break; } } }
mit
jyrkio/Open-IFC-to-RDF-converter
IFC_RDF/src/fi/ni/ifc2x3/IfcChillerType.java
597
package fi.ni.ifc2x3; import fi.ni.ifc2x3.interfaces.*; import fi.ni.*; import java.util.*; /* * IFC Java class * @author Jyrki Oraskari * @license This work is licensed under a Creative Commons Attribution 3.0 Unported License. * http://creativecommons.org/licenses/by/3.0/ */ public class IfcChillerType extends IfcEnergyConversionDeviceType { // The property attributes String predefinedType; // Getters and setters of properties public String getPredefinedType() { return predefinedType; } public void setPredefinedType(String value){ this.predefinedType=value; } }
mit
teinvdlugt/GameOfLife
app/src/main/java/com/teinproductions/tein/gameoflife/files/RLEEncoder.java
6187
package com.teinproductions.tein.gameoflife.files; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import java.util.List; public class RLEEncoder { public static String constructFile(Life info, List<short[]> cells) { String infoStr = writeInfo(info); String pattern = encode(cells); return infoStr + pattern; } /** * @param info Life object containing at least a NonNull value in String field name. * @return Concatenation of the name, creator and comments in 'info' and the current timestamp, * to put in the beginning of an RLE file. Returned String has a newline at the end. */ static String writeInfo(Life info) { StringBuilder sb = new StringBuilder(); // Clear the name and creator of newlines (just to be sure) String name = info.getName().replace("\n", " "); String creator = null; if (info.getCreator() != null) creator = info.getCreator().replace("\n", " "); // Write the name on the first line sb.append("#N ").append(name).append("\n"); // Write down the creator and timestamp sb.append("#O ").append(creator == null ? "" : creator + ", ") .append(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG) .format(Calendar.getInstance().getTime())) .append("\n"); // Write down the comments if (info.getComments() != null) for (String comment : info.getComments()) sb.append("#C ").append(comment).append("\n"); return sb.toString(); } static String encode(List<short[]> c) { // TODO this code can be much optimised by combining for-loops and stuff if (c.isEmpty()) { return "x = 0, y = 0,\n"; } // We're going to modify the cells array, so let's make a copy List<short[]> cells = copyCells(c); // The string to return in the end: StringBuilder sb = new StringBuilder(); // Clear the Life object from any non-living cells, // and find the min and max of x and y. short minX = Short.MAX_VALUE, maxX = Short.MIN_VALUE, minY = Short.MAX_VALUE, maxY = Short.MIN_VALUE; for (Iterator<short[]> iter = cells.iterator(); iter.hasNext(); ) { short[] cell = iter.next(); if (cell[2] == 0) { // Cell is not alive iter.remove(); } else { if (cell[0] < minX) minX = cell[0]; if (cell[0] > maxX) maxX = cell[0]; if (cell[1] < minY) minY = cell[1]; if (cell[1] > maxY) maxY = cell[1]; } } // Find width and height of the pattern for the first line in the encoding int width = maxX - minX + 1; int height = maxY - minY + 1; sb.append("x = ").append(width).append(", y = ").append(height).append(",\n"); // The cells in the Life array aren't ordered by position. sortCellsByPosition(cells); // The upper-righthand corner of the pattern must have coordinate (0,0); // set the cell positions to agree to that. for (short[] cell : cells) { cell[0] = (short) (cell[0] - minX); cell[1] = (short) (cell[1] - minY); } // Let's encode! int currentX = -1, currentY = 0; int counter = 0; // temp counter for number of adjacent cells for (short[] cell : cells) { // Stuff that deals with Y if (cell[1] > currentY) { // Move to a new line // Write down the alive cells if (counter != 0) sb.append(counter == 1 ? "" : counter).append("o"); // Write down new-line-characters for (int i = 0; i < cell[1] - currentY; i++) sb.append("$"); // Start a new line currentX = -1; counter = 0; currentY = cell[1]; } // Stuff that deals with X if (cell[0] == currentX + 1) { // These cells are adjacent, so increment the counter counter++; currentX = cell[0]; } else { // There is a gap of dead cells between this alive cell and the previous alive cell // Write down the previous sequence of adjacent alive cells, and the gap of dead cells // (b = dead cell, o = alive cell) if (counter != 0) sb.append(counter == 1 ? "" : counter).append("o"); int numOfDeadCells = cell[0] - currentX - 1; sb.append(numOfDeadCells == 1 ? "" : numOfDeadCells).append("b"); // Start a new sequence of adjacent alive cells counter = 1; currentX = cell[0]; } } // And write down the last sequence of adjacent alive cells. if (counter != 0) sb.append(counter == 1 ? "" : counter).append("o"); // Concluding character and newline sb.append("!\n"); return sb.toString(); } private static ArrayList<short[]> copyCells(List<short[]> cells) { ArrayList<short[]> result = new ArrayList<>(); for (short[] cell : cells) { result.add(new short[]{cell[0], cell[1], cell[2], cell[3]}); } return result; } private static void sortCellsByPosition(List<short[]> cells) { // Bubble sort algorithm for (int i = cells.size() - 1; i > 1; i--) { for (int j = 0; j < i; j++) { int x1 = cells.get(j)[0], y1 = cells.get(j)[1]; int x2 = cells.get(j + 1)[0], y2 = cells.get(j + 1)[1]; if ((y2 < y1) || (y2 == y1 && x2 < x1)) { // Swap the two cells short[] temp = cells.get(j); cells.set(j, cells.get(j + 1)); cells.set(j + 1, temp); } } } } }
mit
kkyflying/CodeScaner
app/src/main/java/com/kky/codescaner/BaseActivity.java
184
package com.kky.codescaner; import android.support.v7.app.AppCompatActivity; /** * @author kky * @date 2020-02-21 12:44 */ public class BaseActivity extends AppCompatActivity { }
mit
microsoftgraph/msgraph-sdk-java
src/main/java/com/microsoft/graph/requests/PrinterShareCollectionWithReferencesPage.java
2457
// Template Source: BaseEntityCollectionWithReferencesPage.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.models.Printer; import com.microsoft.graph.models.PrinterShare; import java.util.Arrays; import java.util.EnumSet; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.requests.PrinterShareCollectionWithReferencesRequestBuilder; import com.microsoft.graph.requests.PrinterShareCollectionWithReferencesPage; import com.microsoft.graph.requests.PrinterShareCollectionResponse; import com.microsoft.graph.models.PrinterShare; import com.google.gson.JsonObject; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import com.microsoft.graph.http.BaseCollectionPage; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Printer Share Collection With References Page. */ public class PrinterShareCollectionWithReferencesPage extends BaseCollectionPage<PrinterShare, PrinterShareCollectionWithReferencesRequestBuilder> { /** * A collection page for PrinterShare * * @param response the serialized PrinterShareCollectionResponse from the service * @param builder the request builder for the next collection page */ public PrinterShareCollectionWithReferencesPage(@Nonnull final PrinterShareCollectionResponse response, @Nullable final PrinterShareCollectionWithReferencesRequestBuilder builder) { super(response.value, builder, response.additionalDataManager()); } /** * Creates the collection page for PrinterShare * * @param pageContents the contents of this page * @param nextRequestBuilder the request builder for the next page */ public PrinterShareCollectionWithReferencesPage(@Nonnull final java.util.List<PrinterShare> pageContents, @Nullable final PrinterShareCollectionWithReferencesRequestBuilder nextRequestBuilder) { super(pageContents, nextRequestBuilder); } }
mit
dougkoellmer/swarm
src/swarm/shared/account/SignUpCredentials.java
2437
package swarm.shared.account; import swarm.shared.app.BaseAppContext; import swarm.shared.json.A_JsonEncodable; import swarm.shared.json.A_JsonFactory; import swarm.shared.json.I_JsonArray; import swarm.shared.json.I_JsonObject; import swarm.shared.json.JsonHelper; import swarm.shared.json.E_JsonKey; public class SignUpCredentials extends A_AccountCredentials { private String m_captchaChallenge; public SignUpCredentials(A_JsonFactory jsonFactory, I_JsonObject json) { super(jsonFactory, json); init(); } public SignUpCredentials(boolean rememberMe, String... args) { super(rememberMe); init(); for( int i = 0; i < m_credentials.length; i++ ) { m_credentials[i] = args[i]; } m_captchaChallenge = args[args.length-1]; } private void init() { if( m_credentials == null ) { m_credentials = new String[E_SignUpCredentialType.values().length]; } } public String get(E_SignUpCredentialType eType) { return m_credentials[eType.ordinal()]; } public String getCaptchaChallenge() { return m_captchaChallenge; } private void toLowerCase() { m_credentials[E_SignInCredentialType.EMAIL.ordinal()] = m_credentials[E_SignInCredentialType.EMAIL.ordinal()].toLowerCase(); m_credentials[E_SignUpCredentialType.USERNAME.ordinal()] = m_credentials[E_SignUpCredentialType.USERNAME.ordinal()].toLowerCase(); } @Override public void writeJson(I_JsonObject json_out, A_JsonFactory factory) { super.writeJson(json_out, factory); U_Account.cropPassword(m_credentials, E_SignUpCredentialType.PASSWORD.ordinal()); I_JsonArray creds = factory.createJsonArray(); for( int i = 0; i < m_credentials.length; i++ ) { creds.addString(m_credentials[i]); } factory.getHelper().putJsonArray(json_out, E_JsonKey.signUpCredentials, creds); factory.getHelper().putString(json_out, E_JsonKey.captchaChallenge, m_captchaChallenge); } @Override public void readJson(I_JsonObject json, A_JsonFactory factory) { init(); super.readJson(json, factory); I_JsonArray creds = factory.getHelper().getJsonArray(json, E_JsonKey.signUpCredentials); for( int i = 0; i < creds.getSize(); i++ ) { m_credentials[i] = creds.getString(i); } U_Account.cropPassword(m_credentials, E_SignUpCredentialType.PASSWORD.ordinal()); m_captchaChallenge = factory.getHelper().getString(json, E_JsonKey.captchaChallenge); this.toLowerCase(); } }
mit
kzantow/blueocean-plugin
blueocean-bitbucket-pipeline/src/test/java/io/jenkins/blueocean/blueocean_bitbucket_pipeline/cloud/BitbucketCloudScmContentProviderTest.java
10276
package io.jenkins.blueocean.blueocean_bitbucket_pipeline.cloud; import com.cloudbees.hudson.plugins.folder.AbstractFolderProperty; import com.cloudbees.hudson.plugins.folder.AbstractFolderPropertyDescriptor; import com.cloudbees.jenkins.plugins.bitbucket.BitbucketSCMSource; import com.cloudbees.plugins.credentials.domains.Domain; import com.google.common.collect.Lists; import com.mashape.unirest.http.exceptions.UnirestException; import hudson.model.User; import hudson.tasks.Mailer; import hudson.util.DescribableList; import io.jenkins.blueocean.blueocean_bitbucket_pipeline.BitbucketScmSaveFileRequest; import io.jenkins.blueocean.blueocean_bitbucket_pipeline.server.BitbucketServerScmContentProvider; import io.jenkins.blueocean.commons.ServiceException; import io.jenkins.blueocean.rest.impl.pipeline.ScmContentProvider; import io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanCredentialsProvider; import io.jenkins.blueocean.rest.impl.pipeline.scm.GitContent; import io.jenkins.blueocean.rest.impl.pipeline.scm.ScmFile; import jenkins.branch.MultiBranchProject; import jenkins.scm.api.SCMSource; import net.sf.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import org.mockito.Mockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import static org.junit.Assert.*; import static org.powermock.api.mockito.PowerMockito.*; /** * @author Vivek Pandey */ @RunWith(PowerMockRunner.class) @PrepareForTest({Stapler.class}) @PowerMockIgnore({"javax.crypto.*", "javax.security.*", "javax.net.ssl.*","javax.net.SocketFactory"}) public class BitbucketCloudScmContentProviderTest extends BbCloudWireMock{ @Test public void getContent() throws UnirestException, IOException { String credentialId = createCredential(BitbucketCloudScm.ID); StaplerRequest staplerRequest = mockStapler(); MultiBranchProject mbp = mockMbp(credentialId); ScmFile<GitContent> content = (ScmFile<GitContent>) new BitbucketCloudScmContentProvider().getContent(staplerRequest, mbp); assertEquals("Jenkinsfile", content.getContent().getName()); assertEquals("04553981a05754d4bffef56a59d9d996d500301c", content.getContent().getCommitId()); assertEquals("demo1", content.getContent().getRepo()); assertEquals("vivekp7", content.getContent().getOwner()); } @Test public void unauthorizedAccessToContentShouldFail() throws UnirestException, IOException { User alice = User.get("alice"); alice.setFullName("Alice Cooper"); alice.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org")); String aliceCredentialId = createCredential(BitbucketCloudScm.ID, "cloud", alice); StaplerRequest staplerRequest = mockStapler(); MultiBranchProject mbp = mockMbp(aliceCredentialId, alice); try { //Bob trying to access content but his credential is not setup so should fail new BitbucketCloudScmContentProvider().getContent(staplerRequest, mbp); }catch (ServiceException.PreconditionRequired e){ assertEquals("Can't access content from Bitbucket: no credential found", e.getMessage()); return; } fail("Should have failed with PreConditionException"); } @Test public void newContent() throws UnirestException, IOException { String credentialId = createCredential(BitbucketCloudScm.ID); StaplerRequest staplerRequest = mockStapler(); MultiBranchProject mbp = mockMbp(credentialId); GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("VGhpcyBpcyB0ZXN0IGNvbnRlbnQgaW4gbmV3IGZpbGUK") .branch("master").message("new commit").owner("vivekp7").path("foo").repo("demo1").build(); when(staplerRequest.bindJSON(Mockito.eq(BitbucketScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new BitbucketScmSaveFileRequest(content)); String request = "{\n" + " \"content\" : {\n" + " \"message\" : \"first commit\",\n" + " \"path\" : \"foo\",\n" + " \"branch\" : \"master\",\n" + " \"repo\" : \"demo1\",\n" + " \"base64Data\" : "+"\"VGhpcyBpcyB0ZXN0IGNvbnRlbnQgaW4gbmV3IGZpbGUK\""+ " }\n" + "}"; when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length())); ScmFile<GitContent> respContent = (ScmFile<GitContent>) new BitbucketCloudScmContentProvider().saveContent(staplerRequest, mbp); assertEquals("foo", respContent.getContent().getName()); assertEquals(respContent.getContent().getCommitId(), respContent.getContent().getCommitId()); assertEquals("demo1", respContent.getContent().getRepo()); assertEquals("vivekp7", respContent.getContent().getOwner()); assertEquals("master", respContent.getContent().getBranch()); } @Test public void checkScmProperties() throws Exception { // ensure cloud provider works with cloud multibranch pipeline String credentialId = createCredential(BitbucketCloudScm.ID, authenticatedUser); MultiBranchProject mbp = mockMbp(credentialId); ScmContentProvider provider = new BitbucketCloudScmContentProvider(); // unfortunately overriding the apiUrl for WireMock returns a "localhost" URL here, so we mock the call when(((BitbucketSCMSource) mbp.getSCMSources().get(0)).getServerUrl()).thenReturn(BitbucketCloudScm.API_URL); assertTrue(provider.support(mbp)); assertEquals(provider.getScmId(), BitbucketCloudScm.ID); assertEquals(provider.getApiUrl(mbp), BitbucketCloudScm.API_URL); // ensure server provider doesn't work with cloud multibranch pipeline provider = new BitbucketServerScmContentProvider(); assertFalse(provider.support(mbp)); } @Test public void unauthorizedSaveContentShouldFail() throws UnirestException, IOException { User alice = User.get("alice"); alice.setFullName("Alice Cooper"); alice.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org")); String aliceCredentialId = createCredential(BitbucketCloudScm.ID, alice); StaplerRequest staplerRequest = mockStapler(); MultiBranchProject mbp = mockMbp(aliceCredentialId, alice); GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("bm9kZXsKICBlY2hvICdoZWxsbyB3b3JsZCEnCn0K") .branch("master").message("new commit").owner("TESTP").path("README.md").repo("pipeline-demo-test").build(); when(staplerRequest.bindJSON(Mockito.eq(BitbucketScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new BitbucketScmSaveFileRequest(content)); String request = "{\n" + " \"content\" : {\n" + " \"message\" : \"new commit\",\n" + " \"path\" : \"README.md\",\n" + " \"branch\" : \"master\",\n" + " \"repo\" : \"pipeline-demo-test\",\n" + " \"base64Data\" : "+"\"bm9kZXsKICBlY2hvICdoZWxsbyB3b3JsZCEnCn0K\""+ " }\n" + "}"; when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length())); try { new BitbucketCloudScmContentProvider().saveContent(staplerRequest, mbp); }catch (ServiceException.PreconditionRequired e){ assertEquals("Can't access content from Bitbucket: no credential found", e.getMessage()); return; } fail("Should have failed with PreConditionException"); } private StaplerRequest mockStapler(){ mockStatic(Stapler.class); StaplerRequest staplerRequest = mock(StaplerRequest.class); when(Stapler.getCurrentRequest()).thenReturn(staplerRequest); when(staplerRequest.getRequestURI()).thenReturn("http://localhost:8080/jenkins/blue/rest/"); when(staplerRequest.getParameter("path")).thenReturn("Jenkinsfile"); when(staplerRequest.getParameter("repo")).thenReturn("demo1"); when(staplerRequest.getParameter("scmId")).thenReturn(BitbucketCloudScm.ID); return staplerRequest; } private MultiBranchProject mockMbp(String credentialId){ return mockMbp(credentialId, authenticatedUser); } private MultiBranchProject mockMbp(String credentialId, User user){ MultiBranchProject mbp = mock(MultiBranchProject.class); when(mbp.getName()).thenReturn("pipeline1"); when(mbp.getParent()).thenReturn(j.jenkins); BitbucketSCMSource scmSource = mock(BitbucketSCMSource.class); when(scmSource.getServerUrl()).thenReturn(apiUrl); when(scmSource.getCredentialsId()).thenReturn(credentialId); when(scmSource.getRepoOwner()).thenReturn("vivekp7"); when(scmSource.getRepository()).thenReturn("demo1"); when(mbp.getSCMSources()).thenReturn(Lists.<SCMSource>newArrayList(scmSource)); //mock blueocean credential provider stuff BlueOceanCredentialsProvider.FolderPropertyImpl folderProperty = mock(BlueOceanCredentialsProvider.FolderPropertyImpl.class); DescribableList<AbstractFolderProperty<?>,AbstractFolderPropertyDescriptor> properties = new DescribableList<AbstractFolderProperty<?>,AbstractFolderPropertyDescriptor>(mbp); properties.add(new BlueOceanCredentialsProvider.FolderPropertyImpl( user.getId(), credentialId, BlueOceanCredentialsProvider.createDomain(apiUrl) )); Domain domain = mock(Domain.class); when(domain.getName()).thenReturn(BitbucketCloudScm.DOMAIN_NAME); when(folderProperty.getDomain()).thenReturn(domain); when(mbp.getProperties()).thenReturn(properties); return mbp; } }
mit
vulcansteel/autorest
AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/paging/models/PagingGetMultiplePagesNextOptions.java
1594
/** * 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. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package fixtures.paging.models; import com.fasterxml.jackson.annotation.JsonProperty; /** * Additional parameters for the getMultiplePagesNext operation. */ public class PagingGetMultiplePagesNextOptions { /** * Sets the maximum number of items to return in the response. */ @JsonProperty(value = "") private Integer maxresults; /** * Sets the maximum time that the server can spend processing the request, * in seconds. The default is 30 seconds. */ @JsonProperty(value = "") private Integer timeout; /** * Get the maxresults value. * * @return the maxresults value */ public Integer getMaxresults() { return this.maxresults; } /** * Set the maxresults value. * * @param maxresults the maxresults value to set */ public void setMaxresults(Integer maxresults) { this.maxresults = maxresults; } /** * Get the timeout value. * * @return the timeout value */ public Integer getTimeout() { return this.timeout; } /** * Set the timeout value. * * @param timeout the timeout value to set */ public void setTimeout(Integer timeout) { this.timeout = timeout; } }
mit
hironytic/moltonf
Sources/MoltonfDroid/app/src/main/java/com/hironytic/moltonfdroid/StoryElementListAdapter.java
14584
/* * Moltonf * * Copyright (c) 2010,2011 Hironori Ichimiya <hiron@hironytic.com> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.hironytic.moltonfdroid; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Build; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.hironytic.moltonfdroid.model.HighlightSetting; import com.hironytic.moltonfdroid.model.StoryElement; import com.hironytic.moltonfdroid.model.StoryEvent; import com.hironytic.moltonfdroid.model.Talk; import com.hironytic.moltonfdroid.util.BitmapHolder; import com.hironytic.moltonfdroid.util.Proc1; import com.hironytic.moltonfdroid.util.TimePart; /** * ストーリー要素の一覧のためのアダプタクラス */ public class StoryElementListAdapter extends ArrayAdapter<StoryElement> implements AbsListView.RecyclerListener { /** ビューを生成するためのオブジェクト */ private LayoutInflater inflater; /** リソース */ private Resources res; /** デフォルトの顔アイコン */ private Bitmap defaultFaceIcon; /** 強調表示設定のリスト */ private List<HighlightSetting> highlightSettingList; /** ビュー情報 */ private final Map<View, ViewInfo> viewInfoMap = new WeakHashMap<View, ViewInfo>(); /** * 各ビューの情報 */ private static class ViewInfo { } /** * 発言を示すアイテムのビュー情報 */ private static class TalkItemViewInfo extends ViewInfo { /** 発言に燗する情報を表示するビュー */ public TextView infoView; /** 顔アイコンを表示するビュー */ public ImageView faceIconView; /** メッセージを表示するビュー */ public TextView messageView; /** 顔アイコンを要求したビットマップホルダー */ public BitmapHolder faceBitmapHolder; /** 顔アイコンの要求を受け取るプロシージャ */ public Proc1<Bitmap> faceBitmapRequestProc; } /** * ストーリー中のイベントを示すアイテムのビュー情報 */ private static class EventItemViewInfo extends ViewInfo { /** メッセージを表示するビュー */ public TextView messageView; } /** * コンストラクタ * @param context 現在のコンテキスト */ public StoryElementListAdapter(Context context, List<HighlightSetting> highlightSettingList) { super(context, 0); inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); res = context.getResources(); defaultFaceIcon = BitmapFactory.decodeResource(res, R.drawable.default_face); this.highlightSettingList = highlightSettingList; } /** * これ以上このオブジェクトを利用しないときに呼び出します。 */ public void destroy() { // 画像を要求中のものがあれば要求をキャンセル for (ViewInfo viewInfo : viewInfoMap.values()) { if (viewInfo instanceof TalkItemViewInfo) { TalkItemViewInfo talkItemViewInfo = (TalkItemViewInfo)viewInfo; if (talkItemViewInfo.faceBitmapHolder != null) { talkItemViewInfo.faceBitmapHolder.cancelRequest(talkItemViewInfo.faceBitmapRequestProc); talkItemViewInfo.faceBitmapHolder = null; } } } viewInfoMap.clear(); } /** * 表示するStoryElementをすべて差し替えます。 * @param objects */ @TargetApi(11) public void replaceStoryElements(List<StoryElement> objects) { clear(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { for (StoryElement element : objects) { add(element); } } else { addAll(objects); } notifyDataSetChanged(); } /** * @see android.widget.AbsListView.RecyclerListener#onMovedToScrapHeap(android.view.View) */ @Override public void onMovedToScrapHeap(View view) { ViewInfo viewInfo = viewInfoMap.get(view); if (viewInfo instanceof TalkItemViewInfo) { TalkItemViewInfo talkItemViewInfo = (TalkItemViewInfo)viewInfo; // ビューが顔画像を要求中かもしれないので要求をキャンセル。 if (talkItemViewInfo.faceBitmapHolder != null) { talkItemViewInfo.faceBitmapHolder.cancelRequest(talkItemViewInfo.faceBitmapRequestProc); talkItemViewInfo.faceBitmapHolder = null; } } } private static int VIEW_TYPE_TALK = 0; private static int VIEW_TYPE_STORY_EVENT = 1; private static int NUM_VIEW_TYPE = 2; /** * @see android.widget.BaseAdapter#getViewTypeCount() */ @Override public int getViewTypeCount() { return NUM_VIEW_TYPE; } /** * @see android.widget.BaseAdapter#getItemViewType(int) */ @Override public int getItemViewType(int position) { StoryElement item = this.getItem(position); if (item instanceof Talk) { return VIEW_TYPE_TALK; } else if (item instanceof StoryEvent) { return VIEW_TYPE_STORY_EVENT; } return IGNORE_ITEM_VIEW_TYPE; } /** * @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { StoryElement item = this.getItem(position); View retView = convertView; ViewInfo viewInfo = viewInfoMap.get(retView); if (item instanceof Talk) { Talk talkItem = (Talk)item; TalkItemViewInfo talkItemViewInfo; if (retView == null || !(viewInfo instanceof TalkItemViewInfo)) { retView = inflater.inflate(R.layout.listitem_talk, null); talkItemViewInfo = new TalkItemViewInfo(); talkItemViewInfo.infoView = (TextView)retView.findViewById(R.id.talk_info); talkItemViewInfo.faceIconView = (ImageView)retView.findViewById(R.id.face_icon); talkItemViewInfo.messageView = (TextView)retView.findViewById(R.id.talk_message); viewInfoMap.put(retView, talkItemViewInfo); } else { talkItemViewInfo = (TalkItemViewInfo)viewInfo; } // 情報テキスト talkItemViewInfo.infoView.setText(makeTalkInfo(talkItem)); // メッセージ talkItemViewInfo.messageView.setText(makeMessageSequence(talkItem)); // 吹き出しの色と顔アイコン BitmapHolder faceBitmapHolder = talkItem.getSpeaker().getFaceIconHolder(); switch (talkItem.getTalkType()) { case PUBLIC: talkItemViewInfo.messageView.setBackgroundColor(res.getColor(R.color.talk_bg_public)); talkItemViewInfo.messageView.setTextColor(res.getColor(R.color.talk_text_public)); break; case PRIVATE: talkItemViewInfo.messageView.setBackgroundColor(res.getColor(R.color.talk_bg_private)); talkItemViewInfo.messageView.setTextColor(res.getColor(R.color.talk_text_private)); break; case WOLF: talkItemViewInfo.messageView.setBackgroundColor(res.getColor(R.color.talk_bg_wolf)); talkItemViewInfo.messageView.setTextColor(res.getColor(R.color.talk_text_wolf)); break; case GRAVE: talkItemViewInfo.messageView.setBackgroundColor(res.getColor(R.color.talk_bg_grave)); talkItemViewInfo.messageView.setTextColor(res.getColor(R.color.talk_text_grave)); faceBitmapHolder = talkItem.getStory().getGraveIconHolder(); break; } // デフォルト画像に変更しておく talkItemViewInfo.faceIconView.setImageBitmap(defaultFaceIcon); // 実際の顔画像を要求 final ImageView faceIconView = talkItemViewInfo.faceIconView; talkItemViewInfo.faceBitmapHolder = faceBitmapHolder; talkItemViewInfo.faceBitmapRequestProc = new Proc1<Bitmap>() { @Override public void perform(Bitmap arg) { faceIconView.setImageBitmap(arg); } }; talkItemViewInfo.faceBitmapHolder.requestBitmap(talkItemViewInfo.faceBitmapRequestProc); } else if (item instanceof StoryEvent) { StoryEvent eventItem = (StoryEvent)item; EventItemViewInfo eventItemViewInfo; if (retView == null || !(viewInfo instanceof EventItemViewInfo)) { retView = inflater.inflate(R.layout.listitem_story_event, null); eventItemViewInfo = new EventItemViewInfo(); eventItemViewInfo.messageView = (TextView)retView.findViewById(R.id.story_event_message); viewInfoMap.put(retView, eventItemViewInfo); } else { eventItemViewInfo = (EventItemViewInfo)viewInfo; } // メッセージ eventItemViewInfo.messageView.setText(makeMessageSequence(eventItem)); // メッセージの色 switch (eventItem.getEventFamily()) { case ANNOUNCE: eventItemViewInfo.messageView.setBackgroundResource(R.drawable.announce_frame); eventItemViewInfo.messageView.setTextColor(res.getColor(R.color.story_event_announce_text)); break; case ORDER: eventItemViewInfo.messageView.setBackgroundResource(R.drawable.order_frame); eventItemViewInfo.messageView.setTextColor(res.getColor(R.color.story_event_order_text)); break; case EXTRA: eventItemViewInfo.messageView.setBackgroundResource(R.drawable.extra_frame); eventItemViewInfo.messageView.setTextColor(res.getColor(R.color.story_event_extra_text)); break; } } return retView; } /** * メッセージの表示用 CharSequence を生成します。 * @param storyElement メッセージを持つ StoryElement * @return 表示用の CharSequence */ private CharSequence makeMessageSequence(StoryElement storyElement) { SpannableStringBuilder buf = new SpannableStringBuilder(); boolean isFirstLine = true; for (String line : storyElement.getMessageLines()) { if (!isFirstLine) { buf.append("\n"); } int lineStart = buf.length(); buf.append(line); if (highlightSettingList != null) { for (HighlightSetting highlightSetting : highlightSettingList) { if (!highlightSetting.isValid()) { continue; } Pattern pattern = highlightSetting.getPattern(); Matcher matcher = pattern.matcher(line); while (matcher.find()) { buf.setSpan(new ForegroundColorSpan(highlightSetting.getHighlightColor()), matcher.start() + lineStart, matcher.end() + lineStart, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } } isFirstLine = false; } return buf; } /** * 発言情報の表示用 CharSequence を生成します。 * @param talk 発言 * @return 表示用の CharSequence */ private CharSequence makeTalkInfo(Talk talk) { SpannableStringBuilder buf = new SpannableStringBuilder(); int start; int end; int color; start = buf.length(); buf.append(talk.getSpeaker().getFullName()); buf.append(" "); end = buf.length(); color = res.getColor(R.color.talk_speaker_info_text); buf.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); start = buf.length(); TimePart time = talk.getTime(); String timeString = String.format("%02d:%02d", time.getHourPart(), time.getMinutePart()); buf.append(timeString); end = buf.length(); color = res.getColor(R.color.talk_time_info_text); buf.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return buf; } }
mit
kmchugh/Goliath.Data
src/Goliath/Interfaces/Data/IConnectionParameter.java
901
/* ========================================================= * IConnectionParameter.java * * Author: kmchugh * Created: 14-Dec-2007, 11:33:35 * * Description * -------------------------------------------------------- * Interface for the connection paramters to change the options * in a connection string * * Change Log * -------------------------------------------------------- * Init.Date Ref. Description * -------------------------------------------------------- * * =======================================================*/ package Goliath.Interfaces.Data; /** * Interface for the connection paramters to change the options * in a connection string * * @see Goliath.Data.ConnectionParameter * @version 1.0 14-Dec-2007 * @author kmchugh **/ public interface IConnectionParameter<T> extends Goliath.Interfaces.IProperty<T> { }
mit
nickolayrusev/trackteam
domain/src/main/java/com/nrusev/domain/EventGround.java
2495
package com.nrusev.domain; import javax.persistence.*; import java.util.Date; /** * Created by nikolayrusev on 3/10/16. */ @Entity @Table(name = "events_grounds") public class EventGround { private Long id; private Long eventId; private Long groundId; private Date createdAt; private Date updatedAt; @Id @Column(name = "id", nullable = false) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Basic @Column(name = "event_id", nullable = false) public Long getEventId() { return eventId; } public void setEventId(Long eventId) { this.eventId = eventId; } @Basic @Column(name = "ground_id", nullable = false) public Long getGroundId() { return groundId; } public void setGroundId(Long groundId) { this.groundId = groundId; } @Basic @Column(name = "created_at", nullable = true) public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } @Basic @Column(name = "updated_at", nullable = true) public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EventGround that = (EventGround) o; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (eventId != null ? !eventId.equals(that.eventId) : that.eventId != null) return false; if (groundId != null ? !groundId.equals(that.groundId) : that.groundId != null) return false; if (createdAt != null ? !createdAt.equals(that.createdAt) : that.createdAt != null) return false; if (updatedAt != null ? !updatedAt.equals(that.updatedAt) : that.updatedAt != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (eventId != null ? eventId.hashCode() : 0); result = 31 * result + (groundId != null ? groundId.hashCode() : 0); result = 31 * result + (createdAt != null ? createdAt.hashCode() : 0); result = 31 * result + (updatedAt != null ? updatedAt.hashCode() : 0); return result; } }
mit
floralvikings/jenjin-io
src/main/java/com/jenjinstudios/io/serialization/GsonMessageIOFactory.java
736
package com.jenjinstudios.io.serialization; import com.jenjinstudios.io.MessageIOFactory; import com.jenjinstudios.io.MessageReader; import com.jenjinstudios.io.MessageWriter; import java.io.InputStream; import java.io.OutputStream; /** * Used to create GsonMessageReader and GsonMessageWriter instances from Java InputStream and OutputStream * instances. * * @author Caleb Brinkman */ public class GsonMessageIOFactory implements MessageIOFactory { @Override public MessageReader createReader(InputStream inputStream) { return new GsonMessageReader(inputStream); } @Override public MessageWriter createWriter(OutputStream outputStream) { return new GsonMessageWriter(outputStream); } }
mit
codekuangben/Android
Test/TestLibs/Libs/src/main/java/Libs/DataStruct/DynBufResizePolicy.java
872
package Libs.DataStruct; public class DynBufResizePolicy { // 获取一个最近的大小 static public int getCloseSize(int needSize, int capacity, int maxCapacity) { int ret = 0; if (capacity > needSize) // 使用 > ,不适用 >= ,浪费一个自己,方便判断 { ret = capacity; } else { ret = 2 * capacity; while (ret < needSize && ret < maxCapacity) { ret *= 2; } if (ret > maxCapacity) { ret = maxCapacity; } if (ret < needSize) // 分配失败 { //Ctx.mInstance.mLogSys.error(string.Format("Malloc byte buffer failed,cannot malloc {0} byte buffer", needSize)); } } return ret; } }
mit
swaiing/dripster-ws
src/swai/location/data/yelp/Coordinate.java
409
package swai.location.data.yelp; public class Coordinate { private double latitude; private double longitude; public Coordinate() { } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } }
mit
jmthompson2015/rivalry
core/src/main/java/org/rivalry/core/datacollector/ValueStringParser.java
948
//***************************************************************************** // Rivalry (http://code.google.com/p/rivalry) // Copyright (c) 2011 Rivalry.org // Admin rivalry@jeffreythompson.net // // See the file "LICENSE.txt" for information on usage and redistribution of // this file, and for a DISCLAIMER OF ALL WARRANTIES. //***************************************************************************** package org.rivalry.core.datacollector; import org.openqa.selenium.WebElement; /** * Defines methods required by a value string parser. * * @param <T> Type. */ public interface ValueStringParser<T> { /** * @param valueString Value string. * * @return a new object which represents the given parameter. */ T parse(String valueString); /** * @param webElement Web element. * * @return a new object which represents the given parameter. */ T parse(WebElement webElement); }
mit
SpongePowered/Sponge
src/main/java/org/spongepowered/common/item/recipe/stonecutting/SpongeStoneCutterRecipeBuilder.java
5036
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.item.recipe.stonecutting; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.inventory.Inventory; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.item.recipe.RecipeRegistration; import org.spongepowered.api.item.recipe.single.StoneCutterRecipe; import org.spongepowered.common.inventory.util.InventoryUtil; import org.spongepowered.common.item.recipe.SpongeRecipeRegistration; import org.spongepowered.common.item.recipe.ingredient.IngredientUtil; import org.spongepowered.common.item.util.ItemStackUtil; import org.spongepowered.common.util.AbstractResourceKeyedBuilder; import java.util.Collections; import java.util.function.Function; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.Container; import net.minecraft.world.item.Item; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeSerializer; public final class SpongeStoneCutterRecipeBuilder extends AbstractResourceKeyedBuilder<RecipeRegistration, StoneCutterRecipe.Builder> implements StoneCutterRecipe.Builder, StoneCutterRecipe.Builder.ResultStep, StoneCutterRecipe.Builder.EndStep { private ItemStack result; private Ingredient ingredient; private Function<Container, net.minecraft.world.item.ItemStack> resultFunction; private @Nullable String group; @Override public ResultStep ingredient(ItemType ingredient) { this.ingredient = Ingredient.of(() -> ((Item) ingredient)); return this; } @Override public ResultStep ingredient(org.spongepowered.api.item.recipe.crafting.Ingredient ingredient) { this.ingredient = IngredientUtil.toNative(ingredient); return this; } @Override public EndStep result(ItemStackSnapshot result) { this.result = result.createStack(); this.resultFunction = null; return this; } @Override public EndStep result(final ItemStack result) { checkNotNull(result, "result"); this.result = result; this.resultFunction = null; return this; } @Override public EndStep result(Function<Inventory, ItemStack> resultFunction, ItemStack exemplaryResult) { checkNotNull(exemplaryResult, "exemplaryResult"); checkState(!exemplaryResult.isEmpty(), "exemplaryResult must not be empty"); this.result = exemplaryResult; this.resultFunction = (inv) -> ItemStackUtil.toNative(resultFunction.apply(InventoryUtil.toInventory(inv))); return this; } @Override public EndStep group(@Nullable String name) { this.group = name; return this; } @Override public RecipeRegistration build0() { final net.minecraft.world.item.ItemStack result = ItemStackUtil.toNative(this.result); final RecipeSerializer<?> serializer = SpongeRecipeRegistration.determineSerializer(result, this.resultFunction, null, Collections.singleton(this.ingredient), RecipeSerializer.STONECUTTER, SpongeStonecuttingRecipeSerializer.SPONGE_STONECUTTING); return new SpongeStonecuttingRecipeRegistration((ResourceLocation) (Object) key, serializer, this.group, this.ingredient, result, this.resultFunction); } @Override public StoneCutterRecipe.Builder reset() { this.result = null; this.resultFunction = null; this.ingredient = null; this.group = null; return super.reset(); } }
mit
phoen1x/visnetwork-graph-schema
java/visnetwork-graph-schema/src/test/java/de/livingfire/demo/documentation/constant/RequestConstant.java
6049
package de.livingfire.demo.documentation.constant; public interface RequestConstant { public static final String REQUEST_DOMAIN = "skylar.livingfire.de"; public static final String REQUEST_PARAM_CODE = "code"; public static final String REQUEST_PARAM_DESCRIPTION = "description"; public static final String REQUEST_PARAM_DEVELOPER_MESSAGE = "developerMessage"; public static final String REQUEST_PARAM_DIMENSION = "dimension"; public static final String REQUEST_PARAM_ENTRY_DATE = "entryDate"; public static final String REQUEST_PARAM_GROUP = "group"; public static final String REQUEST_PARAM_LOGSTASH = "logstash"; public static final String REQUEST_PARAM_OPEN = "open"; public static final String REQUEST_PARAM_PAGE = "page"; public static final String REQUEST_PARAM_STATUS = "status"; public static final String REQUEST_PARAM_UNIT = "unit"; public static final String REQUEST_PARAM_USER_MESSAGE = "userMessage"; public static final String REQUEST_PARAM_UUID = "uuid"; public static final String REQUEST_PARAM_VALUE = "value"; public static final String REQUEST_PATH_FIND_BY_DESCRIPTION = "/findByDescription"; public static final String REQUEST_PATH_FIND_BY_UUID = "/findByUuid"; public static final String REQUEST_PATH_SEARCH = "/search"; public static final String REQUEST_WEB = "/"; public static final String REQUEST_MANAGEMENT = "/management"; public static final String REQUEST_MANAGEMENT_ENV = REQUEST_MANAGEMENT + "/env"; public static final String REQUEST_MANAGEMENT_HEALTH = REQUEST_MANAGEMENT + "/health"; public static final String REQUEST_ERROR = "/error"; public static final String REQUEST_BASE_API = "/api"; public static final String REQUEST_REPOSITORY_PROFILE = REQUEST_BASE_API + "/profile"; public static final String REQUEST_REPOSITORY_PROFILE_LISTDATAS = REQUEST_REPOSITORY_PROFILE + "/listdatas"; public static final String REQUEST_REPOSITORY_PROFILE_SETTINGS = REQUEST_REPOSITORY_PROFILE + "/settings"; public static final String REQUEST_REPOSITORY_PROFILE_USERS = REQUEST_REPOSITORY_PROFILE + "/users"; public static final String REQUEST_REPOSITORY_USER = REQUEST_BASE_API + "/users"; public static final String REQUEST_REPOSITORY_USER_SEARCH = REQUEST_REPOSITORY_USER + REQUEST_PATH_SEARCH; public static final String REQUEST_REPOSITORY_USER_SEARCH_BY_UUID = REQUEST_REPOSITORY_USER_SEARCH + REQUEST_PATH_FIND_BY_UUID; public static final String REQUEST_REPOSITORY_USER_SEARCH_BY_DESCRIPTION = REQUEST_REPOSITORY_USER_SEARCH + REQUEST_PATH_FIND_BY_DESCRIPTION; public static final String REQUEST_REPOSITORY_SETTING = REQUEST_BASE_API + "/settings"; public static final String REQUEST_REPOSITORY_SETTING_SEARCH = REQUEST_REPOSITORY_SETTING + REQUEST_PATH_SEARCH; public static final String REQUEST_REPOSITORY_SETTING_SEARCH_BY_UUID = REQUEST_REPOSITORY_SETTING_SEARCH + REQUEST_PATH_FIND_BY_UUID; public static final String REQUEST_REPOSITORY_SETTING_SEARCH_BY_DESCRIPTION = REQUEST_REPOSITORY_SETTING_SEARCH + REQUEST_PATH_FIND_BY_DESCRIPTION; public static final String REQUEST_REPOSITORY_LISTDATA = REQUEST_BASE_API + "/listdatas"; public static final String REQUEST_REPOSITORY_LISTDATA_SEARCH = REQUEST_REPOSITORY_LISTDATA + REQUEST_PATH_SEARCH; public static final String REQUEST_REPOSITORY_LISTDATA_SEARCH_BY_UUID = REQUEST_REPOSITORY_LISTDATA_SEARCH + REQUEST_PATH_FIND_BY_UUID; public static final String REQUEST_REPOSITORY_LISTDATA_SEARCH_BY_DESCRIPTION = REQUEST_REPOSITORY_LISTDATA_SEARCH + REQUEST_PATH_FIND_BY_DESCRIPTION; public static final String REQUEST_JAVASCRIPT = REQUEST_BASE_API + "/javascript"; public static final String REQUEST_JAVASCRIPT_ENTITY_PROPERTIES = REQUEST_JAVASCRIPT + "/entityProperties"; public static final String REQUEST_JAVASCRIPT_LISTDATA_GROUP_DIMENSIONS = REQUEST_JAVASCRIPT + "/listdataGroupDimensions"; public static final String REQUEST_JAVASCRIPT_TTS_GOOGLE_CALENDAR = REQUEST_JAVASCRIPT + "/ttsGoogleCalendar"; public static final String REQUEST_JAVASCRIPT_TTS_GREETING = REQUEST_JAVASCRIPT + "/ttsGreeting"; public static final String REQUEST_JAVASCRIPT_TTS_KANBOARD_OVERDUE = REQUEST_JAVASCRIPT + "/ttsKanboardOverdue"; public static final String REQUEST_JAVASCRIPT_TTS_KANBOARD_SHOPPING = REQUEST_JAVASCRIPT + "/ttsKanbaordShopping"; public static final String REQUEST_JAVASCRIPT_TTS_WEATHER = REQUEST_JAVASCRIPT + "/ttsWeather"; public static final String REQUEST_JAVASCRIPT_EMAIL_KANBOARD_SHOPPING = REQUEST_JAVASCRIPT + "/emailKanbaordShopping"; public static final String REQUEST_EXPORT = REQUEST_BASE_API + "/export"; public static final String REQUEST_EXPORT_DATABASE = REQUEST_EXPORT + "/database"; public static final String REQUEST_IMPORT = REQUEST_BASE_API + "/import"; public static final String REQUEST_IMPORT_GARMIN = REQUEST_IMPORT + "/garmin"; public static final String REQUEST_IMPORT_GARMIN_ACTIVITY = REQUEST_IMPORT_GARMIN + "/activity"; public static final String REQUEST_IMPORT_LIBRA = REQUEST_IMPORT + "/libra"; public static final String REQUEST_IMPORT_MICROLIFE = REQUEST_IMPORT + "/microlife"; public static final String REQUEST_IMPORT_ORUXMAPS = REQUEST_IMPORT + "/oruxmaps"; public static final String REQUEST_SAY = REQUEST_BASE_API + "/say"; public static final String REQUEST_SELENIUM = REQUEST_BASE_API + "/selenium"; public static final String REQUEST_SELENIUM_SESSION = REQUEST_SELENIUM + "/session"; public static final String REQUEST_SELENIUM_SESSION_CLOSE = REQUEST_SELENIUM_SESSION + "/close"; public static final String REQUEST_SELENIUM_SESSION_HTML = REQUEST_SELENIUM_SESSION + "/html"; public static final String REQUEST_SELENIUM_WEBPAGE = REQUEST_SELENIUM + "/webpage"; public static final String REQUEST_SELENIUM_WEB_RADIO = REQUEST_SELENIUM + "/webRadio"; }
mit
dhakiki/SimCity201
src/simcity/interfaces/DCook.java
194
package simcity.interfaces; public interface DCook { void msgShouldIPayThisBill(double amnt, MarketManager manager); //public abstract void msgShouldIPayThisBill(double amt, Market ma); }
mit
knuton/hobbes
test/spec_cases/types_and_values/operators_on_floating-point_values/NumericPromotion.java
458
public class NumericPromotion { public static void main(String[] args) { float a = 3.40282347e+38f; float b = 1.40239846e-45f; System.out.println(a+a); System.out.println(a*2f); System.out.println(0.5f*b); double c = 3.40282347e+38; double d = 1.40239846e-45; System.out.println(a+c); System.out.println(a*2d); System.out.println(0.5d*b); System.out.println(c*2f); System.out.println(0.5f*d); } }
mit
lucasbarrosrocha/SI1Projeto
src/main/java/br/edu/ufcg/computacao/si1/transacao/GerenteTransacao.java
414
package br.edu.ufcg.computacao.si1.transacao; import br.edu.ufcg.computacao.si1.model.Usuario; import org.springframework.stereotype.Service; /** * Created by delly on 17/03/17. */ public class GerenteTransacao { public void compra(double valorCompra, Conta contaComprador, Conta contaAnunciante){ contaComprador.debitar(valorCompra); contaAnunciante.creditar(valorCompra); } }
mit
quangvuwpi/SixesWild
SixesWild/src/sw/common/model/entity/Board.java
6129
/** * @file Board.java * @author Tony Vu * @since Apr 11, 2015 */ package sw.common.model.entity; import java.awt.Dimension; import java.awt.Point; import java.util.ArrayList; import java.util.Iterator; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import sw.common.system.factory.SquareFactory; import sw.common.system.manager.IBoardLocationManager; import sw.common.system.manager.IBoardSelectionManager; /** The model for the game board * * Layout: * * 00 01 02 03 04 05 06 07 08 * 10 11 12 13 14 15 16 17 18 * ... * 80 81 82 83 84 85 86 87 88 * * */ public class Board implements IBoardSelectionManager, IBoardLocationManager, IBoard { /** Default dimension for the board */ public static int COLUMN = 9; public static int ROW = 9; /** The grid of Square */ ArrayList<Column> grid = new ArrayList<Column>(); /** The selection queue */ ArrayBlockingQueue<Square> selection = new ArrayBlockingQueue<Square>(Board.COLUMN * Board.ROW, true); /** Create a new Board * @param fill the board with randomly generated value or not */ public Board() { createBoard(true); } public Board(boolean fill) { createBoard(fill); } /** Create new Board * @param fill whether to fill board with Tile */ private void createBoard(boolean fill) { // Create the board for (int x = 0; x < Board.COLUMN; x++) { // Create rows first since we want easy access to columns ArrayList<Square> row = new ArrayList<Square>(); for (int y = 0; y < Board.ROW; y++) { row.add(SquareFactory.getSquare(fill)); } // Add the new row to the grid grid.add(new Column(row)); } } /** * @param col to get * @return the column of Square */ public Column getColumn(int col) { try { return grid.get(col); } catch (IndexOutOfBoundsException e) { return null; } } /* (non-Javadoc) * @see sw.common.model.entity.IBoard#clear() */ @Override public void clear() { for (int x = 0; x < Board.COLUMN; x++) { grid.get(x).clear(); } } /* (non-Javadoc) * @see sw.common.model.entity.IBoard#fill() */ @Override public void fill() { for (int x = 0; x < Board.COLUMN; x++) { grid.get(x).fill(); } } /* (non-Javadoc) * @see sw.common.model.entity.IBoard#pack() */ @Override public void pack() { for (int x = 0; x < Board.COLUMN; x++) { grid.get(x).pack(); } } /* (non-Javadoc) * @see sw.common.model.entity.IBoard#size() */ @Override public Dimension size() { return new Dimension(Board.COLUMN, Board.ROW); } /** * @param p position to remove * @param fill whether to fill empty spaces with new Tiles */ public boolean remove(Point p) { if (isValidPoint(p)) { Column c = grid.get(p.x); return c.removeTile(p.y); // Remove Tile } return false; } /** * @return the number of Tile currently in the Board */ @Override public int count() { int total = 0; for (int x = 0; x < Board.COLUMN; x++) { total += grid.get(x).count(); } return total; } /** * @param p the position * @param t the new Tile to place at the position * @return true if the new Tile was placed at the position, false if not */ @Override public boolean replace(Point p, Tile t) { if (remove(p)) { return grid.get(p.x).setTile(t, p.y); } return false; } /** * @param p the positon * @return true if the position is empty, false if not */ @Override public boolean isEmpty(Point p) { return grid.get(p.x).getTile(p.y) == null; } ////////////////////////////////////////////////////////// // IBoardLocationnManager methods // /* (non-Javadoc) * @see sw.common.model.entity.IBoard#isValidX(int) */ @Override public boolean isValidX(int x) { return (x >= 0 && x < Board.COLUMN); } /* (non-Javadoc) * @see sw.common.model.entity.IBoard#isValidY(int) */ @Override public boolean isValidY(int y) { return (y >= 0 && y < Board.ROW); } /* (non-Javadoc) * @see sw.common.model.entity.IBoard#isValidPoint(java.awt.Point) */ @Override public boolean isValidPoint(Point p) { return (p != null) && (isValidX(p.x) && isValidY(p.y)); } /** * @param tile the Tile to search for * @return the position of the Tile in the Board */ public Point getPoint(Tile tile) { for (int x = 0; x < Board.COLUMN; x++) { try { int y = grid.get(x).indexOf(tile); return new Point(x, y); } catch (IllegalAccessError e) { continue; } } return null; } /** * @param p the position * @return the Tile at the position */ public Tile getTile(Point p) { if (isValidPoint(p)) { return grid.get(p.x).getTile(p.y); } return null; } /** * @param p the position * @return the Square at the position */ public Square getSquare(Point p) { if (isValidPoint(p)) { return grid.get(p.x).getSquare(p.y); } return null; } ////////////////////////////////////////////////////////// // IBoardSelectionManager methods // /** * @param p the position to select */ public boolean select(Point p) { Square s = getSquare(p); if (!s.isSelected()) { s.setSelected(true); try { selection.put(s); return true; } catch (InterruptedException e) { // Queue is full, discard this selection System.err.println("Selection queue is full!"); return false; } } return true; // if Square already selected, return true } /** * @return the selected Squares */ public Queue<Square> getSelectedSquare() { return selection; } /** * @return the selected Tiles */ public Queue<Tile> getSelectedTile() { Queue<Tile> tq = new ArrayBlockingQueue<Tile>(Board.COLUMN * Board.ROW, true); Iterator<Square> si = selection.iterator(); while (si.hasNext()) { tq.add(si.next().getTile()); } return tq; } public boolean clearSelection() { Iterator<Square> si = selection.iterator(); while (si.hasNext()) { si.next().setSelected(false); si.remove(); } // Just in case... if (!selection.isEmpty()) { selection.clear(); } return true; } }
mit
joltix/rehab-engine
src/com/rehab/world/WorldLoop.java
3810
package com.rehab.world; import com.rehab.animation.Renderer; public class WorldLoop extends Thread { // Number of ticks per second private int mTarTick; // Desired duration in nanoseconds private long mTickInterval; private long mLastTickStart = 0; private long mLastTickDuration = 0; // Whether or not to keep looping private boolean mLoop = true; // The Singleton's instance private static WorldLoop mInstance; // The level to run private Arena mLvl; // Source of Frames to fill and send for drawing private FrameDepot mDepot = FrameDepot.getInstance(); /** * Constructor for the World's state loop. * * @param tickRate the desired ticks per second. * @param arena the level to simulate. */ private WorldLoop(int tickRate, Arena arena) { mLvl = arena; mLvl.setTimescale(1d / tickRate); // Measure time needed mTarTick = tickRate; mTickInterval = 1000000000 / mTarTick; } /** * Gets an instance of the WorldLoop. This method should only be used if getInstance(int, Arena) * was ever called at least once. Calling this method first will throw an IllegalStateException. * * @throws IllegalStateException if getInstance(int, Arena) has never been called. */ public static WorldLoop getInstance() { synchronized (WorldLoop.class) { if (mInstance == null) throw new IllegalStateException("getInstance(int, Arena) has never been called"); return mInstance; } } /** * Gets an instance of the WorldLoop. * * @param tickRate the desired ticks per second. * @param arena the level to simulate. */ public static WorldLoop getInstance(int tickRate, Arena arena) { synchronized (WorldLoop.class) { if (mInstance == null) mInstance = new WorldLoop(tickRate, arena); return mInstance; } } /** * The set desired ticks per second. * * @return the number of ticks per second. */ public int getTickRate() { return mTarTick; } /** * Attempts to stop the WorldLoop from running. This method may * be safely called from any {@link Thread}. */ public static void halt() { synchronized (WorldLoop.class) { if (mInstance == null) { return; } mInstance.mLoop = false; } } @Override public void run() { super.run(); mLastTickStart = System.nanoTime(); while (mLoop) { mLastTickDuration = System.nanoTime() - mLastTickStart; mLastTickStart = System.nanoTime(); // Run physics for at least 1 unit (+ more based on previous frame duration) do { mLvl.stepActors(); mLvl.stepProjectiles(); mLastTickDuration -= mTickInterval; } while (mLastTickDuration > mTickInterval); // Send draw requests to update screen InstanceManager manager = InstanceManager.getInstance(); Iterable<Actor> acts = manager.getLoadedActors(); Iterable<Projectile> projs = manager.getLoadedProjectiles(); Iterable<Prop> props = manager.getLoadedProps(); Frame frame = mDepot.requestFrame(); if (frame == null) { frame = new Frame(); } // Send draw requests for all visible game objs for (Actor a : acts) { if (a.isVisible()) { frame.push(a); } } for (Projectile p : projs) { if (p.isVisible()) { frame.push(p); } } for (Prop p : props) { if (p.isVisible()) { frame.push(p); } } Renderer.getInstance().requestDraw(frame); long currentDuration = System.nanoTime() - mLastTickStart; if (currentDuration < mTickInterval) { try { Thread.sleep((mTickInterval - currentDuration) / 1000000); } catch (InterruptedException e) { e.printStackTrace(); } } else if (currentDuration > mTickInterval) { try { Thread.sleep((currentDuration - mTickInterval) / 1000000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
mit
woshiwpa/CoreMathImgProc
src/com/cyzapps/uptloaderssprint/UPTJavaLoader19.java
21815
package com.cyzapps.uptloaderssprint; import com.cyzapps.mathrecog.UnitPrototypeMgr; import com.cyzapps.mathrecog.UnitPrototypeMgr.UnitProtoType; public class UPTJavaLoader19 { public static void load(UnitPrototypeMgr uptMgr) { { byte[][] biMatrix = new byte[26][41]; biMatrix[0][7] = 1; biMatrix[0][39] = 1; biMatrix[0][40] = 1; biMatrix[1][5] = 1; biMatrix[1][6] = 1; biMatrix[1][38] = 1; biMatrix[2][3] = 1; biMatrix[2][4] = 1; biMatrix[2][36] = 1; biMatrix[2][37] = 1; biMatrix[3][2] = 1; biMatrix[3][35] = 1; biMatrix[4][1] = 1; biMatrix[4][33] = 1; biMatrix[4][34] = 1; biMatrix[5][1] = 1; biMatrix[5][31] = 1; biMatrix[5][32] = 1; biMatrix[6][1] = 1; biMatrix[6][30] = 1; biMatrix[7][1] = 1; biMatrix[7][28] = 1; biMatrix[7][29] = 1; biMatrix[8][1] = 1; biMatrix[8][27] = 1; biMatrix[9][1] = 1; biMatrix[9][25] = 1; biMatrix[9][26] = 1; biMatrix[10][1] = 1; biMatrix[10][24] = 1; biMatrix[11][1] = 1; biMatrix[11][22] = 1; biMatrix[11][23] = 1; biMatrix[12][1] = 1; biMatrix[12][20] = 1; biMatrix[12][21] = 1; biMatrix[13][1] = 1; biMatrix[13][19] = 1; biMatrix[14][1] = 1; biMatrix[14][17] = 1; biMatrix[14][18] = 1; biMatrix[15][1] = 1; biMatrix[15][16] = 1; biMatrix[16][1] = 1; biMatrix[16][14] = 1; biMatrix[16][15] = 1; biMatrix[17][1] = 1; biMatrix[17][12] = 1; biMatrix[17][13] = 1; biMatrix[18][1] = 1; biMatrix[18][11] = 1; biMatrix[19][1] = 1; biMatrix[19][9] = 1; biMatrix[19][10] = 1; biMatrix[20][1] = 1; biMatrix[20][7] = 1; biMatrix[20][8] = 1; biMatrix[21][2] = 1; biMatrix[21][6] = 1; biMatrix[22][2] = 1; biMatrix[22][3] = 1; biMatrix[22][4] = 1; biMatrix[22][5] = 1; biMatrix[23][1] = 1; biMatrix[24][1] = 1; biMatrix[25][0] = 1; uptMgr.addUnitPrototype(UnitProtoType.Type.TYPE_SEVEN, "cambria_italian_48_thinned", 0.0, 0.0, biMatrix, UnitPrototypeMgr.NORMAL_UPT_LIST); } { byte[][] biMatrix = new byte[40][60]; biMatrix[0][36] = 1; biMatrix[0][37] = 1; biMatrix[0][38] = 1; biMatrix[0][39] = 1; biMatrix[1][20] = 1; biMatrix[1][21] = 1; biMatrix[1][32] = 1; biMatrix[1][33] = 1; biMatrix[1][34] = 1; biMatrix[1][35] = 1; biMatrix[1][40] = 1; biMatrix[1][41] = 1; biMatrix[1][42] = 1; biMatrix[1][43] = 1; biMatrix[1][44] = 1; biMatrix[1][45] = 1; biMatrix[2][18] = 1; biMatrix[2][19] = 1; biMatrix[2][22] = 1; biMatrix[2][23] = 1; biMatrix[2][24] = 1; biMatrix[2][30] = 1; biMatrix[2][31] = 1; biMatrix[2][46] = 1; biMatrix[2][47] = 1; biMatrix[2][48] = 1; biMatrix[3][16] = 1; biMatrix[3][17] = 1; biMatrix[3][25] = 1; biMatrix[3][26] = 1; biMatrix[3][29] = 1; biMatrix[3][49] = 1; biMatrix[4][15] = 1; biMatrix[4][27] = 1; biMatrix[4][28] = 1; biMatrix[4][50] = 1; biMatrix[4][51] = 1; biMatrix[5][14] = 1; biMatrix[5][28] = 1; biMatrix[5][52] = 1; biMatrix[6][13] = 1; biMatrix[6][28] = 1; biMatrix[6][53] = 1; biMatrix[7][12] = 1; biMatrix[7][28] = 1; biMatrix[7][53] = 1; biMatrix[8][11] = 1; biMatrix[8][28] = 1; biMatrix[8][54] = 1; biMatrix[9][10] = 1; biMatrix[9][28] = 1; biMatrix[9][55] = 1; biMatrix[10][9] = 1; biMatrix[10][28] = 1; biMatrix[10][55] = 1; biMatrix[11][9] = 1; biMatrix[11][27] = 1; biMatrix[11][56] = 1; biMatrix[12][8] = 1; biMatrix[12][26] = 1; biMatrix[12][56] = 1; biMatrix[13][7] = 1; biMatrix[13][25] = 1; biMatrix[13][57] = 1; biMatrix[14][7] = 1; biMatrix[14][25] = 1; biMatrix[14][58] = 1; biMatrix[15][6] = 1; biMatrix[15][24] = 1; biMatrix[15][58] = 1; biMatrix[16][5] = 1; biMatrix[16][24] = 1; biMatrix[16][58] = 1; biMatrix[17][5] = 1; biMatrix[17][24] = 1; biMatrix[17][59] = 1; biMatrix[18][4] = 1; biMatrix[18][23] = 1; biMatrix[18][59] = 1; biMatrix[19][4] = 1; biMatrix[19][23] = 1; biMatrix[19][59] = 1; biMatrix[20][3] = 1; biMatrix[20][23] = 1; biMatrix[20][59] = 1; biMatrix[21][3] = 1; biMatrix[21][23] = 1; biMatrix[21][59] = 1; biMatrix[22][2] = 1; biMatrix[22][23] = 1; biMatrix[22][59] = 1; biMatrix[23][2] = 1; biMatrix[23][23] = 1; biMatrix[23][58] = 1; biMatrix[24][2] = 1; biMatrix[24][23] = 1; biMatrix[24][58] = 1; biMatrix[25][2] = 1; biMatrix[25][24] = 1; biMatrix[25][58] = 1; biMatrix[26][2] = 1; biMatrix[26][24] = 1; biMatrix[26][57] = 1; biMatrix[27][2] = 1; biMatrix[27][25] = 1; biMatrix[27][57] = 1; biMatrix[28][1] = 1; biMatrix[28][25] = 1; biMatrix[28][56] = 1; biMatrix[29][1] = 1; biMatrix[29][26] = 1; biMatrix[29][55] = 1; biMatrix[30][1] = 1; biMatrix[30][26] = 1; biMatrix[30][55] = 1; biMatrix[31][1] = 1; biMatrix[31][27] = 1; biMatrix[31][54] = 1; biMatrix[32][1] = 1; biMatrix[32][28] = 1; biMatrix[32][53] = 1; biMatrix[33][1] = 1; biMatrix[33][28] = 1; biMatrix[33][53] = 1; biMatrix[34][0] = 1; biMatrix[34][29] = 1; biMatrix[34][52] = 1; biMatrix[35][0] = 1; biMatrix[35][30] = 1; biMatrix[35][51] = 1; biMatrix[36][0] = 1; biMatrix[36][30] = 1; biMatrix[36][50] = 1; biMatrix[36][51] = 1; biMatrix[37][1] = 1; biMatrix[37][31] = 1; biMatrix[37][32] = 1; biMatrix[37][49] = 1; biMatrix[37][52] = 1; biMatrix[38][2] = 1; biMatrix[38][33] = 1; biMatrix[38][34] = 1; biMatrix[38][47] = 1; biMatrix[38][48] = 1; biMatrix[38][53] = 1; biMatrix[39][3] = 1; biMatrix[39][35] = 1; biMatrix[39][36] = 1; biMatrix[39][37] = 1; biMatrix[39][38] = 1; biMatrix[39][39] = 1; biMatrix[39][40] = 1; biMatrix[39][41] = 1; biMatrix[39][42] = 1; biMatrix[39][43] = 1; biMatrix[39][44] = 1; biMatrix[39][45] = 1; biMatrix[39][46] = 1; uptMgr.addUnitPrototype(UnitProtoType.Type.TYPE_SIX, "bookman_old_black_72_thinned", 0.0, 0.0, biMatrix, UnitPrototypeMgr.NORMAL_UPT_LIST); } { byte[][] biMatrix = new byte[22][44]; biMatrix[0][18] = 1; biMatrix[0][19] = 1; biMatrix[0][20] = 1; biMatrix[0][23] = 1; biMatrix[0][24] = 1; biMatrix[0][25] = 1; biMatrix[0][26] = 1; biMatrix[0][27] = 1; biMatrix[0][28] = 1; biMatrix[0][29] = 1; biMatrix[0][30] = 1; biMatrix[0][31] = 1; biMatrix[0][32] = 1; biMatrix[0][33] = 1; biMatrix[0][34] = 1; biMatrix[1][15] = 1; biMatrix[1][16] = 1; biMatrix[1][17] = 1; biMatrix[1][21] = 1; biMatrix[1][22] = 1; biMatrix[1][35] = 1; biMatrix[1][36] = 1; biMatrix[1][37] = 1; biMatrix[2][12] = 1; biMatrix[2][13] = 1; biMatrix[2][14] = 1; biMatrix[2][22] = 1; biMatrix[2][38] = 1; biMatrix[3][11] = 1; biMatrix[3][22] = 1; biMatrix[3][39] = 1; biMatrix[4][9] = 1; biMatrix[4][10] = 1; biMatrix[4][21] = 1; biMatrix[4][40] = 1; biMatrix[5][8] = 1; biMatrix[5][21] = 1; biMatrix[5][41] = 1; biMatrix[6][7] = 1; biMatrix[6][20] = 1; biMatrix[6][41] = 1; biMatrix[7][6] = 1; biMatrix[7][20] = 1; biMatrix[7][42] = 1; biMatrix[8][5] = 1; biMatrix[8][19] = 1; biMatrix[8][42] = 1; biMatrix[9][5] = 1; biMatrix[9][19] = 1; biMatrix[9][43] = 1; biMatrix[10][4] = 1; biMatrix[10][19] = 1; biMatrix[10][43] = 1; biMatrix[11][3] = 1; biMatrix[11][19] = 1; biMatrix[11][43] = 1; biMatrix[12][2] = 1; biMatrix[12][18] = 1; biMatrix[12][43] = 1; biMatrix[13][2] = 1; biMatrix[13][18] = 1; biMatrix[13][42] = 1; biMatrix[14][1] = 1; biMatrix[14][18] = 1; biMatrix[14][42] = 1; biMatrix[15][1] = 1; biMatrix[15][19] = 1; biMatrix[15][41] = 1; biMatrix[16][1] = 1; biMatrix[16][20] = 1; biMatrix[16][41] = 1; biMatrix[17][1] = 1; biMatrix[17][20] = 1; biMatrix[17][40] = 1; biMatrix[18][0] = 1; biMatrix[18][21] = 1; biMatrix[18][39] = 1; biMatrix[19][0] = 1; biMatrix[19][22] = 1; biMatrix[19][38] = 1; biMatrix[20][23] = 1; biMatrix[20][36] = 1; biMatrix[20][37] = 1; biMatrix[21][24] = 1; biMatrix[21][25] = 1; biMatrix[21][26] = 1; biMatrix[21][27] = 1; biMatrix[21][28] = 1; biMatrix[21][29] = 1; biMatrix[21][30] = 1; biMatrix[21][31] = 1; biMatrix[21][32] = 1; biMatrix[21][33] = 1; biMatrix[21][34] = 1; biMatrix[21][35] = 1; uptMgr.addUnitPrototype(UnitProtoType.Type.TYPE_SIX, "cambria_48_thinned", 0.0, 0.0, biMatrix, UnitPrototypeMgr.NORMAL_UPT_LIST); } { byte[][] biMatrix = new byte[25][42]; biMatrix[0][23] = 1; biMatrix[0][24] = 1; biMatrix[0][25] = 1; biMatrix[0][26] = 1; biMatrix[0][27] = 1; biMatrix[0][28] = 1; biMatrix[0][29] = 1; biMatrix[0][30] = 1; biMatrix[0][31] = 1; biMatrix[0][32] = 1; biMatrix[0][33] = 1; biMatrix[1][22] = 1; biMatrix[1][34] = 1; biMatrix[1][35] = 1; biMatrix[1][36] = 1; biMatrix[2][16] = 1; biMatrix[2][17] = 1; biMatrix[2][18] = 1; biMatrix[2][19] = 1; biMatrix[2][21] = 1; biMatrix[2][37] = 1; biMatrix[3][14] = 1; biMatrix[3][15] = 1; biMatrix[3][20] = 1; biMatrix[3][38] = 1; biMatrix[4][13] = 1; biMatrix[4][20] = 1; biMatrix[4][39] = 1; biMatrix[5][11] = 1; biMatrix[5][12] = 1; biMatrix[5][20] = 1; biMatrix[5][40] = 1; biMatrix[6][10] = 1; biMatrix[6][19] = 1; biMatrix[6][40] = 1; biMatrix[7][9] = 1; biMatrix[7][19] = 1; biMatrix[7][41] = 1; biMatrix[8][8] = 1; biMatrix[8][18] = 1; biMatrix[8][41] = 1; biMatrix[9][7] = 1; biMatrix[9][18] = 1; biMatrix[9][41] = 1; biMatrix[10][7] = 1; biMatrix[10][18] = 1; biMatrix[10][41] = 1; biMatrix[11][6] = 1; biMatrix[11][18] = 1; biMatrix[11][40] = 1; biMatrix[12][5] = 1; biMatrix[12][17] = 1; biMatrix[12][40] = 1; biMatrix[13][4] = 1; biMatrix[13][17] = 1; biMatrix[13][39] = 1; biMatrix[14][3] = 1; biMatrix[14][17] = 1; biMatrix[14][39] = 1; biMatrix[15][3] = 1; biMatrix[15][18] = 1; biMatrix[15][38] = 1; biMatrix[16][2] = 1; biMatrix[16][18] = 1; biMatrix[16][38] = 1; biMatrix[17][2] = 1; biMatrix[17][19] = 1; biMatrix[17][37] = 1; biMatrix[18][2] = 1; biMatrix[18][19] = 1; biMatrix[18][35] = 1; biMatrix[18][36] = 1; biMatrix[19][1] = 1; biMatrix[19][20] = 1; biMatrix[19][33] = 1; biMatrix[19][34] = 1; biMatrix[20][1] = 1; biMatrix[20][21] = 1; biMatrix[20][22] = 1; biMatrix[20][23] = 1; biMatrix[20][24] = 1; biMatrix[20][29] = 1; biMatrix[20][30] = 1; biMatrix[20][31] = 1; biMatrix[20][32] = 1; biMatrix[21][1] = 1; biMatrix[21][25] = 1; biMatrix[21][26] = 1; biMatrix[21][27] = 1; biMatrix[21][28] = 1; biMatrix[22][1] = 1; biMatrix[23][1] = 1; biMatrix[24][0] = 1; uptMgr.addUnitPrototype(UnitProtoType.Type.TYPE_SIX, "cambria_italian_48_thinned", 0.0, 0.0, biMatrix, UnitPrototypeMgr.NORMAL_UPT_LIST); } { byte[][] biMatrix = new byte[22][43]; biMatrix[0][17] = 1; biMatrix[0][18] = 1; biMatrix[0][19] = 1; biMatrix[0][22] = 1; biMatrix[0][23] = 1; biMatrix[0][24] = 1; biMatrix[0][25] = 1; biMatrix[0][26] = 1; biMatrix[0][27] = 1; biMatrix[0][28] = 1; biMatrix[0][29] = 1; biMatrix[0][30] = 1; biMatrix[0][31] = 1; biMatrix[0][32] = 1; biMatrix[0][33] = 1; biMatrix[1][9] = 1; biMatrix[1][10] = 1; biMatrix[1][11] = 1; biMatrix[1][12] = 1; biMatrix[1][13] = 1; biMatrix[1][14] = 1; biMatrix[1][15] = 1; biMatrix[1][16] = 1; biMatrix[1][20] = 1; biMatrix[1][21] = 1; biMatrix[1][34] = 1; biMatrix[1][35] = 1; biMatrix[1][36] = 1; biMatrix[2][6] = 1; biMatrix[2][7] = 1; biMatrix[2][8] = 1; biMatrix[2][21] = 1; biMatrix[2][37] = 1; biMatrix[3][4] = 1; biMatrix[3][5] = 1; biMatrix[3][21] = 1; biMatrix[3][38] = 1; biMatrix[4][3] = 1; biMatrix[4][20] = 1; biMatrix[4][39] = 1; biMatrix[5][2] = 1; biMatrix[5][19] = 1; biMatrix[5][40] = 1; biMatrix[6][2] = 1; biMatrix[6][18] = 1; biMatrix[6][40] = 1; biMatrix[7][1] = 1; biMatrix[7][18] = 1; biMatrix[7][41] = 1; biMatrix[8][1] = 1; biMatrix[8][17] = 1; biMatrix[8][41] = 1; biMatrix[9][0] = 1; biMatrix[9][17] = 1; biMatrix[9][42] = 1; biMatrix[10][0] = 1; biMatrix[10][17] = 1; biMatrix[10][42] = 1; biMatrix[11][0] = 1; biMatrix[11][17] = 1; biMatrix[11][42] = 1; biMatrix[12][0] = 1; biMatrix[12][17] = 1; biMatrix[12][42] = 1; biMatrix[13][1] = 1; biMatrix[13][17] = 1; biMatrix[13][41] = 1; biMatrix[14][1] = 1; biMatrix[14][17] = 1; biMatrix[14][41] = 1; biMatrix[15][1] = 1; biMatrix[15][18] = 1; biMatrix[15][40] = 1; biMatrix[16][1] = 1; biMatrix[16][19] = 1; biMatrix[16][40] = 1; biMatrix[17][2] = 1; biMatrix[17][3] = 1; biMatrix[17][19] = 1; biMatrix[17][39] = 1; biMatrix[18][4] = 1; biMatrix[18][20] = 1; biMatrix[18][38] = 1; biMatrix[19][5] = 1; biMatrix[19][10] = 1; biMatrix[19][21] = 1; biMatrix[19][37] = 1; biMatrix[20][6] = 1; biMatrix[20][7] = 1; biMatrix[20][8] = 1; biMatrix[20][9] = 1; biMatrix[20][22] = 1; biMatrix[20][35] = 1; biMatrix[20][36] = 1; biMatrix[21][23] = 1; biMatrix[21][24] = 1; biMatrix[21][25] = 1; biMatrix[21][26] = 1; biMatrix[21][27] = 1; biMatrix[21][28] = 1; biMatrix[21][29] = 1; biMatrix[21][30] = 1; biMatrix[21][31] = 1; biMatrix[21][32] = 1; biMatrix[21][33] = 1; biMatrix[21][34] = 1; uptMgr.addUnitPrototype(UnitProtoType.Type.TYPE_SIX, "math_font1_48_thinned", 0.0, 0.0, biMatrix, UnitPrototypeMgr.NORMAL_UPT_LIST); } { byte[][] biMatrix = new byte[14][26]; biMatrix[0][11] = 1; biMatrix[0][17] = 1; biMatrix[0][18] = 1; biMatrix[0][19] = 1; biMatrix[0][20] = 1; biMatrix[1][7] = 1; biMatrix[1][8] = 1; biMatrix[1][9] = 1; biMatrix[1][10] = 1; biMatrix[1][12] = 1; biMatrix[1][13] = 1; biMatrix[1][15] = 1; biMatrix[1][16] = 1; biMatrix[1][21] = 1; biMatrix[1][22] = 1; biMatrix[1][25] = 1; biMatrix[2][4] = 1; biMatrix[2][5] = 1; biMatrix[2][6] = 1; biMatrix[2][14] = 1; biMatrix[2][23] = 1; biMatrix[2][24] = 1; biMatrix[3][3] = 1; biMatrix[3][14] = 1; biMatrix[3][24] = 1; biMatrix[4][2] = 1; biMatrix[4][14] = 1; biMatrix[4][25] = 1; biMatrix[5][2] = 1; biMatrix[5][14] = 1; biMatrix[5][25] = 1; biMatrix[6][1] = 1; biMatrix[6][14] = 1; biMatrix[6][25] = 1; biMatrix[7][0] = 1; biMatrix[7][14] = 1; biMatrix[7][25] = 1; biMatrix[8][1] = 1; biMatrix[8][14] = 1; biMatrix[8][25] = 1; biMatrix[9][2] = 1; biMatrix[9][15] = 1; biMatrix[9][25] = 1; biMatrix[10][3] = 1; biMatrix[10][5] = 1; biMatrix[10][15] = 1; biMatrix[10][24] = 1; biMatrix[11][4] = 1; biMatrix[11][16] = 1; biMatrix[11][24] = 1; biMatrix[12][3] = 1; biMatrix[12][5] = 1; biMatrix[12][15] = 1; biMatrix[12][17] = 1; biMatrix[12][21] = 1; biMatrix[12][22] = 1; biMatrix[12][23] = 1; biMatrix[12][24] = 1; biMatrix[13][2] = 1; biMatrix[13][6] = 1; biMatrix[13][14] = 1; biMatrix[13][18] = 1; biMatrix[13][19] = 1; biMatrix[13][20] = 1; biMatrix[13][25] = 1; uptMgr.addUnitPrototype(UnitProtoType.Type.TYPE_SIX, "math_font2_24_thinned", 0.0, 0.0, biMatrix, UnitPrototypeMgr.NORMAL_UPT_LIST); } { byte[][] biMatrix = new byte[31][46]; biMatrix[0][28] = 1; biMatrix[0][29] = 1; biMatrix[0][30] = 1; biMatrix[0][31] = 1; biMatrix[0][32] = 1; biMatrix[0][33] = 1; biMatrix[0][34] = 1; biMatrix[0][35] = 1; biMatrix[0][36] = 1; biMatrix[0][37] = 1; biMatrix[0][38] = 1; biMatrix[0][42] = 1; biMatrix[1][25] = 1; biMatrix[1][26] = 1; biMatrix[1][27] = 1; biMatrix[1][39] = 1; biMatrix[1][41] = 1; biMatrix[2][24] = 1; biMatrix[2][40] = 1; biMatrix[3][16] = 1; biMatrix[3][17] = 1; biMatrix[3][18] = 1; biMatrix[3][22] = 1; biMatrix[3][23] = 1; biMatrix[3][41] = 1; biMatrix[4][11] = 1; biMatrix[4][12] = 1; biMatrix[4][13] = 1; biMatrix[4][14] = 1; biMatrix[4][15] = 1; biMatrix[4][19] = 1; biMatrix[4][20] = 1; biMatrix[4][21] = 1; biMatrix[4][42] = 1; biMatrix[5][9] = 1; biMatrix[5][10] = 1; biMatrix[5][21] = 1; biMatrix[5][43] = 1; biMatrix[6][8] = 1; biMatrix[6][21] = 1; biMatrix[6][44] = 1; biMatrix[7][7] = 1; biMatrix[7][21] = 1; biMatrix[7][45] = 1; biMatrix[8][6] = 1; biMatrix[8][21] = 1; biMatrix[8][45] = 1; biMatrix[9][5] = 1; biMatrix[9][21] = 1; biMatrix[9][45] = 1; biMatrix[10][4] = 1; biMatrix[10][20] = 1; biMatrix[10][45] = 1; biMatrix[11][3] = 1; biMatrix[11][20] = 1; biMatrix[11][45] = 1; biMatrix[12][3] = 1; biMatrix[12][20] = 1; biMatrix[12][44] = 1; biMatrix[13][2] = 1; biMatrix[13][19] = 1; biMatrix[13][44] = 1; biMatrix[14][2] = 1; biMatrix[14][19] = 1; biMatrix[14][44] = 1; biMatrix[15][1] = 1; biMatrix[15][20] = 1; biMatrix[15][43] = 1; biMatrix[16][1] = 1; biMatrix[16][20] = 1; biMatrix[16][42] = 1; biMatrix[17][0] = 1; biMatrix[17][20] = 1; biMatrix[17][42] = 1; biMatrix[18][0] = 1; biMatrix[18][21] = 1; biMatrix[18][41] = 1; biMatrix[19][0] = 1; biMatrix[19][21] = 1; biMatrix[19][40] = 1; biMatrix[20][1] = 1; biMatrix[20][20] = 1; biMatrix[20][22] = 1; biMatrix[20][39] = 1; biMatrix[21][1] = 1; biMatrix[21][19] = 1; biMatrix[21][23] = 1; biMatrix[21][37] = 1; biMatrix[21][38] = 1; biMatrix[22][2] = 1; biMatrix[22][18] = 1; biMatrix[22][24] = 1; biMatrix[22][25] = 1; biMatrix[22][26] = 1; biMatrix[22][27] = 1; biMatrix[22][32] = 1; biMatrix[22][33] = 1; biMatrix[22][34] = 1; biMatrix[22][35] = 1; biMatrix[22][36] = 1; biMatrix[23][2] = 1; biMatrix[23][11] = 1; biMatrix[23][28] = 1; biMatrix[23][29] = 1; biMatrix[23][30] = 1; biMatrix[23][31] = 1; biMatrix[24][3] = 1; biMatrix[24][10] = 1; biMatrix[25][4] = 1; biMatrix[25][9] = 1; biMatrix[26][4] = 1; biMatrix[26][5] = 1; biMatrix[26][8] = 1; biMatrix[27][3] = 1; biMatrix[27][6] = 1; biMatrix[27][7] = 1; biMatrix[27][8] = 1; biMatrix[28][2] = 1; biMatrix[28][9] = 1; biMatrix[29][1] = 1; biMatrix[29][10] = 1; biMatrix[30][0] = 1; biMatrix[30][11] = 1; uptMgr.addUnitPrototype(UnitProtoType.Type.TYPE_SIX, "math_font3_46_thinned", 0.0, 0.0, biMatrix, UnitPrototypeMgr.NORMAL_UPT_LIST); } { byte[][] biMatrix = new byte[41][49]; biMatrix[0][24] = 1; biMatrix[1][23] = 1; biMatrix[1][25] = 1; biMatrix[2][23] = 1; biMatrix[2][26] = 1; biMatrix[3][22] = 1; biMatrix[3][27] = 1; biMatrix[4][21] = 1; biMatrix[4][27] = 1; biMatrix[5][20] = 1; biMatrix[5][28] = 1; biMatrix[6][20] = 1; biMatrix[6][29] = 1; biMatrix[7][19] = 1; biMatrix[7][30] = 1; biMatrix[8][19] = 1; biMatrix[8][30] = 1; biMatrix[9][18] = 1; biMatrix[9][31] = 1; biMatrix[10][18] = 1; biMatrix[10][31] = 1; biMatrix[11][17] = 1; biMatrix[11][32] = 1; biMatrix[12][17] = 1; biMatrix[12][32] = 1; biMatrix[13][16] = 1; biMatrix[13][33] = 1; biMatrix[14][16] = 1; biMatrix[14][33] = 1; biMatrix[15][15] = 1; biMatrix[15][34] = 1; biMatrix[16][15] = 1; biMatrix[16][34] = 1; biMatrix[17][14] = 1; biMatrix[17][34] = 1; biMatrix[18][14] = 1; biMatrix[18][35] = 1; biMatrix[19][13] = 1; biMatrix[19][35] = 1; biMatrix[20][13] = 1; biMatrix[20][36] = 1; biMatrix[21][12] = 1; biMatrix[21][36] = 1; biMatrix[22][12] = 1; biMatrix[22][37] = 1; biMatrix[23][11] = 1; biMatrix[23][37] = 1; biMatrix[24][11] = 1; biMatrix[24][38] = 1; biMatrix[25][10] = 1; biMatrix[25][38] = 1; biMatrix[26][10] = 1; biMatrix[26][39] = 1; biMatrix[27][9] = 1; biMatrix[27][39] = 1; biMatrix[28][9] = 1; biMatrix[28][40] = 1; biMatrix[29][8] = 1; biMatrix[29][40] = 1; biMatrix[30][8] = 1; biMatrix[30][41] = 1; biMatrix[31][7] = 1; biMatrix[31][41] = 1; biMatrix[32][7] = 1; biMatrix[32][42] = 1; biMatrix[33][6] = 1; biMatrix[33][42] = 1; biMatrix[34][6] = 1; biMatrix[34][43] = 1; biMatrix[35][6] = 1; biMatrix[35][43] = 1; biMatrix[36][5] = 1; biMatrix[36][44] = 1; biMatrix[37][4] = 1; biMatrix[37][5] = 1; biMatrix[37][44] = 1; biMatrix[38][2] = 1; biMatrix[38][3] = 1; biMatrix[38][5] = 1; biMatrix[38][45] = 1; biMatrix[38][46] = 1; biMatrix[39][1] = 1; biMatrix[39][47] = 1; biMatrix[40][0] = 1; biMatrix[40][48] = 1; uptMgr.addUnitPrototype(UnitProtoType.Type.TYPE_SMALLER, "bookman_old_black_72_thinned", 3.0, 3.0, biMatrix, UnitPrototypeMgr.NORMAL_UPT_LIST); } } }
mit
PLJNS/Rutgers-Soft-Meth-Spring-2013
Chess/src/util/InvalidMoveException.java
251
package util; /** * * @author Paul Jones * */ public class InvalidMoveException extends ChessException { /** * */ private static final long serialVersionUID = 1L; public InvalidMoveException(String message) { super(message); } }
mit