text
stringlengths
10
2.72M
package generator.util.python; import java.io.OutputStream; public class PythonOutputStream extends OutputStream { private String buffer; public PythonOutputStream () { buffer = ""; } public void write(int b) { byte[] bytes = new byte[1]; bytes[0] = (byte) (b & 0xff); String letter = new String(bytes); if (bytes[0] == 10) { buffer += ","; } buffer = buffer + letter; if (buffer.endsWith("\n")) { buffer = buffer.replace("\n", "").replace("\r", ""); } } public void flush() { // Commit the buffer to db here // buffer = ""; } public String getBuffer() { return buffer.substring(0, buffer.length() - 1); } }
import java.util.ArrayList; public class RecipeBook{ private ArrayList<CookingRecipe> recipes; private String name; public RecipeBook(String bookName){ this.name = bookName; recipes = new ArrayList<CookingRecipe>(); } public CookingRecipe addRecipe(String name, RecipeIngredient[] ingredients){ if (getRecipe(name) == null){ return null; } else{ CookingRecipe newRecipe = new CookingRecipe(name); for (RecipeIngredient i: ingredients){ newRecipe.addOrUpdateRecipeIngredient(i, i.getQuantity()); } recipes.add(newRecipe); return newRecipe; } } public CookingRecipe getRecipe(String recipeName){ for (CookingRecipe recipe: recipes){ if (recipe.getName().equals(recipeName)){ return recipe; } } return null; } public CookingRecipe removeRecipe(String name){ CookingRecipe recipe = getRecipe(name); recipes.remove(recipe); return recipe; } public CookingRecipe[] findRecipes(RecipeIngredient[] ingredients){ ArrayList<CookingRecipe> matchingRecipes = new ArrayList<CookingRecipe>(); boolean hasIngredients=true; for (CookingRecipe recipe: recipes){ for (RecipeIngredient i: ingredients){ hasIngredients = hasIngredients && recipe.getRecipeIngredient(i) != null; } if (hasIngredients){ matchingRecipes.add(recipe); } } if (matchingRecipes.size()>0){ return (CookingRecipe[])matchingRecipes.toArray(); } else{ return null; } } public CookingRecipe[] findRecipesWithFewIngredients(int numberOfIngredients){ ArrayList<CookingRecipe> matchingRecipes = new ArrayList<CookingRecipe>(); for (CookingRecipe recipe: recipes){ if (recipe.getNumberOfIngredients() < numberOfIngredients){ matchingRecipes.add(recipe); } } if (matchingRecipes.size()>0){ return (CookingRecipe[])matchingRecipes.toArray(); } else{ return null; } } public CookingRecipe[] findRecipesLowCalories(){ ArrayList<CookingRecipe> matchingRecipes = new ArrayList<CookingRecipe>(); float lowestCalories, currentCalories; if (recipes.size()>0){ lowestCalories = recipes.get(0).calculateCalories(); for (CookingRecipe recipe: recipes){ currentCalories = recipe.calculateCalories(); if (currentCalories < lowestCalories){ matchingRecipes.clear(); matchingRecipes.add(recipe); lowestCalories = currentCalories; } else if (currentCalories == lowestCalories){ matchingRecipes.add(recipe); } } if (matchingRecipes.size()>0){ return (CookingRecipe[])matchingRecipes.toArray(); } } return null; } public String toString(){ String str = name; for (CookingRecipe r : recipes){ str+="\n"+r.toString()+"\n"; } return str; } }
package com.beta.rulestrategy; public interface Strategy { /** * @param message * @return */ String applyRule(String message); Rule getRule(); }
package com.coordinatorpattern.scene.main; import android.content.Context; public interface MainCoordinatorDelegate { void goToHome(Context ctx); }
package com.gaoshin.coupon.db; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class UserRoutingDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return UserContextHolder.getUserState(); } }
package com.restapi.repository; import com.restapi.model.quizDuel.Score; import org.springframework.data.mongodb.repository.MongoRepository; import java.util.List; public interface ScoreRepository extends MongoRepository<Score, String> { public List<Score> findAllByAutor(String autor); public List<Score> findAllByOpponent(String opponent); }
package utility; import java.util.concurrent.TimeUnit; public class printWithDelays{ public void DelayedPrint(String data, long delay){ try{ for (char ch:data.toCharArray()) { System.out.print(ch); TimeUnit.MILLISECONDS.sleep(delay); } } catch (Exception e){ e.printStackTrace(); } } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.expression.spel; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.core.convert.TypeDescriptor; import org.springframework.expression.AccessException; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionInvocationTargetException; import org.springframework.expression.MethodExecutor; import org.springframework.expression.MethodFilter; import org.springframework.expression.MethodResolver; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.testresources.PlaceOfBirth; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatException; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests invocation of methods. * * @author Andy Clement * @author Phillip Webb * @author Sam Brannen */ public class MethodInvocationTests extends AbstractExpressionTests { @Test public void testSimpleAccess01() { evaluate("getPlaceOfBirth().getCity()", "SmilJan", String.class); } @Test public void testStringClass() { evaluate("new java.lang.String('hello').charAt(2)", 'l', Character.class); evaluate("new java.lang.String('hello').charAt(2).equals('l'.charAt(0))", true, Boolean.class); evaluate("'HELLO'.toLowerCase()", "hello", String.class); evaluate("' abcba '.trim()", "abcba", String.class); } @Test public void testNonExistentMethods() { // name is ok but madeup() does not exist evaluateAndCheckError("name.madeup()", SpelMessage.METHOD_NOT_FOUND, 5); } @Test public void testWidening01() { // widening of int 3 to double 3 is OK evaluate("new Double(3.0d).compareTo(8)", -1, Integer.class); evaluate("new Double(3.0d).compareTo(3)", 0, Integer.class); evaluate("new Double(3.0d).compareTo(2)", 1, Integer.class); } @Test public void testArgumentConversion01() { // Rely on Double>String conversion for calling startsWith() evaluate("new String('hello 2.0 to you').startsWith(7.0d)", false, Boolean.class); evaluate("new String('7.0 foobar').startsWith(7.0d)", true, Boolean.class); } @Test public void testMethodThrowingException_SPR6760() { // Test method on inventor: throwException() // On 1 it will throw an IllegalArgumentException // On 2 it will throw a RuntimeException // On 3 it will exit normally // In each case it increments the Inventor field 'counter' when invoked SpelExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression("throwException(#bar)"); // Normal exit StandardEvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext(); eContext.setVariable("bar", 3); Object o = expr.getValue(eContext); assertThat(o).isEqualTo(3); assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(1); // Now the expression has cached that throwException(int) is the right thing to call // Let's change 'bar' to be a PlaceOfBirth which indicates the cached reference is // out of date. eContext.setVariable("bar", new PlaceOfBirth("London")); o = expr.getValue(eContext); assertThat(o).isEqualTo("London"); // That confirms the logic to mark the cached reference stale and retry is working // Now let's cause the method to exit via exception and ensure it doesn't cause a retry. // First, switch back to throwException(int) eContext.setVariable("bar", 3); o = expr.getValue(eContext); assertThat(o).isEqualTo(3); assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(2); // Now cause it to throw an exception: eContext.setVariable("bar", 1); assertThatException() .isThrownBy(() -> expr.getValue(eContext)) .isNotInstanceOf(SpelEvaluationException.class); // If counter is 4 then the method got called twice! assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(3); eContext.setVariable("bar", 4); assertThatExceptionOfType(ExpressionInvocationTargetException.class).isThrownBy(() -> expr.getValue(eContext)); // If counter is 5 then the method got called twice! assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(4); } /** * Check on first usage (when the cachedExecutor in MethodReference is null) that the exception is not wrapped. */ @Test public void testMethodThrowingException_SPR6941() { // Test method on inventor: throwException() // On 1 it will throw an IllegalArgumentException // On 2 it will throw a RuntimeException // On 3 it will exit normally // In each case it increments the Inventor field 'counter' when invoked SpelExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression("throwException(#bar)"); context.setVariable("bar", 2); assertThatException() .isThrownBy(() -> expr.getValue(context)) .isNotInstanceOf(SpelEvaluationException.class); } @Test public void testMethodThrowingException_SPR6941_2() { // Test method on inventor: throwException() // On 1 it will throw an IllegalArgumentException // On 2 it will throw a RuntimeException // On 3 it will exit normally // In each case it increments the Inventor field 'counter' when invoked SpelExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression("throwException(#bar)"); context.setVariable("bar", 4); assertThatExceptionOfType(ExpressionInvocationTargetException.class) .isThrownBy(() -> expr.getValue(context)) .satisfies(ex -> assertThat(ex.getCause().getClass().getName()).isEqualTo( "org.springframework.expression.spel.testresources.Inventor$TestException")); } @Test public void testMethodFiltering_SPR6764() { SpelExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); context.setRootObject(new TestObject()); LocalFilter filter = new LocalFilter(); context.registerMethodFilter(TestObject.class,filter); // Filter will be called but not do anything, so first doit() will be invoked SpelExpression expr = (SpelExpression) parser.parseExpression("doit(1)"); String result = expr.getValue(context, String.class); assertThat(result).isEqualTo("1"); assertThat(filter.filterCalled).isTrue(); // Filter will now remove non @Anno annotated methods filter.removeIfNotAnnotated = true; filter.filterCalled = false; expr = (SpelExpression) parser.parseExpression("doit(1)"); result = expr.getValue(context, String.class); assertThat(result).isEqualTo("double 1.0"); assertThat(filter.filterCalled).isTrue(); // check not called for other types filter.filterCalled = false; context.setRootObject(new String("abc")); expr = (SpelExpression) parser.parseExpression("charAt(0)"); result = expr.getValue(context, String.class); assertThat(result).isEqualTo("a"); assertThat(filter.filterCalled).isFalse(); // check de-registration works filter.filterCalled = false; context.registerMethodFilter(TestObject.class,null);//clear filter context.setRootObject(new TestObject()); expr = (SpelExpression) parser.parseExpression("doit(1)"); result = expr.getValue(context, String.class); assertThat(result).isEqualTo("1"); assertThat(filter.filterCalled).isFalse(); } @Test public void testAddingMethodResolvers() { StandardEvaluationContext ctx = new StandardEvaluationContext(); // reflective method accessor is the only one by default List<MethodResolver> methodResolvers = ctx.getMethodResolvers(); assertThat(methodResolvers).hasSize(1); MethodResolver dummy = new DummyMethodResolver(); ctx.addMethodResolver(dummy); assertThat(ctx.getMethodResolvers()).hasSize(2); List<MethodResolver> copy = new ArrayList<>(ctx.getMethodResolvers()); assertThat(ctx.removeMethodResolver(dummy)).isTrue(); assertThat(ctx.removeMethodResolver(dummy)).isFalse(); assertThat(ctx.getMethodResolvers()).hasSize(1); ctx.setMethodResolvers(copy); assertThat(ctx.getMethodResolvers()).hasSize(2); } @Test public void testVarargsInvocation01() { // Calling 'public String aVarargsMethod(String... strings)' evaluate("aVarargsMethod('a','b','c')", "[a, b, c]", String.class); evaluate("aVarargsMethod('a')", "[a]", String.class); evaluate("aVarargsMethod()", "[]", String.class); evaluate("aVarargsMethod(1,2,3)", "[1, 2, 3]", String.class); // all need converting to strings evaluate("aVarargsMethod(1)", "[1]", String.class); // needs string conversion evaluate("aVarargsMethod(1,'a',3.0d)", "[1, a, 3.0]", String.class); // first and last need conversion evaluate("aVarargsMethod(new String[]{'a','b','c'})", "[a, b, c]", String.class); evaluate("aVarargsMethod(new String[]{})", "[]", String.class); evaluate("aVarargsMethod(null)", "[null]", String.class); evaluate("aVarargsMethod(null,'a')", "[null, a]", String.class); evaluate("aVarargsMethod('a',null,'b')", "[a, null, b]", String.class); } @Test public void testVarargsInvocation02() { // Calling 'public String aVarargsMethod2(int i, String... strings)' evaluate("aVarargsMethod2(5,'a','b','c')", "5-[a, b, c]", String.class); evaluate("aVarargsMethod2(2,'a')", "2-[a]", String.class); evaluate("aVarargsMethod2(4)", "4-[]", String.class); evaluate("aVarargsMethod2(8,2,3)", "8-[2, 3]", String.class); evaluate("aVarargsMethod2(2,'a',3.0d)", "2-[a, 3.0]", String.class); evaluate("aVarargsMethod2(8,new String[]{'a','b','c'})", "8-[a, b, c]", String.class); evaluate("aVarargsMethod2(8,new String[]{})", "8-[]", String.class); evaluate("aVarargsMethod2(8,null)", "8-[null]", String.class); evaluate("aVarargsMethod2(8,null,'a')", "8-[null, a]", String.class); evaluate("aVarargsMethod2(8,'a',null,'b')", "8-[a, null, b]", String.class); } @Test public void testVarargsInvocation03() { // Calling 'public int aVarargsMethod3(String str1, String... strings)' - returns all strings concatenated with "-" // No conversion necessary evaluate("aVarargsMethod3('x')", "x", String.class); evaluate("aVarargsMethod3('x', 'a')", "x-a", String.class); evaluate("aVarargsMethod3('x', 'a', 'b', 'c')", "x-a-b-c", String.class); // Conversion necessary evaluate("aVarargsMethod3(9)", "9", String.class); evaluate("aVarargsMethod3(8,2,3)", "8-2-3", String.class); evaluate("aVarargsMethod3('2','a',3.0d)", "2-a-3.0", String.class); evaluate("aVarargsMethod3('8',new String[]{'a','b','c'})", "8-a-b-c", String.class); // Individual string contains a comma with multiple varargs arguments evaluate("aVarargsMethod3('foo', ',', 'baz')", "foo-,-baz", String.class); evaluate("aVarargsMethod3('foo', 'bar', ',baz')", "foo-bar-,baz", String.class); evaluate("aVarargsMethod3('foo', 'bar,', 'baz')", "foo-bar,-baz", String.class); // Individual string contains a comma with single varargs argument. // Reproduces https://github.com/spring-projects/spring-framework/issues/27582 evaluate("aVarargsMethod3('foo', ',')", "foo-,", String.class); evaluate("aVarargsMethod3('foo', ',bar')", "foo-,bar", String.class); evaluate("aVarargsMethod3('foo', 'bar,')", "foo-bar,", String.class); evaluate("aVarargsMethod3('foo', 'bar,baz')", "foo-bar,baz", String.class); } @Test public void testVarargsOptionalInvocation() { // Calling 'public String optionalVarargsMethod(Optional<String>... values)' evaluate("optionalVarargsMethod()", "[]", String.class); evaluate("optionalVarargsMethod(new String[0])", "[]", String.class); evaluate("optionalVarargsMethod('a')", "[Optional[a]]", String.class); evaluate("optionalVarargsMethod('a','b','c')", "[Optional[a], Optional[b], Optional[c]]", String.class); evaluate("optionalVarargsMethod(9)", "[Optional[9]]", String.class); evaluate("optionalVarargsMethod(2,3)", "[Optional[2], Optional[3]]", String.class); evaluate("optionalVarargsMethod('a',3.0d)", "[Optional[a], Optional[3.0]]", String.class); evaluate("optionalVarargsMethod(new String[]{'a','b','c'})", "[Optional[a], Optional[b], Optional[c]]", String.class); evaluate("optionalVarargsMethod(null)", "[Optional.empty]", String.class); evaluate("optionalVarargsMethod(null,'a')", "[Optional.empty, Optional[a]]", String.class); evaluate("optionalVarargsMethod('a',null,'b')", "[Optional[a], Optional.empty, Optional[b]]", String.class); } @Test public void testInvocationOnNullContextObject() { evaluateAndCheckError("null.toString()",SpelMessage.METHOD_CALL_ON_NULL_OBJECT_NOT_ALLOWED); } @Test public void testMethodOfClass() throws Exception { Expression expression = parser.parseExpression("getName()"); Object value = expression.getValue(new StandardEvaluationContext(String.class)); assertThat(value).isEqualTo("java.lang.String"); } @Test public void invokeMethodWithoutConversion() throws Exception { final BytesService service = new BytesService(); byte[] bytes = new byte[100]; StandardEvaluationContext context = new StandardEvaluationContext(bytes); context.setBeanResolver((context1, beanName) -> ("service".equals(beanName) ? service : null)); Expression expression = parser.parseExpression("@service.handleBytes(#root)"); byte[] outBytes = expression.getValue(context, byte[].class); assertThat(outBytes).isSameAs(bytes); } // Simple filter static class LocalFilter implements MethodFilter { public boolean removeIfNotAnnotated = false; public boolean filterCalled = false; private boolean isAnnotated(Method method) { Annotation[] anns = method.getAnnotations(); if (anns == null) { return false; } for (Annotation ann : anns) { String name = ann.annotationType().getName(); if (name.endsWith("Anno")) { return true; } } return false; } @Override public List<Method> filter(List<Method> methods) { filterCalled = true; List<Method> forRemoval = new ArrayList<>(); for (Method method: methods) { if (removeIfNotAnnotated && !isAnnotated(method)) { forRemoval.add(method); } } for (Method method: forRemoval) { methods.remove(method); } return methods; } } @Retention(RetentionPolicy.RUNTIME) @interface Anno { } class TestObject { public int doit(int i) { return i; } @Anno public String doit(double d) { return "double "+d; } } static class DummyMethodResolver implements MethodResolver { @Override public MethodExecutor resolve(EvaluationContext context, Object targetObject, String name, List<TypeDescriptor> argumentTypes) throws AccessException { throw new UnsupportedOperationException(); } } public static class BytesService { public byte[] handleBytes(byte[] bytes) { return bytes; } } }
package org.sagebionetworks.url; /** * Enumerations of HTTP methods. * */ public enum HttpMethod { GET, PUT, POST, DELETE, HEAD }
// Java Iterator interface reference: // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html class PeekingIterator implements Iterator<Integer> { Queue<Integer> q = new LinkedList<>(); public PeekingIterator(Iterator<Integer> iterator) { // initialize any member here. while(iterator.hasNext())q.offer(iterator.next()); //The difference is that offer() will return false if it fails to insert the element on a size restricted Queue, whereas add() will throw an IllegalStateException. //You should use offer() when failure to insert an element would be normal, and add() when failure would be an exceptional occurrence (that needs to be handled } // Returns the next element in the iteration without advancing the iterator. public Integer peek() { return q.peek(); } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. @Override public Integer next() { return q.poll(); } @Override public boolean hasNext() { return !q.isEmpty(); } }
package de.cuuky.varo.command.varo; import java.awt.Color; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import de.cuuky.varo.Main; import de.cuuky.varo.bot.discord.register.BotRegister; import de.cuuky.varo.command.VaroCommand; import de.cuuky.varo.config.config.ConfigEntry; import de.cuuky.varo.gui.admin.discordbot.DiscordBotGUI; import de.cuuky.varo.player.VaroPlayer; import net.dv8tion.jda.core.entities.User; public class DiscordCommand extends VaroCommand { public DiscordCommand() { super("discord", "Der Hauptbefehl für den DiscordBot", "varo.discord"); } @Override public void onCommand(CommandSender sender, VaroPlayer vp, Command cmd, String label, String[] args) { if(args.length == 0) { sender.sendMessage(Main.getPrefix() + "§7----- " + ConfigEntry.PROJECTNAME_COLORCODE.getValueAsString() + "Discord-Commands §7-----"); sender.sendMessage(Main.getPrefix() + ConfigEntry.PROJECTNAME_COLORCODE.getValueAsString() + "/varo discord getLink §7<Spieler>"); sender.sendMessage(Main.getPrefix() + ConfigEntry.PROJECTNAME_COLORCODE.getValueAsString() + "/varo discord unlink §7<Spieler>"); sender.sendMessage(Main.getPrefix() + ConfigEntry.PROJECTNAME_COLORCODE.getValueAsString() + "/varo discord bypassRegister §7<Spieler> <true/false>"); sender.sendMessage(Main.getPrefix() + ConfigEntry.PROJECTNAME_COLORCODE.getValueAsString() + "/varo discord sendMessage §7<Nachricht>"); sender.sendMessage(Main.getPrefix() + ConfigEntry.PROJECTNAME_COLORCODE.getValueAsString() + "/varo discord reload"); sender.sendMessage(Main.getPrefix() + ConfigEntry.PROJECTNAME_COLORCODE.getValueAsString() + "/varo discord shutdown"); sender.sendMessage(Main.getPrefix() + ConfigEntry.PROJECTNAME_COLORCODE.getValueAsString() + "/varo discord settings"); sender.sendMessage(Main.getPrefix() + "§7--------------------------"); return; } BotRegister reg = null; try { reg = BotRegister.getBotRegisterByPlayerName(args[1]); } catch(Exception e) {} if(Main.getDiscordBot() == null) { sender.sendMessage(Main.getPrefix() + "§7Der DiscordBot wurde beim Start nicht aufgesetzt, bitte reloade!"); return; } if(args[0].equalsIgnoreCase("getLink") || args[0].equalsIgnoreCase("link")) { if(!ConfigEntry.DISCORDBOT_VERIFYSYSTEM.getValueAsBoolean()) { sender.sendMessage(Main.getPrefix() + "§7Das Verifzierungs-System wurde in der Config deaktiviert!"); return; } if(Main.getDiscordBot() == null || !Main.getDiscordBot().isEnabled()) { sender.sendMessage(Main.getPrefix() + "§7Der DiscordBot wurde nicht aktiviert!"); return; } if(reg == null) { sender.sendMessage(Main.getPrefix() + "§7Der Spieler §7" + args[1] + " §7hat den Server noch nie betreten!"); return; } User user = Main.getDiscordBot().getJda().getUserById(reg.getUserId()); if(user == null) { sender.sendMessage(Main.getPrefix() + "§7User für diesen Spieler nicht gefunden!"); return; } sender.sendMessage(Main.getPrefix() + "§7Der Discord Account von " + args[1] + " heißt: " + ConfigEntry.PROJECTNAME_COLORCODE.getValueAsString() + user.getName() + "§7 und die ID lautet " + ConfigEntry.PROJECTNAME_COLORCODE.getValueAsString() + user.getId() + "§7!"); } else if(args[0].equalsIgnoreCase("unlink")) { if(!ConfigEntry.DISCORDBOT_VERIFYSYSTEM.getValueAsBoolean()) { sender.sendMessage(Main.getPrefix() + "§7Das Verifzierungs-System wurde in der Config deaktiviert!"); return; } if(Main.getDiscordBot() == null || !Main.getDiscordBot().isEnabled()) { sender.sendMessage(Main.getPrefix() + "§7Der DiscordBot wurde nicht aktiviert!"); return; } if(reg == null) { sender.sendMessage(Main.getPrefix() + "§7Der Spieler §7" + args[1] + " §7hat den Server noch nie betreten!"); return; } reg.setUserId(-1); sender.sendMessage(Main.getPrefix() + "§7Der Discord Account wurde erfolgreich von §7" + args[1] + "§7 entkoppelt!"); if(Bukkit.getPlayerExact(reg.getPlayerName()) != null) Bukkit.getPlayerExact(reg.getPlayerName()).kickPlayer(reg.getKickMessage()); } else if(args[0].equalsIgnoreCase("bypassRegister") || args[0].equalsIgnoreCase("bypass")) { if(!ConfigEntry.DISCORDBOT_VERIFYSYSTEM.getValueAsBoolean()) { sender.sendMessage(Main.getPrefix() + "§7Das Verifzierungs-System wurde in der Config deaktiviert!"); return; } if(Main.getDiscordBot() == null || !Main.getDiscordBot().isEnabled()) { sender.sendMessage(Main.getPrefix() + "§7Der DiscordBot wurde nicht aktiviert!"); return; } if(reg == null) { sender.sendMessage(Main.getPrefix() + "§7Der Spieler §7" + args[1] + " §7hat den Server noch nie betreten!"); return; } if(args.length != 3) { sender.sendMessage(Main.getPrefix() + "§7/varo discord bypass <Spieler> <true/false>"); return; } if(args[2].equalsIgnoreCase("true") || args[2].equalsIgnoreCase("false")) { reg.setBypass(args[2].equalsIgnoreCase("true") ? true : false); sender.sendMessage(Main.getPrefix() + "§7" + args[1] + "§7 bypasst jetzt " + (reg.isBypass() ? "" : "§7nicht mehr§7") + " das Register-System!"); } else sender.sendMessage(Main.getPrefix() + "§7/varo discord bypass <add/remove> <Spielername>"); } else if(args[0].equalsIgnoreCase("reload")) { Main.getDiscordBot().disconnect(); Main.getDiscordBot().connect(); for(Player pl : Bukkit.getOnlinePlayers()) if(ConfigEntry.DISCORDBOT_VERIFYSYSTEM.getValueAsBoolean() && BotRegister.getBotRegisterByPlayerName(pl.getName()) == null) pl.kickPlayer("§7Das Discord Verify System wurde aktiviert!"); sender.sendMessage(Main.getPrefix() + "§7DiscordBot §aerfolgreich §7neu geladen!"); } else if(args[0].equalsIgnoreCase("settings")) { if(!(sender instanceof Player)) { sender.sendMessage(Main.getPrefix() + "Only for players!"); return; } new DiscordBotGUI((Player) sender); } else if(args[0].equalsIgnoreCase("shutdown")) { if(Main.getDiscordBot().getJda() == null) { sender.sendMessage(Main.getPrefix() + "Der §bDiscordBot §7ist nicht online!"); return; } sender.sendMessage(Main.getPrefix() + "§bDiscordBot §7erfolgreich heruntergefahren!"); Main.getDiscordBot().disconnect(); } else if(args[0].equalsIgnoreCase("sendMessage")) { if(Main.getDiscordBot() == null || !Main.getDiscordBot().isEnabled()) { sender.sendMessage(Main.getPrefix() + "§7Der DiscordBot wurde nicht aktiviert!"); return; } String message = ""; for(String ar : args) { if(ar.equals(args[0])) continue; if(message.equals("")) message = ar; else message = message + " " + ar; } Main.getDiscordBot().sendMessage(message, "MESSAGE", Color.YELLOW, Main.getDiscordBot().getEventChannel()); } else sender.sendMessage(Main.getPrefix() + "§7/varo discord " + args[0] + " not found! §7Type /discord for help."); return; } }
package com.pmm.sdgc.dao; import com.pmm.sdgc.model.UserDataTreinamento; import com.pmm.sdgc.model.UserLogin; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author dreges */ @Stateless public class UserDataTreinamentoDao { @PersistenceContext EntityManager em; @EJB FuncionalDao daoFuncional; @EJB UserLoginDao daoUserLogin; public List<UserDataTreinamento> getListaUserDataTreinamento(Integer id) { Query q = em.createQuery("select udt.data, udt.dataHora from UserDataTreinamento udt where udt.userLogin.id = :id order by udt.data").setFirstResult(0).setMaxResults(10); q.setParameter("id", id); return q.getResultList(); } public void incluir(Integer IdUserLogin, LocalDate data) throws Exception { UserDataTreinamento treinamento = new UserDataTreinamento(); UserLogin user = daoUserLogin.getUserLoginPorId(IdUserLogin); treinamento.setUserLogin(user); treinamento.setData(data); treinamento.setDataHora(LocalDateTime.now()); em.persist(treinamento); } public void remover(UserDataTreinamento udt) throws Exception { em.remove(udt); } }
package br.com.android.fjanser.hotspotz; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v4.view.ViewCompat; import android.support.v4.widget.SimpleCursorAdapter; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import br.com.android.fjanser.hotspotz.database.HotSpotContract; import br.com.android.fjanser.hotspotz.R; import br.com.android.fjanser.hotspotz.database.HotSpotDBHelper; public class HotSpotCursorAdapter extends SimpleCursorAdapter { private static final int LAYOUT = R.layout.item_hotspot; private Context ctx; public HotSpotCursorAdapter(Context context, Cursor c) { super(context, LAYOUT, c, HotSpotContract.LIST_COLUMNS, null, 0); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = LayoutInflater.from(context).inflate(LAYOUT, parent, false); VH vh = new VH(); //vh.imageViewPoster = (ImageView) view.findViewById(R.id.movie_item_image_poster); vh.textViewEndereco = (TextView) view.findViewById(R.id.hotspot_item_text_title); vh.textViewPais = (TextView) view.findViewById(R.id.hotspot_item_text); view.setTag(vh); //ViewCompat.setTransitionName(vh.imageViewPoster, "capa"); ViewCompat.setTransitionName(vh.textViewEndereco, "endereco"); ViewCompat.setTransitionName(vh.textViewPais, "pais"); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { float totalEquipe = 0.0f; //String poster = cursor.getString(cursor.getColumnIndex(MovieContract.COL_POSTER)); String endereco = cursor.getString(cursor.getColumnIndex(HotSpotContract.COL_ENDERECO)); String pais = cursor.getString(cursor.getColumnIndex(HotSpotContract.COL_PAIS)); VH vh = (VH)view.getTag(); //Glide.with(context).load(poster).placeholder(R.drawable.ic_placeholder).into(vh.imageViewPoster); vh.textViewEndereco.setText(endereco); vh.textViewPais.setText(pais); } class VH { //ImageView imageViewPoster; TextView textViewEndereco; TextView textViewPais; } }
/* * AP(r) Computer Science GridWorld Case Study: * Copyright(c) 2005-2006 Cay S. Horstmann (http://horstmann.com) * * This code 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. * * This code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Cay Horstmann */ package info.gridworld.world; import java.awt.Color; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.io.File; import java.io.FileWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import java.util.Set; import java.util.TreeSet; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import info.gridworld.actor.Actor; import info.gridworld.grid.BoundedGrid; import info.gridworld.grid.Grid; import info.gridworld.grid.Location; import info.gridworld.gui.WorldFrame; /** * * A <code>World</code> is the mediator between a grid and the GridWorld GUI. <br /> * This class is not tested on the AP CS A and AB exams. */ public class World<T> { private Grid<T> gr; private Set<String> occupantClassNames; private Set<String> gridClassNames; private String message; private WorldFrame<T> frame; private boolean hasShown = false; private static Random generator = new Random(); private static final int DEFAULT_ROWS = 10; private static final int DEFAULT_COLS = 10; public World() { this(new BoundedGrid<T>(DEFAULT_ROWS, DEFAULT_COLS)); message = null; } public World(Grid<T> g) { gr = g; gridClassNames = new TreeSet<String>(); occupantClassNames = new TreeSet<String>(); addGridClass("info.gridworld.grid.BoundedGrid"); addGridClass("info.gridworld.grid.UnboundedGrid"); } /** * Constructs and shows a frame for this world. */ public void show() { if (frame == null) { hasShown = true; frame = new WorldFrame<T>(this); frame.setExtendedState(JFrame.MAXIMIZED_BOTH); frame.setVisible(true); } else frame.repaint(); } /** * Gets the grid managed by this world. * * @return the grid */ public Grid<T> getGrid() { return gr; } /** * Sets the grid managed by this world. * * @param newGrid * the new grid */ public void setGrid(Grid<T> newGrid) { gr = newGrid; repaint(); } /** * Sets the message to be displayed in the world frame above the grid. * * @param newMessage * the new message */ public void setMessage(String newMessage) { message = newMessage; repaint(); } /** * Gets the message to be displayed in the world frame above the grid. * * @return the message */ public String getMessage() { return message; } /** * This method is called when the user clicks on the step button, or when * run mode has been activated by clicking the run button. */ public void step() { repaint(); } /** * This method is called when the user clicks on a location in the * WorldFrame. * * @param loc * the grid location that the user selected * @return true if the world consumes the click, or false if the GUI should * invoke the Location->Edit menu action */ public boolean locationClicked(Location loc) { return false; } /** * This method is called when a key was pressed. Override it if your world * wants to consume some keys (e.g. "1"-"9" for Sudoku). Don't consume plain * arrow keys, or the user loses the ability to move the selection square * with the keyboard. * * @param description * the string describing the key, in <a href= * "http://java.sun.com/javase/6/docs/api/javax/swing/KeyStroke.html#getKeyStroke(java.lang.String)" * >this format</a>. * @param loc * the selected location in the grid at the time the key was * pressed * @return true if the world consumes the key press, false if the GUI should * consume it. */ public boolean keyPressed(String description, Location loc) { return false; } /** * Gets a random empty location in this world. * * @return a random empty location */ public Location getRandomEmptyLocation() { Grid<T> gr = getGrid(); int rows = gr.getNumRows(); int cols = gr.getNumCols(); if (rows > 0 && cols > 0) // bounded grid { // get all valid empty locations and pick one at random ArrayList<Location> emptyLocs = new ArrayList<Location>(); for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) { Location loc = new Location(i, j); if (gr.isValid(loc) && gr.get(loc) == null) emptyLocs.add(loc); } if (emptyLocs.size() == 0) return null; int r = generator.nextInt(emptyLocs.size()); return emptyLocs.get(r); } else // unbounded grid { while (true) { // keep generating a random location until an empty one is found int r; if (rows < 0) r = (int) (DEFAULT_ROWS * generator.nextGaussian()); else r = generator.nextInt(rows); int c; if (cols < 0) c = (int) (DEFAULT_COLS * generator.nextGaussian()); else c = generator.nextInt(cols); Location loc = new Location(r, c); if (gr.isValid(loc) && gr.get(loc) == null) return loc; } } } /** * Adds an occupant at a given location. * * @param loc * the location * @param occupant * the occupant to add */ public void add(Location loc, T occupant) { getGrid().put(loc, occupant); repaint(); } /** * Removes an occupant from a given location. * * @param loc * the location * @return the removed occupant, or null if the location was empty */ public T remove(Location loc) { T r = getGrid().remove(loc); repaint(); return r; } /** * Adds a class to be shown in the "Set grid" menu. * * @param className * the name of the grid class */ public void addGridClass(String className) { gridClassNames.add(className); } /** * Adds a class to be shown when clicking on an empty location. * * @param className * the name of the occupant class */ public void addOccupantClass(String className) { occupantClassNames.add(className); } /** * Gets a set of grid classes that should be used by the world frame for * this world. * * @return the set of grid class names */ public Set<String> getGridClasses() { return gridClassNames; } /** * Gets a set of occupant classes that should be used by the world frame for * this world. * * @return the set of occupant class names */ public Set<String> getOccupantClasses() { return occupantClassNames; } private void repaint() { if (frame != null) frame.repaint(); } /** * Returns a string that shows the positions of the grid occupants. */ public String toString() { String s = ""; Grid<?> gr = getGrid(); int rmin = 0; int rmax = gr.getNumRows() - 1; int cmin = 0; int cmax = gr.getNumCols() - 1; if (rmax < 0 || cmax < 0) // unbounded grid { for (Location loc : gr.getOccupiedLocations()) { int r = loc.getRow(); int c = loc.getCol(); if (r < rmin) rmin = r; if (r > rmax) rmax = r; if (c < cmin) cmin = c; if (c > cmax) cmax = c; } } for (int i = rmin; i <= rmax; i++) { for (int j = cmin; j < cmax; j++) { Object obj = gr.get(new Location(i, j)); if (obj == null) s += " "; else s += obj.toString().substring(0, 1); } s += "\n"; } return s; } /** * Returns a string of all the actors on the grid formatted to be saved * * @author Ben Eisner, Jake Balfour, Shon Kaganovich */ private String getActorString() { Grid<?> gr = getGrid(); ArrayList<Location> locs = gr.getOccupiedLocations(); String code = ""; String actorName; int i = 1; code += "\n\t\tActorWorld world = new ActorWorld();"; code += "\n\t\tworld.setGrid(new BoundedGrid<Actor>(" + gr.getNumRows() + "," + gr.getNumCols() + "));"; for (Location a : locs) { String name1 = gr.get(a).getClass().getName(); name1 = name1.replace(".", " "); String[] s = name1.split(" "); String actorType = s[s.length - 1]; actorName = actorType + i; i++; code += "\n\t\t" + actorType + " " + actorName + " = new " + actorType + "();"; Color c = ((Actor) gr.get(a)).getColor(); int dir = ((Actor) gr.get(a)).getDirection(); if (c == null) code += "\n\t\t" + actorName + ".setColor(null);"; else code += "\n\t\t" + actorName + ".setColor(new Color(" + c.getRed() + "," + c.getGreen() + "," + c.getBlue() + "));"; code += "\n\t\t" + actorName + ".setDirection(" + dir + ");"; code += "\n\t\tworld.add(new Location(" + a.getRow() + "," + a.getCol() + ")," + actorName + ");"; } code += "\n\t\tworld.show();"; return code; } /** * Writes save output to a .java file * * @author Ben Eisner */ private void writeFile(String actorString) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File("/H")); int retrival = chooser.showSaveDialog(null); if (retrival == JFileChooser.APPROVE_OPTION) { try { String fileName = chooser.getSelectedFile() + ""; if (!fileName.substring(fileName.length() - 5, fileName.length()).equals(".java")) fileName = fileName + ".java"; FileWriter fw = new FileWriter(fileName); String s = chooser.getSelectedFile().getName(); if (s.length() > 5 && s.substring(s.length() - 5, s.length()).equals( ".java")) s = s.substring(0, s.length() - 5); actorString = "/*Save Written By: Ben Eisner, Shon Kaganovich, Jake Balfour ©2015*/\n\nimport info.gridworld.actor.Actor;\nimport info.gridworld.actor.ActorWorld;\nimport info.gridworld.actor.Bug;\nimport info.gridworld.actor.Flower;\nimport info.gridworld.actor.Rock;\nimport info.gridworld.actor.Critter;\nimport info.gridworld.grid.BoundedGrid;\nimport info.gridworld.grid.Grid;\nimport info.gridworld.grid.Location;\nimport java.awt.Color;\n\n" + "public class " + s + "{\n\n\tpublic static void main(String[]args){" + actorString + "\n\t}\n}"; fw.write(actorString); System.out.println("Saved " + fileName); JOptionPane.showMessageDialog(null, "Saved Runner to " + fileName + "!"); fw.close(); } catch (Exception ex) { ex.printStackTrace(); } } } /** * Copies save output to clipboard * * @author Ben Eisner */ private void clipboardFile(String actorString) { actorString = "/*Save Written By: Ben Eisner, Shon Kaganovich, Jake Balfour ©2015*/\n\nimport info.gridworld.actor.Actor;\nimport info.gridworld.actor.ActorWorld;\nimport info.gridworld.actor.Bug;\nimport info.gridworld.actor.Flower;\nimport info.gridworld.actor.Rock;\nimport info.gridworld.actor.Critter;\nimport info.gridworld.grid.BoundedGrid;\nimport info.gridworld.grid.Grid;\nimport info.gridworld.grid.Location;\nimport java.awt.Color;\n\n" + "public class Runner/*Change 'Runner' to your class name*/" + "{\n\n\tpublic static void main(String[]args){" + actorString + "\n\t}\n}"; Toolkit toolkit = Toolkit.getDefaultToolkit(); Clipboard clipboard = toolkit.getSystemClipboard(); StringSelection strSel = new StringSelection(actorString); clipboard.setContents(strSel, null); JOptionPane.showMessageDialog(null, "Runner saved to clipboard!\nUse Control+V to paste."); } /** * Similar to getActorString(), but will also save custom classes with * parameters * * @author Ben Eisner */ private String getActorStringWithConstructors() { Grid<?> gr = getGrid(); ArrayList<Location> locs = gr.getOccupiedLocations(); String code = ""; String actorName; int i = 1; code += "\n\t\tActorWorld world = new ActorWorld();"; code += "\n\t\tworld.setGrid(new BoundedGrid<Actor>(" + gr.getNumRows() + "," + gr.getNumCols() + "));"; for (Location a : locs) { String name1 = gr.get(a).getClass().getName(); name1 = name1.replace(".", " "); String[] s = name1.split(" "); String actorType = s[s.length - 1]; actorName = actorType + i; i++; String[] constr = { actorType, actorName }; String parenString = getConstructorString( getConstructor(constr, actorType, a), getConstructorValues(a), a, actorType); if (parenString == null) code += "\n\t\t" + actorType + " " + actorName + " = new " + actorType + "();"; else code += "\n\t\t" + actorType + " " + actorName + " = new " + actorType + parenString; Color c = ((Actor) gr.get(a)).getColor(); int dir = ((Actor) gr.get(a)).getDirection(); if (c == null) code += "\n\t\t" + actorName + ".setColor(null);"; else code += "\n\t\t" + actorName + ".setColor(new Color(" + c.getRed() + "," + c.getGreen() + "," + c.getBlue() + "));"; code += "\n\t\t" + actorName + ".setDirection(" + dir + ");"; code += "\n\t\tworld.add(new Location(" + a.getRow() + "," + a.getCol() + ")," + actorName + ");"; } code += "\n\t\tworld.show();"; return code; } /** * Returns a string of the final constructor output which will be saved * * @author Ben Eisner */ private String getConstructorString(Object[] constructorObjects, Object[] constValues, Location a, String actorType) { if (constructorObjects != null && constValues != null) { String selectedConstructor = (String) constructorObjects[0]; Class<?>[] dataTypes = (Class<?>[]) constructorObjects[1]; @SuppressWarnings("unchecked") ArrayList<Object> constructorValues = (ArrayList<Object>) constValues[0]; @SuppressWarnings("unchecked") ArrayList<Object> constructorValuesNum = (ArrayList<Object>) constValues[1]; String[] showOps = new String[constructorValues.size()]; String[] fOps = new String[constructorValues.size()]; String inParenthesis = "("; ArrayList<String> finalString = new ArrayList<String>(); for (int i = 0; i < showOps.length; i++) { showOps[i] = constructorValues.get(i).toString(); fOps[i] = constructorValuesNum.get(i).toString(); } for (int x = 0; x < dataTypes.length; x++) { String optionDialog = "The constructor " + selectedConstructor + " for the " + actorType + " at " + a + " has been selected.\n"; optionDialog += "What " + dataTypes[x] + " do you want to save in parameter " + (x + 1) + " out of " + dataTypes.length + "?"; if (fOps.length > 1) { int choice = JOptionPane.showOptionDialog(null, optionDialog, "GridWorld Save", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, fOps, null); if (choice != -1) finalString.add(showOps[choice]); } else { finalString.add(showOps[0]); } } for (String f : finalString) { inParenthesis += f + ","; } inParenthesis = inParenthesis.substring(0, inParenthesis.length() - 1) + ");"; return inParenthesis; } return null; } /** * Returns an Object[] with all the Constructor Values at the given location * * @author Ben Eisner */ private Object[] getConstructorValues(Location loc) { Actor a = ((Actor) getGrid().get(loc)); // Class<?> c = a.getClass(); // Field[] fields = c.getDeclaredFields(); Object[] obj = new Object[2]; ArrayList<Object> fieldList = new ArrayList<Object>(); ArrayList<Object> visualList = new ArrayList<Object>(); try { for (Field field : a.getClass().getDeclaredFields()) { Field currentField = a.getClass().getDeclaredField( field.getName()); currentField.setAccessible(true); visualList.add(field.getName() + "(" + currentField.get(a) + ")"); fieldList.add(currentField.get(a)); } obj[0] = fieldList; obj[1] = visualList; return obj; } catch (NoSuchFieldException e) { System.out.println("ERROR"); return null; } catch (IllegalArgumentException e) { System.out.println("ERROR"); return null; } catch (IllegalAccessException e) { System.out.println("ERROR"); return null; } } /** * Returns an Object[] with all the Constructor Types at the given location * * @author Ben Eisner */ private Object[] getConstructor(String[] className, String actorType, Location loc) { try { Class<?> c = Class.forName(className[0]); Constructor<?>[] constructors = c.getConstructors(); if (constructors.length > 1) { String[] conOptions = new String[constructors.length]; for (int x = 0; x < constructors.length; x++) { conOptions[x] = constructors[x].toString(); } int selectedConstructor = JOptionPane.showOptionDialog(null, "What constructor do you want to use to save the " + actorType + " at " + loc + "?", "GridWorld Save", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, conOptions, null); if (selectedConstructor != -1) { Class<?>[] types = constructors[selectedConstructor] .getParameterTypes(); Object[] objects = new Object[2]; objects[0] = conOptions[selectedConstructor]; objects[1] = types; if (types.length == 0) return null; return objects; } return null; } Object[] objects = new Object[2]; objects[0] = constructors[0].toString(); objects[1] = constructors[0].getParameterTypes(); return objects; } catch (ClassNotFoundException e) { return null; } } /** * Save to a file or clipboard * * @author Ben Eisner, Jake Balfour, Shon Kaganovich */ public void save() { String actorString = getActorString(); // String actorString = getActorString(); String[] options = { "Save Runner as .java File", "Copy Runner to Clipboard" }; int choice = JOptionPane.showOptionDialog(null, "Runner successfully generated. What would You Like To Do?", "GridWorld Save", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, null); if (choice == 0) writeFile(actorString); else if (choice == 1) clipboardFile(actorString); } }
package com.legaoyi.protocol.upstream.messagebody; import java.util.List; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonProperty; import com.legaoyi.protocol.message.MessageBody; /** * 采集指定的行驶速度记录(08H) * * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2019-05-20 */ @Scope("prototype") @Component(MessageBody.MESSAGE_BODY_BEAN_PREFIX + "0700_08H_2019" + MessageBody.MESSAGE_BODY_BEAN_SUFFIX) public class Jt808_2019_0700_08H_MessageBody extends Jt808_2019_0700_MessageBody { private static final long serialVersionUID = 3592290914945764548L; /** 数据块 **/ @JsonProperty("dataList") private List<?> dataList; public final List<?> getDataList() { return dataList; } public final void setDataList(List<?> dataList) { this.dataList = dataList; } }
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; public class ClockThread extends Thread{ FibonacciClock fibClock; private final static int seconds =1000; Calendar calendar; public ClockThread(FibonacciClock fibClock) { this.fibClock = fibClock; this.calendar=GregorianCalendar.getInstance(); fibClock.generateColorPattern(fibClock.objPattern0); this.start(); } public void run() { while(true) { try { //Calendar for extract current time zone. Little Old fashion but effective. //Java 8 time feature is not safe to use in Thread. calendar =GregorianCalendar.getInstance(); fibClock.hour=calendar.get(Calendar.HOUR); fibClock.minute=calendar.get(Calendar.MINUTE) / 5; System.out.print("\nIs: "+ (calendar.get(Calendar.MINUTE))%5); if((calendar.get(Calendar.MINUTE))%5 == 0 && calendar.get(Calendar.SECOND)%10 == 0) { fibClock.generateColorPattern(fibClock.objPattern0); //fibClock.buildColorClock(); } showTimeOnTitle(calendar); Thread.sleep(seconds); } catch (InterruptedException e) { e.printStackTrace(); } } } public void showTimeOnTitle(Calendar calendar) { fibClock.cg.setTitle("Fibonacci Clock - " + (new SimpleDateFormat("hh:mm:ss a")).format(calendar.getTime())); //System.out.print("\nDate And Time Is: " + calendar.getTime()); } }
package com.najasoftware.fdv.model; import android.util.Log; import java.io.Serializable; import java.util.List; /** * Created by Lemoel Marques - NajaSoftware on 04/03/2016. * lemoel@gmail.com */ @org.parceler.Parcel public class Cliente implements Serializable { private String cnpj; private String rg; private String inscricacaoEstadual; private String dtCadastro; private String dtUltimaAlteracao; private String nome; private String nomeFantasia; private int status; private String statusFinanceiro; private double latitude; private double longitude; private String urlFoto; private String email; private String obs; private String orgaoExpedidorRg; private List<Telefone> telefones; private List<Endereco> enderecos; private Long vendedorId; private boolean selected; public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCnpj() { return cnpj; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } public String getStatusFinanceiro() { return statusFinanceiro; } public void setStatusFinanceiro(String statusFinanceiro) { this.statusFinanceiro = statusFinanceiro; } public String getUrlFoto() { return urlFoto; } public void setUrlFoto(String urlFoto) { this.urlFoto = urlFoto; } public String getRg() { return rg; } public void setRg(String rg) { this.rg = rg; } public String getInscricacaoEstadual() { return inscricacaoEstadual; } public void setInscricacaoEstadual(String inscricacaoEstadual) { this.inscricacaoEstadual = inscricacaoEstadual; } public String getDtCadastro() { return dtCadastro; } public void setDtCadastro(String dtCadastro) { this.dtCadastro = dtCadastro; } public String getDtUltimaAlteracao() { return dtUltimaAlteracao; } public void setDtUltimaAlteracao(String dtUltimaAlteracao) { this.dtUltimaAlteracao = dtUltimaAlteracao; } public String getNomeFantasia() { return nomeFantasia; } public void setNomeFantasia(String nomeFantasia) { this.nomeFantasia = nomeFantasia; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getObs() { return obs; } public void setObs(String obs) { this.obs = obs; } public String getOrgaoExpedidorRg() { return orgaoExpedidorRg; } public void setOrgaoExpedidorRg(String orgaoExpedidorRg) { this.orgaoExpedidorRg = orgaoExpedidorRg; } public Long getVendedorId() { return vendedorId; } public void setVendedorId(Long vendedorId) { this.vendedorId = vendedorId; } public List<Telefone> getTelefones() { return telefones; } public void setTelefones(List<Telefone> telefones) { this.telefones = telefones; } public List<Endereco> getEnderecos() { return enderecos; } public void setEnderecos(List<Endereco> enderecos) { this.enderecos = enderecos; } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Cliente cliente = (Cliente) o; return cnpj != null ? cnpj.equals(cliente.cnpj) : cliente.cnpj == null; } @Override public int hashCode() { return cnpj != null ? cnpj.hashCode() : 0; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } }
package lawscraper.client.activity; import com.google.gwt.activity.shared.AbstractActivity; import com.google.gwt.core.client.GWT; import com.google.gwt.event.shared.EventBus; import com.google.gwt.place.shared.Place; import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Widget; import com.google.web.bindery.requestfactory.shared.Receiver; import com.google.web.bindery.requestfactory.shared.ServerFailure; import lawscraper.client.ClientFactory; import lawscraper.client.ui.StartView; import lawscraper.client.ui.StartViewImpl; import lawscraper.client.ui.events.*; import lawscraper.client.ui.panels.documentsearchpanel.DocumentResultElement; import lawscraper.shared.*; import lawscraper.shared.proxies.*; import lawscraper.shared.scraper.LawScraperSource; import java.util.List; public class StartViewActivity extends AbstractActivity implements StartView.Presenter { final LawRequestFactory lawRequests = GWT.create(LawRequestFactory.class); final CaseLawRequestFactory caseLawRequests = GWT.create(CaseLawRequestFactory.class); final UserRequestFactory userRequests = GWT.create(UserRequestFactory.class); final LegalResearchRequestFactory legalResearchRequests = GWT.create(LegalResearchRequestFactory.class); final DocumentPartRequestFactory documentPartRequestFactory = GWT.create(DocumentPartRequestFactory.class); //Scrapers request final LawScraperRequestFactory lawScraperRequests = GWT.create(LawScraperRequestFactory.class); final CaseLawScraperRequestFactory caseLawScraperRequests = GWT.create(CaseLawScraperRequestFactory.class); // Used to obtain views, eventBus, placeController private ClientFactory clientFactory; private EventBus eventBus; private FlowPanel flerpContainer; public StartViewActivity(final ClientFactory clientFactory) { this.clientFactory = clientFactory; } /** * Invoked by the ActivityManager to start a new Activity */ @Override public void start(AcceptsOneWidget containerWidget, EventBus eventBus) { final StartView startView = clientFactory.getStartView(); containerWidget.setWidget(startView.asWidget()); //init with the eventbus - pls remember this. lawRequests.initialize(eventBus); caseLawRequests.initialize(eventBus); lawScraperRequests.initialize(eventBus); caseLawScraperRequests.initialize(eventBus); userRequests.initialize(eventBus); legalResearchRequests.initialize(eventBus); documentPartRequestFactory.initialize(eventBus); this.eventBus = eventBus; subscribeToChangeUserEvent(eventBus); subscribeToChangeLawEvent(eventBus); startView.setPresenter(this); getLegalResearchByLoggedInUser(); checkCurrentUser(); } /** * If the current user is changed. Update the view accordingly. * * @param eventBus */ private void subscribeToChangeUserEvent(EventBus eventBus) { eventBus.addHandler(SetCurrentUserEvent.TYPE, new SetCurrentUserEventHandler() { @Override public void onSetCurrentUser(SetCurrentUserEvent event) { clientFactory.getRoleBasedWidgetHandler().handleRoleBasedViews(StartViewImpl.class); getLegalResearchByLoggedInUser(); } }); } private void subscribeToChangeLawEvent(EventBus eventBus) { eventBus.addHandler(SetCurrentLawEvent.TYPE, new SetCurrentLawEventHandler() { @Override public void onSetCurrentLaw(SetCurrentLawEvent event) { clientFactory.getStartView().addDocument(event.getResult()); } }); } @Override public void checkCurrentUser() { UserRequestFactory.UserRequest context = userRequests.userRequest(); context.getCurrentUser().fire(new Receiver<UserProxy>() { @Override public void onSuccess(UserProxy response) { if (response != null && response.getUserRole() != UserRole.Anonymous) { clientFactory.getStartView().setUserLoggedIn(response); } clientFactory.getRoleBasedWidgetHandler().setUserProxy(response); eventBus.fireEvent(new SetCurrentUserEvent(response)); clientFactory.getRoleBasedWidgetHandler().handleRoleBasedViews(StartViewImpl.class); } }); } @Override public void scrapeCaseLaw() { System.out.println("Scraping case laws"); CaseLawScraperRequestFactory.CaseLawScraperRequest context = caseLawScraperRequests.caseLawScraperRequest(); context.scrapeCaseLaws(LawScraperSource.ZIPFILE).fire(new Receiver<ScraperStatusProxy>() { @Override public void onSuccess(ScraperStatusProxy response) { System.out.println("Färdigt"); System.out.println("Antal lästa rättsfall: " + response.getScrapedLaws()); } }); } @Override public void scrapeLaw() { System.out.println("Scraping laws"); LawScraperRequestFactory.LawScraperRequest context = lawScraperRequests.lawScraperRequest(); context.scrapeLaws(LawScraperSource.ZIPFILE).fire(new Receiver<ScraperStatusProxy>() { @Override public void onSuccess(ScraperStatusProxy response) { System.out.println("Färdigt"); System.out.println("Antal lästa lagar: " + response.getScrapedLaws()); } }); } /** * Navigate to a new Place in the browser */ public void goTo(Place place) { clientFactory.getPlaceController().goTo(place); } @Override public void searchLaws(final String query) { LawRequestFactory.LawRequest context = lawRequests.lawRequest(); context.findLawByQuery(query).fire(new Receiver<List<LawProxy>>() { @Override public void onSuccess(List<LawProxy> response) { StartView startView = clientFactory.getStartView(); startView.setLaws(response, query); } }); } @Override public void searchCaseLaws(String query) { query = "%" + query + "%"; CaseLawRequestFactory.CaseLawRequest context = caseLawRequests.caseLawRequest(); context.findCaseLawByQuery(query).fire(new Receiver<List<CaseLawProxy>>() { @Override public void onSuccess(List<CaseLawProxy> response) { StartView startView = clientFactory.getStartView(); startView.setCaseLaws(response); } }); } @Override public void getCaseLawsByYearAndCourt(String year, String court) { CaseLawRequestFactory.CaseLawRequest context = caseLawRequests.caseLawRequest(); /* context.getCaseLawsByYearAndCourt(year, court).fire(new Receiver<List<DocumentListItem>>() { @Override public void onSuccess(List<DocumentListItem> response) { StartView startView = clientFactory.getStartView(); startView.setCaseLaws(response); } }); */ } @Override public void searchLegalResearch(final String query) { LegalResearchRequestFactory.LegalResearchRequest context = legalResearchRequests.legalResearchRequest(); context.findLegalResearchByLoggedInUser().fire(new Receiver<List<LegalResearchProxy>>() { @Override public void onSuccess(List<LegalResearchProxy> response) { StartView startView = clientFactory.getStartView(); startView.setLegalResearch(response, query); } }); } @Override public void getLegalResearch(final String query) { LegalResearchRequestFactory.LegalResearchRequest context = legalResearchRequests.legalResearchRequest(); context.findLegalResearchByLoggedInUser().fire(new Receiver<List<LegalResearchProxy>>() { @Override public void onSuccess(List<LegalResearchProxy> response) { StartView startView = clientFactory.getStartView(); startView.setLegalResearch(response, query); } }); } @Override public void addWidgetToTabPanel(Widget widget, String flerpName, String flerpKey) { StartView lawView = clientFactory.getStartView(); //lawView.getDynamicTabPanel().add(widget, flerpName, flerpKey); } @Override public void getDocumentDescription(final DocumentResultElement resultElement) { DocumentPartRequestFactory.DocumentRequest context = documentPartRequestFactory.documentRequest(); context.getDocumentCommentary(resultElement.getDocumentId()).fire(new Receiver<HTMLProxy>() { @Override public void onSuccess(HTMLProxy response) { resultElement.setDescription(response.getHtml()); } }); } @Override public void getLegalResearchByLoggedInUser() { LegalResearchRequestFactory.LegalResearchRequest context = legalResearchRequests.legalResearchRequest(); context.findLegalResearchByLoggedInUser().fire(new Receiver<List<LegalResearchProxy>>() { @Override public void onSuccess(List<LegalResearchProxy> response) { StartView startView = clientFactory.getStartView(); //startView.setLegalResearch(response, query); } }); } @Override public void changeActiveLegalResearch(Long legalResearchId) { LegalResearchRequestFactory.LegalResearchRequest context = legalResearchRequests.legalResearchRequest(); context.setLegalResearchActive(legalResearchId).fire(new Receiver<Void>() { @Override public void onSuccess(Void response) { System.out.println("LegalResearch set to active"); eventBus.fireEvent(new SetCurrentLegalResearchEvent(null)); } }); } @Override public void addLegalResearch(final String title, final String description) { LegalResearchRequestFactory.LegalResearchRequest context = legalResearchRequests.legalResearchRequest(); context.addLegalResearch(title, description).fire(new Receiver<Void>() { @Override public void onSuccess(Void response) { System.out.println("Added legal research"); getLegalResearchByLoggedInUser(); } @Override public void onFailure(ServerFailure error) { System.out.println(error.getMessage()); } }); } }
package com.example.lbyanBack.contst; public class Contst { /** * 加密key */ public static final String ASE_KEY = "BYKANG"; /** 登录方式--邮箱 */ public static final String DLTYPE_EMAIL = "2"; /** 登录方式--账号 */ public static final String DLTYPE_ACCOUNT = "1"; }
/** * Copyright (C) 2015-2016, Zhichun Wu * * 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 com.github.cassandra.jdbc; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; import com.datastax.driver.core.VersionNumber; import com.google.common.base.Splitter; import com.google.common.io.CharStreams; import org.pmw.tinylog.Logger; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; import java.io.IOException; import java.io.InputStreamReader; public class CassandraServerTest { @BeforeGroups(groups = {"server"}) public void createKeyspaceAndTables() { String scripts = ""; InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream("/create.cql")); try { scripts = CharStreams.toString(reader); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } Cluster cluster = null; try { CassandraConfiguration conf = CassandraConfiguration.DEFAULT; Cluster.Builder builder = Cluster.builder(); for (String host : Splitter.on(',').trimResults().omitEmptyStrings().split(conf.getHosts())) { builder.addContactPoint(host); } if (conf.getPort() > 0) { builder.withPort(conf.getPort()); } cluster = builder.withCredentials(conf.getUserName(), conf.getPassword()).build(); Session session = cluster.newSession(); VersionNumber cassandraVersion = cluster.getMetadata().getAllHosts().iterator().next().getCassandraVersion(); CassandraTestHelper.init(cassandraVersion.getMajor(), cassandraVersion.getMinor()); scripts = CassandraTestHelper.getInstance().replaceScript(scripts); for (String cql : Splitter.on(';').trimResults().omitEmptyStrings().split(scripts)) { Logger.debug("Executing:\n{}\n", cql); session.execute(cql); } cluster.close(); cluster = null; } catch (Exception e) { e.printStackTrace(); } finally { if (cluster != null && !cluster.isClosed()) { cluster.closeAsync().force(); } cluster = null; } } @Test(groups = {"server"}) public void testConnection() { } }
package com.trump.auction.goods.api; import com.trump.auction.goods.model.ProductClassifyModel; import com.trump.auction.goods.model.ProductInfoModel; import com.trump.auction.goods.vo.ProductManageVo; import com.trump.auction.goods.vo.ResultBean; import java.util.List; /** * 商品分类对外提供接口 * @author Administrator * @date 2017/12/21 */ public interface ProductClassifyStubService { /** * 商品分类添加 * @param productClassifyModel * @return */ public ResultBean<Integer> saveClassify(ProductClassifyModel productClassifyModel) throws Exception; /** * 批量删除商品分类 * @param productClassifyModelList * @return */ public ResultBean<Integer> deleteBatch(List<ProductClassifyModel> productClassifyModelList) throws Exception; /** * 批量启用商品分类 * @param productClassifyModelList * @return */ public ResultBean<Integer> enableBatch(List<ProductClassifyModel> productClassifyModelList) throws Exception; /** * 修改商品分类 * @param productClassifyModel * @return */ public ResultBean<Integer> updateClassify(ProductClassifyModel productClassifyModel) throws Exception; }
package dev.com.demo.mt.coinbase.application; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession; import java.io.IOException; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) class CoinbaseWebSocketHandlerTest { @InjectMocks private CoinbaseWebSocketHandler coinbaseWebSocketHandler; @Mock private CoinbaseFacade coinbaseFacade; @Mock private TickerInstrumentsStore tickerInstrumentsStore; @Test void shallSendProperMessageAfterConnectionEstablished() throws IOException { //given final WebSocketSession webSocketSession = mock(WebSocketSession.class); when(tickerInstrumentsStore.getInstruments()).thenReturn(List.of("BTC-EUR","BTC-USD")); //when coinbaseWebSocketHandler.afterConnectionEstablished(webSocketSession); //then ArgumentCaptor<WebSocketMessage<?>> webSocketMessageArgumentCaptor = ArgumentCaptor.forClass(WebSocketMessage.class); verify(webSocketSession).sendMessage(webSocketMessageArgumentCaptor.capture()); final WebSocketMessage<?> captureMessage = webSocketMessageArgumentCaptor.getValue(); assert captureMessage instanceof TextMessage; assertEquals("{\"type\":\"subscribe\",\"channels\":[{\"name\":\"ticker\",\"product_ids\":[\"BTC-EUR\",\"BTC-USD\"]}]}", ((TextMessage) captureMessage).getPayload()); } @Test void shallhandleTickerTypeMessageCorrectly() throws IOException { //given final WebSocketSession webSocketSession = mock(WebSocketSession.class); String wsMessagePayload = "{\"type\":\"ticker\",\"sequence\":11513619090,\"price\":31039.33,\"side\":\"sell\",\"time\":\"2021-05-25T09:46:04.103024Z\",\"product_id\":\"BTC-EUR\",\"open_24h\":29721.45,\"volume_24h\":5023.57848742,\"low_24h\":29458.91,\"high_24h\":32750.0,\"volume_30d\":95972.9729726,\"best_bid\":31039.33,\"best_ask\":31046.95,\"trade_id\":44317645,\"last_size\":6.4434E-4}"; //when coinbaseWebSocketHandler.handleMessage(webSocketSession, new TextMessage(wsMessagePayload)); //then ArgumentCaptor<CoinbaseInstrument> coinbaseInstrumentArgumentCaptor = ArgumentCaptor.forClass(CoinbaseInstrument.class); verify(coinbaseFacade).add(coinbaseInstrumentArgumentCaptor.capture()); final CoinbaseInstrument value = coinbaseInstrumentArgumentCaptor.getValue(); assertEquals("ticker",value.getType()); assertEquals(11513619090L,value.getSequence()); assertEquals(31039.33,value.getPrice()); assertEquals("sell",value.getSide()); assertEquals("2021-05-25T09:46:04.103024Z",value.getTime()); assertEquals("BTC-EUR",value.getProductId()); assertEquals(29721.45,value.getOpen24h()); assertEquals(5023.57848742,value.getVolume24h()); assertEquals(29458.91,value.getLow24h()); assertEquals(32750.0,value.getHigh24h()); assertEquals(95972.9729726,value.getVolume30d()); assertEquals(31039.33,value.getBestBid()); assertEquals(31046.95,value.getBestAsk()); assertEquals(44317645L,value.getTradeId()); assertEquals(6.4434E-4,value.getLastSize()); } }
package com.mabang.android.okhttp.builder; import java.util.Map; /** * Created by View on 2016 11/14 */ public interface HasParamsable { OkHttpRequestBuilder params(Map<String, String> params); OkHttpRequestBuilder addParams(String key, String val); }
import cc.arduino.Arduino; /** * Created by stk on 16/01/21. */ public class MyServo { private Arduino arduino; private int pin; private int angle; public MyServo(Arduino a, int arduinoPin, int startAngle) { arduino = a; pin = arduinoPin; angle = startAngle; a.pinMode(arduinoPin, Arduino.SERVO); arduino.servoWrite(pin, angle); } public void increase(){ if(angle >= 180){ return; } arduino.servoWrite(pin, angle++); System.out.println("servo pin : " + pin + " angle : " + angle); } public void decrease(){ if(angle <= 0){ return; } arduino.servoWrite(pin, angle--); System.out.println("servo pin : " + pin + " angle : " + angle); } }
package com.example.van.baotuan.widget.item; import android.content.Context; import android.os.Build; import android.support.annotation.RequiresApi; import android.util.AttributeSet; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.example.van.baotuan.R; /** * Created by Van on 2016/11/06. */ public class MsgItem extends LinearLayout{ ImageView IV_avatar; //头像框 TextView TV_userName; TextView TV_time; TextView TV_content; //消息内容 public MsgItem(Context context) { super(context); init(); } public MsgItem(Context context, AttributeSet attrs) { super(context, attrs); init(); } public MsgItem(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public MsgItem(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } private void init(){ IV_avatar = (ImageView) findViewById(R.id.IV_avatar); TV_userName = (TextView) findViewById(R.id.TV_userName); TV_time = (TextView) findViewById(R.id.TV_time); TV_content = (TextView) findViewById(R.id.TV_content); } private void setContent(){ } }
package file; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; /** Static convenience methods for creating and accessing zip files. */ // See java.sun.com/developer/technicalArticles/Programming/compression/ // and www.dogma.net/markn/articles/JavaZip/JavaZip.html public final class Zip { private static final Pattern ARGS = Pattern.compile ("-?[cxt]v?f?n?"); private static final int BUF_SIZE = 1024; private File file; private ZipFile zf; // only used when reading private ZipOutputStream zos; // only used when writing private Zip (final File file) { this.file = file; } /** Return a list of entries in the given zip file. */ public static List<ZipEntry> entries (final File file) throws IOException { List<ZipEntry> entries = new ArrayList<ZipEntry>(); if (file.isFile()) { Zip zip = new Zip (file); zip.zf = new ZipFile (file); entries = zip.unzip ((String) null, "t"); zip.zf.close(); } return entries; } /** * Extracts all of the files in the given zip file into the given * directory (which is optional). Returns the number of files * unzipped, or a negative number to indicate an error. */ public static int unzip (final File file, final String dir) throws IOException { return unzip (file, dir, "xv"); } public static int unzip (final File file, final String dir, final String operation) throws IOException { if (!file.isFile()) return -1; Zip zip = new Zip (file); zip.zf = new ZipFile (file); int count = zip.zf.size(); zip.unzip (dir, operation); zip.zf.close(); return count; } private List<ZipEntry> unzip (final String dir, final String operation) throws IOException { List<ZipEntry> list = new ArrayList<ZipEntry>(); Enumeration<? extends ZipEntry> entries = zf.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (!entry.isDirectory()) { list.add (entry); if (operation.contains ("v") || operation.contains ("x")) unzipEntry (entry, dir, operation); } // TBD: else mkdir? } return list; } /** * Extract the zip-file entry into the given directory with the given * operation string.<br> * "x" - extract contents (default off)<br> * "v" - verbose output (default off)<br> * "n" - never overwrite files (default off) */ private void unzipEntry (final ZipEntry entry, final String dir, final String operation) throws IOException { File f = new File (entry.getName()); if (operation.contains ("v")) System.out.println (f.getPath()); if (operation.contains ("x")) { String parent = f.getParent(); if (!parent.toUpperCase().startsWith("META-INF")) // Ignore JAR META-INF { // create any necessary directories if (dir != null) parent = dir + File.separator + parent; FileUtils.makeDir (parent); String path = parent + File.separator + f.getName(); if (!operation.contains("n") || !new File(path).exists()) extractFile (zf.getInputStream (entry), path); } else System.out.println ("Ignoring extraction of META-INF path"); } } private void extractFile (final InputStream is, final String path) throws IOException { FileOutputStream fos = new FileOutputStream (path); BufferedOutputStream bos = new BufferedOutputStream (fos); // TBD: encoding is probably required for database files BufferedInputStream bis = new BufferedInputStream (is, BUF_SIZE); int count; byte[] data = new byte [BUF_SIZE]; while ((count = bis.read (data, 0, BUF_SIZE)) != -1) bos.write (data, 0, count); bis.close(); bos.close(); } /** * Compresses and archives the given list of files into a ZIP file, * optionally deleting the input files. */ public static boolean zip (final Collection<String> inNames, final String outName, final boolean delete) { return zip (inNames, outName, "cv", delete); } public static boolean zip (final Collection<String> inNames, final String outName, final String operation, final boolean delete) { Zip zip = new Zip (new File (outName)); return zip.zip (inNames, delete, operation); } private boolean zip (final Collection<String> inNames, final boolean delete, final String operation) { try { FileOutputStream fos = new FileOutputStream (file); BufferedOutputStream bos = new BufferedOutputStream (fos); this.zos = new ZipOutputStream (bos); for (String fileName : inNames) zipFile (new File (fileName), delete, operation); zos.flush(); zos.close(); return true; } catch (IOException x) { System.err.println ("Could not zip: " + x.getMessage()); return false; } } private void zipFile (final File f, final boolean delete, final String operation) throws IOException { if (f.getCanonicalFile().equals (file.getCanonicalFile())) return; // don't try to zip yourself! if (f.isDirectory()) for (File dirEntry : f.listFiles()) zipFile (dirEntry, delete, operation); // recurse else { if (operation.contains ("v")) System.out.println (f.getPath()); if (operation.contains ("c")) { insertFile (f); if (delete) if (!f.delete()) System.err.println ("Zip.zipFile() failed to delete: " + f); } } } private void insertFile (final File f) throws IOException { FileInputStream fis = new FileInputStream (f); BufferedInputStream bis = new BufferedInputStream (fis, BUF_SIZE); ZipEntry entry = new ZipEntry (f.getPath()); zos.putNextEntry (entry); // add entry to ZIP file int count; byte[] data = new byte [BUF_SIZE]; while ((count = bis.read (data, 0, BUF_SIZE)) != -1) zos.write (data, 0, count); bis.close(); } public static void main (final String[] args) { if (args.length > 1) { Matcher m = ARGS.matcher (args[0]); if (m.matches()) { try { String operation = args[0]; String zipFile = args[1]; boolean delete = false; // TBD if (operation.contains ("c")) { Collection<String> files = new ArrayList<String>(); for (int i = 2, n = args.length; i < n; i++) files.add (args[i]); if (Zip.zip (files, zipFile, operation, delete)) System.out.println ("\n" + zipFile + " created."); } else { String dir = args.length > 2 ? args[2] : null; int count = Zip.unzip (new File (zipFile), dir, operation); System.out.println ("\nEntries in " + zipFile + ": " + count); } } catch (IOException x) { System.err.println (x); } System.exit (0); } } // TBD: // Usage: jar {ctxu}[vfm0Mi] [jar-file] [manifest-file] [-C dir] files ... // - support deleting inserted files // - support extracting specified files System.out.println ("\nUsage: java " + Zip.class.getName() + " {ctx}[vfn] zipfile [files-to-zip... or target-dir]"); } }
class week5qsn7 { public static void main(String args[]) { int num[] = {10, 11, 12, 1, 14}; float sum=0.0f; float avg; for(int i=0; i<num.length; i++){ sum = sum+num[i]; } avg=(sum/num.length); } }
package tasks; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.zip.GZIPOutputStream; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import extraction.EFWExtractor; import extraction.Extractor; import extraction.logging.ConsoleLogger; import extraction.logging.Logger; import extraction.output.TextOutputHandler; import extraction.output.OutputHandlerFactory; import queue.Queue; import queue.TextQueue; import runner.QueueExtractionRunner; import runner.Runner; import utils.CommonCrawlSource; import utils.Utils; public class RunEFWExtractor { private final static Options options; static { options = new Options(); options.addOption("q", "queuePath", true, "Path to TextQeue directory."); options.addOption("o", "outputPath", true, "Path to save output."); options.addOption("t", "threads", true, "Number of threads to use."); options.addOption("z", "zip", false, "Whether to gzip output."); options.addOption("s", "stream", false, "Whether to download archives instead of streaming."); } public static void main(String[] args) { CommandLineParser parser = new BasicParser(); CommandLine cmd; try { cmd = parser.parse(options, args); String queuePath = cmd.getOptionValue("q"); String outputPath = cmd.getOptionValue("o"); int threadNo = Integer.parseInt(cmd.getOptionValue("t")); boolean zip = cmd.hasOption("z"); boolean stream = cmd.hasOption("s"); Extractor extractor = new EFWExtractor(); Queue<String> queue = new TextQueue(new File(queuePath)); OutputHandlerFactory factory = (String element, Logger logger) -> { File outputFile = new File(outputPath + File.separator + CommonCrawlSource.getFileNameFromUrl(element)); try { Writer writer; if (zip) { writer = new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outputFile))); } else { writer = new FileWriter(outputFile); } return new TextOutputHandler(logger, new BufferedWriter(writer), true); } catch (IOException e) { e.printStackTrace(); } return null; }; Logger logger = new ConsoleLogger(); Runner runner = new QueueExtractionRunner(Utils.getHostname(), extractor, queue, factory, logger, threadNo, stream); runner.run(); } catch (ParseException e) { e.printStackTrace(); } } }
package com.gaoshin.fbobuilder.client.model; import java.util.List; import net.edzard.kinetic.PathSVG; import net.edzard.kinetic.Vector2d; public class FpathSVG extends Fshape<PathSVG> { public FpathSVG(PathSVG node) { super(node); } @Override public List<Vector2d> getAnchors() { throw new RuntimeException("unimplemented"); } }
package com.itfacesystem.domain.systemsequence; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Version; import java.io.Serializable; /** * Created by wangrongtao on 2017/4/9. */ @Entity @Table(name="system_sequence") public class SystemSequence implements Serializable { @Id private String type; private Long sequenceindex; @Version private Long version; public String getType() { return type; } public void setType(String type) { this.type = type; } public Long getSequenceindex() { return sequenceindex; } public void setSequenceindex(Long sequenceindex) { this.sequenceindex = sequenceindex; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } }
/* * 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 centro.de.computo; import java.net.URL; import java.sql.SQLException; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.stage.Stage; import javax.swing.JOptionPane; import logica.InterfaceInventarioHardware; import logica.InventarioHardware; /** * FXML Controller class. * @author PREDATOR 15 G9-78Q */ public class CambiarResponsableController implements Initializable { @FXML private ChoiceBox cbResponsable; @FXML private Label labelNumeroSerie; @FXML private Label labelModelo; @FXML private Button bttGuardar; private static String modelo; private static String numeroSerie; private final InterfaceInventarioHardware inventario = new InventarioHardware(); /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { this.labelModelo.setText(CambiarResponsableController.modelo); this.labelNumeroSerie.setText(CambiarResponsableController.numeroSerie); this.cbResponsable.getItems().add("CC1"); this.cbResponsable.getItems().add("CC2"); this.cbResponsable.getItems().add("CC3"); this.cbResponsable.getItems().add("CC4"); this.cbResponsable.getItems().add("Bodega"); this.cbResponsable.getItems().add("Fuera de servicio"); } /** * Este método sirve para enviar los datos del equipo a otra ventana. * @param modelo Dato que se enviará a otra ventana. * @param numeroSerie Dato que se enviará a otra ventana. */ public static void mandarModeloNumeroSerie( String modelo, String numeroSerie) { CambiarResponsableController.modelo = modelo; CambiarResponsableController.numeroSerie = numeroSerie; } @FXML private void clickGuardar(ActionEvent event) { if (this.cbResponsable.getValue() != null) { try { this.inventario.cambiarResponsable(this.labelNumeroSerie.getText(), (String) this.cbResponsable.getValue()); Stage stage = (Stage) bttGuardar.getScene().getWindow(); stage.close(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "El sistema no está disponible por el momento, inténtelo más tarde"); } } else { JOptionPane.showMessageDialog(null, "Seleccione una nueva ubicación"); } } }
package com.cpro.rxjavaretrofit.views.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.cpro.rxjavaretrofit.R; import com.cpro.rxjavaretrofit.entity.ItemPoolListdataEntity; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by lx on 2016/5/31. */ public class HomeworkSupervisionQuestionsAnswerAdapter extends RecyclerView.Adapter { List<ItemPoolListdataEntity> list; public void setList(List<ItemPoolListdataEntity> list){ this.list = list; notifyDataSetChanged(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_homework_supervision_questions_answers, parent, false); return new AnswersViewHolder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { AnswersViewHolder answersViewHolder = (AnswersViewHolder) holder; answersViewHolder.tv_option.setText(list.get(position).getOptionNo() + ":"); answersViewHolder.tv_option_content.setText(list.get(position).getOptionContent()); } @Override public int getItemCount() { return list == null ? 0 : list.size(); } public static class AnswersViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.tv_option) TextView tv_option; @BindView(R.id.tv_option_content) TextView tv_option_content; public AnswersViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
package com.hhdb.csadmin.common.util.commonxmltool; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class NodeEntity { private String name; private String text; private String path; private NodeEntity parentNode; private Map<String, String> attrMap = new HashMap<String, String>(); private List<NodeEntity> childList = new ArrayList<NodeEntity>(); public NodeEntity getParentNode() { return parentNode; } public void setParentNode(NodeEntity parentNode) { this.parentNode = parentNode; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Map<String, String> getAttrMap() { return attrMap; } public void setAttrMap(Map<String, String> attrMap) { this.attrMap = attrMap; } public List<NodeEntity> getChildList() { return childList; } public void setChildList(List<NodeEntity> childList) { this.childList = childList; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("name:" + name + ","); sb.append("text:" + text + ","); sb.append("path:" + path + ","); Set<String> keySet = attrMap.keySet(); sb.append("attr:"); for (String k : keySet) { sb.append(k + ":" + attrMap.get(k) + ","); } //sb.append(childList.toString() + "\r\n"); return sb.toString(); } public void addAttri(String key, String value) { attrMap.put(key, value); } public String getAttri(String key) { return XmlTools.getString(attrMap, key); } public String getAttri(String key, String defaultValue) { return XmlTools.getString(attrMap, key, defaultValue); } public void addNode(NodeEntity node) { childList.add(node); } }
import edu.princeton.cs.algs4.StdRandom; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; public class RandomizedQueue<Item> implements Iterable<Item> { private int n; // number of elements on queue private int capacity; // capacity of q private int minCapacity; // capacity of q private Item[] q; private RandomizedQueue(int minCapacity) { // construct an empty randomized queue this.minCapacity = minCapacity; this.capacity = minCapacity; this.n = 0; this.q = (Item[]) new Object[capacity]; } public RandomizedQueue() { // construct an empty randomized queue this(2); } public boolean isEmpty() { // is the randomized queue empty? return n == 0; } public int size() { // return the number of items on the randomized queue return n; } public void enqueue(Item item) { // add the item if (item == null) throw new java.lang.IllegalArgumentException(); if (n == capacity) { resizeArray(capacity * 2); } q[n++] = item; } public Item dequeue() { // remove and return a random item if (n == 0) throw new NoSuchElementException(); int index = StdRandom.uniform(n); Item ret = q[index]; q[index] = q[--n]; q[n] = null; if (n == capacity / 4) if (capacity / 2 >= minCapacity) resizeArray(capacity / 2); return ret; } public Item sample() { // return a random item (but do not remove it) if (n == 0) throw new NoSuchElementException(); int index = StdRandom.uniform(n); return q[index]; } public Iterator<Item> iterator() { // return an independent iterator over items in random order return new RandomIterator<Item>(q, n); } private class RandomIterator<Item> implements Iterator<Item> { private final Item[] q; private final int n; private final int[] indexes; private int current; public RandomIterator(Item[] q, int n) { this.q = Arrays.copyOf(q, n); this.n = n; this.indexes = StdRandom.permutation(n); this.current = 0; } public boolean hasNext() { return current != n; } public void remove() { throw new UnsupportedOperationException(); } public Item next() { if (!hasNext()) throw new NoSuchElementException(); return q[indexes[current++]]; } } private void resizeArray(int newSize) { q = Arrays.copyOf(q, newSize); capacity = newSize; } public static void main(String[] args) { // unit testing (optional) RandomizedQueue<String> rq = new RandomizedQueue<String>(); assert rq.isEmpty(); rq.enqueue("porcoddio"); assert !rq.isEmpty(); rq.enqueue("porcamadonna"); rq.enqueue("tutti gli angeli"); rq.enqueue("in colonna"); rq.enqueue("un angelo son'io"); rq.enqueue("che mi chiamo"); rq.enqueue("porcoddio"); System.out.println("RQ size: " + rq.size()); assert !rq.isEmpty(); System.out.println(rq.sample()); System.out.println("RQ size: " + rq.size()); for (String s : rq) { System.out.println(s); } } }
package br.com.rmd.demo.dynamo.repository; import br.com.rmd.demo.dynamo.model.Analitico; import br.com.rmd.demo.dynamo.model.Consolidado; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.TransactionWriteRequest; import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; import com.amazonaws.services.dynamodbv2.model.TransactionCanceledException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.retry.annotation.Recover; import org.springframework.retry.annotation.Retryable; import org.springframework.stereotype.Repository; @Slf4j @Repository public class RegistraEventoRepository { @Autowired private DynamoDBMapper dynamoDBMapper; // @Retryable( value = { ConditionalCheckFailedException.class, TransactionCanceledException.class }, maxAttempts = 2 ) public void registrar(Analitico analitico) { TransactionWriteRequest transactionWriteRequest = new TransactionWriteRequest(); Consolidado consolidado = dynamoDBMapper.load( Consolidado.class, analitico.getUsuario(), analitico.getProduto() ); transactionWriteRequest.addPut( analitico ); if ( consolidado != null ) { consolidado.setQuantidadeAcumulada( consolidado.getQuantidadeAcumulada() + analitico.getQuantidade() ); transactionWriteRequest.addUpdate( consolidado ); } else { consolidado = new Consolidado( analitico.getUsuario(), analitico.getProduto(), analitico.getQuantidade(), null ); transactionWriteRequest.addPut( consolidado ); } dynamoDBMapper.transactionWrite( transactionWriteRequest ); } // @Recover // void recover(ConditionalCheckFailedException e, Analitico analitico) { // log.error( String.format( "caiu no retry. %s", analitico ) ); // } // // @Recover // void recover(TransactionCanceledException e, Analitico analitico) { // log.error( String.format( "caiu no retry. %s", analitico ) ); // } }
package com.barclaycard.currency.model; import java.io.Serializable; import java.math.BigDecimal; public class CurrencyDetails implements Serializable { private BigDecimal amount; private String currency; private String noteValue; private int noteCount; private int totalCount; public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public String getNoteValue() { return noteValue; } public void setNoteValue(String noteValue) { this.noteValue = noteValue; } public int getNoteCount() { return noteCount; } public void setNoteCount(int noteCount) { this.noteCount = noteCount; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } }
package com.jlu.sell.repsitory; import com.jlu.sell.dataobject.ProductCategory; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest public class ProductCategoryRepositoryTest { @Autowired private ProductCategoryRepository pcr; @Test public void findOneTest(){ ProductCategory pc = pcr.findById(4).orElse(null); //System.out.println(pc.toString()); Assert.assertNotEquals(null,pc); } @Test public void addTest(){ ProductCategory pc = new ProductCategory(); pc.setCategoryName("男生最爱"); pc.setCategoryType(1); pcr.save(pc); } @Test public void updateTest(){ ProductCategory pc = pcr.findById(4).get(); pc.setCategoryName("老人最爱"); pc.setCategoryType(4); pcr.save(pc); } @Test public void findByCategoryTypeInTest(){ List<Integer> types = new ArrayList<Integer>(); types.add(2);types.add(3);types.add(4); List<ProductCategory> list = pcr.findByCategoryTypeIn(types); System.out.println(2); } }
package com.cninnovatel.ev; import java.util.Locale; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import android.view.View.OnLayoutChangeListener; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import com.cninnovatel.ev.api.ApiClient; import com.cninnovatel.ev.me.MyprofilePassword; import com.cninnovatel.ev.utils.NetworkUtil; import com.cninnovatel.ev.utils.ProgressUtil; import com.cninnovatel.ev.utils.ScreenUtil; import com.cninnovatel.ev.utils.Utils; public class Login extends Activity implements OnLayoutChangeListener { private static Logger log = Logger.getLogger(Login.class); private Activity context; private TextView error_msg; private EditText ucmServer; private EditText username; private EditText password; private RelativeLayout rl_normal; private RelativeLayout rl_moveup; private Button loginBtn; private View activityRootView; private int keyHeight = 0; private SharedPreferences sp = null; private ProgressUtil progress = null; public static void actionStart(Context context) { Intent intent = new Intent(context, Login.class); intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } public static void actionStart(Context context, String error_msg) { Intent intent = new Intent(context, Login.class); intent.putExtra("error_msg", error_msg); intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); log.debug("onCreate()"); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.login); context = this; activityRootView = findViewById(R.id.root_layout); keyHeight = ScreenUtil.getHeight(this) / 3; TextView login_version = (TextView) findViewById(R.id.login_version); login_version.setText(getString(R.string.login_version) + " " + Utils.getVersion()); rl_normal = (RelativeLayout) findViewById(R.id.rl_normal); rl_moveup = (RelativeLayout) findViewById(R.id.rl_moveup); loginBtn = (Button) findViewById(R.id.login); sp = getSharedPreferences("login", Context.MODE_PRIVATE); progress = new ProgressUtil(context, 12000, new Runnable() { @Override public void run() { loginBtn.setEnabled(true); loginBtn.setTextColor(Color.parseColor("#ffffff")); Utils.showToastWithCustomLayout(context, getString(R.string.login_timeout)); } }, getString(R.string.logging)); error_msg = (TextView) findViewById(R.id.error_msg); ucmServer = (EditText) findViewById(R.id.ucmServer); username = (EditText) findViewById(R.id.username); password = (EditText) findViewById(R.id.password); String error = getIntent().getStringExtra("error_msg"); if (error != null) { error_msg.setVisibility(View.VISIBLE); error_msg.setText(" " + error + " "); } Typeface customFont = Typeface.createFromAsset(this.getAssets(), "fonts/MyFont.ttf"); TextView view = (TextView) findViewById(R.id.title); view.setTypeface(customFont); findViewById(R.id.rl_server).setAlpha(0.4f); findViewById(R.id.rl_username).setAlpha(0.4f); findViewById(R.id.rl_password).setAlpha(0.4f); findViewById(R.id.line_one).setAlpha(0.3f); View line_two = findViewById(R.id.line_two); line_two.setAlpha(0.3f); ucmServer.setText(sp.getString("ucmserver", "")); username.setText(sp.getString("username", "")); password.setText(sp.getString("password", "")); if (ucmServer.getText().length() > 0) { password.requestFocus(); } else { ucmServer.requestFocus(); } password.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) { login(); return true; } return false; } }); loginBtn.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { if (login()) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } }); } private boolean login() { String ucm_server_address = ucmServer.getText().toString().trim(); if (StringUtils.isEmpty(ucm_server_address)) { log.warn("ucm server address is empty!"); Utils.showToastWithCustomLayout(context, getString(R.string.please_enter_server_address)); return false; } String uName = username.getText().toString().trim(); if (StringUtils.isEmpty(uName)) { Utils.showToastWithCustomLayout(context, getString(R.string.please_enter_your_account)); return false; } String pwd = password.getText().toString().trim(); if (StringUtils.isEmpty(pwd)) { Utils.showToastWithCustomLayout(context, getString(R.string.please_enter_your_password)); return false; } App.setNetworkConnected(NetworkUtil.isNetConnected(context)); if (!App.isNetworkConnected()) { Utils.showToastInNewThread(context, getString(R.string.server_unavailable)); return false; } Editor editor = sp.edit(); if (!ucm_server_address.contains(".")) { RuntimeData.setUcmServer(ucm_server_address + ".cninnovatel.com"); } else { RuntimeData.setUcmServer(ucm_server_address); } editor.putString("ucmserver", ucm_server_address); editor.putString("username", uName); editor.commit(); ApiClient.reset(); LoginService.getInstance().login(uName, pwd, handler); progress.showDelayed(1000); loginBtn.setEnabled(false); loginBtn.setTextColor(Color.parseColor("#919191")); return true; } final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); progress.dismiss(); if (msg.what == 0) { Editor editor = sp.edit(); editor.putString("password", password.getText().toString()); editor.putBoolean("login", true); editor.commit(); Intent i = getIntent(); if (RuntimeData.getLogUser() != null && RuntimeData.getLogUser().isPasswordModifiedByUser() == false) { if (i != null) { log.debug("login - onCreate data:" + i.getData()); MyprofilePassword.actionStart(context, i.getData()); } else { MyprofilePassword.actionStart(context); } } else { if (i != null) { log.debug("login - onCreate data:" + i.getData()); HexMeet.actionStart(context, i.getData()); } else { log.debug("login - start hexmeet without data intent"); HexMeet.actionStart(context); } } finish(); } else if (msg.what == -1) { loginBtn.setEnabled(true); loginBtn.setTextColor(Color.parseColor("#ffffff")); String errorMsg = (String) msg.obj; if (errorMsg != null && !errorMsg.toLowerCase().contains("failed to connect to")) { String lower = errorMsg.toLowerCase(Locale.US); if (errorMsg.contains(getString(R.string.invalid_username_or_password))) { errorMsg = getString(R.string.error_account_or_password); Utils.showToastWithCustomLayout(context, errorMsg); } else if (lower.contains("handshake timed out")) { Utils.showToastWithCustomLayout(context, getString(R.string.server_unavailable)); } else if (lower.contains("timeout")) { Utils.showToastWithCustomLayout(context, getString(R.string.server_unavailable)); } else if (lower.contains("unable to resolve host")) { Utils.showToastWithCustomLayout(context, getString(R.string.invalid_server_address)); } else { Utils.showToastWithCustomLayout(context, errorMsg); } } } } }; @Override protected void onResume() { super.onResume(); activityRootView.addOnLayoutChangeListener(this); } @Override protected void onDestroy() { super.onDestroy(); } @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) { //setTranslucentStatus(false); rl_normal.setVisibility(View.GONE); rl_moveup.setVisibility(View.VISIBLE); //setTranslucentStatus(true); } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) { rl_normal.setVisibility(View.VISIBLE); rl_moveup.setVisibility(View.GONE); } } private void setTranslucentStatus(boolean enable) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); if (enable) { winParams.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; } else { winParams.flags &= ~WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; } win.setAttributes(winParams); } }
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.identity.recovery.handler.request; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.wso2.carbon.identity.application.authentication.framework.config.ConfigurationFacade; import org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig; import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; import org.wso2.carbon.identity.application.authentication.framework.handler.request.PostAuthnHandlerFlowStatus; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.application.common.model.IdentityProvider; import org.wso2.carbon.identity.application.common.model.IdentityProviderProperty; import org.wso2.carbon.identity.mgt.util.Utils; import org.wso2.carbon.identity.recovery.ChallengeQuestionManager; import org.wso2.carbon.identity.recovery.IdentityRecoveryConstants; import org.wso2.carbon.identity.recovery.internal.IdentityRecoveryServiceDataHolder; import org.wso2.carbon.identity.recovery.model.ChallengeQuestion; import org.wso2.carbon.idp.mgt.IdentityProviderManager; import org.wso2.carbon.user.core.UserCoreConstants; import org.wso2.carbon.user.core.UserRealm; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static org.mockito.Mockito.spy; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.mockito.Mockito.when; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.any; /** * This class will test the Post Authentication Handler for Missing Challenge Questions **/ public class PostAuthnMissingChallengeQuestionsHandlerTest { private static final String CHALLENGE_QUESTIONS_REQUESTED = "challengeQuestionsRequested"; @Mock private HttpServletRequest httpServletRequest; @Mock private HttpServletResponse httpServletResponse; @Mock private IdentityProviderManager identityProviderManager; @Mock private IdentityRecoveryServiceDataHolder frameworkServiceDataHolder; @Mock private ChallengeQuestionManager challengeQuestionManager; @Mock private ConfigurationFacade configurationFacade; private MockedStatic<HttpServletResponse> mockedHttpServletResponse; private MockedStatic<IdentityProviderManager> mockedIdentityProviderManager; private MockedStatic<MultitenantUtils> mockedMultitenantUtils; private MockedStatic<Utils> mockedUtils; private MockedStatic<IdentityRecoveryServiceDataHolder> mockedIdentityRecoveryServiceDataHolder; private MockedStatic<ChallengeQuestionManager> mockedChallengeQuestionManager; private MockedStatic<ConfigurationFacade> mockedConfigurationFacade; @BeforeMethod public void setup() { // initialize all the @Mock objects MockitoAnnotations.openMocks(this); mockedHttpServletResponse = Mockito.mockStatic(HttpServletResponse.class); mockedIdentityProviderManager = Mockito.mockStatic(IdentityProviderManager.class); mockedMultitenantUtils = Mockito.mockStatic(MultitenantUtils.class); mockedUtils = Mockito.mockStatic(Utils.class); mockedIdentityRecoveryServiceDataHolder = Mockito.mockStatic(IdentityRecoveryServiceDataHolder.class); mockedChallengeQuestionManager = Mockito.mockStatic(ChallengeQuestionManager.class); mockedConfigurationFacade = Mockito.mockStatic(ConfigurationFacade.class); } @AfterMethod public void tearDown() { mockedHttpServletResponse.close(); mockedIdentityProviderManager.close(); mockedMultitenantUtils.close(); mockedUtils.close(); mockedIdentityRecoveryServiceDataHolder.close(); mockedChallengeQuestionManager.close(); mockedConfigurationFacade.close(); } @Test(description = "Test get instance method") public void testGetInstance() { testSingleton( PostAuthnMissingChallengeQuestionsHandler.getInstance(), PostAuthnMissingChallengeQuestionsHandler.getInstance() ); } @DataProvider(name = "forceChallengeQuestionSettings") public Object[][] forceChallengeQuestionSettings() { return new Object[][]{ {"false"}, {"random_text"}, {null}, }; } @Test(dataProvider = "forceChallengeQuestionSettings", description = "Test the functionality of the setting to " + "force challenge questions") public void testSettingTheOptionToForceChallengeQuestions(String setting) throws Exception { AuthenticationContext context = spy(new AuthenticationContext()); when(context.getTenantDomain()).thenReturn("carbon.super"); IdentityProvider residentIdp = spy(new IdentityProvider()); IdentityProviderProperty[] idpProperties = new IdentityProviderProperty[1]; IdentityProviderProperty idpProp = new IdentityProviderProperty(); if (setting != null) { idpProp.setName(IdentityRecoveryConstants.ConnectorConfig.FORCE_ADD_PW_RECOVERY_QUESTION); idpProp.setValue(setting); } else { idpProp.setName(IdentityRecoveryConstants.ConnectorConfig.ACCOUNT_LOCK_ON_CREATION); idpProp.setValue("true"); } idpProperties[0] = idpProp; residentIdp.setIdpProperties(idpProperties); mockedIdentityProviderManager.when(IdentityProviderManager::getInstance).thenReturn(identityProviderManager); when(identityProviderManager.getResidentIdP("carbon.super")).thenReturn(residentIdp); PostAuthnHandlerFlowStatus flowStatus = PostAuthnMissingChallengeQuestionsHandler.getInstance().handle (httpServletRequest, httpServletResponse, context); String expectedResult; if (setting == null) { setting = "null"; } switch (setting) { case "false": expectedResult = PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED.name(); break; case "true": expectedResult = PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED.name(); break; case "null": expectedResult = PostAuthnHandlerFlowStatus.UNSUCCESS_COMPLETED.name(); break; default: expectedResult = PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED.name(); break; } assertEquals(flowStatus.name(), expectedResult); } @Test(description = "Test the behaviour of the handler if the user is null") public void testForNullUser() throws Exception { AuthenticationContext context = spy(new AuthenticationContext()); when(context.getTenantDomain()).thenReturn("carbon.super"); IdentityProvider residentIdp = spy(new IdentityProvider()); IdentityProviderProperty[] idpProperties = new IdentityProviderProperty[1]; IdentityProviderProperty idpProp = new IdentityProviderProperty(); idpProp.setName(IdentityRecoveryConstants.ConnectorConfig.FORCE_ADD_PW_RECOVERY_QUESTION); idpProp.setValue("true"); idpProperties[0] = idpProp; residentIdp.setIdpProperties(idpProperties); mockedIdentityProviderManager.when(IdentityProviderManager::getInstance).thenReturn(identityProviderManager); when(identityProviderManager.getResidentIdP("carbon.super")).thenReturn(residentIdp); SequenceConfig sequenceConfig = spy(new SequenceConfig()); when(sequenceConfig.getAuthenticatedUser()).thenReturn(null); context.setSequenceConfig(sequenceConfig); PostAuthnHandlerFlowStatus flowStatus = PostAuthnMissingChallengeQuestionsHandler.getInstance().handle (httpServletRequest, httpServletResponse, context); String expectedResult = PostAuthnHandlerFlowStatus.UNSUCCESS_COMPLETED.name(); assertEquals(flowStatus.name(), expectedResult); } @Test(description = "Test the flow for the user who has already given the challenge questions") public void testAlreadyChallengeQuestionProvidedUserFlow() throws Exception { AuthenticationContext context = spy(new AuthenticationContext()); when(context.getTenantDomain()).thenReturn("carbon.super"); IdentityProvider residentIdp = spy(new IdentityProvider()); IdentityProviderProperty[] idpProperties = new IdentityProviderProperty[1]; IdentityProviderProperty idpProp = new IdentityProviderProperty(); idpProp.setName(IdentityRecoveryConstants.ConnectorConfig.FORCE_ADD_PW_RECOVERY_QUESTION); idpProp.setValue("true"); idpProperties[0] = idpProp; residentIdp.setIdpProperties(idpProperties); mockedIdentityProviderManager.when(IdentityProviderManager::getInstance).thenReturn(identityProviderManager); when(identityProviderManager.getResidentIdP("carbon.super")).thenReturn(residentIdp); SequenceConfig sequenceConfig = spy(new SequenceConfig()); AuthenticatedUser user = spy(new AuthenticatedUser()); user.setUserName("admin"); when(sequenceConfig.getAuthenticatedUser()).thenReturn(user); context.setSequenceConfig(sequenceConfig); mockedMultitenantUtils.when(() -> MultitenantUtils.getTenantDomain("admin")).thenReturn("carbon.super"); mockedUtils.when(() -> Utils.getTenantId("carbon.super")).thenReturn(-1234); mockedIdentityRecoveryServiceDataHolder.when(IdentityRecoveryServiceDataHolder::getInstance) .thenReturn(frameworkServiceDataHolder); RealmService realmService = mock(RealmService.class); UserStoreManager userStoreManager = mock(UserStoreManager.class); UserRealm userRealm = mock(UserRealm.class); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); when(realmService.getTenantUserRealm(-1234)).thenReturn(userRealm); when(frameworkServiceDataHolder.getRealmService()).thenReturn(realmService); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); Map<String, String> claimsMap = new HashMap<>(); claimsMap.put(IdentityRecoveryConstants.CHALLENGE_QUESTION_URI, "dummy_data"); when(userStoreManager.getUserClaimValues("admin", new String[]{IdentityRecoveryConstants .CHALLENGE_QUESTION_URI}, UserCoreConstants.DEFAULT_PROFILE)).thenReturn(claimsMap); PostAuthnHandlerFlowStatus flowStatus = PostAuthnMissingChallengeQuestionsHandler.getInstance().handle (httpServletRequest, httpServletResponse, context); String expectedResult = PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED.name(); assertEquals(flowStatus.name(), expectedResult); } @Test(description = "Test the flow of challenge question post authentication handler before requesting challenge " + "questions from the user") public void testBeforeRequestingChallengeQuestionFlow() throws Exception { AuthenticationContext context = spy(new AuthenticationContext()); when(context.getTenantDomain()).thenReturn("carbon.super"); IdentityProvider residentIdp = spy(new IdentityProvider()); IdentityProviderProperty[] idpProperties = new IdentityProviderProperty[1]; IdentityProviderProperty idpProp = new IdentityProviderProperty(); idpProp.setName(IdentityRecoveryConstants.ConnectorConfig.FORCE_ADD_PW_RECOVERY_QUESTION); idpProp.setValue("true"); idpProperties[0] = idpProp; residentIdp.setIdpProperties(idpProperties); mockedIdentityProviderManager.when(IdentityProviderManager::getInstance).thenReturn(identityProviderManager); when(identityProviderManager.getResidentIdP("carbon.super")).thenReturn(residentIdp); SequenceConfig sequenceConfig = spy(new SequenceConfig()); AuthenticatedUser user = spy(new AuthenticatedUser()); user.setUserName("admin"); when(sequenceConfig.getAuthenticatedUser()).thenReturn(user); context.setSequenceConfig(sequenceConfig); mockedMultitenantUtils.when(() -> MultitenantUtils.getTenantDomain("admin")).thenReturn("carbon.super"); mockedUtils.when(() -> Utils.getTenantId("carbon.super")).thenReturn(-1234); mockedIdentityRecoveryServiceDataHolder.when(IdentityRecoveryServiceDataHolder::getInstance) .thenReturn(frameworkServiceDataHolder); RealmService realmService = mock(RealmService.class); UserStoreManager userStoreManager = mock(UserStoreManager.class); UserRealm userRealm = mock(UserRealm.class); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); when(realmService.getTenantUserRealm(-1234)).thenReturn(userRealm); when(frameworkServiceDataHolder.getRealmService()).thenReturn(realmService); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); Map<String, String> claimsMap = new HashMap<>(); when(userStoreManager.getUserClaimValues("admin", new String[]{IdentityRecoveryConstants .CHALLENGE_QUESTION_URI}, UserCoreConstants.DEFAULT_PROFILE)).thenReturn(claimsMap); List<ChallengeQuestion> challengeQuestions = new ArrayList<>(); ChallengeQuestion challengeQuestion = spy(new ChallengeQuestion()); challengeQuestion.setQuestionSetId("dummy_set"); challengeQuestion.setQuestionId("dummy_id"); challengeQuestion.setQuestion("dummy_question"); challengeQuestions.add(challengeQuestion); when(challengeQuestionManager.getAllChallengeQuestions("carbon.super")).thenReturn(challengeQuestions); mockedChallengeQuestionManager.when(ChallengeQuestionManager::getInstance).thenReturn(challengeQuestionManager); doNothing().doThrow(Exception.class).when(httpServletResponse).sendRedirect((String) any()); when(configurationFacade.getAuthenticationEndpointURL()).thenReturn(""); when(ConfigurationFacade.getInstance()).thenReturn(configurationFacade); PostAuthnHandlerFlowStatus flowStatus = PostAuthnMissingChallengeQuestionsHandler.getInstance().handle (httpServletRequest, httpServletResponse, context); String expectedResult = PostAuthnHandlerFlowStatus.INCOMPLETE.name(); assertEquals(flowStatus.name(), expectedResult); } @Test(description = "Test the flow of challenge question post authentication handler after requesting challenge " + "questions from the user") public void testAfterRequestingChallengeQuestionFlow() throws Exception { AuthenticationContext context = spy(new AuthenticationContext()); when(context.getTenantDomain()).thenReturn("carbon.super"); IdentityProvider residentIdp = spy(new IdentityProvider()); IdentityProviderProperty[] idpProperties = new IdentityProviderProperty[1]; IdentityProviderProperty idpProp = new IdentityProviderProperty(); idpProp.setName(IdentityRecoveryConstants.ConnectorConfig.FORCE_ADD_PW_RECOVERY_QUESTION); idpProp.setValue("true"); idpProperties[0] = idpProp; residentIdp.setIdpProperties(idpProperties); mockedIdentityProviderManager.when(IdentityProviderManager::getInstance).thenReturn(identityProviderManager); when(identityProviderManager.getResidentIdP("carbon.super")).thenReturn(residentIdp); SequenceConfig sequenceConfig = spy(new SequenceConfig()); AuthenticatedUser user = spy(new AuthenticatedUser()); user.setUserName("admin"); when(sequenceConfig.getAuthenticatedUser()).thenReturn(user); context.setSequenceConfig(sequenceConfig); mockedMultitenantUtils.when(() -> MultitenantUtils.getTenantDomain("admin")).thenReturn("carbon.super"); mockedUtils.when(() -> Utils.getTenantId("carbon.super")).thenReturn(-1234); mockedIdentityRecoveryServiceDataHolder.when(IdentityRecoveryServiceDataHolder::getInstance) .thenReturn(frameworkServiceDataHolder); RealmService realmService = mock(RealmService.class); UserStoreManager userStoreManager = mock(UserStoreManager.class); UserRealm userRealm = mock(UserRealm.class); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); when(realmService.getTenantUserRealm(-1234)).thenReturn(userRealm); when(frameworkServiceDataHolder.getRealmService()).thenReturn(realmService); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); Map<String, String> claimsMap = new HashMap<>(); when(userStoreManager.getUserClaimValues("admin", new String[]{IdentityRecoveryConstants .CHALLENGE_QUESTION_URI}, UserCoreConstants.DEFAULT_PROFILE)).thenReturn(claimsMap); List<ChallengeQuestion> challengeQuestions = new ArrayList<>(); ChallengeQuestion challengeQuestion = spy(new ChallengeQuestion()); challengeQuestion.setQuestionSetId("dummy_set"); challengeQuestion.setQuestionId("dummy_id"); challengeQuestion.setQuestion("dummy_question"); challengeQuestions.add(challengeQuestion); when(challengeQuestionManager.getAllChallengeQuestions("carbon.super")).thenReturn(challengeQuestions); mockedChallengeQuestionManager.when(ChallengeQuestionManager::getInstance).thenReturn(challengeQuestionManager); doNothing().doThrow(Exception.class).when(httpServletResponse).sendRedirect((String) any()); when(configurationFacade.getAuthenticationEndpointURL()).thenReturn(""); mockedConfigurationFacade.when(ConfigurationFacade::getInstance).thenReturn(configurationFacade); when(context.getParameter(CHALLENGE_QUESTIONS_REQUESTED)).thenReturn(true); Vector<String> set = new Vector<>(); set.add("Q-dummy_question"); set.add("A-dummy_answer"); Enumeration<String> paramNames = new Vector(set).elements(); when(httpServletRequest.getParameterNames()).thenReturn(paramNames); when(httpServletRequest.getParameter(anyString())).thenReturn("dummy_question"); PostAuthnHandlerFlowStatus flowStatus = PostAuthnMissingChallengeQuestionsHandler.getInstance().handle (httpServletRequest, httpServletResponse, context); String expectedResult = PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED.name(); assertEquals(flowStatus.name(), expectedResult); } public static void testSingleton(Object instance, Object anotherInstance) { assertNotNull(instance); assertNotNull(anotherInstance); assertEquals(instance, anotherInstance); } }
package com.madrapps.dagger.module.binds; import com.madrapps.dagger.models.MudTrail; import dagger.Component; @Component(modules = BindModule.class) public interface BindComponent { MudTrail mudTrail(); }
package com.test.base; /** * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). * 假设有一个升序的数组,被某一个不确定的点旋转了; * (例如[0,1,2,4,5,6,7] 可能成了 [4,5,6,7,0,1,2]) * * You are given a target value to search. If found in the array return its index, otherwise return -1. * 你需要在旋转后的数组中,寻找一个值;若存在,则返回该值的位置,否则返回-1 * * You may assume no duplicate exists in the array. * 数组中,没有重复的值 * * Your algorithm's runtime complexity must be in the order of O(log n). * 你的算法时间复杂度,必须为,O(log n) * * @author YLine * * 2018年9月18日 下午4:31:25 */ public interface Solution { int search(int[] nums, int target); }
package com.woniu.pojo; import java.io.Serializable; public class Zhenshi implements Serializable { private Integer zhenshiId; private Integer officeId; private String zhenshiName; private static final long serialVersionUID = 1L; public Zhenshi(Integer zhenshiId, Integer officeId, String zhenshiName) { this.zhenshiId = zhenshiId; this.officeId = officeId; this.zhenshiName = zhenshiName; } public Zhenshi() { super(); } public Integer getZhenshiId() { return zhenshiId; } public void setZhenshiId(Integer zhenshiId) { this.zhenshiId = zhenshiId; } public Integer getOfficeId() { return officeId; } public void setOfficeId(Integer officeId) { this.officeId = officeId; } public String getZhenshiName() { return zhenshiName; } public void setZhenshiName(String zhenshiName) { this.zhenshiName = zhenshiName == null ? null : zhenshiName.trim(); } }
package com.example.vkoshkin.bandsapplication.main.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.example.vkoshkin.bandsapplication.R; import com.example.vkoshkin.bandsapplication.common.model.BandModel; import com.example.vkoshkin.bandsapplication.main.fragments.adapters.BandsAdapter; import com.example.vkoshkin.bandsapplication.main.fragments.events.BandsLoadRequiredEvent; import com.example.vkoshkin.bandsapplication.main.fragments.events.BandsLoadedEvent; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.util.List; /** * Фрагмент списка всех исполнителей. */ public final class BandsListFragment extends Fragment { private RecyclerView mBandList; private ProgressBar mProgressBar; private SwipeRefreshLayout mSwipeRefreshLayout; private TextView mStatusView; private BandsAdapter mAdapter; private EventBus mBus = EventBus.getDefault(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @SuppressWarnings("ConstantConditions") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_bands_list, container, false); ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.bands_list_title); mProgressBar = (ProgressBar) view.findViewById(R.id.bands_progress_bar); mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.bands_refresher); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mSwipeRefreshLayout.setRefreshing(true); mBus.post(new BandsLoadRequiredEvent()); } }); mStatusView = (TextView) view.findViewById(R.id.bands_status); mBandList = (RecyclerView) view.findViewById(R.id.bands_list); mBandList.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { int topRowVerticalPosition = (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop(); mSwipeRefreshLayout.setEnabled(topRowVerticalPosition >= 0); } }); mBandList.setHasFixedSize(true); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity()); mBandList.setLayoutManager(mLayoutManager); // подписываемся на получение событий if (!mBus.isRegistered(this)) { mBus.register(this); } // запрашиваем данные для отображения mBus.post(new BandsLoadRequiredEvent()); return view; } @Override public void onDestroyView() { super.onDestroyView(); // отписываемся от событий if (mBus.isRegistered(this)) { mBus.unregister(this); } } /** * Метод, вызывающий обновление списка исполнителей на фрагменте. * * @param bandModels список исполнителей */ private void updateBands(List<BandModel> bandModels) { mAdapter = new BandsAdapter(getContext(), bandModels); mBandList.setAdapter(mAdapter); } /** * Метод для получения событий {@link BandsLoadedEvent}. Выполняет обновление фрагмента в зависимости от полученного * содержимого события. * * @param event событие, содержащее в себе результаты загрузки исполнителей */ @Subscribe public void onEvent(BandsLoadedEvent event) { if (mSwipeRefreshLayout.isRefreshing()) { mSwipeRefreshLayout.setRefreshing(false); } switch (event.getLoadResult()) { case ERROR: mProgressBar.setVisibility(View.GONE); mStatusView.setVisibility(View.VISIBLE); mBandList.setVisibility(View.GONE); mStatusView.setText(R.string.error_cant_get_band_list); mSwipeRefreshLayout.setEnabled(true); break; case NO_INTERNET: mProgressBar.setVisibility(View.GONE); mStatusView.setVisibility(View.VISIBLE); mBandList.setVisibility(View.GONE); mStatusView.setText(R.string.error_no_internet); mSwipeRefreshLayout.setEnabled(true); break; case SUCCESS: mProgressBar.setVisibility(View.GONE); if (event.getLoadedContent() == null || event.getLoadedContent().isEmpty()) { mStatusView.setVisibility(View.GONE); } else { mStatusView.setVisibility(View.GONE); mBandList.setVisibility(View.VISIBLE); updateBands(event.getLoadedContent()); } break; } } }
package com.questionanswer.questionanswer.api; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.questionanswer.questionanswer.data.UserQuestionAnswer; import com.questionanswer.questionanswer.data.UserSetDetail; import com.questionanswer.questionanswer.model.AdminQuestionModel; import com.questionanswer.questionanswer.model.ApiResponseModel; import com.questionanswer.questionanswer.model.ComponentAccessModel; import com.questionanswer.questionanswer.model.ComponentEntitlementModel; import com.questionanswer.questionanswer.model.LoginModel; import com.questionanswer.questionanswer.model.Session; import com.questionanswer.questionanswer.model.SetModel; import com.questionanswer.questionanswer.service.AdminService; import com.questionanswer.questionanswer.service.QuestionAnswerService; import com.questionanswer.questionanswer.service.SetServices; @RestController @RequestMapping("/api") public class ApiController { @Autowired private Session session; @Autowired private QuestionAnswerService questionAnswerService; @Autowired private AdminService adminService; @Autowired private SetServices setServices; @GetMapping("/get_sets") public ApiResponseModel<List<SetModel>> getSets () { return new ApiResponseModel<List<SetModel>>(session).setData(setServices.getSets()); } @GetMapping("/get_subscribed_set") public ApiResponseModel<List<UserSetDetail>> getSubscribedSet () { return new ApiResponseModel<List<UserSetDetail>>(session).setData(setServices.getSubscribedSet()); } @PostMapping("/subscribe_set") public ApiResponseModel<List<UserSetDetail>> subscribeSet (@RequestBody SetModel model) { return new ApiResponseModel<List<UserSetDetail>>(session).setData(setServices.subscribeSet(model)); } @PostMapping("/login") public ApiResponseModel<String> login (@RequestBody LoginModel loginModel) { adminService.login(loginModel); return new ApiResponseModel<String>(session); } @PostMapping("/check_entitlement") public ApiResponseModel<ComponentAccessModel> checkEntitlement (@RequestBody ComponentEntitlementModel componentEntitlementModel) { return new ApiResponseModel<ComponentAccessModel>(session).setData(adminService.checkEntitlement(componentEntitlementModel)); } @PostMapping("/submit_answers") public ApiResponseModel<UserQuestionAnswer> submitAnswer (@RequestBody AdminQuestionModel model) { return new ApiResponseModel<UserQuestionAnswer>(session).setData(questionAnswerService.submitAnswer(model)); } @GetMapping("/get_questions/{id}/{userSetId}") public ApiResponseModel<List<AdminQuestionModel>> getQuestionsBySetId (@PathVariable("id") int setId, @PathVariable("userSetId") int userSetId) { return new ApiResponseModel<List<AdminQuestionModel>>(session).setData(questionAnswerService.getQuestionsBySetId(setId, userSetId)); } @PostMapping("/finalize_question") public ApiResponseModel<List<UserSetDetail>> finalizeQuestion (@RequestBody UserSetDetail model) { return new ApiResponseModel<List<UserSetDetail>>(session).setData(setServices.finalizeQuestion(model)); } @PostMapping("/log_out") public ApiResponseModel<String> logOut () { adminService.logOut(); return new ApiResponseModel<String>(session).setData(null); } }
package com.jwebsite.dao; import java.util.List; import com.jwebsite.vo.TemplateProject; /** * 模板方案接口 * @author 魏飞飞 */ public interface TemplateProjectDao { //根据ID删除模板方案 public void delTemplateProject(int TpID) throws Exception; //更新记录 public void updateTemplateProject(TemplateProject Tp) throws Exception; //添加方案 public void insertTemplateProject(TemplateProject Tp) throws Exception; //查询方案 public List<TemplateProject> queryTemplateProject()throws Exception; //获取一个方案信息 public TemplateProject getTemplateProject(String TpID)throws Exception; //执行一个sql public int ExecuteSQL(String sql)throws Exception; //修改状态 public int UpdateState(String Action,String ID)throws Exception; }
package com.birivarmi.birivarmiapp.model; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Embeddable; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; @SuppressWarnings("serial") @Embeddable public class CityStatsPK implements Serializable{ @OneToOne(fetch=FetchType.LAZY, cascade={CascadeType.PERSIST}) @JoinColumn(name="CITY_ID", insertable=true, updatable=true, nullable=false) private City city; public City getCity() { return city; } public void setCity(City city) { this.city = city; } }
package factory.simplefactory; import factory.simplefactory.doorfactory.Door; import factory.simplefactory.doorfactory.DoorFactory; /** * Простая фабрика не совсем паттерн проектирования, а скорее принцип проектирования. Простая фабрика инкапсулирует * создание объекта, но сохраняет контроль над процессом создания. Простые фабрики часто проектируюся как классы со * статическим методом, который возвращает запрашиваемый объект. Простая фабрика находится в шаге от того, чтобы стать * Фабричным методом. * * @author Vladimir Ryazanov (v.ryazanov13@gmail.com) */ public class Example { public static void main(String[] args) { Door door = DoorFactory.constructDoor("glass"); System.out.println(door.getClass().getSimpleName()); door = DoorFactory.constructDoor("steel"); System.out.println(door.getClass().getSimpleName()); } }
package model.dataList; import java.util.Vector; import model.data.Data; public interface IntDataList<T extends Data> { // Any Time Use public void add(T data); public void delete(int iD); public T search(int iD); // Getter & Setter public Vector<T> getList(); public int getID(); public void setID(int id); }
package com.atguigu.java; public class DeadLoopTest { public static void main(String[] args) { while(true){ } } }
package com.my.learn.core_java.ch3; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class InputAndOutput { public static void copyFile(String inFile, String outFile) throws FileNotFoundException { Scanner scanner = new Scanner(new File(inFile)); //scanner = new Scanner(new BufferedReader(new FileReader(new File(inFile)))); PrintWriter printWriter = new PrintWriter(new File(outFile)); String line = null; scanner.useDelimiter("\n"); while (scanner.hasNext()) { line = scanner.nextLine(); printWriter.write(line); printWriter.write("\n"); System.out.println(line); } scanner.close(); printWriter.close(); } public static void main(String[] args) throws FileNotFoundException { String inFile = "src/test/resources/job.properties"; String outFile = inFile + ".copy"; copyFile(inFile, outFile); } }
package com.shangdao.phoenix.entity.report.BO; /** * 法院裁决当事人 * @author Administrator * */ public class Party { private String birthday; //当事人生日 private String title; //当事人称号 private String partytype; //当事人类型 private String lawOffice; //律师事务所 private String status; //当事人立场 private String pname; //当事人名称 private String idcardNo; //当事人身份证号码 private String lawyer; //委托辩护人 public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPartytype() { return partytype; } public void setPartytype(String partytype) { this.partytype = partytype; } public String getLawOffice() { return lawOffice; } public void setLawOffice(String lawOffice) { this.lawOffice = lawOffice; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public String getIdcardNo() { return idcardNo; } public void setIdcardNo(String idcardNo) { this.idcardNo = idcardNo; } public String getLawyer() { return lawyer; } public void setLawyer(String lawyer) { this.lawyer = lawyer; } }
package lab6t01; public class Student { public String name; public int id; public Student(String Name, int ID){ name=Name; id=ID; } }
public class TestFactorielle { public static void main(String[] args) { System.out.println("" + factorielle(10)); } private static long factorielle(long n) { // Clause de finitude if (n == 0) { return 1; } // Pas récursif return n * factorielle(n - 1); } }
package com.cjx.nexwork.fragments.work; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.support.v4.app.Fragment; import android.content.Context; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ScrollingView; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; import com.cjx.nexwork.R; import com.cjx.nexwork.WorkaroundMapFragment; import com.cjx.nexwork.activities.work.WorkActivity; import com.cjx.nexwork.managers.work.WorkDetailCallback; import com.cjx.nexwork.managers.work.WorkManager; import com.cjx.nexwork.model.Work; import com.cjx.nexwork.util.CustomProperties; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.squareup.picasso.Picasso; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; /** * Created by Xavi on 25/03/2017. */ public class FragmentDetailWork extends Fragment implements WorkDetailCallback, OnMapReadyCallback { public static final String WORK_ID = "0"; private TextView workPosition; private TextView workWorker; private ImageView workerImage; private TextView dateStart; private TextView dateEnded; private TextView workDescription; private TextView txtWorkCompany; private TextView workCompany; private ActionBar actionBar; private Work work; private Toolbar toolbar; private GoogleMap mMap; SupportMapFragment mapFragment; public FragmentDetailWork() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(getArguments() != null){ WorkManager.getInstance().getDetailWork(getArguments().getLong(WORK_ID), this); } // actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar(); } @Override public void onAttach(Context context) { super.onAttach(context); ((AppCompatActivity) getActivity()).getSupportActionBar().show(); getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_work_detail,container, false); Log.d("nxw", "DETAIL WORK"); mapFragment = (WorkaroundMapFragment) getChildFragmentManager().findFragmentById(R.id.mapWorkDetail); final ScrollView mScrollView = (ScrollView) view.findViewById(R.id.scrollviewDetail); ((WorkaroundMapFragment) getChildFragmentManager().findFragmentById(R.id.mapWorkDetail)).setListener(new WorkaroundMapFragment.OnTouchListener() { @Override public void onTouch() { mScrollView.requestDisallowInterceptTouchEvent(true); } }); workPosition = (TextView) view.findViewById(R.id.workPosition); workWorker = (TextView) view.findViewById(R.id.workWorker); workerImage = (ImageView) view.findViewById(R.id.workUserImage); dateStart = (TextView) view.findViewById(R.id.fechaInicio); dateEnded = (TextView) view.findViewById(R.id.fechaFinal); workDescription = (TextView) view.findViewById(R.id.workDescription); txtWorkCompany = (TextView) view.findViewById(R.id.txtWorkCompany); workCompany = (TextView) view.findViewById(R.id.workCompany); return view; } @Override public void onDestroy(){ super.onDestroy(); } @Override public void onDetach() { super.onDetach(); } @Override public void onSuccess(Work work) { Log.d("nxw", work.toString()); this.work = work; SimpleDateFormat formateador = new SimpleDateFormat("dd/MM/yyyy"); mapFragment.getMapAsync(this); workPosition.setText(work.getCargo()); //workPosition.setVisibility(View.GONE); workWorker.setText(work.getWorker().getFirstName() + " " + work.getWorker().getLastName()); dateStart.setText(formateador.format(work.getFechaInicio())); if(work.getActualmente()) dateEnded.setText(R.string.current_work); else { dateEnded.setText(formateador.format(work.getFechaFin())); } workDescription.setText(work.getDescripcionCargo()); if(work.getCompany() == null){ workCompany.setText("No establecida"); }else workCompany.setText(work.getCompany().getNombre()); Picasso.with(getContext()) .load(CustomProperties.baseUrl+"/"+work.getWorker().getImagen()) .resize(200, 200) .into(workerImage); } @Override public void onFailure(Throwable t) { } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if(this.work.getCompany() == null){ LatLng sydney = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(sydney).title("Sidney")); mMap.animateCamera(CameraUpdateFactory.newLatLng(sydney)); } else{ if(this.work.getCompany().getLatitud() == null){ LatLng sydney = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(sydney).title("Sidney")); mMap.animateCamera(CameraUpdateFactory.newLatLng(sydney)); } else{ LatLng latLng = new LatLng(Double.parseDouble(this.work.getCompany().getLatitud()), Double.parseDouble(this.work.getCompany().getLongitud())); mMap.addMarker(new MarkerOptions().position(latLng).title(this.work.getCompany().getNombre())); CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(latLng, 15); mMap.animateCamera(yourLocation); } } } }
package fr.cea.nabla.interpreter.nodes.expression; import org.graalvm.polyglot.Context; import org.graalvm.polyglot.Value; import com.oracle.truffle.api.Assumption; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.CachedContext; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.ExplodeLoop; import fr.cea.nabla.interpreter.NablaLanguage; import fr.cea.nabla.interpreter.runtime.NablaContext; public abstract class NablaLLVMCallNode extends NablaExpressionNode { @Children private final NablaExpressionNode[] args; protected final String providerName; private final String memberName; public NablaLLVMCallNode(String providerName, String memberName, NablaExpressionNode[] args) { this.providerName = providerName; this.memberName = memberName; this.args = args; } @ExplodeLoop @Specialization(assumptions = "contextActive") public Object doCached(VirtualFrame frame, @Cached("getMember()") Value member, @CachedContext(NablaLanguage.class) NablaContext context, @Cached("context.getNativeLibrary(providerName)") Value meshWrapper, @Cached("context.getContextActive()") Assumption contextActive) { final Object[] argumentValues = new Object[args.length + 1]; argumentValues[0] = meshWrapper; for (int i = 0; i < args.length; i++) { argumentValues[i + 1] = args[i].executeGeneric(frame); } return member.execute(argumentValues); } protected Value getMember() { final Value llvmBindings = Context.getCurrent().getBindings("llvm"); return llvmBindings.getMember(memberName); } }
package com.adwork.microservices.users.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.ServletWebRequest; @Controller public class CustomErrorController implements ErrorController { private ErrorAttributes errorAttributes = null; @Autowired public CustomErrorController(ErrorAttributes errorAttributes) { Assert.notNull(errorAttributes, "ErrorAttributes must not be null"); this.errorAttributes = errorAttributes; } @Override public String getErrorPath() { return "/error"; } @ResponseBody @RequestMapping("/error") public String handleError(HttpServletRequest req) { return "Error: " + errorAttributes.getError(new ServletWebRequest(req)); } }
/* * ¨for(initialisation;termination condition; update){ * body } * */ package Loop; /** * * @author YNZ */ public class ForLoop { /** * @param args the command line arguments */ public static void main(String[] args) { for (int x = 0, y = 10; x < y; x++, --y) { System.out.printf(" %d %d ", x, y); } } }
/* * 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 juego; public class Arcos { public int x,y,h,l,s,f; public Arcos(int x, int y, int h, int l, int s, int f) { this.x = x; this.y = y; this.h = h; this.l = l; this.s = s; this.f = f; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getH() { return h; } public void setH(int h) { this.h = h; } public int getL() { return l; } public void setL(int l) { this.l = l; } public int getS() { return s; } public void setS(int s) { this.s = s; } public int getF() { return f; } public void setF(int f) { this.f = f; } }
/** * public class TreeNode { * public int key; * public TreeNode left; * public TreeNode right; * public TreeNode(int key) { * this.key = key; * } * } */ public class Solution { public TreeNode reconstruct(int[] post) { List<Integer> list = new ArrayList<>(); for (int i : post) { list.add(i); } return reconstruct(list); } private TreeNode reconstruct(List<Integer> list) { if (list.isEmpty()) { return null; } int cur = list.get(list.size() - 1); TreeNode root = new TreeNode(cur); List<Integer> llist = new ArrayList<>(); List<Integer> rlist = new ArrayList<>(); for (int i = 0; i < list.size() - 1; i++) { if (list.get(i) < cur) { llist.add(list.get(i)); } else { rlist.add(list.get(i)); } } root.left = reconstruct(llist); root.right = reconstruct(rlist); return root; } }
/** * 제목: 다국어 지원 라이브러리 * 설명: * Copyright: Copyright (c) 2006 * Company: *@author 이창훈 *@date 2006. 01 *@version 1.0 */ package com.ziaan.library; import java.util.Locale; import java.util.ResourceBundle; import javax.servlet.http.HttpSession; public class TranslateManager { private String v_language="KOREAN"; public String v_directory=""; public String v_st1=""; public String v_st2=""; public String v_CharSet=""; private String s_languageName=""; private String v_languageName=""; Locale lo_lang = null; RequestBox box=null; HttpSession session = null; void setBox(RequestBox box){ this.box = box; } // Locale lo_lang = new Locale("en", "US"); public TranslateManager(RequestBox box) { this.box = box; try{ // ConfigSet config = new ConfigSet(); // v_language = config.getProperty("ziaan.language.value"); // lo_lang = new Locale("en", "US"); v_language = box.getSession("languageName"); if(v_language.equals("")){ v_language = "KOREAN"; } // System.out.println("v_language:"+v_language); //v_language = getLanguage(); setLanguageVariable(v_language); // setLangVariable("ENGLISH"); } catch(Exception e) { e.printStackTrace(); } } public TranslateManager() { try{ // ConfigSet config = new ConfigSet(); // v_language = config.getProperty("ziaan.language.value"); //v_language = getLanguage(); // v_language = session.getAttribute("languageName").toString(); // System.out.println("result==========================================>"+v_language); setLanguageVariable(v_language); // setLangVariable("ENGLISH"); } catch(Exception e) { e.printStackTrace(); } } public String TranslateMessage(String strCode) { DBConnectionManager connMgr = null; ListSet ls = null; String result=""; String rtn = null; String sql = ""; try{ ResourceBundle bundle =ResourceBundle.getBundle(v_directory, lo_lang); result = bundle.getString(strCode); rtn = new String(result.getBytes(v_st1),v_st2); /* connMgr = new DBConnectionManager(); sql = "select "+v_language+" from tu_languagescript where key = '"+strCode+"'"; ls = connMgr.executeQuery(sql); if(ls.next()){ result = ls.getString(v_language); } System.out.println("result====>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+result); */ }catch(Exception ex) { }finally { if(ls != null) { try { ls.close(); }catch (Exception e) {} } if(connMgr != null) { try { connMgr.freeConnection(); }catch (Exception e10) {} } } return rtn; //return result; } public void setLanguageVariable(String v_language) { //System.out.println("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk===>>"+v_language); if(v_language.equals("ENGLISH")){ v_directory = "conf.ziaan_en"; lo_lang = Locale.ENGLISH; v_st1 = "iso8859-1"; v_st2 = "UTF-8"; } else if (v_language.equals("KOREAN")){ v_directory = "conf.ziaan_ko"; lo_lang = Locale.KOREAN; v_st1 = "iso8859-1"; v_st2 = "euc-kr"; } else if (v_language.equals("JAPANESE")){ v_directory = "conf.ziaan_jp"; lo_lang = Locale.JAPANESE; v_st1 = "iso8859-1"; //8859_1 v_st2 = "UTF-8"; // File Encoding 방법에 따라 ( Properties File ) } else if (v_language.equals("CHINESE")){ v_directory = "conf.ziaan_ch"; lo_lang = Locale.CHINESE; v_st1 = "iso8859-1"; //8859_1 v_st2 = "UTF-8"; // File Encoding 방법에 따라 } //System.out.println("v_directory===>>>"+v_directory); } }
package model; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import model.database.entries.RuleEntry; import model.database.entries.SentenceEntry; import model.database.tables.RuleTable; public class Sentences { private List<SentenceEntry> sentences; private List<Boolean> answersAreCorrect; private int currentSentenceId; private String currentWrongWord; private int score; private String packageName; public Sentences() { sentences = new ArrayList<>(); currentSentenceId = 0; currentWrongWord = ""; score = 0; } public void initialize(SentencesManager sentencesManager, String packageName) { sentences = sentencesManager.getSentences(packageName); answersAreCorrect = new ArrayList<>(); for (int i = 0; i < sentences.size(); ++i) answersAreCorrect.add(false); currentSentenceId = 0; score = 0; this.packageName = packageName; generateWrongWord(); // Random sort of the sentences list ArrayList<SentenceEntry> sentencesTemp = new ArrayList<>(); while (sentences.size() > 0) { int sentenceIdToTransfer = (int) (Math.random() * sentences.size()); sentencesTemp.add(sentences.get(sentenceIdToTransfer)); sentences.remove(sentenceIdToTransfer); } sentences = sentencesTemp; } public String getPackageName() { return packageName; } public int getSentencesCount() { if (sentences != null) return sentences.size(); return 0; } public boolean isFinished() { return currentSentenceId >= sentences.size(); } public String getRule() { try { RuleTable ruleTable = new RuleTable(); RuleEntry ruleModel = ruleTable.getById(sentences.get(currentSentenceId).getIdRule()); return ruleModel.getDetail(); } catch (Exception e) { e.printStackTrace(); return ""; } } public String getRuleName() { try { RuleTable ruleTable = new RuleTable(); RuleEntry ruleModel = ruleTable.getById(sentences.get(currentSentenceId).getIdRule()); return ruleModel.getName(); } catch (Exception e) { e.printStackTrace(); return ""; } } public String getIncompleteWrongSentence() { if (!isFinished()) return sentences.get(currentSentenceId).getDetail().replaceAll("@", "---"); return ""; } public String getWrongSentence() { if (!isFinished()) return sentences.get(currentSentenceId).getDetail().replaceAll("@", currentWrongWord); return ""; } public String getCorrectWord() { if (!isFinished()) return sentences.get(currentSentenceId).getPropOk(); return ""; } public String getCorrectSentence() { if (!isFinished()) return sentences.get(currentSentenceId).getDetail().replaceAll("@", "<span style='color:colorToChange'>" + sentences.get(currentSentenceId).getPropOk() + "</span>"); return ""; } public ArrayList<String> getChoices() { ArrayList<String> sortedChoices = new ArrayList<>(); if (!isFinished()) { String[] choices = (sentences.get(currentSentenceId).getPropNo()).split(","); ArrayList<String> choicesList = new ArrayList<>(Arrays.asList(choices)); for (int i = 0; i < choices.length && sortedChoices.size() < 4; ++i) { int index = (int) (Math.random() * choicesList.size()); sortedChoices.add(choicesList.get(index)); choicesList.remove(index); } sortedChoices.add((int) (Math.random() * (sortedChoices.size() + 1)), getCorrectWord()); } return sortedChoices; } public int getScore() { return score; } public List<String> getRulesNames(SentencesManager sentencesManager, boolean forGoodAnswers) { ArrayList<SentenceEntry> sentencesEntries = new ArrayList<>(); for (int i = 0; i < sentences.size(); ++i) { if (answersAreCorrect.get(i).equals(forGoodAnswers)) { sentencesEntries.add(sentences.get(i)); } } return sentencesManager.getRulesNames(sentencesEntries); } public boolean characterIsFromWrongWord(int characterId) { if (!isFinished()) { int wrongWordFirstIndex = sentences.get(currentSentenceId).getDetail().split("@")[0].length(); int wrongWordLastIndex = wrongWordFirstIndex + currentWrongWord.length() - 1; return characterId >= wrongWordFirstIndex && characterId <= wrongWordLastIndex; } return false; } public void validateSentence(boolean answerIsCorrect) { if (answerIsCorrect) { ++score; } answersAreCorrect.set(currentSentenceId, answerIsCorrect); ++currentSentenceId; generateWrongWord(); } private void generateWrongWord() { if (!isFinished()) { String[] badChoices = sentences.get(currentSentenceId).getPropNo().split(","); int badChoiceId = (int) (Math.random() * badChoices.length); currentWrongWord = badChoices[badChoiceId]; } else { currentWrongWord = ""; } } }
import java.util.Scanner; public class Ternary { public static void main(String[] args) { // Ternarnyi ilitretichnyi operator //------------------------- int a = 5, b = 7, c = 0; c = (a > b) ? a : b; System.out.println(c); //7 Ternarnyi operator vsegda dolzhen vozvrascat znachenie //------------------------- int d = 5, e = 7, f = -5, max = 0; max = (d > e) ? (f = d) : (f = e); // 7 System.out.println(max); //------------------------- String string = "Hello "; Scanner input = new Scanner(System.in); System.out.println("Please Enter Login:"); String userLogin = input.next(); string += (userLogin.equals("Admin")) ? "Administrator" : "User"; System.out.println(string); //------------------------- int a1 = 5; double b1 = 0.0; int max1; max1 = (int) ((a1 > b1) ? a1 : b1); //or //max1 = (a1 > b1) ? a1 : (int)b1; System.out.println(max1); // 5 //------------------------- // Opredelit chetvert int x1 = 3, y1 = -2; String kvadrant1, kvadrant2, kvadrant3; kvadrant1 = (x1 > 0) ? ((y1 > 0) ? "1 kvadrant" : "4 kvadrant") : ((y1 > 0) ? "2 kvadrant" : "3 kvadrant"); System.out.println(kvadrant1); // to zhe samoe kvadrant2 = x1 > 0 ? (y1 > 0) ? "1 kvadrant" : "4 kvadrant" : (y1 > 0) ? "2 kvadrant" : "3 kvadrant"; System.out.println(kvadrant2); // to zhe samoe kvadrant3 = x1 > 0 ? y1 > 0 ? "1 kvadrant" : "4 kvadrant" : y1 > 0 ? "2 kvadrant" : "3 kvadrant"; System.out.println(kvadrant3); //------------------------- // Opredelit skidku // Esli pokupaet >= 10 edinits tovara, skidka 25% double quantity = 10; double price = 100; double discount = 0.75; double cost; cost = (quantity >= 10)? price*discount*quantity:price*quantity; System.out.println("Total cost: " + cost); } }
package enshud.s1.lexer; import enshud.s1.lexer.lexer2.RegexLexer; public class Lexer extends RegexLexer { public static void main(final String[] args) { // normalの確認 new Lexer().run("mydata/compiler/test.pas", "mydata/compiler/test.ts"); } }
/* * Written by Erhan Sezerer * Contact <erhansezerer@iyte.edu.tr> for comments and bug reports * * Copyright (C) 2014 Erhan Sezerer * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.darg.NLPOperations.dictionary; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.darg.utils.ArrayListUtils; import com.darg.fileOperations.utils.FileUtils;; /**This class is responsible for handling stop words * if you do not properly load the stop words, * the functions won't work * * * * @author erhan sezerer * */ public class StopWordsDictionary { private ArrayList<String> stopWords; private long stopWordsCount; //prevent users from calling empty constructor @SuppressWarnings("unused") private StopWordsDictionary() { } public StopWordsDictionary(final String path) { stopWords = new ArrayList<String>(); stopWordsCount = 0; init(path); } public StopWordsDictionary(ArrayList<String> stopwords) { this.stopWords = stopwords; stopWordsCount = stopwords.size(); } private boolean init(final String path) { boolean retVal = true; File file = new File(path); try(BufferedReader br = new BufferedReader(new FileReader(file));) { String line; while ((line = br.readLine()) != null) { if(!line.isEmpty() && line.charAt(0) != '#')//do not count comment lines { retVal = addToList(line.trim()); setStopWordsCount(getStopWordsCount()+1); } } } catch (IOException e) { e.printStackTrace(); retVal = false; } return retVal; } //////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////FUNCTIONS /////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// /**checks whether the given word is a stop word or not * * @author erhan sezerer * * @param word - a string representing a word to examine * * @return boolean - true if the word is a stop word false otherwise. * returns false if the string is null or empty. */ public boolean isStopWord(final String word) { boolean retVal = false; if(word != null && !word.isEmpty()) { if(ArrayListUtils.containsIgnoresCase(stopWords, word.trim())) { retVal = true; } } return retVal; } /**adds the given stop word to the current list of stop words * * @author erhan sezerer * * @param word - a string to add to the stop words * * @return boolean - false if the string is null or empty */ public boolean addStopWord(final String word) { boolean retVal = false; if(word != null && !word.isEmpty()) { retVal = addToList(word); setStopWordsCount(getStopWordsCount()+1); } return retVal; } /**adds the given list of stop words to the current list of stop words * if the string is empty or null it will not try to add it to the list * * @author erhan sezerer * * @param word - a string to add to the stop words * * @return boolean - true if all of the strings are added successfully */ public boolean addStopWords(final ArrayList<String> words) { boolean retVal = true; int length = words.size(); for(int i=0; i<length; i++) { if(!addStopWord(words.get(i))) { retVal = false; break; } } return retVal; } /**retrieves the stop words from the file found from the path and deletes the current ones * * @author erhan sezerer * * @param path - a string that is a path to a file containing stop words * * @return boolean - false if there is any errors while loading the stop words from the file * otherwise true */ public boolean loadStopWords(final String path) { clearStopWords(); return init(path); } /**creates a file from the current stop words in list * * @author erhan sezerer * * @param destination - a path to export * * @return boolean - to determine success, false if there is an error * true if there is none */ public boolean exportStopWords(final String destination) { String content = new String("#STOP WORDS - output of darg.iyte.edu.tr data mining tool\n\n#total: " + getStopWordsCount()+" stop words\n\n"); for(String string : stopWords) { content = content.concat(string); content = content.concat(new String("\n")); } return FileUtils.writeFile(destination, "stopwords.txt", content); } /**retrieves the stop words from the file found from the path and appends them to the current ones * * @author erhan sezerer * * @param path - a string that is a path to a file containing stop words * * @return boolean - false if there is any errors while loading the stop words from the file * otherwise true */ public boolean appendStopWords(final String path) { return init(path); } /**removes the given word from stop word list * if the word is null or empty, or it does not exist in the list * it will return false * * @author erhan sezerer * * @param word - word that will be removed from the list * * @return boolean - true if the operation is successful */ public boolean removeStopWord(final String word) { boolean retVal = false; if(word != null && !word.isEmpty()) { for(int i=0; i<stopWordsCount; i++) { if(stopWords.get(i).equalsIgnoreCase(word.trim())) { removeFromList(i); setStopWordsCount(getStopWordsCount()-1);; retVal = true; } } } return retVal; } /**removes the given words from stop word list * if the words list is null or empty it will return false * * @author erhan sezerer * * @param words - word that will be removed from the list * @return boolean - true if the operation is successful */ public boolean removeStopWords(final ArrayList<String> words) { boolean retVal = false; int length = words.size(); if(words != null && !words.isEmpty()) { retVal = true; for(int i=0; i<length; i++) { removeStopWord(words.get(i)); } } return retVal; } /**removes the stop words from the given map whose keys are the words * returns a map without the stop words * * @author erhan sezerer * * @param words - a map to do the filtering operation * * @return Map<String,E> - a reduced version of the map after the filtering operation */ public <E> Map<String, E> filterStopWords(final Map<String, E> words) { String keyTerm = null; HashMap<String, E> tempMap = (HashMap<String, E>) words; Iterator<String> tempWords = tempMap.keySet().iterator(); while(tempWords.hasNext()) { keyTerm = tempWords.next().trim(); if(ArrayListUtils.containsIgnoresCase(stopWords, keyTerm)) { tempWords.remove(); } } return words; } /**removes the stop words from the given array list * returns an array list without the stop words * * @author erhan sezerer * * @param words - a map to do the filtering operation * * @return ArrayList<String> - a reduced version of the map after the filtering operation */ public ArrayList<String> filterStopWords(final ArrayList<String> words) { String keyTerm = null; int length = words.size(); for(int i=0; i<length; i++) { keyTerm = words.get(i); if(ArrayListUtils.containsIgnoresCase(stopWords, keyTerm)) { words.remove(i); } } return words; } //////////////////////////////////////////////////////////////////////////////////////// //setters and getters vs. //////////////////////////////////////////////////////////////////////////////////////// @Override public String toString() { String retVal = new String(""); for(int i=0; i<stopWordsCount; i++) { retVal += ("stopWord "+ i +": " + stopWords.get(i)); } return retVal; } public synchronized void clearStopWords() { stopWords.clear(); stopWordsCount = 0; } public synchronized boolean addToList(final String word) { return stopWords.add(word); } public synchronized String removeFromList(final int wordIndex) { return stopWords.remove(wordIndex); } public synchronized ArrayList<String> getStopWords() { return stopWords; } public synchronized void setStopWords(ArrayList<String> stopWords) { this.stopWords = stopWords; } public synchronized long getStopWordsCount() { return stopWordsCount; } public synchronized void setStopWordsCount(long stopWordsCount) { this.stopWordsCount = stopWordsCount; } }
package net.ddns.hnmirror.dao; import java.sql.SQLException; import java.util.List; import javax.jms.JMSException; import net.ddns.hnmirror.domain.Story; public interface StoryDAO { public List<Story> listStory(int page); public List<Story> search(String searchStr, String searchBy, int page); }
package com.assignment.service; import com.assignment.model.Employee; import com.assignment.repository.EmployeeRepository; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.inject.Inject; import java.util.List; public class EmployeeService { static Logger log = LogManager.getLogger(EmployeeService.class); @Inject private EmployeeRepository employeeRepository; public Employee addEmployee(Employee employee) { log.info("Adding employee " + employee); return employeeRepository.addEmployee(employee); } public void deleteEmployee(int id) { employeeRepository.deleteEmployee(id); } public Employee updateEmployee(Employee employee) { return employeeRepository.updateEmployee(employee); } public Employee getEmployee(int id) { return employeeRepository.getEmployee(id); } public List<Employee> getAllEmployee() { return employeeRepository.getAllEmployee(); } }
package ru.job4j.addresslist; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class Profiles { public List<Address> collect(List<Profile> profiles) { return profiles.stream().sorted(Comparator.comparing(city -> city.getAddress().getCity())).distinct().map(Profile::getAddress).collect(Collectors.toList()); } }
package com.hackathon.pragati; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import static com.hackathon.pragati.SplashScreen.firebaseAuth; //ok import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import androidx.constraintlayout.widget.ConstraintLayout; import android.app.Activity; import android.app.Notification; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.text.InputType; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.DocumentChange; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.QuerySnapshot; import com.google.firebase.firestore.SetOptions; public class UserHome extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_public_home); startActivity(new Intent(UserHome.this,ProjectHome.class)); } public void exit(View view) { firebaseAuth.signOut(); startActivity(new Intent(UserHome.this,SplashScreen.class)); finish(); } /* Map car; APIService apiService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_car_page); perform(getIntent().getStringExtra("vehicleID")); w=findViewById(R.id.washtatus); apiService= Client.getClient("https://fcm.googleapis.com/").create(APIService.class); } public void perform(String s){ final LinearLayout t = findViewById(R.id.tt); firestore.document("Vehicles/"+s).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if(task.isSuccessful()){ car=task.getResult().getData(); if(car.containsKey("tStatus")) if(car.get("tStatus").equals("Washing")) w.setText("StopWashing"); Set<String> keys= car.keySet(); ArrayList k2 = new ArrayList(keys); ArrayList values= new ArrayList(car.values()); for(int i=0;i<keys.size();i++) { LinearLayout l=new LinearLayout(CarPage.this); l.setOrientation(LinearLayout.HORIZONTAL); TextView carK = new TextView(CarPage.this);//(TextView) inflater.inflate(R.layout.cartext, t, false); carK.setText(k2.get(i).toString()+" : "); carK.setTypeface(Typeface.DEFAULT_BOLD); carK.setTextSize(TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM,20.0f); TextView carV = new TextView(CarPage.this);//(TextView) inflater.inflate(R.layout.cartext, t, false); carV.setText(values.get(i).toString()); carV.setTextSize(TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM,18.0f); l.addView(carK); l.addView(carV); t.addView(l); } } else{ Toast.makeText(CarPage.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } }); } TextView w; public void updateStatus(View v){ if(w.getText().equals("StartWashing")){startWashing();} else {stopWashing();} } private void startWashing() { Map<String,Object> m=new HashMap<>(); m.put("tStatus","Washing"); firestore.document("RUsers/"+car.get("Phone")).set(m,SetOptions.merge()) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { Toast.makeText(CarPage.this, "Started!", Toast.LENGTH_SHORT).show(); w.setText("StopWashing"); } else Toast.makeText(CarPage.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } }); String x="Your Car "+car.get("Manufacturer")+" "+car.get("Model")+" is being washed now!"; Map<String,Object> k=new HashMap<>(); k.put("start",getNowTimeMillis()); firestore.document("RUsers/"+car.get("Phone")+"/History/"+getTodayDate()).set(k,SetOptions.merge()); Map<String,Object> k2=new HashMap<>(); k2.put(getNowTimeMillis(),x); firestore.document("RUsers/"+car.get("Phone")+"/Notifications/"+getTodayDate()).set(k2,SetOptions.merge()); firestore.document("Vehicles/"+car.get("VehicleID")).set(m,SetOptions.merge()); sendNotification(car.get("Phone").toString(),"CarLiteTeam",x); } CheckBox ws,roof,doors,mirrors,bonnet,bumpers,wc,tyres,fsts,bsts,dbrd,cnsl,ftmt,btspc,ipol,expol; private void stopWashing(){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Washed Components"); final LinearLayout pop=new LinearLayout(this); */ /* pop.setOrientation(LinearLayout.HORIZONTAL); final TextView ty=new TextView(this); ty.setText("WindShield"); pop.addView(ty); final Switch input1 = new Switch(this); pop.addView(input1); final LinearLayout pop2=new LinearLayout(this); pop2.setOrientation(LinearLayout.HORIZONTAL); final TextView ty2=new TextView(this); ty2.setText("Tyres"); pop2.addView(ty2); final Switch input2 = new Switch(this); pop2.addView(input2); LinearLayout lol=new LinearLayout(this); lol.setOrientation(LinearLayout.VERTICAL); lol.addView(pop); lol.addView(pop2); *//* LayoutInflater inflater= (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); CardView carD= (CardView) inflater.inflate(R.layout.detail_card,pop,false); LinearLayout l= (LinearLayout) ((ScrollView)((ConstraintLayout) carD.getChildAt(0)).getChildAt(0)).getChildAt(0); ws= (CheckBox) l.getChildAt(0); roof= (CheckBox) l.getChildAt(1); doors= (CheckBox) l.getChildAt(2); mirrors= (CheckBox) l.getChildAt(3); bonnet= (CheckBox) l.getChildAt(4); bumpers= (CheckBox) l.getChildAt(5); wc= (CheckBox) l.getChildAt(6); tyres= (CheckBox) l.getChildAt(7); fsts= (CheckBox) l.getChildAt(8); bsts= (CheckBox) l.getChildAt(9); dbrd= (CheckBox) l.getChildAt(10); cnsl= (CheckBox) l.getChildAt(11); ftmt= (CheckBox) l.getChildAt(12); btspc= (CheckBox) l.getChildAt(13); ipol= (CheckBox) l.getChildAt(14); expol= (CheckBox) l.getChildAt(15); builder.setView(carD); builder.setPositiveButton("Notify", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Map<String,Object> m=new HashMap<>(); m.put("tStatus","Completed"); firestore.document("RUsers/"+car.get("Phone")).set(m,SetOptions.merge()) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ Toast.makeText(CarPage.this, "Notified ;)", Toast.LENGTH_SHORT).show(); w.setText("StartWashing"); } else Toast.makeText(CarPage.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } }); Map<String,Object> k=new HashMap<>(); k.put("stop",getNowTimeMillis()); k.put("WindScreen",ws.isChecked()); k.put("Roof",roof.isChecked()); k.put("Doors",doors.isChecked()); k.put("Mirrors",mirrors.isChecked()); k.put("Bonnet",bonnet.isChecked()); k.put("Bumpers",bumpers.isChecked()); k.put("WheelCovers",wc.isChecked()); k.put("Tyres",tyres.isChecked()); k.put("FrontSeats",fsts.isChecked()); k.put("BackSeats",bsts.isChecked()); k.put("DashBoard",dbrd.isChecked()); k.put("Console",cnsl.isChecked()); k.put("FootMats",ftmt.isChecked()); k.put("BootSpace",btspc.isChecked()); k.put("InteriorPolishing",ipol.isChecked()); k.put("ExteriorPolishing",expol.isChecked()); String x="Your Car "+car.get("Manufacturer")+" "+car.get("Model")+" has been washed!!"; firestore.document("RUsers/"+car.get("Phone")+"/History/"+getTodayDate()).set(k,SetOptions.merge()); firestore.document("Vehicles/"+car.get("VehicleID")).set(m,SetOptions.merge()); Map<String,Object> k2=new HashMap<>(); k2.put(getNowTimeMillis(),x); firestore.document("RUsers/"+car.get("Phone")+"/Notifications/"+getTodayDate()).set(k2,SetOptions.merge()); sendNotification(car.get("Phone").toString(),"CarLiteTeam",x); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } public void showHistory(View v){ } String x; public void notifyUser(View v){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Notification Text"); final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_TEXT ); builder.setView(input); builder.setPositiveButton("Notify", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { x = input.getText().toString(); Map<String,Object> text=new HashMap<>(); text.put(getNowTimeMillis(),x); firestore.document("RUsers/"+car.get("Phone")+"/Notifications/"+getTodayDate()).set(text, SetOptions.merge()) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ // The topic name can be optionally prefixed with "/topics/". // String topic = "highScores"; // See documentation on defining a message payload. //String token= firestore.document("RUsers/"+car.get("Phone")).get().getResult().get("token").toString(); RemoteMessage message =new RemoteMessage.Builder(car.get("Phone").toString()) .addData("msg", x) .build(); // Send a message to the devices subscribed to the provided topic. FirebaseMessaging.getInstance().send(message); // Response is a message ID string. System.out.println("Successfully sent message: " ); Toast.makeText(CarPage.this, "Notified ;)", Toast.LENGTH_SHORT).show();} else Toast.makeText(CarPage.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } }); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); //firestore.collection("Notifications").addSnapshotListener(new EventListener<QuerySnapshot>() { //@Override // public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) { // List<DocumentChange> k= queryDocumentSnapshots.getDocumentChanges(); // ArrayList<String> l=new ArrayList(k.get(0).getDocument().getData().values()); /// sendNotification(car.get("Phone").toString(),"CarLiteTeam",l.get(0)); // } //}); } public void openMap(View v){ String x=car.get("Address").toString(); Uri gmmIntentUri = Uri.parse("geo:0,0?q="+x); Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri); mapIntent.setPackage("com.google.android.apps.maps"); startActivity(mapIntent); } public static String getTodayDate() { Calendar c = Calendar.getInstance(); int mm = (int) (c.get(Calendar.MONTH)) + 1; int dd = c.get(Calendar.DATE); int yyyy = c.get(Calendar.YEAR); return (dd < 10 ? "0" + dd : dd + "") + "." + (mm < 10 ? "0" + mm : mm + "") + "." + yyyy; } public String getNowTime() { int hh = Calendar.getInstance(TimeZone.getDefault()).getTime().getHours(); int mm = Calendar.getInstance(TimeZone.getDefault()).getTime().getMinutes(); return (hh < 10 ? ("0" + hh) : hh) + ":" + (mm < 10 ? ("0" + mm) : mm); } public static String getNowTimeMillis() { int hh = Calendar.getInstance(TimeZone.getDefault()).getTime().getHours(); int mm = Calendar.getInstance(TimeZone.getDefault()).getTime().getMinutes(); int ss = Calendar.getInstance(TimeZone.getDefault()).getTime().getSeconds(); //int mi = Calendar.getInstance(TimeZone.getDefault()).getTime().get; return (hh < 10 ? ("0" + hh) : hh) + ":" + (mm < 10 ? ("0" + mm) : mm)+":"+ (ss < 10 ? ("0" + ss) : ss); //+ (mi < 10 ? ("0" + mi) : mi); } public void feedBack(View v){ Intent i=new Intent(CarPage.this,FeedBack.class); i.putExtra("vehicleID",car.get("VehicleID").toString()); startActivity(i); } private void sendNotification(String receiver, final String username, final String message) { firestore.document("RUsers/"+receiver).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if(task.isSuccessful()){ Token token=new Token(task.getResult().get("token").toString()); Data data=new Data(firebaseAuth.getCurrentUser().getPhoneNumber(),R.drawable.app_icon,message,username,"sented"); Sender sender=new Sender(data,token.getToken()); apiService.sendNotification(sender) .enqueue(new Callback<MyResponse>() { @Override public void onResponse(Call<MyResponse> call, Response<MyResponse> response) { if(response.code()==200){ if(response.body().success!=1){ Toast.makeText(CarPage.this, "Failed!", Toast.LENGTH_SHORT).show(); } } } @Override public void onFailure(Call<MyResponse> call, Throwable t) { System.out.println("mattha kharaab ui "+t.getMessage()); } }); } else System.out.println("mattha kharaab "+task.getException().getMessage()); } }); } */ }
package com.algaworks.algamoney.api.resource; import com.algaworks.algamoney.api.data.search.filter.EntryFilter; import com.algaworks.algamoney.api.event.ResourceCreatedEvent; import com.algaworks.algamoney.api.logic.bean.EntryDTO; import com.algaworks.algamoney.api.logic.service.entry.EntryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; /** * @author jsilva on 31/10/2019 */ @RestController @RequestMapping("/api/v1/entry") public class EntryResource { private EntryService entryService; private ApplicationEventPublisher publisher; @Autowired public EntryResource(EntryService entryService, ApplicationEventPublisher publisher) { this.entryService = entryService; this.publisher = publisher; } @GetMapping public Page<EntryDTO> listAll(EntryFilter filter, Pageable pageable) { return entryService.search(filter, pageable); } @PostMapping public ResponseEntity<EntryDTO> add(@RequestBody @Valid EntryDTO entryDTO, HttpServletResponse response) { EntryDTO savedEntry = entryService.add(entryDTO); publisher.publishEvent(new ResourceCreatedEvent(this, response, savedEntry.getId())); return ResponseEntity.status(HttpStatus.CREATED).body(savedEntry); } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void remove(@PathVariable("id") Long id) { entryService.remove(id); } }
package Tutorial.P1_RegisterNewUser; import java.util.ArrayList; import java.util.List; /** * Created by greenlucky on 6/4/17. */ public class StorageUser{ private List<User> lstUsers; public StorageUser() { lstUsers = new ArrayList<>(); } public void addUser(User user) { lstUsers.add(user); } }
package com.oldschool.model; import java.io.Serializable; import javax.persistence.*; import java.util.List; /** * The persistent class for the cliente database table. * */ @Entity @Table(name="cliente") @NamedQueries({ @NamedQuery(name="Cliente.findAll", query="SELECT c FROM Cliente c"), @NamedQuery(name="Cliente.findByEstado", query="SELECT c FROM Cliente c WHERE c.activo = :estado"), @NamedQuery(name="Cliente.findByNombreOrNit", query="SELECT c FROM Cliente c WHERE c.razon_Social = :nombre OR c.nit = :nit"), @NamedQuery(name="Cliente.findByNombreYEstado", query="SELECT c FROM Cliente c WHERE c.activo = :estado AND LOWER(c.razon_Social) LIKE :nombre"), @NamedQuery(name="Cliente.inactivarCliente", query="UPDATE Cliente c SET c.activo = 0 WHERE c.id_Cliente = :idCliente"), @NamedQuery(name="Cliente.activarCliente", query="UPDATE Cliente c SET c.activo = 1 WHERE c.id_Cliente = :idCliente") }) public class Cliente implements Serializable { private static final long serialVersionUID = 1L; public static final byte ESTADO_ACTIVO = 1; public static final byte ESTADO_INACTIVO = 0; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id_Cliente; private byte activo; private String direccion; private String email; private long nit; private String razon_Social; private long telefono; //bi-directional many-to-one association to Proyecto @OneToMany(mappedBy="cliente") private List<Proyecto> proyectos; public Cliente() { } public Cliente(int idCliente) { this.id_Cliente = idCliente; } public int getId_Cliente() { return this.id_Cliente; } public void setId_Cliente(int id_Cliente) { this.id_Cliente = id_Cliente; } public byte getActivo() { return this.activo; } public void setActivo(byte activo) { this.activo = activo; } public String getDireccion() { return this.direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public long getNit() { return this.nit; } public void setNit(long nit) { this.nit = nit; } public String getRazon_Social() { return this.razon_Social; } public void setRazon_Social(String razon_Social) { this.razon_Social = razon_Social; } public long getTelefono() { return this.telefono; } public void setTelefono(long telefono) { this.telefono = telefono; } public List<Proyecto> getProyectos() { return this.proyectos; } public void setProyectos(List<Proyecto> proyectos) { this.proyectos = proyectos; } public Proyecto addProyecto(Proyecto proyecto) { getProyectos().add(proyecto); proyecto.setCliente(this); return proyecto; } public Proyecto removeProyecto(Proyecto proyecto) { getProyectos().remove(proyecto); proyecto.setCliente(null); return proyecto; } }
package com.company; import java.util.Scanner; public class Ejercicio9 { public static void main(String[] args) { Scanner teclado = new Scanner (System.in); System.out.print("Introduzca un numero: "); int numero1 = teclado.nextInt(); divisoresPrimos(numero1); } public static void divisoresPrimos(int numero1){ boolean primo = true; for (int i = 1; i <= numero1; i++){ if (numero1 % i == 0){ for (int j = 2; j < i && primo; ++j){ if (i % j == 0){ primo = false; } } if (primo){ System.out.println (i+" Es un divisor primo"); } } } } }
package com.example.demo.producer; import org.springframework.jms.core.JmsMessagingTemplate; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.jms.Destination; /** * 消息生产者 * Created by vip on 2019/1/23. */ @Component public class MessageProducer { @Resource private JmsMessagingTemplate jmsTemplate; public void sendMessage(Destination destination, String message) { jmsTemplate.convertAndSend(destination, message); } }
package View.Alimentazione; import javax.swing.*; /** * La classe NewProgAlimView contiene attributi e metodi associati al file XML NewProgAlimView.form */ public class NewProgAlimView { private JPanel mainPanel; private JPanel indexprogalimPanel; private JPanel progalimcombPanel; private IndexProgAlimView indexprogalimview; private ProgAlimCombView progalimcombview; public NewProgAlimView() { mainPanel.add(indexprogalimPanel,"IndexProgAlimView"); } public JPanel getMainPanel() { return mainPanel; } public IndexProgAlimView getIndexprogalimview() { return indexprogalimview; } public ProgAlimCombView getProgalimcombview() { return progalimcombview; } /** * Metodo che crea componenti dell'User Interface */ private void createUIComponents() { indexprogalimview = new IndexProgAlimView(); indexprogalimPanel = indexprogalimview.getMainPanel(); } }
package com.cg.go.greatoutdoor.util; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.cg.go.greatoutdoor.dto.cartItem.CreateCartItemRequest; import com.cg.go.greatoutdoor.dto.cartItem.UpdateCartItemRequest; import com.cg.go.greatoutdoor.entity.CartItemEntity; import com.cg.go.greatoutdoor.entity.ProductEntity; import com.cg.go.greatoutdoor.service.IProductService; @Component public class CartItemUtil { @Autowired public IProductService productService; public Map<ProductEntity,Integer> convertMap(Map<Integer,Integer> map){ Set<Integer> ids=map.keySet(); Map<ProductEntity,Integer> products=new HashMap<>(); for(Integer id:ids) { ProductEntity productEntity=productService.findByProductId(id); products.put(productEntity,map.get(id)); } return products; } public CartItemEntity convertToCartItem(CreateCartItemRequest cartItem) { Integer totalQuantity=0; double totalPrice=0; CartItemEntity cart=new CartItemEntity();/* cart.setUserId(cartItem.getUserId()); Map<ProductEntity,Integer> products=convertMap(cartItem.getProducts()); Set<ProductEntity> productSet=products.keySet(); for(ProductEntity product:productSet) { totalQuantity+=products.get(product); totalPrice+=product.getPrice()*products.get(product); } cart.setProducts(products); cart.setCartTotalPrice(totalPrice); cart.setTotalQuantity(totalQuantity);*/ return cart; } public CartItemEntity convertToCartItem(UpdateCartItemRequest cartItem) { Integer totalQuantity=0; double totalPrice=0; CartItemEntity cart=new CartItemEntity(); /*cart.setUserId(cartItem.getUserId()); Map<ProductEntity,Integer> products=convertMap(cartItem.getProducts()); Set<ProductEntity> productSet=products.keySet(); for(ProductEntity product:productSet) { totalQuantity+=products.get(product); totalPrice+=product.getPrice()*products.get(product); } cart.setProducts(products); cart.setCartTotalPrice(totalPrice); cart.setTotalQuantity(totalQuantity);*/ return cart; } }
package asylumdev.adgresources.api.materialsystem.part; public class Ore { }
package hackhers; public class SaveTips { private String category; private String tip1, tip2, tip3; private int type; public SaveTips(String category, String tip1, String tip2, String tip3, int type) { category = ""; tip1 = ""; tip2 = ""; tip3 = ""; type = 0; } public void createTips(int type) { //1 - low, 2 - avg, 3 - high switch(type) { case 1: System.out.println("Keep it up!"); System.out.println("Based on your lifestyle, keep in mind that you may need to spend on essentials like clothing or groceries."); break; case 2: System.out.println("Consider investing your money. You'll be part owner of a company while getting money from them!"); System.out.println("If you have children, consider setting aside some money for their welfare and education."); break; case 3: System.out.println("Look at the categories you spend most for. Are these really important?"); System.out.println("Consider applying for a rewards card. You'll get money back, which accumulates."); } } }
package com.eegeo.mapapi.services.mapscene; import androidx.annotation.UiThread; import com.eegeo.mapapi.EegeoMap; import com.eegeo.mapapi.services.poi.PoiSearch; import com.eegeo.mapapi.services.poi.TextSearchOptions; /** * A service which allows you to request Mapscenes, as created by the WRLD Map Designer. * Created by the createMapsceneService method of the EegeoMap object. * * This is a Java interface to the <a href="https://github.com/wrld3d/wrld-mapscene-api">WRLD MAPSCENE REST API</a>. * * It also supports additional options for applying a Mapscene to a map when you successfully load it. */ public class MapsceneService { private MapsceneApi m_mapsceneApi; private MapsceneApplier m_mapsceneApplier; /** * @eegeo.internal */ public MapsceneService(MapsceneApi mapsceneApi, EegeoMap map) { this.m_mapsceneApi = mapsceneApi; this.m_mapsceneApplier = new MapsceneApplier(map); this.m_mapsceneApi.setMapsceneApplier(m_mapsceneApplier); } /** * Begins a Mapscene request with the given options. * * The results of the request will be passed as a MapsceneRequestResponse object to the callback provided in the options. * * @param options The parameters of the request. * @return A handle to the ongoing request, which can be used to cancel it. */ @UiThread public MapsceneRequest requestMapscene(final MapsceneRequestOptions options) { return m_mapsceneApi.requestMapscene(options); } }
package Tasks; import java.io.*; import java.util.*; public class Task54{ public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); Map<Integer, String> map = new HashMap<Integer, String>(); while (true) { String idStr = reader.readLine(); if (idStr.isEmpty()) { break; } int id = Integer.parseInt(idStr); String name = reader.readLine(); map.put(id, name); System.out.println(id + " " + name); } } }
package Repository.Impl; import Domain.Car; import Repository.CarRepository; import java.util.HashMap; import java.util.Map; /** * Created by Emma on 8/11/2018. */ public class CarRepositoryImpl implements CarRepository { private static CarRepositoryImpl respository = null; private Map<String, Car> carTable; private CarRepositoryImpl() { carTable = new HashMap<String, Car>(); } public static CarRepositoryImpl getInstance() { if (respository == null) respository = new CarRepositoryImpl(); return respository; } public Car create(Car createCar) { carTable.put(createCar.getCarRegNo(), createCar); Car savedCar = carTable.get(createCar.getCarRegNo()); return savedCar; } public Car read(String id) { Car car1 = carTable.get(id); return car1; } public Car update(Car updateCar) { carTable.put(updateCar.getCarRegNo(), updateCar); Car savedCar = carTable.get(updateCar.getCarRegNo()); return savedCar; } public void delete(String id) { carTable.remove(id); } }
//дана последовательность чисел. если упорядоченая написать - true? если нет - false. // 0 завершение последовательности package Loop; import java.util.Scanner; public class Loop21 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int num = scanner.nextInt(); int num2 = scanner.nextInt(); boolean b = true; if(num2 == 0){ System.out.print(b); } else { if (num2 >= num) { while (num2 >= num) { num = num2; num2 = scanner.nextInt(); b = true; if (num2 == 0) { break; } if (num2 < num) { b = false; break; } num = num2; } System.out.print(b); } else { while (num2 <= num) { num = num2; num2 = scanner.nextInt(); b = true; if (num2 == 0) { break; } if (num2 > num) { b = false; break; } num = num2; } System.out.print(b); } } } }
package org.trektrace.entities; import java.util.Vector; public class Route extends Entity { private String name; private String description; private Vector points = new Vector(); public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void addPoint(Point point) { point.setRouteId(getId()); points.addElement(point); } public Vector getPoints() { return points; } }
package com.uchain.storage; import java.io.IOException; import java.util.List; import java.util.Map; import lombok.val; import org.rocksdb.*; import scala.NotImplementedError; public class RocksDBStorage implements Storage<byte[],byte[]> { private RocksDB db; static { RocksDB.loadLibrary(); } public RocksDBStorage(RocksDB db){ this.db = db; } @Override public boolean containsKey(byte[] bytes) { return false; } @Override public byte[] get(byte[] key) { try{ ReadOptions opt = new ReadOptions().setFillCache(true); byte[] value = db.get(opt,key); if (value == null) { return null; } else { return value; } }catch (Exception e){ e.printStackTrace(); } return null; } @Override public boolean set(byte[] bytes, byte[] bytes2, Batch batch) { throw new NotImplementedError("This Exception!"); } @Override public boolean delete(byte[] bytes, Batch batch) { throw new NotImplementedError("This Exception!"); } @Override public void newSession() { throw new NotImplementedError("This Exception!"); } @Override public void commit(Integer revision) { throw new NotImplementedError("This Exception!"); } @Override public void commit() { throw new NotImplementedError("This Exception!"); } @Override public void rollBack() { throw new NotImplementedError("This Exception!"); } @Override public void close() { throw new NotImplementedError("This Exception!"); } @Override public List<Map.Entry<byte[], byte[]>> find(byte[] prefix) { throw new NotImplementedError("This Exception!"); } @Override public Batch batchWrite() { throw new NotImplementedError("This Exception!"); } @Override public Map.Entry<byte[], byte[]> last() throws IOException { throw new NotImplementedError("This Exception!"); } @Override public Integer revision() { throw new NotImplementedError("This Exception!"); } @Override public List<Integer> uncommitted() { throw new NotImplementedError("This Exception!"); } public static RocksDBStorage open(String path) { return open(path,true); } public static RocksDBStorage open(String path, Boolean createIfMissing){ try { val options = new Options(); options.setCreateIfMissing(createIfMissing); val db = RocksDB.open(options, path); return new RocksDBStorage(db); } catch (RocksDBException e) { e.printStackTrace(); } return null; } }
package com.meetingapp.android.activities.login.presenter; public interface IPresenter { void onCreate(); void onDestroy(); void getCountryCode(); }
package behavioral.iterator.bookcode.iterators; import java.util.ArrayList; import java.util.List; import behavioral.iterator.bookcode.profile.Profile; import behavioral.iterator.bookcode.socialnetwork.Facebook; public class FacebookIter implements ProfileIterator{ private Facebook facebook; private String type; private String email; private int currentPosition; private List<String> contactsEmails = new ArrayList<>(); private List<Profile> contactsProfiles = new ArrayList<>(); public FacebookIter(Facebook facebook, String type, String email) { this.facebook = facebook; this.type = type; this.email = email; } private void lazyLoad() { if (contactsEmails.isEmpty()) { List<String> contacts = facebook.getContacts(email, type); for (String contact : contacts) { contactsEmails.add(contact); contactsProfiles.add(null); } } } @Override public boolean hasNext() { lazyLoad(); return currentPosition < contactsEmails.size(); } @Override public Profile getNext() { if (!hasNext()) return null; String friendEmail = contactsEmails.get(currentPosition); Profile friendProfile = contactsProfiles.get(currentPosition); if (friendProfile == null) { friendProfile = facebook.getProfile(friendEmail); contactsProfiles.set(currentPosition, friendProfile); } currentPosition++; return friendProfile; } @Override public void reset() { currentPosition = 0; } }
// ********************************************************** // 1. 제 목: 관리자권한 // 2. 프로그램명 : GadminAdminBean.java // 3. 개 요: 관리자권한 관리 // 4. 환 경: JDK 1.3 // 5. 버 젼: 1.0 // 6. 작 성: 2003. 7. 16 // 7. 수 정: // ********************************************************** package com.ziaan.system; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.ErrorManager; import com.ziaan.library.ListSet; import com.ziaan.library.StringManager; /** * 회사조직분류 관리(ADMIN) * * @date : 2003. 7 * @author : s.j Jung */ public class GadminAdminBean { public GadminAdminBean() { } /** 권한코드 검색 리스트 @param box receive from the form object and session @return ArrayList 권한코드 검색 리스트 */ /* public ArrayList searchGadmin(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = null; String sql = ""; GadminData data = null; String v_search = box.getString("p_gubun"); String v_searchtext = box.getString("p_key1"); int v_pageno = box.getInt("p_pageno"); try { connMgr = new DBConnectionManager(); list = new ArrayList(); sql = " select gadmin, control, gadminnm, comments, isneedsubj, isneedcomp from TZ_GADMIN "; if ( !v_searchtext.equals("") ) { // 검색어가 있으면 if ( v_search.equals("gadmin") ) { // 코드로 검색할때 sql += " where comp like " + StringManager.makeSQL("%" + v_searchtext + "%"); } else if ( v_search.equals("gadminnm") ) { // 명칭으로 검색할때 sql += " where deptnm like " + StringManager.makeSQL("%" + v_searchtext + "%"); } } sql += " order by gadmin asc "; ls = connMgr.executeQuery(sql); ls.setPageSize(10); // 페이지당 row 갯수를 세팅한다 ls.setCurrentPage(v_pageno); // 현재페이지번호를 세팅한다. int total_page_count = ls.getTotalPage(); // 전체 페이지 수를 반환한다 int total_row_count = ls.getTotalCount(); // 전체 row 수를 반환한다 while ( ls.next() ) { data = new GadminData(); data.setGadmin( ls.getString("gadmin") ); data.setGadminnm( ls.getString("gadminnm") ); data.setControl( ls.getString("control") ); data.setComments( ls.getString("comments") ); data.setIsneedsubj( ls.getString("isneedsubj") ); data.setIsneedcomp( ls.getString("isneedcomp") ); data.setDispnum(total_row_count - ls.getRowNum() + 1); data.setTotalPageCount(total_page_count); list.add(data); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } */ /** 권한코드 셀렉트박스 @param name,selected,event,allcheck 셀렉트박스명,선택값,이벤트명,전체유무(0 -전체없음, 1 - 전체있음) @return result 권한코드 + "," + 교육그룹필요여부 + "," + 과목코드필요여부 + "," + 회사코드필요여부 + "," + 부서코드필요여부 */ public static String getGadminSelect (String name, String selected, String event) throws Exception { return getGadminSelect (name, selected, event, 1); } public static String getGadminSelect (String name, String selected, String event, int allcheck) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String result = null; String sql = ""; GadminData data = null; String v_value = ""; result = " <SELECT name=" + name + " " + event + " > \n"; if ( allcheck == 1) { result += " <option value='' >== =전체 == =</option > \n"; } try { connMgr = new DBConnectionManager(); sql = " select gadmin, gadminnm, isneedgrcode, isneedsubj, isneedcomp,isneeddept,seq from tz_gadmin "; sql += " where isview = 'Y'"; sql += " order by seq asc,gadmin asc"; ls = connMgr.executeQuery(sql); while ( ls.next() ) { data = new GadminData(); data.setGadmin( ls.getString("gadmin") ); data.setGadminnm( ls.getString("gadminnm") ); data.setIsneedgrcode( ls.getString("isneedgrcode") ); data.setIsneedsubj( ls.getString("isneedsubj") ); data.setIsneedcomp( ls.getString("isneedcomp") ); data.setIsneeddept( ls.getString("isneeddept") ); v_value = data.getGadmin() + "," + data.getIsneedgrcode() + "," + data.getIsneedsubj() + "," + data.getIsneedcomp() + "," + data.getIsneeddept(); result += " <option value=\"" + v_value + "\""; if ( selected.equals(v_value)) { result += " selected "; } result += " > " + data.getGadminnm() + "</option > \n"; } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } result += " </SELECT > \n"; return result; } /** 권한코드 셀렉트박스(강사제외) @param name,selected,event,allcheck 셀렉트박스명,선택값,이벤트명,전체유무(0 -전체없음, 1 - 전체있음) @return result 권한코드 + "," + 교육주관필요여부 + "," + 과목코드필요여부 + "," + 회사코드필요여부 + "," + 부서코드필요여부 */ public static String getGadminSelectNop (String name, String selected, String event) throws Exception { return getGadminSelectNop (name, selected, event, 1); } public static String getGadminSelectNop (String name, String selected, String event, int allcheck) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String result = null; String sql = ""; GadminData data = null; String v_value = ""; result = " <SELECT name=" + name + " " + event + " > \n"; if ( allcheck == 1) { result += " <option value='' >== =전체 == =</option > \n"; } try { connMgr = new DBConnectionManager(); sql = " select gadmin, gadminnm, isneedgrcode, isneedsubj, isneedcomp,isneeddept, isneedoutcomp from tz_gadmin "; sql += " where substr(gadmin,1,1) != 'P' "; sql += " and isview = 'Y'"; sql += " order by gadmin asc "; ls = connMgr.executeQuery(sql); while ( ls.next() ) { data = new GadminData(); data.setGadmin( ls.getString("gadmin") ); data.setGadminnm( ls.getString("gadminnm") ); data.setIsneedgrcode( ls.getString("isneedgrcode") ); data.setIsneedsubj( ls.getString("isneedsubj") ); data.setIsneedcomp( ls.getString("isneedcomp") ); data.setIsneeddept( ls.getString("isneeddept") ); data.setIsneedoutcomp( ls.getString("isneedoutcomp") ); v_value = data.getGadmin() + "," + data.getIsneedgrcode() + "," + data.getIsneedsubj() + "," + data.getIsneedcomp() + "," + data.getIsneeddept() + "," + data.getIsneedoutcomp(); result += " <option value=\"" + v_value + "\""; if ( selected.equals(v_value)) { result += " selected "; } result += " > " + data.getGadminnm() + "</option > \n"; } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } result += " </SELECT > \n"; return result; } /** 권한코드 셀렉트박스(강사제외) @param name,selected,event,allcheck 셀렉트박스명,선택값,이벤트명) @return result 권한코드 */ public static String getGadminSelectTop (String name, String gadmin) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String result = null; String sql = ""; GadminData data = null; String v_value = ""; String v_padmin = ""; result = " <SELECT name=" + name + " > \n"; try { connMgr = new DBConnectionManager(); sql = " select gadmin,"; sql += " gadminnm,"; sql += " isneedgrcode,"; sql += " isneedsubj,"; sql += " isneedcomp,"; sql += " isneeddept,"; sql += " padmin"; sql += " from tz_gadmin "; sql += " where gadmin = 'A1'"; sql += " or gadmin='A2'"; sql += " or gadmin='C1'"; sql += " or gadmin='C2'"; sql += " or gadmin='F1'"; sql += " or gadmin='H1'"; sql += " or gadmin='K2'"; sql += " or gadmin='P1'"; sql += " or gadmin='M1'"; sql += " order by gadmin asc"; ls = connMgr.executeQuery(sql); while ( ls.next() ) { data = new GadminData(); data.setGadmin( ls.getString("gadmin") ); data.setGadminnm( ls.getString("gadminnm") ); data.setIsneedgrcode( ls.getString("isneedgrcode") ); data.setIsneedsubj( ls.getString("isneedsubj") ); data.setIsneedcomp( ls.getString("isneedcomp") ); data.setIsneeddept( ls.getString("isneeddept") ); data.setPadmin( ls.getString("padmin") ); v_value = data.getGadmin() + "," + data.getIsneedgrcode() + "," + data.getIsneedsubj() + "," + data.getIsneedcomp() + "," + data.getIsneeddept(); v_padmin = data.getPadmin(); result += " <option value=\"" + v_value + "\""; if ( gadmin.equals(v_padmin)) { result += " selected "; } result += " > " + data.getGadminnm() + "</option > \n"; } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } result += " </SELECT > \n"; return result; } /** 권한코드 셀렉트박스-권한코드만 조회(강사제외) @param name,selected 셀렉트박스명,선택값,이벤트명) @return result 권한코드 */ public static String getGadminSelectOnly (String name, String gadmin, String event) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String result = null; String sql = ""; GadminData data = null; String v_value = ""; String v_gadmin = ""; result = " <SELECT name=" + name + " " + event + " > \n"; result += " <option value=userid"; if ( name.equals("") || name.equals("userid") ) { result += " selected "; } result += " > 운영자메뉴권한</option > \r\n"; try { connMgr = new DBConnectionManager(); sql = " select gadmin, gadminnm from tz_gadmin "; sql += " where isview = 'Y'"; sql += " order by gadmin asc "; ls = connMgr.executeQuery(sql); while ( ls.next() ) { data = new GadminData(); data.setGadmin( ls.getString("gadmin") ); data.setGadminnm( ls.getString("gadminnm") ); v_gadmin = data.getGadmin(); result += " <option value=\"" + v_gadmin + "\""; if ( gadmin.equals(v_gadmin)) { result += " selected "; } result += " > " + data.getGadminnm() + "</option > \n"; } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } result += " </SELECT > \n"; return result; } /** 권한코드 + 필요코드여부 @param gadmin gadmin code @return result 권한코드 + "," + 교육그룹필요여부 + "," + 과목코드필요여부 + "," + 회사코드필요여부 + "," + 부서코드필요여부 */ public static String getGadminIsNeed (String gadmin) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String result = null; String sql = ""; GadminData data = null; result = gadmin; try { connMgr = new DBConnectionManager(); sql = " select isneedgrcode, isneedsubj, isneedcomp,isneeddept, isneedoutcomp from tz_gadmin "; sql += " where gadmin = " + StringManager.makeSQL(gadmin); ls = connMgr.executeQuery(sql); if ( ls.next() ) { data = new GadminData(); data.setIsneedgrcode( ls.getString("isneedgrcode") ); data.setIsneedsubj( ls.getString("isneedsubj") ); data.setIsneedcomp( ls.getString("isneedcomp") ); data.setIsneeddept( ls.getString("isneeddept") ); data.setIsneedoutcomp( ls.getString("isneedoutcomp") ); result += "," + data.getIsneedgrcode() + "," + data.getIsneedsubj() + "," + data.getIsneedcomp() + "," + data.getIsneeddept() + "," + data.getIsneedoutcomp(); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return result; } /** 권한명 @param gadmin gadmin code @return result 권한명 */ public static String getGadminName (String gadmin) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String result = null; String sql = ""; GadminData data = null; result = gadmin; try { connMgr = new DBConnectionManager(); sql = " select gadminnm from tz_gadmin "; sql += " where gadmin = " + StringManager.makeSQL(gadmin); ls = connMgr.executeQuery(sql); if ( ls.next() ) { result = ls.getString("gadminnm"); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return result; } }
package com.programapprentice.app; /** * User: program-apprentice * Date: 8/17/15 * Time: 7:36 PM * Finished Time: 8:25 PM */ /** Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place, do not allocate extra memory. Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1 * */ public class NextPermutation_31 { public void reverse(int[] nums, int start) { int low = start; int high = nums.length-1; int tmp = 0; while(low < high) { tmp = nums[low]; nums[low] = nums[high]; nums[high] = tmp; low++; high--; } } public void nextPermutation(int[] nums) { if(nums == null || nums.length <= 1) { return; } int idx = nums.length-1; int pre = idx-1; while(pre >= 0 && nums[pre] >= nums[idx]) { pre--; idx--; } int start = 0; if(pre >= 0) { start = idx; idx = nums.length-1; while(nums[idx] <= nums[pre]) { idx--; } int tmp = nums[idx]; nums[idx] = nums[pre]; nums[pre] = tmp; } reverse(nums, start); } }
package com.example.admin.quizapplication; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import static android.os.Build.VERSION_CODES.M; import static com.example.admin.quizapplication.R.layout.page1; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void takeQuiz(View view){ Intent objectIntent = new Intent(MainActivity.this,page1.class); startActivity(objectIntent); } }
/* First created by JCasGen Sat Nov 30 21:13:01 EST 2013 */ package edu.cmu.lti.oaqa.qa4ds.types; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.cas.TOP_Type; /** * Updated by JCasGen Sat Nov 30 21:13:01 EST 2013 * @generated */ public class MergedAnswerLists_Type extends TOP_Type { /** @generated */ @Override protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (MergedAnswerLists_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = MergedAnswerLists_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new MergedAnswerLists(addr, MergedAnswerLists_Type.this); MergedAnswerLists_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new MergedAnswerLists(addr, MergedAnswerLists_Type.this); } }; /** @generated */ @SuppressWarnings ("hiding") public final static int typeIndexID = MergedAnswerLists.typeIndexID; /** @generated @modifiable */ @SuppressWarnings ("hiding") public final static boolean featOkTst = JCasRegistry.getFeatOkTst("edu.cmu.lti.oaqa.qa4ds.types.MergedAnswerLists"); /** @generated */ final Feature casFeat_children; /** @generated */ final int casFeatCode_children; /** @generated */ public int getChildren(int addr) { if (featOkTst && casFeat_children == null) jcas.throwFeatMissing("children", "edu.cmu.lti.oaqa.qa4ds.types.MergedAnswerLists"); return ll_cas.ll_getRefValue(addr, casFeatCode_children); } /** @generated */ public void setChildren(int addr, int v) { if (featOkTst && casFeat_children == null) jcas.throwFeatMissing("children", "edu.cmu.lti.oaqa.qa4ds.types.MergedAnswerLists"); ll_cas.ll_setRefValue(addr, casFeatCode_children, v);} /** @generated */ final Feature casFeat_parent; /** @generated */ final int casFeatCode_parent; /** @generated */ public int getParent(int addr) { if (featOkTst && casFeat_parent == null) jcas.throwFeatMissing("parent", "edu.cmu.lti.oaqa.qa4ds.types.MergedAnswerLists"); return ll_cas.ll_getRefValue(addr, casFeatCode_parent); } /** @generated */ public void setParent(int addr, int v) { if (featOkTst && casFeat_parent == null) jcas.throwFeatMissing("parent", "edu.cmu.lti.oaqa.qa4ds.types.MergedAnswerLists"); ll_cas.ll_setRefValue(addr, casFeatCode_parent, v);} /** initialize variables to correspond with Cas Type and Features * @generated */ public MergedAnswerLists_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_children = jcas.getRequiredFeatureDE(casType, "children", "uima.cas.FSList", featOkTst); casFeatCode_children = (null == casFeat_children) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_children).getCode(); casFeat_parent = jcas.getRequiredFeatureDE(casType, "parent", "org.oaqa.model.answer.AnswerList", featOkTst); casFeatCode_parent = (null == casFeat_parent) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_parent).getCode(); } }
package strike.elements; import java.awt.Color; import java.awt.Graphics2D; import resources.ColorSet; import square.Member; public class Element implements Member { protected int x; protected int y; public Element(int x, int y){ this.x=x; this.y=y; } @Override public void moveUp() { y--; } @Override public void moveRight() { x++; } @Override public void moveLeft() { x--; } @Override public void moveDown() { y++; } @Override public int getX() { return x; } @Override public int getY() { return y; } @Override public void draw(Graphics2D grf, int x, int y, int cellSize) { Color in = ColorSet.colorApple; Color out = ColorSet.colorBorder; int cellStep = cellSize*20/100; int cellSizeInner = cellSize-2*cellStep; grf.setColor(out); grf.fillRect(x, y, cellSize, cellSize); grf.setColor(in); grf.fillRect(x+cellStep, y+cellStep, cellSizeInner, cellSizeInner); } }
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.bvt.sql.mysql.create; import com.alibaba.druid.sql.MysqlTest; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateUserStatement; public class MySqlCreateUserTest_6 extends MysqlTest { public void test_0() throws Exception { String sql = "CREATE USER 'jeffrey'@'localhost' IDENTIFIED BY 'password';"; MySqlCreateUserStatement stmt = (MySqlCreateUserStatement) SQLUtils.parseSingleMysqlStatement(sql); assertEquals("CREATE USER 'jeffrey'@'localhost' IDENTIFIED BY 'password';", // SQLUtils.toMySqlString(stmt)); } public void test_1() throws Exception { String sql = "CREATE USER jeffrey@'localhost' IDENTIFIED BY 'password';"; MySqlCreateUserStatement stmt = (MySqlCreateUserStatement) SQLUtils.parseSingleMysqlStatement(sql); assertEquals("CREATE USER 'jeffrey'@'localhost' IDENTIFIED BY 'password';", // SQLUtils.toMySqlString(stmt)); } public void test_2() throws Exception { String sql = "CREATE USER 'jeffrey'@localhost IDENTIFIED BY 'password';"; MySqlCreateUserStatement stmt = (MySqlCreateUserStatement) SQLUtils.parseSingleMysqlStatement(sql); assertEquals("CREATE USER 'jeffrey'@'localhost' IDENTIFIED BY 'password';", // SQLUtils.toMySqlString(stmt)); } }
package com.github.dvdme.DarkSkyJava; // TODO: move to utils public enum DarkSkyLanguages { BOSNIAN("bs"), GERMAN("de"), ENGLISH("en"), SPANISH("es"), FRENCH("fr"), ITALIAN("it"), DUTCH ("nl"), POLISH ("pl"), PORTUGUESE("pt"), TETUM("tet"), PIG_LATIN("x-pig-latin"), RUSSIAN ("ru") ; private final String lang; private DarkSkyLanguages(final String lang) { this.lang = lang; } @Override public String toString() { return lang; } }
package com.gsccs.sme.api.domain.shop; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import com.gsccs.sme.api.domain.base.Domain; /** * 商品评价 * @author x.d zhang * */ public class EvalGoods extends Domain{ private static final long serialVersionUID = 1824833393882688421L; private Long id; /** * 产品ID */ private Long productid; /** * 评分 */ private Integer score; /** * 评价者 */ private Long userid; /** * 店铺ID */ private Long siteid; /** * 评价内容 */ private String content; /** * 评价时间 */ private Date addtime; private String showdatestr; private String username; public String getShowdatestr() { if (null != getAddtime()){ DateFormat df = new SimpleDateFormat("yyyy-mm-dd"); showdatestr = df.format(getAddtime()); } return showdatestr; } public void setShowdatestr(String showdatestr) { this.showdatestr = showdatestr; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getProductid() { return productid; } public void setProductid(Long productid) { this.productid = productid; } public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } public Long getUserid() { return userid; } public void setUserid(Long userid) { this.userid = userid; } public Long getSiteid() { return siteid; } public void setSiteid(Long siteid) { this.siteid = siteid; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getAddtime() { return addtime; } public void setAddtime(Date addtime) { this.addtime = addtime; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
package nesto.tapdragonaccessibility; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; /** * Created on 2017/2/22. * By nesto */ class Commands { private Process process; private DataOutputStream request; private void exec(String cmd) { try { if (process == null) { process = Runtime.getRuntime().exec("su"); request = new DataOutputStream(process.getOutputStream()); } request.write(cmd.getBytes()); request.flush(); } catch (Exception e) { e.printStackTrace(); } } void simulateKey(int keyCode) { exec("input keyevent " + keyCode + "\n"); } void tap(int x, int y) { // exec("input tap " + x + " " + y + "\n"); exec("sendevent /dev/input/event3 3 57 10086\n" + "sendevent /dev/input/event3 1 325 1\n" + "sendevent /dev/input/event3 1 330 1\n" + "sendevent /dev/input/event3 3 53 " + x + "\n" + "sendevent /dev/input/event3 3 54 " + y + "\n" + "sendevent /dev/input/event3 3 58 200\n" + "sendevent /dev/input/event3 3 50 5\n" + "sendevent /dev/input/event3 0 00 00000000\n" + "sendevent /dev/input/event3 3 57 4294967295\n" + "sendevent /dev/input/event3 1 325 0\n" + "sendevent /dev/input/event3 1 330 0\n" + "sendevent /dev/input/event3 0 00 00000000"); } void swipe(int x1, int y1, int x2, int y2) { StringBuilder builder = new StringBuilder(); builder.append("sendevent /dev/input/event3 3 57 10086\n"); builder.append("sendevent /dev/input/event3 1 325 1\n"); builder.append("sendevent /dev/input/event3 1 330 1\n"); for (int i = 0; i <= 100; i += 50) { double k = i / 100.0; builder.append("sendevent /dev/input/event3 3 53 ") .append((int) (x1 * (1 - k) + x2 * k)).append("\n"); builder.append("sendevent /dev/input/event3 3 54 ") .append((int) (y1 * (1 - k) + y2 * k)).append("\n"); builder.append("sendevent /dev/input/event3 3 58 200\n") .append("sendevent /dev/input/event3 3 50 5\n") .append("sendevent /dev/input/event3 0 00 00000000\n"); } builder.append("sendevent /dev/input/event3 3 57 4294967295\n") .append("sendevent /dev/input/event3 1 325 0\n") .append("sendevent /dev/input/event3 1 330 0\n") .append("sendevent /dev/input/event3 0 00 00000000"); exec(builder.toString()); // exec("input swipe " + x1 + " " + y1 + " " + x2 + " " + y2 + "\n"); } boolean isRightActivity() { try { Process process = Runtime.getRuntime() .exec("su -c dumpsys activity | grep top-activity"); if (process.waitFor() == 0) { BufferedReader in = new BufferedReader(new InputStreamReader( process.getInputStream())); String line = in.readLine(); return line.contains("game.dragon"); } } catch (InterruptedException | IOException e) { e.printStackTrace(); } return false; } }
/* Application Name: VideoInBox File Name: Date: Author: Description: */ package com.xtv.video_in_box; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.webkit.WebView; import android.widget.TextView; import android.widget.Toast; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerView; /* Activity that hosts youtube media player to play video that is selcted. */ public class MediaPlayer_Activity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener { public static final String API_KEY = "AIzaSyAdC9kSxN454zVTg0Q08Yvbhr6OjQiVbAQ"; ProgressDialog pDialog; WebView webView; TextView tv; String videoURL; /* Instantiates YouTube player and creates loader dialog/spinner image. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_media_player_); // webView = (WebView)findViewById(R.id.WebView); YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player); youTubePlayerView.initialize(API_KEY, this); tv = (TextView) findViewById(R.id.tv1); Intent i = getIntent(); videoURL = i.getStringExtra("media"); pDialog = new ProgressDialog(this); // Set progressbar title pDialog.setTitle("Loading Content..."); // Set progressbar message pDialog.setMessage("Buffering..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); // Show progressbar pDialog.show(); Log.i("url", videoURL); // webView.getSettings().setJavaScriptEnabled(true); // webView.getSettings().setPluginState(WebSettings.PluginState.ON); // webView.loadUrl("http://www.youtube.com/embed/" + videoURL + "?autoplay=1&vq=small"); // webView.setWebChromeClient(new WebChromeClient()); } /* Youtube Player Failed */ @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) { Toast.makeText(this, "Failed to Initialize!", Toast.LENGTH_LONG).show(); } /* Player success, plays video. */ @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) { /** add listeners to YouTubePlayer instance **/ player.setPlayerStateChangeListener(playerStateChangeListener); player.setPlaybackEventListener(playbackEventListener); /** Start buffering **/ if (!wasRestored) { player.cueVideo(videoURL); } } private YouTubePlayer.PlaybackEventListener playbackEventListener = new YouTubePlayer.PlaybackEventListener() { @Override public void onBuffering(boolean arg0) { } @Override public void onPaused() { } @Override public void onPlaying() { } @Override public void onSeekTo(int arg0) { } @Override public void onStopped() { } }; private YouTubePlayer.PlayerStateChangeListener playerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() { @Override public void onAdStarted() { } public void onError(YouTubePlayer.ErrorReason arg0) { } @Override public void onLoaded(String arg0) { } @Override public void onLoading() { } @Override public void onVideoEnded() { } @Override public void onVideoStarted() { } }; }
package com.alibaba.druid.bvt.sql.oracle.tomysql; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.druid.sql.SQLUtils; public class OracleToMySql_PageTest2 extends TestCase { public void test_page() throws Exception { String sql = "SELECT XX.*, ROWNUM AS RN" + // "\nFROM (SELECT *" + // "\n\tFROM t" + // "\n\tORDER BY id" + // "\n\t) XX" + // "\nWHERE ROWNUM < 10"; String mysqlSql = SQLUtils.translateOracleToMySql(sql); Assert.assertEquals("SELECT *"// + "\nFROM t"// + "\nORDER BY id"// + "\nLIMIT 9", mysqlSql); System.out.println(mysqlSql); } }
package com.zjf.myself.codebase.activity; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import com.zjf.myself.codebase.R; import com.zjf.myself.codebase.activity.ExerciseLibrary.BreakPointTestAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.BuilderTestAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.CloseBackKeyTestAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.CustomViewAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.DataPutExtraAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.GenQrCodeAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.GlideImgTestAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.HttpURLConnectionTestAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.DataStorageAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.HttpURLConnectionTestMeAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.KotlinTestAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.LifeCycleAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.LocWordAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.MapTestAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.MultiThreadAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.MySQLDatabaseTestAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.PhoneNumAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.PngToGifAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.ScreenTestAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.SharedPreferencesTestAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.TXTFileStorageAct; import com.zjf.myself.codebase.activity.ExerciseLibrary.VolleyAct; import com.zjf.myself.codebase.adapter.CommonAdaper; import com.zjf.myself.codebase.adapter.ViewHolder; import com.zjf.myself.codebase.model.BasicListViewInfo; import com.zjf.myself.codebase.util.AppLog; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2016/12/22. */ public class ListExerciseLibraryAct extends BaseAct implements AbsListView.OnScrollListener{ private ListView projectPageList; private BasicListViewAdapter adaper; private TextView title; private int mScreenHeight; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.win_exercise_library_list); title = (TextView)findViewById(R.id.title); title.setText("日常学习"); projectPageList = (ListView) findViewById(R.id.lvExerciseLibrary); adaper=new BasicListViewAdapter(this,null,R.layout.item_main); projectPageList.setAdapter(adaper); projectPageList.setOnItemClickListener(onItemClickListener); mScreenHeight = getResources().getDisplayMetrics().heightPixels; projectPageList.setOnScrollListener(this); List<BasicListViewInfo> menuItemList=new ArrayList<BasicListViewInfo>(); menuItemList.add(new BasicListViewInfo(0,"Builder练习","",new Intent(this, BuilderTestAct.class))); menuItemList.add(new BasicListViewInfo(0,"自定义View","",new Intent(this, CustomViewAct.class))); menuItemList.add(new BasicListViewInfo(0,"KotlinTest","",new Intent(this, KotlinTestAct.class))); menuItemList.add(new BasicListViewInfo(0,"数据库本地存储测试","",new Intent(this, DataStorageAct.class))); menuItemList.add(new BasicListViewInfo(0,"简单的创建SQL数据库测试","",new Intent(this, MySQLDatabaseTestAct.class))); menuItemList.add(new BasicListViewInfo(0,"数据本地存储测试","",new Intent(this, SharedPreferencesTestAct.class))); menuItemList.add(new BasicListViewInfo(0,"TXT文件存储","",new Intent(this, TXTFileStorageAct.class))); menuItemList.add(new BasicListViewInfo(0,"数据传递练习","",new Intent(this, DataPutExtraAct.class))); menuItemList.add(new BasicListViewInfo(0,"多线程基础","",new Intent(this, MultiThreadAct.class))); menuItemList.add(new BasicListViewInfo(0,"HttpURLConnection","",new Intent(this, HttpURLConnectionTestAct.class))); menuItemList.add(new BasicListViewInfo(0,"自定义图片HttpURLConnection","",new Intent(this, HttpURLConnectionTestMeAct.class))); menuItemList.add(new BasicListViewInfo(0,"简单生命周期示例","",new Intent(this, LifeCycleAct.class))); menuItemList.add(new BasicListViewInfo(0,"手机号码正则判断","",new Intent(this, PhoneNumAct.class))); menuItemList.add(new BasicListViewInfo(0,"地图定位测试","",new Intent(this, LocWordAct.class))); menuItemList.add(new BasicListViewInfo(0,"关闭物理返回键测试","",new Intent(this, CloseBackKeyTestAct.class))); menuItemList.add(new BasicListViewInfo(0,"断点调试测试学习","",new Intent(this, BreakPointTestAct.class))); menuItemList.add(new BasicListViewInfo(0,"Map学习","",new Intent(this, MapTestAct.class))); menuItemList.add(new BasicListViewInfo(0,"屏幕学习","",new Intent(this, ScreenTestAct.class))); menuItemList.add(new BasicListViewInfo(0,"Glide加载图片缓存练习","",new Intent(this, GlideImgTestAct.class))); menuItemList.add(new BasicListViewInfo(0,"png帧动画","",new Intent(this, PngToGifAct.class))); menuItemList.add(new BasicListViewInfo(0,"生成二维码","",new Intent(this, GenQrCodeAct.class))); menuItemList.add(new BasicListViewInfo(0,"Volley","",new Intent(this, VolleyAct.class))); adaper.addList(menuItemList,true); AppLog.e("start onCreate~~~1"); } private AdapterView.OnItemClickListener onItemClickListener=new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { BasicListViewInfo item= (BasicListViewInfo) adapterView.getAdapter().getItem(i); Intent intent = new Intent(item.getIt()); startActivity(intent); // Toast.makeText(ListExerciseLibraryAct.this,"您点击了"+item.getTxtLeft(),Toast.LENGTH_SHORT).show(); } }; static class BasicListViewAdapter extends CommonAdaper{ public BasicListViewAdapter(Context context, List list, int itemLayoutId) { super(context, list, itemLayoutId); } @Override public void convert(ViewHolder holder, Object item, int position) { BasicListViewInfo menuItem= (BasicListViewInfo) item; holder.setImageResource(R.id.imgleft, menuItem.getImgLeft()); holder.setText(R.id.txtLeft,menuItem.getTxtLeft()); holder.setText(R.id.txtRight, menuItem.getTxtRight()); int num = position +1; holder.setText(R.id.txtNum, num+"."); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { View childAt = view.getChildAt(0); if (childAt == null) return; int scrollY = firstVisibleItem * childAt.getHeight() - childAt.getTop(); if (scrollY <= (mScreenHeight / 3f)) { float alpha = 1f - (scrollY / (mScreenHeight / 3f)); title.setAlpha(alpha); } } @Override protected void onStart() { super.onStart(); AppLog.e("start onStart~~~1"); } @Override protected void onRestart() { super.onRestart(); // editView.setText(mString); AppLog.e("start onRestart~~~1"); } @Override protected void onResume() { super.onResume(); AppLog.e("start onResume~~~1"); } @Override public void onPause() { super.onPause(); // mString = editView.getText().toString(); AppLog.e("start onPause~~~1"); } @Override protected void onStop() { super.onStop(); AppLog.e("start onStop~~~1"); } @Override protected void onDestroy() { super.onDestroy(); AppLog.e("start onDestroy~~~1"); } }
package com.example.marvelapp.comics; import com.google.gson.annotations.SerializedName; import java.util.HashMap; import java.util.Map; public class Price { @SerializedName("type") private String type; @SerializedName("price") private Double price; public String getType() { return type; } public Double getPrice() { return price; } }
package Trie; /** * @Auther: liuyi * @Date: 2019/7/24 17:19 * @Description: 字典树 */ class TrieNode { private boolean isEnd; private final int size = 26; private TrieNode[] trieNum; public TrieNode(){ trieNum = new TrieNode[size]; } public boolean getIsEnd(){ return isEnd; } public void setEnd(){ isEnd=true; } public boolean containsKey(Character ch){ return trieNum[ch-'a']!=null; } public void put(Character ch,TrieNode node){ trieNum[ch-'a']=node; } public TrieNode get(Character ch){ return trieNum[ch-'a']; } } public class Trie { private TrieNode root; /** Initialize your data structure here. */ public Trie() { root=new TrieNode(); } /** Inserts a word into the trie. */ public void insert(String word) { TrieNode node = root; for(int i=0;i<word.length();i++){ Character ch = word.charAt(i); if(!node.containsKey(ch)){ node.put(ch,new TrieNode()); } node=node.get(ch); } node.setEnd(); } public TrieNode searchPrefix(String word){ TrieNode node = root; for(int i=0;i<word.length();i++){ Character ch=word.charAt(i); if(node.containsKey(ch)){ node=node.get(ch); }else{ return null; } } return node; } /** Returns if the word is in the trie. */ public boolean search(String word) { TrieNode node = searchPrefix(word); return node!=null && node.getIsEnd(); } /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { TrieNode node=searchPrefix(prefix); return node!=null; } }
package com.zantong.mobilecttx.base; /** * Created by Administrator on 2016/4/25. */ public class APPConfig { //// public static String HTTPUrl = "https://ctkapptest.icbc-axa.com/"; //上海地址 // public static String HTTPUrl = "https://ctkapp.icbc-axa.com/"; //上海地址(正式地址) // public static String APPUrl = HTTPUrl+"ecip/"; //上海地址 // public static String BASE_Url = APPUrl+"mobilecall_call"; //上海地址 // public static String APPFileUrl = "https://ctkapp.icbc-axa.com:9000/"; //外网地址(正式地址) // public static String ImageLoadUrl = "https://ctkapp.icbc-axa.com/"; //图片下载地址(正式地址) // // public static String CARMANGERURL = "http://test.w1buy.cn:8081/cttx/"; // public static String LATURL = "http://api.go2map.com/engine/api/translate/json?points="; }