repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
Dexter245/JTetris
core/src/com/dextersLaboratory/jtetris/model/GameState.java
102
package com.dextersLaboratory.jtetris.model; public enum GameState { playing, paused, gameOver; }
mit
McJty/RFTools
src/main/java/mcjty/rftools/blocks/shield/BakedModelLoader.java
1237
package mcjty.rftools.blocks.shield; import mcjty.rftools.RFTools; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.resources.IResourceManager; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.model.ICustomModelLoader; import net.minecraftforge.client.model.IModel; public class BakedModelLoader implements ICustomModelLoader { public static final CamoModel MIMIC_MODEL = new CamoModel(); @Override public boolean accepts(ResourceLocation modelLocation) { if (!modelLocation.getResourceDomain().equals(RFTools.MODID)) { return false; } if (modelLocation instanceof ModelResourceLocation && ((ModelResourceLocation)modelLocation).getVariant().equals("inventory")) { return false; } return CamoShieldBlock.CAMO.equals(modelLocation.getResourcePath()); } @Override public IModel loadModel(ResourceLocation modelLocation) { if (CamoShieldBlock.CAMO.equals(modelLocation.getResourcePath())) { return MIMIC_MODEL; } return null; } @Override public void onResourceManagerReload(IResourceManager resourceManager) { } }
mit
ssdsham/quicksort-timing
SortTiming.java
4608
/*Coded by Sham Dorairaj */ import java.util.Stack; //Uncomment the following imports to use without JUnint. Keep StopWatch.java and RandomInputGenerator.java in build /*import java.util.ArrayList; import java.util.List; */ public class SortTiming{ /* * @param inputTrack Stack of input values to sort * @return Stack of values from input in sorted order */ public static Stack<Integer> trainSort(Stack<Integer> inputTrack) { //Catch Null input exception if(inputTrack == null){ System.out.println("Null Value Nothing to Sort"); System.out.println("---------------------------"); Stack<Integer> exitTrack=new Stack<Integer>(); return exitTrack; } //Catch Empty input exceptions else if (inputTrack.isEmpty()){ System.out.println("Nothing to Sort"); System.out.println("---------------------------"); Stack<Integer> exitTrack=new Stack<Integer>(); return exitTrack; } else{ Stack<Integer> sideTrack=new Stack<Integer>(); Stack<Integer> exitTrack=new Stack<Integer>(); StopWatch stopWatch = new StopWatch(); stopWatch.start(); trainSort(inputTrack,sideTrack,exitTrack); stopWatch.stop(); System.out.print("\nOutput Track: "); System.out.print("[ "); for(int val: exitTrack){ System.out.print(val+" "); } System.out.print("]"); System.out.println(""); System.out.println("\nSorting took : "+stopWatch.getElapsedTime()+" milliseconds"); System.out.println("---------------------------"); return exitTrack; } } //Sort Train cars on inputTrack and Put them on exitTrack in ascending order /* * Algorithm: * Start by popping inputTrack and pushing into exitTrack. * Compare inputTrack, sideTrack and exitTrack. * Push/Pop such that smaller value goes to exitTrack and larger value remains on sideTrack. * Once inputTrack is exhausted pop all cars from sideTrack and push onto exitTrack */ private static void trainSort(Stack<Integer> inputTrack, Stack<Integer> sideTrack, Stack<Integer> exitTrack){ while(!inputTrack.isEmpty()){ int x = 0; if(exitTrack.isEmpty()){ x = inputTrack.pop(); System.out.println("\nMove "+x +" from input to exit"); exitTrack.push(x); }else if(inputTrack.peek() >= exitTrack.peek() && sideTrack.isEmpty() ){ x = inputTrack.pop(); System.out.println("\nMove "+x +" from input to exit"); exitTrack.push(x); }else if(inputTrack.peek() >= exitTrack.peek() && !sideTrack.isEmpty()){ if(inputTrack.peek() >= sideTrack.peek()){ x = sideTrack.pop(); System.out.println("\nMove "+x +" from siding to exit"); exitTrack.push(x); }else{ x=inputTrack.pop(); System.out.println("\nMove "+x +" from input to exit"); exitTrack.push(x); } }else if(inputTrack.peek() < exitTrack.peek() && !sideTrack.isEmpty()){ if(inputTrack.peek() < sideTrack.peek()){ x= exitTrack.pop(); System.out.println("\nMove "+x +" from exit to siding"); sideTrack.push(x); } } else if(inputTrack.peek() < exitTrack.peek() && sideTrack.isEmpty()){ x= exitTrack.pop(); System.out.println("\nMove "+x +" from exit to siding"); sideTrack.push(x); } } sortSideTrack(sideTrack,exitTrack); } //Dump all remaining train cars from side track onto exit track. They are already sorted in the sortExitTrack function public static void sortSideTrack( Stack<Integer> sideTrack, Stack<Integer> exitTrack){ int x = 0; while(!sideTrack.isEmpty()){ x = sideTrack.pop(); System.out.println("\nMove "+x +" from siding to exit"); exitTrack.push(x); } } } //Remove this parenthesis to use without Lab1Test JUnint. Keep StopWatch.java and RandomInputGenerator.java in build //Uncomment the following to use without Lab1Test JUnint. Keep StopWatch.java and RandomInputGenerator.java in build /* public static void main(String[] args) { List<Integer> inputList = new ArrayList<Integer>(); inputList = RandomInputGenerator.genInTrack(100, 100); Stack<Integer> ipStack=new Stack<Integer>(); for (int inp : inputList) { ipStack.push(inp); } System.out.println("Input track: "); for(int val: ipStack){ System.out.print(val+" "); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); Stack<Integer> outputStack =new Stack<Integer>(); outputStack = trainSort(ipStack); System.out.println("\nOutput stack: "); for(int val: outputStack){ System.out.print(val+" "); } stopWatch.stop(); System.out.println("\nSorting took : "+stopWatch.getElapsedTime()+" milliseconds"); } } */
mit
CyclopsMC/ColossalChests
src/main/java/org/cyclops/colossalchests/advancement/criterion/ChestFormedTrigger.java
3585
package org.cyclops.colossalchests.advancement.criterion; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import net.minecraft.advancements.criterion.AbstractCriterionTrigger; import net.minecraft.advancements.criterion.CriterionInstance; import net.minecraft.advancements.criterion.EntityPredicate; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.loot.ConditionArrayParser; import net.minecraft.util.JSONUtils; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import org.apache.commons.lang3.tuple.Pair; import org.cyclops.colossalchests.Reference; import org.cyclops.colossalchests.block.ChestMaterial; import org.cyclops.cyclopscore.advancement.criterion.ICriterionInstanceTestable; import javax.annotation.Nullable; import java.util.Objects; import java.util.stream.Collectors; /** * Triggers when a colossal chest is formed. * @author rubensworks */ public class ChestFormedTrigger extends AbstractCriterionTrigger<ChestFormedTrigger.Instance> { private final ResourceLocation ID = new ResourceLocation(Reference.MOD_ID, "chest_formed"); public ChestFormedTrigger() { MinecraftForge.EVENT_BUS.register(this); } @Override public ResourceLocation getId() { return ID; } @Override public Instance deserializeTrigger(JsonObject json, EntityPredicate.AndPredicate entityPredicate, ConditionArrayParser conditionsParser) { ChestMaterial material = null; JsonElement element = json.get("material"); if (element != null && !element.isJsonNull()) { String materialString = element.getAsString(); try { material = Objects.requireNonNull(ChestMaterial.valueOf(materialString), "Could not find a chest material by name " + materialString); } catch (IllegalArgumentException e) { throw new JsonSyntaxException("Could not find a colossal chest material by name " + materialString + ". Allowed values: " + ChestMaterial.VALUES.stream().map(ChestMaterial::getName).collect(Collectors.toList())); } } Integer minimumSize = null; JsonElement elementSize = json.get("minimumSize"); if (elementSize != null && !elementSize.isJsonNull()) { minimumSize = JSONUtils.getInt(elementSize, "minimumSize"); } return new Instance(getId(), entityPredicate, material, minimumSize); } public void test(ServerPlayerEntity player, ChestMaterial material, int size) { this.triggerListeners(player, (instance) -> { return instance.test(player, Pair.of(material, size)); }); } public static class Instance extends CriterionInstance implements ICriterionInstanceTestable<Pair<ChestMaterial, Integer>> { private final ChestMaterial material; private final Integer minimumSize; public Instance(ResourceLocation criterionIn, EntityPredicate.AndPredicate player, @Nullable ChestMaterial material, @Nullable Integer minimumSize) { super(criterionIn, player); this.material = material; this.minimumSize = minimumSize; } public boolean test(ServerPlayerEntity player, Pair<ChestMaterial, Integer> data) { return (this.material == null || this.material == data.getLeft()) && (this.minimumSize == null || this.minimumSize <= data.getRight()); } } }
mit
tdmitriy/RWR
src/main/java/com/rwr/utils/IPageWrapper.java
603
package com.rwr.utils; import java.util.Collection; public interface IPageWrapper<T> { int getRowsCount(); void setRowsCount(int rowsCount); int getTotalPages(); int getMaxRecordsPerPage(); boolean getNextPage(); void setNextPage(boolean nextPage); boolean getPrevPage(); void setPrevPage(boolean prevPage); boolean getLastPage(); void setLastPage(boolean lastPage); void setMaxRecordsPerPage(int maxRecordsPerPage); void setTotalPages(int totalPages); Collection<T> getCollection(); void setCollection(Collection<T> collection); }
mit
tobyclemson/msci-project
vendor/poi-3.6/src/java/org/apache/poi/hssf/record/chart/SeriesTextRecord.java
3840
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.hssf.record.chart; import org.apache.poi.hssf.record.RecordInputStream; import org.apache.poi.hssf.record.StandardRecord; import org.apache.poi.util.HexDump; import org.apache.poi.util.LittleEndianOutput; import org.apache.poi.util.StringUtil; /** * SERIESTEXT (0x100D)</p> * Defines a series name</p> * * @author Andrew C. Oliver (acoliver at apache.org) */ public final class SeriesTextRecord extends StandardRecord { public final static short sid = 0x100D; /** the actual text cannot be longer than 255 characters */ private static final int MAX_LEN = 0xFF; private int field_1_id; private boolean is16bit; private String field_4_text; public SeriesTextRecord() { field_4_text = ""; is16bit = false; } public SeriesTextRecord(RecordInputStream in) { field_1_id = in.readUShort(); int field_2_textLength = in.readUByte(); is16bit = (in.readUByte() & 0x01) != 0; if (is16bit) { field_4_text = in.readUnicodeLEString(field_2_textLength); } else { field_4_text = in.readCompressedUnicode(field_2_textLength); } } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[SERIESTEXT]\n"); sb.append(" .id =").append(HexDump.shortToHex(getId())).append('\n'); sb.append(" .textLen=").append(field_4_text.length()).append('\n'); sb.append(" .is16bit=").append(is16bit).append('\n'); sb.append(" .text =").append(" (").append(getText()).append(" )").append('\n'); sb.append("[/SERIESTEXT]\n"); return sb.toString(); } public void serialize(LittleEndianOutput out) { out.writeShort(field_1_id); out.writeByte(field_4_text.length()); if (is16bit) { // Excel (2007) seems to choose 16bit regardless of whether it is needed out.writeByte(0x01); StringUtil.putUnicodeLE(field_4_text, out); } else { // Excel can read this OK out.writeByte(0x00); StringUtil.putCompressedUnicode(field_4_text, out); } } protected int getDataSize() { return 2 + 1 + 1 + field_4_text.length() * (is16bit ? 2 : 1); } public short getSid() { return sid; } public Object clone() { SeriesTextRecord rec = new SeriesTextRecord(); rec.field_1_id = field_1_id; rec.is16bit = is16bit; rec.field_4_text = field_4_text; return rec; } /** * Get the id field for the SeriesText record. */ public int getId() { return field_1_id; } /** * Set the id field for the SeriesText record. */ public void setId(int id) { field_1_id = id; } /** * Get the text field for the SeriesText record. */ public String getText() { return field_4_text; } /** * Set the text field for the SeriesText record. */ public void setText(String text) { if (text.length() > MAX_LEN) { throw new IllegalArgumentException("Text is too long (" + text.length() + ">" + MAX_LEN + ")"); } field_4_text = text; is16bit = StringUtil.hasMultibyte(text); } }
mit
simplify20/Simple
app/src/main/java/com/simple/creact/simple/app/data/di/common/component/ProductionComponent.java
487
package com.simple.creact.simple.app.data.di.common.component; import android.databinding.DataBindingComponent; import com.simple.creact.simple.app.data.di.common.ActivityScope; import com.simple.creact.simple.app.data.di.common.module.ProductionModule; import dagger.Component; /** * @author:YJJ * @date:2016/3/14 * @email:yangjianjun@117go.com */ @ActivityScope @Component(modules = ProductionModule.class) public interface ProductionComponent extends DataBindingComponent { }
mit
uiradias/saveferris
src/main/java/com/ferrishibernatesupport/saveferris/reflection/ReflectionUtil.java
13141
package com.ferrishibernatesupport.saveferris.reflection; import com.ferrishibernatesupport.saveferris.exception.SearchCriteriaSyntaxException; import com.ferrishibernatesupport.saveferris.exception.UnsupportedDateFormatException; import com.ferrishibernatesupport.saveferris.httpsearchapi.DateFormatDiscover; import org.hibernate.LazyInitializationException; import javax.persistence.*; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Created by uiradias on 03/09/14. */ public class ReflectionUtil { private static final Map<Class, List<Field>> fieldsCache = new HashMap<Class, List<Field>>(); public static boolean isEntity(Class<?> clazz) { boolean result = false; for (int i = 0; i < clazz.getAnnotations().length; i++) { Annotation annotation = clazz.getAnnotations()[i]; Class<?> type = annotation.annotationType(); if (type == Entity.class) { return true; } } return result; } public static Object executeGetterOfField(Object entity, Field sourceIdField) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { final Method sourceGetId = entity.getClass().getMethod(ReflectionUtil.getGetter(sourceIdField)); return sourceGetId.invoke(entity); } public static String getGetter(Field field) { String fieldName = field.getName(); String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); return methodName; } public static String getGetter(String property) { return "get" + property.substring(0, 1).toUpperCase() + property.substring(1); } public static String getSetter(String property) { return "set" + property.substring(0, 1).toUpperCase() + property.substring(1); } public static boolean isEmbedded(Class<?> clazz) { boolean result = false; for (int i = 0; i < clazz.getAnnotations().length; i++) { Annotation annotation = clazz.getAnnotations()[i]; Class<?> type = annotation.annotationType(); if (type == Embeddable.class) { return true; } } return result; } public static List<Field> getNoTransientFields(Class<?> clazz) { final List<Field> fieldsCollection = new ArrayList<Field>(); Field[] declaredFields = clazz.getDeclaredFields(); for (int i = 0; i < declaredFields.length; i++) { boolean isTransient = false; Field field = clazz.getDeclaredFields()[i]; Annotation[] annotations = field.getAnnotations(); for (int j = 0; j < annotations.length; j++) { if (annotations[j].annotationType() == Transient.class) isTransient = true; } if (!isTransient) { fieldsCollection.add(field); } } return fieldsCollection; } public static Object invoke(Object entity, String property) { final Class<?> clazz = entity.getClass(); Object invocation = null; try { Method method = clazz.getMethod(ReflectionUtil.getGetter(property)); invocation = method.invoke(entity); } catch (LazyInitializationException e) { throw new LazyInitializationException(""); } catch (Exception e) { //TODO Log something here... } return invocation; } public static boolean isEmbedded(Class<?> clazz, String attributePath) { try { String embeddedCandidateName; if (attributePath.contains(".")) { embeddedCandidateName = attributePath.substring(0, attributePath.indexOf(".")); Field fieldCandidate = clazz.getDeclaredField(embeddedCandidateName); Class<?> clazzCandidate = fieldCandidate.getType(); // getGetter(fieldCandidate).getClass(); int length = embeddedCandidateName.length(); String associationPathCandidate = attributePath.substring(length + 1); return isEmbedded(clazzCandidate, associationPathCandidate); } else { embeddedCandidateName = attributePath; } final Field field = clazz.getDeclaredField(embeddedCandidateName); for (int i = 0; i < field.getAnnotations().length; i++) { Annotation annotation = field.getAnnotations()[i]; if (annotation.annotationType() == EmbeddedId.class) { return true; } } } catch (Exception e) { //TODO Log something here... return false; } return false; } public static boolean isCollection(Class<?> clazz, String attributePath) { try { Field field = getField(clazz, attributePath); if (field.getType().isAssignableFrom(List.class)) { return true; } } catch (SecurityException e) { //TODO Log something here... } catch (NoSuchFieldException e) { //TODO Log something here... } return false; } public static Field getIdField(Class clazz) { try { final List<Field> declaredFields = getDeclaredFields(clazz); for (Field field : declaredFields) { if (field.isAnnotationPresent(Id.class)){ return field; } } } catch (SecurityException e) { //TODO Log something here... } return null; } public static Field getField(Class clazz, String attribute) throws NoSuchFieldException { try { return clazz.getDeclaredField(attribute); } catch (NoSuchFieldException e){ final Class superClass = clazz.getSuperclass(); if(superClass != null){ return getField(superClass, attribute); } else{ throw e; } } } public static List<Field> getDeclaredFields(Class clazz) { if(fieldsCache.containsKey(clazz)){ return fieldsCache.get(clazz); } else { final List<Field> fields = new ArrayList<Field>(); Collections.addAll(fields, clazz.getDeclaredFields()); Class superClass = clazz.getSuperclass(); while(superClass != null){ Collections.addAll(fields, superClass.getDeclaredFields()); superClass = superClass.getSuperclass(); } fieldsCache.put(clazz, fields); return fields; } } public static boolean isOneToMany(Field fieldSource) { if(fieldSource.getAnnotation(OneToMany.class) != null){ return true; } return false; } public static boolean isOneToManyWithOrphanRemoval(Field fieldSource) { if(fieldSource.getAnnotation(OneToMany.class) != null && fieldSource.getAnnotation(OneToMany.class).orphanRemoval()){ return true; } return false; } public static boolean isOneToManyWithoutOrphanRemoval(Field fieldSource) { if(fieldSource.getAnnotation(OneToMany.class) != null && !fieldSource.getAnnotation(OneToMany.class).orphanRemoval()){ return true; } return false; } public static boolean isManyToOne(Field fieldSource) { if(fieldSource.getAnnotation(ManyToOne.class) != null){ return true; } return false; } public static Class<?> getGenericType(Field field) { Class<?> clazz = Object.class; Type genericType = field.getGenericType(); if (genericType instanceof ParameterizedType) { Type[] types = ((ParameterizedType) genericType).getActualTypeArguments(); if (types.length > 0) { Type type = types[0]; if (type instanceof TypeVariable) { clazz = (Class<?>) ((TypeVariable<?>) type).getGenericDeclaration(); } else { clazz = (Class<?>) type; } } } return clazz; } public static String getBooleanVariationGetter(Field field) { String fieldName = field.getName(); String methodName = "is" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); return methodName; } public static Object getObjectWithType(Class<?> clazz, String attr, Object value) throws SearchCriteriaSyntaxException { try { return castDynamicClass(returnObjectType(clazz, attr, value), value.toString()); } catch (IllegalArgumentException e) { throw new SearchCriteriaSyntaxException("IllegalArgumentException"); } catch (SecurityException e) { throw new SearchCriteriaSyntaxException("SecurityException"); } catch (InstantiationException e) { throw new SearchCriteriaSyntaxException("The constructor to this was not found"); } catch (IllegalAccessException e) { throw new SearchCriteriaSyntaxException("IllegalAccessException"); } catch (InvocationTargetException e) { throw new SearchCriteriaSyntaxException("IllegalAccessException"); } catch (NoSuchMethodException e) { throw new SearchCriteriaSyntaxException("The field "+ attr + " does not belong to the model " + clazz.getName()); } catch (NoSuchFieldException e) { throw new SearchCriteriaSyntaxException("The field "+ attr + " does not belong to the model " + clazz.getName()); } } public static Class<? extends Object> returnObjectType(Class<? extends Object> model, String attr, Object value) throws SecurityException, NoSuchFieldException, SearchCriteriaSyntaxException { Class<?> parentClass = model; String[] pathArray = attr.split("[.]"); for (int i = 0; i < pathArray.length; i++) { if(pathArray.length==1){ return getClassBy(pathArray[0], model); } parentClass = getClassBy(pathArray[i], parentClass); } return parentClass; } private static Class<? extends Object> getClassBy(String attr, Class<? extends Object> parentClass) throws SecurityException, NoSuchFieldException, SearchCriteriaSyntaxException{ Field field = getFieldFromClassAndInheritance(attr, parentClass); if(field != null){ if (Collection.class.isAssignableFrom(field.getType())) { ParameterizedType listType = (ParameterizedType) field .getGenericType(); return (Class<?>) listType.getActualTypeArguments()[0]; } else { return field.getType(); } } throw new SearchCriteriaSyntaxException(); } private static Field getFieldFromClassAndInheritance(String attr, Class<?> clazz) throws SecurityException, SearchCriteriaSyntaxException { Field field; try { field = clazz.getDeclaredField(attr); } catch (NoSuchFieldException e) { if(clazz.getSuperclass() != null){ return getFieldFromClassAndInheritance(attr, clazz.getSuperclass()); } throw new SearchCriteriaSyntaxException(); } return field; } private static Date convertObjectToDate(Object value) { String dateFormat = DateFormatDiscover.discoverDateFormatForString((String) value); SimpleDateFormat formatter = new SimpleDateFormat(dateFormat); try { return formatter.parse((String) value); } catch (ParseException e) { throw new UnsupportedDateFormatException(); } } public static Object castDynamicClass(Class<?> clazz, String value) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException { if (clazz == Date.class) { return convertObjectToDate(value); } if(clazz.isEnum()){ return Enum.valueOf((Class<Enum>)clazz, value); } if (clazz == Character.class) { return convertObjectToCharacter(value); } Constructor<?> cons = (Constructor<?>) clazz.getConstructor(new Class<?>[] { String.class }); return (Object) cons.newInstance(new Object[] { value }); } private static Character convertObjectToCharacter(String value) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException { Constructor<Character> constructor = Character.class.getConstructor(char.class); return (Character) constructor.newInstance(value.charAt(0)); } }
mit
killme2008/kilim
src/kilim/http/HttpResponseParser.java
9135
// line 1 "HttpResponseParser.rl" /* Copyright (c) 2006, Sriram Srinivasan * * You may distribute this software under the terms of the license * specified in the file "License" */ package kilim.http; /** * --- DO NOT EDIT ----- * HttpRequestParser.java generated from RAGEL (http://www.complang.org/ragel/) from the * specification file HttpResponseParser.rl. All changes must be made in the .rl file. **/ import java.util.TimeZone; import java.util.GregorianCalendar; import java.nio.charset.Charset; import java.nio.ByteBuffer; import java.io.UnsupportedEncodingException; import java.io.IOException; import java.net.URLDecoder; public class HttpResponseParser { public static final Charset UTF8 = Charset.forName("UTF-8"); // line 81 "HttpResponseParser.rl" // line 34 "HttpResponseParser.java" private static byte[] init__http_parser_actions_0() { return new byte [] { 0, 1, 0, 1, 1, 1, 2, 1, 3, 1, 5, 1, 6, 2, 0, 2, 2, 0, 3, 2, 4, 0, 3, 4, 0, 3 }; } private static final byte _http_parser_actions[] = init__http_parser_actions_0(); private static byte[] init__http_parser_key_offsets_0() { return new byte [] { 0, 0, 1, 2, 3, 4, 5, 7, 10, 12, 15, 17, 19, 21, 24, 26, 43, 44, 60, 63, 65, 66, 68 }; } private static final byte _http_parser_key_offsets[] = init__http_parser_key_offsets_0(); private static char[] init__http_parser_trans_keys_0() { return new char [] { 72, 84, 84, 80, 47, 48, 57, 46, 48, 57, 48, 57, 32, 48, 57, 48, 57, 48, 57, 48, 57, 10, 13, 32, 10, 13, 10, 13, 33, 124, 126, 35, 39, 42, 43, 45, 46, 48, 57, 65, 90, 94, 122, 10, 33, 58, 124, 126, 35, 39, 42, 43, 45, 46, 48, 57, 65, 90, 94, 122, 10, 13, 32, 10, 13, 10, 10, 13, 0 }; } private static final char _http_parser_trans_keys[] = init__http_parser_trans_keys_0(); private static byte[] init__http_parser_single_lengths_0() { return new byte [] { 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 3, 2, 5, 1, 4, 3, 2, 1, 2, 0 }; } private static final byte _http_parser_single_lengths[] = init__http_parser_single_lengths_0(); private static byte[] init__http_parser_range_lengths_0() { return new byte [] { 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 6, 0, 6, 0, 0, 0, 0, 0 }; } private static final byte _http_parser_range_lengths[] = init__http_parser_range_lengths_0(); private static byte[] init__http_parser_index_offsets_0() { return new byte [] { 0, 0, 2, 4, 6, 8, 10, 12, 15, 17, 20, 22, 24, 26, 30, 33, 45, 47, 58, 62, 65, 67, 70 }; } private static final byte _http_parser_index_offsets[] = init__http_parser_index_offsets_0(); private static byte[] init__http_parser_trans_targs_0() { return new byte [] { 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 7, 0, 9, 0, 10, 9, 0, 11, 0, 12, 0, 13, 0, 15, 20, 21, 14, 15, 20, 14, 22, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 22, 0, 17, 18, 17, 17, 17, 17, 17, 17, 17, 17, 0, 15, 20, 18, 19, 15, 20, 19, 15, 0, 15, 20, 14, 0, 0 }; } private static final byte _http_parser_trans_targs[] = init__http_parser_trans_targs_0(); private static byte[] init__http_parser_trans_actions_0() { return new byte [] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 1, 0, 0, 0, 0, 0, 22, 22, 19, 19, 7, 7, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 13, 1, 1, 5, 5, 0, 0, 0, 16, 16, 1, 11, 0 }; } private static final byte _http_parser_trans_actions[] = init__http_parser_trans_actions_0(); static final int http_parser_start = 1; static final int http_parser_first_final = 22; static final int http_parser_error = 0; static final int http_parser_en_main = 1; // line 84 "HttpResponseParser.rl" public static void err(String msg) throws IOException{ throw new IOException(msg); } public static void initHeader(HttpResponse resp, int headerLength) throws IOException { ByteBuffer bb = resp.buffer; /* required variables */ byte[] data = bb.array(); int p = 0; int pe = headerLength; // int eof = pe; int cs = 0; // variables used by actions in http_req_parser machine above. int mark = 0; String field_name = ""; // line 163 "HttpResponseParser.java" { cs = http_parser_start; } // line 103 "HttpResponseParser.rl" // line 170 "HttpResponseParser.java" { int _klen; int _trans = 0; int _acts; int _nacts; int _keys; int _goto_targ = 0; _goto: while (true) { switch ( _goto_targ ) { case 0: if ( p == pe ) { _goto_targ = 4; continue _goto; } if ( cs == 0 ) { _goto_targ = 5; continue _goto; } case 1: _match: do { _keys = _http_parser_key_offsets[cs]; _trans = _http_parser_index_offsets[cs]; _klen = _http_parser_single_lengths[cs]; if ( _klen > 0 ) { int _lower = _keys; int _mid; int _upper = _keys + _klen - 1; while (true) { if ( _upper < _lower ) break; _mid = _lower + ((_upper-_lower) >> 1); if ( data[p] < _http_parser_trans_keys[_mid] ) _upper = _mid - 1; else if ( data[p] > _http_parser_trans_keys[_mid] ) _lower = _mid + 1; else { _trans += (_mid - _keys); break _match; } } _keys += _klen; _trans += _klen; } _klen = _http_parser_range_lengths[cs]; if ( _klen > 0 ) { int _lower = _keys; int _mid; int _upper = _keys + (_klen<<1) - 2; while (true) { if ( _upper < _lower ) break; _mid = _lower + (((_upper-_lower) >> 1) & ~1); if ( data[p] < _http_parser_trans_keys[_mid] ) _upper = _mid - 2; else if ( data[p] > _http_parser_trans_keys[_mid+1] ) _lower = _mid + 2; else { _trans += ((_mid - _keys)>>1); break _match; } } _trans += _klen; } } while (false); cs = _http_parser_trans_targs[_trans]; if ( _http_parser_trans_actions[_trans] != 0 ) { _acts = _http_parser_trans_actions[_trans]; _nacts = (int) _http_parser_actions[_acts++]; while ( _nacts-- > 0 ) { switch ( _http_parser_actions[_acts++] ) { case 0: // line 31 "HttpResponseParser.rl" {mark = p; } break; case 1: // line 33 "HttpResponseParser.rl" { field_name = HttpCommonParser.kw_lookup(data, mark, p); if (field_name == null) {// not a known keyword field_name = resp.extractRange(mark, p); } } break; case 2: // line 40 "HttpResponseParser.rl" { int value = HttpCommonParser.encodeRange(mark, p); resp.addField(field_name, value); } break; case 3: // line 45 "HttpResponseParser.rl" { resp.reasonRange = HttpCommonParser.encodeRange(mark, p); } break; case 4: // line 49 "HttpResponseParser.rl" { resp.statusRange = HttpCommonParser.encodeRange(mark, p); } break; case 5: // line 53 "HttpResponseParser.rl" { resp.versionRange = HttpCommonParser.encodeRange(mark, p); } break; case 6: // line 79 "HttpResponseParser.rl" {err("Malformed Header. Error at " + p + "\n" + new String(data, 0, pe, UTF8));} break; // line 291 "HttpResponseParser.java" } } } case 2: if ( cs == 0 ) { _goto_targ = 5; continue _goto; } if ( ++p != pe ) { _goto_targ = 1; continue _goto; } case 4: case 5: } break; } } // line 104 "HttpResponseParser.rl" if (cs == http_parser_error) { throw new IOException("Malformed HTTP Header. p = " + p +", cs = " + cs); } } public static void main(String args[]) throws Exception { /// Testing String s = "HTTP/1.1 200 OK\r\n"+ "Server: nginx\r\n"+ "Date: Wed, 03 Nov 2010 07:38:42 GMT\r\n"+ "Content-Type: text/html; charset=GBK\r\n"+ "Transfer-Encoding: chunked\r\n"+ "Vary: Accept-Encoding\r\n"+ "Expires: Wed, 03 Nov 2010 07:40:42 GMT\r\n"+ "Cache-Control: max-age=120\r\n"+ "Content-Encoding: gzip\r\n"+ "X-Via: 1.1 ls103:8103 (Cdn Cache Server V2.0), 1.1 zjls205:8103 (Cdn Cache Server V2.0)\r\n"+ "Connection: keep-alive\r\n"+ "Age: 1\r\n\r\n"; System.out.println("Input Response: (" + s.length() + " bytes)");System.out.println(s); byte[] data = s.getBytes(); int len = data.length; System.out.println("============================================================="); HttpResponse resp = new HttpResponse(); resp.buffer = ByteBuffer.allocate(2048); resp.buffer.put(data); initHeader(resp, len); System.out.println(resp); } }
mit
klimesf/a4m36sep-semestral-project
src/main/java/cz/cvut/fel/sep/klimefi1/semestral/WebSecurityConfig.java
1441
package cz.cvut.fel.sep.klimefi1.semestral; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .clearAuthentication(true) .invalidateHttpSession(true) .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } }
mit
gzavitz/blackberry-apps
FML/src/com/zavitz/fml/data/SubmitReceiver.java
139
package com.zavitz.fml.data; public interface SubmitReceiver { public void submitLoading(); public void submitSubmitted(); }
mit
factcenter/inchworm
src/test/java/org/factcenter/inchworm/asm/AssemblerTest.java
2639
package org.factcenter.inchworm.asm; import org.antlr.runtime.RecognitionException; import org.factcenter.inchworm.VMState; import org.factcenter.inchworm.ops.dummy.DummyOPFactory; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import static org.junit.Assert.assertEquals; public class AssemblerTest { VMState state; Assembler asm; String fullprog1 = ".header\n"+ "wordsize: 13 regptrsize: 8 romptrsize: 8 ramptrsize: 10 counters: 5 9 stackptrsize 5 framesize: 4 instruction: zero xori call return add add mux halt next\n"+ ".const\n" + "label1=15\n" + "label2=25\n" + ".data\n" + "%r0 = 5 6\n"+ "datalabel1:\n"+ "%r10 = (label1)\n"+ "datalabel2: $\n"+ "%r50 = (datalabel2+5) ($) (datalabel1)\n"+ ".code\n"+ "zero %ctr9\n"+ "xori %r10 < 0x10\n"+ "call codelabel\n"+ "return\n"+ "add %local1 < %local[3], %ctr5\n"+ "---\n"+ "codelabel:\n"+ "zero %r10\n"+ "xori %r30 < 0xffffffff\n"+ "add %r11 < %r30, %r50\n"+ "---\n"+ ""; String dataOnly = ".data\n" + "%r1 = 7 8 9\n" + "%r20: 10 20 30 (codelabel) (datalabel1)\n" + ""; void firstAsm() throws RecognitionException, IOException { ByteArrayInputStream in1 = new ByteArrayInputStream(fullprog1.getBytes()); asm.assemble(in1); DisAssembler.disassemble(state, System.out, true); } void secondAsm() throws RecognitionException, IOException { ByteArrayInputStream in2 = new ByteArrayInputStream(dataOnly.getBytes()); asm.assemble(in2, false); } @Before public void setUp() throws Exception { state = new VMState(); state.setMemory(new DummyOPFactory()); asm = new Assembler(state); } @Test public void dataLoadTest() throws RecognitionException, IOException { firstAsm(); assertEquals(5, state.getReg(0)); assertEquals(6, state.getReg(1)); secondAsm(); assertEquals(5, state.getReg(0)); assertEquals(7, state.getReg(1)); assertEquals(8, state.getReg(2)); assertEquals(9, state.getReg(3)); assertEquals(10, state.getReg(20)); assertEquals(20, state.getReg(21)); assertEquals(30, state.getReg(22)); } @Test public void labelTest() throws RecognitionException, IOException { firstAsm(); assertEquals(15, state.getReg(10)); assertEquals(16, state.getReg(50)); assertEquals(51, state.getReg(51)); assertEquals(10, state.getReg(52)); } @Test public void labelCarryOverTest() throws RecognitionException, IOException { firstAsm(); secondAsm(); assertEquals(1, state.getReg(23)); assertEquals(10, state.getReg(24)); } }
mit
fabiohxcx/PedidoVenda
src/main/java/model/Grupo.java
1347
package model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "grupo") public class Grupo implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; @Column(nullable = false, length = 60) private String nome; @Column(nullable = false, length = 100) private String descricao; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Grupo other = (Grupo) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
mit
Telestream/telestream-cloud-java-sdk
telestream-cloud-tts-sdk/src/main/java/net/telestream/cloud/tts/JSON.java
11354
/* * Tts API * Description * * OpenAPI spec version: 2.0.0 * Contact: cloudsupport@telestream.net * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package net.telestream.cloud.tts; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; import io.gsonfire.GsonFireBuilder; import io.gsonfire.TypeSelector; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import org.threeten.bp.format.DateTimeFormatter; import net.telestream.cloud.tts.*; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; import java.util.Date; import java.util.Map; import java.util.HashMap; public class JSON { private Gson gson; private boolean isLenientOnJson = false; private DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() ; return fireBuilder.createGsonBuilder(); } private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { JsonElement element = readElement.getAsJsonObject().get(discriminatorField); if(null == element) { throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); } return element.getAsString(); } private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue.toUpperCase()); if(null == clazz) { throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); } return clazz; } public JSON() { gson = createGson() .registerTypeAdapter(Date.class, dateTypeAdapter) .registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter) .registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter) .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) .create(); } /** * Get Gson. * * @return Gson */ public Gson getGson() { return gson; } /** * Set Gson. * * @param gson Gson * @return JSON */ public JSON setGson(Gson gson) { this.gson = gson; return this; } public JSON setLenientOnJson(boolean lenientOnJson) { isLenientOnJson = lenientOnJson; return this; } /** * Serialize the given Java object into JSON string. * * @param obj Object * @return String representation of the JSON */ public String serialize(Object obj) { return gson.toJson(obj); } /** * Deserialize the given JSON string to Java object. * * @param <T> Type * @param body The JSON string * @param returnType The type to deserialize into * @return The deserialized Java object */ @SuppressWarnings("unchecked") public <T> T deserialize(String body, Type returnType) { try { if (isLenientOnJson) { JsonReader jsonReader = new JsonReader(new StringReader(body)); // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) jsonReader.setLenient(true); return gson.fromJson(jsonReader, returnType); } else { return gson.fromJson(body, returnType); } } catch (JsonParseException e) { // Fallback processing when failed to parse JSON form response body: // return the response body string directly for the String return type; if (returnType.equals(String.class)) return (T) body; else throw (e); } } /** * Gson TypeAdapter for JSR310 OffsetDateTime type */ public static class OffsetDateTimeTypeAdapter extends TypeAdapter<OffsetDateTime> { private DateTimeFormatter formatter; public OffsetDateTimeTypeAdapter() { this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); } public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { this.formatter = formatter; } public void setFormat(DateTimeFormatter dateFormat) { this.formatter = dateFormat; } @Override public void write(JsonWriter out, OffsetDateTime date) throws IOException { if (date == null) { out.nullValue(); } else { out.value(formatter.format(date)); } } @Override public OffsetDateTime read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); if (date.endsWith("+0000")) { date = date.substring(0, date.length()-5) + "Z"; } return OffsetDateTime.parse(date, formatter); } } } /** * Gson TypeAdapter for JSR310 LocalDate type */ public class LocalDateTypeAdapter extends TypeAdapter<LocalDate> { private DateTimeFormatter formatter; public LocalDateTypeAdapter() { this(DateTimeFormatter.ISO_LOCAL_DATE); } public LocalDateTypeAdapter(DateTimeFormatter formatter) { this.formatter = formatter; } public void setFormat(DateTimeFormatter dateFormat) { this.formatter = dateFormat; } @Override public void write(JsonWriter out, LocalDate date) throws IOException { if (date == null) { out.nullValue(); } else { out.value(formatter.format(date)); } } @Override public LocalDate read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); return LocalDate.parse(date, formatter); } } } public JSON setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { offsetDateTimeTypeAdapter.setFormat(dateFormat); return this; } public JSON setLocalDateFormat(DateTimeFormatter dateFormat) { localDateTypeAdapter.setFormat(dateFormat); return this; } /** * Gson TypeAdapter for java.sql.Date type * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used * (more efficient than SimpleDateFormat). */ public static class SqlDateTypeAdapter extends TypeAdapter<java.sql.Date> { private DateFormat dateFormat; public SqlDateTypeAdapter() { } public SqlDateTypeAdapter(DateFormat dateFormat) { this.dateFormat = dateFormat; } public void setFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; } @Override public void write(JsonWriter out, java.sql.Date date) throws IOException { if (date == null) { out.nullValue(); } else { String value; if (dateFormat != null) { value = dateFormat.format(date); } else { value = date.toString(); } out.value(value); } } @Override public java.sql.Date read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); try { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } } } } /** * Gson TypeAdapter for java.util.Date type * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter<Date> { private DateFormat dateFormat; public DateTypeAdapter() { } public DateTypeAdapter(DateFormat dateFormat) { this.dateFormat = dateFormat; } public void setFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; } @Override public void write(JsonWriter out, Date date) throws IOException { if (date == null) { out.nullValue(); } else { String value; if (dateFormat != null) { value = dateFormat.format(date); } else { value = ISO8601Utils.format(date, true); } out.value(value); } } @Override public Date read(JsonReader in) throws IOException { try { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); try { if (dateFormat != null) { return dateFormat.parse(date); } return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } } } catch (IllegalArgumentException e) { throw new JsonParseException(e); } } } public JSON setDateFormat(DateFormat dateFormat) { dateTypeAdapter.setFormat(dateFormat); return this; } public JSON setSqlDateFormat(DateFormat dateFormat) { sqlDateTypeAdapter.setFormat(dateFormat); return this; } }
mit
D3nnisH/SoPra
src/application/controller/ImportController.java
4093
package application.controller; import java.io.File; import java.io.FileNotFoundException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import application.Main; import application.model.daten.Turnier; import application.model.daten.TurnierVeranstaltung; import application.model.daten.TurnierVeranstaltung.MergeImpossibleException; import application.model.einstellungen.Einstellungen; import application.model.transfer.Transfer; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.Region; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.stage.FileChooser.ExtensionFilter; /** * Dialog zum Import einer {@link TurnierVeranstaltung} * @author Dennis Heller, Marvin Wohlfarth, Burak Ünal * */ public class ImportController { @FXML private TextField speicherortTextField; @FXML private Button openFileChooserButton; @FXML private TextField passwortTextField; @FXML private Button fertigstellenButton; @FXML private Region rootPane; private Stage window; @FXML private void initialize() { speicherortTextField.setText(Einstellungen.get("letzterSpeicherort", "")); } @FXML private void openFileChooser() { File selectedFile = getInputPath().toFile(); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Datei auswählen"); if(!selectedFile.isDirectory()) { fileChooser.setInitialFileName(selectedFile.getName()); selectedFile = selectedFile.getParentFile(); } if(selectedFile!=null && selectedFile.isDirectory()) { fileChooser.setInitialDirectory(selectedFile.isFile()?selectedFile.getParentFile():selectedFile); } fileChooser.getExtensionFilters().add(new ExtensionFilter("Turnierdateien", "*.tmnt")); File speicherort = fileChooser.showOpenDialog(getWindow()); if(speicherort!=null) { speicherortTextField.setText(speicherort.getAbsolutePath()); } else { speicherortTextField.setText(""); } } /** * überprüft, ob der im Textfeld eingegeben Pfad zu einer lesbaren Datei führt und deaktiviert, falls nicht, den fertigstellenButton * @return */ @FXML private boolean validate() { try { if(!Files.exists(Paths.get(speicherortTextField.getText()))) throw new FileNotFoundException(); if(!Files.isRegularFile(Paths.get(speicherortTextField.getText())) || !Files.isReadable(Paths.get(speicherortTextField.getText()))) throw new IllegalArgumentException("Datei nicht lesbar!"); fertigstellenButton.setDisable(false); return true; } catch(FileNotFoundException | IllegalArgumentException e) { fertigstellenButton.setDisable(true); return false; } } @FXML private void importieren() { if(!validate()) return; Path speicherort = Paths.get(speicherortTextField.getText()); Einstellungen.set("letzterSpeicherort", speicherort.toString()); TurnierVeranstaltung tv = Transfer.importieren(speicherort, passwortTextField.getText()); if(tv!=null) { if(Main.getTurnierVeranstaltung()!=null) { try { Main.getTurnierVeranstaltung().mergeWith(tv); schliessen(); } catch(MergeImpossibleException e) { Main.showErrorDialog(getWindow(), e); } } else { Main.setTurnierVeranstaltung(tv); schliessen(); } for(Turnier turnier: Main.getTurnierVeranstaltung().getTurnierListe()) { turnier.updateGewinnerText(Main.getTurnierVeranstaltung()); } } else { passwortTextField.setText(""); } } private Path getInputPath() { return speicherortTextField.getText().isEmpty()? Paths.get(System.getProperty("user.home")): Paths.get(speicherortTextField.getText().endsWith(File.separator)?speicherortTextField.getText():speicherortTextField.getText()+File.separator); } private Stage getWindow() { if(window==null) { window = (Stage) rootPane.getScene().getWindow(); } return window; } @FXML private void schliessen() { getWindow().close(); } }
mit
pvgoran/BlogApp
java/blogapp/Action.java
877
package blogapp; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import pvgoran.dataaccess.DataException; public abstract class Action { protected BlogAppContext appContext; protected BlogAppDatabase db; public Action(BlogAppContext appContext) { this.appContext = appContext; this.db = appContext.db; } public abstract void process(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, SQLException, DataException; public void forward(String path, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { req.setAttribute("ac", appContext); req.getRequestDispatcher(path).forward(req, res); } }
mit
JKatzwinkel/settlers-remake
jsettlers.mapcreator/src/jsettlers/mapcreator/control/EditorControl.java
23722
/******************************************************************************* * Copyright (c) 2015 * * 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 jsettlers.mapcreator.control; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Desktop; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Timer; import java.util.TimerTask; import javax.swing.AbstractAction; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingUtilities; import go.graphics.area.Area; import go.graphics.region.Region; import go.graphics.swing.AreaContainer; import go.graphics.swing.sound.SwingSoundPlayer; import jsettlers.common.CommonConstants; import jsettlers.common.buildings.EBuildingType; import jsettlers.common.landscape.ELandscapeType; import jsettlers.common.map.MapLoadException; import jsettlers.common.menu.FakeMapGame; import jsettlers.common.menu.IMapInterfaceListener; import jsettlers.common.menu.action.EActionType; import jsettlers.common.menu.action.IAction; import jsettlers.common.position.ShortPoint2D; import jsettlers.common.resources.ResourceManager; import jsettlers.exceptionhandler.ExceptionHandler; import jsettlers.graphics.action.ActionFireable; import jsettlers.graphics.action.PointAction; import jsettlers.graphics.map.MapContent; import jsettlers.graphics.map.MapInterfaceConnector; import jsettlers.logic.map.MapLoader; import jsettlers.logic.map.save.MapFileHeader; import jsettlers.logic.map.save.MapList; import jsettlers.main.swing.SwingManagedJSettlers; import jsettlers.mapcreator.data.MapData; import jsettlers.mapcreator.data.MapDataDelta; import jsettlers.mapcreator.localization.EditorLabels; import jsettlers.mapcreator.main.action.AbortDrawingAction; import jsettlers.mapcreator.main.action.CombiningActionFirerer; import jsettlers.mapcreator.main.action.DrawLineAction; import jsettlers.mapcreator.main.action.EndDrawingAction; import jsettlers.mapcreator.main.action.StartDrawingAction; import jsettlers.mapcreator.main.map.MapEditorControls; import jsettlers.mapcreator.main.window.EditorFrame; import jsettlers.mapcreator.main.window.LastUsedHandler; import jsettlers.mapcreator.main.window.NewFileDialog; import jsettlers.mapcreator.main.window.OpenExistingDialog; import jsettlers.mapcreator.main.window.SettingsDialog; import jsettlers.mapcreator.main.window.sidebar.RectIcon; import jsettlers.mapcreator.main.window.sidebar.Sidebar; import jsettlers.mapcreator.main.window.sidebar.ToolSidebar; import jsettlers.mapcreator.mapvalidator.AutoFixErrorAction; import jsettlers.mapcreator.mapvalidator.GotoNextErrorAction; import jsettlers.mapcreator.mapvalidator.IScrollToAble; import jsettlers.mapcreator.mapvalidator.ShowErrorsAction; import jsettlers.mapcreator.mapvalidator.ValidationResultListener; import jsettlers.mapcreator.mapvalidator.result.ValidationListModel; import jsettlers.mapcreator.mapvalidator.result.fix.FixData; import jsettlers.mapcreator.mapview.MapGraphics; import jsettlers.mapcreator.stat.StatisticsDialog; import jsettlers.mapcreator.tools.SetStartpointTool; import jsettlers.mapcreator.tools.Tool; import jsettlers.mapcreator.tools.landscape.ResourceTool; import jsettlers.mapcreator.tools.objects.PlaceBuildingTool; import jsettlers.mapcreator.tools.shapes.ShapeType; /** * Controller for map editing * * @author Andreas Butti */ public class EditorControl extends EditorControlBase implements IMapInterfaceListener, ActionFireable, IPlayerSetter, IScrollToAble { /** * Map drawing */ private MapGraphics map; /** * Currently active tool */ private Tool tool = null; /** * Currently selected player */ private int currentPlayer = 0; /** * Undo / Redo stack */ private UndoRedoHandler undoRedo; /** * To scrol to positions */ private MapInterfaceConnector connector; /** * Window displayed */ private EditorFrame window; /** * Open GL Contents (Drawing) */ private MapContent mapContent; /** * Sidebar with the tools */ private final ToolSidebar toolSidebar = new ToolSidebar(this) { private static final long serialVersionUID = 1L; @Override protected void changeTool(Tool lastPathComponent) { EditorControl.this.changeTool(lastPathComponent); } }; /** * Sidebar with all tabs */ private final Sidebar sidebar = new Sidebar(toolSidebar, this); /** * Timer for redrawing */ private final Timer redrawTimer = new Timer(true); /** * Action to fix all errors automatically, if clear what to do */ private AutoFixErrorAction autoFixErrorAction; /** * Always display resources */ private boolean showResourcesAlways = false; /** * Show the resources because the current tool requests it */ private boolean showResourcesBecauseOfTool = false; /** * Combobox with the player selection */ private final JComboBox<Integer> playerCombobox = new JComboBox<>(); /** * Constructor */ public EditorControl() { // use heavyweight component playerCombobox.setLightWeightPopupEnabled(false); playerCombobox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { currentPlayer = (Integer) playerCombobox.getSelectedItem(); } }); playerCombobox.setRenderer(new DefaultListCellRenderer() { private static final long serialVersionUID = 1L; @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); Integer player = (Integer) value; setIcon(new RectIcon(22, new Color(mapContent.getPlayerColor(player.byteValue()).getARGB()), Color.GRAY)); setText(String.format(EditorLabels.getLabel("general.player_x"), player)); return this; } }); } /** * Update the player selection combobox */ private void updatePlayerCombobox() { // create a new model, because a swing bug there are sometimes problems updating an existing model DefaultComboBoxModel<Integer> model = new DefaultComboBoxModel<>(); model.setSelectedItem(playerCombobox.getSelectedItem()); for (int i = 0; i < mapData.getPlayerCount(); i++) { model.addElement(i); } playerCombobox.setModel(model); } /** * Load a map * * @param loader * Map to load * @throws MapLoadException */ public void loadMap(MapLoader loader) throws MapLoadException { MapData data = new MapData(loader.getMapData()); MapFileHeader header = loader.getFileHeader(); loadMap(header, data); } /** * Create a new map * * @param header * Header of the file to open * @param ground * Ground to use for the new map */ public void createNewMap(MapFileHeader header, ELandscapeType ground) { loadMap(header, new MapData(header.getWidth(), header.getHeight(), header.getMaxPlayer(), ground)); } /** * Load a map * * @param header * Header to use * @param mapData * Map to use */ public void loadMap(MapFileHeader header, MapData mapData) { setHeader(header); this.mapData = mapData; updatePlayerCombobox(); map = new MapGraphics(mapData); validator.setData(mapData); validator.setHeader(header); validator.addListener(sidebar); buildMapEditingWindow(); new LastUsedHandler().saveUsedMapId(header.getUniqueId()); undoRedo = new UndoRedoHandler(window, mapData); FixData fixData = new FixData(mapData, undoRedo, validator); sidebar.setFixData(fixData); autoFixErrorAction.setFixData(fixData); // Go to center of the map connector.scrollTo(new ShortPoint2D(header.getWidth() / 2, header.getHeight() / 2), false); } /** * Build the Main Window */ public void buildMapEditingWindow() { JPanel root = new JPanel(); root.setLayout(new BorderLayout(10, 10)); // map display Area area = new Area(); final Region region = new Region(Region.POSITION_CENTER); area.add(region); AreaContainer displayPanel = new AreaContainer(area); displayPanel.setMinimumSize(new Dimension(640, 480)); displayPanel.setFocusable(true); root.add(displayPanel, BorderLayout.CENTER); window = new EditorFrame(root, sidebar) { private static final long serialVersionUID = 1L; @Override protected JComponent createPlayerSelectSelection() { return playerCombobox; } }; registerActions(); window.initMenubarAndToolbar(); initActions(); validator.reValidate(); // window.pack(); window.setSize(1200, 800); window.invalidate(); window.setFilename(getHeader().getName()); // center on screen window.setLocationRelativeTo(null); this.mapContent = new MapContent(new FakeMapGame(map), new SwingSoundPlayer(), new MapEditorControls(new CombiningActionFirerer(this))); connector = mapContent.getInterfaceConnector(); region.setContent(mapContent); redrawTimer.schedule(new TimerTask() { @Override public void run() { region.requestRedraw(); } }, 50, 50); connector.addListener(this); window.setVisible(true); displayPanel.requestFocus(); } /** * Quit this editor instance */ private void quit() { redrawTimer.cancel(); validator.dispose(); window.dispose(); } /** * Open an existing file */ private void openExistingFile() { if (!checkSaved()) { // user canceled return; } OpenExistingDialog dlg = new OpenExistingDialog(window); dlg.setVisible(true); if (!dlg.isConfirmed()) { return; } // only one map can be active quit(); // create new control for new map EditorControl control = new EditorControl(); try { control.loadMap(dlg.getSelectedMap()); } catch (MapLoadException e) { ExceptionHandler.displayError(e, "Could not load map"); } } /** * Create a new map */ private void createNewFile() { if (!checkSaved()) { // user canceled return; } NewFileDialog dlg = new NewFileDialog(window); dlg.setVisible(true); if (!dlg.isConfirmed()) { return; } MapFileHeader header = dlg.getHeader(); // only one map can be active quit(); // create new control for new map EditorControl control = new EditorControl(); control.createNewMap(header, dlg.getGroundTypes()); } /** * Check if saved, if not ask user * * @return true to continue, false to cancel */ private boolean checkSaved() { if (!undoRedo.isChangedSinceLastSave()) { return true; } else { int result = JOptionPane.showConfirmDialog(window, EditorLabels.getLabel("ctrl.save-chages"), "JSettler", JOptionPane.YES_NO_CANCEL_OPTION); if (result == JOptionPane.YES_OPTION) { save(); return true; } else if (result == JOptionPane.NO_OPTION) { return true; } // cancel return false; } } /** * Register toolbar / menubar actions */ private void registerActions() { window.registerAction("quit", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { if (checkSaved()) { quit(); // TODO dispose all window, make all threads deamon, then remove this exit! System.exit(0); } } }); window.registerAction("new", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { createNewFile(); } }); window.registerAction("open", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { openExistingFile(); } }); window.registerAction("zoom-in", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { mapContent.zoomIn(); } }); window.registerAction("zoom-out", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { mapContent.zoomOut(); } }); window.registerAction("zoom100", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { mapContent.zoom100(); } }); window.registerAction("show-resources-always", new AbstractAction() { private static final long serialVersionUID = 1L; { putValue(EditorFrame.DISPLAY_CHECKBOX, true); } @Override public void actionPerformed(ActionEvent e) { Boolean checked = (Boolean) getValue(EditorFrame.CHECKBOX_VALUE); if (checked != null && checked) { showResourcesAlways = true; } else { showResourcesAlways = false; } map.setShowResources(showResourcesAlways | showResourcesBecauseOfTool); } }); window.registerAction("save", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { save(); } }); window.registerAction("save-as", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { String name = JOptionPane.showInputDialog(window, EditorLabels.getLabel("ctrl.save-as-name")); if (name != null) { createNewHeaderWithName(name); save(); window.setFilename(name); } } }); window.registerAction("open-map-folder", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { try { Desktop.getDesktop().open(new File(ResourceManager.getResourcesDirectory(), "maps")); } catch (IOException e1) { ExceptionHandler.displayError(e1, "Could not open map folder"); } } }); window.registerAction("undo", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { undoRedo.undo(); validator.reValidate(); } }); window.registerAction("redo", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { undoRedo.redo(); validator.reValidate(); } }); window.registerAction("show-statistic", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { StatisticsDialog dlg = new StatisticsDialog(window, mapData); dlg.setVisible(true); } }); window.registerAction("show-map-settings", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { editSettings(); } }); final AbstractAction playAction = new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { play(); } }; window.registerAction("play", playAction); validator.addListener(new ValidationResultListener() { @Override public void validationFinished(ValidationListModel list) { playAction.setEnabled(list.size() == 0); } }); window.registerAction("show-tools", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { sidebar.showTools(); } }); ShowErrorsAction showErrorsAction = new ShowErrorsAction(sidebar, true); ShowErrorsAction showWarningsAction = new ShowErrorsAction(sidebar, false); window.registerAction("show-errors", showErrorsAction); window.registerAction("show-warnings", showWarningsAction); validator.addListener(showErrorsAction); validator.addListener(showWarningsAction); // show-warnings GotoNextErrorAction gotoNextErrorAction = new GotoNextErrorAction(this); window.registerAction("goto-error", gotoNextErrorAction); validator.addListener(gotoNextErrorAction); this.autoFixErrorAction = new AutoFixErrorAction(); window.registerAction("auto-fix-error", autoFixErrorAction); validator.addListener(autoFixErrorAction); window.registerAction("locate-player", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { int playerId = getActivePlayer(); scrollTo(mapData.getStartPoint(playerId)); } }); } /** * Set some actions disabled per default, will be enabled when they are available */ private void initActions() { window.enableAction("save", false); window.enableAction("undo", false); window.enableAction("redo", false); } /** * Display the map settings dialog */ protected void editSettings() { SettingsDialog dlg = new SettingsDialog(window, getHeader()) { private static final long serialVersionUID = 1L; @Override public void applyNewHeader(MapFileHeader header) { setHeader(header); mapData.setMaxPlayers(header.getMaxPlayer()); updatePlayerCombobox(); validator.reValidate(); } }; dlg.setVisible(true); } /** * Save current map */ protected void save() { try { MapFileHeader imagedHeader = generateMapHeader(); new LastUsedHandler().saveUsedMapId(imagedHeader.getUniqueId()); mapData.doPreSaveActions(); CommonConstants.USE_SAVEGAME_COMPRESSION = false; MapList.getDefaultList().saveNewMap(imagedHeader, mapData, null); undoRedo.setSaved(); } catch (Throwable e) { ExceptionHandler.displayError(e, "Error saving"); } } /** * Start Another process * * @param args * Arguments * @param name * For Log output and thread ID * @throws IOException */ protected void startProcess(String[] args, final String name) throws IOException { System.out.println("Starting process:"); for (String arg : args) { System.out.print(arg + " "); } System.out.println(); ProcessBuilder builder = new ProcessBuilder(args); builder.redirectErrorStream(true); final Process process = builder.start(); Thread streamReader = new Thread(new Runnable() { @Override public void run() { BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); while (true) { String line; try { line = reader.readLine(); } catch (IOException e) { break; } if (line == null) { break; } System.out.println(name + " " + line); } } }, "ExecThread " + name); streamReader.setDaemon(true); } /** * Play the game in a new process */ protected void play() { try { File temp = File.createTempFile("tmp_map", ""); mapData.doPreSaveActions(); MapList.getDefaultList().saveNewMap(generateMapHeader(), mapData, new FileOutputStream(temp)); String[] args = new String[] { "java", "-classpath", System.getProperty("java.class.path"), SwingManagedJSettlers.class.getName(), "--mapfile=" + temp.getAbsolutePath(), "--control-all", "--activate-all-players" }; startProcess(args, "game"); } catch (IOException e) { ExceptionHandler.displayError(e, "Failed to start game"); } } /** * Set the selected tool * * @param lastPathComponent */ protected void changeTool(Tool lastPathComponent) { tool = lastPathComponent; toolSidebar.updateShapeSettings(tool); showResourcesBecauseOfTool = false; if (tool != null) { // if the resource tool is used they should be displayed showResourcesBecauseOfTool |= tool instanceof ResourceTool; if (tool instanceof PlaceBuildingTool) { PlaceBuildingTool pbt = (PlaceBuildingTool) tool; EBuildingType type = pbt.getType(); // display resources for Mines and Fisher if (type.isMine() || type == EBuildingType.FISHER) { showResourcesBecauseOfTool = true; } } } map.setShowResources(showResourcesAlways | showResourcesBecauseOfTool); } /** * This listener is called from different Thread, all swing calls have to be from event dispatcher thread! */ @Override public void action(final IAction action) { System.out.println("Got action: " + action.getActionType()); if (action.getActionType() == EActionType.SELECT_AREA) { // IMapArea area = ((SelectAreaAction) action).getArea(); } else if (action instanceof DrawLineAction) { if (tool != null && !(tool instanceof SetStartpointTool)) { DrawLineAction lineAction = (DrawLineAction) action; // only getter call, no Swing calls ShapeType shape = toolSidebar.getActiveShape(); tool.apply(mapData, shape, lineAction.getStart(), lineAction.getEnd(), lineAction.getUidy()); validator.reValidate(); } } else if (action instanceof StartDrawingAction) { if (tool != null && !(tool instanceof SetStartpointTool)) { StartDrawingAction lineAction = (StartDrawingAction) action; // only getter call, no Swing calls ShapeType shape = toolSidebar.getActiveShape(); tool.start(mapData, shape, lineAction.getPos()); validator.reValidate(); } } else if (action instanceof EndDrawingAction) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { undoRedo.endUseStep(); validator.reValidate(); } }); } else if (action instanceof AbortDrawingAction) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MapDataDelta delta = mapData.getUndoDelta(); if (delta != null) { mapData.apply(delta); } mapData.resetUndoDelta(); validator.reValidate(); } }); } else if (action.getActionType() == EActionType.SELECT_POINT) { if (tool != null) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { PointAction lineAction = (PointAction) action; ShapeType shape = toolSidebar.getActiveShape(); tool.start(mapData, shape, lineAction.getPosition()); tool.apply(mapData, shape, lineAction.getPosition(), lineAction.getPosition(), 0); undoRedo.endUseStep(); validator.reValidate(); } }); } } } @Override public void fireAction(IAction action) { action(action); } @Override public int getActivePlayer() { return currentPlayer; } @Override public void scrollTo(ShortPoint2D pos) { if (pos != null) { connector.scrollTo(pos, true); } } }
mit
selvasingh/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/fluent/AvailablePrivateEndpointTypesClient.java
5311
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.network.fluent; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.util.Context; import com.azure.resourcemanager.network.fluent.models.AvailablePrivateEndpointTypeInner; /** An instance of this class provides access to all the operations defined in AvailablePrivateEndpointTypesClient. */ public interface AvailablePrivateEndpointTypesClient { /** * Returns all of the resource types that can be linked to a Private Endpoint in this subscription in this region. * * @param location The location of the domain name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an array of available PrivateEndpoint types. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<AvailablePrivateEndpointTypeInner> listAsync(String location); /** * Returns all of the resource types that can be linked to a Private Endpoint in this subscription in this region. * * @param location The location of the domain name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an array of available PrivateEndpoint types. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<AvailablePrivateEndpointTypeInner> list(String location); /** * Returns all of the resource types that can be linked to a Private Endpoint in this subscription in this region. * * @param location The location of the domain name. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an array of available PrivateEndpoint types. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<AvailablePrivateEndpointTypeInner> list(String location, Context context); /** * Returns all of the resource types that can be linked to a Private Endpoint in this subscription in this region. * * @param location The location of the domain name. * @param resourceGroupName The name of the resource group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an array of available PrivateEndpoint types. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<AvailablePrivateEndpointTypeInner> listByResourceGroupAsync(String location, String resourceGroupName); /** * Returns all of the resource types that can be linked to a Private Endpoint in this subscription in this region. * * @param location The location of the domain name. * @param resourceGroupName The name of the resource group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an array of available PrivateEndpoint types. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<AvailablePrivateEndpointTypeInner> listByResourceGroup(String location, String resourceGroupName); /** * Returns all of the resource types that can be linked to a Private Endpoint in this subscription in this region. * * @param location The location of the domain name. * @param resourceGroupName The name of the resource group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return an array of available PrivateEndpoint types. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<AvailablePrivateEndpointTypeInner> listByResourceGroup( String location, String resourceGroupName, Context context); }
mit
raoulvdberge/refinedstorage
src/main/java/com/refinedmods/refinedstorage/integration/jei/RecipeTransferCraftingGridError.java
2621
package com.refinedmods.refinedstorage.integration.jei; import com.mojang.blaze3d.vertex.PoseStack; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.recipe.transfer.IRecipeTransferError; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TranslatableComponent; import java.awt.*; import java.util.ArrayList; import java.util.List; public class RecipeTransferCraftingGridError implements IRecipeTransferError { protected static final Color AUTOCRAFTING_HIGHLIGHT_COLOR = new Color(0.0f, 0.0f, 1.0f, 0.4f); private static final Color MISSING_HIGHLIGHT_COLOR = new Color(1.0f, 0.0f, 0.0f, 0.4f); protected final IngredientTracker tracker; public RecipeTransferCraftingGridError(IngredientTracker tracker) { this.tracker = tracker; } @Override public Type getType() { return Type.COSMETIC; } @Override public void showError(PoseStack stack, int mouseX, int mouseY, IRecipeLayout recipeLayout, int recipeX, int recipeY) { List<Component> message = drawIngredientHighlights(stack, recipeX, recipeY); Screen currentScreen = Minecraft.getInstance().screen; currentScreen.renderComponentTooltip(stack, message, mouseX, mouseY); } protected List<Component> drawIngredientHighlights(PoseStack stack, int recipeX, int recipeY) { List<Component> message = new ArrayList<>(); message.add(new TranslatableComponent("jei.tooltip.transfer")); boolean craftMessage = false; boolean missingMessage = false; for (Ingredient ingredient : tracker.getIngredients()) { if (!ingredient.isAvailable()) { if (ingredient.isCraftable()) { ingredient.getGuiIngredient().drawHighlight(stack, AUTOCRAFTING_HIGHLIGHT_COLOR.getRGB(), recipeX, recipeY); craftMessage = true; } else { ingredient.getGuiIngredient().drawHighlight(stack, MISSING_HIGHLIGHT_COLOR.getRGB(), recipeX, recipeY); missingMessage = true; } } } if (missingMessage) { message.add(new TranslatableComponent("jei.tooltip.error.recipe.transfer.missing").withStyle(ChatFormatting.RED)); } if (craftMessage) { message.add(new TranslatableComponent("gui.refinedstorage.jei.transfer.request_autocrafting").withStyle(ChatFormatting.BLUE)); } return message; } }
mit
dstar55/100-words-design-patterns-java
src/main/java/com/hundredwordsgof/composite/Leaf.java
192
package com.hundredwordsgof.composite; /** * * Leaf class represents leaf objects in the composition * */ public class Leaf extends Component { void operation() { } }
mit
WilliansCPPP/jeasygame
src/easygame/TouchVerifier.java
2252
/*The MIT License (MIT) Copyright (c) 2015 Willians Magalhães Primo 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 easygame; import android.view.MotionEvent; /** * Essa classe é utilizada para verificar se houve toque em algum elemento. * @author Willians Magalhães Primo */ public class TouchVerifier { protected static Vector2D touchPosition = new Vector2D(0.0f, 0.0f), elementPosition = new Vector2D(0.0f, 0.0f); /** * Verifica se o elemento foi tocado. */ public static boolean touched(MotionEvent event, Properties properties){ touchPosition.set(event.getX(), event.getY()); elementPosition.set(properties.getPosition()); if(properties.getRotation() != 0){ touchPosition.rotate(-properties.getRotation()); elementPosition.rotate(-properties.getRotation()); } if(touchPosition.getX() < (elementPosition.getX() - properties.getWidth()/2)){ return false; } if(touchPosition.getX() > (elementPosition.getX() + properties.getWidth()/2)){ return false; } if(touchPosition.getY() < (elementPosition.getY() - properties.getHeight()/2)){ return false; } if(touchPosition.getY() > (elementPosition.getY() + properties.getHeight()/2)){ return false; } return true; } }
mit
jiangkunkun/cmsbuild
src/main/java/com/mingsoft/parser/IGeneralParser.java
7835
/** The MIT License (MIT) * Copyright (c) 2015 铭飞科技 * 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.mingsoft.parser; import java.io.File; import org.apache.log4j.Logger; import com.mingsoft.basic.entity.AppEntity; import com.mingsoft.base.constant.Const; import com.mingsoft.parser.impl.general.GlobalCopyrightParser; import com.mingsoft.parser.impl.general.GlobalDescripParser; import com.mingsoft.parser.impl.general.GlobalHostParser; import com.mingsoft.parser.impl.general.GlobalKeywordParser; import com.mingsoft.parser.impl.general.GlobalLogoParser; import com.mingsoft.parser.impl.general.GlobalNameParser; import com.mingsoft.parser.impl.general.GlobalSkinUrlParser; import com.mingsoft.parser.impl.general.GlobalUrlParser; import com.mingsoft.parser.impl.general.IncludeParser; import com.mingsoft.util.PageUtil; import com.mingsoft.util.StringUtil; /** * * * * <p> * <b>铭飞科技</b> * </p> * * <p> * Copyright: Copyright (c) 2014 - 2015 * </p> * * @author killfen * * <p> * Comments: ms平台通用标签解析 * </p> * * <p> * Create Date:2015-4-19 * </p> * * <p> * Modification history: * </p> */ public abstract class IGeneralParser extends IParser { /** * 移动端生成路径 */ public static final Object MOBILE = "mobilePath"; protected AppEntity app; protected String mobilePath = ""; protected String htmlContent; protected PageUtil page; /** * 模块模板路径,例如论坛、商城等 */ protected String modelPath = ""; /** * 模块编号 */ protected int modelId; public static final String MODEL_ID = "modelId", CUR_COLUMNID = "curColumnId", PREVIOUS = "previous", NEXT = "next", CUR_PAGE_NO = "curPageNo", LIST_LINK_PATH = "listLinkPath"; /** * 通用的标签解析方法,其他扩展方法务必要调用该方法,否则导致模板页面取不出基本数据,如:网站名称,网站的地址,关键字等待 * * @return 解析好的内容,一般不会出现什么问题,如果出现问题会返回注释格式的提示信息 */ protected String parseGeneral() { htmlContent = new IncludeParser(htmlContent, Const.PROJECT_PATH + File.separator + IParserRegexConstant.REGEX_SAVE_TEMPLATE + File.separator + app.getAppId() + File.separator + app.getAppStyle() + File.separator + modelPath + File.separator, mobilePath).parse(); // 替换网站版权信息标签:{ms: global.copyright/} htmlContent = new GlobalCopyrightParser(htmlContent, app.getAppCopyright()).parse(); // 替换网站关键字标签:{ms: global.keyword/} htmlContent = new GlobalKeywordParser(htmlContent, app.getAppKeyword()).parse(); // 替换网站LOGO标签:{ms: global.logo/} htmlContent = new GlobalLogoParser(htmlContent, app.getAppLogo()).parse(); // 替换网站名称标签:{ms:global.name /} htmlContent = new GlobalNameParser(htmlContent, app.getAppName()).parse(); // 替换模版链接地址标签:{ms: globalskin.url/} String tmpSkinUrl = app.getAppHostUrl() + StringUtil.removeRepeatStr(File.separator + IParserRegexConstant.REGEX_SAVE_TEMPLATE + File.separator + app.getAppId() + File.separator + app.getAppStyle(), File.separator)+File.separator; // 替换网站链接地址标签:{ms:global.url/} String linkUrl = app.getAppHostUrl() + File.separator + IParserRegexConstant.HTML_SAVE_PATH + File.separator + app.getAppId()+File.separator; //如果论坛模板不为空,模板连接地址=原有地址+"/"+论坛模板 if(!StringUtil.isBlank(modelPath)){ tmpSkinUrl=tmpSkinUrl+ File.separator +modelPath; linkUrl=linkUrl+File.separator +modelPath; } //如果手机端模板不为空,模板连接地址=原有地址+"/"+手机模板 if(!StringUtil.isBlank(this.mobilePath)){ tmpSkinUrl=tmpSkinUrl+File.separator + this.mobilePath; linkUrl=linkUrl+File.separator +this.mobilePath; } //去掉重复的"/" //tmpSkinUrl = StringUtil.removeRepeatStr(tmpSkinUrl, File.separator); //linkUrl = StringUtil.removeRepeatStr(linkUrl, File.separator); htmlContent = new GlobalSkinUrlParser(htmlContent, tmpSkinUrl).parse(); htmlContent = new GlobalUrlParser(htmlContent, linkUrl).parse(); // 替换网站链接地址标签:{ms:global.host/} htmlContent = new GlobalHostParser(htmlContent, app.getAppHostUrl()).parse(); // 替换网站描述标签:{ms: global.descrip/} htmlContent = new GlobalDescripParser(htmlContent, app.getAppDescription()).parse(); return htmlContent; } /** * 生成通用标签, * * @param modelPath * 对用模块模板路径 * @return 解析后的结果 */ protected String parseGeneral(String modelPath) { this.modelPath = modelPath; return parseGeneral(); } /** * 会根据用户的请求客户端返回pc页面\手机页面主机地址 * * @return 应用的主机地址 */ protected String getWebsiteUrl() { if (!StringUtil.isBlank(mobilePath)) { return StringUtil.removeRepeatStr(app.getAppHostUrl() + File.separator + IParserRegexConstant.HTML_SAVE_PATH + File.separator + app.getAppId() + File.separator + mobilePath,File.separator); } return app.getAppHostUrl() + File.separator + IParserRegexConstant.HTML_SAVE_PATH + File.separator + app.getAppId(); } /** * 解析方法模板,最后调用该方法返回生成后的数据 * * @param html * 模板源代码 * @param obj *  可选:便于子模块调用的时候进行参数扩展,具体的参数由子模块控制,例如解析分页模板的时候就需要外部传入地址, * @return 生成好的html内容 */ public abstract String parse(String html, Object... obj); @Override public String parse() { // TODO Auto-generated method stub return this.parse(); } /** * 解析器入口,通常第一个参数未appEntity,如果存在map类型,那么map的的键值为IGeneralParser常量 * 1、内容数据显示、列表数据、 a、cms 下的文章显示,当前文章的上一篇、下一篇、当前文章栏目 MsTagParser mtp = new * MsTagParser(模块代码,ServletConext); Map map = new HashMap(); * map.put(CmsParser.PREVIOUS,preArticle); * map.put(CmsParser.NEXT,preArticle); mtp.parse(app,article,); * * b、cms列表,必须知道当前栏目信息 mtp.parse(app,article,column); 2、自动定义页面 * * @param obj * ,可以存在多个,对于基础数据类型可以使用map存储,对象直接传入 * @return */ public void init(Object... obj) { for (Object o : obj) { if (o != null) { if (o instanceof AppEntity) { this.app = (AppEntity) o; } if (o instanceof PageUtil) { this.page = (PageUtil) o; } } } } }
mit
lockan/WifiDoorBell
AndroidSender/HeyListenDroid/app/src/main/java/net/lockan/heylisten/HeyListenMain.java
880
package net.lockan.heylisten; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class HeyListenMain extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hey_listen_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_hey_listen_main, menu); return true; } public void sendHeyListen(View v) { UDPBroadcastTask heylistentask = new UDPBroadcastTask(); heylistentask.execute(); } }
mit
shromyak/AlienClock
app/src/main/java/com/svyat/sample/alienclock/content/DefaultContentManager.java
4135
package com.svyat.sample.alienclock.content; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import com.svyat.sample.alienclock.controller.AlienController; import com.svyat.sample.alienclock.settings.AlienSettingsManager; import java.util.HashSet; /** * Created by shromyak on 14.07.2016. * * This certain implementation of content brick persistence is based on Shared Preferences * You can make your own implementation based on Content Provider, for example * * The main idea is that components don't know what exact content should be shown on the screen * Control upon this behaviour is delegated to this controller * * Please refer to component brick interface description * for extra explanation * * @link AlienContentBrick * and * @link DefaultContentScheme */ public class DefaultContentManager implements AlienContentManager { private static DefaultContentManager instance; private final static String PREFS_FILE_PREFIX = "alien_content_scheme"; private String sharedPrefsSchemeFile = PREFS_FILE_PREFIX; private boolean needClearStore = false; public synchronized static DefaultContentManager get(Context context) { if (instance == null) { instance = new DefaultContentManager(context); } return instance; } public synchronized static void clear() { if (instance != null) { instance.deinit(); instance = null; } } private final HashSet<AlienController> managedControllers = new HashSet<>(); private final Context context; private DefaultContentManager(Context context) { assert context != null; this.context = context.getApplicationContext(); init(); } private void init() { initStore(); } private void deinit() { unregisterManagedControllers(); } private void initStore() { String suffix = getRootTag(); if (!TextUtils.isEmpty(suffix)) { sharedPrefsSchemeFile = PREFS_FILE_PREFIX + "_" + suffix.toLowerCase().replace('.', '_'); if (sharedPrefsSchemeFile.length() > 127) { sharedPrefsSchemeFile = sharedPrefsSchemeFile.substring(0, 127); } } } private void unregisterManagedControllers() { synchronized (managedControllers) { managedControllers.clear(); } } @Override public void reinitScheme() { DefaultContentScheme scheme = new DefaultContentScheme(context); boolean save = needClearStore; needClearStore = true; scheme.initDefault(); needClearStore = save; } @Override public void storeBrick(AlienContentBrick brick) { context.getSharedPreferences(sharedPrefsSchemeFile, Context.MODE_PRIVATE) .edit() .putString(brick.getTag(), brick.toJson()) .apply(); } @Override public AlienContentBrick getBrickWithTag(String tag) { SharedPreferences prefs = context.getSharedPreferences(sharedPrefsSchemeFile, Context.MODE_PRIVATE); if (prefs.contains(tag)) { String brickAsJson = prefs.getString(tag, ""); return DefaultContentBrick.fromJson(brickAsJson); } return null; } @Override public String getRootTag() { AlienSettingsManager manager = AlienSettingsManager.get(context); return manager.getSettings().getContentRootTag(); } @Override public void setRootTag(String tag) { AlienSettingsManager manager = AlienSettingsManager.get(context); manager.setSettings(manager.getSettings().setContentRootTag(tag)); initStore(); if (needClearStore) { context.getSharedPreferences(sharedPrefsSchemeFile, Context.MODE_PRIVATE).edit().clear().apply(); } } @Override public void reinitWithRootTag(String tag) { boolean save = needClearStore; needClearStore = true; setRootTag(tag); needClearStore = save; } }
mit
jaime29010/RandomHub
src/main/java/me/jaimemartz/randomhub/StatusInfo.java
1289
package me.jaimemartz.randomhub; import net.md_5.bungee.api.config.ServerInfo; public final class StatusInfo { private final String description; private final int online, maximum; private boolean outdated = true; public StatusInfo() { this("Server Unreachable", 0, 0); } public StatusInfo(ServerInfo server) { this(server.getMotd(), server.getPlayers().size(), Integer.MAX_VALUE); } public StatusInfo(String description, int online, int maximum) { this.description = description; this.online = online; this.maximum = maximum; } public String getDescription() { return description; } public int getOnlinePlayers() { return online; } public int getMaximumPlayers() { return maximum; } public void setOutdated(boolean outdated) { this.outdated = outdated; } public boolean isOutdated() { return outdated; } public boolean isAccessible() { if (maximum == 0) { return false; } for (String pattern : ConfigEntries.SERVER_CHECK_MARKERS.get()) { if (description.matches(pattern)) { return false; } } return online < maximum; } }
mit
jeevatkm/digitalocean-api-java
src/test/java/com/myjeeva/digitalocean/DigitalOceanIntegrationReadOperationsTest.java
7888
package com.myjeeva.digitalocean; import static org.junit.Assert.*; import com.myjeeva.digitalocean.common.ActionType; import com.myjeeva.digitalocean.exception.DigitalOceanException; import com.myjeeva.digitalocean.exception.RequestUnsuccessfulException; import com.myjeeva.digitalocean.impl.DigitalOceanClient; import com.myjeeva.digitalocean.pojo.*; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Junit Integration Test case for DigitalOcean API client wrapper ReadOnly methods. So that it call * * <p><strong>Please Note:</strong> <i>Kindly go through and update private variable value before * using executing this test case(s).</i> * * @author Jeevanandam M. (jeeva@myjeeva.com) */ // Marked as Ignore since its a Integration Test case with real values @Ignore @RunWith(JUnit4.class) public class DigitalOceanIntegrationReadOperationsTest { private final Logger log = LoggerFactory.getLogger(DigitalOceanIntegrationTest.class); /** * This is testing values of my own respective to DigitalOcean account, to real-time integration * with API. So place your's for integration test case before use */ private final String authTokenR = ""; private final DigitalOcean apiClient = new DigitalOceanClient(authTokenR); @Test public void testGetAvailableDroplets() throws DigitalOceanException, RequestUnsuccessfulException { Droplets droplets = apiClient.getAvailableDroplets(1, null); assertNotNull(droplets); assertFalse((droplets.getDroplets().isEmpty())); int i = 1; for (Droplet droplet : droplets.getDroplets()) { log.info(i++ + " -> " + droplet.toString()); } } @Test public void testGetAvailableImages() throws DigitalOceanException, RequestUnsuccessfulException { Images images = apiClient.getAvailableImages(1, 20); assertNotNull(images); assertFalse((images.getImages().isEmpty())); for (Image img : images.getImages()) { log.info(img.toString()); } } @Test public void testGetAvailableImagesByDistribution() throws DigitalOceanException, RequestUnsuccessfulException { Images images = apiClient.getAvailableImages(1, 20, ActionType.DISTRIBUTION); assertNotNull(images); assertFalse((images.getImages().isEmpty())); for (Image img : images.getImages()) { log.info(img.toString()); } } @Test public void testGetAvailableImagesByApplication() throws DigitalOceanException, RequestUnsuccessfulException { Images images = apiClient.getAvailableImages(1, 20, ActionType.APPLICATION); assertNotNull(images); assertFalse((images.getImages().isEmpty())); for (Image img : images.getImages()) { log.info(img.toString()); } } @Test public void testGetAvailableImagesByIncorrrect() throws DigitalOceanException, RequestUnsuccessfulException { try { apiClient.getAvailableImages(1, 20, ActionType.BACKUP); } catch (DigitalOceanException doe) { log.info(doe.getMessage()); } } @Test public void testGetUserImages() throws DigitalOceanException, RequestUnsuccessfulException { Images images = apiClient.getUserImages(1, 20); assertNotNull(images); assertFalse((images.getImages().isEmpty())); for (Image img : images.getImages()) { log.info(img.toString()); } } @Test public void testGetImageInfoById() throws DigitalOceanException, RequestUnsuccessfulException { // Ubuntu 18.04 x64 20191022 Integer imageId = 53893572; Image image = apiClient.getImageInfo(imageId); assertNotNull(image); log.info(image.toString()); } @Test public void testGetImageInfoBySlug() throws DigitalOceanException, RequestUnsuccessfulException { String imageSlug = "ubuntu-18-04-x64"; Image image = apiClient.getImageInfo(imageSlug); assertNotNull(image); log.info(image.toString()); } // Regions test cases @Test public void testGetAvailableRegions() throws DigitalOceanException, RequestUnsuccessfulException { Regions regions = apiClient.getAvailableRegions(1); assertNotNull(regions); assertFalse((regions.getRegions().isEmpty())); for (Region region : regions.getRegions()) { log.info(region.toString()); } } // Sizes test cases @Test public void testGetAvailableSizes() throws DigitalOceanException, RequestUnsuccessfulException { Sizes sizes = apiClient.getAvailableSizes(1); assertNotNull(sizes); assertFalse((sizes.getSizes().isEmpty())); for (Size size : sizes.getSizes()) { log.info(size.toString()); } } @Test public void testGetAvailableDomains() throws DigitalOceanException, RequestUnsuccessfulException { Domains domains = apiClient.getAvailableDomains(1); assertNotNull(domains); assertFalse((domains.getDomains().isEmpty())); for (Domain d : domains.getDomains()) { log.info(d.toString()); } } @Test public void testGetDomainInfo() throws DigitalOceanException, RequestUnsuccessfulException { Domain domain = apiClient.getDomainInfo("myjeeva.com"); assertNotNull(domain); log.info(domain.toString()); } @Test public void testGetAvailableKeys() throws DigitalOceanException, RequestUnsuccessfulException { Keys keys = apiClient.getAvailableKeys(1); assertNotNull(keys); assertFalse((keys.getKeys().isEmpty())); for (Key k : keys.getKeys()) { log.info(k.toString()); } } @Test public void testGetAvailableFloatingIPs() throws DigitalOceanException, RequestUnsuccessfulException { FloatingIPs floatingIPs = apiClient.getAvailableFloatingIPs(1, 10); log.info(floatingIPs.toString()); assertNotNull(floatingIPs); // assertFalse((floatingIPs.getFloatingIPs().isEmpty())); int i = 1; for (FloatingIP floatingIP : floatingIPs.getFloatingIPs()) { log.info(i++ + " -> " + floatingIP.toString()); } } @Test public void testGetAvailableTags() throws DigitalOceanException, RequestUnsuccessfulException { Tags tags = apiClient.getAvailableTags(1, 10); log.info(tags.toString()); assertNotNull(tags); } @Test public void testGetAvailableVolumes() throws DigitalOceanException, RequestUnsuccessfulException { Volumes volumes = apiClient.getAvailableVolumes("nyc1"); assertNotNull(volumes); assertFalse((volumes.getVolumes().isEmpty())); int i = 1; for (Volume volume : volumes.getVolumes()) { log.info(i++ + " -> " + volume.toString()); } } @Test public void testGetAvailableLoadBalancers() throws DigitalOceanException, RequestUnsuccessfulException { LoadBalancers lbs = apiClient.getAvailableLoadBalancers(1, null); assertNotNull(lbs); assertTrue((lbs.getLoadBalancers().isEmpty())); int i = 0; for (LoadBalancer lb : lbs.getLoadBalancers()) { log.info(i++ + " -> " + lb.toString()); } } @Test public void testGetAvailableCertificates() throws DigitalOceanException, RequestUnsuccessfulException { Certificates certificates = apiClient.getAvailableCertificates(1, 10); assertNotNull(certificates); assertFalse(certificates.getCertificates().isEmpty()); for (Certificate c : certificates.getCertificates()) { log.info(c.toString()); } } @Test public void testGetAvailableFirewalls() throws DigitalOceanException, RequestUnsuccessfulException { Firewalls firewalls = apiClient.getAvailableFirewalls(1, null); assertNotNull(firewalls); assertNotNull(firewalls.getFirewalls()); assertFalse(firewalls.getFirewalls().isEmpty()); int i = 0; for (Firewall firewall : firewalls.getFirewalls()) { log.info(i++ + " -> " + firewall.toString()); } } }
mit
alorlea/CurrencyConverterJSF
src/java/currencyConverter/view/Converter.java
4093
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package currencyConverter.view; import currencyConverter.controller.ConversionFacade; import currencyConverter.model.IConversion; import javax.inject.Named; import javax.enterprise.context.ConversationScoped; import javax.enterprise.context.Conversation; import java.io.Serializable; import javax.ejb.EJB; import javax.inject.Inject; /** * * @author Alberto Lorente Leal <albll@kth.se>, <a.lorenteleal@gmail.com> */ @Named(value = "converter") @ConversationScoped public class Converter implements Serializable { @EJB private ConversionFacade convFacade; private String homeCurrency; private String foreignCurrency; private IConversion homeConversion; private IConversion foreignConversion; private Float money = 0.0f; private Float rate = 0.0f; private Float convResult = 0.0f; private Exception transactionFailure; private boolean showRate = false; @Inject private Conversation conversation; private boolean showConversion = false; private void startConversation() { if (conversation.isTransient()) { conversation.begin(); } } private void stopConversation() { if (!conversation.isTransient()) { conversation.end(); } } private void handleException(Exception e) { stopConversation(); e.printStackTrace(System.err); transactionFailure = e; } /** * Set the value of the homeCurrency * @param currency */ public void setHomeCurrency(String currency) { this.homeCurrency = currency; } /** * */ public String getHomeCurrency() { return homeCurrency; } /** * Set the value of the foreignCurrency * @param currency */ public void setForeignCurrency(String currency) { this.foreignCurrency = currency; } /** * */ public String getForeignCurrency() { return foreignCurrency; } /** * set the value of money to change * @param money */ public void setMoney(Float money) { this.money = money; } /** * * @return */ public Float getMoney() { return money; } public Float getConvResult() { return convResult; } public void setConvResult(Float cr) { convResult = cr; } public void findRates() { try { startConversation(); transactionFailure = null; homeConversion = convFacade.findConversion(homeCurrency); foreignConversion = convFacade.findConversion(foreignCurrency); rateCalculator(); showRate = true; } catch (Exception e) { handleException(e); } } /** * Returns the latest thrown exception. */ public Exception getException() { return transactionFailure; } /** * Returns <code>false</code> if the latest transaction failed, otherwise <code>false</code>. */ public boolean getSuccess() { return transactionFailure == null; } private void rateCalculator() { if (homeCurrency.equals("SEK")) { rate = homeConversion.getRate() * foreignConversion.getRate(); } if (homeConversion.equals(foreignConversion)) { rate = homeConversion.getRate() / foreignConversion.getRate(); } else { rate = foreignConversion.getRate() / homeConversion.getRate(); } } public boolean getRateDone() { return showRate; } public Float getRate() { return rate; } public void convert() { findRates(); if (money == null || money.isNaN() || money < 0) { handleException(new Exception("The money must be a positive float number.")); } else { convResult = money * rate; showConversion = true; } } public boolean getShowConvert() { return showConversion; } }
mit
selvasingh/azure-sdk-for-java
sdk/storage/mgmt-v2019_06_01/src/main/java/com/microsoft/azure/management/storage/v2019_06_01/EncryptionScopeSource.java
1444
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.storage.v2019_06_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for EncryptionScopeSource. */ public final class EncryptionScopeSource extends ExpandableStringEnum<EncryptionScopeSource> { /** Static value Microsoft.Storage for EncryptionScopeSource. */ public static final EncryptionScopeSource MICROSOFT_STORAGE = fromString("Microsoft.Storage"); /** Static value Microsoft.KeyVault for EncryptionScopeSource. */ public static final EncryptionScopeSource MICROSOFT_KEY_VAULT = fromString("Microsoft.KeyVault"); /** * Creates or finds a EncryptionScopeSource from its string representation. * @param name a name to look for * @return the corresponding EncryptionScopeSource */ @JsonCreator public static EncryptionScopeSource fromString(String name) { return fromString(name, EncryptionScopeSource.class); } /** * @return known EncryptionScopeSource values */ public static Collection<EncryptionScopeSource> values() { return values(EncryptionScopeSource.class); } }
mit
rocket-internet-berlin/RocketBucket
android/RIBucket/src/main/java/de/rocketinternet/android/bucket/core/SharedPrefManager.java
2002
package de.rocketinternet.android.bucket.core; import android.content.Context; import android.content.SharedPreferences; import org.json.JSONException; import de.rocketinternet.android.bucket.models.Bucket; import de.rocketinternet.android.bucket.network.JsonParser; /** * Created by mohamed.elawadi on 22/04/16. */ public final class SharedPrefManager { private SharedPrefManager() { } private static final String KEY_PREFIX = "ROCKET_BUCKET_"; private static SharedPreferences getSharePreferences(Context context) { return android.preference.PreferenceManager.getDefaultSharedPreferences(context); } public static void saveCustomBucket(Context context, String experimentName, Bucket bucket) { String bucketAsString; try { bucketAsString = JsonParser.convertBucketToJSON(bucket).toString(); } catch (JSONException e) { e.printStackTrace(); return; } SharedPreferences.Editor editor = getSharePreferences(context).edit(); editor.putString(KEY_PREFIX.concat(experimentName), bucketAsString); editor.apply(); } public static Bucket getCustomBucket(Context context, String experimentName) { String bucketString = getSharePreferences(context).getString(KEY_PREFIX.concat(experimentName), null); if (bucketString != null) { try { return JsonParser.getBucketFromJSON(bucketString); } catch (JSONException e) { e.printStackTrace(); return null; } } else { return null; } } public static void removeBucket(Context context, String experimentName) { getSharePreferences(context).edit().remove(KEY_PREFIX.concat(experimentName)).apply(); } public static boolean isBucketExist(Context context, String experimentName) { return getSharePreferences(context).contains(KEY_PREFIX.concat(experimentName)); } }
mit
myeonginwoo/KotlinWithAndroid
app/src/main/java/com/lazysoul/kotlinwithandroid/ui/detail/DetailActivity.java
4641
package com.lazysoul.kotlinwithandroid.ui.detail; import com.lazysoul.kotlinwithandroid.R; import com.lazysoul.kotlinwithandroid.common.BaseActivity; import com.lazysoul.kotlinwithandroid.datas.Todo; import com.lazysoul.kotlinwithandroid.singletons.TodoManager; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AlertDialog; import android.support.v7.widget.AppCompatEditText; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; /** * Created by Lazysoul on 2017. 7. 15.. */ public class DetailActivity extends BaseActivity implements DetailMvpView { DetailMvpPresenter<DetailMvpView> presenter; AppCompatEditText et; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); setSupportActionBar((Toolbar) findViewById(R.id.tb_activity_detail)); et = findViewById(R.id.et_activity_detail); et.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { presenter.onTextChanged(s.toString()); } @Override public void afterTextChanged(Editable s) { } }); presenter.loadTodo(getIntent()); } @Override protected void onDestroy() { super.onDestroy(); presenter.destroy(); } @Override public void onBackPressed() { if (!presenter.isFixed()) { super.onBackPressed(); } else { showSaveDialog(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.activity_detail, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem saveMenu = menu.findItem(R.id.menu_activity_main_save); saveMenu.setVisible(presenter.isFixed()); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_activity_main_save: presenter.saveTodo(et.getText().toString()); break; } return super.onOptionsItemSelected(item); } private void showSaveDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.msg_not_save) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); DetailActivity.super.onBackPressed(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } @Override public void inject() { component.inject(this); } @Override public void initPresenter() { presenter = new DetailMvpPresentImpl<>(); presenter.attachView(this); } @Override public void onUpdated(Todo todo, boolean editable) { et.setText(todo.getBody()); if (editable) { et.requestFocus(); } } @Override public void onChagedSaveBt() { invalidateOptionsMenu(); } @Override public void onSaved(int requestType, Todo todo) { int result = -1; switch (requestType) { case TodoManager.REQUEST_TYPE_CREATE: result = TodoManager.RESULT_TYPE_CREATED; break; case TodoManager.REQUEST_TYPE_VIEW: result = TodoManager.RESULT_TYPE_UPDATED; break; } Intent resultData = new Intent(); resultData.putExtra(TodoManager.KEY_RESULT_TYPE, result); resultData.putExtra(TodoManager.KEY_ID, todo.getId()); resultData.putExtra(TodoManager.KEY_BODY, todo.getBody()); setResult(RESULT_OK, resultData); } }
mit
dbisUnibas/cineast
cineast-runtime/src/main/java/org/vitrivr/cineast/standalone/run/path/NoContainerProvider.java
999
package org.vitrivr.cineast.standalone.run.path; import org.vitrivr.cineast.standalone.run.ExtractionCompleteListener; import org.vitrivr.cineast.standalone.run.ExtractionContainerProvider; import org.vitrivr.cineast.standalone.run.ExtractionItemContainer; import java.util.List; import java.util.Optional; /** * Convenience Method when you don't want to actually provide Elements. * * @author silvan on 19.01.18. */ public class NoContainerProvider implements ExtractionContainerProvider, ExtractionCompleteListener { @Override public void onCompleted(ExtractionItemContainer path) { //Ignore } @Override public void close() { //Ignore } @Override public void addPaths(List<ExtractionItemContainer> pathList) { //Ignore } @Override public boolean isOpen() { return false; } @Override public boolean hasNextAvailable() { return false; } @Override public Optional<ExtractionItemContainer> next() { return Optional.empty(); } }
mit
adorilson/AndroidManifestParser
ManifestParser/src/main/java/com/donvigo/androidmanifestparser/manifest/ActivityEntry.java
1401
package com.donvigo.androidmanifestparser.manifest; import org.simpleframework.xml.Attribute; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root; import java.util.List; /** * Created by vgaidarji on 13.03.14. */ @Root(strict = false) public class ActivityEntry{ @Attribute(name = "name", required = false) private String name; @Attribute(name = "theme", required = false) private String theme; @Attribute(name = "excludeFromRecents", required = false) private String excludedFromRecents; @ElementList(entry = "intent-filter", inline = true, required = false) private List<IntentFilterEntry> intentFilter; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTheme() { return theme; } public void setTheme(String theme) { this.theme = theme; } public String getExcludedFromRecents() { return excludedFromRecents; } public void setExcludedFromRecents(String excludedFromRecents) { this.excludedFromRecents = excludedFromRecents; } public List<IntentFilterEntry> getIntentFilter() { return intentFilter; } public void setIntentFilter(List<IntentFilterEntry> intentFilter) { this.intentFilter = intentFilter; } }
mit
vaisaghvt/gameAnalyzer
ecj19/ecj/ec/app/multiplexer/func/D5.java
1706
/* Copyright 2006 by Sean Luke Licensed under the Academic Free License version 3.0 See the file "LICENSE" for more information */ package ec.app.multiplexer.func; import ec.*; import ec.app.multiplexer.*; import ec.gp.*; import ec.util.*; /* * D5.java * * Created: Wed Nov 3 18:26:37 1999 * By: Sean Luke */ /** * @author Sean Luke * @version 1.0 */ public class D5 extends GPNode { final static int bitpos = 5; /* D5 */ public String toString() { return "d5"; } public void checkConstraints(final EvolutionState state, final int tree, final GPIndividual typicalIndividual, final Parameter individualBase) { super.checkConstraints(state,tree,typicalIndividual,individualBase); if (children.length!=0) state.output.error("Incorrect number of children for node " + toStringForError() + " at " + individualBase); } public void eval(final EvolutionState state, final int thread, final GPData input, final ADFStack stack, final GPIndividual individual, final Problem problem) { MultiplexerData md = (MultiplexerData)input; if (md.status == MultiplexerData.STATUS_3) md.dat_3 = Fast.M_3[bitpos + MultiplexerData.STATUS_3]; else if (md.status == MultiplexerData.STATUS_6) md.dat_6 = Fast.M_6[bitpos + MultiplexerData.STATUS_6]; else // md.status == MultiplexerData.STATUS_11 System.arraycopy(Fast.M_11[bitpos + MultiplexerData.STATUS_11],0, md.dat_11,0, MultiplexerData.MULTI_11_NUM_BITSTRINGS); } }
mit
SKCraft/SMES
src/main/java/com/skcraft/smes/tileentity/TileEntityRareMetalExtractor.java
11996
package com.skcraft.smes.tileentity; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; import cofh.api.energy.IEnergyContainerItem; import cofh.api.tileentity.IReconfigurableSides; import cofh.api.transport.IItemDuct; import cofh.lib.util.helpers.BlockHelper; import cofh.lib.util.helpers.InventoryHelper; import cofh.lib.util.helpers.ItemHelper; import com.skcraft.smes.client.gui.GuiRareMetalExtractor; import com.skcraft.smes.inventory.container.ContainerRareMetalExtractor; import com.skcraft.smes.recipes.RareMetalExtractorRecipes; import com.skcraft.smes.util.StringUtils; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class TileEntityRareMetalExtractor extends TileEntityEnergyInventory implements IReconfigurableSides { private static final int batteryCapacity = 1400000; private int[] sideSlots = new int[6]; private int currentEnergyRequired = 0; private int processingEnergy = -1; private int energyPerTick = 1000; private int processedItem = 0; private ItemStack currentlyProcessed; public TileEntityRareMetalExtractor() { super(batteryCapacity, 3); this.resetSides(); } @Override public void updateEntity() { super.updateEntity(); boolean invChanged = false; if (!this.worldObj.isRemote) { if (this.canProcess()) { if (this.processingEnergy < 0) { this.currentEnergyRequired = this.getEnergyRequired(); this.processingEnergy = this.currentEnergyRequired; } this.processingEnergy -= Math.max(this.getBattery().extractEnergy(this.energyPerTick, false), 0); if (this.processingEnergy <= 0) { this.processItem(); invChanged = true; } } else { this.processingEnergy = -1; } if (this.getInventory()[2] != null && this.getInventory()[2].getItem() instanceof IEnergyContainerItem) { int maxExtract = this.getBattery().getMaxEnergyStored() - this.getBattery().getEnergyStored(); int energy = ((IEnergyContainerItem) this.getInventory()[2].getItem()).extractEnergy(this.getInventory()[2], maxExtract, false); this.getBattery().receiveEnergy(energy, false); } } if (invChanged) { this.markDirty(); outputResult(); } } private void outputResult() { // Check all sides if output side for (int i = 0; i < 6; i++) { if (this.getSideConfig(i) == 2) { // Grab the adjecent tile at the output side TileEntity adjecent = BlockHelper.getAdjacentTileEntity(this, i); // Check if the adjecent tile entity is an inventory (IIventory, ISidedInventory or IItemDuct) if (adjecent instanceof IInventory || adjecent instanceof ISidedInventory || adjecent instanceof IItemDuct) { // Try to output into the inventory if (InventoryHelper.isInsertion(adjecent)) { ItemStack notInserted = InventoryHelper.addToInsertion(adjecent, i, this.getInventory()[1]); this.getInventory()[1] = notInserted; } } } } } @Override public void readFromNBT(NBTTagCompound tagCompound) { super.readFromNBT(tagCompound); this.currentEnergyRequired = tagCompound.getInteger("EnergyRequired"); this.processingEnergy = tagCompound.getInteger("ProcessingEnergy"); this.processedItem = tagCompound.getInteger("ProcessedItem"); this.currentlyProcessed = ItemStack.loadItemStackFromNBT(tagCompound.getCompoundTag("CurrentlyProcessed")); } @Override public void writeToNBT(NBTTagCompound tagCompound) { super.writeToNBT(tagCompound); tagCompound.setInteger("EnergyRequired", this.currentEnergyRequired); tagCompound.setInteger("ProcessingEnergy", this.processingEnergy); tagCompound.setInteger("ProcessedItem", this.processedItem); if (this.currentlyProcessed != null) { NBTTagCompound itemStackTagCompound = new NBTTagCompound(); this.currentlyProcessed.writeToNBT(itemStackTagCompound); tagCompound.setTag("CurrentlyProcessed", itemStackTagCompound); } } @Override public boolean isActive() { return this.processingEnergy >= 0; } @Override public Container getContainer(InventoryPlayer invPlayer) { return new ContainerRareMetalExtractor(this, invPlayer); } @Override @SideOnly(Side.CLIENT) public GuiContainer getGui(InventoryPlayer invPlayer) { return new GuiRareMetalExtractor(this, invPlayer); } private boolean canProcess() { if (this.getInventory()[0] != null) { // If no result exists for the current input return false ItemStack result = RareMetalExtractorRecipes.getOutput(this.getInventory()[0]); if (result == null) { return false; } // If the current item being processed is 0 set the current item being processed to the item in the input slot if (this.processedItem == 0 || this.currentlyProcessed == null) { this.currentlyProcessed = this.getInventory()[0]; } else if (!ItemHelper.isOreNameEqual(this.getInventory()[0], ItemHelper.getOreName(this.currentlyProcessed))) { // Ore dictionary check on the item vs the item being processed to allow other items of same ore dict to be processed return false; } // Add the stacksize to the amount already processed and remove the itemstack this.processedItem += this.getInventory()[0].stackSize; this.getInventory()[0] = null; } if (this.currentlyProcessed != null) { // If no result exists for the current input return false ItemStack result = RareMetalExtractorRecipes.getOutput(this.currentlyProcessed); if (result == null) { return false; } // If there isn't enough processed yet return false if (processedItem < RareMetalExtractorRecipes.getInputSize(this.currentlyProcessed)) { return false; } // Check if there is space to process if (this.getInventory()[1] != null) { if ((this.getInventory()[1].stackSize + result.stackSize) > this.getInventoryStackLimit() || !ItemHelper.isOreNameEqual(this.getInventory()[1], ItemHelper.getOreName(result))) { return false; } } // Everything is okay! Return true return true; } return false; } private void processItem() { if (this.canProcess()) { ItemStack result = RareMetalExtractorRecipes.getOutput(this.currentlyProcessed); if (this.getInventory()[1] == null) { this.getInventory()[1] = result.copy(); } else if (ItemHelper.isOreNameEqual(this.getInventory()[1], ItemHelper.getOreName(result))) { this.getInventory()[1].stackSize += result.stackSize; } this.processedItem -= RareMetalExtractorRecipes.getInputSize(this.currentlyProcessed); this.processingEnergy = -1; if (this.processedItem <= 0) { this.currentlyProcessed = null; } } } private int getEnergyRequired() { if (this.currentlyProcessed != null) { return RareMetalExtractorRecipes.getEnergyRequired(this.currentlyProcessed); } return 0; } @SideOnly(Side.CLIENT) public int getProcessingEnergyScaled(int scale) { return this.processingEnergy >= 0 ? (int) Math.floor(((double) this.currentEnergyRequired - (double) this.processingEnergy) / this.currentEnergyRequired * scale) : 0; } @Override public String getInventoryName() { return StringUtils.translate("gui.rareMetalExtractor.name", true); } @Override public boolean hasCustomInventoryName() { return true; } public int getCurrentRequiredEnergy() { return this.currentEnergyRequired; } public int getProcessingEnergy() { return this.processingEnergy; } public int getSideConfig(int side) { return this.sideSlots[side]; } public void setProcessingEnergy(int energy) { this.processingEnergy = energy; } public void setCurrentRequiredEnergy(int energy) { this.currentEnergyRequired = energy; } /* ISidedInventory */ /** * Return the slot indeces available from the given side. * Can return the slot configuration - 1 as this'd reflect the slot id */ @Override public int[] getAccessibleSlotsFromSide(int side) { int sideConfig = sideSlots[side]; switch(sideConfig) { case 0: return new int[] {}; case 1: // Input slot return new int[] { 0 }; case 2: // Output slot return new int[] { 1 }; default: return new int[] {}; } } @Override public boolean canInsertItem(int slot, ItemStack item, int side) { return sideSlots[side] == 1 && this.getContainer(null).getSlot(0).isItemValid(item); } @Override public boolean canExtractItem(int slot, ItemStack item, int side) { return sideSlots[side] == 2; } /* IReconfigurableSides */ @Override public boolean decrSide(int side) { if (this.sideSlots[side] > 1) { this.sideSlots[side]--; } else if (this.sideSlots[side] == 0) { this.sideSlots[side] = this.getNumConfig(side); } else { return false; } return true; } @Override public boolean incrSide(int side) { if (this.sideSlots[side] < this.getNumConfig(side) - 1) { this.sideSlots[side]++; } else if (this.sideSlots[side] == this.getNumConfig(side)) { this.sideSlots[side] = 0; } else { return false; } return true; } @Override public boolean setSide(int side, int config) { if (config < this.getNumConfig(side)) { this.sideSlots[side] = config; return true; } else { return false; } } /** * Reset configs on all sides to their base values. * * Base values: * West of facing is input, * East of facing is output * * @return True if reset was successful, false otherwise. */ @Override public boolean resetSides() { this.sideSlots[BlockHelper.getRightSide(getFacing().ordinal())] = 1; this.sideSlots[BlockHelper.getLeftSide(getFacing().ordinal())] = 2; return true; } /** * Returns the number of possible config settings for a given side. * * In this case the following options are available for all sides: * 0: None * 1: Input * 2: Output */ @Override public int getNumConfig(int side) { return 3; } }
mit
bingzhang/stork-iRods
stork/ad/AdType.java
11313
package stork.ad; import java.lang.reflect.*; import java.util.*; // A betterized wrapper around Java reflection types that makes it feel // just a bit more classlier. class AdType { final transient Type type; private transient Class clazz; private transient AdType parent; protected AdType(Member m) { this(getMemberType(m)); } protected AdType(Type t) { if (t == null) throw new NullPointerException(); type = t; } // Get the type from an accessible object. private static Type getMemberType(Member m) { if (m instanceof Field) return ((Field)m).getGenericType(); if (m instanceof Method) return ((Method)m).getGenericReturnType(); if (m instanceof Constructor) return ((Constructor)m).getDeclaringClass(); throw new Error("Invalid member: "+m); } // Print the wrapped type in a way similar to how it would appear in // source code. public String toString() { String ps = ""; if (owner() != null) ps = owner()+"."; if (isArray()) return component()+"[]"; return ps+clazz().getSimpleName()+genericString(); } private String genericString() { AdType[] g = generics(); String s = ""; switch (g.length) { default: for (int i = 1; i < g.length; i++) s += ","+g[i]; case 1: return "<"+g[0]+s+">"; case 0: return s; } } // Type Reification // ---------------- // Resolve the raw class type, if possible. Otherwise null. protected Class clazz() { return (clazz != null) ? clazz : (clazz = clazz(type)); } private Class clazz(Type type) { if (type instanceof Class) return (Class) type; if (type instanceof ParameterizedType) return clazz(((ParameterizedType) type).getRawType()); if (type instanceof GenericArrayType) return reifyArrayType(); if (type instanceof TypeVariable) return reifyTypeVariable((TypeVariable) type); if (type instanceof WildcardType) return clazz(((WildcardType)type).getUpperBounds()[0]); throw new Error(type.getClass().toString()); } // Resolve a type variable against the parent type. Only works on a // best-effort basis. Returns upper type bound if the variable can't // be resolved. private Class reifyTypeVariable(TypeVariable v) { if (parent != null) return parent.resolveTypeVariable(v); return clazz(v.getBounds()[0]); } // Resolve a type variable against this type. Returns upper type bound // if the variable can't be resolved. private Class resolveTypeVariable(TypeVariable v) { if (type instanceof ParameterizedType) { Type t = scope().get(v); if (t != null) return clazz(t); } return clazz(v.getBounds()[0]); } // Get the raw class of an array type, or null if not an array. Only // really useful if the type is a generic array. private Class reifyArrayType() { return isArray() ? component().arrayType(1) : null; } // Returns whether the type is an array and thus has a component type. protected boolean isArray() { return (type instanceof GenericArrayType) || clazz().isArray(); } // Return an array class with a component type of the encapsulated class. protected Class arrayType(int dim) { AdType t = this; if (dim <= 0) return clazz(); return asArray(new int[dim]).getClass(); } // Get the generic parameters of the type. Returns a zero-length array if the // type has no generic parameters. protected AdType[] generics() { return wrap(rawGenerics()); } private Type[] rawGenerics() { if (type instanceof ParameterizedType) return ((ParameterizedType) type).getActualTypeArguments(); if (type instanceof Class) return ((Class)type).getTypeParameters(); return new Type[0]; } // Get the type variable scope for this type. protected Map<TypeVariable, Type> scope() { Map<TypeVariable, Type> scope; scope = (parent != null) ? parent.scope() : new HashMap<TypeVariable, Type>(); Type[] types = rawGenerics(); TypeVariable[] vars = clazz().getTypeParameters(); assert types.length == vars.length; for (int i = 0; i < vars.length; i++) scope.put(vars[i], types[i]); return scope; } // Wrap an array of types. protected AdType[] wrap(Type[] types) { return wrap(this, types); } protected static AdType[] wrap(AdType parent, Type[] types) { AdType[] arr = new AdType[types.length]; for (int i = 0; i < types.length; i++) { arr[i] = new AdType(types[i]); if (parent != null) arr[i].parent(parent); } return arr; } // If this an array, get the component type. Otherwise null. protected AdType component() { Type t = rawComponent(); return (t != null) ? new AdType(t) : null; } private Type rawComponent() { if (type instanceof GenericArrayType) return ((GenericArrayType)type).getGenericComponentType(); return clazz().getComponentType(); } // Type Hierarchy Reflection // ------------------------- // Get the superclasses of this type, from most general to most specific (or // reversed), including this type. The returned array will contain only this // type if the wrapped type is an interface or an array type. protected AdType[] supers() { return supers(false); } protected AdType[] supers(boolean reverse) { List<AdType> list = new LinkedList<AdType>(); return fillSupers(list, reverse).toArray(new AdType[0]); } private List<AdType> fillSupers(List<AdType> list, boolean reverse) { if (parent != null) parent.fillSupers(list, reverse); else if (rawSuper() != null) superclass().fillSupers(list, reverse); if (reverse) list.add(0, this); else list.add(this); return list; } // Get the super class of this type, or null if it's an interface or array // type. protected AdType superclass() { Type t = rawSuper(); if (t == null) return null; return new AdType(t); } private Type rawSuper() { if (isArray()) return null; return clazz().getGenericSuperclass(); } // Get the owner type of this type, or null if there is none. protected AdType owner() { Type o = rawOwner(); return (o != null) ? new AdType(o) : null; } private Type rawOwner() { if (type instanceof ParameterizedType) return ((ParameterizedType) type).getOwnerType(); return clazz().getEnclosingClass(); } // Set the parent type, for more accurate type reification. protected AdType parent(AdType p) { parent = p; return this; } // Member Reflection // ----------------- // Get the fields from the class as a mapping from their names to their // reflective field objects. XXX: Homonymous but otherwise distinct fields // in superclasses will not be accessible through this. protected AdMember[] fields() { return fields(false); } protected AdMember[] fields(boolean publicOnly) { Map<String, AdMember> fm = new HashMap<String, AdMember>(); if (publicOnly) fillFields(fm, clazz().getFields()); else for (AdType t : supers()) t.fillFields(fm, t.clazz().getDeclaredFields()); return fm.values().toArray(new AdMember[fm.size()]); } private void fillFields(Map<String, AdMember> fm, Field[] fs) { for (Field f : fs) fm.put(f.getName(), (AdMember) new AdMember(f).parent(this)); } // Get a single field. protected AdMember field(String name) { Field f = rawField(name); if (f == null) return null; return (AdMember) new AdMember(f).parent(this); } private Field rawField(String name) { try { return clazz().getDeclaredField(name); } catch (Exception e) { } try { return clazz().getField(name); } catch (Exception e) { return null; } } // Get a constructor for the class based on the parameter type, or null if // none exists. protected AdMember constructor(Class... params) { try { return new AdMember(clazz().getDeclaredConstructor(params)); } catch (Exception e) { return null; } } // Get a method based on the parameter type. protected AdMember method(String name, Class... params) { Method m = rawMethod(name, params); if (m == null) return null; return new AdMember(m); } protected Method rawMethod(String name, Class... params) { try { Method m = clazz().getDeclaredMethod(name, params); if (!AdMember.ignore(m)) return m; } catch (NoSuchMethodException e) { } try { Method m = clazz().getMethod(name, params); if (!AdMember.ignore(m)) return m; } catch (NoSuchMethodException e) { } return null; } // Get all the methods exposed by this class. protected AdMember[] methods() { try { Set<AdMember> methods = new HashSet<AdMember>(); for (Method m : clazz().getDeclaredMethods()) if (!AdMember.ignore(m)) methods.add(new AdMember(m)); for (Method m : clazz().getMethods()) if (!AdMember.ignore(m)) methods.add(new AdMember(m)); return methods.toArray(new AdMember[methods.size()]); } catch (Exception e) { return null; } } // Get all the methods of a given name exposed by this class. protected AdMember[] methods(String name) { try { Set<AdMember> methods = new HashSet<AdMember>(); for (Method m : clazz().getDeclaredMethods()) if (!AdMember.ignore(m)) if (name.equals(m.getName())) methods.add(new AdMember(m)); for (Method m : clazz().getMethods()) if (!AdMember.ignore(m)) if (name.equals(m.getName())) methods.add(new AdMember(m)); return methods.toArray(new AdMember[methods.size()]); } catch (Exception e) { return null; } } // Returns whether the type is a non-static inner type and thus requires // an enclosing instance of the parent class. protected boolean isInner() { return clazz().isMemberClass(); } // Misc // ---- // Check if this type is a primitive. protected boolean isPrimitive() { return clazz().isPrimitive(); } // Takes care of those nasty primitive type classes. protected Class wrapper() { return wrapper(clazz()); } private static Class wrapper(Class c) { if (c.isPrimitive()) { if (c == int.class) return Integer.class; if (c == long.class) return Long.class; if (c == double.class) return Double.class; if (c == boolean.class) return Boolean.class; if (c == float.class) return Float.class; if (c == char.class) return Character.class; if (c == byte.class) return Byte.class; if (c == short.class) return Short.class; if (c == void.class) return Void.class; } return c; } // Return a new array instance of this type. protected Object asArray(int... dims) { if (dims == null || dims.length == 0) throw new IllegalArgumentException(); return Array.newInstance(clazz(), dims); } // Check if the type is an enum. protected boolean isEnum() { return clazz().isEnum(); } // If this is an enum, look it up by a string value. Returns null if not // found or type is not an enum. public Enum resolveEnum(String s) { try { return Enum.valueOf(clazz(), s); } catch (Exception e) { return null; } } }
mit
jamilr/fashionScraper
src/main/java/org/fscraper/helpers/ImgType.java
310
package org.fscraper.helpers; public enum ImgType { JPG("jpg"), PNG("png"), BMP("bmp"); private String ext; ImgType(String ext) { this.ext = ext; } public String getExt() { return ext; } public void setExt(String ext) { this.ext = ext; } }
mit
yuriytkach/spring-basics-course-project
src/main/java/com/yet/spring/core/aspects/ConsoleLoggerLimitAspect.java
1011
package com.yet.spring.core.aspects; import org.aspectj.lang.ProceedingJoinPoint; import com.yet.spring.core.beans.Event; import com.yet.spring.core.loggers.EventLogger; public class ConsoleLoggerLimitAspect { private final int maxCount; private final EventLogger otherLogger; private int currentCount = 0; public ConsoleLoggerLimitAspect(int maxCount, EventLogger otherLogger) { this.maxCount = maxCount; this.otherLogger = otherLogger; } public void aroundLogEvent(ProceedingJoinPoint jp, Event evt) throws Throwable { if (currentCount < maxCount) { System.out.println("ConsoleEventLogger max count is not reached. Continue..."); currentCount++; jp.proceed(new Object[] {evt}); } else { System.out.println("ConsoleEventLogger max count is reached. Logging to " + otherLogger.getName()); otherLogger.logEvent(evt); } } }
mit
tim-group/karg
src/main/java/com/timgroup/karg/naming/TargetNameFormatter.java
2342
package com.timgroup.karg.naming; import java.util.Iterator; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import static com.google.common.base.Functions.compose; import static com.google.common.collect.Iterators.concat; import static com.google.common.collect.Iterators.singletonIterator; import static com.google.common.collect.Iterators.transform; import static com.google.common.collect.Lists.newArrayList; import static com.timgroup.karg.naming.StringFunctions.CAPITALISE; import static com.timgroup.karg.naming.StringFunctions.LOWERCASE_TRIM; public interface TargetNameFormatter { static final TargetNameFormatter LOWER_CAMEL_CASE = new LowerCamelCaseFormatter(); static final TargetNameFormatter UPPER_CAMEL_CASE = new UpperCamelCaseFormatter(); static final TargetNameFormatter UNDERSCORE_SEPARATED = new UnderscoreSeparatedFormatter(); static final class LowerCamelCaseFormatter implements TargetNameFormatter { @Override public String format(Iterable<String> words) { Iterator<String> lowercased = transform(words.iterator(), LOWERCASE_TRIM); if (!lowercased.hasNext()) { return ""; } Iterator<String> lowerCamelCased = concat(singletonIterator(lowercased.next()), transform(lowercased, CAPITALISE)); return Joiner.on("").join(Lists.newArrayList(lowerCamelCased)); } } static final class UpperCamelCaseFormatter implements TargetNameFormatter { @Override public String format(Iterable<String> words) { Iterator<String> upperCamelCased = transform(words.iterator(), compose(CAPITALISE, LOWERCASE_TRIM)); return Joiner.on("").join(Lists.newArrayList(upperCamelCased)); } } static final class UnderscoreSeparatedFormatter implements TargetNameFormatter { @Override public String format(Iterable<String> words) { Iterator<String> upperCamelCased = transform(words.iterator(), LOWERCASE_TRIM); return Joiner.on("_").join(newArrayList(upperCamelCased)); } } public abstract String format(Iterable<String> words); }
mit
NataliaD/Android-Dice-game-Study-Project
DiceApp4/gen/ru/devprojet/diceapp4/BuildConfig.java
163
/** Automatically generated file. DO NOT MODIFY */ package ru.devprojet.diceapp4; public final class BuildConfig { public final static boolean DEBUG = true; }
mit
concord-consortium/energy3d
src/main/java/org/concord/energy3d/undo/SetFresnelReflectorLabelCommand.java
1738
package org.concord.energy3d.undo; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import org.concord.energy3d.model.FresnelReflector; public class SetFresnelReflectorLabelCommand extends MyAbstractUndoableEdit { private static final long serialVersionUID = 1L; private final boolean oldLabelId; private final boolean oldLabelCustom; private final boolean oldLabelEnergyOutput; private boolean newLabelId; private boolean newLabelCustom; private boolean newLabelEnergyOutput; private final FresnelReflector reflector; public SetFresnelReflectorLabelCommand(final FresnelReflector reflector) { this.reflector = reflector; oldLabelId = reflector.getLabelId(); oldLabelCustom = reflector.getLabelCustom(); oldLabelEnergyOutput = reflector.getLabelEnergyOutput(); } public FresnelReflector getFresnelReflector() { return reflector; } public boolean getOldLabelId() { return oldLabelId; } public boolean getNewLabelId() { return newLabelId; } @Override public void undo() throws CannotUndoException { super.undo(); newLabelId = reflector.getLabelId(); newLabelCustom = reflector.getLabelCustom(); newLabelEnergyOutput = reflector.getLabelEnergyOutput(); reflector.setLabelId(oldLabelId); reflector.setLabelCustom(oldLabelCustom); reflector.setLabelEnergyOutput(oldLabelEnergyOutput); reflector.draw(); } @Override public void redo() throws CannotRedoException { super.redo(); reflector.setLabelId(newLabelId); reflector.setLabelCustom(newLabelCustom); reflector.setLabelEnergyOutput(newLabelEnergyOutput); reflector.draw(); } @Override public String getPresentationName() { return "Change Label of Fresnel Reflector"; } }
mit
justin-espedal/polydes
Common/src/com/polydes/common/sys/FilePreviewer.java
2272
package com.polydes.common.sys; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import org.apache.commons.lang3.StringUtils; import com.polydes.common.comp.DisabledPanel; import com.polydes.common.ui.propsheet.PropertiesSheetStyle; import misc.gfx.GraphicsUtilities; public class FilePreviewer { public static JPanel getPreview(SysFile f) { String type = Mime.get(f.getFile()); JComponent toPreview = null; if(type.startsWith("image")) toPreview = buildImagePreview(f.getFile()); else if(type.startsWith("text") || type.equals("application/octet-stream")) toPreview = buildTextPreview(f.getFile()); if(toPreview != null) { DisabledPanel previewPanel = new DisabledPanel(toPreview); previewPanel.setBackground(PropertiesSheetStyle.DARK.pageBg); previewPanel.setEnabled(false); previewPanel.setDisabledColor(new Color(0, 0, 0, 0)); return previewPanel; } JPanel filePanel = new JPanel(); filePanel.add(new JLabel(FileRenderer.fileThumb)); filePanel.setBackground(PropertiesSheetStyle.DARK.pageBg); return filePanel; } private static JComponent buildImagePreview(File f) { try { BufferedImage previewImage = ImageIO.read(f); if(previewImage.getWidth() > 500 || previewImage.getHeight() > 500) previewImage = GraphicsUtilities.createThumbnail(previewImage, 500); return new JLabel(new ImageIcon(previewImage)); } catch (IOException e) { e.printStackTrace(); return new JLabel(); } } private static JComponent buildTextPreview(File f) { JPanel panel = new JPanel(new BorderLayout()); JTextArea preview = new JTextArea(); Dimension previewSize = new Dimension(380, 200); preview.setMinimumSize(previewSize); preview.setMaximumSize(previewSize); preview.setPreferredSize(previewSize); String[] previewLines = FileRenderer.getLines(f, 20); preview.setText(StringUtils.join(previewLines,'\n')); panel.add(preview, BorderLayout.CENTER); return panel; } }
mit
MauricePeek513/MySneakerProject
app/src/main/java/com/adafruit/bluefruit/le/connect/app/PressureActivity.java
4196
package com.adafruit.bluefruit.le.connect.app; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.adafruit.bluefruit.le.connect.R; import com.adafruit.bluefruit.le.connect.ble.BleManager; import java.nio.ByteBuffer; public class PressureActivity extends UartInterfaceActivity { // Log private final static String TAG = PressureActivity.class.getSimpleName(); // Constants private final static boolean kPersistValues = true; private final static String kPreferences = "PressureActivity_prefs"; private final static String kPreferences_color = "color"; private final static int kFirstTimeColor = 0x0000ff; // UI private View mRgbColorView; private TextView mRgbTextView; private int mSelectedColor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pressure); mBleManager = BleManager.getInstance(this); // Start services onServicesDiscovered(); } @Override public void onStop() { // Preserve values if (kPersistValues) { SharedPreferences settings = getSharedPreferences(kPreferences, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putInt(kPreferences_color, mSelectedColor); editor.apply(); } super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_color_picker, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_help) { startHelp(); return true; } return super.onOptionsItemSelected(item); } private void startHelp() { // Launch help activity Intent intent = new Intent(this, CommonHelpActivity.class); intent.putExtra("title_pressure", getString(R.string.colorpicker_help_title)); intent.putExtra("help_pressure", "colorpicker_help.html"); startActivity(intent); } // region BleManagerListener /* @Override public void onConnected() { } @Override public void onConnecting() { } */ @Override public void onDisconnected() { super.onDisconnected(); Log.d(TAG, "Disconnected. Back to previous activity"); setResult(-1); // Unexpected Disconnect finish(); } /* @Override public void onServicesDiscovered() { super.onServicesDiscovered(); } @Override public void onDataAvailable(BluetoothGattCharacteristic characteristic) { } @Override public void onDataAvailable(BluetoothGattDescriptor descriptor) { } @Override public void onReadRemoteRssi(int rssi) { } */ // endregion public void onClickSendStart(View view) { ByteBuffer buffer = ByteBuffer.allocate(2).order(java.nio.ByteOrder.LITTLE_ENDIAN); Log.d(TAG, "onClickSendStart"); // prefix String prefix = "!P"; buffer.put(prefix.getBytes()); byte[] result = buffer.array(); sendDataWithCRC(result); } public void onClickSendStop(View view) { ByteBuffer buffer = ByteBuffer.allocate(2).order(java.nio.ByteOrder.LITTLE_ENDIAN); Log.d(TAG, "onClickSendStop"); // prefix String prefix = "!Q"; buffer.put(prefix.getBytes()); byte[] result = buffer.array(); sendDataWithCRC(result); } }
mit
dajidan/CMART
WEB-INF/src/com/cmart/PageControllers/ConfirmBidController.java
4292
package com.cmart.PageControllers; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import com.cmart.Data.Error; import com.cmart.Data.GlobalVars; import com.cmart.util.CheckInputs; import com.cmart.util.StopWatch; /** * This controller controls the confirm bid page * * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com) * @since 0.1 * @version 1.0 * @date 23rd Aug 2012 * * C-MART Benchmark * Copyright (C) 2011-2012 theONE Networking Group, Carnegie Mellon University, Pittsburgh, PA 15213, U.S.A * * 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/>. * */ public class ConfirmBidController extends PageController{ private static final GlobalVars GV = GlobalVars.getInstance(); // Variables passed in the request private long userID = -1; private String authToken = null; private String itemName = null; private String bid = null; // Structures to hold the DB data // Structures to hold the parsed page data /** * This method checks the page for any input errors that may have come from Client generator error * These would need to be check in real life to stop users attempting to hack and mess with things * * @param request * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com) */ public void checkInputs(HttpServletRequest request){ super.startTimer(); if(request != null){ super.checkInputs(request); // Get the userID (if exists), we will pass it along to the next pages try{ this.userID = CheckInputs.checkUserID(request); } catch(Error e){ } // Get the authToken (if exists), we will pass it along to the next pages try{ this.authToken = CheckInputs.checkAuthToken(request); } catch(Error e){ } // Get the item name this.itemName = CheckInputs.getParameter(request, "itemName"); // Get the bid amount this.bid = CheckInputs.getParameter(request, "bid"); } // Calculate how long that took super.stopTimerAddParam(); } /** * This method get the data needed for the HTML4 page from the database * * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com) */ public void getHTML4Data() { super.startTimer(); // Calculate how long that took super.stopTimerAddDB(); } /** * This method processes all of the data that was read from the database such that it is ready to be printed * on to the page. We try to do as much of the page logic here as possible * * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com) */ public void processHTML4() { super.startTimer(); // Calculate how long that took super.stopTimerAddProcessing(); } /** * Gets the HTML5 data from the database * * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com) */ public void getHTML5Data(){ super.startTimer(); // Calculate how long that took super.stopTimerAddDB(); } /** * Processes the HTML5 data that is needed to create the page * * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com) */ public void processHTML5(){ super.startTimer(); // Calculate how long that took super.stopTimerAddProcessing(); } /** * Returns the current userID as a String * * @return String the userID * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com) */ public String getUserIDString(){ return Long.toString(this.userID); } /** * Returns the authToken sent to the page * * @return string the authToken * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com) */ public String getAuthTokenString(){ return this.authToken; } public String getItemName(){ return this.itemName; } public String getBid(){ return this.bid; } }
mit
maxim-pandra/yandexturaev
app/src/main/java/com/example/maxim/turaevyandex/translator/TranslatorPresenter.java
4690
package com.example.maxim.turaevyandex.translator; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import com.example.maxim.turaevyandex.data.Translation; import com.example.maxim.turaevyandex.data.source.LoaderProvider; import com.example.maxim.turaevyandex.data.source.TranslationsDataSource; import com.example.maxim.turaevyandex.data.source.TranslationsRepository; import timber.log.Timber; class TranslatorPresenter implements TranslatorContract.Presenter, TranslationsRepository.LoadDataCallback, TranslationsDataSource.GetTranslationCallback, LoaderManager.LoaderCallbacks<Cursor> { private static final java.lang.String EXTRA_REQUEST = "extra_request"; private static final String EXTRA_TRANSLATION_DIRECTION = "extra_translation_direction"; private final TranslatorContract.View translatorView; @NonNull private final TranslationsRepository translationsRepository; @NonNull private final LoaderManager loaderManager; @NonNull private final LoaderProvider loaderProvider; @NonNull private final SetTitleCallback titleCallback; private TranslationDirection translationDirection; public TranslatorPresenter(@NonNull LoaderProvider loaderProvider, @NonNull LoaderManager supportLoaderManager, @NonNull TranslationsRepository translationsRepository, TranslatorFragment translatorFragment, TranslationDirection translationDirection, @NonNull SetTitleCallback titleCallback) { this.translatorView = translatorFragment; this.translationsRepository = translationsRepository; this.loaderManager = supportLoaderManager; this.loaderProvider = loaderProvider; this.translationDirection = translationDirection; this.titleCallback = titleCallback; this.translatorView.setPresenter(this); } @Override public void start() { titleCallback.setTitle(translationDirection.getStringDirection()); translatorView.showEmptyView(); Timber.d("Translator presenter starts"); } @Override public void loadTranslation(String request) { translatorView.setLoadingIndicator(true); translationsRepository.getTranslation(request, translationDirection.getStringDirection(), this); // loaderProvider.createTranslationLoader(request, translationDirection); } @Override public void updateTranslationBookmarkState(Translation translation) { translationsRepository.setBookmark(translation.getId()); } @Override public void setTranslationDirection(TranslationDirection lang) { titleCallback.setTitle(lang.getStringDirection()); translationDirection = lang; } @Override public void onTranslationLoaded(Translation translation) { translatorView.setLoadingIndicator(false); translatorView.showTranslation(translation); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { String request = args.getString(EXTRA_REQUEST, ""); TranslationDirection translationDirection = ((TranslationDirection) args.getSerializable(EXTRA_TRANSLATION_DIRECTION)); return loaderProvider.createTranslationLoader(request, translationDirection); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null) { if (data.moveToLast()) { onDataLoaded(data); } else { onDataEmpty(); } } else { onDataNotAvailable(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { onDataReset(); } @Override public void onDataLoaded(Cursor data) { translatorView.setLoadingIndicator(false); translatorView.showTranslation(Translation.from(data)); } @Override public void onDataEmpty() { translatorView.setLoadingIndicator(false); translatorView.showEmptyView(); } @Override public void onDataNotAvailable() { translatorView.setLoadingIndicator(false); translatorView.showLoadingTranslationError(); } @Override public void onDataReset() { translatorView.showTranslation(null); } @Override public TranslationDirectionType getTranslationDirection() { return translationDirection.getTranslationDirectionType(); } }
mit
snclucas/spacebits
src/org/spacebits/universe/Universe.java
9772
package org.spacebits.universe; import java.math.BigDecimal; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.spacebits.Configuration; import org.spacebits.components.SpacecraftBusComponent; import org.spacebits.components.Tickable; import org.spacebits.components.TypeInfo; import org.spacebits.components.propulsion.thrust.ThrustingEngine; import org.spacebits.components.sensors.SensorProfile; import org.spacebits.data.EnvironmentDataProvider; import org.spacebits.physics.Unit; import org.spacebits.spacecraft.Spacecraft; import org.spacebits.universe.celestialobjects.CelestialObject; import org.spacebits.universe.celestialobjects.Region; import org.spacebits.universe.celestialobjects.SensorSignalResponseLibrary; import org.spacebits.universe.celestialobjects.SensorSignalResponseProfile; import org.spacebits.universe.celestialobjects.Star; import org.spacebits.universe.structures.SubspaceBeacon; public class Universe implements UniverseLocationDataProvider, UniverseSpacecraftLocationDataProvider, EnvironmentDataProvider, Tickable { private UniverseLocationDataProvider universeLocationDataProvider = Configuration.getUniverseLocationDataProvider(); private UniverseSpacecraftLocationDataProvider universeSpacecraftLocationDataProvider = Configuration.getUniverseSpacecraftLocationDataProvider(); private EnvironmentDataProvider universeEnvironmentDataProvider = Configuration.getEnvironmentDataProvider(); private static volatile Universe instance, emptyInstance; public static Universe getInstance() { Universe localInstance = instance; if(localInstance == null) { synchronized (Universe.class) { localInstance = instance; if(localInstance == null) { instance = localInstance = new Universe(); instance.populate(); } } } return localInstance; } public static Universe getEmptyInstance() { Universe localEmptyInstance = emptyInstance; if(localEmptyInstance == null) { synchronized (Universe.class) { localEmptyInstance = emptyInstance; if(localEmptyInstance == null) { emptyInstance = localEmptyInstance = new Universe(); } } } return localEmptyInstance; } public final static CelestialObject galacticCenter = new Region("Galactic center", new Coordinates(new BigDecimal(0.0),new BigDecimal(0.0),new BigDecimal(0.0)), new SensorSignalResponseProfile(1000.0, 1000.0, 1000.0, 1000.0, 1000.0), 10.0 * Unit.Pc.value()); public Universe() { super(); } public List<CelestialObject> getCelelestialObjects() { return universeLocationDataProvider.getLocationsByCategory(CelestialObject.category()); } public void addSpacecraft(Spacecraft spacecraft, Coordinates coordinates) { universeSpacecraftLocationDataProvider.addSpacecraft(spacecraft, coordinates); } public void updateSpacecraftLocation(String spacecraftIdent, Coordinates coordinates) { universeSpacecraftLocationDataProvider.updateSpacecraftLocation(spacecraftIdent, coordinates); } public void updateSpacecraftLocation(String spacecraftIdent, Location location) { universeSpacecraftLocationDataProvider.updateSpacecraftLocation(spacecraftIdent, location.getCoordinates()); } public Coordinates getSpacecraftLocation(String spacecraftIdent) { return universeSpacecraftLocationDataProvider.getSpacecraftLocation(spacecraftIdent); } public void setupSimpleUniverse() { System.out.println("Adding "); Star sol = new Star("Sol", Star.G_CLASS_STAR, new Coordinates( new BigDecimal(8*Unit.kPc.value()), new BigDecimal(0), new BigDecimal(100*Unit.Ly.value())), SensorSignalResponseLibrary.getStandardSignalResponseProfile(Star.G_CLASS_STAR)); addLocation(sol); Star alphaCenturi = new Star("Alpha centuri", Star.G_CLASS_STAR, new Coordinates( new BigDecimal(8*Unit.kPc.value() + 2.98*Unit.Ly.value()), new BigDecimal(2.83* Unit.Ly.value()), new BigDecimal(101.34*Unit.Ly.value())), SensorSignalResponseLibrary.getStandardSignalResponseProfile(Star.M_CLASS_STAR)); addLocation(alphaCenturi); //Setup subspace beacons //Above Sol north pole, 1e8 Km addLocation(new SubspaceBeacon("SolBeacon", new Coordinates(new BigDecimal(0.0),new BigDecimal(0.0),new BigDecimal(1*Unit.AU.value())), sol, SensorSignalResponseLibrary.getStandardSignalResponseProfile(SensorSignalResponseLibrary.SUBSPACE_BEACON))); addLocation(new SubspaceBeacon("ACBeacon", new Coordinates(new BigDecimal(0.0),new BigDecimal(0.0),new BigDecimal(1*Unit.AU.value())), alphaCenturi, SensorSignalResponseLibrary.getStandardSignalResponseProfile(SensorSignalResponseLibrary.SUBSPACE_BEACON))); } public UniverseLocationDataProvider getDataProvider() { return universeLocationDataProvider; } public void setDataProvider(UniverseLocationDataProvider dataProvider) { this.universeLocationDataProvider = dataProvider; } public List<CelestialObject> getLocationsByType(TypeInfo type) { return universeLocationDataProvider.getLocationsByType(type); } public int addLocation(CelestialObject location) { return universeLocationDataProvider.addLocation(location); } public CelestialObject getLocationById(String locationID) { return universeLocationDataProvider.getLocationById(locationID); } public CelestialObject getLocationByName(String locationProperName) { return universeLocationDataProvider.getLocationByName(locationProperName); } public long getUniversalTime() { return System.currentTimeMillis(); } public double[] moveSpacecraft() { double[] thrust = new double[]{}; //for(Spacecraft spacecraft : spacecraftInUniverse.values()) { //thrust = spacecraft.getThrust(); //} return thrust; } @Override public void tick() { List<Spacecraft> col = universeSpacecraftLocationDataProvider.getSpacecraft() .entrySet().stream() .map(x -> x.getValue()).collect(Collectors.toList()); col.stream().forEach(Spacecraft::tick); //Move the spacecraft for(Spacecraft spacecraft : universeSpacecraftLocationDataProvider.getSpacecraft().values()) { spacecraft.tick(); Coordinates currentLocation = universeSpacecraftLocationDataProvider.getSpacecraftLocation(spacecraft.getIdent()); double[] currentVelocity = universeSpacecraftLocationDataProvider.getSpacecraftVelocity(spacecraft.getIdent()); double[] dV = new double[]{0.0, 0.0, 0.0}; List<SpacecraftBusComponent> components = spacecraft.getSpacecraftBus().findComponentByType(ThrustingEngine.type()); for(SpacecraftBusComponent component : components) { double[] thrust = ((ThrustingEngine) component).getThrust(currentVelocity); dV[0] += thrust[0] / spacecraft.getMass() * 1 * Unit.s.value(); dV[1] += thrust[1] / spacecraft.getMass() * 1 * Unit.s.value(); dV[2] += thrust[2] / spacecraft.getMass() * 1 * Unit.s.value(); }; double[] newVelocity = new double[]{ currentVelocity[0] + dV[0],currentVelocity[1] + dV[1],currentVelocity[2] + dV[2] }; double[] translation = new double[]{ currentVelocity[0] * 1 * Unit.s.value(),currentVelocity[1] * 1 * Unit.s.value(),currentVelocity[2] * 1 * Unit.s.value() }; currentLocation.addDistance(new BigDecimal[]{ new BigDecimal(translation[0]), new BigDecimal(translation[1]), new BigDecimal(translation[2]) }); universeSpacecraftLocationDataProvider.updateSpacecraftLocation(spacecraft.getIdent(), currentLocation); universeSpacecraftLocationDataProvider.updateSpacecraftVelocity(spacecraft.getIdent(), newVelocity); System.out.println(currentLocation); } } //Delegate methods @Override public List<CelestialObject> getLocationsByCategory(TypeInfo category) { return universeLocationDataProvider.getLocationsByCategory(category); } @Override public List<CelestialObject> getLocationsCloserThan(Coordinates coordinates, BigDecimal distance) { return universeLocationDataProvider.getLocationsCloserThan(coordinates, distance); } @Override public List<CelestialObject> getLocationsByTypeCloserThan(TypeInfo type, Coordinates coordinates, BigDecimal distance) { return universeLocationDataProvider.getLocationsByTypeCloserThan(type, coordinates, distance); } @Override public double getSignalPropagationSpeed(SensorProfile sensorProfile) { return universeLocationDataProvider.getSignalPropagationSpeed(sensorProfile); } @Override public void populate() { universeLocationDataProvider.populate(); } @Override public Map<String, Spacecraft> getSpacecraft() { return universeSpacecraftLocationDataProvider.getSpacecraft(); } @Override public double[] getSpacecraftVelocity(String spacecraftIdent) { return universeSpacecraftLocationDataProvider.getSpacecraftVelocity(spacecraftIdent); } @Override public void updateSpacecraftVelocity(String spacecraftIdent, double[] velocity) { universeSpacecraftLocationDataProvider.updateSpacecraftVelocity(spacecraftIdent, velocity); } @Override public BigDecimal getDistanceBetweenTwoSpacecraft(String spacecraftIdent1, String spacecraftIdent2, Unit unit) { return universeSpacecraftLocationDataProvider.getDistanceBetweenTwoSpacecraft(spacecraftIdent1, spacecraftIdent2, unit); } @Override public Map<String, Coordinates> getSpacecraftWithinRangeOfLocation(Location location, BigDecimal range) { return universeSpacecraftLocationDataProvider.getSpacecraftWithinRangeOfLocation(location, range); } @Override public EnvironmentData getEnvironmentData(Coordinates coordinates) { return universeEnvironmentDataProvider.getEnvironmentData(coordinates); } @Override public double getSubspaceNoise(Coordinates coordinates) { return universeEnvironmentDataProvider.getSubspaceNoise(coordinates); } }
mit
asmodeirus/BackOffice
src/main/java/app/fw/confluence/client/softwareleaf/confluence/rest/util/Pair.java
359
package app.fw.confluence.client.softwareleaf.confluence.rest.util; /** * An immutable tuple structure, that can hold two * different types. * * @author Jonathon Hope * @since 7/07/2015 */ public class Pair<U, V> { public final U p1; public final V p2; public Pair( U p1, V p2 ) { this.p1 = p1; this.p2 = p2; } }
mit
YouCruit/billogram-v2-api-java-lib
src/main/java/com/youcruit/billogram/exception/ApiException.java
1022
package com.youcruit.billogram.exception; import java.io.IOException; import com.youcruit.billogram.objects.response.error.ApiError; public class ApiException extends IOException { private static final long serialVersionUID = -744741081235948125L; private final ApiError error; public ApiException(ApiError error) { super(getString(error)); this.error = error; } private static String getString(ApiError error) { final StringBuilder sb = new StringBuilder(); sb.append(error.getStatus().name()).append('(').append(error.getStatus().httpStatus).append(") ").append(error.getData().getMessage()); final String fieldName = error.getData().getField(); if (fieldName != null && !fieldName.trim().isEmpty()) { sb.append(" for field: '").append(fieldName). append("' and path: '").append(error.getData().getFieldPath()).append("'"); } return sb.toString(); } public ApiError getError() { return error; } }
mit
IntoRobot/react-native-imlink
android/src/main/java/com/molmc/rnimlink/esptouch/protocol/DataCode.java
2440
package com.molmc.rnimlink.esptouch.protocol; import com.molmc.rnimlink.esptouch.task.ICodeData; import com.molmc.rnimlink.esptouch.util.ByteUtil; import com.molmc.rnimlink.esptouch.util.CRC8; /** * one data format:(data code should have 2 to 65 data) * * control byte high 4 bits low 4 bits * 1st 9bits: 0x0 crc(high) data(high) * 2nd 9bits: 0x1 sequence header * 3rd 9bits: 0x0 crc(low) data(low) * * sequence header: 0,1,2,... * * @author afunx * */ public class DataCode implements ICodeData { public static final int DATA_CODE_LEN = 6; private static final int INDEX_MAX = 127; private final byte mSeqHeader; private final byte mDataHigh; private final byte mDataLow; // the crc here means the crc of the data and sequence header be transformed // it is calculated by index and data to be transformed private final byte mCrcHigh; private final byte mCrcLow; /** * Constructor of DataCode * @param u8 the character to be transformed * @param index the index of the char */ public DataCode(char u8, int index) { if (index > INDEX_MAX) { throw new RuntimeException("index > INDEX_MAX"); } byte[] dataBytes = ByteUtil.splitUint8To2bytes(u8); mDataHigh = dataBytes[0]; mDataLow = dataBytes[1]; CRC8 crc8 = new CRC8(); crc8.update(ByteUtil.convertUint8toByte(u8)); crc8.update(index); byte[] crcBytes = ByteUtil.splitUint8To2bytes((char) crc8.getValue()); mCrcHigh = crcBytes[0]; mCrcLow = crcBytes[1]; mSeqHeader = (byte) index; } @Override public byte[] getBytes() { byte[] dataBytes = new byte[DATA_CODE_LEN]; dataBytes[0] = 0x00; dataBytes[1] = ByteUtil.combine2bytesToOne(mCrcHigh,mDataHigh); dataBytes[2] = 0x01; dataBytes[3] = mSeqHeader; dataBytes[4] = 0x00; dataBytes[5] = ByteUtil.combine2bytesToOne(mCrcLow, mDataLow); return dataBytes; } @Override public String toString() { StringBuilder sb = new StringBuilder(); byte[] dataBytes = getBytes(); for (int i = 0; i < DATA_CODE_LEN; i++) { String hexString = ByteUtil.convertByte2HexString(dataBytes[i]); sb.append("0x"); if (hexString.length() == 1) { sb.append("0"); } sb.append(hexString).append(" "); } return sb.toString(); } @Override public char[] getU8s() { throw new RuntimeException("DataCode don't support getU8s()"); } }
mit
mmithril/XChange
xchange-cointrader/src/test/java/org/knowm/xchange/cointrader/service/CointraderDigestTest.java
1208
package org.knowm.xchange.cointrader.service; import static org.junit.Assert.assertEquals; import org.junit.Test; public class CointraderDigestTest { private final CointraderDigest hmac = new CointraderDigest("ks73GPO1qVPhIlFYeaCauiKwRMROpoL0DhwI7d3NcpNM"); @Test public void testDigest1() throws Exception { test("{\"t\":\"Mon Apr 27 17:43:32 CEST 2015\"}", "945de89251b0781ada32d2a389f41684436482b529d45b3ee270355f978020f1"); } @Test public void testDigest2() throws Exception { test("{\"t\":\"Mon Apr 27 17:51:14 CEST 2015\"}", "801f3410bed1a7823cd135e74318be946138bb920889fb9c234d9ea3e38903ac"); } /* * @Test public void testDigest3a() throws Exception { test("{\"t\":\"Tue Apr 28 06:35:14 CEST 2015\",\"total_quantity\":0.03,\"price\":2000}", * "19a3ba7a48a604d56007a1fb3975a4010e2b238ce0285e96adeb60d10dd79dc2"); } */ @Test public void testDigest3b() throws Exception { test("{\"t\":\"Tue Apr 28 06:35:14 CEST 2015\",\"total_quantity\":\"0.03\",\"price\":\"2000\"}", "19a3ba7a48a604d56007a1fb3975a4010e2b238ce0285e96adeb60d10dd79dc2"); } private void test(String data, String expected) { assertEquals(expected, hmac.digest(data)); } }
mit
Azure/azure-sdk-for-java
sdk/streamanalytics/azure-resourcemanager-streamanalytics/src/main/java/com/azure/resourcemanager/streamanalytics/models/AzureSqlDatabaseOutputDataSource.java
1932
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.streamanalytics.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.streamanalytics.fluent.models.AzureSqlDatabaseOutputDataSourceProperties; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** Describes an Azure SQL database output data source. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonTypeName("Microsoft.Sql/Server/Database") @Fluent public final class AzureSqlDatabaseOutputDataSource extends OutputDataSource { @JsonIgnore private final ClientLogger logger = new ClientLogger(AzureSqlDatabaseOutputDataSource.class); /* * The properties that are associated with an Azure SQL database output. * Required on PUT (CreateOrReplace) requests. */ @JsonProperty(value = "properties") private AzureSqlDatabaseOutputDataSourceProperties innerProperties; /** * Get the innerProperties property: The properties that are associated with an Azure SQL database output. Required * on PUT (CreateOrReplace) requests. * * @return the innerProperties value. */ private AzureSqlDatabaseOutputDataSourceProperties innerProperties() { return this.innerProperties; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ @Override public void validate() { super.validate(); if (innerProperties() != null) { innerProperties().validate(); } } }
mit
daemon/magma
src/main/net/rocketeer/magma/arena/BoundingBoxReader.java
1227
package net.rocketeer.magma.arena; import net.rocketeer.magma.MagmaPlugin; import net.rocketeer.magma.admin.BoundingBox; import org.bukkit.block.Block; import java.io.*; import java.util.zip.GZIPInputStream; public class BoundingBoxReader { private final BoundingBox _bbox; private final DataInputStream _in; private BoundingBox.Iterator _iterator; public BoundingBoxReader(BoundingBox bbox, String fileName) throws IOException { this._bbox = bbox; this._in = new DataInputStream(new GZIPInputStream(new FileInputStream(new File(MagmaPlugin.instance.getDataFolder(), fileName)))); this._iterator = this._bbox.iterator(); } public int readIntoWorld(int nBlocks) throws IOException { if (!this._iterator.hasNext()) return 0; int read = 0; while (this._iterator.hasNext() && read < nBlocks) { int typeId = this._in.readInt(); int dv = this._in.readInt(); Block block = this._iterator.next().getBlock(); block.setTypeId(typeId); block.setData((byte) dv); ++read; } return read; } public void reset() { this._iterator = this._bbox.iterator(); try { this._in.reset(); } catch (IOException ignored) {} } }
mit
AlphaModder/SpongeAPI
src/main/java/org/spongepowered/api/plugin/PluginContainer.java
4813
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.plugin; import com.google.common.collect.ImmutableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongepowered.api.Sponge; import org.spongepowered.api.asset.Asset; import org.spongepowered.api.asset.AssetManager; import java.nio.file.Path; import java.util.List; import java.util.Optional; /** * A wrapper around a class marked with an {@link Plugin} annotation to retrieve * information from the annotation for easier use. */ public interface PluginContainer { /** * Gets the qualified ID of the {@link Plugin} within this container. * * @return The plugin ID * @see Plugin#id() */ String getId(); /** * Gets the name of the {@link Plugin} within this container. * * @return The plugin name, or {@link #getId()} if unknown * @see Plugin#name() */ default String getName() { return getId(); } /** * Gets the version of the {@link Plugin} within this container. * * @return The plugin version, or {@link Optional#empty()} if unknown * @see Plugin#version() */ default Optional<String> getVersion() { return Optional.empty(); } /** * Gets the description of the {@link Plugin} within this container. * * @return The plugin description, or {@link Optional#empty()} if unknown * @see Plugin#description() */ default Optional<String> getDescription() { return Optional.empty(); } /** * Gets the url or website of the {@link Plugin} within this container. * * @return The plugin url, or {@link Optional#empty()} if unknown * @see Plugin#url() */ default Optional<String> getUrl() { return Optional.empty(); } /** * Gets the Minecraft version the {@link Plugin} within this container was * designed for. * * <p>Note: This will be empty for most plugins because SpongeAPI plugins * are usually designed for a specific API version and not for a specific * Minecraft version.</p> * * @return The Minecraft version, or {@link Optional#empty()} if unknown */ default Optional<String> getMinecraftVersion() { return Optional.empty(); } /** * Gets the authors of the {@link Plugin} within this container. * * @return The plugin authors, or empty if unknown * @see Plugin#authors() */ default List<String> getAuthors() { return ImmutableList.of(); } /** * Retrieves the {@link Asset} of the specified name from the * {@link AssetManager} for this {@link Plugin}. * * @param name Name of asset * @return Asset if present, empty otherwise */ default Optional<Asset> getAsset(String name) { return Sponge.getAssetManager().getAsset(this, name); } /** * Returns the source the plugin was loaded from. * * @return The source the plugin was loaded from or {@link Optional#empty()} * if unknown */ default Optional<Path> getSource() { return Optional.empty(); } /** * Returns the created instance of {@link Plugin} if it is available. * * @return The instance if available */ default Optional<?> getInstance() { return Optional.empty(); } /** * Returns the assigned logger to this {@link Plugin}. * * @return The assigned logger */ default Logger getLogger() { return LoggerFactory.getLogger(getId()); } }
mit
kubac65/CIT_AOT1
src/main/java/aot1/persistence/models/HostReport.java
3239
package aot1.persistence.models; import org.bson.Document; import java.util.Date; /** * Created by Jakub Potocki on 27/04/17. */ public class HostReport { /** * Hostname */ private String host; /** * Count of sent packages */ private long packetsSent; /** * Count of received packages */ private long packetsReceived; /** * Count of exchanged tcp packages */ private long tcpPackets; /** * Count of exchanged udp packages */ private long udpPackets; /** * Date of the report */ private Date reportDate; /** * Creates an instance of the HostReport * @param host Hostname * @param packetsSent Packets sent * @param packetsReceived Packets received * @param tcpPackets Tcp packets exchanged * @param udpPackets Udp packets exchanges * @param reportDate Report date */ public HostReport(String host, long packetsSent, long packetsReceived, long tcpPackets, long udpPackets, Date reportDate) { this.host = host; this.packetsSent = packetsSent; this.packetsReceived = packetsReceived; this.tcpPackets = tcpPackets; this.udpPackets = udpPackets; this.reportDate = reportDate; } /** * Gets hostname * @return hostname */ public String getHost() { return host; } /** * Gets packets sent * @return packets sent */ public long getPacketsSent() { return packetsSent; } /** * Gets packets received * @return packets received */ public long getPacketsReceived() { return packetsReceived; } /** * Gets tcp packets * @return tcp packets */ public long getTcpPackets() { return tcpPackets; } /** * Gets udp packets * @return udp packets */ public long getUdpPackets() { return udpPackets; } /** * Gets report date * @return report date */ public Date getReportDate() { return reportDate; } /** * Maps report entity to mongo document * @return Mongo document */ public Document toDocument() { Document doc = new Document() .append("host", this.getHost()) .append("sentPackets", this.getPacketsSent()) .append("receivedPackets", this.getPacketsReceived()) .append("tcpPackets", this.getTcpPackets()) .append("udpPackets", this.getUdpPackets()) .append("date", this.getReportDate()); return doc; } /** * Maps mongo document to report * @param doc Mongo document * @return HostReport instance */ public static HostReport fromDocument(Document doc){ HostReport report = new HostReport( doc.getString("host"), doc.getLong("sentPackets"), doc.getLong("receivedPackets"), doc.getLong("tcpPackets"), doc.getLong("udpPackets"), doc.getDate("date") ); return report; } }
mit
GetYourLocation/GYL-Client
app/src/androidTest/java/com/getyourlocation/app/client/ExampleInstrumentedTest.java
768
package com.getyourlocation.app.client; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.getyourlocation.app.gyl_client", appContext.getPackageName()); } }
mit
joansmith/XChange
xchange-bleutrade/src/test/java/com/xeiam/xchange/bleutrade/service/polling/BleutradeMarketDataServiceTest.java
16213
package com.xeiam.xchange.bleutrade.service.polling; import com.xeiam.xchange.ExchangeFactory; import com.xeiam.xchange.bleutrade.BleutradeAssert; import com.xeiam.xchange.bleutrade.BleutradeAuthenticated; import com.xeiam.xchange.bleutrade.BleutradeExchange; import com.xeiam.xchange.bleutrade.dto.marketdata.BleutradeCurrenciesReturn; import com.xeiam.xchange.bleutrade.dto.marketdata.BleutradeCurrency; import com.xeiam.xchange.bleutrade.dto.marketdata.BleutradeMarket; import com.xeiam.xchange.bleutrade.dto.marketdata.BleutradeMarketHistoryReturn; import com.xeiam.xchange.bleutrade.dto.marketdata.BleutradeMarketsReturn; import com.xeiam.xchange.bleutrade.dto.marketdata.BleutradeOrderBookReturn; import com.xeiam.xchange.bleutrade.dto.marketdata.BleutradeTicker; import com.xeiam.xchange.bleutrade.dto.marketdata.BleutradeTickerReturn; import com.xeiam.xchange.bleutrade.dto.marketdata.BleutradeTrade; import com.xeiam.xchange.currency.CurrencyPair; import com.xeiam.xchange.dto.marketdata.OrderBook; import com.xeiam.xchange.dto.marketdata.Ticker; import com.xeiam.xchange.dto.marketdata.Trade; import com.xeiam.xchange.dto.marketdata.Trades; import com.xeiam.xchange.dto.trade.LimitOrder; import com.xeiam.xchange.exceptions.ExchangeException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.fail; import static org.powermock.api.mockito.PowerMockito.mock; @RunWith(PowerMockRunner.class) public class BleutradeMarketDataServiceTest extends BleutradeServiceTestSupport { private BleutradeMarketDataService marketDataService; private static final Ticker TICKER = new Ticker.Builder() .currencyPair(BLEU_BTC_CP).last(new BigDecimal("0.00101977")).bid(new BigDecimal("0.00100000")) .ask(new BigDecimal("0.00101977")).high(new BigDecimal("0.00105000")).low(new BigDecimal("0.00086000")) .vwap(new BigDecimal("0.00103455")).volume(new BigDecimal("2450.97496015")).timestamp(new Date(1406632770000L)).build(); @Before public void setUp() { BleutradeExchange exchange = (BleutradeExchange) ExchangeFactory.INSTANCE.createExchange(BleutradeExchange.class.getCanonicalName()); exchange.getExchangeSpecification().setUserName(SPECIFICATION_USERNAME); exchange.getExchangeSpecification().setApiKey(SPECIFICATION_API_KEY); exchange.getExchangeSpecification().setSecretKey(SPECIFICATION_SECRET_KEY); marketDataService = new BleutradeMarketDataService(exchange); } @Test public void constructor() { assertThat(Whitebox.getInternalState(marketDataService, "apiKey")).isEqualTo(SPECIFICATION_API_KEY); } @Test public void shouldGetTicker() throws IOException { // given BleutradeTickerReturn tickerReturn = new BleutradeTickerReturn(); tickerReturn.setSuccess(true); tickerReturn.setMessage("test message"); tickerReturn.setResult(expectedBleutradeTicker()); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeTicker("BLEU_BTC")).thenReturn(tickerReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when Ticker ticker = marketDataService.getTicker(BLEU_BTC_CP); // then assertThat(ticker.toString()).isEqualTo(EXPECTED_BLEUTRADE_TICKER_STR); BleutradeAssert.assertEquals(ticker, TICKER); } @Test(expected = ExchangeException.class) public void shouldFailOnUnsuccesfulGetTicker() throws IOException { // given BleutradeTickerReturn tickerReturn = new BleutradeTickerReturn(); tickerReturn.setSuccess(false); tickerReturn.setMessage("test message"); tickerReturn.setResult(expectedBleutradeTicker()); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeTicker("BLEU_BTC")).thenReturn(tickerReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when marketDataService.getTicker(BLEU_BTC_CP); // then fail("BleutradeMarketDataService should throw ExchangeException when ticker request was unsuccessful"); } @Test public void shouldGetOrderBook() throws IOException { // given BleutradeOrderBookReturn orderBookReturn1 = new BleutradeOrderBookReturn(); orderBookReturn1.setSuccess(true); orderBookReturn1.setMessage("test message"); orderBookReturn1.setResult( createBleutradeOrderBook(expectedBleutradeLevelBuys(), expectedBleutradeLevelSells())); BleutradeOrderBookReturn orderBookReturn2 = new BleutradeOrderBookReturn(); orderBookReturn2.setSuccess(true); orderBookReturn2.setMessage(""); orderBookReturn2.setResult(createBleutradeOrderBook(Collections.EMPTY_LIST, Collections.EMPTY_LIST)); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeOrderBook("BTC_AUD", "ALL", 30)).thenReturn(orderBookReturn1); PowerMockito.when(bleutrade.getBleutradeOrderBook("BLEU_BTC", "ALL", 50)).thenReturn(orderBookReturn2); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); final LimitOrder[] expectedAsks = expectedAsks(); final LimitOrder[] expectedBids = expectedBids(); // when OrderBook orderBook1 = marketDataService.getOrderBook(CurrencyPair.BTC_AUD, 30); OrderBook orderBook2 = marketDataService.getOrderBook(BLEU_BTC_CP, "test parameter"); // then List<LimitOrder> asks = orderBook1.getAsks(); assertThat(asks).hasSize(4); for (int i=0; i < asks.size(); i++) { BleutradeAssert.assertEquals(asks.get(i), expectedAsks[i]); } List<LimitOrder> bids = orderBook1.getBids(); assertThat(bids).hasSize(2); for (int i=0; i < bids.size(); i++) { BleutradeAssert.assertEquals(bids.get(i), expectedBids[i]); } assertThat(orderBook2.getAsks()).isEmpty(); assertThat(orderBook2.getBids()).isEmpty(); } @Test(expected = ExchangeException.class) public void shouldFailOnUnsuccessfulGetOrderBook() throws IOException { // given BleutradeOrderBookReturn orderBookReturn = new BleutradeOrderBookReturn(); orderBookReturn.setSuccess(false); orderBookReturn.setMessage("test message"); orderBookReturn.setResult(createBleutradeOrderBook( expectedBleutradeLevelBuys(), expectedBleutradeLevelSells())); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeOrderBook("BLEU_BTC", "ALL", 50)).thenReturn(orderBookReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when marketDataService.getOrderBook(BLEU_BTC_CP); // then fail("BleutradeMarketDataService should throw ExchangeException when order book request was unsuccessful"); } @Test public void shouldGetTrades() throws IOException { // given final List<BleutradeTrade> expectedBleutradeTrades = expectedBleutradeTrades(); BleutradeMarketHistoryReturn marketHistoryReturn1 = new BleutradeMarketHistoryReturn(); marketHistoryReturn1.setSuccess(true); marketHistoryReturn1.setMessage("test message"); marketHistoryReturn1.setResult(expectedBleutradeTrades); BleutradeMarketHistoryReturn marketHistoryReturn2 = new BleutradeMarketHistoryReturn(); marketHistoryReturn2.setSuccess(true); marketHistoryReturn2.setMessage(""); marketHistoryReturn2.setResult(Collections.EMPTY_LIST); BleutradeMarketHistoryReturn marketHistoryReturn3 = new BleutradeMarketHistoryReturn(); marketHistoryReturn3.setSuccess(true); marketHistoryReturn3.setMessage("test message"); marketHistoryReturn3.setResult(Arrays.asList(expectedBleutradeTrades.get(0))); BleutradeMarketHistoryReturn marketHistoryReturn4 = new BleutradeMarketHistoryReturn(); marketHistoryReturn4.setSuccess(true); marketHistoryReturn4.setMessage("test message"); marketHistoryReturn4.setResult(Arrays.asList(expectedBleutradeTrades.get(1))); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeMarketHistory("BTC_AUD", 30)).thenReturn(marketHistoryReturn1); PowerMockito.when(bleutrade.getBleutradeMarketHistory("BTC_AUD", 50)).thenReturn(marketHistoryReturn2); PowerMockito.when(bleutrade.getBleutradeMarketHistory("BTC_AUD", 1)).thenReturn(marketHistoryReturn3); PowerMockito.when(bleutrade.getBleutradeMarketHistory("BTC_AUD", 200)).thenReturn(marketHistoryReturn4); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); final Trade[] expectedTrades = expectedTrades(); // when Trades trades1 = marketDataService.getTrades(CurrencyPair.BTC_AUD, 30); Trades trades2 = marketDataService.getTrades(CurrencyPair.BTC_AUD, "test parameter"); Trades trades3 = marketDataService.getTrades(CurrencyPair.BTC_AUD, 0); Trades trades4 = marketDataService.getTrades(CurrencyPair.BTC_AUD, 201); // then List<Trade> tradeList = trades1.getTrades(); assertThat(tradeList).hasSize(2); for (int i=0; i<tradeList.size(); i++) { BleutradeAssert.assertEquals(tradeList.get(i), expectedTrades[i]); } assertThat(trades2.getTrades()).isEmpty(); assertThat(trades3.getTrades()).hasSize(1); BleutradeAssert.assertEquals(trades3.getTrades().get(0), expectedTrades[0]); assertThat(trades4.getTrades()).hasSize(1); BleutradeAssert.assertEquals(trades4.getTrades().get(0), expectedTrades[1]); } @Test(expected = ExchangeException.class) public void shouldFailOnUnsuccessfulGetTrades() throws IOException { // given BleutradeMarketHistoryReturn marketHistoryReturn = new BleutradeMarketHistoryReturn(); marketHistoryReturn.setSuccess(false); marketHistoryReturn.setMessage("test message"); marketHistoryReturn.setResult(expectedBleutradeTrades()); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeMarketHistory("BLEU_BTC", 50)).thenReturn(marketHistoryReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when marketDataService.getTrades(BLEU_BTC_CP); // then fail("BleutradeMarketDataService should throw ExchangeException when trades request was unsuccessful"); } @Test public void shouldGetTickers() throws IOException { // given final List<BleutradeTicker> expectedBleutradeTickers = expectedBleutradeTickers(); final String[] expectedBleutradeTickersStr = expectedBleutradeTickersStr(); BleutradeTickerReturn tickerReturn = new BleutradeTickerReturn(); tickerReturn.setSuccess(true); tickerReturn.setMessage("test message"); tickerReturn.setResult(expectedBleutradeTickers); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeTickers()).thenReturn(tickerReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when List<BleutradeTicker> tickers = marketDataService.getBleutradeTickers(); // then assertThat(tickers).hasSize(2); for (int i=0; i<tickers.size(); i++) { BleutradeAssert.assertEquals(tickers.get(i), expectedBleutradeTickers.get(i)); assertThat(tickers.get(i).toString()).isEqualTo(expectedBleutradeTickersStr[i]); } } @Test(expected = ExchangeException.class) public void shouldFailOnUnsuccesfulGetTickers() throws IOException { // given BleutradeTickerReturn tickerReturn = new BleutradeTickerReturn(); tickerReturn.setSuccess(false); tickerReturn.setMessage("test message"); tickerReturn.setResult(expectedBleutradeTickers()); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeTickers()).thenReturn(tickerReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when marketDataService.getBleutradeTickers(); // then fail("BleutradeMarketDataService should throw ExchangeException when tickers request was unsuccessful"); } @Test public void shouldGetCurrencies() throws IOException { // given final List<BleutradeCurrency> expectedBleutradeCurrencies = expectedBleutradeCurrencies(); final String[] expectedBleutradeCurrenciesStr = expectedBleutradeCurrenciesStr(); BleutradeCurrenciesReturn currenciesReturn = new BleutradeCurrenciesReturn(); currenciesReturn.setSuccess(true); currenciesReturn.setMessage("test message"); currenciesReturn.setResult(expectedBleutradeCurrencies); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeCurrencies()).thenReturn(currenciesReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when List<BleutradeCurrency> currencies = marketDataService.getBleutradeCurrencies(); // then assertThat(currencies).hasSize(2); for (int i=0; i<currencies.size(); i++) { BleutradeAssert.assertEquals(currencies.get(i), expectedBleutradeCurrencies.get(i)); assertThat(currencies.get(i).toString()).isEqualTo(expectedBleutradeCurrenciesStr[i]); } } @Test(expected = ExchangeException.class) public void shouldFailOnUnsuccesfulGetCurrencies() throws IOException { // given BleutradeCurrenciesReturn currenciesReturn = new BleutradeCurrenciesReturn(); currenciesReturn.setSuccess(false); currenciesReturn.setMessage("test message"); currenciesReturn.setResult(expectedBleutradeCurrencies()); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeCurrencies()).thenReturn(currenciesReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when marketDataService.getBleutradeCurrencies(); // then fail("BleutradeMarketDataService should throw ExchangeException when currencies request was unsuccessful"); } @Test public void shouldGetMarkets() throws IOException { // given final List<BleutradeMarket> expectedBleutradeMarkets = expectedBleutradeMarkets(); final String[] expectedBleutradeMarketsStr = expectedBleutradeMarketsStr(); BleutradeMarketsReturn marketsReturn = new BleutradeMarketsReturn(); marketsReturn.setSuccess(true); marketsReturn.setMessage("test message"); marketsReturn.setResult(expectedBleutradeMarkets); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeMarkets()).thenReturn(marketsReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when List<BleutradeMarket> markets = marketDataService.getBleutradeMarkets(); // then assertThat(markets).hasSize(2); for (int i=0; i<markets.size(); i++) { BleutradeAssert.assertEquals(markets.get(i), expectedBleutradeMarkets.get(i)); assertThat(markets.get(i).toString()).isEqualTo(expectedBleutradeMarketsStr[i]); } } @Test(expected = ExchangeException.class) public void shouldFailOnUnsuccesfulGetMarkets() throws IOException { // given BleutradeMarketsReturn marketsReturn = new BleutradeMarketsReturn(); marketsReturn.setSuccess(false); marketsReturn.setMessage("test message"); marketsReturn.setResult(expectedBleutradeMarkets()); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeMarkets()).thenReturn(marketsReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when marketDataService.getBleutradeMarkets(); // then fail("BleutradeMarketDataService should throw ExchangeException when markets request was unsuccessful"); } }
mit
mfinley3/eBayBarcodeScanner-AndroidVersion
app/src/main/java/cs436project/ebaybarcodescanner_androidversion/NoScanFragment.java
454
package cs436project.ebaybarcodescanner_androidversion; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class NoScanFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_no_scan, container, false); } }
mit
HenrikSamuelsson/Yakindu_Explorations
YoutubeTutorials/Part8/src-gen/org/yakindu/scr/ITimer.java
974
package org.yakindu.scr; /** * Interface a timer has to implement. Use to implement your own timer * service. * */ public interface ITimer { /** * Starts the timing for a given time event id. * * @param callback * : The target callback where the time event has to be raised. * * @param eventID * : The eventID the timer should use if timed out. * * @param time * : Time in milliseconds after the given time event should be * triggered * * @param isPeriodic * : Set to true if the time event should be triggered periodically */ public void setTimer(ITimerCallback callback, int eventID, long time, boolean isPeriodic); /** * Unset a time event. * * @param callback * : The target callback for which the time event has to be unset. * * @param eventID * : The time event id. */ public void unsetTimer(ITimerCallback callback, int eventID); }
mit
timechild/tflRestClient
src/main/java/org/disruptiontables/rest/LineResource.java
1363
package org.disruptiontables.rest; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; import org.disruptiontables.dao.Branch; import org.disruptiontables.dao.Line; import org.disruptiontables.service.LineService; @Path("lines") public class LineResource { @GET @Produces(MediaType.APPLICATION_JSON) public List<Line> getAllLines(){ LineService ls = new LineService(); return ls.getAllLines(); } @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public Line getLine(@PathParam("id") int id){ LineService ls = new LineService(); return ls.getLine(id); } @GET @Path("/{id}/branches") @Produces(MediaType.APPLICATION_JSON) public List<Branch> getSortedLineBranches(@PathParam("id") int id, @Context UriInfo info){ String from = info.getQueryParameters().getFirst("from"); String to = info.getQueryParameters().getFirst("to"); System.out.println("to: "+to+" from: "+from); LineService ls = new LineService(); if(from==null || to==null) return ls.getAllLineBranches(id); else return ls.getSortedLineBranches(id, Integer.parseInt(from), Integer.parseInt(to)); } }
mit
deltacat/intro-java-prog-8e
src/chapter09/Calculator.java
847
package chapter09; public class Calculator { /** Main method */ public static void main(String[] args) { // Check number of strings passed if (args.length != 3) { System.out .println("Usage: java Calculator operand1 operator operand2"); System.exit(0); } // The result of the operation int result = 0; // Determine the operator switch (args[1].charAt(0)) { case '+': result = Integer.parseInt(args[0]) + Integer.parseInt(args[2]); break; case '-': result = Integer.parseInt(args[0]) - Integer.parseInt(args[2]); break; case '*': result = Integer.parseInt(args[0]) * Integer.parseInt(args[2]); break; case '/': result = Integer.parseInt(args[0]) / Integer.parseInt(args[2]); } // Display result System.out.println(args[0] + ' ' + args[1] + ' ' + args[2] + " = " + result); } }
mit
marcaddeo/MAMBot
Java/MAMBot/src/mamclient/Packets/NpcInfoPacket.java
945
package mamclient.Packets; import mamclient.MAMClient; import csocket.Packet; public class NpcInfoPacket implements IPacket { public int id; public short type; public short look; public short x; public short y; public String name; public NpcInfoPacket() { } public NpcInfoPacket(Packet packet) { this.parse(packet); } public NpcInfoPacket(MAMClient client, Packet packet) { this.execute(client, packet); } @Override public void execute(MAMClient client, Packet packet) { this.parse(packet); // TODO Add code to update the eventual NPC list that will be contained inside MAMClient } @Override public Packet pack() { return new Packet(0, 0); } @Override public void parse(Packet packet) { this.id = packet.getInt(0); this.type = packet.getShort(6); this.look = packet.getShort(8); this.x = packet.getShort(10); this.y = packet.getShort(12); this.name = packet.getString(14, 16); } }
mit
paperclipmonkey/Android-M10
app/src/main/java/uk/co/threeequals/notepad/NoteEdit.java
7973
/** * Michael 2015 * Main Activity for editing Notes */ package uk.co.threeequals.notepad; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class NoteEdit extends FragmentActivity implements TimePickerFragment.OnTimePickedListener { private EditText mBodyText; private LinearLayout mAlarmTimeout; private TextView mAlarmTimeoutText; private Calendar cal; private RadioGroup mTypeRadio; private Long mRowId; private NotesDbAdapter mDbHelper; // This is a handle so that we can call methods on our service private ScheduleClient scheduleClient; /** * On time picked event, converts hour and minutes values to milliseconds * milliseconds and sets a new value for the layout in the activity. * @param hour Hour value. * @param minute Minutes value. */ @Override public void onTimePicked(int hour, int minute) { cal = Calendar.getInstance(); // creates calendar cal.setTime(new Date()); // sets calendar time/date cal.set(Calendar.MINUTE, minute); cal.set(Calendar.HOUR_OF_DAY, hour); showTime(cal); } /** * Format and show time in view * @param cl Calendar time to show */ public void showTime(Calendar cl){ SimpleDateFormat format = new SimpleDateFormat("h:mm a", Locale.UK); mAlarmTimeoutText.setText(format.format(cl.getTime())); } /** * This is the onClick called from the XML to set a new notification */ public void onDateSelectedButtonClick(View v){ // Get the date from our datepicker // Create a new calendar set to the date chosen // we set the time to midnight (i.e. the first minute of that day) // Ask our service to set an alarm for that date, this activity talks to the client that talks to the service Log.d("Time", cal.getTimeInMillis() + ""); scheduleClient.setAlarmForNotification(cal); // Notify the user what they just did Toast.makeText(this, "Notification set", Toast.LENGTH_SHORT).show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDbHelper = new NotesDbAdapter(this); mDbHelper.open(); setContentView(R.layout.note_edit); mBodyText = (EditText) findViewById(R.id.body); mAlarmTimeout = (LinearLayout) findViewById(R.id.alarm); mAlarmTimeoutText = (TextView) findViewById(R.id.alarmText); mTypeRadio = (RadioGroup) findViewById(R.id.type); Button confirmButton = (Button) findViewById(R.id.confirm); mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID); if (mRowId == null) { Bundle extras = getIntent().getExtras(); mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID) : null; } mTypeRadio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){ @Override public void onCheckedChanged(RadioGroup radioGroup, int checkedId){ RadioButton checkedButton = (RadioButton) findViewById(checkedId); if(checkedButton.getText().toString().compareTo("urgent") == 0){ mAlarmTimeout.setVisibility(View.VISIBLE); } else { mAlarmTimeout.setVisibility(View.GONE); } } }); populateFields(); confirmButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { setResult(RESULT_OK); finish(); } }); scheduleClient = new ScheduleClient(this); scheduleClient.doBindService(); } /** * Using cursor populate data entry fields with data from Db row */ private void populateFields() { if (mRowId != null) { Cursor note = mDbHelper.fetchNote(mRowId); startManagingCursor(note);//Using deprecated as the other option is a lot more code and overly complicated mBodyText.setText(note.getString( note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY))); if(note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TYPE)).compareTo("normal") == 0){ mTypeRadio.check(R.id.radio_normal); } if(note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TYPE)).compareTo("urgent") == 0){ mTypeRadio.check(R.id.radio_urgent); } if(note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TYPE)).compareTo("important") == 0){ mTypeRadio.check(R.id.radio_important); } String time = note.getString( note.getColumnIndexOrThrow(NotesDbAdapter.KEY_ALARM)); if(time!= null && !time.equals("")) { cal = Calendar.getInstance(); // creates calendar cal.setTime(new Date((Long.parseLong(time)))); // sets calendar time/date //Update the TextView showTime(cal); } } else { mTypeRadio.check(R.id.radio_normal); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); saveState(); outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId); } @Override protected void onStop() { // When our activity is stopped ensure we also stop the connection to the service // this stops us leaking our activity into the system *bad* if(scheduleClient != null) scheduleClient.doUnbindService(); super.onStop(); } @Override protected void onPause() { super.onPause(); saveState(); } /** * Create a new date time picker dialog * @param v */ public void showTimePickerDialog(View v) { DialogFragment newFragment; if(cal != null){ int minutes = cal.get(Calendar.MINUTE); int hours = cal.get(Calendar.HOUR_OF_DAY); newFragment = TimePickerFragment.newInstance(0, hours, minutes); } else { newFragment = TimePickerFragment.newInstance(0, 11, 43); } newFragment.show(getSupportFragmentManager(), "timePicker"); } @Override protected void onResume() { super.onResume(); populateFields(); } /** * Save the activity state to the db */ private void saveState() { String body = mBodyText.getText().toString(); String type = ""; Date alarm = null; if(mTypeRadio.getCheckedRadioButtonId()!=-1){ int id= mTypeRadio.getCheckedRadioButtonId(); View radioButton = mTypeRadio.findViewById(id); int radioId = mTypeRadio.indexOfChild(radioButton); RadioButton btn = (RadioButton) mTypeRadio.getChildAt(radioId); type = (String) btn.getText(); } if(cal != null && type.equals("urgent")) { alarm = cal.getTime(); } if (mRowId == null) { long id = mDbHelper.createNote(body, type, alarm); if (id > 0) { mRowId = id; } } else { mDbHelper.updateNote(mRowId, body, type, alarm); } } }
mit
hsz/idea-vcswatch
src/mobi/hsz/idea/vcswatch/requests/GitWatchRequest.java
1795
package mobi.hsz.idea.vcswatch.requests; import com.intellij.execution.process.ProcessOutput; import com.intellij.openapi.vcs.AbstractVcs; import com.intellij.openapi.vfs.VirtualFile; import git4idea.config.GitVcsApplicationSettings; import mobi.hsz.idea.vcswatch.core.Commit; import org.jetbrains.annotations.NotNull; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GitWatchRequest extends VcsWatchRequest { private static final String TEMPLATE = "%h %an ## %ad ## %s"; private static final Pattern PATTERN = Pattern.compile("^(\\w+) (.*?) ## (\\d+) .*? ## (.*)$", Pattern.MULTILINE); public GitWatchRequest(@NotNull AbstractVcs vcs, @NotNull VirtualFile workingDirectory) { super(vcs, workingDirectory); } @NotNull @Override protected String getExecutable() { return GitVcsApplicationSettings.getInstance().getPathToGit(); } @Override public void run() { // Update information about ahead commits. If nothing is returned, repository has no remote. if (exec("remote", "update") == null) { return; } // Check logs. If nothing is returned, there are not commits to pull. ProcessOutput output = exec("log", "..@{u}", "--date=raw", "--pretty=format:" + TEMPLATE); if (output == null) { return; } // Parse logs. Matcher matcher = PATTERN.matcher(output.getStdout()); while (matcher.find()) { String id = matcher.group(1); String user = matcher.group(2); Date date = new Date(Long.valueOf(matcher.group(3)) * 1000); String message = matcher.group(4); addCommit(new Commit(id, user, date, message)); } } }
mit
rockysims/fortressplugin
src/main/java/me/newyith/fortress/bedrock/util/ManagedBedrock.java
2969
package me.newyith.fortress.bedrock.util; import me.newyith.fortress.util.Point; import org.bukkit.Material; import org.bukkit.World; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.bukkit.material.Button; import org.bukkit.material.PressureSensor; public class ManagedBedrock extends ManagedBedrockBase { private static class Model { private Point point; private boolean isConverted; private BlockRevertData revertData; @JsonCreator public Model(@JsonProperty("point") Point point, @JsonProperty("isConverted") boolean isConverted, @JsonProperty("revertData") BlockRevertData revertData) { this.point = point; this.isConverted = isConverted; this.revertData = revertData; //rebuild transient fields } } private Model model = null; @JsonCreator public ManagedBedrock(@JsonProperty("model") Model model) { this.model = model; } public ManagedBedrock(World world, Point p) { boolean isConverted = false; BlockRevertData revertData = new BlockRevertData(world, p); model = new Model(p, isConverted, revertData); } //----------------------------------------------------------------------- public void convert(World world) { model.isConverted = true; updateConverted(world); } public void revert(World world) { model.isConverted = false; updateConverted(world); } public boolean isConverted() { return model.isConverted; } public Material getMaterial(Point p) { return model.revertData.getMaterial(); } private void updateConverted(World world) { boolean isBedrock = model.point.is(Material.BEDROCK, world); boolean isConverted = model.isConverted; if (isConverted && !isBedrock) { //convert boolean showParticlesInstead; switch (model.revertData.getMaterial()) { case WOOD_BUTTON: //buttons can get stuck in pressed state case STONE_BUTTON: Button button = (Button) model.point.getBlock(world).getState().getData(); showParticlesInstead = button.isPowered(); break; case DETECTOR_RAIL: //rail with pressure plate can get stuck in pressed state case WOOD_PLATE: //pressure plates can get stuck in pressed state case STONE_PLATE: PressureSensor pressureSensor = (PressureSensor) model.point.getBlock(world).getState().getData(); showParticlesInstead = pressureSensor.isPressed(); break; case IRON_PLATE: //weighted pressure plates can get stuck in pressed state case GOLD_PLATE: //can't cast to PressureSensor so just check if it's powered instead showParticlesInstead = model.point.getBlock(world).getBlockPower() > 0; break; default: showParticlesInstead = false; } if (showParticlesInstead) { showParticles(world, model.point); } else { model.point.setType(Material.BEDROCK, world); } } else if (!isConverted && isBedrock) { //revert model.revertData.revert(world, model.point); } } }
mit
hres/cfg-task-service
src/main/java/ca/gc/ip346/classification/model/PseudoBoolean.java
650
package ca.gc.ip346.classification.model; public class PseudoBoolean { private Boolean value; /* = false; */ private Boolean modified = false; public PseudoBoolean(Boolean value) { this.value = value; } public PseudoBoolean() { } /** * @return the value */ public Boolean getValue() { return value; } /** * @param value the value to set */ public void setValue(Boolean value) { this.value = value; } /** * @return the modified */ public Boolean getModified() { return modified; } /** * @param modified the modified to set */ public void setModified(Boolean modified) { this.modified = modified; } }
mit
AntonisPlatis92/Wifi-Awareness
app/src/main/java/com/example/android/wifiawareness/GetUrlContentTask.java
2269
package com.example.android.wifiawareness; import android.os.AsyncTask; import android.util.Log; import android.widget.TextView; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.io.*; import static android.content.ContentValues.TAG; /** * Created by Antonis Platis on 2/4/2017. */ class GetUrlContentTask extends AsyncTask<String, Integer, String> { private String contentReturn; private boolean finished=false; protected String doInBackground(String... urls) { URL url = null; try { url = new URL(urls[0]); } catch (MalformedURLException e) { e.printStackTrace(); } HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { e.printStackTrace(); } try { connection.setRequestMethod("GET"); } catch (ProtocolException e) { e.printStackTrace(); } connection.setDoOutput(true); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); try { connection.connect(); } catch (IOException e) { e.printStackTrace(); } BufferedReader rd = null; String content = "", line; try { rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = rd.readLine()) != null) { content += line + "\n"; } } catch (IOException e) { e.printStackTrace(); } this.contentReturn=content; this.finished=true; return content; } protected void onPostExecute(String result) { // this is executed on the main thread after the process is over // update your UI here } public void waitUntilFinish(){ while (!this.finished){ } } public String getContentReturn(){ return this.contentReturn; } }
mit
Rubentxu/SuperMariano
core/src/com/indignado/games/states/splash/components/Delay.java
401
package com.indignado.games.states.splash.components; import com.ilargia.games.entitas.api.IComponent; import com.ilargia.games.entitas.codeGenerator.Component; @Component(pools = {"Splash"}) public class Delay implements IComponent { public float duration; public float time; public Delay(float duration) { this.duration = duration; this.time = 0; } }
mit
zhangqiang110/my4j
pms/src/main/java/com/swfarm/biz/aliexpress/dto/AliExperssFreightTemplateDTO.java
780
package com.swfarm.biz.aliexpress.dto; import java.io.Serializable; public class AliExperssFreightTemplateDTO implements Serializable { private static final long serialVersionUID = 4928762139484999613L; private Integer templateId ; private String templateName ; private Boolean defaults; public Integer getTemplateId() { return templateId; } public void setTemplateId(Integer templateId) { this.templateId = templateId; } public String getTemplateName() { return templateName; } public void setTemplateName(String templateName) { this.templateName = templateName; } public Boolean getDefaults() { return defaults; } public void setDefaults(Boolean defaults) { this.defaults = defaults; } }
mit
emmertf/OpenBlocks
src/main/java/openblocks/client/gui/GuiDrawingTable.java
2922
package openblocks.client.gui; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import openblocks.common.Stencil; import openblocks.common.container.ContainerDrawingTable; import openblocks.rpc.IStencilCrafter; import openmods.gui.BaseGuiContainer; import openmods.gui.component.BaseComponent; import openmods.gui.component.GuiComponentIconButton; import openmods.gui.component.GuiComponentSprite; import openmods.gui.component.GuiComponentTextButton; import openmods.gui.listener.IMouseDownListener; import openmods.utils.render.FakeIcon; public class GuiDrawingTable extends BaseGuiContainer<ContainerDrawingTable> { public static final int BUTTON_DRAW = 0; private GuiComponentSprite iconDisplay; private int patternIndex = 0; public GuiDrawingTable(ContainerDrawingTable container) { super(container, 176, 172, "openblocks.gui.drawingtable"); final IStencilCrafter rpcProxy = getContainer().getOwner().createClientRpcProxy(IStencilCrafter.class); GuiComponentIconButton buttonLeft = new GuiComponentIconButton(47, 32, 0xFFFFFF, FakeIcon.createSheetIcon(0, 82, 16, 16), BaseComponent.TEXTURE_SHEET); buttonLeft.setListener(new IMouseDownListener() { @Override public void componentMouseDown(BaseComponent component, int x, int y, int button) { patternIndex--; if (patternIndex < 0) patternIndex = Stencil.VALUES.length - 1; iconDisplay.setIcon(Stencil.VALUES[patternIndex].getBlockIcon()); } }); GuiComponentIconButton buttonRight = new GuiComponentIconButton(108, 32, 0xFFFFFF, FakeIcon.createSheetIcon(16, 82, -16, 16), BaseComponent.TEXTURE_SHEET); buttonRight.setListener(new IMouseDownListener() { @Override public void componentMouseDown(BaseComponent component, int x, int y, int button) { patternIndex++; if (patternIndex >= Stencil.VALUES.length) patternIndex = 0; iconDisplay.setIcon(Stencil.VALUES[patternIndex].getBlockIcon()); } }); GuiComponentTextButton buttonDraw = new GuiComponentTextButton(68, 57, 40, 13, 0xFFFFFF); buttonDraw.setText("Draw").setListener(new IMouseDownListener() { @Override public void componentMouseDown(BaseComponent component, int x, int y, int button) { rpcProxy.craft(Stencil.VALUES[patternIndex]); } }); root.addComponent(buttonDraw); (iconDisplay = new GuiComponentSprite(80, 34, Stencil.values()[0].getBlockIcon(), TextureMap.locationBlocksTexture)) .setColor(0f, 0f, 0f) .setOverlayMode(true) .setEnabled(inventorySlots.getSlot(0).getStack() != null); root.addComponent(iconDisplay); root.addComponent(buttonLeft); root.addComponent(buttonRight); } @Override public void updateScreen() { super.updateScreen(); final Slot slot = inventorySlots.getSlot(0); final ItemStack stack = slot.getStack(); iconDisplay.setEnabled(stack != null && slot.isItemValid(stack)); } }
mit
dcshock/forklift
core/src/test/java/forklift/consumer/parser/KeyValueParserTest.java
3127
package forklift.consumer.parser; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Map; import org.junit.jupiter.api.Test; public class KeyValueParserTest { @Test public void parseNull() { assertSame(0, KeyValueParser.parse(null).size()); assertSame(0, KeyValueParser.parse("").size()); } @Test public void parse() { String msg = "x=y\n" + "x=y\n" + "xy\n" + "y=hello this is a really cool message;"; final Map<String, String> result = KeyValueParser.parse(msg); assertTrue("y".equals(result.get("x"))); assertTrue("hello this is a really cool message;".equals(result.get("y"))); assertTrue("".equals(result.get("xy"))); assertTrue(result.size() == 3); } @Test public void parse2() { String msg = "x=5\n" + "x=y\n" + "xy\n" + "&*F=\n" + "\n" + "\n" + "# y= test\tspace \n" + "y=hello this is a really cool message;\n" + "m=x=y+5\n" + "n=hello\\nworld\n" + " p =!@#$%^&*()_+|}{?><,./-=`~'\""; final Map<String, String> result = KeyValueParser.parse(msg); assertTrue("y".equals(result.get("x"))); assertTrue("hello this is a really cool message;".equals(result.get("y"))); assertTrue("".equals(result.get("xy"))); assertTrue("".equals(result.get("&*F"))); assertTrue("hello\\nworld".equals(result.get("n"))); assertTrue("x=y+5".equals(result.get("m"))); assertTrue(" test\tspace ".equals(result.get("# y"))); assertTrue("!@#$%^&*()_+|}{?><,./-=`~'\"".equals(result.get("p"))); assertTrue(result.size() == 8); } @Test public void parse3() { String msg = "="; final Map<String, String> result = KeyValueParser.parse(msg); assertTrue(result.size() == 0); } @Test public void parse4() { String msg = "========="; final Map<String, String> result = KeyValueParser.parse(msg); assertTrue(result.size() == 0); } @Test public void parse5() { String msg = "===*****------^^^^^"; final Map<String, String> result = KeyValueParser.parse(msg); assertTrue(result.size() == 0); } @Test public void parse6() { String msg = " = =="; final Map<String, String> result = KeyValueParser.parse(msg); assertTrue(result.size() == 0); } @Test public void parseNLCR() { String msg = "x=y\n\r" + "a=123\n\r\n\r" + "name=Buzz Lightyear\n\r"; final Map<String, String> result = KeyValueParser.parse(msg); assertTrue("y".equals(result.get("x"))); assertTrue("123".equals(result.get("a"))); assertTrue("Buzz Lightyear".equals(result.get("name"))); assertTrue(result.size() == 3); } }
mit
raydeng83/devopsbuddy
src/main/java/com/devopsbuddy/backend/persistence/domain/backend/PasswordResetToken.java
3206
package com.devopsbuddy.backend.persistence.domain.backend; import com.devopsbuddy.backend.persistence.converters.LocalDateTimeAttributeConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.*; import java.io.Serializable; import java.time.LocalDateTime; /** * Created by lede on 8/8/16. */ @Entity public class PasswordResetToken implements Serializable{ private static final long serialVersionUID = 1L; private static final int DEFAULT_TOKEN_LENGTH_IN_MINUTES = 120; /** The application logger */ private static final Logger LOG = LoggerFactory.getLogger(PasswordResetToken.class); @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(unique = true) private String token; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "user_id") private User user; @Column(name = "expire_date") @Convert(converter = LocalDateTimeAttributeConverter.class) private LocalDateTime expireDate; public PasswordResetToken() {} public PasswordResetToken(String token, User user, LocalDateTime creationDateTime, int expirationInMinutes) { if ((null == token) || (null == user) || (null == creationDateTime)) { throw new IllegalArgumentException("token, user and creation date time can't be null"); } if (expirationInMinutes == 0) { LOG.warn("The token expiration length in minutes is zero. Assigning the default value {}", DEFAULT_TOKEN_LENGTH_IN_MINUTES); expirationInMinutes = DEFAULT_TOKEN_LENGTH_IN_MINUTES; } this.token = token; this.user = user; expireDate = creationDateTime.plusMinutes(expirationInMinutes); } public LocalDateTime getExpireDate() { return expireDate; } public void setExpireDate(LocalDateTime expireDate) { this.expireDate = expireDate; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PasswordResetToken that = (PasswordResetToken) o; if (id != that.id) return false; if (token != null ? !token.equals(that.token) : that.token != null) return false; if (user != null ? !user.equals(that.user) : that.user != null) return false; return expireDate != null ? expireDate.equals(that.expireDate) : that.expireDate == null; } @Override public int hashCode() { int result = (int) (id ^ (id >>> 32)); result = 31 * result + (token != null ? token.hashCode() : 0); result = 31 * result + (user != null ? user.hashCode() : 0); result = 31 * result + (expireDate != null ? expireDate.hashCode() : 0); return result; } }
mit
jonchui/BibleMem
Android/dbt-sdk-android/app/src/main/java/com/faithcomesbyhearing/dbtdemo/ShowFragmentCallback.java
180
package com.faithcomesbyhearing.dbtdemo; import android.app.Fragment; public interface ShowFragmentCallback { void showFragment(Fragment fragment, boolean addToBackStack); }
mit
CS2103AUG2016-T17-C2/main
src/main/java/seedu/task/logic/parser/FindParser.java
4143
package seedu.task.logic.parser; //@@author A0138301U import static seedu.task.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import seedu.task.commons.exceptions.IllegalValueException; import seedu.task.logic.commands.Command; import seedu.task.logic.commands.FindCommand; import seedu.task.logic.commands.IncorrectCommand; import seedu.task.model.tag.Tag; import seedu.task.model.task.TaskPriority; import seedu.task.model.task.Status; /** * Helper class to parse input when find is invoked, and to return the appropriate find command or other command based on input */ public class FindParser { private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one // or // more // keywords // separated // by // whitespace private static final char PREFIX_HASHTAG = '#'; private static final char PREFIX_AT = '@'; private static final String HIGH = "high"; private static final String MEDIUM = "medium"; private static final String LOW = "low"; private static final String ACTIVE = "active"; private static final String EXPIRED = "expired"; private static final String DONE = "done"; private static final String IGNORE = "ignore"; public static Command parseInput(String args) throws IllegalValueException { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); if (keywords[0].charAt(0) == PREFIX_AT) { // prefix @ used to denote find // venue return returnFindCommandForVenue(keywords); } if (keywords[0].charAt(0) == PREFIX_HASHTAG) { // prefix # used to denote find // tag, priority or status return returnFindCommandForHashtagPrefix(keywords); } final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindCommand(keywordSet); } /** * Returns the find command for priority or status, or by tagging. */ private static Command returnFindCommandForHashtagPrefix(final String[] keywords) throws IllegalValueException { if (keywords[0].substring(1).isEmpty()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } if (keywords[0].substring(1).equalsIgnoreCase(HIGH)) { return new FindCommand(TaskPriority.HIGH); } else if (keywords[0].substring(1).equalsIgnoreCase(MEDIUM)) { return new FindCommand(TaskPriority.MEDIUM); } else if (keywords[0].substring(1).equalsIgnoreCase(LOW)) { return new FindCommand(TaskPriority.LOW); } else if (keywords[0].substring(1).equalsIgnoreCase(ACTIVE)) { return new FindCommand(Status.ACTIVE); } else if (keywords[0].substring(1).equalsIgnoreCase(DONE)) { return new FindCommand(Status.DONE); } else if (keywords[0].substring(1).equalsIgnoreCase(EXPIRED)) { return new FindCommand(Status.EXPIRED); } else if (keywords[0].substring(1).equalsIgnoreCase(IGNORE)) { return new FindCommand(Status.IGNORE); } else { Tag tag = new Tag(keywords[0].substring(1)); return new FindCommand(tag); } } private static Command returnFindCommandForVenue(final String[] keywords) { if (keywords[0].substring(1).isEmpty()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } return new FindCommand(keywords[0].substring(1)); } }
mit
aterai/java-swing-tips
TableColumnHeaderIcon/src/java/example/MainPanel.java
5444
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.net.URL; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumnModel; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); URL[] icons = { getUrl("wi0062-16.png"), getUrl("wi0063-16.png"), getUrl("wi0064-16.png") }; String[] columnNames = {"Column1", "Column2", "Column3"}; JTable table = new JTable(new DefaultTableModel(columnNames, 8)); TableColumnModel m = table.getColumnModel(); for (int i = 0; i < m.getColumnCount(); i++) { // m.getColumn(i).setHeaderRenderer(new IconColumnHeaderRenderer()); // m.getColumn(i).setHeaderRenderer(new HtmlIconHeaderRenderer()); String td = String.format("<td><img src='%s'/></td>&nbsp;%s", icons[i], columnNames[i]); m.getColumn(i).setHeaderValue("<html><table cellpadding='0' cellspacing='0'>" + td); } table.setAutoCreateRowSorter(true); add(new JScrollPane(table)); JMenuBar mb = new JMenuBar(); mb.add(LookAndFeelUtil.createLookAndFeelMenu()); EventQueue.invokeLater(() -> getRootPane().setJMenuBar(mb)); setPreferredSize(new Dimension(320, 240)); } private URL getUrl(String str) { return getClass().getResource(str); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } // // TEST: LookAndFeel // class IconColumnHeaderRenderer implements TableCellRenderer { // private final Icon icon = new ImageIcon(getClass().getResource("wi0063-16.png")); // @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // TableCellRenderer r = table.getTableHeader().getDefaultRenderer(); // Component c = r.getTableCellRendererComponent( // table, value, isSelected, hasFocus, row, column); // if (c instanceof JLabel) { // JLabel l = (JLabel) c; // l.setHorizontalTextPosition(SwingConstants.RIGHT); // l.setIcon(icon); // } // return c; // } // } // TEST: html baseline // class HtmlIconHeaderRenderer implements TableCellRenderer { // private final URL url = getClass().getResource("wi0063-16.png"); // @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // TableCellRenderer r = table.getTableHeader().getDefaultRenderer(); // String str = Objects.toString(value, ""); // String html = String.format("<html><img src='%s'/>&nbsp;%s", url, str); // // String html = String.format("<html><table><td cellpadding='0'><img src='%s'/></td>%s", url, str); // return r.getTableCellRendererComponent(table, html, isSelected, hasFocus, row, column); // } // } // @see https://java.net/projects/swingset3/sources/svn/content/trunk/SwingSet3/src/com/sun/swingset3/SwingSet3.java final class LookAndFeelUtil { private static String lookAndFeel = UIManager.getLookAndFeel().getClass().getName(); private LookAndFeelUtil() { /* Singleton */ } public static JMenu createLookAndFeelMenu() { JMenu menu = new JMenu("LookAndFeel"); ButtonGroup lafGroup = new ButtonGroup(); for (UIManager.LookAndFeelInfo lafInfo : UIManager.getInstalledLookAndFeels()) { menu.add(createLookAndFeelItem(lafInfo.getName(), lafInfo.getClassName(), lafGroup)); } return menu; } private static JMenuItem createLookAndFeelItem(String laf, String lafClass, ButtonGroup bg) { JMenuItem lafItem = new JRadioButtonMenuItem(laf, lafClass.equals(lookAndFeel)); lafItem.setActionCommand(lafClass); lafItem.setHideActionText(true); lafItem.addActionListener(e -> { ButtonModel m = bg.getSelection(); try { setLookAndFeel(m.getActionCommand()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { UIManager.getLookAndFeel().provideErrorFeedback((Component) e.getSource()); } }); bg.add(lafItem); return lafItem; } private static void setLookAndFeel(String lookAndFeel) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { String oldLookAndFeel = LookAndFeelUtil.lookAndFeel; if (!oldLookAndFeel.equals(lookAndFeel)) { UIManager.setLookAndFeel(lookAndFeel); LookAndFeelUtil.lookAndFeel = lookAndFeel; updateLookAndFeel(); // firePropertyChange("lookAndFeel", oldLookAndFeel, lookAndFeel); } } private static void updateLookAndFeel() { for (Window window : Window.getWindows()) { SwingUtilities.updateComponentTreeUI(window); } } }
mit
tiagopnoliveira/programming
PowerSet.java
1530
import java.util.*; import java.util.stream.Collectors; public class PowerSet { private static int[] a = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; public static void main(String[] args) { long startTime = System.currentTimeMillis(); PowerSet ps = new PowerSet(); Set<Set<Integer>> result = ps.powerSet(a); double duration = (System.currentTimeMillis() - startTime) / 1000; String listString = result.stream().map(Object::toString).collect(Collectors.joining(", ")); System.out.println("Size: " + result.size()); System.out.println(listString); System.out.print("Processing time: "); System.out.format("%.3f%n", duration); System.out.println(" seconds."); } public Set<Set<Integer>> powerSet(int[] a) { Set<Set<Integer>> result = new HashSet<Set<Integer>>(); powerSetRecursive(a, result); return result; } private void powerSetRecursive(int[] a, Set<Set<Integer>> s) { Set<Integer> newSet; if(a.length == 0) { newSet = new HashSet<Integer>(); if(!s.contains(newSet)) s.add(newSet); return; } for(int i = 0; i < a.length; i++) { int[] tmp = removeItem(a, i); newSet = new HashSet<Integer>(); for(int j = 0; j < tmp.length; j++) { newSet.add(tmp[j]); } if(s.contains(newSet)) continue; s.add(newSet); powerSetRecursive(tmp, s); } } private int[] removeItem(int[] a, int pos) { int res[] = new int[a.length-1]; int j = 0; for(int i = 0; i < a.length; i++) { if(i == pos) continue; res[j++] = a[i]; } return res; } }
mit
gfx/android-power-assert-plugin
example/src/main/java/com/github/gfx/android/example/p/Baz.java
197
package com.github.gfx.android.example.p; public class Baz { public static void f(boolean expr) { assert expr; } public boolean g(boolean expr) { return expr; } }
mit
bing-ads-sdk/BingAds-Java-SDK
src/main/java/com/microsoft/bingads/v12/bulk/entities/BulkAdGroupDynamicSearchAdTarget.java
16956
package com.microsoft.bingads.v12.bulk.entities; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer; import com.microsoft.bingads.internal.functionalinterfaces.Function; import com.microsoft.bingads.v12.bulk.BulkFileReader; import com.microsoft.bingads.v12.bulk.BulkFileWriter; import com.microsoft.bingads.v12.bulk.BulkOperation; import com.microsoft.bingads.v12.bulk.BulkServiceManager; import com.microsoft.bingads.v12.campaignmanagement.AdGroupCriterion; import com.microsoft.bingads.v12.campaignmanagement.AdGroupCriterionStatus; import com.microsoft.bingads.v12.campaignmanagement.ArrayOfWebpageCondition; import com.microsoft.bingads.v12.campaignmanagement.BiddableAdGroupCriterion; import com.microsoft.bingads.v12.campaignmanagement.CriterionBid; import com.microsoft.bingads.v12.campaignmanagement.FixedBid; import com.microsoft.bingads.v12.campaignmanagement.Webpage; import com.microsoft.bingads.v12.campaignmanagement.WebpageParameter; import com.microsoft.bingads.v12.internal.bulk.BulkMapping; import com.microsoft.bingads.v12.internal.bulk.ComplexBulkMapping; import com.microsoft.bingads.v12.internal.bulk.MappingHelpers; import com.microsoft.bingads.v12.internal.bulk.RowValues; import com.microsoft.bingads.v12.internal.bulk.SimpleBulkMapping; import com.microsoft.bingads.v12.internal.bulk.StringExtensions; import com.microsoft.bingads.v12.internal.bulk.StringTable; import com.microsoft.bingads.v12.internal.bulk.entities.SingleRecordBulkEntity; /** * Represents a dynamic search ad target that is assigned to an ad group. Each dynamic search ad target can be read or written in a bulk file. * * <p> * For more information, see Ad Group Dynamic Search Ad Target at * <a href="https://go.microsoft.com/fwlink/?linkid=846127">https://go.microsoft.com/fwlink/?linkid=846127</a>. * </p> * * @see BulkServiceManager * @see BulkOperation * @see BulkFileReader * @see BulkFileWriter */ public class BulkAdGroupDynamicSearchAdTarget extends SingleRecordBulkEntity { private BiddableAdGroupCriterion biddableAdGroupCriterion; private String campaignName; private String adGroupName; private PerformanceData performanceData; private static final List<BulkMapping<BulkAdGroupDynamicSearchAdTarget>> MAPPINGS; static { List<BulkMapping<BulkAdGroupDynamicSearchAdTarget>> m = new ArrayList<BulkMapping<BulkAdGroupDynamicSearchAdTarget>>(); m.add(new SimpleBulkMapping<BulkAdGroupDynamicSearchAdTarget, String>(StringTable.Status, new Function<BulkAdGroupDynamicSearchAdTarget, String>() { @Override public String apply(BulkAdGroupDynamicSearchAdTarget c) { AdGroupCriterionStatus status = c.getBiddableAdGroupCriterion().getStatus(); return status == null ? null : status.value(); } }, new BiConsumer<String, BulkAdGroupDynamicSearchAdTarget>() { @Override public void accept(String v, BulkAdGroupDynamicSearchAdTarget c) { c.getBiddableAdGroupCriterion().setStatus(StringExtensions.parseOptional(v, new Function<String, AdGroupCriterionStatus>() { @Override public AdGroupCriterionStatus apply(String s) { return AdGroupCriterionStatus.fromValue(s); } })); } } )); m.add(new SimpleBulkMapping<BulkAdGroupDynamicSearchAdTarget, Long>(StringTable.Id, new Function<BulkAdGroupDynamicSearchAdTarget, Long>() { @Override public Long apply(BulkAdGroupDynamicSearchAdTarget c) { return c.getBiddableAdGroupCriterion().getId(); } }, new BiConsumer<String, BulkAdGroupDynamicSearchAdTarget>() { @Override public void accept(String v, BulkAdGroupDynamicSearchAdTarget c) { c.getBiddableAdGroupCriterion().setId(StringExtensions.parseOptional(v, new Function<String, Long>() { @Override public Long apply(String s) { return Long.parseLong(s); } })); } } )); m.add(new SimpleBulkMapping<BulkAdGroupDynamicSearchAdTarget, Long>(StringTable.ParentId, new Function<BulkAdGroupDynamicSearchAdTarget, Long>() { @Override public Long apply(BulkAdGroupDynamicSearchAdTarget c) { return c.getBiddableAdGroupCriterion().getAdGroupId(); } }, new BiConsumer<String, BulkAdGroupDynamicSearchAdTarget>() { @Override public void accept(String v, BulkAdGroupDynamicSearchAdTarget c) { c.getBiddableAdGroupCriterion().setAdGroupId(StringExtensions.<Long>parseOptional(v, new Function<String, Long>() { @Override public Long apply(String value) { return Long.parseLong(value); } })); } } )); m.add(new SimpleBulkMapping<BulkAdGroupDynamicSearchAdTarget, String>(StringTable.Campaign, new Function<BulkAdGroupDynamicSearchAdTarget, String>() { @Override public String apply(BulkAdGroupDynamicSearchAdTarget c) { return c.getCampaignName(); } }, new BiConsumer<String, BulkAdGroupDynamicSearchAdTarget>() { @Override public void accept(String v, BulkAdGroupDynamicSearchAdTarget c) { c.setCampaignName(v); } } )); m.add(new SimpleBulkMapping<BulkAdGroupDynamicSearchAdTarget, String>(StringTable.AdGroup, new Function<BulkAdGroupDynamicSearchAdTarget, String>() { @Override public String apply(BulkAdGroupDynamicSearchAdTarget c) { return c.getAdGroupName(); } }, new BiConsumer<String, BulkAdGroupDynamicSearchAdTarget>() { @Override public void accept(String v, BulkAdGroupDynamicSearchAdTarget c) { c.setAdGroupName(v); } } )); m.add(new SimpleBulkMapping<BulkAdGroupDynamicSearchAdTarget, String>(StringTable.Bid, new Function<BulkAdGroupDynamicSearchAdTarget, String>() { @Override public String apply(BulkAdGroupDynamicSearchAdTarget c) { if (c.getBiddableAdGroupCriterion() instanceof BiddableAdGroupCriterion) { CriterionBid bid = ((BiddableAdGroupCriterion) c.getBiddableAdGroupCriterion()).getCriterionBid(); if (bid == null) { return null; } else { return StringExtensions.toAdGroupCriterionFixedBidBulkString((FixedBid) bid); } } else { return null; } } }, new BiConsumer<String, BulkAdGroupDynamicSearchAdTarget>() { @Override public void accept(String v, BulkAdGroupDynamicSearchAdTarget c) { if (c.getBiddableAdGroupCriterion() instanceof BiddableAdGroupCriterion) { ((FixedBid) ((BiddableAdGroupCriterion) c.getBiddableAdGroupCriterion()).getCriterionBid()).setAmount(( StringExtensions.nullOrDouble(v)) ); } } } )); m.add(new SimpleBulkMapping<BulkAdGroupDynamicSearchAdTarget, String>(StringTable.TrackingTemplate, new Function<BulkAdGroupDynamicSearchAdTarget, String>() { @Override public String apply(BulkAdGroupDynamicSearchAdTarget c) { if (c.getBiddableAdGroupCriterion() instanceof BiddableAdGroupCriterion) { return StringExtensions.toOptionalBulkString(((BiddableAdGroupCriterion) c.getBiddableAdGroupCriterion()).getTrackingUrlTemplate(), c.getBiddableAdGroupCriterion().getId()); } else { return null; } } }, new BiConsumer<String, BulkAdGroupDynamicSearchAdTarget>() { @Override public void accept(String v, BulkAdGroupDynamicSearchAdTarget c) { if (c.getBiddableAdGroupCriterion() instanceof BiddableAdGroupCriterion) { ((BiddableAdGroupCriterion) c.getBiddableAdGroupCriterion()).setTrackingUrlTemplate(StringExtensions.getValueOrEmptyString(v));; } } } )); m.add(new SimpleBulkMapping<BulkAdGroupDynamicSearchAdTarget, String>(StringTable.CustomParameter, new Function<BulkAdGroupDynamicSearchAdTarget, String>() { @Override public String apply(BulkAdGroupDynamicSearchAdTarget c) { if (c.getBiddableAdGroupCriterion() instanceof BiddableAdGroupCriterion) { return StringExtensions.toCustomParaBulkString(((BiddableAdGroupCriterion) c.getBiddableAdGroupCriterion()).getUrlCustomParameters(), c.getBiddableAdGroupCriterion().getId()); } else { return null; } } }, new BiConsumer<String, BulkAdGroupDynamicSearchAdTarget>() { @Override public void accept(String v, BulkAdGroupDynamicSearchAdTarget c) { if (c.getBiddableAdGroupCriterion() instanceof BiddableAdGroupCriterion) { try { ((BiddableAdGroupCriterion) c.getBiddableAdGroupCriterion()).setUrlCustomParameters(StringExtensions.parseCustomParameters(v)); } catch (Exception e) { e.printStackTrace(); } } } } )); m.add(new ComplexBulkMapping<BulkAdGroupDynamicSearchAdTarget>( new BiConsumer<BulkAdGroupDynamicSearchAdTarget, RowValues>() { @Override public void accept(BulkAdGroupDynamicSearchAdTarget c, RowValues v) { if (c.getBiddableAdGroupCriterion().getCriterion() instanceof Webpage) { WebpageParameter webpageParameter = ((Webpage) c.getBiddableAdGroupCriterion().getCriterion()).getParameter(); if (webpageParameter == null || webpageParameter.getConditions() == null) { return; } WebpageConditionHelper.addRowValuesFromConditions(webpageParameter.getConditions(), v); } } }, new BiConsumer<RowValues, BulkAdGroupDynamicSearchAdTarget>() { @Override public void accept(RowValues v, BulkAdGroupDynamicSearchAdTarget c) { if (c.getBiddableAdGroupCriterion().getCriterion() instanceof Webpage) { WebpageParameter webpageParameter = ((Webpage) c.getBiddableAdGroupCriterion().getCriterion()).getParameter(); if (webpageParameter != null) { webpageParameter.setConditions(new ArrayOfWebpageCondition()); WebpageConditionHelper.addConditionsFromRowValues(v, webpageParameter.getConditions()); } } } } )); m.add(new SimpleBulkMapping<BulkAdGroupDynamicSearchAdTarget, String>(StringTable.Name, new Function<BulkAdGroupDynamicSearchAdTarget, String>() { @Override public String apply(BulkAdGroupDynamicSearchAdTarget c) { if (c.getBiddableAdGroupCriterion().getCriterion() instanceof Webpage) { WebpageParameter webpageParameter = ((Webpage) c.getBiddableAdGroupCriterion().getCriterion()).getParameter(); return StringExtensions.toCriterionNameBulkString(webpageParameter, c.getBiddableAdGroupCriterion().getId()); } return null; } }, new BiConsumer<String, BulkAdGroupDynamicSearchAdTarget>() { @Override public void accept(String v, BulkAdGroupDynamicSearchAdTarget c) { if (c.getBiddableAdGroupCriterion().getCriterion() instanceof Webpage) { WebpageParameter webpageParameter = ((Webpage) c.getBiddableAdGroupCriterion().getCriterion()).getParameter(); if (webpageParameter != null) { webpageParameter.setCriterionName(StringExtensions.parseCriterionName(v)); } } } } )); MAPPINGS = Collections.unmodifiableList(m); } @Override public void processMappingsFromRowValues(RowValues values) { BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion(); FixedBid fixedBid = new FixedBid(); fixedBid.setType(FixedBid.class.getSimpleName()); Webpage webpage = new Webpage(); webpage.setParameter(new WebpageParameter()); adGroupCriterion.setCriterion(webpage); adGroupCriterion.getCriterion().setType(Webpage.class.getSimpleName()); adGroupCriterion.setCriterionBid(fixedBid); adGroupCriterion.setType("BiddableAdGroupCriterion"); setBiddableAdGroupCriterion(adGroupCriterion); MappingHelpers.convertToEntity(values, MAPPINGS, this); performanceData = PerformanceData.readFromRowValuesOrNull(values); } @Override public void processMappingsToRowValues(RowValues values, boolean excludeReadonlyData) { validatePropertyNotNull(getBiddableAdGroupCriterion(), AdGroupCriterion.class.getSimpleName()); MappingHelpers.convertToValues(this, values, MAPPINGS); if (!excludeReadonlyData) { PerformanceData.writeToRowValuesIfNotNull(getPerformanceData(), values); } } /** * Gets an Ad Group Criterion. */ public AdGroupCriterion getBiddableAdGroupCriterion() { return biddableAdGroupCriterion; } /** * Sets an Ad Group Criterion */ public void setBiddableAdGroupCriterion(BiddableAdGroupCriterion biddableAdGroupCriterion) { this.biddableAdGroupCriterion = biddableAdGroupCriterion; } /** * Gets the name of the campaign. * Corresponds to the 'Campaign' field in the bulk file. */ public String getCampaignName() { return campaignName; } /** * Sets the name of the ad group. * Corresponds to the 'Ad Group' field in the bulk file. */ public void setAdGroupName(String adGroupName) { this.adGroupName = adGroupName; } /** * Gets the name of the ad group. * Corresponds to the 'Ad Group' field in the bulk file. */ public String getAdGroupName() { return adGroupName; } /** * Sets the name of the campaign. * Corresponds to the 'Campaign' field in the bulk file. */ public void setCampaignName(String campaignName) { this.campaignName = campaignName; } /** * Gets the historical performance data. */ public PerformanceData getPerformanceData() { return performanceData; } }
mit
fabian-rump/VoteManager
src/main/java/net/cgro/votemanager/model/Liste.java
2526
package net.cgro.votemanager.model; import javax.xml.bind.annotation.XmlID; import java.util.ArrayList; import java.util.List; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlAttribute; public class Liste { private final SimpleStringProperty name; private final SimpleStringProperty kuerzel; private final SimpleIntegerProperty nummer; private final ObservableList<Kandidat> kandidaten = FXCollections.observableArrayList(); private int stimmenTemp = 0; private int stimmenTemp2 = 0; public Liste(String name, String kuerzel, int nummer) { this.name = new SimpleStringProperty(name); this.kuerzel = new SimpleStringProperty(kuerzel); this.nummer = new SimpleIntegerProperty(nummer); } private Liste() { this.name = new SimpleStringProperty(); this.kuerzel = new SimpleStringProperty(); this.nummer = new SimpleIntegerProperty(); } @XmlID @XmlAttribute public String getKuerzel() { return kuerzel.get(); } public void setKuerzel(String kuerzel) { this.kuerzel.set(kuerzel); } @XmlAttribute public String getName() { return name.get(); } public void setName(String name) { this.name.set(name); } @XmlAttribute public int getNummer() { return nummer.get(); } public void setNummer(int nummer) { this.nummer.set(nummer); } @XmlElementWrapper @XmlElement(name="kandidat") public ObservableList<Kandidat> getKandidaten() { return kandidaten; } public void addKandidat(Kandidat kandidat) { kandidaten.add(kandidat); } public void resetStimmenTemp() { stimmenTemp = 0; } public void addStimmenTemp(int stimmen) { stimmenTemp += stimmen; } public int getStimmenTemp() { return stimmenTemp; } public void resetStimmenTemp2() { stimmenTemp2 = 0; } public void addStimmenTemp2(int stimmen) { stimmenTemp2 += stimmen; } public int getStimmenTemp2() { return stimmenTemp2; } }
mit
tranek/ChivalryServerBrowser
src/com/tranek/chivalryserverbrowser/Location.java
1463
package com.tranek.chivalryserverbrowser; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.nio.charset.Charset; import org.json.JSONException; import org.json.JSONObject; /** * * Super class of the location classes. Contains shared utility methods. * */ public class Location { /** * Reads JSON data from a URL address. * * * @param url the URL address to read the JSON data from * @return a JSONObject of the text data read in from the URL * @throws IOException * @throws JSONException */ public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = new URL(url).openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } } /** * Reads all text data from a Reader and converts it to one complete string. * * @param rd the Reader containing the text separated by new lines * @return a concatenated string of the text * @throws IOException */ private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } }
mit
EinsamHauer/disthene-reader
src/main/java/net/iponweb/disthene/reader/graphite/functions/AbsoluteFunction.java
2051
package net.iponweb.disthene.reader.graphite.functions; import net.iponweb.disthene.reader.beans.TimeSeries; import net.iponweb.disthene.reader.exceptions.EvaluationException; import net.iponweb.disthene.reader.exceptions.InvalidArgumentException; import net.iponweb.disthene.reader.exceptions.TimeSeriesNotAlignedException; import net.iponweb.disthene.reader.graphite.Target; import net.iponweb.disthene.reader.graphite.evaluation.TargetEvaluator; import net.iponweb.disthene.reader.utils.TimeSeriesUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author Andrei Ivanov */ public class AbsoluteFunction extends DistheneFunction { public AbsoluteFunction(String text) { super(text, "absolute"); } @Override public List<TimeSeries> evaluate(TargetEvaluator evaluator) throws EvaluationException { List<TimeSeries> processedArguments = new ArrayList<>(); processedArguments.addAll(evaluator.eval((Target) arguments.get(0))); if (processedArguments.size() == 0) return new ArrayList<>(); if (!TimeSeriesUtils.checkAlignment(processedArguments)) { throw new TimeSeriesNotAlignedException(); } for(TimeSeries timeSeries : processedArguments) { for(int i = 0; i < timeSeries.getValues().length; i++) { if (timeSeries.getValues()[i] != null) { timeSeries.getValues()[i] = Math.abs(timeSeries.getValues()[i]); } } setResultingName(timeSeries); } return processedArguments; } @Override public void checkArguments() throws InvalidArgumentException { if (arguments.size() > 1 || arguments.size() == 0) throw new InvalidArgumentException("absolute: number of arguments is " + arguments.size() + ". Must be one."); if (!(arguments.get(0) instanceof Target)) throw new InvalidArgumentException("absolute: argument is " + arguments.get(0).getClass().getName() + ". Must be series"); } }
mit
davidelvir/Laboratorio4
Lab4/src/lab4/Pieza.java
1054
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lab4; import java.awt.Color; /** * * @author David */ public abstract class Pieza { private Color color; private String material; public Pieza() { } public Pieza(Color color, String material) { this.color = color; this.material = material; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public String getMaterial() { return material; } public void setMaterial(String material) { this.material = material; } @Override public String toString() { return ""; } public abstract Pieza[][] movimiento(Pieza tablero [][],int i,int j, int x, int y)throws Excepcion; public abstract Pieza[][] comer(Pieza tablero [][],int i,int j, int x, int y) throws Excepcion; }
mit
josepozoz/ClusterK
source map-reduce/KMeansDriver.java
4700
package source map-reduce; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.conf.Configuration; import datapoint.DataPoint; public class KMeansDriver { public static ArrayList<DataPoint> oldKCentroids, newKCentroids; public static final String partFile = "/part-r-00000"; public static boolean hasConverged(String oldKCentroidsFile, String newKCentroidsFile) throws Exception { // String to hold lines read from files String line; // Allocate memory for oldKCentroids and newKCentroids oldKCentroids = new ArrayList<DataPoint>(); newKCentroids = new ArrayList<DataPoint>(); // Create a new Configuration and obtain a handle on the FileSystem Configuration configuration = new Configuration(); FileSystem filesystem = FileSystem.get(configuration); // Read the Old k-Means Centroid File if(DataPoint.NUM_ITERATIONS == 0) { // If this is the first iteration, the centroids lie in the k-Means Centroid input file BufferedReader oldReader = new BufferedReader(new InputStreamReader(filesystem.open (new Path(configuration.get("fs.default.name") + oldKCentroidsFile)))); line = oldReader.readLine(); while(line != null) { oldKCentroids.add(new DataPoint(line)); line = oldReader.readLine(); } } else { BufferedReader oldReader = new BufferedReader(new InputStreamReader(filesystem.open (new Path(configuration.get("fs.default.name") + oldKCentroidsFile + partFile)))); line = oldReader.readLine(); while(line != null) { int tabPosition = line.indexOf("\t"); oldKCentroids.add(new DataPoint(line.substring(tabPosition + 1))); line = oldReader.readLine(); } } BufferedReader newReader = new BufferedReader(new InputStreamReader(filesystem.open( new Path(configuration.get("fs.default.name") + newKCentroidsFile + partFile)))); line = newReader.readLine(); while(line != null) { int tabPosition = line.indexOf("\t"); newKCentroids.add(new DataPoint(line.substring(tabPosition + 1))); line = newReader.readLine(); } for(int i = 0; i < oldKCentroids.size(); i++) { if(oldKCentroids.get(i).complexDistance(newKCentroids.get(i)) > DataPoint.CONVERGENCE_THRESHOLD) return false; } return true; } public static void copyFinalCentroidsFile(String outputFolderName) throws Exception { Configuration configuration = new Configuration(); FileSystem filesystem = FileSystem.get(configuration); FileUtil.copy(filesystem, new Path(configuration.get("fs.default.name") + outputFolderName + "_" + (DataPoint.NUM_ITERATIONS-1)), filesystem, new Path(configuration.get("fs.default.name") + outputFolderName), false, true, configuration); } public static void main(String[] args) throws Exception { if(args.length != 3) { System.out.println("Usage: kMeansDriver <Input Path> <K-Centroids File> <Output Path>"); System.exit(-1); } while(true) { Configuration configuration = new Configuration(); if(DataPoint.NUM_ITERATIONS == 0) configuration.set("kCentroidsFile", args[1]); else configuration.set("kCentroidsFile", args[2] + "_" + (DataPoint.NUM_ITERATIONS-1) + partFile); System.out.println("Iteration: " + DataPoint.NUM_ITERATIONS); configuration.set("iteration", ""+DataPoint.NUM_ITERATIONS); Job job = new Job(configuration); job.setJarByClass(KMeansDriver.class); job.setJobName("K-Means Clustering"); FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[2] + "_" + DataPoint.NUM_ITERATIONS)); job.setMapperClass(KMeansMapper.class); job.setReducerClass(KMeansReducer.class); job.setMapOutputKeyClass(DataPoint.class); job.setMapOutputValueClass(DataPoint.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(DataPoint.class); job.waitForCompletion(true); if(DataPoint.NUM_ITERATIONS == 0) { if(hasConverged(args[1], args[2] + "_" + DataPoint.NUM_ITERATIONS)) break; } else { if(hasConverged(args[2] + "_" + (DataPoint.NUM_ITERATIONS - 1), args[2] + "_" + DataPoint.NUM_ITERATIONS)) break; } DataPoint.NUM_ITERATIONS++; } copyFinalCentroidsFile(args[2]); } }
mit
jmthompson2015/vizzini
example/src/test/java/org/vizzini/example/boardgame/tictactoe/TTTTokenTest.java
2579
package org.vizzini.example.boardgame.tictactoe; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import org.junit.Test; /** * Provides tests for the <code>TTTToken</code> class. */ public final class TTTTokenTest { /** * Test the <code>findByName()</code> method. */ @Test public void findByName() { assertThat(TTTToken.findByName("X"), is(TTTToken.X)); assertThat(TTTToken.findByName("O"), is(TTTToken.O)); } /** * Test the <code>findByName()</code> method. */ @Test public void findByNameNull() { try { TTTToken.findByName(null); fail("Should have thrown an exception"); } catch (final IllegalArgumentException e) { assertThat(e.getMessage(), is("name is null or empty")); } try { TTTToken.findByName(""); fail("Should have thrown an exception"); } catch (final IllegalArgumentException e) { assertThat(e.getMessage(), is("name is null or empty")); } assertNull(TTTToken.findByName("bogus")); } /** * Test the <code>findByTeam()</code> method. */ @Test public void findByTeam() { assertThat(TTTToken.findByTeam(TTTTeam.X), is(TTTToken.X)); assertThat(TTTToken.findByTeam(TTTTeam.O), is(TTTToken.O)); } /** * Test the <code>findByTeam()</code> method. */ @Test public void findByTeamNull() { try { TTTToken.findByTeam(null); fail("Should have thrown an exception"); } catch (final IllegalArgumentException e) { assertThat(e.getMessage(), is("team is null")); } } /** * Test the <code>getName()</code> method. */ @Test public void getName() { assertThat(TTTToken.X.getName(), is("X")); assertThat(TTTToken.O.getName(), is("O")); } /** * Test the <code>getTeam()</code> method. */ @Test public void getTeam() { assertThat(TTTToken.X.getTeam(), is(TTTTeam.X)); assertThat(TTTToken.O.getTeam(), is(TTTTeam.O)); } /** * Test the <code>opposite()</code> method. */ @Test public void opposite() { assertThat(TTTToken.X.opposite(), is(TTTToken.O)); assertThat(TTTToken.O.opposite(), is(TTTToken.X)); } }
mit
mostertg/dsa
Prac_1-0113Feb17P/task1.java
1900
import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; public class task1 { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); // add items to ArrayList list.add("Item 1"); list.add("Item 2"); list.add(2, "Item 3"); list.add("Item 4"); // print contents System.out.println("ArrayList: " + list); // index of 'Item 2' System.out.println("Item 2 position: " + list.indexOf("Item 2")); // is ArrayList empty? return boolean System.out.println("ArrayList empty? " + list.isEmpty()); // size dimension System.out.println("ArrayList size: " + list.size()); // ArrayList contains element 'Item 5'? return boolean System.out.println("\"Item 5\" in ArrayList? " + list.contains("Item 5")); // Value at index 2 System.out.println("Value at index 2: " + list.get(2)); // for loop print all values of ArrayList for (int i=0; i<list.size(); i++) { System.out.println("Index: " + i + " - item: " + list.get(i)); } // remove item at index 0 list.remove(0); // for-each loop print all values of ArrayList for (String str : list) { System.out.println("Index: " + list.indexOf(str) + " - item: " + str); } // remove 1st occurence of 'Item 3' list.remove("Item 3"); // iterator print all values of ArrayList for (ListIterator<String> iter = list.listIterator(); iter.hasNext();) { System.out.println("Index: " + iter.nextIndex() + " - item: " + iter.next()); } // convert to Array String[] aimpleArray = list.toArray(new String[list.size()]); } }
mit
Azure/azure-sdk-for-java
sdk/dataprotection/azure-resourcemanager-dataprotection/src/main/java/com/azure/resourcemanager/dataprotection/models/SourceDataStoreType.java
1449
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.dataprotection.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for SourceDataStoreType. */ public final class SourceDataStoreType extends ExpandableStringEnum<SourceDataStoreType> { /** Static value ArchiveStore for SourceDataStoreType. */ public static final SourceDataStoreType ARCHIVE_STORE = fromString("ArchiveStore"); /** Static value SnapshotStore for SourceDataStoreType. */ public static final SourceDataStoreType SNAPSHOT_STORE = fromString("SnapshotStore"); /** Static value VaultStore for SourceDataStoreType. */ public static final SourceDataStoreType VAULT_STORE = fromString("VaultStore"); /** * Creates or finds a SourceDataStoreType from its string representation. * * @param name a name to look for. * @return the corresponding SourceDataStoreType. */ @JsonCreator public static SourceDataStoreType fromString(String name) { return fromString(name, SourceDataStoreType.class); } /** @return known SourceDataStoreType values. */ public static Collection<SourceDataStoreType> values() { return values(SourceDataStoreType.class); } }
mit
fahadadeel/Aspose.Cells-for-Java
Examples/src/main/java/com/aspose/cells/examples/articles/WritingLargeExcelFiles.java
1369
package com.aspose.cells.examples.articles; import com.aspose.cells.Cells; import com.aspose.cells.MemorySetting; import com.aspose.cells.Workbook; import com.aspose.cells.examples.Utils; public class WritingLargeExcelFiles { public static void main(String[] args) throws Exception { // The path to the documents directory. String dataDir = Utils.getSharedDataDir(WritingLargeExcelFiles.class) + "articles/"; // Instantiate a new Workbook Workbook wb = new Workbook(); // Set the memory preferences // Note: This setting cannot take effect for the existing worksheets that are created before using the below line of code wb.getSettings().setMemorySetting(MemorySetting.MEMORY_PREFERENCE); /* * Note: The memory settings also would not work for the default sheet i.e., "Sheet1" etc. automatically created by the * Workbook. To change the memory setting of existing sheets, please change memory setting for them manually: */ Cells cells = wb.getWorksheets().get(0).getCells(); cells.setMemorySetting(MemorySetting.MEMORY_PREFERENCE); // Input large dataset into the cells of the worksheet.Your code goes here. // Get cells of the newly created Worksheet "Sheet2" whose memory setting is same with the one defined in // WorkbookSettings: cells = wb.getWorksheets().add("Sheet2").getCells(); } }
mit
JEEventStore/JCommonDomain
common/src/main/java/org/jeecqrs/common/CompareById.java
1538
/* * Copyright (c) 2013 Red Rainbow IT Solutions GmbH, Germany * * 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.jeecqrs.common; /** * Provides the ability to compare by identity. */ public interface CompareById<T> { /** * Tests whether this has the same identity as the other object. * * @param other the other object to compare with * @return true if the identities are the same, regardless of other attributes. */ boolean sameIdentityAs(T other); }
mit
LisLo/ArTEMiS
src/main/java/de/tum/in/www1/exerciseapp/service/GitService.java
9228
package de.tum.in.www1.exerciseapp.service; import de.tum.in.www1.exerciseapp.domain.File; import de.tum.in.www1.exerciseapp.domain.Participation; import de.tum.in.www1.exerciseapp.domain.Repository; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.HiddenFileFilter; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.PullResult; import org.eclipse.jgit.api.Status; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; @Service public class GitService { private final Logger log = LoggerFactory.getLogger(GitService.class); @Value("${artemis.bitbucket.user}") private String GIT_USER; @Value("${artemis.bitbucket.password}") private String GIT_PASSWORD; @Value("${artemis.repo-clone-path}") private String REPO_CLONE_PATH; @Value("${artemis.git.name}") private String GIT_NAME; @Value("${artemis.git.email}") private String GIT_EMAIL; private HashMap<Path, Repository> cachedRepositories = new HashMap<>(); /** * Get the local repository for a given participation. * If the local repo does not exist yet, it will be checked out. * * @param participation Participation the remote repository belongs to. * @return * @throws IOException * @throws GitAPIException */ public Repository getOrCheckoutRepository(Participation participation) throws IOException, GitAPIException { URL repoUrl = participation.getRepositoryUrlAsUrl(); Repository repository = getOrCheckoutRepository(repoUrl); repository.setParticipation(participation); return repository; } /** * Get the local repository for a given remote repository URL. * If the local repo does not exist yet, it will be checked out. * * @param repoUrl The remote repository. * @return * @throws IOException * @throws GitAPIException */ public Repository getOrCheckoutRepository(URL repoUrl) throws IOException, GitAPIException { Path localPath = new java.io.File(REPO_CLONE_PATH + folderNameForRepositoryUrl(repoUrl)).toPath(); // check if Repository object already created and available in cachedRepositories if (cachedRepositories.containsKey(localPath)) { return cachedRepositories.get(localPath); } // Check if the repository is already checked out on the server if (!Files.exists(localPath)) { // Repository is not yet available on the server // We need to check it out from the remote repositroy log.debug("Cloning from " + repoUrl + " to " + localPath); Git.cloneRepository() .setURI(repoUrl.toString()) .setCredentialsProvider(new UsernamePasswordCredentialsProvider(GIT_USER, GIT_PASSWORD)) .setDirectory(localPath.toFile()) .call(); } else { log.debug("Repository at " + localPath + " already exists"); } // Open the repository from the filesystem FileRepositoryBuilder builder = new FileRepositoryBuilder(); builder.setGitDir(new java.io.File(localPath + "/.git")) .readEnvironment() // scan environment GIT_* variables .findGitDir() .setup(); // Create the JGit repository object Repository repository = new Repository(builder); repository.setLocalPath(localPath); // Cache the JGit repository object for later use // Avoids the expensive re-opening of local repositories cachedRepositories.put(localPath, repository); return repository; } /** * Commits with the given message into the repository and pushes it to the remote. * * @param repo Local Repository Object. * @param message Commit Message * @throws GitAPIException */ public void commitAndPush(Repository repo, String message) throws GitAPIException { Git git = new Git(repo); git.commit().setMessage(message).setAllowEmpty(true).setCommitter(GIT_NAME, GIT_EMAIL).call(); git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(GIT_USER, GIT_PASSWORD)).call(); } /** * Stage all files in the repo including new files. * * @param repo * @throws GitAPIException */ public void stageAllChanges(Repository repo) throws GitAPIException { Git git = new Git(repo); // stage deleted files: http://stackoverflow.com/a/35601677/4013020 git.add().setUpdate(true).addFilepattern(".").call(); // stage new files git.add().addFilepattern(".").call(); } /** * Pulls from remote repository. * * @param repo Local Repository Object. * @return The PullResult which contains FetchResult and MergeResult. * @throws GitAPIException */ public PullResult pull(Repository repo) throws GitAPIException { Git git = new Git(repo); // flush cache of files repo.setFiles(null); return git.pull().setCredentialsProvider(new UsernamePasswordCredentialsProvider(GIT_USER, GIT_PASSWORD)).call(); } /** * List all files in the repository * * @param repo Local Repository Object. * @return Collection of File objects */ public Collection<File> listFiles(Repository repo) { // Check if list of files is already cached if(repo.getFiles() == null) { Iterator<java.io.File> itr = FileUtils.iterateFiles(repo.getLocalPath().toFile(), HiddenFileFilter.VISIBLE, HiddenFileFilter.VISIBLE); Collection<File> files = new LinkedList<>(); while(itr.hasNext()) { files.add(new File(itr.next(), repo)); } // Cache the list of files // Avoid expensive rescanning repo.setFiles(files); } return repo.getFiles(); } /** * Get a specific file by name. Makes sure the file is actually part of the repository. * * @param repo Local Repository Object. * @param filename String of zje filename (including path) * @return The File object */ public Optional<File> getFileByName(Repository repo, String filename) { // Makes sure the requested file is part of the scanned list of files. // Ensures that it is not possible to do bad things like filename="../../passwd" Iterator<File> itr = listFiles(repo).iterator(); while (itr.hasNext()) { File file = itr.next(); if(file.toString().equals(filename)) { return Optional.of(file); } } return Optional.empty(); } /** * Checks if no differences exist between the working-tree, the index, and the current HEAD. * * @param repo Local Repository Object. * @return True if the status is clean * @throws GitAPIException */ public Boolean isClean(Repository repo) throws GitAPIException { Git git = new Git(repo); Status status = git.status().call(); return status.isClean(); } /** * Deletes a local repository folder. * * @param repo Local Repository Object. * @throws IOException */ public void deleteLocalRepository(Repository repo) throws IOException { Path repoPath = repo.getLocalPath(); cachedRepositories.remove(repoPath); FileUtils.deleteDirectory(repoPath.toFile()); repo.setFiles(null); log.debug("Deleted Repository at " + repoPath); } /** * Deletes a local repository folder for a Participation. * * @param participation Participation Object. * @throws IOException */ public void deleteLocalRepository(Participation participation) throws IOException { Path repoPath = new java.io.File(REPO_CLONE_PATH + folderNameForRepositoryUrl(participation.getRepositoryUrlAsUrl())).toPath(); cachedRepositories.remove(repoPath); if (Files.exists(repoPath)) { FileUtils.deleteDirectory(repoPath.toFile()); log.debug("Deleted Repository at " + repoPath); } } /** * Generates the unique local folder name for a given remote repository URL. * * @param repoUrl URL of the remote repository. * @return * @throws MalformedURLException */ public String folderNameForRepositoryUrl(URL repoUrl) throws MalformedURLException { String path = repoUrl.getPath(); path = path.replaceAll(".git$", ""); path = path.replaceAll("/$", ""); path = path.replaceAll("^/", ""); path = path.replaceAll("^scm/", ""); return path; } }
mit
tcsiwula/java_code
classes/cs112/Projects/project2/src/Cat.java
771
//******************************************************************************************* // Cat.java created by Author: @Tim_Siwula on Mar 26, 2014 // // Description: //******************************************************************************************* public class Cat extends Pet { public Cat(String type, String breed, String name, String size, String age, String gender, boolean booleanValue, String location) { super(type, breed, name, size, age, gender, booleanValue, location); // TODO Auto-generated constructor stub } // --------------------------------------------------------------------------------- // Instance variables // --------------------------------------------------------------------------------- }
mit
alvinlyt94/CZ2002-OBJECT-ORIENTED-DESIGN-PROGRAMMING
workspace/StuPlanner/src/planner/manager/IndexMgr.java
2935
package planner.manager; import java.io.*; import java.text.*; import java.util.*; import planner.model.Index; import planner.model.Lesson; import planner.model.StudentCourse; public class IndexMgr { private static Scanner sc = new Scanner(System.in); public static void updateVacancy(String courseCode) throws IOException, ParseException{ ArrayList<Index> indexList = DataListMgr.getIndexes(); PrintMgr.printIndexList(courseCode); System.out.println(); System.out.print("Please select one of the index number to modify vancancy amount: "); int indexNumber = sc.nextInt(); sc.nextLine(); for (Index i : indexList) { if(i.equals(indexNumber)){ System.out.println("Index Name\t Vacancy"); System.out.println("----------------------------------------"); System.out.print(i.getIndexNumber() + "\t\t "); System.out.println(i.getVacancy()); System.out.println(); System.out.print("Please enter new amount of Vacancy: "); int vc = sc.nextInt(); sc.nextLine(); indexList.remove(i); Index newIndex = new Index(courseCode, i.getIndexNumber(), i.getTutorialGroup(), vc, i.getWaitingList()); DataListMgr.writeObject(newIndex); NotificationMgr.sendAlertWaitlist(i.getIndexNumber()); break; } } } public static void updateIndex(String courseCode) throws IOException, ParseException{ ArrayList<Index> indexList = DataListMgr.getIndexes(); ArrayList<Lesson> lessonList = DataListMgr.getLessons(); PrintMgr.printIndexList(courseCode); System.out.println(); System.out.print("Please enter index number that you want to modify: "); int indexNumber = sc.nextInt(); sc.nextLine(); System.out.print("Please enter new index number: "); int newIndexNumber = sc.nextInt(); sc.nextLine(); for(Index i : indexList){ if(i.equals(indexNumber)){ indexList.remove(i); Index newIndex = new Index(courseCode, newIndexNumber, i.getTutorialGroup(), i.getVacancy(), i.getWaitingList()); DataListMgr.writeObject(newIndex); //updating studentCourses info data ArrayList<StudentCourse> studentCourseList = DataListMgr.getStudentCourses(); for(StudentCourse sc : studentCourseList){ if(sc.getIndexNumber() == indexNumber){ studentCourseList.remove(sc); StudentCourse newSc = new StudentCourse(sc.getUserName(), sc.getCourseCode(), newIndexNumber, sc.getRegisterStatus()); DataListMgr.writeObject(newSc); } } int counter = 0; while(counter != lessonList.size()){ for(Lesson l : lessonList){ if(l.getIndexNumber() == indexNumber){ lessonList.remove(l); Lesson newLesson = new Lesson(newIndexNumber, l.getLessonType(), l.getLessonDay(), l.getLessonTime(), l.getLessonVenue()); DataListMgr.writeObject(newLesson); counter = 0; break; } counter++; } } } } } }
mit
ccjeng/TPTrash
app/src/main/java/com/oddsoft/tpetrash2/view/base/MVPBaseActivity.java
1286
package com.oddsoft.tpetrash2.view.base; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.google.android.gms.analytics.GoogleAnalytics; import com.oddsoft.tpetrash2.presenter.base.BasePresenter; /** * Created by andycheng on 2016/9/23. */ public abstract class MVPBaseActivity<V, T extends BasePresenter<V>> extends AppCompatActivity { protected T mPresenter; @SuppressWarnings("unchecked") @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // LayoutInflaterCompat.setFactory(getLayoutInflater(), new IconicsLayoutInflater(getDelegate())); mPresenter = createPresenter(); mPresenter.attachView((V) this); } @SuppressWarnings("unchecked") @Override public void onStart() { super.onStart(); GoogleAnalytics.getInstance(this).reportActivityStart(this); } @Override protected void onDestroy() { super.onDestroy(); mPresenter.detachView(); } @Override public void onStop() { super.onStop(); GoogleAnalytics.getInstance(this).reportActivityStop(this); } protected abstract T createPresenter(); }
mit
polysantiago/spring-boot-rest-client
src/test/java/io/github/polysantiago/spring/rest/RestClientListenableFutureAsyncTest.java
4576
package io.github.polysantiago.spring.rest; import io.github.polysantiago.spring.rest.RestClientListenableFutureAsyncTest.ListenableFutureAsyncFooClient; import org.junit.Test; import org.mockito.Mock; import org.springframework.context.annotation.Configuration; import org.springframework.http.*; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; import org.springframework.web.bind.annotation.*; import java.net.URI; import java.util.List; import java.util.Optional; import static org.mockito.Mockito.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; public class RestClientListenableFutureAsyncTest extends AbstractRestClientAsyncTest<ListenableFutureAsyncFooClient> { @Configuration @EnableRestClients(basePackageClasses = ListenableFutureAsyncFooClient.class) protected static class TestConfiguration extends BaseTestConfiguration { } @Mock private ListenableFutureCallback<Optional<String>> callback; @RestClient(value = "localhost", url = "${localhost.uri}") interface ListenableFutureAsyncFooClient extends AbstractRestClientAsyncTest.AsyncFooClient { @Override @RequestMapping ListenableFuture<String> defaultFoo(); @Override @RequestMapping(value = "/{id}") ListenableFuture<String> foo(@PathVariable("id") String id, @RequestParam("query") String query); @Override @RequestMapping(value = "/foo/{id}") ListenableFuture<Foo> getFoo(@PathVariable("id") String id); @Override @RequestMapping(value = "/fooList", method = RequestMethod.GET) ListenableFuture<List<Foo>> fooList(); @Override @RequestMapping(value = "/fooArray", method = RequestMethod.GET) ListenableFuture<Foo[]> fooArray(); @Override @RequestMapping(value = "/fooObject", method = RequestMethod.GET) ListenableFuture<Object> fooObject(); @Override @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) ListenableFuture<Foo> getFooWithAcceptHeader(@PathVariable("id") String id); @Override @RequestMapping(value = "/", method = RequestMethod.POST) ListenableFuture<Void> bar(String body); @Override @RequestMapping(value = "/", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) ListenableFuture<Void> barWithContentType(Foo foo); @Override @RequestMapping(method = RequestMethod.PUT) ListenableFuture<Void> barPut(String body); @Override @RequestMapping(method = RequestMethod.PATCH) ListenableFuture<Void> barPatch(String body); @Override @RequestMapping(method = RequestMethod.DELETE) ListenableFuture<Void> barDelete(String body); @Override @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) ListenableFuture<Optional<Foo>> tryNonEmptyOptional(); @Override @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) ListenableFuture<Optional<String>> tryEmptyOptional(); @Override @RequestMapping(produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) ListenableFuture<byte[]> raw(); @Override @RequestMapping(headers = "Some-Header:some-value") ListenableFuture<Void> fooWithHeaders(@RequestHeader("User-Id") String userId, @RequestHeader("Password") String password); @Override @RequestMapping ListenableFuture<ResponseEntity<String>> getEntity(); @Override @RequestMapping ListenableFuture<HttpEntity<String>> getHttpEntity(); @Override @PostForLocation(value = "/postForLocation") ListenableFuture<URI> postForLocation(String body); } @Test public void testRestClientWithEmptyOptionalAndCallback() throws Exception { asyncServer.expect(requestTo("http://localhost/")) .andExpect(method(HttpMethod.GET)) .andRespond(withStatus(HttpStatus.NOT_FOUND)); fooClient.tryEmptyOptional().addCallback(callback); verify(callback, timeout(10000)).onSuccess(eq(Optional.empty())); } }
mit
BlueWizardHat/2fa-demo
2fa-demo-webapp/src/main/java/net/bluewizardhat/tfa/web/data/dao/UserJpaDao.java
2475
/* * Copyright (C) 2014 BlueWizardHat * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.bluewizardhat.tfa.web.data.dao; import static org.springframework.transaction.annotation.Propagation.MANDATORY; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import net.bluewizardhat.tfa.web.data.entities.User; /** * Database access for the {@link User} entity * * @author bluewizardhat */ @Repository public class UserJpaDao { @PersistenceContext private EntityManager entityManager; @Transactional(propagation = MANDATORY) public void persist(User user) { entityManager.persist(user); } @Transactional(propagation = MANDATORY) public User update(User user) { return entityManager.merge(user); } @Transactional(propagation = MANDATORY) public void remove(User user) { entityManager.remove(user); } public User refreshFromDb(User user) { return entityManager.find(User.class, user.getId()); } public User findByUserName(String userName) { List<User> users = entityManager .createNamedQuery(User.FIND_BY_USERNAME, User.class) .setParameter("userName", userName) // .getSingleResult() would throw an exception if not found, we don't want that .getResultList(); return users.isEmpty() ? null: users.get(0); } }
mit
prasad-gowda/Design_Patterns
src/com/introduction/inheritence/Cat.java
183
package com.introduction.inheritence; /** * @author Prasad - 12/12/2016 */ public class Cat extends Animal { public Cat() { super(); setSound("Meow"); } }
mit
oxidy/animtools64
src/main/java/se/oxidev/animtools64/JacksonObjectMapper.java
480
package se.oxidev.animtools64; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonObjectMapper { private static ObjectMapper mapper; static { mapper = new ObjectMapper(); // Instead of @JsonIgnoreProperties(ignoreUnknown = true) mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } public static ObjectMapper getObjectMapper() { return mapper; } }
mit
jbekas/AND_PopularMovies
app/src/main/java/com/redgeckotech/popularmovies/model/Movie.java
7508
package com.redgeckotech.popularmovies.model; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.google.gson.annotations.SerializedName; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; import timber.log.Timber; public class Movie implements Parcelable { @SerializedName("id") protected int id; @SerializedName("adult") protected boolean adult; @SerializedName("backdrop_path") protected String backdropPath; @SerializedName("genre_ids") protected List<Integer> genreIds; @SerializedName("original_language") protected String originalLanguage; @SerializedName("original_title") protected String originalTitle; @SerializedName("overview") protected String overview; @SerializedName("popularity") protected double popularity; @SerializedName("poster_path") protected String posterPath; @SerializedName("release_date") protected String releaseDate; @SerializedName("title") protected String title; @SerializedName("video") protected boolean video; @SerializedName("vote_average") protected float voteAverage; @SerializedName("vote_count") protected int voteCount; public Movie() { } protected Movie(Parcel in) { this.id = in.readInt(); this.adult = in.readByte() != 0; this.backdropPath = in.readString(); this.genreIds = new ArrayList<Integer>(); in.readList(this.genreIds, Integer.class.getClassLoader()); this.originalLanguage = in.readString(); this.originalTitle = in.readString(); this.overview = in.readString(); this.popularity = in.readDouble(); this.posterPath = in.readString(); this.releaseDate = in.readString(); this.title = in.readString(); this.video = in.readByte() != 0; this.voteAverage = in.readFloat(); this.voteCount = in.readInt(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getOriginalTitle() { return originalTitle; } public void setOriginalTitle(String originalTitle) { this.originalTitle = originalTitle; } public boolean isAdult() { return adult; } public void setAdult(boolean adult) { this.adult = adult; } public String getBackdropPath() { return backdropPath; } public void setBackdropPath(String backdropPath) { this.backdropPath = backdropPath; } @NonNull public List<Integer> getGenreIds() { if (genreIds == null) { genreIds = new ArrayList<Integer>(); } return genreIds; } public void setGenreIds(List<Integer> genreIds) { if (genreIds == null) { this.genreIds = new ArrayList<>(); } else { this.genreIds = genreIds; } } @NonNull public String getGenreIdsAsString() { StringBuilder builder = new StringBuilder(); for (Integer id : getGenreIds()) { if (builder.length() > 0) { builder.append(","); } builder.append(id); } return builder.toString(); } public void setGenreIdsFromString(String genreIdString) { genreIds = new ArrayList<>(); if (genreIdString != null) { String[] array = genreIdString.split(","); for (String id : array) { genreIds.add(Integer.valueOf(id)); } } } public String getOriginalLanguage() { return originalLanguage; } public void setOriginalLanguage(String originalLanguage) { this.originalLanguage = originalLanguage; } public String getOverview() { return overview; } public void setOverview(String overview) { this.overview = overview; } public double getPopularity() { return popularity; } public void setPopularity(double popularity) { this.popularity = popularity; } public String getPosterPath() { return posterPath; } public void setPosterPath(String posterPath) { this.posterPath = posterPath; } public String getReleaseDate() { return releaseDate; } public void setReleaseDate(String releaseDate) { this.releaseDate = releaseDate; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean isVideo() { return video; } public void setVideo(boolean video) { this.video = video; } public float getVoteAverage() { return voteAverage; } public void setVoteAverage(float voteAverage) { this.voteAverage = voteAverage; } public int getVoteCount() { return voteCount; } public void setVoteCount(int voteCount) { this.voteCount = voteCount; } // Helper methods @Nullable public String getReleaseYear() { try { DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US); Date date = format.parse(releaseDate); SimpleDateFormat df = new SimpleDateFormat("yyyy", Locale.US); return df.format(date); } catch (ParseException e) { Timber.e(e, null); } return null; } @Override public String toString() { return "Movie{" + "id=" + id + ", adult=" + adult + ", backdropPath='" + backdropPath + '\'' + ", genreIds=" + genreIds + ", originalLanguage='" + originalLanguage + '\'' + ", originalTitle='" + originalTitle + '\'' + ", overview='" + overview + '\'' + ", popularity=" + popularity + ", posterPath='" + posterPath + '\'' + ", releaseDate='" + releaseDate + '\'' + ", title='" + title + '\'' + ", video=" + video + ", voteAverage=" + voteAverage + ", voteCount=" + voteCount + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.id); dest.writeByte(adult ? (byte) 1 : (byte) 0); dest.writeString(this.backdropPath); dest.writeList(this.genreIds); dest.writeString(this.originalLanguage); dest.writeString(this.originalTitle); dest.writeString(this.overview); dest.writeDouble(this.popularity); dest.writeString(this.posterPath); dest.writeString(this.releaseDate); dest.writeString(this.title); dest.writeByte(video ? (byte) 1 : (byte) 0); dest.writeFloat(this.voteAverage); dest.writeInt(this.voteCount); } public static final Creator<Movie> CREATOR = new Creator<Movie>() { @Override public Movie createFromParcel(Parcel source) { return new Movie(source); } @Override public Movie[] newArray(int size) { return new Movie[size]; } }; }
mit
yht-fand/cardone-platform-configuration
consumer-bak/src/test/java/top/cardone/func/v1/configuration/systemInfo/D0002FuncTest.java
3283
package top.cardone.func.v1.configuration.systemInfo; import com.google.common.base.Charsets; import com.google.common.collect.Maps; import com.google.gson.Gson; import top.cardone.CardoneConsumerApplication; import lombok.extern.log4j.Log4j2; import lombok.val; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.CollectionUtils; import top.cardone.context.ApplicationContextHolder; import java.util.Map; @Log4j2 @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = CardoneConsumerApplication.class, value = {"spring.profiles.active=test"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class D0002FuncTest { @Value("http://localhost:${server.port:8765}${server.servlet.context-path:}/v1/configuration/systemInfo/d0002.json") private String funcUrl; @Value("file:src/test/resources/top/cardone/func/v1/configuration/systemInfo/D0002FuncTest.func.input.json") private Resource funcInputResource; @Value("file:src/test/resources/top/cardone/func/v1/configuration/systemInfo/D0002FuncTest.func.output.json") private Resource funcOutputResource; @Test public void func() throws Exception { if (!funcInputResource.exists()) { FileUtils.write(funcInputResource.getFile(), "{}", Charsets.UTF_8); } val input = FileUtils.readFileToString(funcInputResource.getFile(), Charsets.UTF_8); Map<String, Object> parametersMap = ApplicationContextHolder.getBean(Gson.class).fromJson(input, Map.class); Assert.assertFalse("输入未配置", CollectionUtils.isEmpty(parametersMap)); Map<String, Object> output = Maps.newLinkedHashMap(); for (val parametersEntry : parametersMap.entrySet()) { val body = ApplicationContextHolder.getBean(Gson.class).toJson(parametersEntry.getValue()); val headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE); headers.set("collectionStationCodeForToken", parametersEntry.getKey().split(":")[0]); headers.set("token", ApplicationContextHolder.getBean(org.apache.shiro.authc.credential.PasswordService.class).encryptPassword(headers.get("collectionStationCodeForToken").get(0))); val httpEntity = new HttpEntity<>(body, headers); val json = new org.springframework.boot.test.web.client.TestRestTemplate().postForObject(funcUrl, httpEntity, String.class); val value = ApplicationContextHolder.getBean(Gson.class).fromJson(json, Map.class); output.put(parametersEntry.getKey(), value); } FileUtils.write(funcOutputResource.getFile(), ApplicationContextHolder.getBean(Gson.class).toJson(output), Charsets.UTF_8); } }
mit
JPMoresmau/sqlg
sqlg-core/src/main/java/org/umlg/sqlg/step/SqlgAddVertexStartStep.java
4361
package org.umlg.sqlg.step; import org.apache.tinkerpop.gremlin.process.traversal.*; import org.apache.tinkerpop.gremlin.process.traversal.step.Mutating; import org.apache.tinkerpop.gremlin.process.traversal.step.Parameterizing; import org.apache.tinkerpop.gremlin.process.traversal.step.Scoping; import org.apache.tinkerpop.gremlin.process.traversal.step.TraversalParent; import org.apache.tinkerpop.gremlin.process.traversal.step.util.Parameters; import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.CallbackRegistry; import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.Event; import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.ListCallbackRegistry; import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategy; import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement; import org.apache.tinkerpop.gremlin.process.traversal.util.FastNoSuchElementException; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.util.StringFactory; import org.umlg.sqlg.structure.SqlgTraverserGenerator; import java.util.List; import java.util.Set; /** * @author Pieter Martin (https://github.com/pietermartin) * Date: 2018/08/26 */ public class SqlgAddVertexStartStep extends SqlgAbstractStep<Vertex, Vertex> implements Mutating<Event.VertexAddedEvent>, TraversalParent, Parameterizing, Scoping { private Parameters parameters; private boolean first = true; private CallbackRegistry<Event.VertexAddedEvent> callbackRegistry; public SqlgAddVertexStartStep(final Traversal.Admin traversal, Parameters parameters) { super(traversal); this.parameters = parameters; } @Override public void configure(final Object... keyValues) { this.parameters.set(this, keyValues); } @Override public Parameters getParameters() { return this.parameters; } @Override public Set<String> getScopeKeys() { return this.parameters.getReferencedLabels(); } @Override public <S, E> List<Traversal.Admin<S, E>> getLocalChildren() { return this.parameters.getTraversals(); } @Override protected Traverser.Admin<Vertex> processNextStart() { if (this.first) { this.first = false; final SqlgTraverserGenerator generator = SqlgTraverserGenerator.instance(); final Vertex vertex = this.getTraversal().getGraph().get().addVertex( this.parameters.getKeyValues( generator.generate(false, (Step)this, 1L, false, false) )); if (this.callbackRegistry != null && !this.callbackRegistry.getCallbacks().isEmpty()) { final EventStrategy eventStrategy = getTraversal().getStrategies().getStrategy(EventStrategy.class).get(); final Event.VertexAddedEvent vae = new Event.VertexAddedEvent(eventStrategy.detach(vertex)); this.callbackRegistry.getCallbacks().forEach(c -> c.accept(vae)); } return generator.generate(vertex, (Step)this, 1L, false, false); } else throw FastNoSuchElementException.instance(); } @Override public CallbackRegistry<Event.VertexAddedEvent> getMutatingCallbackRegistry() { if (null == this.callbackRegistry) this.callbackRegistry = new ListCallbackRegistry<>(); return this.callbackRegistry; } @Override public Set<TraverserRequirement> getRequirements() { return this.getSelfAndChildRequirements(); } @Override public int hashCode() { return super.hashCode() ^ this.parameters.hashCode(); } @Override public void reset() { super.reset(); } @Override public String toString() { return StringFactory.stepString(this, this.parameters); } @Override public void setTraversal(final Traversal.Admin<?, ?> parentTraversal) { super.setTraversal(parentTraversal); this.parameters.getTraversals().forEach(this::integrateChild); } @Override public SqlgAddVertexStartStep clone() { final SqlgAddVertexStartStep clone = (SqlgAddVertexStartStep) super.clone(); clone.parameters = this.parameters.clone(); return clone; } }
mit
birdcage/soundcloud-web-api-android
soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Group.java
1700
/* * The MIT License (MIT) * * Copyright (c) 2015 Jacob Lubecki * * 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.jlubecki.soundcloud.webapi.android.models; /** * Representation of a SoundCloud Group. * * @see <a href="https://developers.soundcloud.com/docs/api/reference#groups"> * SoundCloud Group Reference</a> */ public class Group { private String id; private String created_at; private String permalink; private String name; private String short_description; private String description; private String uri; private String artwork_url; private String permalink_url; private MiniUser creator; }
mit
taylorlloyd/Graviton
src/game/LevelPackPane.java
5117
package game; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.event.*; import java.io.FileInputStream; import java.io.InputStream; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; public class LevelPackPane extends AnimatablePane { public static Image background; boolean back=true; public LevelPackPane(LevelPack pack) { if(background == null) background = DataManager.loadImage("horizon.png"); setBackground(new Color(0,0,0,0)); setLayout(new GridBagLayout()); InternalPane buttonlist = new InternalPane(); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx=0; gbc.gridy=0; gbc.fill=gbc.HORIZONTAL; gbc.weightx=1; gbc.insets=new Insets(5, 10, 5, 10);//tlbr for(int i=0;i<pack.getLevelCount();i++) { buttonlist.add(new LevelButton(pack.getLevel(i)),gbc); gbc.gridy++; } JScrollPane jsp = new JScrollPane(buttonlist); jsp.setBorder(BorderFactory.createEmptyBorder()); gbc.gridx=0; gbc.gridy=0; gbc.fill=gbc.NONE; gbc.insets=new Insets(0, 0, 0, 0); add(new TitlePane(pack),gbc); gbc.gridy=1; gbc.fill=gbc.VERTICAL; gbc.weightx=1; gbc.weighty=1; add(jsp,gbc); } public void paintComponent(Graphics g) { paintComponent(g,back); } public void paint(Graphics g, boolean paintBackground){ back=paintBackground; paint(g); back=true; } @Override public void paintComponent(Graphics g, boolean paintBackground) { if(paintBackground) g.drawImage(background, 0, 0, null); } } class InternalPane extends JPanel { public InternalPane() { super(); setBackground(new Color(0,0,0,0)); setLayout(new GridBagLayout()); } public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); d.width =400; return d; } public Dimension getMinimumSize() { Dimension d = super.getMinimumSize(); d.width =400; return d; } public Dimension getMaximumSize() { Dimension d = super.getMaximumSize(); d.width =400; return d; } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g2.drawImage(LevelPackPane.background, -1*this.getX(), -1*this.getY(), null); g2.setColor(new Color(0,0,0,160)); g2.fillRoundRect(6, -25, getWidth()-12, getHeight()+25, 14, 14); g2.setColor(new Color(255,255,255,80)); g2.setStroke(new BasicStroke(6)); g2.drawRoundRect(3, -28, getWidth()-6, getHeight()+25, 14, 14); } } class TitlePane extends JPanel implements ActionListener{ public TitlePane(LevelPack pack) { setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); Font font=DataManager.loadFont("text.ttf"); JButton back = new JButton(new ImageIcon(DataManager.loadImage("back.png"))); back.setBorder(BorderFactory.createEmptyBorder(0,0,0,0)); back.setRolloverIcon(new ImageIcon(DataManager.loadImage("back_over.png"))); back.addActionListener(this); back.setActionCommand("back"); back.setBorderPainted(false); JLabel name = new JLabel(pack.name.substring(0,1).toUpperCase() + pack.name.substring(1).toLowerCase()); name.setFont(font.deriveFont((float)30)); name.setForeground(new Color(255,255,255,80)); JLabel complete = new JLabel("Complete: "+GameState.highestCompleteLevel(pack.name)+"/"+pack.getLevelCount()); complete.setFont(font.deriveFont((float)20)); complete.setForeground(new Color(255,255,255,80)); gbc.gridx=0; gbc.gridy=0; gbc.insets=new Insets(10,0,0,0); add(back, gbc); gbc.gridx=1; gbc.insets=new Insets(10, 30, 0, 30);//tlbr add(name, gbc); gbc.insets=new Insets(10, 0, 0, 0);//tlbr gbc.gridx=2; add(complete, gbc); } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(new Color(0,0,0,160)); g2.fillRoundRect(6, 6, getWidth()-12, getHeight()+25, 14, 14); g2.setColor(new Color(255,255,255,80)); g2.setStroke(new BasicStroke(6)); g2.drawRoundRect(3, 3, getWidth()-6, getHeight()+25, 14, 14); } public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); d.width =400; return d; } public Dimension getMinimumSize() { Dimension d = super.getMinimumSize(); d.width =400; return d; } public Dimension getMaximumSize() { Dimension d = super.getMaximumSize(); d.width =400; return d; } @Override public void actionPerformed(ActionEvent e) { Window.current.toPane(Window.current.levelPane); } }
mit
mbuzdalov/non-dominated-sorting
implementations/src/main/java/ru/ifmo/nds/jfb/JFBInt.java
3086
package ru.ifmo.nds.jfb; import ru.ifmo.nds.util.RankQueryStructureInt; public class JFBInt extends JFBBase { private RankQueryStructureInt rankQuery; private int[] compressedOrdinates; public JFBInt(RankQueryStructureInt rankQueryStructure, int maximumDimension, int allowedThreads, HybridAlgorithmWrapper hybridWrapper) { super(rankQueryStructure.maximumPoints(), maximumDimension, rankQueryStructure.supportsMultipleThreads() ? allowedThreads : 1, hybridWrapper, "ordinate compression, data structure = " + rankQueryStructure.getName()); compressedOrdinates = new int[rankQueryStructure.maximumPoints()]; this.rankQuery = rankQueryStructure; } @Override protected void closeImpl() { super.closeImpl(); rankQuery = null; compressedOrdinates = null; } @Override protected void postTransposePointHook(int newN) { sorter.compressCoordinates(transposedPoints[1], indices, compressedOrdinates, 0, newN); } @Override protected int sweepA(int from, int until) { int[] local = compressedOrdinates; RankQueryStructureInt.RangeHandle rankQuery = this.rankQuery.createHandle(from, from, until, indices, local); int minOverflow = until; for (int i = from; i < until; ++i) { int curr = indices[i]; int currY = local[curr]; int result = Math.max(ranks[curr], rankQuery.getMaximumWithKeyAtMost(currY, ranks[curr]) + 1); ranks[curr] = result; if (result <= maximalMeaningfulRank) { rankQuery = rankQuery.put(currY, result); } else if (minOverflow > i) { minOverflow = i; } } return JFBBase.kickOutOverflowedRanks(indices, ranks, maximalMeaningfulRank, minOverflow, until); } @Override protected int sweepB(int goodFrom, int goodUntil, int weakFrom, int weakUntil, int tempFrom) { int[] local = compressedOrdinates; RankQueryStructureInt.RangeHandle rankQuery = this.rankQuery.createHandle(tempFrom, goodFrom, goodUntil, indices, local); int goodI = goodFrom; int minOverflow = weakUntil; for (int weakI = weakFrom; weakI < weakUntil; ++weakI) { int weakCurr = indices[weakI]; while (goodI < goodUntil && indices[goodI] < weakCurr) { int goodCurr = indices[goodI]; rankQuery = rankQuery.put(local[goodCurr], ranks[goodCurr]); ++goodI; } int result = Math.max(ranks[weakCurr], rankQuery.getMaximumWithKeyAtMost(local[weakCurr], ranks[weakCurr]) + 1); ranks[weakCurr] = result; if (result > maximalMeaningfulRank && minOverflow > weakI) { minOverflow = weakI; } } return JFBBase.kickOutOverflowedRanks(indices, ranks, maximalMeaningfulRank, minOverflow, weakUntil); } }
mit