hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
d14adbd70f1e7fc8bd1b354175d7f0cea2240e41
1,399
/* * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ package io.dapr.apps.twitter.provider.model; import com.fasterxml.jackson.annotation.JsonProperty; public class Tweet { @JsonProperty("id_str") private String id; @JsonProperty("user") private TwitterUser author; @JsonProperty("full_text") private String fullText; @JsonProperty("text") private String text; @JsonProperty("lang") private String language; public String getId() { return id; } public void setId(String id) { this.id = id; } public TwitterUser getAuthor() { return author; } public void setAuthor(TwitterUser author) { this.author = author; } public String getFullText() { return fullText; } public void setFullText(String fullText) { this.fullText = fullText; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } @Override public String toString() { return "Tweet [author=" + author + ", fullText=" + fullText + ", id=" + id + ", language=" + language + ", text=" + text + "]"; } }
19.164384
109
0.59614
6d23dcf291c6641461b352da9750e8249ee26c94
3,095
package xreliquary.items; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.MobEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.potion.EffectInstance; import net.minecraft.potion.Effects; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.event.entity.living.LivingSetAttackTargetEvent; import xreliquary.items.util.IBaubleItem; import xreliquary.reference.Settings; import xreliquary.util.InventoryHelper; import xreliquary.util.MobHelper; public class TwilightCloakItem extends ToggleableItem implements IBaubleItem { public TwilightCloakItem() { super("twilight_cloak", new Properties().maxStackSize(1)); MinecraftForge.EVENT_BUS.addListener(this::onEntityTargetedEvent); MinecraftForge.EVENT_BUS.addListener(this::onLivingUpdate); } @Override public Rarity getRarity(ItemStack stack) { return Rarity.EPIC; } @Override public void inventoryTick(ItemStack twilightCloak, World world, Entity entity, int itemSlot, boolean isSelected) { if (!(entity instanceof PlayerEntity)) { return; } updateInvisibility(twilightCloak, (PlayerEntity) entity); } private void updateInvisibility(ItemStack twilightCloak, PlayerEntity player) { if (!isEnabled(twilightCloak)) { return; } //toggled effect, makes player invisible based on light level (configurable) if (player.world.getLight(new BlockPos(player.getPosition())) > Settings.COMMON.items.twilightCloak.maxLightLevel.get()) { return; } //checks if the effect would do anything. Literally all this does is make the player invisible. It doesn't interfere with mob AI. //for that, we're attempting to use an event handler. EffectInstance quickInvisibility = new EffectInstance(Effects.INVISIBILITY, 2, 0, false, false); player.addPotionEffect(quickInvisibility); } @Override public IBaubleItem.Type getBaubleType() { return Type.BODY; } @Override public void onWornTick(ItemStack twilightCloak, LivingEntity player) { updateInvisibility(twilightCloak, (PlayerEntity) player); } private void onEntityTargetedEvent(LivingSetAttackTargetEvent event) { doTwilightCloakCheck(event); } private void onLivingUpdate(LivingEvent.LivingUpdateEvent event) { doTwilightCloakCheck(event); } private void doTwilightCloakCheck(LivingEvent event) { if (event.getEntity() instanceof MobEntity) { MobEntity entityLiving = ((MobEntity) event.getEntity()); if (!(entityLiving.getAttackTarget() instanceof PlayerEntity)) { return; } PlayerEntity player = (PlayerEntity) entityLiving.getAttackTarget(); if (!InventoryHelper.playerHasItem(player, this, true, IBaubleItem.Type.BODY) || player.world.getLight(player.getPosition()) > Settings.COMMON.items.twilightCloak.maxLightLevel.get()) { return; } MobHelper.resetTarget(entityLiving); } } }
33.641304
188
0.78643
0643d6e97b880e036e93e85a07c4c81f5421fb28
2,109
package b.l.a.c.f.i; public final class j1 extends p5<j1, i1> implements r6 { /* access modifiers changed from: private */ public static final j1 zzi; private int zza; private int zze; private c2 zzf; private c2 zzg; private boolean zzh; static { j1 j1Var = new j1(); zzi = j1Var; p5.q(j1.class, j1Var); } public static /* synthetic */ void B(j1 j1Var, int i2) { j1Var.zza |= 1; j1Var.zze = i2; } public static /* synthetic */ void C(j1 j1Var, c2 c2Var) { j1Var.zzf = c2Var; j1Var.zza |= 2; } public static /* synthetic */ void D(j1 j1Var, c2 c2Var) { j1Var.zzg = c2Var; j1Var.zza |= 4; } public static /* synthetic */ void E(j1 j1Var, boolean z) { j1Var.zza |= 8; j1Var.zzh = z; } public static i1 z() { return (i1) zzi.m(); } public final Object r(int i2, Object obj, Object obj2) { int i3 = i2 - 1; if (i3 == 0) { return (byte) 1; } if (i3 == 2) { return new z6(zzi, "\u0001\u0004\u0000\u0001\u0001\u0004\u0004\u0000\u0000\u0000\u0001င\u0000\u0002ဉ\u0001\u0003ဉ\u0002\u0004ဇ\u0003", new Object[]{"zza", "zze", "zzf", "zzg", "zzh"}); } else if (i3 == 3) { return new j1(); } else { if (i3 == 4) { return new i1((f1) null); } if (i3 != 5) { return null; } return zzi; } } public final boolean s() { return (this.zza & 1) != 0; } public final int t() { return this.zze; } public final c2 u() { c2 c2Var = this.zzf; return c2Var == null ? c2.D() : c2Var; } public final boolean v() { return (this.zza & 4) != 0; } public final c2 w() { c2 c2Var = this.zzg; return c2Var == null ? c2.D() : c2Var; } public final boolean x() { return (this.zza & 8) != 0; } public final boolean y() { return this.zzh; } }
22.923913
196
0.485064
4af4ec2ca2f277ce678d5166b22ebdf27e5f6b85
1,447
package transformation; import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import transform.LineTransformator; @RunWith(JUnitParamsRunner.class) public class ReplaceStringTransformatorTest { @Test @Parameters public void testUpdateLineWorks(String inputLine, Map<String, String> map, boolean isItRegex, String expected) { LineTransformator tran = new ReplaceStringTransformator(map, isItRegex); assertEquals(expected, tran.updateLine(inputLine)); } public Object[] parametersForTestUpdateLineWorks() { return new Object[] { new Object[] {"This is not good", getMap("good", "bad"), false, "This is not bad"}, new Object[] {"This is not good", getMap("o", "-", "i", "*"), false, "Th*s *s n-t g--d"}, new Object[] {"^(-?[0-9]+)(-)(-?[0-9]+)$", getMap("(","", ")", ""), false, "^-?[0-9]+--?[0-9]+$"}, new Object[] {"-0 (-?[0-9]+)", getMap("(-?[0-9]+)", "regex"), false, "-0 regex"}, new Object[] {"This is not good", getMap("([dgo])", ""), true, "This is nt "}, }; } private Map<String, String> getMap(String... params){ Map<String, String> result = new HashMap<>(); for (int i = 0; i < params.length; i+=2) { result.put(params[i], params[i+1]); } return result; } }
31.456522
114
0.626814
faed01e76c9be57d928f3bd48e7b48eb115bb3a4
168
package com.duo.bai.cheng.web.api.service; import com.duo.bai.cheng.commons.dto.BaseResult; public interface EssentialService { BaseResult select(String name); }
21
48
0.779762
4f6265a3a43826097eba6577f72053cf1216702e
2,253
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. *******************************************************************************/ package org.ofbiz.shark.instance; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilObject; import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericDelegator; public abstract class InstanceEntityObject { protected transient Delegator delegator = null; protected EntityPersistentMgr mgr = null; protected String delegatorName = null; public InstanceEntityObject(EntityPersistentMgr mgr, Delegator delegator) { this.delegatorName = delegator.getDelegatorName(); this.delegator = delegator; this.mgr = mgr; } public EntityPersistentMgr getPersistentManager() { return this.mgr; } public Delegator getGenericDelegator() { if (this.delegator == null && delegatorName != null) { this.delegator = DelegatorFactory.getDelegator(this.delegatorName); } return this.delegator; } public abstract boolean isLoaded(); public abstract void store() throws GenericEntityException; public abstract void reload() throws GenericEntityException; public abstract void remove() throws GenericEntityException; }
38.186441
82
0.671105
6129d3818223b20867a45759e32ee4c10830569d
4,939
package automaton.cards; import com.megacrit.cardcrawl.actions.AbstractGameAction; import com.megacrit.cardcrawl.actions.common.AttackDamageRandomEnemyAction; import com.megacrit.cardcrawl.actions.common.ExhaustSpecificCardAction; import com.megacrit.cardcrawl.actions.utility.WaitAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.cards.status.Burn; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.monsters.AbstractMonster; public class BurnOut extends AbstractBronzeCard { public final static String ID = makeID("BurnOut"); //stupid intellij stuff attack, all_enemy, rare private static final int DAMAGE = 5; private static final int UPG_DAMAGE = 3; public BurnOut() { super(ID, 2, CardType.ATTACK, CardRarity.RARE, CardTarget.ALL_ENEMY); baseDamage = DAMAGE; cardsToPreview = new Burn(); } public void use(AbstractPlayer p, AbstractMonster m) { int statusCount = 0; for (int i = 0; i < p.drawPile.size(); ) { AbstractCard c = p.drawPile.group.get(i); if (c.type == CardType.STATUS) { statusCount++; p.drawPile.removeCard(c); p.limbo.addToTop(c); c.targetDrawScale = 0.5F; c.setAngle(0, true); c.target_x = AbstractDungeon.cardRandomRng.random(AbstractCard.IMG_WIDTH, Settings.WIDTH - AbstractCard.IMG_WIDTH); c.target_y = AbstractDungeon.cardRandomRng.random(AbstractCard.IMG_HEIGHT, Settings.HEIGHT - AbstractCard.IMG_HEIGHT); atb(new ExhaustSpecificCardAction(c, p.limbo)); atb(new WaitAction(0.1F)); } else { i++; } } for (int i = 0; i < p.discardPile.size(); ) { AbstractCard c = p.discardPile.group.get(i); if (c.type == CardType.STATUS) { statusCount++; p.discardPile.removeCard(c); p.limbo.addToTop(c); c.targetDrawScale = 0.5F; c.setAngle(0, true); c.target_x = AbstractDungeon.cardRandomRng.random(AbstractCard.IMG_WIDTH, Settings.WIDTH - AbstractCard.IMG_WIDTH); c.target_y = AbstractDungeon.cardRandomRng.random(AbstractCard.IMG_HEIGHT, Settings.HEIGHT - AbstractCard.IMG_HEIGHT); atb(new ExhaustSpecificCardAction(c, p.limbo)); atb(new WaitAction(0.1F)); } else { i++; } } for (int i = 0; i < p.hand.size(); ) { AbstractCard c = p.hand.group.get(i); if (c.type == CardType.STATUS) { statusCount++; p.hand.removeCard(c); p.limbo.addToTop(c); c.targetDrawScale = 0.5F; c.setAngle(0, true); c.target_x = AbstractDungeon.cardRandomRng.random(AbstractCard.IMG_WIDTH, Settings.WIDTH - AbstractCard.IMG_WIDTH); c.target_y = AbstractDungeon.cardRandomRng.random(AbstractCard.IMG_HEIGHT, Settings.HEIGHT - AbstractCard.IMG_HEIGHT); atb(new ExhaustSpecificCardAction(c, p.limbo)); atb(new WaitAction(0.1F)); } else { i++; } } if (statusCount > 0) { for (int i = 0; i < statusCount; i++) { atb(new AttackDamageRandomEnemyAction(this, AbstractGameAction.AttackEffect.FIRE)); } } shuffleIn(new Burn(), 3); } public void applyPowers() { super.applyPowers(); if (AbstractDungeon.player != null) { this.rawDescription = cardStrings.DESCRIPTION; int statusCount = 0; for (AbstractCard c : AbstractDungeon.player.drawPile.group) { if (c.type == CardType.STATUS) { statusCount++; } } for (AbstractCard c : AbstractDungeon.player.discardPile.group) { if (c.type == CardType.STATUS) { statusCount++; } } for (AbstractCard c : AbstractDungeon.player.hand.group) { if (c.type == CardType.STATUS) { statusCount++; } } this.rawDescription = this.rawDescription + cardStrings.EXTENDED_DESCRIPTION[0] + statusCount; this.rawDescription = this.rawDescription + cardStrings.EXTENDED_DESCRIPTION[1]; this.initializeDescription(); } } public void onMoveToDiscard() { this.rawDescription = cardStrings.DESCRIPTION; this.initializeDescription(); } public void upp() { upgradeDamage(UPG_DAMAGE); } }
37.135338
134
0.585746
96f9d01e365db1275d367a6ebd75ab15c9931995
884
package site.wenlong.dimens.utils; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; /** * 计算工具类 * * @author : 郭文龙 * @date : 2019/4/30 23:30 */ public class CalculateUtils { public static String targetDimension(float dimens, int length, float scale) { return formatDecimal(dimens / scale, length); } public static float scale(float originDimension, float toDimension) { return originDimension / toDimension; } public static String formatDecimal(double originNumber, int length) { StringBuilder sb = new StringBuilder("0."); for (int l = 0; l < length; l++) { sb.append("#"); } String decimal = new DecimalFormat(sb.toString()).format(originNumber); return NumberFormat.getNumberInstance(Locale.getDefault()).format(Double.valueOf(decimal)); } }
29.466667
99
0.670814
853f862feb46221967f66ef85dea57bd151e3967
13,162
package com.alibaba.dcm.agent; import com.alibaba.dcm.DnsCache; import com.alibaba.dcm.DnsCacheEntry; import com.alibaba.dcm.DnsCacheManipulator; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.*; import java.lang.instrument.Instrumentation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.*; import java.util.logging.Logger; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; /** * DCM agent. * * @author Jerry Lee (oldratlee at gmail dot com) * @see Instrumentation * @see <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.instrument/java/lang/instrument/package-summary.html">The mechanism for instrumentation</a> * @see <a href="https://docs.oracle.com/javase/10/docs/specs/jar/jar.html#jar-manifest">JAR File Specification - JAR Manifest</a> * @see <a href="https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html">Working with Manifest Files - The Java™ Tutorials</a> * @since 1.4.0 */ public class DcmAgent { private static final Logger logger = Logger.getLogger(DcmAgent.class.getName()); private static final String FILE_KEY = "file"; private static final String DCM_AGENT_SUPRESS_EXCEPTION_STACK = "DCM_AGENT_SUPRESS_EXCEPTION_STACK"; static final String DCM_AGENT_SUCCESS_MARK_LINE = "!!DCM SUCCESS!!"; /** * Entrance method of DCM Java Agent. */ @SuppressFBWarnings("THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION") public static void agentmain(@Nonnull String agentArgument) throws Exception { logger.info(format("%s: attached with agent argument: %s.%n", DcmAgent.class.getName(), agentArgument)); agentArgument = agentArgument.trim(); if (agentArgument.isEmpty()) { logger.info(DcmAgent.class.getName() + ": agent argument is blank, do nothing!"); return; } initAction2Method(); PrintWriter filePrinter = null; try { final Map<String, List<String>> action2Arguments = parseAgentArgument(agentArgument); // Extract file argument, set file printer if needed filePrinter = getFilePrintWriter(action2Arguments.remove(FILE_KEY)); if (action2Arguments.isEmpty()) { logger.info(DcmAgent.class.getName() + ": No action in agent argument, do nothing!"); if (filePrinter != null) { filePrinter.printf("No action in agent argument, do nothing! agent argument: %s.%n", agentArgument); } return; } boolean allSuccess = true; for (Map.Entry<String, List<String>> entry : action2Arguments.entrySet()) { final String action = entry.getKey(); final List<String> arguments = entry.getValue(); boolean success = doAction(action, arguments, filePrinter); if (!success) allSuccess = false; } if (allSuccess && filePrinter != null) { filePrinter.println(DCM_AGENT_SUCCESS_MARK_LINE); } } finally { if (filePrinter != null) { try { filePrinter.close(); } catch (Exception e) { // do nothing! } } } } @Nonnull private static Map<String, List<String>> parseAgentArgument(@Nonnull String argument) { final String[] split = argument.split("\\s+"); int idx = 0; Map<String, List<String>> action2Arguments = new HashMap<>(); while (idx < split.length) { final String action = split[idx++]; if (!action2Method.containsKey(action)) { continue; // TODO error message } List<String> arguments = new ArrayList<>(); while (idx < split.length) { if (action2Method.containsKey(split[idx])) { break; } arguments.add(split[idx++]); } action2Arguments.put(action, arguments); } return action2Arguments; } @Nullable private static PrintWriter getFilePrintWriter(@Nullable List<String> files) throws FileNotFoundException { if (null == files) return null; FileOutputStream fileOutputStream = new FileOutputStream(files.get(0), false); final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, UTF_8); return new PrintWriter(outputStreamWriter, true); } private static boolean doAction(final String action, final List<String> arguments, final PrintWriter filePrinter) { final String argumentString = join(arguments); if (!action2Method.containsKey(action)) { logger.info(format(("%s: Unknown action %s, ignore! action: %<s %s!%n"), DcmAgent.class.getName(), action, argumentString)); if (filePrinter != null) { filePrinter.printf("Unknown action %s, ignore! action: %<s %s !%n", action, argumentString); } return false; } try { final Object result = invokeAction(action, arguments.toArray(new String[0])); printActionResult(action, result, filePrinter); return true; } catch (Exception e) { final String exString = throwable2StackString(e); final String sdtoutExString; if (isDcmAgentSupressExceptionStack()) { sdtoutExString = e.toString(); } else { sdtoutExString = exString; } logger.info(format(("%s: Error to do action %s %s, cause: %s%n"), DcmAgent.class.getName(), action, argumentString, sdtoutExString)); if (filePrinter != null) { filePrinter.printf("Error to do action %s %s, cause: %s%n", action, argumentString, exString); } return false; } } private static boolean isDcmAgentSupressExceptionStack() { String supressException = getConfig(DCM_AGENT_SUPRESS_EXCEPTION_STACK); if (supressException == null) return false; supressException = supressException.trim(); if (supressException.length() == 0) return false; return "true".equalsIgnoreCase(supressException); } private static Object invokeAction(String action, String[] arguments) throws InvocationTargetException, IllegalAccessException { Method method = action2Method.get(action); final Class<?>[] parameterTypes = method.getParameterTypes(); final Object[] methodArgs = convertStringArray2Arguments(action, arguments, parameterTypes); return method.invoke(null, methodArgs); } private static Object[] convertStringArray2Arguments(String action, String[] arguments, Class<?>[] parameterTypes) { if (arguments.length < parameterTypes.length) { final String message = format("Action %s need more argument! arguments: %s", action, Arrays.toString(arguments)); throw new IllegalStateException(message); } if (parameterTypes.length == 0) return new Object[0]; final Object[] methodArgs = new Object[parameterTypes.length]; final int lastArgumentIdx = parameterTypes.length - 1; if (parameterTypes[(lastArgumentIdx)] == String[].class) { // set all tail method argument of type String[] String[] varArgs = new String[arguments.length - lastArgumentIdx]; System.arraycopy(arguments, lastArgumentIdx, varArgs, 0, varArgs.length); methodArgs[(lastArgumentIdx)] = varArgs; } else if (arguments.length > parameterTypes.length) { String message = format("Too many arguments for action %s! arguments: %s", action, Arrays.toString(arguments)); throw new IllegalStateException(message); } for (int i = 0; i < parameterTypes.length; i++) { // already set if (methodArgs[i] != null) continue; Class<?> parameterType = parameterTypes[i]; final String argument = arguments[i]; if (parameterType.equals(String.class)) { methodArgs[i] = argument; } else if (parameterType.equals(int.class)) { methodArgs[i] = Integer.parseInt(argument); } else { final String message = format("Unexpected method type %s! Misused or Bug!!", parameterType.getName()); throw new IllegalStateException(message); } } return methodArgs; } private static void printActionResult(String action, Object result, PrintWriter writer) { if (writer == null) return; final Method method = action2Method.get(action); if (method.getReturnType() == void.class) return; if (result == null) { writer.println((Object) null); } else if (result instanceof DnsCacheEntry) { printDnsCacheEntry((DnsCacheEntry) result, writer); } else if (result instanceof DnsCache) { DnsCache dnsCache = (DnsCache) result; printDnsCacheEntryList("Dns cache: ", dnsCache.getCache(), writer); writer.println(); printDnsCacheEntryList("Dns negative cache: ", dnsCache.getNegativeCache(), writer); } else { writer.println(result); } } private static void printDnsCacheEntryList(String msg, List<DnsCacheEntry> dnsCacheEntries, PrintWriter writer) { writer.println(msg); for (DnsCacheEntry entry : dnsCacheEntries) { printDnsCacheEntry(entry, writer); } } private static void printDnsCacheEntry(DnsCacheEntry entry, PrintWriter writer) { final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); writer.printf(" %s %s %s%n", entry.getHost(), join(Arrays.asList(entry.getIps()), ","), dateFormat.format(entry.getExpiration())); } private static volatile Map<String, Method> action2Method; private static volatile ArrayList<String> actionList; private static synchronized void initAction2Method() throws NoSuchMethodException { if (action2Method != null) return; Map<String, Method> map = new LinkedHashMap<>(); map.put("set", DnsCacheManipulator.class.getMethod("setDnsCache", String.class, String[].class)); map.put("get", DnsCacheManipulator.class.getMethod("getDnsCache", String.class)); map.put("rm", DnsCacheManipulator.class.getMethod("removeDnsCache", String.class)); map.put("list", DnsCacheManipulator.class.getMethod("getWholeDnsCache")); map.put("ls", DnsCacheManipulator.class.getMethod("getWholeDnsCache")); map.put("clear", DnsCacheManipulator.class.getMethod("clearDnsCache")); map.put("setPolicy", DnsCacheManipulator.class.getMethod("setDnsCachePolicy", int.class)); map.put("getPolicy", DnsCacheManipulator.class.getMethod("getDnsCachePolicy")); map.put("setNegativePolicy", DnsCacheManipulator.class.getMethod("setDnsNegativeCachePolicy", int.class)); map.put("getNegativePolicy", DnsCacheManipulator.class.getMethod("getDnsNegativeCachePolicy")); actionList = new ArrayList<>(map.keySet()); map.put(FILE_KEY, null); // FAKE KEY action2Method = map; } /** * the action list for DCM agent. * * @since 1.6.0 */ @SuppressWarnings("unchecked") @SuppressFBWarnings("THROWS_METHOD_THROWS_RUNTIMEEXCEPTION") public static List<String> getActionList() { try { initAction2Method(); return (List<String>) actionList.clone(); } catch (Exception e) { throw new RuntimeException("fail to getActionList, cause: " + e, e); } } /////////////////////////////////////////////// // util methods /////////////////////////////////////////////// @Nullable private static String getConfig(@Nonnull String name) { String var = System.getenv(name); if (var == null || var.trim().length() == 0) { var = System.getProperty(name); } return var; } @Nonnull private static String join(@Nonnull List<String> list) { return join(list, " "); } @Nonnull private static String join(@Nonnull List<String> list, @Nonnull String separator) { StringBuilder ret = new StringBuilder(); for (String argument : list) { if (ret.length() > 0) { ret.append(separator); } ret.append(argument); } return ret.toString(); } @Nonnull private static String throwable2StackString(@Nonnull Throwable e) { final StringWriter w = new StringWriter(); e.printStackTrace(new PrintWriter(w, true)); return w.toString(); } }
39.525526
164
0.625893
6336bee1a73a1a8afe49a8829867ce2431d622eb
1,018
package smitebot; import javax.security.auth.login.LoginException; import net.dv8tion.jda.core.AccountType; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.JDABuilder; import net.dv8tion.jda.core.exceptions.RateLimitedException; public class Bot { public static JDA jda; // public static final String BOT_TOKEN = "MzE1MTU0NTU3NDAxNDMyMDY2.DACqsg.nLkof0R_ChX-65TAgpQcXLhe99Y"; public static void main(String[] args) { SmiteApiMethods session = SmiteApiMethods.getSession(); try { jda = new JDABuilder(AccountType.BOT).addEventListener(new BotListener(session)).setToken(Utils.botToken).buildBlocking(); // driver.getPlayer("DemonSlab"); // driver.getMatchHistory("DemonSlab"); // driver.getPlayerAchievements(2689961 + ""); } catch (LoginException | IllegalArgumentException | InterruptedException | RateLimitedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
29.941176
134
0.710216
aa5b545331af01800bf535d6737bff67ee2db478
425
package com.epicodus.guest.fairweatherfriend.ui; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.epicodus.guest.fairweatherfriend.R; public class RestaurantDetailActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_restaurant_detail); } }
26.5625
65
0.788235
59a6911e061f8c1542e9c1fc7ce6e95f861cef2f
898
// The SUPPLYQUANTITIES procedure returns the average, minimum, and maximum // quantities of available parts in inventory to separate output // parameters. // // See http://trafodion.incubator.apache.org/docs/spj_guide/index.html#supplyquantities-procedure // for more documentation. public static void supplyQuantities( int[] avgQty , int[] minQty , int[] maxQty ) throws SQLException { Connection conn = DriverManager.getConnection( "jdbc:default:connection" ) ; PreparedStatement getQty = conn.prepareStatement( "SELECT AVG(qty_on_hand), " + " MIN(qty_on_hand), " + " MAX(qty_on_hand) " + "FROM trafodion.invent.partloc" ) ; ResultSet rs = getQty.executeQuery() ; rs.next() ; avgQty[0] = rs.getInt( 1 ) ; minQty[0] = rs.getInt( 2 ) ; maxQty[0] = rs.getInt( 3 ) ; rs.close() ; conn.close() ; }
27.212121
97
0.64588
347fa39f1697b21799ecc50aab5016aa93299a7e
266
package com.fr.swift.cloud.service.info; import com.fr.swift.cloud.executor.type.ExecutorTaskType; /** * @author Heng.J * @date 2020/11/13 * @description 计划任务信息, 同planningInfo * @since swift-1.2.0 */ public interface TaskInfo { ExecutorTaskType type(); }
19
57
0.718045
00b2d59c15dc04d8fce740e8ea262c88f281736e
1,968
package net.collaud.fablab.manager.data; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; /** * * @author Gaetan Collaud <[email protected]> */ @Entity @Table(name = "t_payment") @Getter @Setter @NoArgsConstructor @ToString @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class PaymentEO extends AbstractDataEO<Long> implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "payment_id", nullable = false) private Long id; @Column(name = "total", nullable = false) private double total; @Column(name = "date_payement", nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date datePayment; @Column(name = "comment") private String comment; @JsonProperty("payment-user") @JoinColumn(name = "user_id", referencedColumnName = "user_id") @ManyToOne(fetch = FetchType.LAZY) private UserEO user; @JsonProperty("payement-cashier") @JoinColumn(name = "cashier_id", referencedColumnName = "user_id") @ManyToOne(fetch = FetchType.LAZY) private UserEO cashier; public PaymentEO(Date datePayement, double total, UserEO user, UserEO cashier, String comment) { this.id = 0l; this.datePayment = datePayement; this.total = total; this.user = user; this.cashier = cashier; this.comment = comment; } }
27.333333
97
0.780488
6fa04973853d96e0ac7732f64c51bf7ab92b72b8
666
package edu.usd.pheno2grn.reporting.dox4jUtilities; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; /** * Contains word document styling functionality. */ public class StylingUtilities { /** * Adds header3 text to a word document package. * * @param wordPackage Document which the header will be added to. * * @param headerText Text to be in the header. */ public static void addHeader3(WordprocessingMLPackage wordPackage, String headerText) { //adding the summary heading wordPackage.getMainDocumentPart().addStyledParagraphOfText("Heading3", headerText); } }
30.272727
92
0.696697
f10d93545e2dbe0fb15cadfcc3a6d8f4b774c57a
3,637
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.nemo.common.partitioner; import org.apache.nemo.common.KeyExtractor; import org.apache.nemo.common.exception.UnsupportedPartitionerException; import org.apache.nemo.common.ir.edge.executionproperty.KeyExtractorProperty; import org.apache.nemo.common.ir.edge.executionproperty.PartitionerProperty; import org.apache.nemo.common.ir.executionproperty.EdgeExecutionProperty; import org.apache.nemo.common.ir.executionproperty.ExecutionPropertyMap; import org.apache.nemo.common.ir.executionproperty.VertexExecutionProperty; import org.apache.nemo.common.ir.vertex.executionproperty.ParallelismProperty; import java.io.Serializable; /** * This interface represents the way of partitioning output data from a source task. * It takes an element and designates key of partition to write the element, * according to the number of destination tasks, the key of each element, etc. * * @param <K> the key type of the partition to write. */ public interface Partitioner<K extends Serializable> { /** * Divides the output data from a task into multiple blocks. * * @param element the output element from a source task. * @return the key of the partition in the block to write the element. */ K partition(Object element); /** * @param edgeProperties edge properties. * @param dstProperties vertex properties. * @return the partitioner. */ static Partitioner getPartitioner(final ExecutionPropertyMap<EdgeExecutionProperty> edgeProperties, final ExecutionPropertyMap<VertexExecutionProperty> dstProperties) { final PartitionerProperty.Type type = edgeProperties.get(PartitionerProperty.class).orElseThrow(IllegalStateException::new).left(); final Partitioner partitioner; switch (type) { case INTACT: partitioner = new IntactPartitioner(); break; case DEDICATED_KEY_PER_ELEMENT: partitioner = new DedicatedKeyPerElementPartitioner(); break; case HASH: final int numOfPartitions = edgeProperties .get(PartitionerProperty.class) .orElseThrow(IllegalStateException::new) .right(); final int actualNumOfPartitions = (numOfPartitions == PartitionerProperty.NUM_EQUAL_TO_DST_PARALLELISM) ? dstProperties.get(ParallelismProperty.class).orElseThrow(IllegalStateException::new) : numOfPartitions; final KeyExtractor keyExtractor = edgeProperties.get(KeyExtractorProperty.class) .orElseThrow(IllegalStateException::new); partitioner = new HashPartitioner(actualNumOfPartitions, keyExtractor); break; default: throw new UnsupportedPartitionerException( new Throwable("Partitioner " + type.toString() + " is not supported.")); } return partitioner; } }
42.788235
111
0.74237
f0a9f7098c3dbe2342b2dde851c5a0083ee6cbd2
379
package com.nolva.product.dao; import com.nolva.product.entity.CommentReplayEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 商品评价回复关系 * * @author Nolva * @email [email protected] * @date 2020-08-10 20:07:43 */ @Mapper public interface CommentReplayDao extends BaseMapper<CommentReplayEntity> { }
21.055556
75
0.773087
ba9ac6688ce0b66aedf75c7773cbbd4f187e90db
1,550
package com.osomapps.pt.programs; import com.fasterxml.jackson.annotation.JsonBackReference; import java.time.LocalDateTime; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; @AllArgsConstructor @NoArgsConstructor @Accessors(chain = true) @Getter @Setter @Entity @Table(name = "parse_workout_item_set", schema = "ptcore") @DynamicInsert @DynamicUpdate public class ParseWorkoutItemSet { @Id @SequenceGenerator( name = "ParseWorkoutItemSetIdSequence", sequenceName = "ptcore.parse_workout_item_set_id_seq", allocationSize = 1, initialValue = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ParseWorkoutItemSetIdSequence") Long id; LocalDateTime created; Integer repetitions; Boolean repetitions_to_failure; Float weight; Boolean bodyweight; Float time_in_min; Integer speed; Integer incline; Integer resistance; @ManyToOne @JoinColumn(name = "parse_workout_item_id") @JsonBackReference ParseWorkoutItem parseWorkoutItem; }
28.181818
100
0.776774
139cdcf05c1704498489fce4114886d2c1be14aa
3,820
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.openide.windows; import javax.swing.Icon; import org.openide.util.Lookup; /** * Settings of tool tip/icon for IO component (tab). * <p> * Client usage: * <pre> * // settings of IO tab icon, tooltip * InputOutput io = ...; * Icon icon = ...; * IOTab.setIcon(io, icon); * IOTab.setToolTipText(io, "text"); * </pre> * How to support {@link IOTab} in own {@link IOProvider} implementation: * <ul> * <li> {@link InputOutput} provided by {@link IOProvider} has to implement {@link org.openide.util.Lookup.Provider} * <li> Extend {@link IOTab} and implement its abstract methods * <li> Place instance of {@link IOTab} to {@link Lookup} provided by {@link InputOutput} * </ul> * @since 1.15 * @author Tomas Holy */ public abstract class IOTab { private static IOTab find(InputOutput io) { if (io instanceof Lookup.Provider) { Lookup.Provider p = (Lookup.Provider) io; return p.getLookup().lookup(IOTab.class); } return null; } /** * Gets current tab icon for specified IO * @param io IO to operate on * @return current tab icon or null if not supported */ public static Icon getIcon(InputOutput io) { IOTab iot = find(io); return iot != null ? iot.getIcon() : null; } /** * Sets icon to tab corresponding to specified IO * @param io IO to operate on * @param icon tab icon */ public static void setIcon(InputOutput io, Icon icon) { IOTab iot = find(io); if (iot != null) { iot.setIcon(icon); } } /** * Gets current tool tip text for specified IO * @param io IO to operate on * @return current tool tip text or null if not supported */ public static String getToolTipText(InputOutput io) { IOTab iot = find(io); return iot != null ? iot.getToolTipText() : null; } /** * Sets tool tip text to tab corresponding to specified IO * @param io IO to operate on * @param text new tool tip text */ public static void setToolTipText(InputOutput io, String text) { IOTab iot = find(io); if (iot != null) { iot.setToolTipText(text); } } /** * Checks whether this feature is supported for provided IO * @param io IO to check on * @return true if supported */ public static boolean isSupported(InputOutput io) { return find(io) != null; } /** * Gets current tab icon * @return current tab icon */ abstract protected Icon getIcon(); /** * Sets icon to tab * @param icon tab icon */ abstract protected void setIcon(Icon icon); /** * Gets current tool tip text * @return current tool tip text */ abstract protected String getToolTipText(); /** * Sets tool tip text to tab * @param text new tool tip text */ abstract protected void setToolTipText(String text); }
28.939394
118
0.631675
3ecd52162e9ef4825f3a27b9cbe5086da358e7e3
2,253
package com.queatz.snappy.team.actions; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.preference.PreferenceManager; import com.queatz.snappy.chat.ChatManager; import com.queatz.snappy.chat.ChatRoom; import com.queatz.snappy.shared.Config; import java.io.IOException; import java.io.InputStream; /** * Created by jacob on 9/18/17. * * @emit true on completion */ public class SendChatPhotoAction extends ActivityAction { private final ChatManager chatManager; private final ChatRoom topic; public SendChatPhotoAction(ChatManager chatManager) { this.chatManager = chatManager; this.topic = chatManager.getCurrentTopic(); } @Override protected void execute() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); me().getActivity().startActivityForResult(intent, Config.REQUEST_CODE_SEND_CHAT_PHOTO); getTeam().callbacks.set(Config.REQUEST_CODE_SEND_CHAT_PHOTO, new PreferenceManager.OnActivityResultListener() { @Override public boolean onActivityResult(int requestCode, int resultCode, Intent intent) { emit(resultCode == Activity.RESULT_OK); if(resultCode == Activity.RESULT_OK) { final Uri photo = intent.getData(); if (photo == null) { return false; } try { InputStream inputStream = getTeam().context.getContentResolver().openInputStream(photo); if (inputStream == null) { return false; } byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes, 0, inputStream.available()); inputStream.close(); chatManager.sendPhoto(topic.getName(), bytes); } catch (IOException e) { e.printStackTrace(); return false; } } return false; } }); } }
31.732394
119
0.577452
cf30ad3a949d4e1a398b82772e56697921cf5781
252
package io.hektor.core.internal.messages; /** * Internal message to indicate that an actor should be started. * * @author [email protected] */ public class Start { public static final Start MSG = new Start(); private Start() {} }
18
64
0.694444
d3666ea7b53fe8747e43a2a0d07d7d3dd5d665ae
2,164
/* * Copyright 2019 Arcus Project. * * 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 arcus.cornea.utils; import com.iris.client.ClientEvent; import com.iris.client.event.ClientFuture; import com.iris.client.event.Listener; import com.iris.client.model.DeviceModel; import com.iris.client.util.Result; import java.util.TimerTask; public class DebouncedRequest extends TimerTask { private DeviceModel model; private Listener<Throwable> onError; private Listener<ClientEvent> onSuccess; private Listener<Result<ClientEvent>> onCompletion; private DebounceCallback callback; public DebouncedRequest(DeviceModel model) { this.model = model; } public void setCallbackHandler(DebounceCallback callback) { this.callback = callback; } public void setOnError(Listener<Throwable> onError) { this.onError = onError; } public void setOnSuccess(Listener<ClientEvent> onSuccess) { this.onSuccess = onSuccess; } public void setOnCompletion(Listener<Result<ClientEvent>> onCompletion) { this.onCompletion = onCompletion; } @Override public void run() { ClientFuture<ClientEvent> request = model.commit(); if(callback != null) { callback.commitEvent(); } if (onError != null) { request.onFailure(onError); } if (onSuccess != null) { request.onSuccess(onSuccess); } if (onCompletion != null) { request.onCompletion(onCompletion); } } public interface DebounceCallback { void commitEvent(); } }
29.243243
77
0.679298
7202a1ec637457b7fbeaa23eeae3c83ba2b33743
2,388
/******************************************************************************* * Copyright 2014 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. * * 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 gov.nasa.arc.spife.ui.timeline.action; import gov.nasa.arc.spife.ui.timeline.Timeline; import gov.nasa.arc.spife.ui.timeline.model.ZoomManager; import java.util.WeakHashMap; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.gef.editparts.ZoomListener; public abstract class ZoomTimelineCommandHandler extends AbstractTimelineCommandHandler implements ZoomListener { protected WeakHashMap<ZoomManager, ZoomListener> zoomManagerToZoomListenerMap = new WeakHashMap<ZoomManager, ZoomListener>(); public static ZoomManager getZoomManager() { ZoomManager zoomManager = null; Timeline<?> timeline = getTimeline(); if (timeline != null) { zoomManager = timeline.getZoomManager(); } return zoomManager; } @Override public void dispose() { Timeline<?> timeline = getTimeline(); if (timeline != null) { ZoomManager zoomManager = timeline.getZoomManager(); if (zoomManager != null) { zoomManager.removeZoomListener(this); zoomManagerToZoomListenerMap.remove(zoomManager); } } super.dispose(); } @Override public void zoomChanged(double zoom) { this.updateEnablement(); } /** * Calculate the center of the current page so that zoom out stays centered * (used for zoom in and zoom out, but not for sweep zoom) * @return the center of the current page */ protected int getScreenPositionForZoom(ExecutionEvent event) { Timeline<?> timeline = getTimeline(event); return timeline.getCurrentScreenCenterLocation(); } }
33.633803
126
0.703936
954bc4941c5c1861e61b571cc3ec1341321cb5a9
3,272
package vn.iadd.excel; import java.io.Serializable; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; import java.util.Map; import vn.iadd.util.ObjectUtil; /** * BaseExcelModel * * @author DaiNV * @since 20180529 */ public abstract class BaseExcelModel implements IExcelModel, Serializable { /** * Serial version */ private static final long serialVersionUID = 1L; /** * Map column name - index */ private Map<String, Integer> mapColumnNameToIndex = new HashMap<>(); /** * Map index - column name */ private Map<Integer, String> mapIndexToColumnName = new HashMap<>(); /** * Map property name - field */ private final Map<String, Field> mapFields = new HashMap<>(); /** * Default constructor */ public BaseExcelModel() { initFields(); mapColumnWithIndex(); } /** * Constructor with parameter * @param fields Map<String, Field> */ public BaseExcelModel(Map<String, Field> fields) { if (fields != null && !fields.isEmpty()) { //mapFields.clear(); this.mapFields.putAll(fields); } mapColumnWithIndex(); } public boolean containColumn(String colName) { return mapColumnNameToIndex.containsKey(colName); } /** * Add column name with index in excel file * @param colName String * @param index int */ public void addColumnIndex(String colName, int index) { Integer i = Integer.valueOf(index); mapColumnNameToIndex.put(colName, i); mapIndexToColumnName.put(i, colName); } public int getColumnIndex(String colName) { return mapColumnNameToIndex.get(colName).intValue(); } /** * Get map fields using reflection. */ private void initFields() { initFields(ObjectUtil.getFields(this)); } /** * Get map fields using another object template. * @param fields */ private void initFields(List<Field> fields) { if (fields == null || fields.isEmpty()) { return; } mapFields.clear(); for (Field f : fields) { boolean isFinal = false; isFinal = isFinal || java.lang.reflect.Modifier.isFinal(f.getModifiers()); mapFields.put(f.getName(), f); if (isFinal) { continue; } f.setAccessible(true); } } @Override public Map<String, Field> getMapFields() { return mapFields; } public Map<String, Integer> getMapColumnNameToIndex() { return mapColumnNameToIndex; } public void setMapColumnNameToIndex(Map<String, Integer> mapColumnNameToIndex) { this.mapColumnNameToIndex = mapColumnNameToIndex; } public void set(String propertyName, Object value) { if (!mapFields.containsKey(propertyName)) { return; } try { mapFields.get(propertyName).set(this, value); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } } public Object get(String propertyName) { if (!mapFields.containsKey(propertyName)) { return null; } return mapFields.get(propertyName); } @Override public void setExcelValue(Object[] arr) { if (arr == null || arr.length == 0) { return; } for (int i = 0; i < arr.length; i++) { Integer col = Integer.valueOf(i + 1); Object value = arr[i]; if (!mapIndexToColumnName.containsKey(col)) { continue; } String colName = mapIndexToColumnName.get(col); this.set(colName, value); } } }
21.385621
81
0.682152
818445bc73b78240735e444aca29d452c5e1b395
3,505
package balance; public class BalanceCheckerTester { public static void main(String[] args) { System.out.println("CS 1723 Lab 5: written by Ivan Capistran"); BalanceChecker test1=new BalanceChecker("(a+(b*c3)+d)"); BalanceChecker test2=new BalanceChecker("(a+(b+dog+cat)"); BalanceChecker test3=new BalanceChecker("a+b+(c+d"); BalanceChecker test4=new BalanceChecker("a+b+(c+d))+e"); BalanceChecker test5=new BalanceChecker("(((a+b+(c+d)+e"); BalanceChecker test6=new BalanceChecker("()()(())"); BalanceCheckerAdvance test7 = new BalanceCheckerAdvance("{}[a+(b+c)]{d+e}"); BalanceCheckerAdvance test8 = new BalanceCheckerAdvance("a+{[a+b}]"); BalanceCheckerAdvance test9 = new BalanceCheckerAdvance("a+[b+c("); BalanceCheckerAdvance test10 = new BalanceCheckerAdvance("a+d+(c-d)]"); BalanceCheckerAdvance test11 = new BalanceCheckerAdvance("(f+gh+s+[g+g+g]"); BalanceCheckerAdvance test12 = new BalanceCheckerAdvance("a+b+c[d+s+{d+a+b]"); BalanceCheckerAdvance test13 = new BalanceCheckerAdvance("{f+i+j)+gj+ab+{}+gh)"); System.out.println(test1.toString()); System.out.println(test2.toString()); System.out.println(test3.toString()); System.out.println(test4.toString()); System.out.println(test5.toString()); System.out.println(test6.toString()); System.out.println("\n-----Checking Balanced and Index of Delimiter------\n"); System.out.println(test1.toString()+", Balanced : "+test1.isBalanced()+", Position : "+test1.getPosition()); System.out.println(test2.toString()+", Balanced : "+test2.isBalanced()+", Position : "+test2.getPosition()); System.out.println(test3.toString()+", Balanced : "+test3.isBalanced()+", Position : "+test3.getPosition()); System.out.println(test4.toString()+", Balanced : "+test4.isBalanced()+", Position : "+test4.getPosition()); System.out.println(test5.toString()+", Balanced : "+test5.isBalanced()+", Position : "+test5.getPosition()); System.out.println(test6.toString()+", Balanced : "+test6.isBalanced()+", Position : "+test6.getPosition()); System.out.println(); System.out.println("-----------------------BalanceCheckerAdvance----------------------"); System.out.println(test7.toString()); System.out.println(test8.toString()); System.out.println(test9.toString()); System.out.println(test10.toString()); System.out.println(test11.toString()); System.out.println(test12.toString()); System.out.println(test13.toString()); System.out.println("\n-----Checking Balanced and Index of Delimiter------\n"); System.out.println(test7.toString()+", Balanced : "+test7.isBalanced()+", Position : "+test7.getPosition()); System.out.println(test8.toString()+", Balanced : "+test8.isBalanced()+", Position : "+test8.getPosition()); System.out.println(test9.toString()+", Balanced : "+test9.isBalanced()+", Position : "+test9.getPosition()); System.out.println(test10.toString()+", Balanced : "+test10.isBalanced()+", Position : "+test10.getPosition()); System.out.println(test11.toString()+", Balanced : "+test11.isBalanced()+", Position : "+test11.getPosition()); System.out.println(test12.toString()+", Balanced : "+test12.isBalanced()+", Position : "+test12.getPosition()); System.out.println(test13.toString()+", Balanced : "+test13.isBalanced()+", Position : "+test13.getPosition()); } }
53.923077
116
0.65592
143cadc81cbbde4ac6fd155892a8ccec5d9a5112
834
package org.kilocraft.essentials.api.util.schedule; import org.kilocraft.essentials.api.user.OnlineUser; public class SinglePlayerScheduler extends StandStillScheduler { private final ScheduledExecution scheduled; public SinglePlayerScheduler(OnlineUser sender, int blocks, int countdown, ScheduledExecution scheduled) { super(sender, blocks, countdown); this.scheduled = scheduled; this.tick(); } @Override public boolean onTick() { return super.onTick(); } @Override void sendAbortMessage() { this.player.sendLangMessage("teleport.abort"); } @Override public void onFinish() { if (this.moved()) { this.sendAbortMessage(); } else { if (this.player.isOnline()) this.scheduled.apply(); } } }
24.529412
110
0.64988
e70d91f123e77f5bd7b844c1b210ad5360f885c8
2,321
package app.components; import app.app; import app.screens.Level; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import java.util.Random; /** * @author Samantha Whitt * used for creating shooting stars on the screen * example: create a shooting star to eventually fall down the scene */ public class ShootingStar { ImageView myShootingStar; /** * constructor for ShootingStar that creates a new shooting star * example: ShootingStar newShootingStar = new ShootingStar(); */ public ShootingStar() { Image shootingStar_img = new Image(this.getClass().getClassLoader().getResourceAsStream(app.STAR_IMAGE)); myShootingStar = new ImageView(shootingStar_img); } /** * used for adding to scene * @return shootingStar's ImageView */ public ImageView getImage() { return myShootingStar; } /** * @return shootingStar's current x location */ public double getX() { return myShootingStar.getX(); } /** * sets shooting star's x location * @param location */ public void setX(double location) { myShootingStar.setX(location); } /** * @return shootingStar's current y location */ public double getY() { return myShootingStar.getY(); } /** * sets shooting star's y location * @param location */ public void setY(double location) { myShootingStar.setY(location); } /** * @return myShootingStar's ImageView width */ public double getWidth() { return myShootingStar.getBoundsInLocal().getWidth(); } /** * @return myShootingStar's ImageView height */ public double getHeight() { return myShootingStar.getBoundsInLocal().getHeight(); } /** * places shooting stars from any of three places (random) and adds to scene * @return */ public static void shootStar(ShootingStar newStar) { int randomStarPos = new Random().nextInt(3); if (randomStarPos == 0) { newStar.setX(100); } else if (randomStarPos == 1) { newStar.setX(200); } else if (randomStarPos == 2) { newStar.setX(300); } Level.addToRoot(newStar.getImage()); } }
24.177083
113
0.618268
0c67a97905d52a1104394594747ec0bfcff5c3a0
1,492
package org.shahin.nazarov.edd.rabbitmq.producer; import com.fasterxml.jackson.databind.ObjectMapper; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import org.shahin.nazarov.edd.rabbitmq.domain.JavaObject; import org.shahin.nazarov.edd.rabbitmq.util.Constants; import java.io.IOException; import java.util.concurrent.TimeoutException; public class ProducerOne { public static void main(String[] args) { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(Constants.hostname); try (Connection connection = factory.newConnection();Channel channel = connection.createChannel()) { ObjectMapper mapper = new ObjectMapper(); channel.queueDeclare(Constants.queueOne, false, false, false, null); for(int i = 0; i < 1000; i++){ JavaObject javaObject = new JavaObject(); javaObject.setData("Test"); javaObject.setIndex(i); channel.basicPublish("", Constants.queueOne, null, mapper.writeValueAsBytes(javaObject)); System.out.println(" [x] Sent '" + javaObject.toString() + "'"); Thread.sleep(100); } } catch (TimeoutException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
37.3
108
0.649464
d22df2f72b295894f1af7ed125d03856a64667d5
3,162
/* * Copyright 2017 StreamSets Inc. * * 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.streamsets.pipeline.api.el; import com.streamsets.pipeline.api.impl.Utils; /** * An <code>ELEval</code> instance evaluates Java EL expressions. * <p/> * In the context of a specific stage configuration, the <code>ELEval</code> uses the EL functions and EL constants * defined in the configuration. * * @see com.streamsets.pipeline.api.Stage.ELContext */ public abstract class ELEval { private static final ThreadLocal<ELVars> VARIABLES_IN_SCOPE_TL = new ThreadLocal<>(); /** * Returns the stage configuration associated with the <code>ELEval</code> instance. * * @return the stage configuration associated with the <code>ELEval</code> instance. */ public abstract String getConfigName(); /** * Returns an empty <code>ELVars</code> instance. * * @return an empty <code>ELVars</code> instance. */ public abstract ELVars createVariables(); /** * Evaluates an EL. * <p/> * <b>IMPORTANT:</b> This is method is used by the implementation. It is not available for stages. * * @param vars the variables to be available for the evaluation. * @param el the EL string to evaluate. * @param returnType the class the EL evaluates to. * @return the evaluated EL as an instance of the specified return type. * @throws ELEvalException if the EL could not be evaluated. */ protected abstract <T> T evaluate(ELVars vars, String el, Class<T> returnType) throws ELEvalException; /** * Evaluates an EL. * * @param vars the variables to be available for the evaluation. * @param el the EL string to evaluate. * @param returnType the class the EL evaluates to. * @return the evaluated EL as an instance of the specified return type. * @throws ELEvalException if the EL could not be evaluated. */ public <T> T eval(ELVars vars, String el, Class<T> returnType) throws ELEvalException { Utils.checkNotNull(vars, "vars"); Utils.checkNotNull(el, "expression"); Utils.checkNotNull(returnType, "returnType"); VARIABLES_IN_SCOPE_TL.set(vars); try { return evaluate(vars, el, returnType); } finally { VARIABLES_IN_SCOPE_TL.set(null); } } /** * Returns the <code>ELVars</code> in scope while an EL is being evaluated. * <p/> * EL functions should use this method to get hold of the <code>ELVars</code> used to invoke the {@link #eval} method. * @return the <code>ELVars</code> in scope while an EL is being evaluated. */ public static ELVars getVariablesInScope() { return VARIABLES_IN_SCOPE_TL.get(); } }
35.52809
120
0.70525
b60f22c6d923f6c306324a2b18be965e42c92fa4
14,610
/* * Copyright (C) 2004-2016 L2J DataPack * * This file is part of L2J DataPack. * * L2J DataPack 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. * * L2J DataPack 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 quests.Q00373_SupplierOfReagents; import java.util.HashMap; import quests.Q00235_MimirsElixir.Q00235_MimirsElixir; import com.l2jserver.gameserver.enums.audio.Sound; import com.l2jserver.gameserver.model.actor.L2Npc; import com.l2jserver.gameserver.model.actor.instance.L2PcInstance; import com.l2jserver.gameserver.model.holders.ItemHolder; import com.l2jserver.gameserver.model.quest.Quest; import com.l2jserver.gameserver.model.quest.QuestState; /** * Supplier of Reagents (373) * @author Joxit */ public final class Q00373_SupplierOfReagents extends Quest { // NPCs private static final int WESLEY = 30166; private static final int ALCHEMIST_MIXING_URN = 31149; // Mobs private static final int HALLATE_MAID = 20822; private static final int HALLATE_GUARDIAN = 21061; private static final int HAMES_ORC_SHAMAN = 21115; private static final int LAVA_WYRM = 21111; private static final int CRENDION = 20813; private static final int PLATINUM_TRIBE_SHAMAN = 20828; private static final int PLATINUM_GUARDIAN_SHAMAN = 21066; // Items private static final int REAGENT_POUNCH1 = 6007; private static final int REAGENT_POUNCH2 = 6008; private static final int REAGENT_POUNCH3 = 6009; private static final int REAGENT_BOX = 6010; private static final int WYRM_BLOOD = 6011; private static final int LAVA_STONE = 6012; private static final int MOONSTONE_SHARD = 6013; private static final int ROTTEN_BONE = 6014; private static final int DEMONS_BLOOD = 6015; private static final int INFERNIUM_ORE = 6016; private static final int BLOOD_ROOT = 6017; private static final int VOLCANIC_ASH = 6018; private static final int QUICKSILVER = 6019; private static final int SULFUR = 6020; private static final int DRACOPLASM = 6021; private static final int MAGMA_DUST = 6022; private static final int MOON_DUST = 6023; private static final int NECROPLASM = 6024; private static final int DEMONPLASM = 6025; private static final int INFERNO_DUST = 6026; private static final int DRACONIC_ESSENCE = 6027; private static final int FIRE_ESSENCE = 6028; private static final int LUNARGENT = 6029; private static final int MIDNIGHT_OIL = 6030; private static final int DEMONIC_ESSENCE = 6031; private static final int ABYSS_OIL = 6032; private static final int HELLFIRE_OIL = 6033; private static final int NIGHTMARE_OIL = 6034; private static final int PURE_SILVER = 6320; private static final int MIXING_MANUAL = 6317; private static final int WESLEYS_MIXING_STONE = 5904; // Misc private static final int MIN_LVL = 57; private static final HashMap<String, Integer> HTML_TO_MEMO_STATE = new HashMap<>(20); private static final HashMap<Integer, ItemHolder> MEMO_STATE_TO_ITEM = new HashMap<>(20); private static final HashMap<Integer, Entry> MEMO_STATE_TO_REWARD = new HashMap<>(15); static { // List of ingredients to mix HTML_TO_MEMO_STATE.put("31149-03.html", 11); HTML_TO_MEMO_STATE.put("31149-04.html", 12); HTML_TO_MEMO_STATE.put("31149-05.html", 13); HTML_TO_MEMO_STATE.put("31149-06.html", 14); HTML_TO_MEMO_STATE.put("31149-07.html", 15); HTML_TO_MEMO_STATE.put("31149-08.html", 16); HTML_TO_MEMO_STATE.put("31149-09.html", 17); HTML_TO_MEMO_STATE.put("31149-10.html", 18); HTML_TO_MEMO_STATE.put("31149-11.html", 19); HTML_TO_MEMO_STATE.put("31149-12.html", 20); HTML_TO_MEMO_STATE.put("31149-13.html", 21); HTML_TO_MEMO_STATE.put("31149-14.html", 22); HTML_TO_MEMO_STATE.put("31149-15.html", 23); HTML_TO_MEMO_STATE.put("31149-16.html", 24); MEMO_STATE_TO_ITEM.put(11, new ItemHolder(WYRM_BLOOD, 10)); MEMO_STATE_TO_ITEM.put(12, new ItemHolder(LAVA_STONE, 10)); MEMO_STATE_TO_ITEM.put(13, new ItemHolder(MOONSTONE_SHARD, 10)); MEMO_STATE_TO_ITEM.put(14, new ItemHolder(ROTTEN_BONE, 10)); MEMO_STATE_TO_ITEM.put(15, new ItemHolder(DEMONS_BLOOD, 10)); MEMO_STATE_TO_ITEM.put(16, new ItemHolder(INFERNIUM_ORE, 10)); MEMO_STATE_TO_ITEM.put(17, new ItemHolder(DRACOPLASM, 10)); MEMO_STATE_TO_ITEM.put(18, new ItemHolder(MAGMA_DUST, 10)); MEMO_STATE_TO_ITEM.put(19, new ItemHolder(MOON_DUST, 10)); MEMO_STATE_TO_ITEM.put(20, new ItemHolder(NECROPLASM, 10)); MEMO_STATE_TO_ITEM.put(21, new ItemHolder(DEMONPLASM, 10)); MEMO_STATE_TO_ITEM.put(22, new ItemHolder(INFERNO_DUST, 10)); MEMO_STATE_TO_ITEM.put(23, new ItemHolder(FIRE_ESSENCE, 1)); MEMO_STATE_TO_ITEM.put(24, new ItemHolder(LUNARGENT, 1)); // List of catalysts to mix HTML_TO_MEMO_STATE.put("31149-19.html", 1100); HTML_TO_MEMO_STATE.put("31149-20.html", 1200); HTML_TO_MEMO_STATE.put("31149-21.html", 1300); HTML_TO_MEMO_STATE.put("31149-22.html", 1400); HTML_TO_MEMO_STATE.put("31149-23.html", 1500); HTML_TO_MEMO_STATE.put("31149-24.html", 1600); MEMO_STATE_TO_ITEM.put(1100, new ItemHolder(BLOOD_ROOT, 1)); MEMO_STATE_TO_ITEM.put(1200, new ItemHolder(VOLCANIC_ASH, 1)); MEMO_STATE_TO_ITEM.put(1300, new ItemHolder(QUICKSILVER, 1)); MEMO_STATE_TO_ITEM.put(1400, new ItemHolder(SULFUR, 1)); MEMO_STATE_TO_ITEM.put(1500, new ItemHolder(DEMONIC_ESSENCE, 1)); MEMO_STATE_TO_ITEM.put(1600, new ItemHolder(MIDNIGHT_OIL, 1)); // The reward is the sum of ingredient and catalyst MEMO_STATE_TO_REWARD.put(1111, new Entry(DRACOPLASM, "31149-30.html")); MEMO_STATE_TO_REWARD.put(1212, new Entry(MAGMA_DUST, "31149-31.html")); MEMO_STATE_TO_REWARD.put(1213, new Entry(MOON_DUST, "31149-32.html")); MEMO_STATE_TO_REWARD.put(1114, new Entry(NECROPLASM, "31149-33.html")); MEMO_STATE_TO_REWARD.put(1115, new Entry(DEMONPLASM, "31149-34.html")); MEMO_STATE_TO_REWARD.put(1216, new Entry(INFERNO_DUST, "31149-35.html")); MEMO_STATE_TO_REWARD.put(1317, new Entry(DRACONIC_ESSENCE, "31149-36.html")); MEMO_STATE_TO_REWARD.put(1418, new Entry(FIRE_ESSENCE, "31149-37.html")); MEMO_STATE_TO_REWARD.put(1319, new Entry(LUNARGENT, "31149-38.html")); MEMO_STATE_TO_REWARD.put(1320, new Entry(MIDNIGHT_OIL, "31149-39.html")); MEMO_STATE_TO_REWARD.put(1421, new Entry(DEMONIC_ESSENCE, "31149-40.html")); MEMO_STATE_TO_REWARD.put(1422, new Entry(ABYSS_OIL, "31149-41.html")); MEMO_STATE_TO_REWARD.put(1523, new Entry(HELLFIRE_OIL, "31149-42.html")); MEMO_STATE_TO_REWARD.put(1624, new Entry(NIGHTMARE_OIL, "31149-43.html")); MEMO_STATE_TO_REWARD.put(1324, new Entry(PURE_SILVER, "31149-46.html")); } public Q00373_SupplierOfReagents() { super(373, Q00373_SupplierOfReagents.class.getSimpleName(), "Supplier of Reagents"); addStartNpc(WESLEY); addKillId(HALLATE_GUARDIAN, HALLATE_MAID, HAMES_ORC_SHAMAN, LAVA_WYRM, CRENDION, PLATINUM_GUARDIAN_SHAMAN, PLATINUM_TRIBE_SHAMAN); addTalkId(WESLEY, ALCHEMIST_MIXING_URN); registerQuestItems(WESLEYS_MIXING_STONE, MIXING_MANUAL); } @Override public String onAdvEvent(String event, L2Npc npc, L2PcInstance player) { final QuestState qs = getQuestState(player, false); String htmltext = null; if (qs == null) { return htmltext; } switch (event) { case "30166-03.htm": case "30166-06.html": case "30166-04a.html": case "30166-04b.html": case "30166-04c.html": case "30166-04d.html": case "31149-18.html": { htmltext = event; break; } case "30166-04.html": { if ((player.getLevel() >= MIN_LVL) && qs.isCreated()) { giveItems(player, WESLEYS_MIXING_STONE, 1); giveItems(player, MIXING_MANUAL, 1); qs.startQuest(); htmltext = event; } break; } case "30166-07.html": { qs.exitQuest(true, true); htmltext = event; break; } case "31149-02.html": { qs.setMemoState(0); qs.setMemoStateEx(1, 0); htmltext = event; break; } case "31149-03.html": case "31149-04.html": case "31149-05.html": case "31149-06.html": case "31149-07.html": case "31149-08.html": case "31149-09.html": case "31149-10.html": case "31149-11.html": case "31149-12.html": case "31149-13.html": case "31149-14.html": case "31149-15.html": case "31149-16.html": case "31149-19.html": case "31149-20.html": case "31149-21.html": case "31149-22.html": case "31149-23.html": case "31149-24.html": { final int memoState = HTML_TO_MEMO_STATE.get(event); if (hasItem(player, MEMO_STATE_TO_ITEM.get(memoState))) { // If the player has the chosen item (ingredient or catalyst), we save it (for the catalyst or the reward) qs.setMemoState(qs.getMemoState() + memoState); htmltext = event; playSound(player, Sound.SKILLSOUND_LIQUID_MIX); } else { // If the player has not the chosen catalyst, we take the ingredient previously saved (if not null) takeItem(player, MEMO_STATE_TO_ITEM.get(qs.getMemoState())); if (event.equals("31149-19.html")) { htmltext = "31149-25.html"; } else { htmltext = "31149-17.html"; } } break; } case "31149-26.html": { if (qs.isMemoState(1324)) { htmltext = "31149-26a.html"; } else { htmltext = event; } break; } case "31149-27.html": { qs.setMemoStateEx(1, 1); // Temperature Salamander htmltext = event; break; } case "31149-28a.html": { if (getRandom(100) < 33) { qs.setMemoStateEx(1, 3); // Temperature Ifrit } else { qs.setMemoStateEx(1, 0); } htmltext = event; break; } case "31149-29a.html": { if (getRandom(100) < 20) { qs.setMemoStateEx(1, 5); // Temperature Phoenix } else { qs.setMemoStateEx(1, 0); } htmltext = event; break; } case "mixitems": { final int memoState = qs.getMemoState(); final ItemHolder item1 = MEMO_STATE_TO_ITEM.get(memoState % 100); final ItemHolder item2 = MEMO_STATE_TO_ITEM.get((memoState / 100) * 100); final Entry reward = MEMO_STATE_TO_REWARD.get(memoState); final QuestState q235 = player.getQuestState(Q00235_MimirsElixir.class.getSimpleName()); if ((reward == null) || qs.isMemoStateEx(1, 0)) { takeItem(player, item1); takeItem(player, item2); htmltext = (reward == null) ? "31149-44.html" : "31149-45.html"; playSound(player, Sound.SKILLSOUND_LIQUID_FAIL); } else if ((memoState != 1324) || ((memoState == 1324) && (q235 != null) && q235.isStarted() && !hasQuestItems(player, reward.getItem()))) { if ((item1 != null) && (item2 != null) && hasItem(player, item1) && hasItem(player, item2)) { takeItem(player, item1); takeItem(player, item2); giveItems(player, reward.getItem(), (memoState == 1324) ? 1 : qs.getMemoStateEx(1)); qs.setMemoState(0); qs.setMemoStateEx(1, 0); htmltext = reward.getHtml(); playSound(player, Sound.SKILLSOUND_LIQUID_SUCCESS); } else { htmltext = "31149-44.html"; playSound(player, Sound.SKILLSOUND_LIQUID_FAIL); } } else { htmltext = "31149-44.html"; } break; } } return htmltext; } @Override public String onKill(L2Npc npc, L2PcInstance killer, boolean isSummon) { final QuestState qs = getRandomPartyMemberState(killer, -1, 3, npc); if (qs != null) { switch (npc.getId()) { case HALLATE_GUARDIAN: { final int chance = getRandom(1000); if (chance < 766) { giveItemRandomly(qs.getPlayer(), npc, DEMONS_BLOOD, 3, 0, 1, true); } else if (chance < 876) { giveItemRandomly(qs.getPlayer(), npc, MOONSTONE_SHARD, 1, 0, 1, true); } break; } case HALLATE_MAID: { final int chance = getRandom(100); if (chance < 45) { giveItemRandomly(qs.getPlayer(), npc, REAGENT_POUNCH1, 1, 0, 1, true); } else if (chance < 65) { giveItemRandomly(qs.getPlayer(), npc, VOLCANIC_ASH, 1, 0, 1, true); } break; } case HAMES_ORC_SHAMAN: { if (getRandom(1000) < 616) { giveItemRandomly(qs.getPlayer(), npc, REAGENT_POUNCH3, 1, 0, 1, true); } break; } case LAVA_WYRM: { final int chance = getRandom(1000); if (chance < 666) { giveItemRandomly(qs.getPlayer(), npc, WYRM_BLOOD, 1, 0, 1, true); } else if (chance < 989) { giveItemRandomly(qs.getPlayer(), npc, LAVA_STONE, 1, 0, 1, true); } break; } case CRENDION: { if (getRandom(1000) < 618) { giveItemRandomly(qs.getPlayer(), npc, ROTTEN_BONE, 1, 0, 1, true); } else { giveItemRandomly(qs.getPlayer(), npc, QUICKSILVER, 1, 0, 1, true); } break; } case PLATINUM_GUARDIAN_SHAMAN: { if (getRandom(1000) < 444) { giveItemRandomly(qs.getPlayer(), npc, REAGENT_BOX, 1, 0, 1, true); } break; } case PLATINUM_TRIBE_SHAMAN: { if (getRandom(1000) < 658) { giveItemRandomly(qs.getPlayer(), npc, REAGENT_POUNCH2, 1, 0, 1, true); } else { giveItemRandomly(qs.getPlayer(), npc, QUICKSILVER, 2, 0, 1, true); } break; } } } return super.onKill(npc, killer, isSummon); } @Override public String onTalk(L2Npc npc, L2PcInstance talker) { final QuestState qs = getQuestState(talker, true); String htmltext = getNoQuestMsg(talker); if (qs.isCreated()) { if (talker.getLevel() < MIN_LVL) { htmltext = "30166-01.html"; } else { htmltext = "30166-02.htm"; } } else if (qs.isStarted()) { if (npc.getId() == WESLEY) { htmltext = "30166-05.html"; } else { htmltext = "31149-01.html"; } } return htmltext; } private static final class Entry { private final int item; private final String html; public Entry(int item, String html) { this.item = item; this.html = html; } public int getItem() { return item; } public String getHtml() { return html; } } }
30.311203
140
0.67796
ace9b286cbaaf84ceb2608a6b7acd6c046a51198
3,611
package com.qiniu.process.qiniu; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.qiniu.common.Constants; import com.qiniu.common.QiniuException; import com.qiniu.http.Client; import com.qiniu.http.Response; import com.qiniu.storage.Configuration; import com.qiniu.util.Auth; import com.qiniu.util.Json; import java.util.HashMap; import java.util.Map; public class CdnHelper { private final Auth auth; private final Client client; private static String refreshUrl = "http://fusion.qiniuapi.com/v2/tune/refresh"; private static String prefetchUrl = "http://fusion.qiniuapi.com/v2/tune/prefetch"; private static String refreshQueryUrl = "http://fusion.qiniuapi.com/v2/tune/refresh/list"; private static String prefetchQueryUrl = "http://fusion.qiniuapi.com/v2/tune/prefetch/list"; public CdnHelper(Auth auth, Configuration configuration) { this.auth = auth; if (configuration == null) { this.client = new Client(); } else { this.client = new Client(configuration.clone()); if (configuration.useHttpsDomains) { refreshUrl = refreshUrl.replace("http://", "https://"); prefetchUrl = prefetchUrl.replace("http://", "https://"); refreshQueryUrl = refreshQueryUrl.replace("http://", "https://"); prefetchQueryUrl = prefetchQueryUrl.replace("http://", "https://"); } } } public Response refresh(String[] urls, String[] dirs) throws QiniuException { Map<String, String[]> req = new HashMap<>(); if (urls != null) req.put("urls", urls); if (dirs != null) req.put("dirs", dirs); return UOperationForUrls(refreshUrl, req); } public Response queryRefresh(String[] urls) throws QiniuException { Map<String, String[]> req = new HashMap<>(); req.put("urls", urls); return UOperationForUrls(refreshQueryUrl, req); } public Response queryRefresh(JsonArray urls, int pageNo, int pageSize, String startTime, String endTime) throws QiniuException { JsonObject req = new JsonObject(); req.add("urls", urls); req.addProperty("pageNo", pageNo); req.addProperty("pageSize", pageSize); req.addProperty("startTime", startTime); req.addProperty("endTime", endTime); return UOperationForUrls(refreshQueryUrl, req); } public Response prefetch(String[] urls) throws QiniuException { Map<String, String[]> req = new HashMap<>(); req.put("urls", urls); return UOperationForUrls(prefetchUrl, req); } public Response queryPrefetch(String[] urls) throws QiniuException { Map<String, String[]> req = new HashMap<>(); req.put("urls", urls); return UOperationForUrls(prefetchQueryUrl, req); } public Response queryPrefetch(JsonArray urls, int pageNo, int pageSize, String startTime, String endTime) throws QiniuException { JsonObject req = new JsonObject(); req.add("urls", urls); req.addProperty("pageNo", pageNo); req.addProperty("pageSize", pageSize); req.addProperty("startTime", startTime); req.addProperty("endTime", endTime); return UOperationForUrls(prefetchQueryUrl, req); } private Response UOperationForUrls(String apiUrl, Object req) throws QiniuException { byte[] body = Json.encode(req).getBytes(Constants.UTF_8); return client.post(apiUrl, body, auth.authorizationV2(apiUrl, "POST", body, Client.JsonMime), Client.JsonMime); } }
40.122222
133
0.660759
26372c1fbcef2844f075e17c18613a235d330b41
3,045
package org.jfrog.teamcity.server.project.maven; import jetbrains.buildServer.controllers.ActionErrors; import jetbrains.buildServer.serverSide.ProjectManager; import jetbrains.buildServer.serverSide.SBuildServer; import org.apache.commons.lang3.StringUtils; import org.jfrog.teamcity.common.ReleaseManagementParameterKeys; import org.jfrog.teamcity.server.project.BaseReleaseManagementController; import javax.servlet.http.HttpServletRequest; import java.util.Map; /** * Schedules staged Maven build based on the release build parameters from the {@link MavenReleaseManagementTab}. * * @author Noam Y. Tenne */ public class MavenReleaseManagementController extends BaseReleaseManagementController { public MavenReleaseManagementController(ProjectManager projectManager, SBuildServer server) { super(projectManager, server); } @Override protected void handleVersioning(HttpServletRequest request, Map<String, String> customParameters, ActionErrors errors) { boolean useGlobalVersion = Boolean.valueOf(request.getParameter(ReleaseManagementParameterKeys.USE_GLOBAL_VERSION)); boolean usePerModuleVersion = Boolean.valueOf(request.getParameter(ReleaseManagementParameterKeys.USE_PER_MODULE_VERSION)); boolean noVersionChange = Boolean.valueOf(request.getParameter(ReleaseManagementParameterKeys.NO_VERSION_CHANGE)); if (useGlobalVersion) { handleGlobalVersion(request, customParameters, errors); } else if (usePerModuleVersion) { handlePerModuleVersion(request, customParameters, errors); } else if (noVersionChange) { customParameters.put(ReleaseManagementParameterKeys.NO_VERSION_CHANGE, Boolean.TRUE.toString()); } else { errors.addError("versionChangeError", "Version change policy selection is mandatory."); } } private void handleGlobalVersion(HttpServletRequest request, Map<String, String> customParameters, ActionErrors errors) { customParameters.put(ReleaseManagementParameterKeys.USE_GLOBAL_VERSION, Boolean.TRUE.toString()); String globalReleaseVersion = request.getParameter(ReleaseManagementParameterKeys.GLOBAL_RELEASE_VERSION); if (StringUtils.isNotBlank(globalReleaseVersion)) { customParameters.put(ReleaseManagementParameterKeys.GLOBAL_RELEASE_VERSION, globalReleaseVersion); } else { errors.addError("globalReleaseVersionError", "Release version is mandatory."); } String nextDevelopmentVersion = request.getParameter(ReleaseManagementParameterKeys.NEXT_GLOBAL_DEVELOPMENT_VERSION); if (StringUtils.isNotBlank(nextDevelopmentVersion)) { customParameters.put(ReleaseManagementParameterKeys.NEXT_GLOBAL_DEVELOPMENT_VERSION, nextDevelopmentVersion); } else { errors.addError("nextGlobalDevVersionError", "Release version is mandatory."); } } }
48.333333
114
0.745156
a47a9d6a495a5f5477fe3aca04eb95e8f4a31913
1,627
package com.ferius_057.onlineToStatus.vk; import com.ferius_057.onlineToStatus.data.Config; import com.ferius_057.onlineToStatus.utilities.Request; import java.io.IOException; import java.net.URLEncoder; public class Status { public boolean setStatus(String text) { try { String request = new Request().get("https://api.vk.com/method/status.set?text=" + URLEncoder.encode(text, "UTF-8") + "&group_id=" + Config.group_id + "&access_token=" + Config.token + "&v=5.130"); if (request.contains("error")) { // Переведено специально для тех кто не шарит в английском if (request.contains("User authorization failed: invalid access_token")) { System.err.println("ERROR: Ошибка авторизации пользователя, неверный token."); } else if (request.contains("Access denied: you should be a group administrator")) { System.err.println("ERROR: Доступ запрещен: вы должны быть администратором/редактором группы, проверьте наброность id группы в конфиге."); } else if (request.contains("Captcha needed")) { System.err.println("ERROR: Вы получили капчу, подождите несколько минут и сделайте больше задержку 'delay' в конфиге."); } System.out.println(request); return false; } return true; } catch (IOException e) { System.err.println("X | Не удалось сделать запрос. " + e.getMessage()); e.printStackTrace(); } return false; } }
49.30303
209
0.609711
3ba5813fb0de8f0050d74b1c22d7bca484cfdb07
7,191
/* * Copyright (c) 2018 Stanislav Myachenkov * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mytoptag.service.impl; import lombok.extern.slf4j.Slf4j; import org.mytoptag.model.Compatibility; import org.mytoptag.model.CompatibilityKey; import org.mytoptag.model.PostsOfTag; import org.mytoptag.model.dto.TagSuggestion; import org.mytoptag.model.dto.query.TagCategorySuggestionQueryResult; import org.mytoptag.repository.CategoryRepository; import org.mytoptag.repository.CompatibilityRepository; import org.mytoptag.repository.PostsOfTagRepository; import org.mytoptag.service.SuggestionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * {@link SuggestionService} implementation. */ @Service @Slf4j public class SuggestionServiceImpl implements SuggestionService { private static final Integer SCALE = 5; private static final Integer MAX_CATEGORIES = 10; private static final Integer MAX_CATEGORIES_FROM_INPUT = 5; private static final Integer MAX_TAGS_IN_POST = 30; private PostsOfTagRepository postsOfTagRepository; private CompatibilityRepository compatibilityRepository; private CategoryRepository categoryRepository; @Value("${spring.jpa.properties.hibernate.jdbc.batch_size}") private Integer maxBatchSize; /** * Ctor. * * @param compatibilityRepository {@link CompatibilityRepository} * @param postsOfTagRepository {@link PostsOfTagRepository} * @param categoryRepository {@link CategoryRepository} */ @Autowired public SuggestionServiceImpl( final CompatibilityRepository compatibilityRepository, final PostsOfTagRepository postsOfTagRepository, final CategoryRepository categoryRepository) { this.compatibilityRepository = compatibilityRepository; this.postsOfTagRepository = postsOfTagRepository; this.categoryRepository = categoryRepository; } /** * Update tag compatibility matrix. */ @Async("processExecutor") public void updateCompatibilityMatrix() { compatibilityRepository.clearCompatibilityMatrix(); final Map<Integer, List<Integer>> tagsMap = postsOfTagRepository.findAll() .stream() .collect(Collectors.toMap(PostsOfTag::getTag, v -> Arrays.asList(v.getPosts()))); final Integer[] tags = tagsMap.keySet().toArray(new Integer[0]); final int matrixSize = tags.length; for (int i = 0; i < matrixSize; i++) { log.info("Calculating compatibility for tag {}", tags[i]); final Integer allPostsOccurrence = tagsMap.get(tags[i]).size(); final List<Compatibility> compatibilities = new ArrayList<>(); for (int j = matrixSize - 1; j > i; j--) { final long compatiblePosts = tagsMap.get(tags[i]) .stream() .filter(tagsMap.get(tags[j])::contains) .count(); if (compatiblePosts > 0) { final BigDecimal compatibilityValue = new BigDecimal(compatiblePosts).divide( BigDecimal.valueOf(allPostsOccurrence), SCALE, BigDecimal.ROUND_HALF_UP ); compatibilities.add( new Compatibility( new CompatibilityKey(tags[i], tags[j]), compatibilityValue.doubleValue() ) ); } } log.info("Saving {} compatibility entries for tag {}", compatibilities.size(), tags[i]); saveInBatches(compatibilities); } log.info("compatibility matrix has been updated successfully, new entries amount: {}", compatibilityRepository.count()); } private void saveInBatches(final List<Compatibility> compatibilities) { final List<Compatibility> batch = new ArrayList<>(); for (int i = 0; i < compatibilities.size(); i++) { batch.add(compatibilities.get(i)); if (batch.size() == maxBatchSize || i == compatibilities.size() - 1) { compatibilityRepository.saveAll(batch); batch.clear(); } } } /** * Retrieves most relevant tags according to tag category relations. * * @param input set of users tags * @return List of {@link TagSuggestion} */ public List<TagSuggestion> getRecommendations(final Set<String> input) { final Map<String, Map<String, List<TagSuggestion>>> inputResult = new HashMap<>(); input.stream().limit(MAX_CATEGORIES).forEach(i -> { final List<TagCategorySuggestionQueryResult> queryResults = categoryRepository.findRelevantTags(i); final Map<String, List<TagSuggestion>> inputSearchResult = queryResults.stream() .collect(Collectors.groupingBy(TagCategorySuggestionQueryResult::getCategory)) .entrySet().stream() .collect( Collectors.toMap( Map.Entry::getKey, e -> e.getValue().stream().map(TagSuggestion::new).collect(Collectors.toList()), (u, v) -> { throw new IllegalStateException("Duplicate key"); }, LinkedHashMap::new ) ); inputResult.put(i, inputSearchResult); }); final List<TagSuggestion> suggestions = new LinkedList<>(); inputResult.forEach((i, res) -> suggestions.addAll( res.values().stream() .limit(MAX_CATEGORIES_FROM_INPUT) .flatMap(List::stream) .collect(Collectors.toList())) ); return suggestions.stream() .sorted(Comparator.comparing(TagSuggestion::getSortOrder)) .limit(MAX_TAGS_IN_POST) .sorted(Comparator.comparing(TagSuggestion::getCategory)) .collect(Collectors.toList()); } }
37.847368
105
0.69295
07a6f8ff19dd3338bd3bd8bb7d36f33f55c27cb0
7,504
/** * Copyright "TBD", Metron Aviation & CSSI. All rights reserved. * * This computer Software was developed with the sponsorship of the U.S. Government * under Contract No. DTFAWA-10-D-00033, which has a copyright license in accordance with AMS 3.5-13.(c)(1). */ package gov.faa.ang.swac.common.flightmodeling; import java.io.Serializable; import gov.faa.ang.swac.common.entities.Carrier; import gov.faa.ang.swac.common.flightmodeling.fileio.BadaRecord; /** * Represents an aircraft. It is primarily based on data contained in {@link ScheduleRecord}. * @author Jason Femino - CSSI, Inc. */ public class Aircraft implements Cloneable, Serializable { public enum PhysicalClass { J { @Override public String description() { return "Jet"; } }, T { @Override public String description() { return "Turboprop"; } }, P { @Override public String description() { return "Piston"; } }; public abstract String description(); } //--------------------- // Static class members //--------------------- // toString related members private static final String SEP = ","; public static final String TEXT_RECORD_KEY = "AIRCRAFT: carrierId, badaAircraftType, etmsAircraftType, physicalClass, userClass, atoUserClass, turnAroundCategory, enrouteCategory, climbDescentCategory, EquipmentSuffix"; //----------------------- // Instance class members //----------------------- private String carrierId = null; // An aircraft can have a carrierId but not a carrier. private Carrier carrier = null; private String filedBadaAircraftType = null; private String filedEtmsAircraftType = null; private final PhysicalClass physicalClass; private final String userClass; private BadaRecord badaRecord = null; private String atoUserClass = null; private EquipmentSuffix equipmentSuffix = new EquipmentSuffix(); /** * Constructs an {@link Aircraft} from a {@link ScheduleRecord}. * @param scheduleRecord */ public Aircraft(ScheduleRecord scheduleRecord) { setCarrierId(scheduleRecord.carrierId()); this.filedBadaAircraftType = scheduleRecord.badaAircraftType; this.filedEtmsAircraftType = scheduleRecord.etmsAircraftType; this.physicalClass = scheduleRecord.physicalClass; this.userClass = scheduleRecord.userClass; this.atoUserClass = scheduleRecord.atoUserClass; } /** * Copy constructor. * @param aircraft */ public Aircraft(Aircraft aircraft) { this.carrierId = aircraft.carrierId; this.carrier = aircraft.carrier == null ? null : new Carrier(aircraft.carrier); this.filedBadaAircraftType = aircraft.filedBadaAircraftType; this.filedEtmsAircraftType = aircraft.filedEtmsAircraftType; this.physicalClass = aircraft.physicalClass; this.userClass = aircraft.userClass; this.badaRecord = aircraft.badaRecord; this.atoUserClass = aircraft.atoUserClass; this.equipmentSuffix = (aircraft.equipmentSuffix == null ? null : aircraft.equipmentSuffix.clone()); } @Override public boolean equals(Object o) { if (o instanceof Aircraft) { Aircraft aircraft = (Aircraft)o; boolean carriersEqual = false; if (carrier == null) { carriersEqual = (this.carrierId == null ? aircraft.carrierId == null : this.carrierId.equals(aircraft.carrierId)); if (carriersEqual) assert( aircraft.carrier == null ); } else { carriersEqual = (aircraft.carrier == null) ? false : carrier.equals(aircraft.carrier); } if (carriersEqual && (this.filedBadaAircraftType == null ? aircraft.filedBadaAircraftType == null : this.filedBadaAircraftType.equals(aircraft.filedBadaAircraftType)) && (this.physicalClass == null ? aircraft.physicalClass == null : this.physicalClass.equals(aircraft.physicalClass)) && (this.userClass == null ? aircraft.userClass == null : this.userClass.equals(aircraft.userClass)) && (this.filedBadaAircraftType == null ? aircraft.filedBadaAircraftType == null : this.filedBadaAircraftType.equals(aircraft.filedBadaAircraftType)) && (this.atoUserClass == null ? aircraft.atoUserClass == null : this.atoUserClass.equals(aircraft.atoUserClass)) && (this.filedBadaAircraftType == null ? aircraft.filedBadaAircraftType == null : this.filedBadaAircraftType.equals(aircraft.filedBadaAircraftType)) && (this.equipmentSuffix == null ? aircraft.equipmentSuffix == null : this.equipmentSuffix.equals(aircraft.equipmentSuffix))) { return true; } } return false; } /** * Gets the name of the {@link Aircraft} operator. */ public String carrierId() { return carrierId; } /** * Sets the name of the {@link Aircraft} operator. * @param carrierId */ public void setCarrierId(String carrierId) { this.carrierId = carrierId; this.carrier = null; } /** * Returns the operator * @param carrier */ public Carrier getCarrier() { return carrier; } /** * Sets the operator * @param carrier */ public void setCarrier(Carrier carrier) { this.carrier = carrier; this.carrierId = carrier.getCarrierId(); } /** * Gets the name of the BADA (Base of Aircraft DAta) performance database entry. */ public String filedBadaAircraftType() { return this.filedBadaAircraftType; } /** * Sets the name of the BADA (Base of Aircraft DAta) performance database entry. */ public void setFiledBadaAircraftType(String badaAircraftType) { this.filedBadaAircraftType = badaAircraftType; } /** * Gets the name of the ETMS (Enhanced Traffic Management System) aircraft type. */ public String filedEtmsAircraftType() { return this.filedEtmsAircraftType; } /** * Sets the name of the ETMS (Enhanced Traffic Management System) aircraft type. */ public void setFiledEtmsAircraftType(String etmsAircraftType) { this.filedEtmsAircraftType = etmsAircraftType; } /** * Gets the aircraft engine type. */ public PhysicalClass physicalClass() { return this.physicalClass; } /** * Gets the aircraft engine type. */ public String userClass() { return this.userClass; } /** * Gets the BADA (Base of Aircraft DAta) performance database entry. */ public BadaRecord badaRecord() { return this.badaRecord; } /** * Sets the BADA (Base of Aircraft DAta) performance database entry. */ public void setBadaRecord(BadaRecord badaRecord) { this.badaRecord = badaRecord; } /** * @return the equipmentSuffix */ public EquipmentSuffix equipmentSuffix() { return this.equipmentSuffix; } /** * @param equipmentSuffix the equipmentSuffix to set */ public void setEquipmentSuffix(EquipmentSuffix equipmentSuffix) { this.equipmentSuffix = equipmentSuffix; } /** * Gets the ATO user class. */ public String atoUserClass() { return this.atoUserClass; } /** * Sets the ATO user class. */ public void setAtoUserClass(String newUserClass) { this.atoUserClass = newUserClass; } @Override public String toString() { return "AIRCRAFT:" + " " + (this.carrier == null ? "" : this.carrier) + SEP + " " + (this.filedBadaAircraftType == null ? "" : this.filedBadaAircraftType) + SEP + " " + (this.filedEtmsAircraftType == null ? "" : this.filedEtmsAircraftType) + SEP + " " + (this.physicalClass == null ? "" : this.physicalClass) + SEP + " " + (this.atoUserClass == null ? "" : this.atoUserClass) + SEP + " " + (this.equipmentSuffix == null ? "" : this.equipmentSuffix.toString()); } @Override public Aircraft clone() { return new Aircraft(this); } }
29.085271
220
0.701493
80bd686305a71fa71f3ec45b9bd2750bef55c560
3,227
package ninja.egg82.primitive.doubles; import it.unimi.dsi.fastutil.Arrays; public class DoubleArrays { //vars public final static double[] EMPTY_ARRAY = new double[0]; //constructor private DoubleArrays() { } //public public static double[] ensureCapacity(final double[] array, final int length) { if (length > array.length) { final double t[] = new double[length]; System.arraycopy(array, 0, t, 0, array.length); return t; } return array; } public static double[] ensureCapacity(final double[] array, final int length, final int preserve) { if (length > array.length) { final double t[] = new double[length]; System.arraycopy(array, 0, t, 0, preserve); return t; } return array; } public static double[] grow(final double[] array, final int length) { if (length > array.length) { final int newLength = (int) Math.max(Math.min(2L * array.length, Arrays.MAX_ARRAY_SIZE), length); final double t[] = new double[newLength]; System.arraycopy(array, 0, t, 0, array.length); return t; } return array; } public static double[] grow(final double[] array, final int length, final int preserve) { if (length > array.length) { final int newLength = (int) Math.max(Math.min(2L * array.length, Arrays.MAX_ARRAY_SIZE), length); final double t[] = new double[newLength]; System.arraycopy(array, 0, t, 0, preserve); return t; } return array; } public static double[] trim(final double[] array, final int length) { if (length >= array.length) { return array; } final double t[] = length == 0 ? EMPTY_ARRAY : new double[length]; System.arraycopy(array, 0, t, 0, length); return t; } public static double[] setLength(final double[] array, final int length) { if (length == array.length) { return array; } if (length < array.length) { return trim(array, length); } return ensureCapacity(array, length); } public static double[] copy(final double[] array, final int offset, final int length) { ensureOffsetLength(array, offset, length); final double[] a = length == 0 ? EMPTY_ARRAY : new double[length]; System.arraycopy(array, offset, a, 0, length); return a; } public static double[] copy(final double[] array) { return array.clone(); } public static void fill(final double[] array, final double value) { int i = array.length; while (i-- != 0) { array[i] = value; } } public static void fill(final double[] array, final int from, int to, final double value) { ensureFromTo(array, from, to); if (from == 0) { while (to-- != 0) { array[to] = value; } } else { for (int i = from; i < to; i++) { array[i] = value; } } } public static boolean equals(final double[] a1, final double a2[]) { int i = a1.length; if (i != a2.length) { return false; } while (i-- != 0) { if (!((a1[i]) == (a2[i]))) { return false; } } return true; } public static void ensureFromTo(final double[] a, final int from, final int to) { Arrays.ensureFromTo(a.length, from, to); } public static void ensureOffsetLength(final double[] a, final int offset, final int length) { Arrays.ensureOffsetLength(a.length, offset, length); } //private }
26.024194
100
0.651379
9d3fa08865a7ae05b5bd874a0711400f415838b4
691
package gd.rf.ta98.coffeeGit; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextArea; public class Main { public static void main(String[] args) { JFrame win = new JFrame("coffeeGit"); win.setSize(480, 720); win.setLocation(0,0); final JButton button = new JButton("Log in"); win.getContentPane().add(BorderLayout.SOUTH, button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // login duh } }); win.setVisible(true); } }
20.939394
57
0.680174
301081bb656cf27401b197241b34b47b75ddb997
1,701
package com.swr.matchmatch.util; import android.support.design.widget.Snackbar; import android.view.View; import com.swr.matchmatch.R; /** * Created by Steve Rock, SWR Technologies, LLC on 10/6/2017. * * MIT License Copyright (c) [2017] Steven William Rock, SWR Technologies, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ public class UIUtils { public static void showSnackBar(String msg, View view){ if(msg == null ) return; Snackbar snackbar = Snackbar .make(view, msg, Snackbar.LENGTH_LONG); snackbar.getView().setBackgroundColor(view.getResources().getColor(R.color.colorAccent)); snackbar.show(); } }
47.25
462
0.740153
6bec6dc659e18d9e91d58e0c1d1e14f0e61b4f9a
3,416
package io.ebeaninternal.server.core; import io.ebean.config.ServerConfig; import io.ebeaninternal.server.dto.DtoNamedQueries; import io.ebeaninternal.xmlmapping.XmlMappingReader; import io.ebeaninternal.xmlmapping.model.XmDto; import io.ebeaninternal.xmlmapping.model.XmEbean; import io.ebeaninternal.xmlmapping.model.XmRawSql; import org.avaje.classpath.scanner.ClassPathScanner; import org.avaje.classpath.scanner.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Reads the Xml deployment information. */ class InternalConfigXmlRead { private static final Logger log = LoggerFactory.getLogger(InternalConfigXmlRead.class); private final ServerConfig serverConfig; private final ClassLoader classLoader; private final Map<Class<?>, DtoNamedQueries> dtoNamedQueries = new HashMap<>(); private List<XmEbean> xmlEbeanList; InternalConfigXmlRead(ServerConfig serverConfig) { this.serverConfig = serverConfig; this.classLoader = serverConfig.getClassLoadConfig().getClassLoader(); if (serverConfig.getClassLoadConfig().isJavaxJAXBPresent()) { init(); } } private void init() { this.xmlEbeanList = XmlMappingReader.readByResourceName(classLoader, "ebean.xml"); xmlEbeanList.addAll(XmlMappingReader.readByResourceList(xmlMappingResources())); } private List<Resource> xmlMappingResources() { List<ClassPathScanner> scanners = ClassPathScanners.find(serverConfig); List<String> mappingLocations = serverConfig.getMappingLocations(); List<Resource> resourceList = new ArrayList<>(); long st = System.currentTimeMillis(); if (mappingLocations != null && !mappingLocations.isEmpty()) { for (ClassPathScanner finder : scanners) { for (String mappingLocation : mappingLocations) { resourceList.addAll(finder.scanForResources(mappingLocation, resourceName -> resourceName.endsWith(".xml"))); } } } long searchTime = System.currentTimeMillis() - st; log.debug("Classpath search mappings[{}] searchTime[{}]", resourceList.size(), searchTime); return resourceList; } /** * Return the XML deployment information for entity beans. */ List<XmEbean> xmlDeployment() { return xmlEbeanList; } /** * Return the named queries for Dto beans. */ Map<Class<?>, DtoNamedQueries> readDtoMapping() { if (xmlEbeanList != null) { for (XmEbean mapping : xmlEbeanList) { List<XmDto> dtoList = mapping.getDto(); for (XmDto dto : dtoList) { readDtoMapping(dto); } } } return dtoNamedQueries; } private void readDtoMapping(XmDto dto) { String dtoClassName = dto.getClazz(); Class<?> dtoClass; try { dtoClass = Class.forName(dtoClassName, false, classLoader); } catch (Exception e) { log.error("Could not load dto bean class " + dtoClassName + " for ebean xml entry"); return; } DtoNamedQueries namedQueries = dtoNamedQueries.computeIfAbsent(dtoClass, aClass -> new DtoNamedQueries()); for (XmRawSql sql : dto.getRawSql()) { namedQueries.addRawSql(sql.getName(), sql.getQuery().getValue()); } if (!dto.getNamedQuery().isEmpty()) { log.error("Only raw-sql named queries supported for DTO beans - bean:" + dtoClass); } } }
30.5
119
0.711066
76f83f08647b1edf9454c79d49520a21c786b443
1,403
package com.app2.manager; public class Configuration { public static final String MANAGER_SERVER_IP = "10.128.180.43"; public static final int MANAGER_SERVER_PORT = 6666; public static final int ADB_SERVER_PORT = 9999; public static final String CMD_RETURN_TAG = "RETURN-"; public static final String CMD_CONNECT_ADB = "cmd_connect_adb"; public static final String CMD_LIST_DEVICES = "cmd_list_devices"; public static final String CMD_SET_DEVICE = "cmd_set_device"; public static final String CMD_GET_DEVICE = "cmd_get_device"; public static final String CMD_RETRUN_LIST_DEVICES = CMD_RETURN_TAG + CMD_LIST_DEVICES; public static final String CMD_RETRUN_SET_DEVICE = CMD_RETURN_TAG + CMD_SET_DEVICE; public static final String CMD_RETRUN_GET_DEVICE = CMD_RETURN_TAG + CMD_GET_DEVICE; public static final String CMD_RETRUN_CONNECT_ADB = CMD_RETURN_TAG + CMD_CONNECT_ADB; public static final String SEG = "#@#"; public static final String TYPE_PC_TERMINAL = "type_pc_terminal"; public static final String TYPE_PHONE_CLIENT = "type_phone_client"; public static final int TYPE_INT_PC_TERMINAL = 1 << 0; public static final int TYPE_INT_PHONE_CLIENT = 1 << 1; public static final int TYPE_ALL = 0xFFFF; public static final int FLAG_START_ADB_SUCCESS = 1; public static final int FLAG_START_ADB_FAIL = 2; }
41.264706
91
0.758375
8ddcae1b4c774cd8238b664e15a9ed81a6329d5f
3,268
// ********************************************************** // Assignment2: // Student1: // UTORID user_name: bryanch3 // UT Student #: 1004015683 // Author: Chanzo Bryan // // Student2: // UTORID user_name: gaylejoe // UT Student #: 1004029268 // Author: Joey Lakerdas-Gayle // // Student3: // UTORID user_name: appleb16 // UT Student #: 1004432205 // Author: Sean Applebaum // // Student4: // UTORID user_name: ngevan1 // UT Student #:1004166662 // Author: Evan Kar Long Ng // // // Honor Code: I pledge that this program represents my own // program code and that I have coded on my own. I received // help from no one in designing and debugging my program. // I have also read the plagiarism section in the course info // sheet of CSC B07 and understand the consequences. // ********************************************************* package command; import shell.Directory; import shell.Navigate; import shell.State; import exception.IllegalNumberOfArgumentsException; import exception.InvalidPathException; /** * The pushd command */ public class PushdCommand extends Command { /* _____ _________________________ / \ | | | o| | | | | | | | \_| | | |__ _| _| | | |________| | Command | | __________| | | | | | | | | | / | | | | |\ \ | | |_| \_\ |_________________________| */ /** * Creates the pushd command with the appropriate documentation */ public PushdCommand() { // The name of the pushd command name = "pushd"; // The description of the pushd command description = "Will push the current directory onto the directory stack " + "then change to the given directory."; // The parameters for the pushd command pushd their description parameters.put("DIR", "The directory to change to"); } /** * Given a directory path, will push the current working directory onto the * directory stack then change the directory to the given directory * * @param state The state of the JShell * @throws IllegalNumberOfArgumentsException if more or less than 1 argument * is given * @throws InvalidPathException if the given directory is not valid */ public void run(State state) throws IllegalNumberOfArgumentsException, InvalidPathException { // Get the parameters of the command String[] stateParams = state.getParameters(); if (stateParams.length != 1) { throw new IllegalNumberOfArgumentsException(stateParams.length, 1); } // Get the new directory Directory directory = Navigate.navigateToDirectory(state, stateParams[0]); // Push the current directory onto the directory stack state.pushDirectory(state.getWorkingDirectory()); // Change to the given directory, not using cd to avoid adding cd to // history state.setWorkingDirectory(directory); } }
31.423077
78
0.571909
c1fc603327453f69a8053c9311b709a2f8057e32
1,710
package com.intellij.spring.webflow.graph.impl; import com.intellij.spring.webflow.graph.WebflowNodeType; import com.intellij.spring.webflow.model.xml.Transition; import com.intellij.spring.webflow.model.xml.WebflowNamedAction; import com.intellij.spring.webflow.WebflowIcons; import com.intellij.util.Icons; import com.intellij.util.xml.GenericAttributeValue; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.Collections; import java.util.List; public abstract class GlobalTransitionNode extends WebflowBasicNode<GenericAttributeValue<String>> { private final Transition myTransition; public GlobalTransitionNode(final Transition transition, final GenericAttributeValue<String> identifying) { super(identifying, identifying.getValue()); myTransition = transition; } public Transition getTransition() { return myTransition; } @NotNull public WebflowNodeType getNodeType() { return WebflowNodeType.GLOBAL_TRANSITIONS; } public List<WebflowNamedAction> getAllNodeActions() { return Collections.emptyList(); } public static class OnExceptionTransition extends GlobalTransitionNode { public OnExceptionTransition(final Transition transition, final GenericAttributeValue<String> identifying) { super(transition, identifying); } public Icon getIcon() { return Icons.EXCEPTION_CLASS_ICON; } } public static class OnTransition extends GlobalTransitionNode { public OnTransition(final Transition transition, final GenericAttributeValue<String> identifying) { super(transition, identifying); } public Icon getIcon() { return WebflowIcons.WEBFLOW_ON_TRANSITION_STATE; } } }
30.535714
112
0.781287
7ea508ae40a84d861b88c685da0c91e3edf762db
789
package com.essue.jvcache.redis; import com.essue.jvcache.Cache; import com.essue.jvcache.CacheProvider; import com.essue.jvcache.event.CacheEventBus; import com.essue.jvcache.redis.codec.RedisCodec; import io.vertx.redis.RedisClient; public class RedisCacheProvider implements CacheProvider { private CacheEventBus eventBus; private RedisClient client; private RedisCodec codec; public RedisCacheProvider(CacheEventBus eventBus, RedisClient client, RedisCodec codec) { this.eventBus = eventBus; this.client = client; this.codec = codec; } @Override public Cache getCache(String name, int timeout) { RedisCache cache = new RedisCache(eventBus, name, client, codec, timeout); return cache; } public void init() {} public void destroy() {} }
23.909091
91
0.755387
f572954d796eb047b8324fae89efb231a31c49aa
525
// http://codeforces.com/problemset/problem/61/A import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner read = new Scanner(System.in); String a = read.nextLine(); String b = read.nextLine(); StringBuilder output = new StringBuilder(); for (int i = 0; i < a.length(); ++i) { if (a.charAt(i) != b.charAt(i)) { output.append("1"); } else { output.append("0"); } } System.out.println(output); // Close scanner read.close(); } }
17.5
48
0.60381
8c2c853ce084213d336900cff2fffdfb843bdd00
682
package izuzeci; import java.util.Scanner; public class TestTryCatchPetlja { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Unesite ceo broj: "); int i = sc.nextInt(); sc.close(); // telo for-petlje je try-catch blok // (izbacivanje izuzetka ne uzrokuje prekid petlje) for(int j=3; j>=-1; j--) try { System.out.println("Uslo se u try: i=" + i + ", j=" + j); System.out.println("i/j = " + i/j); System.out.println("kraj try\n"); } catch(ArithmeticException e){ System.out.println("Uhvacen izuzetak: deljenje nulom!\n"); } System.out.println("Dovidjenja!"); } }
26.230769
63
0.617302
1da47ca6ec17067efbdf687d6936e1d6f9a271fe
659
package org.embulk.input.jira; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import org.embulk.config.ConfigException; public enum AuthenticateMethod { BASIC; @JsonValue @Override public String toString() { return this.name().toLowerCase(); } @JsonCreator public static AuthenticateMethod fromString(String value) { switch(value) { case "basic": return BASIC; default: throw new ConfigException(String.format("Unknown AuthenticateMethod value '%s'. Supported values is basic.", value)); } } }
23.535714
129
0.666161
6de024a195a36a2579f8e6ed485f29127df78f35
8,259
package org.umlg.sqlg.test.where; import org.apache.commons.lang3.time.StopWatch; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.junit.Assert; import org.junit.Test; import org.umlg.sqlg.test.BaseTest; import java.util.Arrays; import java.util.List; import java.util.Map; /** * @author Pieter Martin (https://github.com/pietermartin) * Date: 2017/09/29 */ public class TestTraversalFilterStepBarrier extends BaseTest { // @Test // public void testSqlgTraversalFilterStepPerformance() { // this.sqlgGraph.tx().normalBatchModeOn(); // int count = 10000; // for (int i = 0; i < count; i++) { // Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "name", "a1"); // Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "name", "b1"); // a1.addEdge("ab", b1); // } // this.sqlgGraph.tx().commit(); // // StopWatch stopWatch = new StopWatch(); // for (int i = 0; i < 1000; i++) { // stopWatch.start(); // GraphTraversal<Vertex, Vertex> traversal = this.sqlgGraph.traversal() // .V().hasLabel("A") // .where(__.out().hasLabel("B")); // List<Vertex> vertices = traversal.toList(); // Assert.assertEquals(count, vertices.size()); // stopWatch.stop(); // System.out.println(stopWatch.toString()); // stopWatch.reset(); // } // } @Test public void testOutEWithAttributes() throws Exception { this.sqlgGraph.tx().normalBatchModeOn(); Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "p1"); for (int j = 0; j < 10_000; j++) { Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "p2"); Vertex v3 = this.sqlgGraph.addVertex(T.label, "Person", "name", "p3"); Vertex v4 = this.sqlgGraph.addVertex(T.label, "Person", "name", "p4"); Vertex v5 = this.sqlgGraph.addVertex(T.label, "Person", "name", "p5"); v1.addEdge("aaa", v2, "real", true); v1.addEdge("aaa", v3, "real", false); v1.addEdge("aaa", v4, "real", true, "other", "one"); v1.addEdge("aaa", v5, "real", false); } this.sqlgGraph.tx().commit(); // int count = 10_000; int count = 1; for (int i = 0; i < count; i++) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); GraphTraversal<Vertex, Edge> gt = this.sqlgGraph.traversal() .V(v1) .outE() .where( __.inV().has("name", P.within("p4", "p2")) ); Assert.assertEquals(20_000, gt.count().next().intValue()); stopWatch.stop(); System.out.println(stopWatch.toString()); stopWatch.reset(); } } @Test public void testWhereVertexStepTraversalStep1() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "name", "a1"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A", "name", "a2"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "name", "b1"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B", "name", "b2"); Vertex b3 = this.sqlgGraph.addVertex(T.label, "B", "name", "b3"); a1.addEdge("ab", b1); a1.addEdge("ab", b2); a1.addEdge("ab", b3); a2.addEdge("ab", b1); this.sqlgGraph.tx().commit(); GraphTraversal<Vertex, Vertex> traversal = this.sqlgGraph.traversal().V().hasLabel("A").where(__.out()); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(2, vertices.size()); } @Test public void testWhereVertexStepTraversalStep() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "name", "a1"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A", "name", "a2"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "name", "b1"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B", "name", "b2"); Vertex b3 = this.sqlgGraph.addVertex(T.label, "B", "name", "b3"); a1.addEdge("ab", b1); a1.addEdge("ab", b2); a1.addEdge("ab", b3); a2.addEdge("ab", b1); this.sqlgGraph.tx().commit(); GraphTraversal<Vertex, Vertex> traversal = this.sqlgGraph.traversal().V().hasLabel("A").where(__.out().has("name", "b3")); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(1, vertices.size()); } @Test public void g_V_hasXageX_asXaX_out_in_hasXageX_asXbX_selectXa_bX_whereXa_eqXbXX() { loadModern(); final Traversal<Vertex, Map<String, Object>> traversal = this.sqlgGraph.traversal() .V().has("age").as("a") .out().in().has("age").as("b") .select("a", "b") .where("a", P.eq("b")); printTraversalForm(traversal); int counter = 0; while (traversal.hasNext()) { counter++; final Map<String, Object> map = traversal.next(); Assert.assertEquals(2, map.size()); Assert.assertTrue(map.containsKey("a")); Assert.assertTrue(map.containsKey("b")); Assert.assertEquals(map.get("a"), map.get("b")); } Assert.assertEquals(6, counter); Assert.assertFalse(traversal.hasNext()); } @Test public void g_VX1X_asXaX_out_hasXageX_whereXgtXaXX_byXageX_name() { loadModern(); Object marko = convertToVertexId(this.sqlgGraph, "marko"); final Traversal<Vertex, String> traversal = this.sqlgGraph.traversal() .V(marko).as("a") .out().has("age") .where(P.gt("a")).by("age") .values("name"); printTraversalForm(traversal); Assert.assertEquals("josh", traversal.next()); Assert.assertFalse(traversal.hasNext()); } @Test public void g_V_matchXa_created_lop_b__b_0created_29_c__c_whereXrepeatXoutX_timesX2XXX() throws Exception { loadModern(); final Traversal<Vertex, Map<String, String>> traversal = this.sqlgGraph.traversal().V().match( __.as("a").out("created").has("name", "lop").as("b"), __.as("b").in("created").has("age", 29).as("c"), __.as("c").where(__.repeat(__.out()).times(2))); printTraversalForm(traversal); checkResults(makeMapList(3, "a", convertToVertex(this.sqlgGraph, "marko"), "b", convertToVertex(this.sqlgGraph, "lop"), "c", convertToVertex(this.sqlgGraph, "marko"), "a", convertToVertex(this.sqlgGraph, "josh"), "b", convertToVertex(this.sqlgGraph, "lop"), "c", convertToVertex(this.sqlgGraph, "marko"), "a", convertToVertex(this.sqlgGraph, "peter"), "b", convertToVertex(this.sqlgGraph, "lop"), "c", convertToVertex(this.sqlgGraph, "marko")), traversal); } @Test public void g_V_matchXa_hasXsong_name_sunshineX__a_mapX0followedBy_weight_meanX_b__a_0followedBy_c__c_filterXweight_whereXgteXbXXX_outV_dX_selectXdX_byXnameX() { loadGratefulDead(); final Traversal<Vertex, String> traversal = this.sqlgGraph.traversal().V().match( __.as("a").has("song", "name", "HERE COMES SUNSHINE"), __.as("a").map(__.inE("followedBy").values("weight").mean()).as("b"), __.as("a").inE("followedBy").as("c"), __.as("c").filter(__.values("weight").where(P.gte("b"))).outV().as("d")). <String>select("d").by("name"); printTraversalForm(traversal); checkResults(Arrays.asList("THE MUSIC NEVER STOPPED", "PROMISED LAND", "PLAYING IN THE BAND", "CASEY JONES", "BIG RIVER", "EL PASO", "LIBERTY", "LOOKS LIKE RAIN"), traversal); } }
45.131148
167
0.583606
8000a0ae1eee136f348bfae7256440d0fbf94717
2,789
/* * 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 pmart; /** * * @author LeakSmey */ public class ProductList { private int pid; private String barcode; private String productName; private String priceIn; private String priceOut; private String qty; private String dateIn; public ProductList(String barcode, String productName, String priceIn, String priceOut) { this.barcode = barcode; this.productName = productName; this.priceIn = priceIn; this.priceOut = priceOut; } public ProductList(int pid,String barcode, String productName, String priceIn, String priceOut, String qty, String dateIn) { this.pid = pid; this.barcode = barcode; this.productName = productName; this.priceIn = priceIn; this.priceOut = priceOut; this.qty = qty; this.dateIn = dateIn; } /** * @return the barcode */ public String getBarcode() { return barcode; } /** * @param barcode the barcode to set */ public void setBarcode(String barcode) { this.barcode = barcode; } /** * @return the productName */ public String getProductName() { return productName; } /** * @param productName the productName to set */ public void setProductName(String productName) { this.productName = productName; } /** * @return the priceIn */ public String getPriceIn() { return priceIn; } /** * @param priceIn the priceIn to set */ public void setPriceIn(String priceIn) { this.priceIn = priceIn; } /** * @return the priceOut */ public String getPriceOut() { return priceOut; } /** * @param priceOut the priceOut to set */ public void setPriceOut(String priceOut) { this.priceOut = priceOut; } /** * @return the qty */ public String getQty() { return qty; } /** * @param qty the qty to set */ public void setQty(String qty) { this.qty = qty; } /** * @return the dateIn */ public String getDateIn() { return dateIn; } /** * @param dateIn the dateIn to set */ public void setDateIn(String dateIn) { this.dateIn = dateIn; } /** * @return the pid */ public int getPid() { return pid; } /** * @param pid the pid to set */ public void setPid(int pid) { this.pid = pid; } }
19.368056
129
0.557189
5f64a468f55fc810c231165ad8ad86d61f2d5554
1,760
package main; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import java.util.Map; public class Main { JFrame mainFrame = new JFrame(); JPanel panel = new JPanel(); JTextPane poem = new JTextPane(); JButton submit = new JButton("Submit"); Map<Integer, Character> map; public static void main(String[] args){ Main main = new Main(); main.runJFrame(); } private void runJFrame(){ map = new HashMap<>(); panel.add(poem, Component.CENTER_ALIGNMENT); panel.add(submit); mainFrame.add(panel); mainFrame.setSize(Toolkit.getDefaultToolkit().getScreenSize()); mainFrame.setVisible(true); submit.addActionListener(e -> lookInPoem()); } private void lookInPoem(){ int i = 0; String[] text = poem.getText().split(" "); for(String word : text){ if(word.toCharArray()[0]== System.getProperty("line.separator").toCharArray()[0]){ word.replace(System.getProperty("line.separator").toCharArray()[0],' '); } try { if(map.get(i) != word.toCharArray()[0]){ i=0; } }catch (NullPointerException ignored){ } i++; map.put(i, word.toCharArray()[0]); System.out.println(i + "|" +word.toCharArray()[0]); //if i > 2 = allieration if((word.toCharArray()[word.length()-1]) == System.getProperty("line.separator").toCharArray()[0] && !(word.contains(",") || word.contains("."))){ System.out.println("Enjabement"); } } } }
28.852459
158
0.55625
d0d540a321d7b87b35a81ffcf866a763d689e575
447
/* ** GENEREATED FILE - DO NOT MODIFY ** */ package com.wilutions.mslib.outlook; import com.wilutions.com.*; /** * AccountSelectorEvents. * */ @CoInterface(guid="{00063104-0000-0000-C000-000000000046}") public interface AccountSelectorEvents extends IDispatch { static boolean __typelib__loaded = __TypeLib.load(); @DeclDISPID(64627) public void onSelectedAccountChange(final Account SelectedAccount) throws ComException; }
31.928571
110
0.744966
9e0c7a86eba7e9934ba3f74da06e18f20ee96443
634
package de.agrirouter.middleware.persistence; import de.agrirouter.middleware.domain.Endpoint; import de.agrirouter.middleware.domain.log.Error; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * Access all errors. */ public interface ErrorRepository extends JpaRepository<Error, Long> { /** * Find all errors for the endpoint. * * @param endpoint - * @return - */ List<Error> findByEndpoint(Endpoint endpoint); /** * Remove all errors for the endpoint. * * @param endpoint - */ void deleteAllByEndpoint(Endpoint endpoint); }
21.862069
69
0.687697
4fd7edfb20b6aa99279dc5d7118e1e70abd4b63d
4,622
package picard.arrays.illumina; import htsjdk.tribble.annotation.Strand; /** * A simple class to represent a locus entry in an Illumina Bead Pool Manifest (BPM) file */ public class IlluminaBPMLocusEntry { int version; // The LocusEntry version. // IlmnID (probe identifier) of locus String ilmnId; // Name (variant identifier) of locus String name; // Index of this entry. int index; // Illumina Strand value IlluminaManifestRecord.IlluminaStrand ilmnStrand; // SNP value for locus (e.g., [A/C]) String snp; // Chromosome for the locus (e.g., XY) String chrom; String ploidy; String species; // Mapping location of locus int mapInfo; // Customer Strand String customerStrand; // AddressA ID of locus int addressA; // Only populated in CSV files or BPM files with version 4 data block String alleleAProbeSeq; // AddressB ID of locus (0 if none) int addressB; // Only populated in CSV files or BPM files with version 4 data block (empty if none) String alleleBProbeSeq; String genomeBuild; String source; String sourceVersion; IlluminaManifestRecord.IlluminaStrand sourceStrand; // Only populated in CSV files or BPM files with version 4 data block String sourceSeq; // Only populated in CSV files or BPM files with version 4 data block String topGenomicSeq; int expClusters; boolean intensityOnly; // Identifies type of assay (0 - Infinium II , 1 - Infinium I (A/T), 2 - Infinium I (G/C) int assayType; float fracA; float fracC; float fracT; float fracG; // Refstrand annotation Strand refStrand; // Not part of the locusEntry record in the BPM, added here for convenience int normalizationId; public IlluminaBPMLocusEntry() { version = -1; ilmnId = ""; name = ""; index = -1; ilmnStrand = IlluminaManifestRecord.IlluminaStrand.NONE; snp = ""; chrom = ""; ploidy = ""; species = ""; mapInfo = -1; customerStrand = ""; addressA = -1; addressB = -1; genomeBuild = ""; source = ""; sourceVersion = ""; sourceStrand = IlluminaManifestRecord.IlluminaStrand.NONE; expClusters = -1; intensityOnly = false; assayType = -1; fracA = 0.0f; fracC = 0.0f; fracT = 0.0f; fracG = 0.0f; refStrand = Strand.NONE; normalizationId = -1; } public int getVersion() { return version; } public String getIlmnId() { return ilmnId; } public String getName() { return name; } public int getIndex() { return index; } public IlluminaManifestRecord.IlluminaStrand getIlmnStrand() { return ilmnStrand; } public String getSnp() { return snp; } public String getChrom() { return chrom; } public String getPloidy() { return ploidy; } public String getSpecies() { return species; } public int getMapInfo() { return mapInfo; } public String getCustomerStrand() { return customerStrand; } public int getAddressA() { return addressA; } public String getAlleleAProbeSeq() { return alleleAProbeSeq; } public int getAddressB() { return addressB; } public String getAlleleBProbeSeq() { return alleleBProbeSeq; } public String getGenomeBuild() { return genomeBuild; } public String getSource() { return source; } public String getSourceVersion() { return sourceVersion; } public IlluminaManifestRecord.IlluminaStrand getSourceStrand() { return sourceStrand; } public String getSourceSeq() { return sourceSeq; } public String getTopGenomicSeq() { return topGenomicSeq; } public int getExpClusters() { return expClusters; } public boolean isIntensityOnly() { return intensityOnly; } public int getAssayType() { return assayType; } public float getFracA() { return fracA; } public float getFracC() { return fracC; } public float getFracT() { return fracT; } public float getFracG() { return fracG; } public Strand getRefStrand() { return refStrand; } public int getNormalizationId() { return normalizationId; } }
19.668085
92
0.598442
786df75a1ce8bbb3a4e923c703572368c259e734
6,388
package com.easydataservices.db2admintool.database.agent.db2luw; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.env.SimpleCommandLinePropertySource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import com.easydataservices.db2admintool.database.agent.JdbcAgent; import com.easydataservices.db2admintool.database.agent.config.FileConfigClasses; import com.easydataservices.db2admintool.database.agent.config.JdbcMonitorClasses; import com.easydataservices.db2admintool.database.agent.db2luw.Db2DatabaseIdentity; import com.easydataservices.db2admintool.database.agent.db2luw.Db2DatabaseIdentityDao; import com.easydataservices.db2admintool.database.agent.db2luw.jdbc.monitor.JdbcMonitorSnapshotDao; import com.easydataservices.db2admintool.repository.agent.db2luw.dao.ClientAdminDao; import com.easydataservices.db2admintool.repository.scheduler.model.Job; import com.easydataservices.db2admintool.repository.scheduler.model.PollDelay; //------------------------------------------------------------------------------ // File: JdbcMonitor.java // Licence: Apache License 2.0 // Description: /** * Main class for a Db2 for LUW monitoring agent using a JDBC data source. * @author [email protected] * @version 2021.11.06 */ //------------------------------------------------------------------------------ @Repository public class JdbcMonitor extends JdbcAgent { private static final String className = JdbcMonitor.class.getName(); private static final Logger logger = Logger.getLogger(className); private ClientAdminDao clientAdminDao; private Db2DatabaseIdentityDao db2DatabaseIdentityDao; private Db2DatabaseIdentity db2DatabaseIdentity; /** * Return the process type. * @return Process type. */ @Override protected String getProcessType() { return "JDBC_MONITOR"; } /** * Validate supplied command line properties. */ @Override protected void validateProperties(SimpleCommandLinePropertySource propertySource) { final String method = "validateProperties"; final String textUsage = "Usage: " + className + " [ --repositoryFile=<path> ] [ --databaseFile=<path> ] [ --configFile=<path> ]"; logger.entering(className, method, new Object[] {propertySource}); if (!Arrays.asList(propertySource.getPropertyNames()).contains("configFile")) { throw new IllegalArgumentException("Argument --configFile missing"); } if (propertySource.getPropertyNames().length > 3) { throw new IllegalArgumentException("Too many arguments\n" + textUsage); } logger.exiting(className, method); } /** * Register required classes in application context. */ @Override protected void registerClasses(AnnotationConfigApplicationContext context) { final String method = "registerClasses"; logger.entering(className, method, new Object[] {context}); super.registerClasses(context); context.register(Db2DatabaseIdentityDao.class); context.register(ClientAdminDao.class); context.register(FileConfigClasses.class); context.register(JdbcMonitorClasses.class); logger.exiting(className, method); } /** * Instantiate required classes from application context. */ @Override protected void instantiateClasses(AnnotationConfigApplicationContext context) { final String method = "instantiateClasses"; logger.entering(className, method, new Object[] {context}); db2DatabaseIdentityDao = context.getBean(Db2DatabaseIdentityDao.class); clientAdminDao = context.getBean(ClientAdminDao.class); logger.exiting(className, method); } /** * Execute. */ @Override protected void exec(AnnotationConfigApplicationContext context) { final String method = "exec"; logger.entering(className, method); Integer dbId = getDb2DatabaseIdentity().getDbId(); while (true) { PollDelay pollDelay = getSchedulerDao().getPollDelay(dbId, getProcessType()); if (pollDelay.getNextPollDelayMilliseconds() == null) { break; } if (pollDelay.getNextPollDelayMilliseconds().equals(0)) { Job job = getSchedulerDao().getNextJob(dbId, getProcessType()); try { JdbcMonitorSnapshotDao snapshotDao = (JdbcMonitorSnapshotDao) Class.forName(job.getExecClass()).newInstance(); snapshotDao.setContext(context); snapshotDao.setDb2DatabaseIdentity(getDb2DatabaseIdentity()); snapshotDao.capture(); } catch (Exception exception) { logger.logp(Level.WARNING, className, method, exception.getMessage()); } try { Thread.sleep(10000); } catch (InterruptedException exception) { // Do nothing. } } else { try { Thread.sleep(pollDelay.getNextPollDelayMilliseconds()); } catch (InterruptedException exception) { // Do nothing. } } } logger.exiting(className, method); } /** * Return Db2 database identity object. */ protected Db2DatabaseIdentity getDb2DatabaseIdentity() { final String method = "getDb2DatabaseIdentity"; logger.entering(className, method); db2DatabaseIdentity = db2DatabaseIdentityDao.getIdentity(); Integer dbId = clientAdminDao.getDbId(db2DatabaseIdentity.getDbName(), db2DatabaseIdentity.getDbSeed()); if (dbId == null) { throw new IllegalArgumentException("Database not registered"); } db2DatabaseIdentity.setDbId(dbId); logger.exiting(className, method, db2DatabaseIdentity); return db2DatabaseIdentity; } /** * Main process (entry point). */ public static void main(String[] args) { final String method = "main"; logger.entering(className, method, args); try { JdbcAgent agent = new JdbcMonitor(); agent.run(args); } catch (Exception exception) { logger.logp(Level.SEVERE, className, method, exception.getMessage() + "\nABORT"); } logger.exiting(className, method); } }
36.712644
120
0.695679
ac90eebe05c8547770d3a23e3656ab0f4037f644
1,645
package org.kidding.orm.test; import org.kidding.orm.parser.impl.EntityParser; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * Created by iCrany on 14/11/28. */ public class EntityParserTest { public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException { EntityParser<POJOTest> tt = new EntityParser<POJOTest>(POJOTest.class); POJOTest pojo = new POJOTest(); pojo.setId(123); pojo.setLastName("li"); pojo.setName("shan"); Field[] fields = pojo.getClass().getDeclaredFields(); Method[] methods = pojo.getClass().getDeclaredMethods(); Map<String,Method> methodMap = new HashMap<String,Method>(); for(Method method : methods){ methodMap.put(method.getName(),method); } System.out.println("fields size = " + fields.length); for(Field field : fields){ field.setAccessible(true); String methodName = tt.hasGetMethod(methods,field.getName()); if(null != methodName){ Method method = methodMap.get(methodName); System.out.println("FieldName : " + field.getName() + " = " + method.invoke(pojo)); }else { System.out.println("FieldName : " + field.getName() + " "); } } for(Method method: methods){ System.out.println("MethodName : " + method.getName()); } tt.getAttrValueMap(pojo, true); } }
33.571429
125
0.621277
ecfe71ef0f28181bd437280f3f9d6453e8e8386d
288
package dev.mohsenkohan.petclinic.repositories.jpa; import dev.mohsenkohan.petclinic.model.Vet; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface VetRepository extends CrudRepository<Vet, Long> { }
28.8
66
0.847222
980ba0efbdad4cf67a274c35914a14b182c4af0b
1,974
package Models.Clowns; import Models.Utils.ArrayListIterator; import Models.Utils.Loader; import Models.Stick.Observer; import View.game.GameObject; import java.awt.image.BufferedImage; import java.util.ArrayList; public class ImageObject implements GameObject,Cloneable { public BufferedImage[] spriteImages = new BufferedImage[1]; public ArrayList observers = new ArrayList(); Loader loader; public int x; int y; public boolean visible = true; public int type; @Override public int getX() { return x; } @Override public void setX(int mX) { this.x = mX; } @Override public int getY() { return y; } @Override public void setY(int mY) { this.y = mY; } @Override public BufferedImage[] getSpriteImages() { return spriteImages; } @Override public int getWidth() { return spriteImages[0].getWidth(); } @Override public int getHeight() { return spriteImages[0].getHeight(); } @Override public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } public int getType() { return type; } public void setType(int type) { this.type = type; } public void registerObserver(Observer o) { observers.add(o); } public void removeObserver(Observer o) { int i = observers.indexOf(o); if (i >= 0) { observers.remove(i); } } public boolean notifyObservers(int diff) { ArrayListIterator iterator = new ArrayListIterator(observers); while (iterator.hasNext()){ Observer observer = (Observer)iterator.next(); observer.update(diff); } return true; } public Object clone() throws CloneNotSupportedException { return super.clone(); } }
20.142857
70
0.599797
8cbd3ffc4944233cfecb54f01a5b664062f0558b
793
package me.paulf.wings.client.flight.state; import me.paulf.wings.client.flight.Animator; import me.paulf.wings.server.flight.Flight; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; public final class StateIdle extends State { public StateIdle() { super(Animator::beginIdle); } @Override protected State createIdle() { return this; } @Override protected State getDescent(final Flight flight, final EntityPlayer player, final ItemStack wings) { final BlockPos below = new BlockPos(player.posX, player.posY - 0.25D, player.posZ); if (player.world.isAirBlock(below) && player.world.isAirBlock(below.down())) { return super.getDescent(flight, player, wings); } return this.createIdle(); } }
28.321429
100
0.760404
4e6b215b46e99ac0972a8b47cffbf150b5587a8e
2,219
/* * Copyright 2022 The Android Open Source Project * * 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 androidx.car.app.hardware.common; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.OptIn; import androidx.annotation.RestrictTo; import androidx.car.app.annotations.ExperimentalCarApi; import java.util.List; /** * Utility functions to work with {@link androidx.car.app.hardware.info.AutomotiveCarInfo} and * {@link androidx.car.app.hardware.climate.AutomotiveCarClimate} * * @hide */ @RestrictTo(LIBRARY) public final class CarValueUtils { /** * Gets a {@link androidx.car.app.hardware.common.CarValue} object from * {@link androidx.car.app.hardware.common.CarPropertyResponse} */ @NonNull @OptIn(markerClass = ExperimentalCarApi.class) public static <T> CarValue<T> getCarValue(@NonNull CarPropertyResponse<?> response, @Nullable T value) { long timestampMillis = response.getTimestampMillis(); int status = response.getStatus(); List<CarZone> zones = response.getCarZones(); return new CarValue<>(value, timestampMillis, status, zones); } /** * Builds {@link CarValue} from an existing {@link CarPropertyResponse}. */ @NonNull @OptIn(markerClass = ExperimentalCarApi.class) @SuppressWarnings("unchecked") public static <T> CarValue<T> getCarValue(@NonNull CarPropertyResponse<?> response) { return new CarValue<>((T) response.getValue(), response.getTimestampMillis(), response.getStatus()); } private CarValueUtils() { } }
34.138462
94
0.71744
73fcadea6ccd6775cf8334bed11a10bc4091aad7
925
// This file is part of MicropolisJ. // Copyright (C) 2013 Jason Long // Portions Copyright (C) 1989-2007 Electronic Arts Inc. // // MicropolisJ is free software; you can redistribute it and/or modify // it under the terms of the GNU GPLv3, with additional terms. // See the README file, included in this distribution, for details. package micropolisj.engine; /** * The listener interface for receiving notifications whenever a tile on * the city map changes, or when a sprite moves or changes. */ public interface MapListener { /** Called whenever data for a specific overlay has changed. */ void mapOverlayDataChanged(MapState overlayDataType); /** Called when a sprite moves. */ void spriteMoved(Sprite sprite); /** Called when a map tile changes, including for animations. */ void tileChanged(int xpos, int ypos); /** Called when the entire map should be reread and rendered. */ void wholeMapChanged(); }
31.896552
72
0.743784
a23b73a2176e241e20c9a873f881027ed0d446c4
2,181
package ink.dvc.ezmybatis.core.sqlgenerate.oracle; import ink.dvc.ezmybatis.core.sqlgenerate.AbstractEzUpdateToSql; import ink.dvc.ezmybatis.core.sqlstruct.UpdateSet; import ink.dvc.ezmybatis.core.sqlstruct.update.UpdateItem; import org.apache.ibatis.session.Configuration; import ink.dvc.ezmybatis.core.EzUpdate; import ink.dvc.ezmybatis.core.sqlgenerate.MybatisParamHolder; import ink.dvc.ezmybatis.core.utils.Assert; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class OracleEzUpdateToSql extends AbstractEzUpdateToSql { private static volatile OracleEzUpdateToSql instance; private OracleEzUpdateToSql() { } public static OracleEzUpdateToSql getInstance() { if (instance == null) { synchronized (OracleEzUpdateToSql.class) { if (instance == null) { instance = new OracleEzUpdateToSql(); } } } return instance; } @Override public String toSql(Configuration configuration, List<EzUpdate> updates, Map<String, Object> mybatisParam) { String sql = super.toSql(configuration, updates, mybatisParam); return "BEGIN \n" + sql + "END;"; } @Override protected StringBuilder setToSql(StringBuilder sqlBuilder, Configuration configuration, EzUpdate update, MybatisParamHolder mybatisParamHolder) { UpdateSet set = update.getSet(); if (set != null && set.getItems() != null) { List<UpdateItem> items = set.getItems().stream().filter(e -> e.getTable() == update.getTable()) .collect(Collectors.toList()); Assert.notEmpty(items, "Valid update items cannot be empty"); set.getItems().clear(); set.getItems().addAll(items); } return super.setToSql(sqlBuilder, configuration, update, mybatisParamHolder); } @Override protected StringBuilder joinsToSql(StringBuilder sqlBuilder, Configuration configuration, EzUpdate update, MybatisParamHolder mybatisParamHolder) { return sqlBuilder; } }
37.603448
112
0.665291
fe4564a6721ea4beac82c076634150bb0cc92afc
1,521
package mdelacalle.com.cartasnauticas; import io.realm.RealmObject; public class Situacion extends RealmObject { String analisis; String inicio; String fin; String texto; String nombre; public Situacion(String analisis, String inicio, String fin, String texto, String nombre) { this.analisis = analisis; this.inicio = inicio; this.fin = fin; this.texto = texto; this.nombre = nombre; } public Situacion() { } public String getAnalisis() { return analisis; } public void setAnalisis(String analisis) { this.analisis = analisis; } public String getInicio() { return inicio; } public void setInicio(String inicio) { this.inicio = inicio; } public String getFin() { return fin; } public void setFin(String fin) { this.fin = fin; } public String getTexto() { return texto; } public void setTexto(String texto) { this.texto = texto; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @Override public String toString() { return "Situacion{" + "analisis='" + analisis + '\'' + ", inicio='" + inicio + '\'' + ", fin='" + fin + '\'' + ", texto='" + texto + '\'' + ", nombre='" + nombre + '\'' + '}'; } }
20.554054
95
0.529257
a3ad8d9c1bf2ab7688636c3866188abc5ad44ddd
647
package Release_VIII.B_Chapter_13.P3_Editor; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Editor { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str[] = new String[100]; System.out.println("Wpisz wiersze tekstu \n Wpisz 'stop' aby wyjsc."); for(int i=0; i<100; i++) { str[i] = br.readLine(); if(str[i].equals("stop")) break; } System.out.println("Wynik"); for(String s : str) { if(s.equalsIgnoreCase("stop")) break; System.out.println(s); } } }
22.310345
75
0.684699
42473ea706e57a94f00e0a7b30dbcd5a0b4b4799
1,290
/* * Copyright 2019 StreamSets Inc. * * 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.streamsets.pipeline.lib.jdbc.multithread; /** * Database vendor (Oracle, MySQL, ...) */ public enum DatabaseVendor { DB2("com.ibm.db2.jcc.DB2Driver"), MYSQL("com.mysql.jdbc.Driver"), HIVE("org.apache.hive.jdbc.HiveDriver", "com.cloudera.impala.jdbc41.Driver", "com.cloudera.impala.jdbc4.Driver"), TERADATA("com.teradata.jdbc.TeraDriver"), ORACLE("oracle.jdbc.driver.OracleDriver"), POSTGRESQL("org.postgresql.Driver"), SQL_SERVER("com.microsoft.sqlserver.jdbc.SQLServerDriver"), UNKNOWN(), ; private final String[] drivers; DatabaseVendor(String ...drivers) { this.drivers = drivers; } public String[] getDrivers() { return drivers; } }
30.714286
115
0.72093
577a2791b255f7d781e365ffd0295c69dedc3707
1,181
package hackerrank.practice.warmup; public class CountingValleys { public static void main(String[] args){ // String[] path= {"D", "D", "U", "U", "U", "U", "D", "D"}; // String[] path= {"U", "D", "D", "D", "U", "D", "U", "U"}; // String[] path= {"U", "D", "D", "D", "U", "D", "U"}; // String[] path= {"U", "D", "D", "D", "U", "D", "U", "U", "D", "U"}; String[] path= {"D", "U","U", "D", "D", "D", "U", "D", "U", "U", "D", "U"}; System.out.println("volleys count : "+countVolleys(path.length, path)); } private static int countVolleys(int length, String[] path) { int level=0; int volleysCount =0; boolean doCount = false; for(String step: path) { char c = step.charAt(0); if(step.equals("U")){ level +=1; } else { level -=1; } if(level > 0) { doCount = false; } if(level < 0) { doCount = true; } if(doCount && level == 0) { volleysCount +=1; } } return volleysCount; } }
31.918919
83
0.401355
fb57ce901b80cd32909ce1888afed8e066cc25da
743
package de.melanx.skyguis.config; import io.github.noeppi_noeppi.libx.annotation.config.RegisterConfig; import io.github.noeppi_noeppi.libx.config.Config; import java.text.SimpleDateFormat; @RegisterConfig(client = true) public class ClientConfig { @Config({ "See here for information how to configure this:", "https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/text/SimpleDateFormat.html", "Examples:", "dd.MM.yyyy HH:mm - 07.12.1997 23:30", "yyyy-MM-dd'T'HH:mm:ss - 1997-12-07T23:30:00", "EEE, d MMM yyyy HH:mm:ss - Sun, 7 Dec 1997 23:30:00" }) public static SimpleDateFormat date = new SimpleDateFormat("dd.MM.yyyy HH:mm"); }
35.380952
107
0.656797
a5f3cc281d3a75c193751257ba4f825f40a842e5
930
package com.github.sqrlserverjava.backchannel; import static com.github.sqrlserverjava.backchannel.SqrlTifTest.isTifAbsent; import static com.github.sqrlserverjava.backchannel.SqrlTifTest.isTifPresent; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; import org.junit.Test; import com.github.sqrlserverjava.backchannel.SqrlTifResponse.SqrlTifResponseBuilder; public class SqrlTifConstructorTest { @Test public void testIpsMatched() throws Exception { final SqrlTifResponse tif = new SqrlTifResponseBuilder(true).createTif(); assertTrue(isTifPresent(tif, SqrlTifFlag.IPS_MATCHED)); assertEquals("4", tif.toHexString()); } @Test public void testIpsNotMatched() throws Exception { final SqrlTifResponse tif = new SqrlTifResponseBuilder(false).createTif(); assertTrue(isTifAbsent(tif, SqrlTifFlag.IPS_MATCHED)); assertEquals("0", tif.toHexString()); } }
32.068966
84
0.811828
3bb15a6158a49f4a4aac3f661f9f0af1eba8255e
8,659
package keisuke.count.diff; import static keisuke.count.diff.renderer.RendererConstant.MSG_DIFF_RND_PREFIX; import static keisuke.count.option.CountOptionConstant.*; import static keisuke.report.property.MessageConstant.MSG_DIFF_STATUS_PREFIX; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import keisuke.count.AbstractCountMainProc; import keisuke.count.FormatEnum; import keisuke.count.Formatter; import keisuke.count.PathStyleEnum; import keisuke.count.SortOrderEnum; import keisuke.count.diff.renderer.RendererFactory; import keisuke.count.option.DiffCountOption; import keisuke.report.property.MessageDefine; import keisuke.util.LogUtil; /** * コマンドラインから引数で指定した2つのディレクトリ配下のファイルの * 差分行数をカウントするコマンドのメイン処理クラス */ public class DiffCountProc extends AbstractCountMainProc { public static final String[] MSG_DIFF_PREFIXES = {MSG_DIFF_STATUS_PREFIX, MSG_DIFF_RND_PREFIX}; private File srcdir = null; private File oldSrcdir = null; private MessageDefine msgDef = null; private DiffFolderResult diffResult; public DiffCountProc() { super(); this.setCommandOption(new DiffCountOption()); } /** {@inheritDoc} */ protected void setDefaultFormat() { // DiffCountのformatオプションのデフォルトはTEXT this.setFormatEnum(FormatEnum.TEXT); } /** {@inheritDoc} */ protected void setDefaultPathStyle() { // DiffCountのpathオプションのデフォルトはBASE this.setPathStyleEnum(PathStyleEnum.BASE); } /** {@inheritDoc} */ protected void setDefaultSortOrder() { // DiffCountのsortオプションのデフォルトはnull // デフォルト値のままであればRendererFactoryがformatに応じて再設定する this.setSortOrderEnum(null); // 実際にはnullが設定されるのでなく変更されない } /** {@inheritDoc} */ protected void setFileArguments() throws IllegalArgumentException { // 新しい版のソースの基点ディレクトリの設定 String newdir = this.argMap().get(ARG_NEWDIR); if (newdir == null) { LogUtil.errorLog("new directory is not specified."); throw new IllegalArgumentException("no new directory"); } else { try { this.validateAndSetNewDirectory(newdir); } catch (IllegalArgumentException e) { LogUtil.errorLog("'" + newdir + "' is not directory."); throw e; } } // 古い版のソースの基点ディレクトリの設定 String olddir = this.argMap().get(ARG_OLDDIR); if (olddir == null) { LogUtil.errorLog("old directory is not specified."); throw new IllegalArgumentException("no old directory."); } else { try { this.validateAndSetOldDirectory(olddir); } catch (IllegalArgumentException e) { LogUtil.errorLog("'" + olddir + "' is not directory."); throw e; } } } /** {@inheritDoc} */ protected void setOptions() throws FileNotFoundException { String encoding = this.argMap().get(OPT_ENCODE); String outfile = this.argMap().get(OPT_OUTPUT); String format = this.argMap().get(OPT_FORMAT); String path = this.argMap().get(OPT_PATH); String sort = this.argMap().get(OPT_SORT); String xmlfile = this.argMap().get(OPT_XML); // 対象ファイルのエンコード指定を設定 if (encoding != null && encoding.length() > 0) { this.setSourceEncoding(encoding); } // 出力フォーマットの指定 // フォーマットを設定 if (format != null) { try { this.validateFormatOption(format); } catch (IllegalArgumentException e) { LogUtil.errorLog("'" + format + "' is invalid option value for '" + OPT_FORMAT + "'."); throw e; } this.setFormat(format); } // 出力のパス表記方法の指定 if (path != null) { try { this.validatePathOption(path); } catch (IllegalArgumentException e) { LogUtil.errorLog("'" + path + "' is invalid option value for '" + OPT_PATH + "'."); throw e; } this.setPathStyle(path); } // ソート順の指定 if (sort != null) { try { this.validateSortOption(sort); } catch (IllegalArgumentException e) { LogUtil.errorLog("'" + sort + "' is invalid option value for '" + OPT_SORT + "'."); throw e; } this.setSortOrder(sort); } // カスタマイズしたXML定義ファイル指定 if (xmlfile != null) { this.setXmlFileName(xmlfile); } // 出力先の指定 if (outfile != null && outfile.length() > 0) { this.setOutputStream(new FileOutputStream(new File(outfile))); } } private void validateAndSetNewDirectory(final String dirname) { File newdirFile = this.validateAndGetDirectory("new", dirname); this.setNewDirectory(newdirFile); } private void validateAndSetOldDirectory(final String dirname) { File olddirFile = this.validateAndGetDirectory("old", dirname); this.setOldDirectory(olddirFile); } private File validateAndGetDirectory(final String prefix, final String dirname) { if (dirname == null || dirname.isEmpty()) { throw new IllegalArgumentException(prefix + " directory is not specified."); } File dirFile = new File(dirname); return this.validateDirectory(prefix, dirFile); } private void validateAndSetNewDirectory(final File dirFile) { this.validateDirectory("new", dirFile); this.setNewDirectory(dirFile); } private void validateAndSetOldDirectory(final File dirFile) { this.validateDirectory("old", dirFile); this.setOldDirectory(dirFile); } private File validateDirectory(final String prefix, final File dirFile) { if (dirFile == null) { throw new IllegalArgumentException(prefix + " directory is null."); } if (!dirFile.isDirectory()) { throw new IllegalArgumentException(dirFile.getPath() + " is not directory."); } return dirFile; } /** * 保持している2つのソースルートディレクトリに対してカウントを実行します * @throws IOException 出力時に異常があると発行 */ protected void executeCounting() throws IOException { this.msgDef = new MessageDefine(MSG_DIFF_PREFIXES); DiffCountFunction diffcounter = new DiffCountFunction(this.sourceEncoding(), this.xmlFileName()); if (this.sortOrder() == SortOrderEnum.OFF) { // 未指定の場合はOS順で計測し、出力時は形式毎に決まる diffcounter.setSortingOrder(SortOrderEnum.OS); } else { diffcounter.setSortingOrder(this.sortOrder()); } this.diffResult = diffcounter.countDiffBetween(this.oldSrcdir, this.srcdir); } /** {@inheritDoc} */ protected void writeResults() throws IOException { // フォーマッタを設定 Formatter<DiffFolderResult> renderer = RendererFactory.getFormatter(this.format(), this.msgDef, this.pathStyle(), this.sortOrder()); this.setFormatter(renderer); if (renderer == null) { throw new RuntimeException("fail to get a formatter"); } this.outputStream().write(renderer.format(this.diffResult)); this.outputStream().flush(); //LogUtil.debugLog("カウント結果を出力しました。"); } /** * 新しい版のソースを格納するディレクトリをセットします * @param dir 新しい版のディレクトリ */ private void setNewDirectory(final File dir) { this.srcdir = dir; } /** * 古い版のソースを格納するディレクトリをセットします * @param dir 古い版のディレクトリ */ private void setOldDirectory(final File dir) { this.oldSrcdir = dir; } /** * 計測結果データを格納しているルートオブジェクトをセットします * @param result 計測結果のルートオブジェクト */ protected void setResult(final DiffFolderResult result) { this.diffResult = result; } /** * 計測結果を格納している木構造データのルートを返す * @return 木構造データのルート */ public DiffFolderResult getResultAsRawData() { return this.diffResult; } /** {@inheritDoc} */ public void doCountingAndWriting(final String[] filenames, final OutputStream output) throws IOException { if (filenames == null || filenames.length < 2) { LogUtil.errorLog("old and new directories are not specified."); throw new IllegalArgumentException("short of arguments"); } doCountingAndWriting(filenames[0], filenames[1], output); } /** * オプションや計測対象ファイル名を設定後に、差分ステップ計測と結果出力を実行する * @param olddir 計測対象の旧バージョンのディレクトリ * @param newdir 計測対象の新バージョンのディレクトリ * @param output 結果出力先 * @throws IOException ファイル入出力で異常があれば発行する */ public void doCountingAndWriting(final String olddir, final String newdir, final OutputStream output) throws IOException { // 旧バージョンDir File oldDirFile = this.validateAndGetDirectory("old", olddir); // 新バージョンDir File newDirFile = this.validateAndGetDirectory("new", newdir); // 計測と出力 this.doCountingAndWriting(oldDirFile, newDirFile, output); } /** * オプションや計測対象ファイル名を設定後に、差分ステップ計測と結果出力を実行する * @param olddir 計測対象の旧バージョンのディレクトリ * @param newdir 計測対象の新バージョンのディレクトリ * @param output 結果出力先 * @throws IOException ファイル入出力で異常があれば発行する */ public void doCountingAndWriting(final File olddir, final File newdir, final OutputStream output) throws IOException { // 旧バージョンDir this.validateAndSetOldDirectory(olddir); // 新バージョンDir this.validateAndSetNewDirectory(newdir); // 計測と出力 this.validatePathOption(this.pathStyleName()); this.validateSortOption(this.sortType()); this.executeCounting(); if (output != null) { this.setOutputStream(output); this.validateFormatOption(this.formatType()); this.writeResults(); } } }
29.452381
107
0.727451
f870113ce0c78bb36d1dbe3d879d27e36a6cc131
1,741
package uk.gov.hmcts.ethos.replacement.docmosis.service; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import uk.gov.hmcts.ethos.replacement.docmosis.helpers.PersistentQHelper; import uk.gov.hmcts.ethos.replacement.docmosis.servicebus.CreateUpdatesBusSender; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static uk.gov.hmcts.ecm.common.model.helper.Constants.NO; import static uk.gov.hmcts.ecm.common.model.helper.Constants.SINGLE_CASE_TYPE; @Slf4j @RequiredArgsConstructor @Service("persistentQHelperService") public class PersistentQHelperService { private final CreateUpdatesBusSender createUpdatesBusSender; private final UserService userService; public void sendCreationEventToSinglesWithoutConfirmation(String userToken, String caseTypeId, String jurisdiction, List<String> errors, String ethosCaseReference, String officeCT, String positionTypeCT, String ccdGatewayBaseUrl) { String username = userService.getUserDetails(userToken).getEmail(); PersistentQHelper.sendSingleUpdatesPersistentQ(caseTypeId, jurisdiction, username, new ArrayList<>(Collections.singletonList(ethosCaseReference)), PersistentQHelper.getCreationSingleDataModel(ccdGatewayBaseUrl, officeCT, positionTypeCT), errors, SINGLE_CASE_TYPE, NO, createUpdatesBusSender, "1"); } }
38.688889
119
0.673751
439b71d909c5dcb256ecbaa5ff1e0d2b18728c0a
318
package dev.vality.wallets.hooker.handler.withdrawal; import dev.vality.fistful.withdrawal.TimestampedChange; import dev.vality.machinegun.eventsink.MachineEvent; import dev.vality.wallets.hooker.handler.EventHandler; public interface WithdrawalEventHandler extends EventHandler<TimestampedChange, MachineEvent> { }
35.333333
95
0.858491
c0200ed67a5cb2afd1ba7c6baacc102ce3fcc3d2
372
package me.haruhime.utils.time; public class TimerUtils { private long past; public TimerUtils() { past = 0; } public boolean hasPassed(float tp) { return (float) (getTime() - past) >= tp; } public long getTime() { return System.nanoTime() / 1000000; } public void renew() { past = getTime(); } }
15.5
48
0.553763
ddd94ff79b761134c6450b0b1039be71dd0a8b7f
197
package com.neko233.forward; import org.junit.jupiter.api.Test; /** * @author SolarisNeko * Date on 2022-04-12 */ public class ForwardEngineTest { @Test public void test() { } }
12.3125
34
0.654822
6f281480699c6232a884b410b3e20a567ecf86bb
6,168
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * 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.p1nesap.ezdungeon.levels; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import com.p1nesap.ezdungeon.EZDungeon; import com.p1nesap.ezdungeon.levels.painters.*; import com.p1nesap.utils.Bundlable; import com.p1nesap.utils.Bundle; import com.p1nesap.utils.Graph; import com.p1nesap.utils.Point; import com.p1nesap.utils.Random; import com.p1nesap.utils.Rect; public class Room extends Rect implements Graph.Node, Bundlable { public HashSet<Room> neigbours = new HashSet<Room>(); public HashMap<Room, Door> connected = new HashMap<Room, Door>(); public int distance; public int price = 1; public static enum Type { NULL( null ), STANDARD ( StandardPainter.class ), ENTRANCE ( EntrancePainter.class ), EXIT ( ExitPainter.class ), BOSS_EXIT ( BossExitPainter.class ), TUNNEL ( TunnelPainter.class ), PASSAGE ( PassagePainter.class ), SHOP ( ShopPainter.class ), BLACKSMITH ( BlacksmithPainter.class ), TREASURY ( TreasuryPainter.class ), ARMORY ( ArmoryPainter.class ), LIBRARY ( LibraryPainter.class ), LABORATORY ( LaboratoryPainter.class ), VAULT ( VaultPainter.class ), TRAPS ( TrapsPainter.class ), STORAGE ( StoragePainter.class ), MAGIC_WELL ( MagicWellPainter.class ), GARDEN ( GardenPainter.class ), CRYPT ( CryptPainter.class ), STATUE ( StatuePainter.class ), POOL ( PoolPainter.class ), RAT_KING ( RatKingPainter.class ), WEAK_FLOOR ( WeakFloorPainter.class ), PIT ( PitPainter.class ); private Method paint; private Type( Class<? extends Painter> painter ) { try { paint = painter.getMethod( "paint", Level.class, Room.class ); } catch (Exception e) { paint = null; } } public void paint( Level level, Room room ) { try { paint.invoke( null, level, room ); } catch (Exception e) { EZDungeon.reportException(e); } } }; public static final ArrayList<Type> SPECIALS = new ArrayList<Type>( Arrays.asList( Type.WEAK_FLOOR, Type.MAGIC_WELL, Type.CRYPT, Type.POOL, Type.GARDEN, Type.LIBRARY, Type.ARMORY, Type.TREASURY, Type.TRAPS, Type.STORAGE, Type.STATUE, Type.LABORATORY, Type.VAULT ) ); public Type type = Type.NULL; public int random() { return random( 0 ); } public int random( int m ) { int x = Random.Int( left + 1 + m, right - m ); int y = Random.Int( top + 1 + m, bottom - m ); return x + y * Level.WIDTH; } public void addNeigbour( Room other ) { Rect i = intersect( other ); if ((i.width() == 0 && i.height() >= 3) || (i.height() == 0 && i.width() >= 3)) { neigbours.add( other ); other.neigbours.add( this ); } } public void connect( Room room ) { if (!connected.containsKey( room )) { connected.put( room, null ); room.connected.put( this, null ); } } public Door entrance() { return connected.values().iterator().next(); } public boolean inside( int p ) { int x = p % Level.WIDTH; int y = p / Level.WIDTH; return x > left && y > top && x < right && y < bottom; } public Point center() { return new Point( (left + right) / 2 + (((right - left) & 1) == 1 ? Random.Int( 2 ) : 0), (top + bottom) / 2 + (((bottom - top) & 1) == 1 ? Random.Int( 2 ) : 0) ); } // **** Graph.Node interface **** @Override public int distance() { return distance; } @Override public void distance( int value ) { distance = value; } @Override public int price() { return price; } @Override public void price( int value ) { price = value; } @Override public Collection<Room> edges() { return neigbours; } @Override public void storeInBundle( Bundle bundle ) { bundle.put( "left", left ); bundle.put( "top", top ); bundle.put( "right", right ); bundle.put( "bottom", bottom ); bundle.put( "type", type.toString() ); } @Override public void restoreFromBundle( Bundle bundle ) { left = bundle.getInt( "left" ); top = bundle.getInt( "top" ); right = bundle.getInt( "right" ); bottom = bundle.getInt( "bottom" ); type = Type.valueOf( bundle.getString( "type" ) ); } public static void shuffleTypes() { int size = SPECIALS.size(); for (int i=0; i < size - 1; i++) { int j = Random.Int( i, size ); if (j != i) { Type t = SPECIALS.get( i ); SPECIALS.set( i, SPECIALS.get( j ) ); SPECIALS.set( j, t ); } } } public static void useType( Type type ) { if (SPECIALS.remove( type )) { SPECIALS.add( type ); } } private static final String ROOMS = "rooms"; public static void restoreRoomsFromBundle( Bundle bundle ) { if (bundle.contains( ROOMS )) { SPECIALS.clear(); for (String type : bundle.getStringArray( ROOMS )) { SPECIALS.add( Type.valueOf( type )); } } else { shuffleTypes(); } } public static void storeRoomsInBundle( Bundle bundle ) { String[] array = new String[SPECIALS.size()]; for (int i=0; i < array.length; i++) { array[i] = SPECIALS.get( i ).toString(); } bundle.put( ROOMS, array ); } public static class Door extends Point { public static enum Type { EMPTY, TUNNEL, REGULAR, UNLOCKED, HIDDEN, BARRICADE, LOCKED } public Type type = Type.EMPTY; public Door( int x, int y ) { super( x, y ); } public void set( Type type ) { if (type.compareTo( this.type ) > 0) { this.type = type; } } } }
24.09375
98
0.649643
96897ab96e3cbd70099bdc2fdac35d01b305ccf5
1,441
/* * Copyright DataStax, Inc. * * 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.datastax.oss.dsbulk.workflow.commons.log; import static org.fusesource.jansi.Ansi.ansi; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.pattern.MessageConverter; import ch.qos.logback.classic.spi.ILoggingEvent; /** * A {@link MessageConverter} that highlights WARN and ERROR messages in bold yellow and bold red * respectively. */ public class HighlightingMessageConverter extends MessageConverter { @Override public String convert(ILoggingEvent event) { String msg = super.convert(event); if (event.getLevel().toInt() == Level.WARN_INT) { msg = ansi().bold().fgYellow().a(event.getFormattedMessage()).reset().toString(); } if (event.getLevel().toInt() >= Level.ERROR_INT) { msg = ansi().bold().fgRed().a(event.getFormattedMessage()).reset().toString(); } return msg; } }
34.309524
97
0.726579
d2f8db4823968dd48da7f54b65d7ac91fa108c4b
3,843
/** */ package org.multicore_association.shim.model.shim; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Power Consumption Set</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link org.multicore_association.shim.model.shim.PowerConsumptionSet#getName <em>Name</em>}</li> * <li>{@link org.multicore_association.shim.model.shim.PowerConsumptionSet#getId <em>Id</em>}</li> * <li>{@link org.multicore_association.shim.model.shim.PowerConsumptionSet#getPowerConsumption <em>Power Consumption</em>}</li> * <li>{@link org.multicore_association.shim.model.shim.PowerConsumptionSet#getPowerConsumerRef <em>Power Consumer Ref</em>}</li> * </ul> * * @see org.multicore_association.shim.model.shim.ShimPackage#getPowerConsumptionSet() * @model extendedMetaData="name='PowerConsumptionSet' kind='elementOnly'" * @generated */ public interface PowerConsumptionSet extends EObject { /** * Returns the value of the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Name</em>' attribute. * @see #setName(String) * @see org.multicore_association.shim.model.shim.ShimPackage#getPowerConsumptionSet_Name() * @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true" * extendedMetaData="kind='attribute' name='name'" * @generated */ String getName(); /** * Sets the value of the '{@link org.multicore_association.shim.model.shim.PowerConsumptionSet#getName <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Name</em>' attribute. * @see #getName() * @generated */ void setName(String value); /** * Returns the value of the '<em><b>Id</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Id</em>' attribute. * @see #setId(String) * @see org.multicore_association.shim.model.shim.ShimPackage#getPowerConsumptionSet_Id() * @model id="true" dataType="org.eclipse.emf.ecore.xml.type.ID" required="true" * extendedMetaData="kind='attribute' name='id'" * @generated */ String getId(); /** * Sets the value of the '{@link org.multicore_association.shim.model.shim.PowerConsumptionSet#getId <em>Id</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Id</em>' attribute. * @see #getId() * @generated */ void setId(String value); /** * Returns the value of the '<em><b>Power Consumption</b></em>' containment reference list. * The list contents are of type {@link org.multicore_association.shim.model.shim.PowerConsumption}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Power Consumption</em>' containment reference list. * @see org.multicore_association.shim.model.shim.ShimPackage#getPowerConsumptionSet_PowerConsumption() * @model containment="true" * extendedMetaData="kind='element' name='PowerConsumption'" * @generated */ EList<PowerConsumption> getPowerConsumption(); /** * Returns the value of the '<em><b>Power Consumer Ref</b></em>' reference list. * The list contents are of type {@link org.multicore_association.shim.model.shim.AbstractComponent}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Power Consumer Ref</em>' reference list. * @see org.multicore_association.shim.model.shim.ShimPackage#getPowerConsumptionSet_PowerConsumerRef() * @model extendedMetaData="kind='element' name='PowerConsumerRef'" * @generated */ EList<AbstractComponent> getPowerConsumerRef(); } // PowerConsumptionSet
38.049505
131
0.686963
65815d48a913b593e26998462798dd03aeba35da
2,698
/* * Copyright 2017 Nemanja Zbiljić * * 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.zbiljic.nodez; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; /** * Predicate switch nodes make a choice based on a predicate and subsequently represents the output * of the chosen node. * <p> * If the predicate is true, then the node set with {@code ifTrue} is used, otherwise the node set * with {@code ifFalse} is used. * <p> * The chosen node is lazily executed, so work is not wasted on the unused node. * * @param <R> return type of the node * @see Node */ public class PredicateSwitchNode<R> extends Node<R> { private final Node<Boolean> predicateNode; private final Node<R> trueNode; private final Node<R> falseNode; public PredicateSwitchNode(Node<Boolean> predicateNode, Node<R> trueNode, Node<R> falseNode) { super(String.format("IF::%s(%s, %s)", predicateNode.getName(), trueNode.getName(), falseNode.getName()), false, allowNull(trueNode, falseNode), predicateNode); this.predicateNode = predicateNode; this.trueNode = Preconditions.checkNotNull(trueNode); this.falseNode = Preconditions.checkNotNull(falseNode); } private static boolean allowNull(final Node trueNode, final Node falseNode) { return trueNode.canEmitNull() || falseNode.canEmitNull(); } @Override protected void logEnd() { super.logEnd(); debugDetailed("predicate value from [%s] = %s", predicateNode.getName(), predicateNode.emit()); } @Override public String getResponseClassName() { return this.trueNode.getResponseClassName(); } @Override protected final CompletableFuture<R> evaluate() throws Exception { return predicateNode.emit() ? trueNode.apply() : falseNode.apply(); } @Override Map<String, Node> getInputsByName() { final Map<String, Node> inputs = new HashMap<>(); inputs.put("condition", predicateNode); inputs.put("TRUE", trueNode); inputs.put("FALSE", falseNode); return Collections.unmodifiableMap(inputs); } }
32.119048
108
0.70089
00e5d2b0dd614c2e2661d76e763857db38d4a343
14,351
package org.ovirt.engine.core.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Named; import javax.inject.Singleton; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.common.businessentities.ArchitectureType; import org.ovirt.engine.core.common.businessentities.QuotaEnforcementTypeEnum; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VmDevice; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.core.dal.dbbroker.DbFacadeUtils; import org.ovirt.engine.core.utils.collections.MultiValueMapUtils; import org.springframework.jdbc.core.RowMapper; /** * <code>VmDAODbFacadeImpl</code> provides a concrete implementation of {@link VmDAO}. The functionality is code * refactored out of {@link Dorg.ovirt.engine.core.dal.dbbroker.DbFacad}. */ @Named @Singleton public class VmDAODbFacadeImpl extends BaseDAODbFacade implements VmDAO { @Override public VM get(Guid id) { return get(id, null, false); } @Override public VM get(Guid id, Guid userID, boolean isFiltered) { return getCallsHandler().executeRead("GetVmByVmGuid", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("vm_guid", id).addValue("user_id", userID).addValue("is_filtered", isFiltered)); } @Override public VM getByNameForDataCenter(Guid dataCenterId, String name, Guid userID, boolean isFiltered) { return getCallsHandler().executeRead("GetVmByVmNameForDataCenter", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("data_center_id", dataCenterId).addValue("vm_name", name).addValue("user_id", userID).addValue("is_filtered", isFiltered)); } @Override public Map<Boolean, List<VM>> getForDisk(Guid id, boolean includeVmsSnapshotAttachedTo) { Map<Boolean, List<VM>> result = new HashMap<Boolean, List<VM>>(); List<Pair<VM, VmDevice>> vms = getVmsWithPlugInfo(id); for (Pair<VM, VmDevice> pair : vms) { VmDevice device = pair.getSecond(); if (includeVmsSnapshotAttachedTo || device.getSnapshotId() == null) { MultiValueMapUtils.addToMap(device.getIsPlugged(), pair.getFirst(), result); } } return result; } @Override public List<VM> getAllVMsWithDisksOnOtherStorageDomain(Guid storageDomainGuid) { return getCallsHandler().executeReadList("GetAllVMsWithDisksOnOtherStorageDomain", VMRowMapper.instance, getCustomMapSqlParameterSource().addValue("storage_domain_id", storageDomainGuid)); } @Override public List<VM> getVmsListForDisk(Guid id, boolean includeVmsSnapshotAttachedTo) { List<VM> result = new ArrayList<>(); List<Pair<VM, VmDevice>> vms = getVmsWithPlugInfo(id); for (Pair<VM, VmDevice> pair : vms) { if (includeVmsSnapshotAttachedTo || pair.getSecond().getSnapshotId() == null) { result.add(pair.getFirst()); } } return result; } @Override public List<VM> getVmsListByInstanceType(Guid id) { return getCallsHandler().executeReadList("GetVmsByInstanceTypeId", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("instance_type_id", id)); } public List<Pair<VM, VmDevice>> getVmsWithPlugInfo(Guid id) { return getCallsHandler().executeReadList ("GetVmsByDiskId", VMWithPlugInfoRowMapper.instance, getCustomMapSqlParameterSource().addValue("disk_guid", id)); } @Override public List<VM> getAllForUser(Guid id) { return getCallsHandler().executeReadList("GetVmsByUserId", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("user_id", id)); } @Override public List<VM> getAllForUserWithGroupsAndUserRoles(Guid id) { return getCallsHandler().executeReadList("GetVmsByUserIdWithGroupsAndUserRoles", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("user_id", id)); } @Override public List<VM> getAllForAdGroupByName(String name) { return getCallsHandler().executeReadList("GetVmsByAdGroupNames", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("ad_group_names", name)); } @Override public List<VM> getAllWithTemplate(Guid id) { return getCallsHandler().executeReadList("GetVmsByVmtGuid", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("vmt_guid", id)); } @Override public List<VM> getAllRunningForVds(Guid id) { return getCallsHandler().executeReadList("GetVmsRunningOnVds", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("vds_id", id)); } @Override public List<VM> getAllRunningOnOrMigratingToVds(Guid id) { return getCallsHandler().executeReadList("GetVmsRunningOnOrMigratingToVds", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("vds_id", id)); } @Override public Map<Guid, VM> getAllRunningByVds(Guid id) { HashMap<Guid, VM> map = new HashMap<Guid, VM>(); for (VM vm : getAllRunningForVds(id)) { map.put(vm.getId(), vm); } return map; } @Override public List<VM> getAllUsingQuery(String query) { return getJdbcTemplate().query(query, VMRowMapper.instance); } @Override public List<VM> getAllForStorageDomain(Guid id) { return getCallsHandler().executeReadList("GetVmsByStorageDomainId", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("storage_domain_id", id)); } @Override public List<VM> getAllVmsRelatedToQuotaId(Guid quotaId) { return getCallsHandler().executeReadList("getAllVmsRelatedToQuotaId", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("quota_id", quotaId)); } @Override public List<VM> getVmsByIds(List<Guid> vmsIds) { return getCallsHandler().executeReadList("GetVmsByIds", VMRowMapper.instance, getCustomMapSqlParameterSource().addValue("vms_ids", StringUtils.join(vmsIds, ','))); } @Override public List<VM> getAllActiveForStorageDomain(Guid id) { return getCallsHandler().executeReadList("GetActiveVmsByStorageDomainId", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("storage_domain_id", id)); } @Override public List<VM> getAll() { return getAll(null, false); } @Override public List<VM> getAll(Guid userID, boolean isFiltered) { return getCallsHandler().executeReadList("GetAllFromVms", VMRowMapper.instance, getCustomMapSqlParameterSource().addValue("user_id", userID).addValue("is_filtered", isFiltered)); } @Override public void saveIsInitialized(Guid vmid, boolean isInitialized) { getCallsHandler().executeModification("UpdateIsInitialized", getCustomMapSqlParameterSource() .addValue("vm_guid", vmid) .addValue("is_initialized", isInitialized)); } @Override public void remove(Guid id) { getCallsHandler().executeModification("DeleteVm", getCustomMapSqlParameterSource() .addValue("vm_guid", id)); } @Override public List<VM> getAllForNetwork(Guid id) { return getCallsHandler().executeReadList("GetVmsByNetworkId", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("network_id", id)); } @Override public List<VM> getAllForVnicProfile(Guid vNicProfileId) { return getCallsHandler().executeReadList("GetVmsByVnicProfileId", VMRowMapper.instance, getCustomMapSqlParameterSource().addValue("vnic_profile_id", vNicProfileId)); } @Override public List<VM> getAllForVdsGroup(Guid vds_group_id) { return getCallsHandler().executeReadList("GetVmsByVdsGroupId", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("vds_group_id", vds_group_id)); } @Override public List<VM> getAllForVmPool(Guid vmPoolId) { return getCallsHandler().executeReadList("GetVmsByVmPoolId", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("vm_pool_id", vmPoolId)); } @Override public List<VM> getAllFailedAutoStartVms() { return getCallsHandler().executeReadList("GetFailedAutoStartVms", VMRowMapper.instance, getCustomMapSqlParameterSource()); } @Override public List<VM> getAllMigratingToHost(Guid vdsId) { return getCallsHandler().executeReadList("GetVmsMigratingToVds", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("vds_id", vdsId)); } @Override public void updateOriginalTemplateName(Guid originalTemplateId, String originalTemplateName) { getCallsHandler().executeModification("UpdateOriginalTemplateName", getCustomMapSqlParameterSource() .addValue("original_template_id", originalTemplateId) .addValue("original_template_name", originalTemplateName) ); } @Override public List<VM> getAllRunningByCluster(Guid clusterId) { return getCallsHandler().executeReadList("GetRunningVmsByClusterId", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("cluster_id", clusterId)); } @Override public List<Guid> getVmIdsForVersionUpdate(Guid baseTemplateId) { return getCallsHandler().executeReadList("getVmIdsForVersionUpdate", createGuidMapper(), getCustomMapSqlParameterSource() .addValue("base_template_id", baseTemplateId)); } @Override public List<VM> getAllForStoragePool(Guid storagePoolId) { return getCallsHandler().executeReadList("GetAllForStoragePool", VMRowMapper.instance, getCustomMapSqlParameterSource() .addValue("storage_pool_id", storagePoolId)); } static final class VMRowMapper implements RowMapper<VM> { public static final VMRowMapper instance = new VMRowMapper(); @Override public VM mapRow(ResultSet rs, int rowNum) throws SQLException { VM entity = new VM(); entity.setStaticData(VmStaticDAODbFacadeImpl.getRowMapper().mapRow(rs, rowNum)); entity.setDynamicData(VmDynamicDAODbFacadeImpl.getRowMapper().mapRow(rs, rowNum)); entity.setStatisticsData(VmStatisticsDaoDbFacadeImpl.getRowMapper().mapRow(rs, rowNum)); entity.setQuotaName(rs.getString("quota_name")); entity.setQuotaEnforcementType(QuotaEnforcementTypeEnum.forValue(rs.getInt("quota_enforcement_type"))); entity.setVdsGroupName(rs.getString("vds_group_name")); entity.setVdsGroupDescription(rs.getString("vds_group_description")); entity.setVmtName(rs.getString("vmt_name")); entity.setVmtMemSizeMb(rs.getInt("vmt_mem_size_mb")); entity.setVmtOsId(rs.getInt("vmt_os")); entity.setVmtCreationDate(DbFacadeUtils.fromDate(rs.getTimestamp("vmt_creation_date"))); entity.setVmtChildCount(rs.getInt("vmt_child_count")); entity.setVmtNumOfCpus(rs.getInt("vmt_num_of_cpus")); entity.setVmtNumOfSockets(rs.getInt("vmt_num_of_sockets")); entity.setVmtCpuPerSocket(rs.getInt("vmt_cpu_per_socket")); entity.setVmtDescription(rs.getString("vmt_description")); entity.setVmPoolName(rs.getString("vm_pool_name")); entity.setVmPoolId(getGuid(rs, "vm_pool_id")); entity.setRunOnVdsName(rs.getString("run_on_vds_name")); entity.setVdsGroupCpuName(rs.getString("vds_group_cpu_name")); entity.setStoragePoolId(getGuidDefaultEmpty(rs, "storage_pool_id")); entity.setStoragePoolName(rs.getString("storage_pool_name")); entity.setTransparentHugePages(rs.getBoolean("transparent_hugepages")); entity.setVdsGroupCompatibilityVersion(new Version(rs.getString("vds_group_compatibility_version"))); entity.setTrustedService(rs.getBoolean("trusted_service")); entity.setClusterArch(ArchitectureType.forValue(rs.getInt("architecture"))); entity.setVmPoolSpiceProxy(rs.getString("vm_pool_spice_proxy")); entity.setVdsGroupSpiceProxy(rs.getString("vds_group_spice_proxy")); entity.setNextRunConfigurationExists(rs.getBoolean("next_run_config_exists")); return entity; } } private static final class VMWithPlugInfoRowMapper implements RowMapper<Pair<VM, VmDevice>> { public static final VMWithPlugInfoRowMapper instance = new VMWithPlugInfoRowMapper(); @Override public Pair<VM, VmDevice> mapRow(ResultSet rs, int rowNum) throws SQLException { @SuppressWarnings("synthetic-access") Pair<VM, VmDevice> entity = new Pair<>(); entity.setFirst(VMRowMapper.instance.mapRow(rs, rowNum)); entity.setSecond(VmDeviceDAODbFacadeImpl.VmDeviceRowMapper.instance.mapRow(rs, rowNum)); return entity; } } }
41.002857
149
0.658421
9c27a387be997d4cb27f3584b4fdfe12a1db8e97
1,177
package com.ABC.bitrade.entity; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; /** * 邀请日榜、周榜、月榜排名数据 * @author shaox * */ @Entity @Data public class MemberInviteStasticRank { @GeneratedValue(strategy = GenerationType.IDENTITY) @Id private Long id; private Long memberId; /** * 用户账户标识,手机或邮箱 */ private String userIdentify; /** * 邀请一级好友数量 */ private int levelOne; /** * 邀请二级好友数量 */ private int levelTwo; /** * 类型:0 = 日榜,1 = 周榜, 2 = 月榜 */ @NotNull private int type; /** * 是否机器人(0:否,1:是) */ @JsonIgnore private int isRobot = 0; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date stasticDate; }
18.390625
68
0.677145
8d996083984df64127b81ab0a47a8b6634d7e85c
2,364
package com.dong.lib.common.di.component; import android.app.Application; import android.content.Context; import com.dong.lib.common.base.delegate.AppDelegate; import com.dong.lib.common.di.module.AppModule; import com.dong.lib.common.di.module.ClientModule; import com.dong.lib.common.di.module.GlobalConfigModule; import com.dong.lib.common.http.imageloader.ImageLoader; import com.dong.lib.common.integration.AppManager; import com.dong.lib.common.integration.IRepositoryManager; import com.dong.lib.common.integration.cache.Cache; import com.dong.lib.common.utils.Utils; import com.google.gson.Gson; import java.io.File; import javax.inject.Singleton; import dagger.BindsInstance; import dagger.Component; import me.jessyan.rxerrorhandler.core.RxErrorHandler; import okhttp3.OkHttpClient; /** * ================================================ * Component:是组件,也可以称为注入器。 * 是@Inject和@Module之间的桥梁,主要职责是把二者组合在一起。 * <p> * Component 注解用来标记接口或者抽象类。 * 所有的components都可以通过它的 modules 知道它所提供的依赖范围。 * 一个Component可以依赖一个或多个Component,并拿到被依赖Component暴露出来的实例, * Component的 dependencies 属性就是确定依赖关系的实现。 * <p> * 可通过 {@link Utils#obtainAppComponentFromContext(Context)} 拿到此接口的实现类 * 拥有此接口的实现类即可调用对应的方法拿到 Dagger 提供的对应实例 * Created by xiaoyulaoshi on 2018/3/21. * <p> * ================================================ */ @Singleton @Component(modules = {AppModule.class, ClientModule.class, GlobalConfigModule.class}) public interface AppComponent { //Application单例 Application application(); //用于管理所有 activity AppManager appManager(); //用于管理网络请求层,以及数据缓存层 IRepositoryManager repositoryManager(); //RxJava 错误处理管理类 RxErrorHandler rxErrorHandler(); //图片管理器,用于加载图片的管理类,默认使用 Glide ,使用策略模式,可在运行时替换框架 ImageLoader imageLoader(); OkHttpClient okHttpClient(); //gson Gson gson(); //缓存文件根目录(RxCache 和 Glide 的缓存都已经作为子文件夹放在这个根目录下),应该将所有缓存都放到这个根目录下,便于管理和清理,可在 GlobalConfigModule 里配置 File cacheFile(); //用来存取一些整个App公用的数据,切勿大量存放大容量数据 Cache<String, Object> extras(); //用于创建框架所需缓存对象的工厂 Cache.Factory cacheFactory(); void inject(AppDelegate delegate); @Component.Builder interface Builder { @BindsInstance Builder application(Application application); Builder globalConfigModule(GlobalConfigModule globalConfigModule); AppComponent build(); } }
27.172414
102
0.730541
26a9233360d20b573188328ce6f488e484551bfe
1,276
package ${rootPackage}; import com.google.gwt.core.client.EntryPoint; import org.dominokit.domino.ui.Typography.Paragraph; import org.dominokit.domino.ui.cards.Card; import org.dominokit.domino.ui.icons.Icons; import org.dominokit.domino.ui.layout.Layout; import org.dominokit.domino.ui.style.ColorScheme; import org.dominokit.domino.ui.tree.Tree; import org.dominokit.domino.ui.tree.TreeItem; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class App implements EntryPoint { /** * This is the entry point method. */ public void onModuleLoad() { var layout = Layout.create("Domino-ui starter") .show(ColorScheme.BLUE); layout.getLeftPanel() .appendChild(Tree.create("Menu") .appendChild(TreeItem.create("Menu 1", Icons.ALL.widgets())) .appendChild(TreeItem.create("Menu 2", Icons.ALL.widgets())) .addItemClickListener(treeItem -> { layout.setContent(Card.create(treeItem.getValue()) .appendChild(Paragraph.create("Welcome to domino-ui , you are viewing "+treeItem.getValue()+" content"))); }) ); } }
36.457143
142
0.615204
3f3d64720d16071b279a4f6ed7c0f64aa61a80d5
3,267
/* * Copyright (C) 2013 Google Inc. * * 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 interactivespaces.workbench.project.constituent; import interactivespaces.InteractiveSpacesException; import interactivespaces.workbench.project.Project; import interactivespaces.workbench.project.ProjectContext; import org.apache.commons.logging.Log; import org.jdom.Element; import java.io.File; /** * Interface for project constituents. * * @author Trevor Pering */ public interface ProjectConstituent { /** * Attribute value specifying a source file. */ String SOURCE_FILE_ATTRIBUTE = "sourceFile"; /** * Attribute value specifying a source directory. */ String SOURCE_DIRECTORY_ATTRIBUTE = "sourceDirectory"; /** * Attribute value specifying a destination file. */ String DESTINATION_FILE_ATTRIBUTE = "destinationFile"; /** * Attribute value specifying a destination directory. */ String DESTINATION_DIRECTORY_ATTRIBUTE = "destinationDirectory"; /** * Process the needed constituent for the project. * * @param project * the project being built * @param stagingDirectory * where the items will be copied * @param context * project context in which to process the constituent */ void processConstituent(Project project, File stagingDirectory, ProjectContext context); /** * Return the source directory for this constituent. * * @return source directory * * @throws InteractiveSpacesException * if constituent type does not provide a source directory */ String getSourceDirectory() throws InteractiveSpacesException; /** * Factory for project constituent builders. * * @author Keith M. Hughes */ interface ProjectConstituentFactory { /** * Get the type name of this project constituent. * * @return constituent type name */ String getName(); /** * Create a new builder. * * @return the new builder */ ProjectConstituentBuilder newBuilder(); } /** * Builder interface for creating new constituent instances. */ interface ProjectConstituentBuilder { /** * Get a new constituent of the appropriate type. * * @param constituentElement * project file definition element * @param project * the project description being built * * @return new project object or {@code null} if there were errors */ ProjectConstituent buildConstituentFromElement(Element constituentElement, Project project); /** * Set the logging provider for use by the builder. * * @param log * logging provider to use */ void setLog(Log log); } }
26.346774
96
0.689317
f1de6a7978726897da0fdbc75e3333d9a3f0a012
4,756
/* * 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 cn.zhengcaiyun.idata.user.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.swagger.annotations.ApiModelProperty; import java.util.Date; import java.util.List; /** * @author shiyin * @date 2021-03-03 00:08 */ @JsonIgnoreProperties({"token"}) public class UserInfoDto { private Long id; private Integer del; private String creator; private Date createTime; private String editor; private Date editTime; private String username; @ApiModelProperty(value = "是否系统管理员,0:否,1:是,2:其他系统管理员") private Integer sysAdmin; private String authType; private String password; private String token; private String nickname; private String employeeId; private String department; private String realName; private String avatar; private String email; private String mobile; private List<String> roleCodes; private List<String> roleNames; // GaS public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getDel() { return del; } public void setDel(Integer del) { this.del = del; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getEditor() { return editor; } public void setEditor(String editor) { this.editor = editor; } public Date getEditTime() { return editTime; } public void setEditTime(Date editTime) { this.editTime = editTime; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getSysAdmin() { return sysAdmin; } public void setSysAdmin(Integer sysAdmin) { this.sysAdmin = sysAdmin; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getEmployeeId() { return employeeId; } public void setEmployeeId(String employeeId) { this.employeeId = employeeId; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public List<String> getRoleCodes() { return roleCodes; } public void setRoleCodes(List<String> roleCodes) { this.roleCodes = roleCodes; } public List<String> getRoleNames() { return roleNames; } public void setRoleNames(List<String> roleNames) { this.roleNames = roleNames; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAuthType() { return authType; } public void setAuthType(String authType) { this.authType = authType; } }
22.224299
75
0.641295
a53ec80ee4cf6747e3283d4cf7d608ec948d36e0
1,178
package me.zhengjie.modules.qe.repository; import me.zhengjie.modules.qe.domain.EnvironmentBaseGroup; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; public interface EnvironmentBaseGroupRepository extends JpaRepository<EnvironmentBaseGroup,Integer> { @Query(value = "select * from environment_base_group where " +"zone = :zone",nativeQuery = true) //nativeQuery代表开启原生sql写法 :date是传入下方名为date的参数 Page<EnvironmentBaseGroup> findAllByZone(@Param("zone") String zone, Pageable pageable); @Query(value = "select * from environment_base_group where " +"zone = :zone and"+" date = :date",nativeQuery = true) List<EnvironmentBaseGroup> findAllByZoneAndYear(@Param("zone") String zone, @Param("date") String date); @Query(value = "select * from environment_base_group where " +" date = :date",nativeQuery = true) List<EnvironmentBaseGroup> findAllByDate(@Param("date") String date);//纯粹按月份查找数据 所以excel的数据格式绝对不能错 }
51.217391
146
0.782683
f99a4db604b07ce22f4540b50c58ba6a77252c87
3,525
package com.rommelrico.exercises.s7queuesandstacks.queuewithtwostacks; import java.util.NoSuchElementException; import java.util.Stack; /** * Solution * * Let's call our stacks inStack and outStack. * * For enqueue, we simply push the enqueued item onto inStack. * * For dequeue on an empty outStack, the oldest item is at the bottom of inStack. So we dig to the bottom of inStack * by pushing each item one-by-one onto outStack until we reach the bottom item, which we return. * * After moving everything from inStack to outStack, the item that was enqueued the 2nd longest ago (after the item * we just returned) is at the top of outStack, the item enqueued 3rd longest ago is just below it, etc. So to * dequeue on a non-empty outStack, we simply return the top item from outStack. * * Complexity * * Each enqueue is O(1) time, and so is each dequeue when outStack has items. Dequeue on an empty outStack is order * of the number of items in inStack at that moment, which can vary significantly. * * Notice that the more expensive a dequeue on an empty outStack is (that is, the more items we have to move from * inStack to outStack), the more O(1)-time dequeues off of a non-empty outStack it wins us in the future. Once items * are moved from inStack to outStack they just sit there, ready to be dequeued in O(1) time. An item never moves * "backwards" in our data structure. * * We might guess that this "averages out" so that in a set of m enqueues and dequeues the total cost of all dequeues * is actually just O(m). To check this rigorously, we can use the accounting method, counting the time cost per item * instead of per enqueue or dequeue. * * So let's look at the worst case for a single item, which is the case where it is enqueued and then later dequeued. * In this case, the item enters inStack (costing 1 push), then later moves to outStack (costing 1 pop and 1 push), * then later comes off outStack to get returned (costing 1 pop). * * Each of these 4 pushes and pops is O(1) time. So our total cost per item is O(1). Our m enqueue and dequeue * operations put m or fewer items into the system, giving a total runtime of O(m). * * What We Learned * * People often struggle with the runtime analysis for this one. The trick is to think of the cost per item passing * through our queue, rather than the cost per enqueue() and dequeue(). * * This trick generally comes in handy when you're looking at the time cost of not just one call, but "m" calls. * */ public class QueueWithTwoStacks { private Stack<Integer> inStack = new Stack<>(); private Stack<Integer> outStack = new Stack<>(); public void enqueue(int item) { inStack.push(item); } public int dequeue() { if (outStack.empty()) { // Move items from inStack to outStack, reversing order while (!inStack.empty()) { int newestInStackItem = inStack.pop(); outStack.push(newestInStackItem); } // If outStack is still empty, raise an error if (outStack.empty()) { throw new NoSuchElementException("Can't dequeue from empty queue!"); } } return outStack.pop(); } public static void main(String[] args) { QueueWithTwoStacks queue = new QueueWithTwoStacks(); queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); queue.dequeue(); queue.dequeue(); queue.dequeue(); } }
41.964286
117
0.689362
d72450ccfa7417b6da24f8abefed43a5cde521eb
1,882
package com.service.framework.jdbc.interceptor; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.DefaultReflectorFactory; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.SystemMetaObject; import java.sql.Connection; import java.util.Properties; @Intercepts({ @Signature( // 只能是: StatementHandler | ParameterHandler | ResultSetHandler | Executor 类或者子类 type = StatementHandler.class, // StatementHandler (prepare, parameterize, batch, update, query) // ResultSetHandler (handleResultSets, handleOutputParameters) // ParameterHandler (getParameterObject, setParameters) // Executor (update, query, flushStatements, commit, rollback,getTransaction, close, isClosed) method = "prepare", args = {Connection.class, Integer.class} ) }) public class MyCatInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { StatementHandler handler = (StatementHandler) invocation.getTarget(); // 获取指定对象的元信息 MetaObject metaObject = MetaObject.forObject( handler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory() ); metaObject.setValue("delegate.boundSql.sql", handler.getBoundSql().getSql().replace("/*!mycat:", "/* mycat:")); return invocation.proceed(); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { } }
37.64
119
0.679065
c8e284084d9e8fd007dd0c118c1c26adeab0d3c9
2,136
package cn.codethink.xiaoming.contact; import cn.codethink.common.util.Preconditions; import lombok.Data; /** * Qq 群设置项 * * @author Chuanwise */ @Data public class QqGroupConfiguration implements GroupConfiguration { private final QqGroup group; public QqGroupConfiguration(QqGroup group) { Preconditions.nonNull(group, "group"); this.group = group; } @Override public String getName() { group.assertBotIsInGroup(); return group.qqGroup.getName(); } @Override public void setName(String name) { group.assertBotIsInGroup(); group.qqGroup.setName(name); } @Override public boolean isAllowMemberInvite() { group.assertBotIsInGroup(); return group.qqGroup.getSettings().isAllowMemberInvite(); } @Override public void setAllowMemberInvite(boolean allowMemberInvite) { group.assertBotIsInGroup(); group.qqGroup.getSettings().setAllowMemberInvite(allowMemberInvite); } @Override public boolean isAllowAnonymousChat() { group.assertBotIsInGroup(); return group.qqGroup.getSettings().isAnonymousChatEnabled(); } @Override public void setAllowAnonymousChat(boolean allowAnonymousChat) { group.assertBotIsInGroup(); group.qqGroup.getSettings().setAnonymousChatEnabled(allowAnonymousChat); } @Override public boolean isAutoAcceptMemberAddRequest() { group.assertBotIsInGroup(); return group.qqGroup.getSettings().isAutoApproveEnabled(); } // @Override // public void setAutoAcceptMemberAddRequest(boolean autoAcceptMemberAddRequest) { // group.assertBotIsInGroup(); // group.qqGroup.getSettings().setA(muteAll); // } @Override public boolean isMuteAll() { group.assertBotIsInGroup(); return group.qqGroup.getSettings().isMuteAll(); } @Override public void setMuteAll(boolean muteAll) { group.assertBotIsInGroup(); group.qqGroup.getSettings().setMuteAll(muteAll); } }
26.04878
85
0.660581
6ffbfc88ac13bad049bdc1cce547237bc844ec41
4,206
package io.fluidity.search.agg.histo; import io.fluidity.util.DateUtil; import org.graalvm.collections.Pair; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.junit.jupiter.api.Test; import java.util.List; import java.util.stream.Collectors; import static io.fluidity.util.DateUtil.HOUR; import static io.fluidity.util.DateUtil.MINUTE; import static io.fluidity.util.DateUtil.floorDay; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class OverlayTimeSeriesTest { @Test public void testReproduceOffsetBug() throws Exception { // reproduce // events at 12:30 // use time series overlay at 1430pm projects to 1400-1500 - for 24 hours. // should see events at 14:30 // long today = floorDay(System.currentTimeMillis()); DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("HH:mm.SS"); long from = today + dateTimeFormatter.parseDateTime("01:00.00").getMillis(); long to = today + dateTimeFormatter.parseDateTime("15:45.00").getMillis(); Series<Long> series = new OverlayTimeSeries<>("someFile", "", from, to, new Series.LongOps()); DateTime localTime = dateTimeFormatter.parseDateTime("12:30.00"); long millis = today + localTime.getMillis(); series.update(millis, 100l); long getTime = today + dateTimeFormatter.parseDateTime("15:30.00").getMillis(); long translatedHits = series.get(getTime); System.out.println("Got Data:" + series.data()); List<Pair<Long, Long>> found = series.data().stream().filter(dataPair -> dataPair.getRight() != null).collect(Collectors.toList()); assertEquals(1, found.size(), "Didn't get any hits!"); System.out.println("Got Hits at:" + dateTimeFormatter.print(found.get(0).getRight())); assertEquals(100, translatedHits); } @Test public void testStandardTimeSeries() throws Exception { long last = System.currentTimeMillis(); long from = last - HOUR; Series series = new OverlayTimeSeries("someFile", "", from, last, new Series.LongOps()); assertFalse(series.hasData()); testBucket("From Bucket", from, series, false); testBucket("From Bucket+1000", from + 1000, series, false); testBucket("Middle Bucket", from + 30 * MINUTE, series, false); testBucket("Last Bucket", last, series, false); } @Test public void testOutOfBoundsOverlay() throws Exception { long last = System.currentTimeMillis(); long from = last - HOUR; Series series = new OverlayTimeSeries("someFile", "", from, last, new Series.LongOps()); assertFalse(series.hasData()); // bounds testing testBucket("Before From Bucket", from - MINUTE, series, false); testBucket("Last Bucket-1000", last - 1000, series, false); testBucket("Last Bucket+1000", last + 1000, series, false); // dont support bounds in the future - only historic testBucket("Last Bucket+1H", last + HOUR, series, true); assertTrue(series.hasData()); } @Test public void testUpdateMatchesAcrossDifferentBounds() throws Exception { long last = System.currentTimeMillis(); long from = last - HOUR; Series series = new OverlayTimeSeries("someData", "", from, last, new Series.LongOps()); long expectedFrom = DateUtil.ceilHour(last)-HOUR; // First bucket assertEquals(0, series.index(expectedFrom)); // First bucket - but 1 span before - it should map to the first bucket long time = expectedFrom - HOUR + 10; assertEquals(0, series.index(time)); } private void testBucket(String message, long time, Series<Long> series, boolean shouldFail) { long value = 1234; series.update(time, value); Long returnedValue = series.get(time); if (!shouldFail) { assertEquals(value, returnedValue, message); } } }
35.344538
139
0.66524
aaf96e4664858b71862d71c605134c26a522e3ba
627
/* * Copyright (C) 2017 Orange * * This software is distributed under the terms and conditions of the 'Apache-2.0' * license which can be found in the file 'LICENSE.txt' in this package distribution * or at 'http://www.apache.org/licenses/LICENSE-2.0'. */ package com.orange.oswe.demo.woofer.webfront.clients; import com.orange.oswe.demo.woofer.webfront.domain.User; import feign.Param.Expander; public class ToUserUriExpander implements Expander { @Override public String expand(Object value) { if(value instanceof User) { return "/users/"+((User)value).getId(); } else { return "/users/"+value; } } }
26.125
84
0.720893
4397ac0d38df59d46043f7e505d1a2feb629e503
2,927
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. */ package com.microsoft.embeddedsocial.ui.fragment; import com.microsoft.embeddedsocial.base.event.EventBus; import com.microsoft.embeddedsocial.data.model.AccountData; import com.microsoft.embeddedsocial.event.data.ProfileDataUpdatedEvent; import com.microsoft.embeddedsocial.event.relationship.UserFollowedStateChangedEvent; import com.microsoft.embeddedsocial.fetcher.FetchersFactory; import com.microsoft.embeddedsocial.fetcher.base.Callback; import com.microsoft.embeddedsocial.fetcher.base.Fetcher; import com.microsoft.embeddedsocial.sdk.R; import com.microsoft.embeddedsocial.service.IntentExtras; import com.microsoft.embeddedsocial.ui.adapter.ProfileInfoAdapter; import com.microsoft.embeddedsocial.ui.fragment.base.BaseListContentFragment; import com.squareup.otto.Subscribe; import android.content.Context; import android.os.Bundle; /** * Shows user's profile. */ public class ProfileInfoFragment extends BaseListContentFragment<ProfileInfoAdapter> { private String userHandle; private Fetcher<AccountData> fetcher; public ProfileInfoFragment() { addThemeToMerge(R.style.EmbeddedSocialSdkThemeOverlayFeed); } @Override public void onAttach(Context context) { super.onAttach(context); Bundle arguments = getArguments(); userHandle = arguments.getString(IntentExtras.USER_HANDLE); } @Override protected ProfileInfoAdapter createInitialAdapter() { if (fetcher == null) { fetcher = FetchersFactory.createProfileFetcher(userHandle); } ProfileInfoAdapter adapter = new ProfileInfoAdapter(this, fetcher, userHandle); adapter.addFetcherCallback(new Callback() { @Override public void onDataRequestSucceeded() { notifyDataUpdatedIfNeeded(); } }); return adapter; } @Override public void onResume() { super.onResume(); notifyDataUpdatedIfNeeded(); } protected void notifyDataUpdatedIfNeeded() { ProfileInfoAdapter adapter = getAdapter(); if (adapter.getDataSize() > 0) { EventBus.post(new ProfileDataUpdatedEvent(userHandle, adapter.getItem(0))); } } @Subscribe public void onFollowedStatusChanged(UserFollowedStateChangedEvent event) { if (event.isForUser(userHandle)) { getAdapter().onFollowedStatusChanged(event.getFollowedStatus()); } } public static ProfileInfoFragment create(String userHandle) { ProfileInfoFragment fragment = new ProfileInfoFragment(); Bundle arguments = new Bundle(); arguments.putString(IntentExtras.USER_HANDLE, userHandle); fragment.setArguments(arguments); return fragment; } }
33.643678
91
0.724291
b07d1097419c72253c15e34dfec69d72e3378814
6,880
/* * Copyright © 2015 Cask Data, Inc. * * 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 co.cask.cdap.notifications.service; import co.cask.cdap.common.service.UncaughtExceptionIdleService; import co.cask.cdap.data2.dataset2.DatasetFramework; import co.cask.cdap.data2.transaction.TransactionSystemClientService; import co.cask.cdap.notifications.NotificationFeedInfoDeserializer; import co.cask.cdap.notifications.feeds.NotificationFeedException; import co.cask.cdap.notifications.feeds.NotificationFeedManager; import co.cask.cdap.notifications.feeds.NotificationFeedNotFoundException; import co.cask.cdap.notifications.service.inmemory.InMemoryNotificationService; import co.cask.cdap.proto.id.NotificationFeedId; import co.cask.cdap.proto.notification.NotificationFeedInfo; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.util.concurrent.ListenableFuture; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import org.apache.twill.common.Cancellable; import org.apache.twill.common.Threads; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Type; import java.util.Collection; import java.util.concurrent.Executor; /** * Common implementation of the the {@link NotificationService} that handles the subscriptions to all the notification * feeds for the current process and that has the ability to push notifications to subscribers. */ public abstract class AbstractNotificationService extends UncaughtExceptionIdleService implements NotificationService { private static final Logger LOG = LoggerFactory.getLogger(InMemoryNotificationService.class); protected static final Gson GSON = new GsonBuilder() .enableComplexMapKeySerialization() .registerTypeAdapter(NotificationFeedInfo.class, new NotificationFeedInfoDeserializer()) .create(); private final Multimap<NotificationFeedId, NotificationCaller<?>> subscribers; private final DatasetFramework dsFramework; private final TransactionSystemClientService transactionSystemClient; private final NotificationFeedManager feedManager; protected AbstractNotificationService(DatasetFramework dsFramework, TransactionSystemClientService transactionSystemClient, NotificationFeedManager feedManager) { this.dsFramework = dsFramework; this.transactionSystemClient = transactionSystemClient; this.feedManager = feedManager; this.subscribers = Multimaps.synchronizedMultimap( HashMultimap.<NotificationFeedId, NotificationCaller<?>>create()); } @Override protected void startUp() throws Exception { transactionSystemClient.startAndWait(); } @Override protected void shutDown() throws Exception { transactionSystemClient.stopAndWait(); } /** * Called when a notification is received on a feed, to push it to all the handlers that subscribed to the feed. * * @param feed {@link NotificationFeedId} of the notification * @param notificationJson notification as a json object */ protected void notificationReceived(NotificationFeedId feed, JsonElement notificationJson) { LOG.trace("Notification received on feed {}: {}", feed, notificationJson); Collection<NotificationCaller<?>> callers = subscribers.get(feed); synchronized (subscribers) { callers = ImmutableList.copyOf(callers); } for (NotificationCaller caller : callers) { Object notification = GSON.fromJson(notificationJson, caller.getNotificationType()); caller.received(notification, new BasicNotificationContext(feed.getParent(), dsFramework, transactionSystemClient)); } } @Override public <N> ListenableFuture<N> publish(NotificationFeedId feed, N notification) throws NotificationException { return publish(feed, notification, notification.getClass()); } @Override public <N> Cancellable subscribe(NotificationFeedId feed, NotificationHandler<N> handler) throws NotificationFeedNotFoundException, NotificationFeedException { return subscribe(feed, handler, Threads.SAME_THREAD_EXECUTOR); } @Override public <N> Cancellable subscribe(NotificationFeedId feed, NotificationHandler<N> handler, Executor executor) throws NotificationFeedNotFoundException, NotificationFeedException { // This call will make sure that the feed exists feedManager.getFeed(feed); NotificationCaller<N> caller = new NotificationCaller<>(feed, handler, executor); subscribers.put(feed, caller); return caller; } @Override protected Logger getUncaughtExceptionLogger() { return LOG; } /** * Wrapper around a {@link NotificationHandler}, containing a reference to a {@link NotificationHandler} * and a {@link NotificationFeedId}. * * @param <N> Type of the Notification to handle */ private class NotificationCaller<N> implements NotificationHandler<N>, Cancellable { private final NotificationFeedId feed; private final NotificationHandler<N> handler; private final Executor executor; private volatile boolean completed; NotificationCaller(NotificationFeedId feed, NotificationHandler<N> handler, Executor executor) { this.feed = feed; this.handler = handler; this.executor = executor; } @Override public Type getNotificationType() { return handler.getNotificationType(); } @Override public void received(final N notification, final NotificationContext notificationContext) { if (completed) { return; } executor.execute(new Runnable() { @Override public void run() { if (completed) { return; } try { handler.received(notification, notificationContext); } catch (Throwable t) { LOG.warn("Notification {} on feed {} could not be processed successfully by handler {}", notification, feed, handler, t); } } }); } @Override public void cancel() { completed = true; subscribers.remove(feed, this); } } }
38.01105
119
0.738517
533d833089b716f533d3b8a236b494bc6949fbd9
3,354
package wcsdata.xmen.controller.crud_html; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.http.MediaType; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.servlet.function.RouterFunction; import org.springframework.web.servlet.function.ServerRequest; import org.springframework.web.servlet.function.ServerResponse; import org.springframework.web.servlet.support.RequestContext; import wcsdata.xmen.controller.AbstractCrudController; import wcsdata.xmen.entity.CerebookUser; import wcsdata.xmen.model.UserDetailsWrapper; import wcsdata.xmen.repository.CerebookUserRepository; import javax.servlet.http.HttpServletRequest; import java.lang.annotation.Annotation; import java.security.Principal; import static org.springframework.web.servlet.function.RequestPredicates.accept; import static org.springframework.web.servlet.function.RouterFunctions.route; public abstract class AbstractCrudHtmlController<E, EK> extends AbstractCrudController<E, EK> { // <editor-fold desc="Route methods"> @GetMapping("") public String getAll(Model model) { model.addAttribute("allElements", getRepository().findAll()); addCommonModel(model); return getControllerRoute() + "/getAll"; } @GetMapping("rest") public String getAllWithRest(Model model) { model.addAttribute("allElements", new ObjectMapper().valueToTree(getRepository().findAll())); addCommonModel(model); return getControllerRoute() + "/getAllWithRest"; } @PostMapping("") public String create(HttpServletRequest hsr, @ModelAttribute E e) { preProcessElement(e, hsr); getRepository().save(e); return "redirect:/" + getControllerRoute(); } @GetMapping("/{id}") public String getOne(@PathVariable("id") String id, Model model) { model.addAttribute("element", getElement(id)); addCommonModel(model); return getControllerRoute() + "/getOne"; } @GetMapping("/{id}/update") public String updateGet(@PathVariable("id") String id, Model model) { E e = getElement(id); postProcessElementForUpdateGet(e); model.addAttribute("element", e); addCommonModel(model); return getControllerRoute() + "/update"; } private void addCommonModel(Model model) { model.addAttribute("elementFields", getElementFields()); model.addAttribute("controllerRoute", getControllerRoute()); } @PostMapping("/{id}/update") public String update(HttpServletRequest hsr, @PathVariable("id") String id, @ModelAttribute E e) { preProcessElement(e, hsr); getRepository().save(e); return "redirect:/" + getControllerRoute(); } @PostMapping("/{id}/delete") public String delete(@PathVariable("id") String id) { getRepository().deleteById(parseId(id)); return "redirect:/" + getControllerRoute(); } // </editor-fold> }
35.680851
102
0.725104
fcf5753fb372d418a602dd91c494047503e8a8f4
2,605
/* * 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.aliyuncs.polardb.model.v20170801; import com.aliyuncs.AcsResponse; import com.aliyuncs.polardb.transform.v20170801.DescribeDBClusterVersionResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class DescribeDBClusterVersionResponse extends AcsResponse { private String requestId; private String dBClusterId; private String dBVersion; private String dBMinorVersion; private String dBVersionStatus; private String isLatestVersion; private String dBRevisionVersion; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getDBClusterId() { return this.dBClusterId; } public void setDBClusterId(String dBClusterId) { this.dBClusterId = dBClusterId; } public String getDBVersion() { return this.dBVersion; } public void setDBVersion(String dBVersion) { this.dBVersion = dBVersion; } public String getDBMinorVersion() { return this.dBMinorVersion; } public void setDBMinorVersion(String dBMinorVersion) { this.dBMinorVersion = dBMinorVersion; } public String getDBVersionStatus() { return this.dBVersionStatus; } public void setDBVersionStatus(String dBVersionStatus) { this.dBVersionStatus = dBVersionStatus; } public String getIsLatestVersion() { return this.isLatestVersion; } public void setIsLatestVersion(String isLatestVersion) { this.isLatestVersion = isLatestVersion; } public String getDBRevisionVersion() { return this.dBRevisionVersion; } public void setDBRevisionVersion(String dBRevisionVersion) { this.dBRevisionVersion = dBRevisionVersion; } @Override public DescribeDBClusterVersionResponse getInstance(UnmarshallerContext context) { return DescribeDBClusterVersionResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
24.345794
93
0.753167
3b25ac320d7a8ee3ec55eecb89ec3552795396fb
28,936
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.cloudformation.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * The structure that contains information about a specified operation's results for a given account in a given Region. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/StackSetOperationResultSummary" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class StackSetOperationResultSummary implements Serializable, Cloneable { /** * <p> * [Self-managed permissions] The name of the AWS account for this operation result. * </p> */ private String account; /** * <p> * The name of the AWS Region for this operation result. * </p> */ private String region; /** * <p> * The result status of the stack set operation for the given account in the given Region. * </p> * <ul> * <li> * <p> * <code>CANCELLED</code>: The operation in the specified account and Region has been cancelled. This is either * because a user has stopped the stack set operation, or because the failure tolerance of the stack set operation * has been exceeded. * </p> * </li> * <li> * <p> * <code>FAILED</code>: The operation in the specified account and Region failed. * </p> * <p> * If the stack set operation fails in enough accounts within a Region, the failure tolerance for the stack set * operation as a whole might be exceeded. * </p> * </li> * <li> * <p> * <code>RUNNING</code>: The operation in the specified account and Region is currently in progress. * </p> * </li> * <li> * <p> * <code>PENDING</code>: The operation in the specified account and Region has yet to start. * </p> * </li> * <li> * <p> * <code>SUCCEEDED</code>: The operation in the specified account and Region completed successfully. * </p> * </li> * </ul> */ private String status; /** * <p> * The reason for the assigned result status. * </p> */ private String statusReason; /** * <p> * The results of the account gate function AWS CloudFormation invokes, if present, before proceeding with stack set * operations in an account * </p> */ private AccountGateResult accountGateResult; /** * <p> * [Service-managed permissions] The organization root ID or organizational unit (OU) IDs that you specified for <a * href="https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeploymentTargets.html"> * DeploymentTargets</a>. * </p> */ private String organizationalUnitId; /** * <p> * [Self-managed permissions] The name of the AWS account for this operation result. * </p> * * @param account * [Self-managed permissions] The name of the AWS account for this operation result. */ public void setAccount(String account) { this.account = account; } /** * <p> * [Self-managed permissions] The name of the AWS account for this operation result. * </p> * * @return [Self-managed permissions] The name of the AWS account for this operation result. */ public String getAccount() { return this.account; } /** * <p> * [Self-managed permissions] The name of the AWS account for this operation result. * </p> * * @param account * [Self-managed permissions] The name of the AWS account for this operation result. * @return Returns a reference to this object so that method calls can be chained together. */ public StackSetOperationResultSummary withAccount(String account) { setAccount(account); return this; } /** * <p> * The name of the AWS Region for this operation result. * </p> * * @param region * The name of the AWS Region for this operation result. */ public void setRegion(String region) { this.region = region; } /** * <p> * The name of the AWS Region for this operation result. * </p> * * @return The name of the AWS Region for this operation result. */ public String getRegion() { return this.region; } /** * <p> * The name of the AWS Region for this operation result. * </p> * * @param region * The name of the AWS Region for this operation result. * @return Returns a reference to this object so that method calls can be chained together. */ public StackSetOperationResultSummary withRegion(String region) { setRegion(region); return this; } /** * <p> * The result status of the stack set operation for the given account in the given Region. * </p> * <ul> * <li> * <p> * <code>CANCELLED</code>: The operation in the specified account and Region has been cancelled. This is either * because a user has stopped the stack set operation, or because the failure tolerance of the stack set operation * has been exceeded. * </p> * </li> * <li> * <p> * <code>FAILED</code>: The operation in the specified account and Region failed. * </p> * <p> * If the stack set operation fails in enough accounts within a Region, the failure tolerance for the stack set * operation as a whole might be exceeded. * </p> * </li> * <li> * <p> * <code>RUNNING</code>: The operation in the specified account and Region is currently in progress. * </p> * </li> * <li> * <p> * <code>PENDING</code>: The operation in the specified account and Region has yet to start. * </p> * </li> * <li> * <p> * <code>SUCCEEDED</code>: The operation in the specified account and Region completed successfully. * </p> * </li> * </ul> * * @param status * The result status of the stack set operation for the given account in the given Region.</p> * <ul> * <li> * <p> * <code>CANCELLED</code>: The operation in the specified account and Region has been cancelled. This is * either because a user has stopped the stack set operation, or because the failure tolerance of the stack * set operation has been exceeded. * </p> * </li> * <li> * <p> * <code>FAILED</code>: The operation in the specified account and Region failed. * </p> * <p> * If the stack set operation fails in enough accounts within a Region, the failure tolerance for the stack * set operation as a whole might be exceeded. * </p> * </li> * <li> * <p> * <code>RUNNING</code>: The operation in the specified account and Region is currently in progress. * </p> * </li> * <li> * <p> * <code>PENDING</code>: The operation in the specified account and Region has yet to start. * </p> * </li> * <li> * <p> * <code>SUCCEEDED</code>: The operation in the specified account and Region completed successfully. * </p> * </li> * @see StackSetOperationResultStatus */ public void setStatus(String status) { this.status = status; } /** * <p> * The result status of the stack set operation for the given account in the given Region. * </p> * <ul> * <li> * <p> * <code>CANCELLED</code>: The operation in the specified account and Region has been cancelled. This is either * because a user has stopped the stack set operation, or because the failure tolerance of the stack set operation * has been exceeded. * </p> * </li> * <li> * <p> * <code>FAILED</code>: The operation in the specified account and Region failed. * </p> * <p> * If the stack set operation fails in enough accounts within a Region, the failure tolerance for the stack set * operation as a whole might be exceeded. * </p> * </li> * <li> * <p> * <code>RUNNING</code>: The operation in the specified account and Region is currently in progress. * </p> * </li> * <li> * <p> * <code>PENDING</code>: The operation in the specified account and Region has yet to start. * </p> * </li> * <li> * <p> * <code>SUCCEEDED</code>: The operation in the specified account and Region completed successfully. * </p> * </li> * </ul> * * @return The result status of the stack set operation for the given account in the given Region.</p> * <ul> * <li> * <p> * <code>CANCELLED</code>: The operation in the specified account and Region has been cancelled. This is * either because a user has stopped the stack set operation, or because the failure tolerance of the stack * set operation has been exceeded. * </p> * </li> * <li> * <p> * <code>FAILED</code>: The operation in the specified account and Region failed. * </p> * <p> * If the stack set operation fails in enough accounts within a Region, the failure tolerance for the stack * set operation as a whole might be exceeded. * </p> * </li> * <li> * <p> * <code>RUNNING</code>: The operation in the specified account and Region is currently in progress. * </p> * </li> * <li> * <p> * <code>PENDING</code>: The operation in the specified account and Region has yet to start. * </p> * </li> * <li> * <p> * <code>SUCCEEDED</code>: The operation in the specified account and Region completed successfully. * </p> * </li> * @see StackSetOperationResultStatus */ public String getStatus() { return this.status; } /** * <p> * The result status of the stack set operation for the given account in the given Region. * </p> * <ul> * <li> * <p> * <code>CANCELLED</code>: The operation in the specified account and Region has been cancelled. This is either * because a user has stopped the stack set operation, or because the failure tolerance of the stack set operation * has been exceeded. * </p> * </li> * <li> * <p> * <code>FAILED</code>: The operation in the specified account and Region failed. * </p> * <p> * If the stack set operation fails in enough accounts within a Region, the failure tolerance for the stack set * operation as a whole might be exceeded. * </p> * </li> * <li> * <p> * <code>RUNNING</code>: The operation in the specified account and Region is currently in progress. * </p> * </li> * <li> * <p> * <code>PENDING</code>: The operation in the specified account and Region has yet to start. * </p> * </li> * <li> * <p> * <code>SUCCEEDED</code>: The operation in the specified account and Region completed successfully. * </p> * </li> * </ul> * * @param status * The result status of the stack set operation for the given account in the given Region.</p> * <ul> * <li> * <p> * <code>CANCELLED</code>: The operation in the specified account and Region has been cancelled. This is * either because a user has stopped the stack set operation, or because the failure tolerance of the stack * set operation has been exceeded. * </p> * </li> * <li> * <p> * <code>FAILED</code>: The operation in the specified account and Region failed. * </p> * <p> * If the stack set operation fails in enough accounts within a Region, the failure tolerance for the stack * set operation as a whole might be exceeded. * </p> * </li> * <li> * <p> * <code>RUNNING</code>: The operation in the specified account and Region is currently in progress. * </p> * </li> * <li> * <p> * <code>PENDING</code>: The operation in the specified account and Region has yet to start. * </p> * </li> * <li> * <p> * <code>SUCCEEDED</code>: The operation in the specified account and Region completed successfully. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see StackSetOperationResultStatus */ public StackSetOperationResultSummary withStatus(String status) { setStatus(status); return this; } /** * <p> * The result status of the stack set operation for the given account in the given Region. * </p> * <ul> * <li> * <p> * <code>CANCELLED</code>: The operation in the specified account and Region has been cancelled. This is either * because a user has stopped the stack set operation, or because the failure tolerance of the stack set operation * has been exceeded. * </p> * </li> * <li> * <p> * <code>FAILED</code>: The operation in the specified account and Region failed. * </p> * <p> * If the stack set operation fails in enough accounts within a Region, the failure tolerance for the stack set * operation as a whole might be exceeded. * </p> * </li> * <li> * <p> * <code>RUNNING</code>: The operation in the specified account and Region is currently in progress. * </p> * </li> * <li> * <p> * <code>PENDING</code>: The operation in the specified account and Region has yet to start. * </p> * </li> * <li> * <p> * <code>SUCCEEDED</code>: The operation in the specified account and Region completed successfully. * </p> * </li> * </ul> * * @param status * The result status of the stack set operation for the given account in the given Region.</p> * <ul> * <li> * <p> * <code>CANCELLED</code>: The operation in the specified account and Region has been cancelled. This is * either because a user has stopped the stack set operation, or because the failure tolerance of the stack * set operation has been exceeded. * </p> * </li> * <li> * <p> * <code>FAILED</code>: The operation in the specified account and Region failed. * </p> * <p> * If the stack set operation fails in enough accounts within a Region, the failure tolerance for the stack * set operation as a whole might be exceeded. * </p> * </li> * <li> * <p> * <code>RUNNING</code>: The operation in the specified account and Region is currently in progress. * </p> * </li> * <li> * <p> * <code>PENDING</code>: The operation in the specified account and Region has yet to start. * </p> * </li> * <li> * <p> * <code>SUCCEEDED</code>: The operation in the specified account and Region completed successfully. * </p> * </li> * @see StackSetOperationResultStatus */ public void setStatus(StackSetOperationResultStatus status) { withStatus(status); } /** * <p> * The result status of the stack set operation for the given account in the given Region. * </p> * <ul> * <li> * <p> * <code>CANCELLED</code>: The operation in the specified account and Region has been cancelled. This is either * because a user has stopped the stack set operation, or because the failure tolerance of the stack set operation * has been exceeded. * </p> * </li> * <li> * <p> * <code>FAILED</code>: The operation in the specified account and Region failed. * </p> * <p> * If the stack set operation fails in enough accounts within a Region, the failure tolerance for the stack set * operation as a whole might be exceeded. * </p> * </li> * <li> * <p> * <code>RUNNING</code>: The operation in the specified account and Region is currently in progress. * </p> * </li> * <li> * <p> * <code>PENDING</code>: The operation in the specified account and Region has yet to start. * </p> * </li> * <li> * <p> * <code>SUCCEEDED</code>: The operation in the specified account and Region completed successfully. * </p> * </li> * </ul> * * @param status * The result status of the stack set operation for the given account in the given Region.</p> * <ul> * <li> * <p> * <code>CANCELLED</code>: The operation in the specified account and Region has been cancelled. This is * either because a user has stopped the stack set operation, or because the failure tolerance of the stack * set operation has been exceeded. * </p> * </li> * <li> * <p> * <code>FAILED</code>: The operation in the specified account and Region failed. * </p> * <p> * If the stack set operation fails in enough accounts within a Region, the failure tolerance for the stack * set operation as a whole might be exceeded. * </p> * </li> * <li> * <p> * <code>RUNNING</code>: The operation in the specified account and Region is currently in progress. * </p> * </li> * <li> * <p> * <code>PENDING</code>: The operation in the specified account and Region has yet to start. * </p> * </li> * <li> * <p> * <code>SUCCEEDED</code>: The operation in the specified account and Region completed successfully. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see StackSetOperationResultStatus */ public StackSetOperationResultSummary withStatus(StackSetOperationResultStatus status) { this.status = status.toString(); return this; } /** * <p> * The reason for the assigned result status. * </p> * * @param statusReason * The reason for the assigned result status. */ public void setStatusReason(String statusReason) { this.statusReason = statusReason; } /** * <p> * The reason for the assigned result status. * </p> * * @return The reason for the assigned result status. */ public String getStatusReason() { return this.statusReason; } /** * <p> * The reason for the assigned result status. * </p> * * @param statusReason * The reason for the assigned result status. * @return Returns a reference to this object so that method calls can be chained together. */ public StackSetOperationResultSummary withStatusReason(String statusReason) { setStatusReason(statusReason); return this; } /** * <p> * The results of the account gate function AWS CloudFormation invokes, if present, before proceeding with stack set * operations in an account * </p> * * @param accountGateResult * The results of the account gate function AWS CloudFormation invokes, if present, before proceeding with * stack set operations in an account */ public void setAccountGateResult(AccountGateResult accountGateResult) { this.accountGateResult = accountGateResult; } /** * <p> * The results of the account gate function AWS CloudFormation invokes, if present, before proceeding with stack set * operations in an account * </p> * * @return The results of the account gate function AWS CloudFormation invokes, if present, before proceeding with * stack set operations in an account */ public AccountGateResult getAccountGateResult() { return this.accountGateResult; } /** * <p> * The results of the account gate function AWS CloudFormation invokes, if present, before proceeding with stack set * operations in an account * </p> * * @param accountGateResult * The results of the account gate function AWS CloudFormation invokes, if present, before proceeding with * stack set operations in an account * @return Returns a reference to this object so that method calls can be chained together. */ public StackSetOperationResultSummary withAccountGateResult(AccountGateResult accountGateResult) { setAccountGateResult(accountGateResult); return this; } /** * <p> * [Service-managed permissions] The organization root ID or organizational unit (OU) IDs that you specified for <a * href="https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeploymentTargets.html"> * DeploymentTargets</a>. * </p> * * @param organizationalUnitId * [Service-managed permissions] The organization root ID or organizational unit (OU) IDs that you specified * for <a * href="https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeploymentTargets.html"> * DeploymentTargets</a>. */ public void setOrganizationalUnitId(String organizationalUnitId) { this.organizationalUnitId = organizationalUnitId; } /** * <p> * [Service-managed permissions] The organization root ID or organizational unit (OU) IDs that you specified for <a * href="https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeploymentTargets.html"> * DeploymentTargets</a>. * </p> * * @return [Service-managed permissions] The organization root ID or organizational unit (OU) IDs that you specified * for <a * href="https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeploymentTargets.html" * >DeploymentTargets</a>. */ public String getOrganizationalUnitId() { return this.organizationalUnitId; } /** * <p> * [Service-managed permissions] The organization root ID or organizational unit (OU) IDs that you specified for <a * href="https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeploymentTargets.html"> * DeploymentTargets</a>. * </p> * * @param organizationalUnitId * [Service-managed permissions] The organization root ID or organizational unit (OU) IDs that you specified * for <a * href="https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeploymentTargets.html"> * DeploymentTargets</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public StackSetOperationResultSummary withOrganizationalUnitId(String organizationalUnitId) { setOrganizationalUnitId(organizationalUnitId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAccount() != null) sb.append("Account: ").append(getAccount()).append(","); if (getRegion() != null) sb.append("Region: ").append(getRegion()).append(","); if (getStatus() != null) sb.append("Status: ").append(getStatus()).append(","); if (getStatusReason() != null) sb.append("StatusReason: ").append(getStatusReason()).append(","); if (getAccountGateResult() != null) sb.append("AccountGateResult: ").append(getAccountGateResult()).append(","); if (getOrganizationalUnitId() != null) sb.append("OrganizationalUnitId: ").append(getOrganizationalUnitId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof StackSetOperationResultSummary == false) return false; StackSetOperationResultSummary other = (StackSetOperationResultSummary) obj; if (other.getAccount() == null ^ this.getAccount() == null) return false; if (other.getAccount() != null && other.getAccount().equals(this.getAccount()) == false) return false; if (other.getRegion() == null ^ this.getRegion() == null) return false; if (other.getRegion() != null && other.getRegion().equals(this.getRegion()) == false) return false; if (other.getStatus() == null ^ this.getStatus() == null) return false; if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false; if (other.getStatusReason() == null ^ this.getStatusReason() == null) return false; if (other.getStatusReason() != null && other.getStatusReason().equals(this.getStatusReason()) == false) return false; if (other.getAccountGateResult() == null ^ this.getAccountGateResult() == null) return false; if (other.getAccountGateResult() != null && other.getAccountGateResult().equals(this.getAccountGateResult()) == false) return false; if (other.getOrganizationalUnitId() == null ^ this.getOrganizationalUnitId() == null) return false; if (other.getOrganizationalUnitId() != null && other.getOrganizationalUnitId().equals(this.getOrganizationalUnitId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAccount() == null) ? 0 : getAccount().hashCode()); hashCode = prime * hashCode + ((getRegion() == null) ? 0 : getRegion().hashCode()); hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode()); hashCode = prime * hashCode + ((getStatusReason() == null) ? 0 : getStatusReason().hashCode()); hashCode = prime * hashCode + ((getAccountGateResult() == null) ? 0 : getAccountGateResult().hashCode()); hashCode = prime * hashCode + ((getOrganizationalUnitId() == null) ? 0 : getOrganizationalUnitId().hashCode()); return hashCode; } @Override public StackSetOperationResultSummary clone() { try { return (StackSetOperationResultSummary) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
35.723457
137
0.586259
7f35373ce6ee64a4f4fd751b08831ae82d194363
3,610
/* * Copyright 2010-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.jet.lang.psi.stubs.elements; import com.intellij.lang.ASTNode; import com.intellij.psi.stubs.IndexSink; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.util.io.StringRef; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.psi.JetExpression; import org.jetbrains.jet.lang.psi.JetParameter; import org.jetbrains.jet.lang.psi.JetTypeReference; import org.jetbrains.jet.lang.psi.stubs.PsiJetParameterStub; import org.jetbrains.jet.lang.psi.stubs.impl.PsiJetParameterStubImpl; import java.io.IOException; /** * @author Nikolay Krasko */ public class JetParameterElementType extends JetStubElementType<PsiJetParameterStub, JetParameter> { public JetParameterElementType(@NotNull @NonNls String debugName) { super(debugName); } @Override public JetParameter createPsiFromAst(@NotNull ASTNode node) { return new JetParameter(node); } @Override public JetParameter createPsi(@NotNull PsiJetParameterStub stub) { return new JetParameter(stub, JetStubElementTypes.VALUE_PARAMETER); } @Override public PsiJetParameterStub createStub(@NotNull JetParameter psi, StubElement parentStub) { JetTypeReference typeReference = psi.getTypeReference(); JetExpression defaultValue = psi.getDefaultValue(); return new PsiJetParameterStubImpl(JetStubElementTypes.VALUE_PARAMETER, parentStub, psi.getName(), psi.isMutable(), psi.isVarArg(), typeReference != null ? typeReference.getText() : null, defaultValue != null ? defaultValue.getText() : null); } @Override public boolean shouldCreateStub(ASTNode node) { return node.getElementType() == JetStubElementTypes.VALUE_PARAMETER; } @Override public void serialize(PsiJetParameterStub stub, StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); dataStream.writeBoolean(stub.isMutable()); dataStream.writeBoolean(stub.isVarArg()); dataStream.writeName(stub.getTypeText()); dataStream.writeName(stub.getDefaultValueText()); } @Override public PsiJetParameterStub deserialize(StubInputStream dataStream, StubElement parentStub) throws IOException { StringRef name = dataStream.readName(); boolean isMutable = dataStream.readBoolean(); boolean isVarArg = dataStream.readBoolean(); StringRef typeText = dataStream.readName(); StringRef defaultValueText = dataStream.readName(); return new PsiJetParameterStubImpl(JetStubElementTypes.VALUE_PARAMETER, parentStub, name, isMutable, isVarArg, typeText, defaultValueText); } @Override public void indexStub(PsiJetParameterStub stub, IndexSink sink) { // No index } }
38
118
0.730748
e1b1f07f14c746804ffb0c617805c04cf0519a6d
948
package org.com.allen.enhance.basic.limit; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * @author allen.wu * @since 2018-06-21 22:52 */ public class CountLimiter { private static final AtomicInteger count = new AtomicInteger(0); public static void main(String[] args) { for (int i = 0; i < 20; i++) { new Thread(() -> { exec(); }).start(); } } public static void exec() { if (count.get() > 10) { System.out.println("拒绝访问."); } else { count.incrementAndGet(); try { TimeUnit.SECONDS.sleep(1); System.out.println("--" + System.currentTimeMillis() / 1000); } catch (InterruptedException e) { e.printStackTrace(); } finally { count.decrementAndGet(); } } } }
23.7
77
0.514768
b432f246115480549da74b1549c0bb003292ab75
261
package bytecryb.clio.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import bytecryb.clio.model.PDF; @Repository public interface PDFRepository extends JpaRepository<PDF, Long> { }
23.727273
65
0.835249
faf9780c3069b32dcea6da67b948dcdb1f03702c
1,247
package cn.k12soft.servo.module.wxLogin.repository; import cn.k12soft.servo.module.wxLogin.domain.pojo.PushCode; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.List; @Repository public interface PushCodeRepository extends JpaSpecificationExecutor<PushCode>, JpaRepository<PushCode, Long>{ @Query(value = " SELECT * FROM push_code p" + " WHERE TIMESTAMPDIFF(DAY, p.created_at, p.timeout_at) > 7" + " AND p.actor_id = :actorId", nativeQuery = true) Collection<PushCode> findAllByTimeOut7Days(@Param("actorId") Integer actorId); @Query(value = "SELECT * FROM push_code p" + " WHERE p.actor_id = :actorId" + " AND p.created_at = " + " (SELECT MAX(pc.created_at) FROM push_code pc " + " WHERE pc.actor_id = :actorId)", nativeQuery = true) List<PushCode> findAllByActorIdAndCreatedAtMax(@Param("actorId") Integer actorId); void deleteByFormId(String formid); }
41.566667
110
0.730553
08e0027ffab839891b8c4c5f6245437e297756f2
2,312
package nl.lucasridder.RealIP.bungee.handler; import io.netty.channel.AbstractChannel; import net.md_5.bungee.api.connection.PendingConnection; import nl.lucasridder.RealIP.provider.PlayerProvider; import nl.lucasridder.RealIP.util.ReflectionUtil; import nl.lucasridder.RealIP.util.exception.manipulate.PlayerManipulationException; import java.lang.reflect.Field; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.UUID; /** * A player wrapper for Bungee */ public class BungeePlayer implements PlayerProvider { private final PendingConnection pendingConnection; private String ip; public BungeePlayer(PendingConnection pendingConnection) { this.pendingConnection = pendingConnection; this.ip = pendingConnection.getAddress().getAddress().getHostAddress(); } /** * Trys to grab the UUID of the handshake * @return If found, the corrosponding uuid, if not, unknown */ @Override public String getUUID() { UUID uuid = pendingConnection.getUniqueId(); if (uuid == null) return "unknown"; return uuid.toString(); } @Override public String getName() { return pendingConnection.getName(); } @Override public String getIP() { return ip; } @Override public void setIP(InetSocketAddress ip) throws PlayerManipulationException { try { this.ip = ip.getAddress().getHostAddress(); Object channelWrapper = ReflectionUtil.getObjectInPrivateField(pendingConnection, "ch"); Object channel = ReflectionUtil.getObjectInPrivateField(channelWrapper, "ch"); try { Field socketAddressField = ReflectionUtil.searchFieldByClass(channelWrapper.getClass(), SocketAddress.class); ReflectionUtil.setFinalField(channelWrapper, socketAddressField, ip); } catch (IllegalArgumentException ignored) { // Some BungeeCord versions, notably those on 1.7 (e.g. zBungeeCord) don't have an SocketAddress field in the ChannelWrapper class } ReflectionUtil.setFinalField(channel, ReflectionUtil.getPrivateField(AbstractChannel.class, "remoteAddress"), ip); ReflectionUtil.setFinalField(channel, ReflectionUtil.getPrivateField(AbstractChannel.class, "localAddress"), ip); } catch (Exception e) { throw new PlayerManipulationException(e); } } @Override public void disconnect() { pendingConnection.disconnect(); } }
29.265823
134
0.772924
a12f5937ab6def75b41f2f5c1a1a68c8419f6a8c
2,118
package io.github.reugn.gravity.bench; import io.github.reugn.gravity.bench.state.Before; import io.github.reugn.gravity.matcher.BMHMatcher; import io.github.reugn.gravity.matcher.ContainsMatcher; import io.github.reugn.gravity.matcher.Matcher; import io.github.reugn.gravity.util.Utils; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.TimeUnit; /** * ./gradlew jmh * <p> * Benchmark Mode Cnt Score Error Units * MatcherBenchmark.bmhMatcherBenchmark thrpt 4.580 ops/ms * MatcherBenchmark.containsMatcherBenchmark thrpt 5.910 ops/ms * MatcherBenchmark.stringBMHMatcherBenchmark thrpt 5.446 ops/ms * MatcherBenchmark.stringContainsMatcherBenchmark thrpt 5.968 ops/ms */ @OutputTimeUnit(TimeUnit.MILLISECONDS) @BenchmarkMode(Mode.Throughput) @SuppressWarnings("unused") public class MatcherBenchmark { @Benchmark public void containsMatcherBenchmark(Before b) throws IOException { InputStream is = Utils.readResource("/apache-license-2.0.txt"); Matcher m = new ContainsMatcher(); m.match(b.pattern, is, 8); } @Benchmark public void bmhMatcherBenchmark(Before b) throws IOException { InputStream is = Utils.readResource("/apache-license-2.0.txt"); Matcher m = new BMHMatcher(); m.match(b.pattern, is, 8); } @Benchmark public void stringContainsMatcherBenchmark(Before b) { InputStream is = Utils.readResource("/apache-license-2.0.txt"); Matcher m = new ContainsMatcher(); m.match(b.pattern, Utils.toStr(is)); } @Benchmark public void stringBMHMatcherBenchmark(Before b) { InputStream is = Utils.readResource("/apache-license-2.0.txt"); Matcher m = new BMHMatcher(); m.match(b.pattern, Utils.toStr(is)); } }
35.898305
85
0.687441
e86fc57155d462e79d2d049bdafaf3350241fd0f
516
package com.fullmark.service; import com.fullmark.pojo.Goods; import org.springframework.web.multipart.MultipartFile; import java.util.List; public interface GoodsService { public List<Goods> showGoodsList(); boolean isGoodsEnough(int gid, int number); void reduceNumber(int gid, int number); void editGoods(int gid, String gname, String gdesc, int gnumber); void addNew(String gname, String gdesc, int gnumber); void addNew1(String gname, String gdesc, int gnumber, String gimage); }
25.8
73
0.75
35d50c02151afb0a161adeb288021efd92e7922d
1,457
package com.kencloud.partner.user.network_util; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.android.volley.toolbox.JsonRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; /** * Created by Kranti on 18/3/2016. */ public class JsonArrayRequest extends JsonRequest<JSONArray> { public JsonArrayRequest( String url,JSONObject param, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) { super(Method.POST, url,param.toString(), listener, errorListener); } /* @Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { return null; }*/ @Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } } }
28.568627
86
0.707618