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 |
|---|---|---|---|---|---|
487b486ce28d9172657cbc8f4f5d4b35d853e56d | 1,006 | /**
*
*/
package com.app.sa.joinThreads;
/**
* @author iHSPA
*/
public class JoinThreadsB implements Runnable {
@Override
public void run ( ) {
String name = Thread.currentThread ( ).getId ( ) + "===JoinThreadsB===" + Thread.currentThread ( ).getName ( );
/*
* Consider this as the second thread which is actually reading the data from the server. Imagine it will take 2
* seconds and then it returns to the other threads to continue working.
*/
System.out.println ( "Sending file/image from the Server..." );
// Wait until the other thread has finished reading //
for ( int i = 0; i < 4; i++ ) {
System.out.println ( name + "===> Loading..." );
try {
Thread.sleep ( 250 );
} catch ( InterruptedException e ) {
e.printStackTrace ( );
}
System.out.println ( "Reading file/image from the Server completed..." );
}
}
}
| 27.944444 | 120 | 0.550696 |
6ee0ca7244bd7f1f5967c72a70d34c0f6d325d64 | 32,032 | package codes.biscuit.skyblockaddons.utils;
import codes.biscuit.skyblockaddons.SkyblockAddons;
import codes.biscuit.skyblockaddons.constants.game.Rarity;
import codes.biscuit.skyblockaddons.utils.nifty.ChatFormatting;
import codes.biscuit.skyblockaddons.utils.nifty.RegexUtil;
import codes.biscuit.skyblockaddons.utils.nifty.StringUtil;
import codes.biscuit.skyblockaddons.utils.nifty.reflection.MinecraftReflection;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.ObjectArrays;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.client.Minecraft;
import net.minecraft.event.ClickEvent;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.scoreboard.Score;
import net.minecraft.scoreboard.ScoreObjective;
import net.minecraft.scoreboard.ScorePlayerTeam;
import net.minecraft.scoreboard.Scoreboard;
import net.minecraft.util.ChatComponentText;
import net.minecraftforge.client.event.ClientChatReceivedEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.MetadataCollection;
import net.minecraftforge.fml.common.ModMetadata;
import net.minecraftforge.fml.relauncher.CoreModManager;
import net.minecraftforge.fml.relauncher.FMLInjectionData;
import net.minecraftforge.fml.relauncher.FileListHelper;
import net.minecraftforge.fml.relauncher.ModListHelper;
import org.apache.commons.lang3.mutable.MutableInt;
import java.awt.*;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.*;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
@Getter
@Setter
public class Utils {
/**
* Added to the beginning of messages.
*/
private static final String MESSAGE_PREFIX =
ChatFormatting.YELLOW + "" + ChatFormatting.BOLD + "[" + ChatFormatting.YELLOW + SkyblockAddons.MOD_NAME + ChatFormatting.BOLD + "] ";
/**
* Enchantments listed by how good they are. May or may not be subjective lol.
*/
private static final List<String> ORDERED_ENCHANTMENTS = Collections.unmodifiableList(Arrays.asList(
"smite", "bane of arthropods", "knockback", "fire aspect", "venomous", // Sword Bad
"thorns", "growth", "protection", "depth strider", "respiration", "aqua affinity", // Armor
"lure", "caster", "luck of the sea", "blessing", "angler", "frail", "magnet", "spiked hook", // Fishing
"dragon hunter", "power", "snipe", "piercing", "aiming", "infinite quiver", // Bow Main
"sharpness", "critical", "first strike", "giant killer", "execute", "lethality", "ender slayer", "cubism", "impaling", // Sword Damage
"vampirism", "life steal", "looting", "luck", "scavenger", "experience", "cleave", "thunderlord", // Sword Others
"punch", "flame", // Bow Others
"telekinesis"
));
private static final Pattern SERVER_REGEX = Pattern.compile("([0-9]{2}/[0-9]{2}/[0-9]{2}) (mini[0-9]{1,3}[A-Za-z])");
/**
* In English, Chinese Simplified.
*/
private static final Set<String> SKYBLOCK_IN_ALL_LANGUAGES = Sets.newHashSet("SKY BLOCK");
/**
* Used for web requests.
*/
private static final String USER_AGENT = "SkyblockAddons/" + SkyblockAddons.VERSION;
/**
* Items containing these in the name should never be dropped. Helmets a lot of times
* in skyblock are weird items and are not damageable so that's why its included.
*/
private static final String[] RARE_ITEM_OVERRIDES = {"Mochila", "Capacete"};
private static final Pattern NUMBERS_SLASHES = Pattern.compile("[^0-9 /]");
private static final Pattern LETTERS_NUMBERS = Pattern.compile("[^a-z A-Z:0-9/']");
// I know this is messy af, but frustration led me to take this dark path - said someone not biscuit
public static boolean blockNextClick = false;
/**
* Get a player's attributes. This includes health, mana, and defence.
*/
private Map<Attribute, MutableInt> attributes = new EnumMap<>(Attribute.class);
/**
* List of enchantments that the player is looking to find.
*/
private List<String> enchantmentMatches = new LinkedList<>();
/**
* List of enchantment substrings that the player doesn't want to match.
*/
private List<String> enchantmentExclusions = new LinkedList<>();
private Backpack backpackToRender = null;
/**
* Whether the player is on skyblock.
*/
private boolean onSkyblock = false;
/**
* List of enchantments that the player is looking to find.
*/
private Location location = null;
/**
* The skyblock profile that the player is currently on. Ex. "Grapefruit"
*/
private String profileName = null;
/**
* Whether or not a loud sound is being played by the mod.
*/
private boolean playingSound = false;
/**
* The current serverID that the player is on.
*/
private String serverID = "";
private SkyblockDate currentDate = new SkyblockDate(SkyblockDate.SkyblockMonth.EARLY_WINTER, 1, 1, 1);
private int lastHoveredSlot = -1;
/**
* Whether the player is using the old style of bars packaged into Imperial's Skyblock Pack.
*/
private boolean usingOldSkyBlockTexture = false;
/**
* Whether the player is using the default bars packaged into the mod.
*/
private boolean usingDefaultBarTextures = true;
private boolean fadingIn;
private SkyblockAddons main;
public Utils(SkyblockAddons main) {
this.main = main;
addDefaultStats();
}
public static String color(String text) {
return ChatFormatting.translateAlternateColorCodes('&', text);
}
public static String niceDouble(double value, int decimals) {
if (value == (long) value) {
return String.format("%d", (long) value);
} else {
return String.format("%." + decimals + "f", value);
}
}
private void addDefaultStats() {
for (Attribute attribute : Attribute.values()) {
attributes.put(attribute, new MutableInt(attribute.getDefaultValue()));
}
}
public void sendMessage(String text, boolean prefix) {
ClientChatReceivedEvent event = new ClientChatReceivedEvent((byte) 1, new ChatComponentText((prefix ? MESSAGE_PREFIX : "") + text));
MinecraftForge.EVENT_BUS.post(event); // Let other mods pick up the new message
if (!event.isCanceled()) {
Minecraft.getMinecraft().thePlayer.addChatMessage(event.message); // Just for logs
}
}
public void sendMessage(String text) {
sendMessage(text, true);
}
private void sendMessage(ChatComponentText text) {
sendMessage(text.getFormattedText());
}
private void sendMessage(ChatComponentText text, boolean prefix) {
sendMessage(text.getFormattedText(), prefix);
}
public void sendErrorMessage(String errorText) {
sendMessage(ChatFormatting.RED + "Error: " + errorText);
}
public void checkGameLocationDate() {
boolean foundLocation = false;
Minecraft mc = Minecraft.getMinecraft();
if (mc != null && mc.theWorld != null) {
Scoreboard scoreboard = mc.theWorld.getScoreboard();
ScoreObjective sidebarObjective = mc.theWorld.getScoreboard().getObjectiveInDisplaySlot(1);
if (sidebarObjective != null) {
String objectiveName = stripColor(sidebarObjective.getDisplayName());
onSkyblock = false;
for (String skyblock : SKYBLOCK_IN_ALL_LANGUAGES) {
if (objectiveName.endsWith(skyblock)) {
onSkyblock = true;
break;
}
}
Collection<Score> scores = scoreboard.getSortedScores(sidebarObjective);
List<Score> list = Lists.newArrayList(scores.stream().filter(p_apply_1_ -> p_apply_1_.getPlayerName() != null && !p_apply_1_.getPlayerName().startsWith("#")).collect(Collectors.toList()));
if (list.size() > 15) {
scores = Lists.newArrayList(Iterables.skip(list, scores.size() - 15));
} else {
scores = list;
}
for (Score score1 : scores) {
ScorePlayerTeam scorePlayerTeam = scoreboard.getPlayersTeam(score1.getPlayerName());
String locationString = keepLettersAndNumbersOnly(
stripColor(ScorePlayerTeam.formatPlayerName(scorePlayerTeam, score1.getPlayerName())));
for (Location loopLocation : Location.values()) {
if (locationString.endsWith(loopLocation.getScoreboardName())) {
location = loopLocation;
foundLocation = true;
break;
}
}
}
} else {
onSkyblock = false;
}
} else {
onSkyblock = false;
}
if (!foundLocation) {
location = null;
}
}
private String keepLettersAndNumbersOnly(String text) {
return LETTERS_NUMBERS.matcher(text).replaceAll("");
}
public String getNumbersOnly(String text) {
return NUMBERS_SLASHES.matcher(text).replaceAll("");
}
public String removeDuplicateSpaces(String text) {
return text.replaceAll("\\s+", " ");
}
public void checkUpdates() {
if (SkyblockAddons.VERSION.contains("-dev")) {
main.getRenderListener().getDownloadInfo().setMessageType(EnumUtils.UpdateMessageType.DEVELOPMENT);
}
}
void sendUpdateMessage(boolean showDownload, boolean showAutoDownload) {
String newestVersion = main.getRenderListener().getDownloadInfo().getNewestVersion();
sendMessage(color("&7&m------------&7[&b&l SkyblockAddons &7]&7&m------------"), false);
if (main.getRenderListener().getDownloadInfo().getMessageType() == EnumUtils.UpdateMessageType.DOWNLOAD_FINISHED) {
ChatComponentText deleteOldFile = new ChatComponentText(ChatFormatting.RED + Message.MESSAGE_DELETE_OLD_FILE.getMessage() + "\n");
sendMessage(deleteOldFile, false);
} else {
ChatComponentText newUpdate = new ChatComponentText(ChatFormatting.AQUA + Message.MESSAGE_NEW_UPDATE.getMessage(newestVersion) + "\n");
sendMessage(newUpdate, false);
}
ChatComponentText buttonsMessage = new ChatComponentText("");
if (showDownload) {
buttonsMessage = new ChatComponentText(ChatFormatting.AQUA.toString() + ChatFormatting.BOLD + '[' + Message.MESSAGE_DOWNLOAD_LINK.getMessage(newestVersion) + ']');
buttonsMessage.setChatStyle(buttonsMessage.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, main.getRenderListener().getDownloadInfo().getDownloadLink())));
buttonsMessage.appendSibling(new ChatComponentText(" "));
}
if (showAutoDownload) {
ChatComponentText downloadAutomatically = new ChatComponentText(ChatFormatting.GREEN.toString() + ChatFormatting.BOLD + '[' + Message.MESSAGE_DOWNLOAD_AUTOMATICALLY.getMessage(newestVersion) + ']');
downloadAutomatically.setChatStyle(downloadAutomatically.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/sba update")));
buttonsMessage.appendSibling(downloadAutomatically);
buttonsMessage.appendSibling(new ChatComponentText(" "));
}
ChatComponentText openModsFolder = new ChatComponentText(ChatFormatting.YELLOW.toString() + ChatFormatting.BOLD + '[' + Message.MESSAGE_OPEN_MODS_FOLDER.getMessage(newestVersion) + ']');
openModsFolder.setChatStyle(openModsFolder.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/sba folder")));
buttonsMessage.appendSibling(openModsFolder);
sendMessage(buttonsMessage, false);
if (main.getRenderListener().getDownloadInfo().getMessageType() != EnumUtils.UpdateMessageType.DOWNLOAD_FINISHED) {
ChatComponentText discord = new ChatComponentText(ChatFormatting.AQUA + Message.MESSAGE_VIEW_PATCH_NOTES.getMessage() + " " +
ChatFormatting.BLUE.toString() + ChatFormatting.BOLD + '[' + Message.MESSAGE_JOIN_DISCORD.getMessage() + ']');
discord.setChatStyle(discord.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://discord.gg/PqTAEek")));
sendMessage(discord);
}
sendMessage(color("&7&m----------------------------------------------"), false);
}
public void checkDisabledFeatures() {
new Thread(() -> {
try {
URL url = new URL("https://raw.githubusercontent.com/biscuut/SkyblockAddons/master/disabledFeatures.txt");
URLConnection connection = url.openConnection();
connection.setReadTimeout(5000);
connection.addRequestProperty("User-Agent", "SkyblockAddons");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String currentLine;
Set<Feature> disabledFeatures = main.getConfigValues().getRemoteDisabledFeatures();
while ((currentLine = reader.readLine()) != null) {
String[] splitLine = currentLine.split(Pattern.quote("|"));
if (!currentLine.startsWith("all|")) {
if (!SkyblockAddons.VERSION.equals(splitLine[0])) {
continue;
}
}
if (splitLine.length > 1) {
for (int i = 1; i < splitLine.length; i++) {
String part = splitLine[i];
Feature feature = Feature.fromId(Integer.parseInt(part));
if (feature != null) {
disabledFeatures.add(feature);
}
}
}
}
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}).start();
}
public int getDefaultColor(float alphaFloat) {
int alpha = (int) alphaFloat;
return new Color(150, 236, 255, alpha).getRGB();
}
/**
* When you use this function, any sound played will bypass the player's
* volume setting, so make sure to only use this for like warnings or stuff like that.
*/
public void playLoudSound(String sound, double pitch) {
playingSound = true;
Minecraft.getMinecraft().thePlayer.playSound(sound, 1, (float) pitch);
playingSound = false;
}
/**
* This one plays the sound normally. See {@link Utils#playLoudSound(String, double)} for playing
* a sound that bypasses the user's volume settings.
*/
public void playSound(String sound, double pitch) {
Minecraft.getMinecraft().thePlayer.playSound(sound, 1, (float) pitch);
}
public boolean enchantReforgeMatches(String text) {
text = text.toLowerCase();
for (String enchant : enchantmentMatches) {
enchant = enchant.trim().toLowerCase();
if (StringUtil.notEmpty(enchant) && text.contains(enchant)) {
boolean foundExclusion = false;
for (String exclusion : enchantmentExclusions) {
exclusion = exclusion.trim().toLowerCase();
if (StringUtil.notEmpty(exclusion) && text.contains(exclusion)) {
foundExclusion = true;
break;
}
}
if (!foundExclusion) {
return true;
}
}
}
return false;
}
public void fetchEstimateFromServer() {
new Thread(() -> {
FMLLog.info("[SkyblockAddons] Getting magma boss spawn estimate from server...");
try {
URL url = new URL("https://hypixel-api.inventivetalent.org/api/skyblock/bosstimer/magma/estimatedSpawn");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", USER_AGENT);
FMLLog.info("[SkyblockAddons] Got response code " + connection.getResponseCode());
StringBuilder response = new StringBuilder();
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = in.readLine()) != null) {
response.append(line);
}
}
connection.disconnect();
JsonObject responseJson = new Gson().fromJson(response.toString(), JsonObject.class);
long estimate = responseJson.get("estimate").getAsLong();
long currentTime = responseJson.get("queryTime").getAsLong();
int magmaSpawnTime = (int) ((estimate - currentTime) / 1000);
FMLLog.info("[SkyblockAddons] Query time was " + currentTime + ", server time estimate is " +
estimate + ". Updating magma boss spawn to be in " + magmaSpawnTime + " seconds.");
main.getPlayerListener().setMagmaTime(magmaSpawnTime);
main.getPlayerListener().setMagmaAccuracy(EnumUtils.MagmaTimerAccuracy.ABOUT);
} catch (IOException ex) {
FMLLog.warning("[SkyblockAddons] Failed to get magma boss spawn estimate from server");
}
}).start();
}
public void sendPostRequest(EnumUtils.MagmaEvent event) {
new Thread(() -> {
FMLLog.info("[SkyblockAddons] Posting event " + event.getInventiveTalentEvent() + " to InventiveTalent API");
try {
String urlString = "https://hypixel-api.inventivetalent.org/api/skyblock/bosstimer/magma/addEvent";
if (event == EnumUtils.MagmaEvent.PING) {
urlString = "https://hypixel-api.inventivetalent.org/api/skyblock/bosstimer/magma/ping";
}
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("User-Agent", USER_AGENT);
Minecraft mc = Minecraft.getMinecraft();
if (mc != null && mc.thePlayer != null) {
String postString;
if (event == EnumUtils.MagmaEvent.PING) {
postString = "minecraftUser=" + mc.thePlayer.getName() + "&lastFocused=" + System.currentTimeMillis() / 1000 + "&serverId=" + serverID;
} else {
postString = "type=" + event.getInventiveTalentEvent() + "&isModRequest=true&minecraftUser=" + mc.thePlayer.getName() + "&serverId=" + serverID;
}
connection.setDoOutput(true);
try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) {
out.writeBytes(postString);
out.flush();
}
FMLLog.info("[SkyblockAddons] Got response code " + connection.getResponseCode());
connection.disconnect();
}
} catch (IOException ex) {
FMLLog.warning("[SkyblockAddons] Failed to post event to server");
}
}).start();
}
public boolean isMaterialForRecipe(ItemStack item) {
final List<String> tooltip = item.getTooltip(null, false);
for (String s : tooltip) {
if ("§5§o§eRight-click to view recipes!".equals(s)) {
return true;
}
}
return false;
}
private Set<String> reforgesWarned = new LinkedHashSet<>();
public String getReforgeFromItem(ItemStack item) {
if (item.hasTagCompound()) {
NBTTagCompound extraAttributes = item.getTagCompound();
if (extraAttributes.hasKey("reforge")) {
String reforgeTag = extraAttributes.getString("reforge");
String[] split = reforgeTag.split("_");
String reforgeName;
EnumUtils.ReforgeType reforgeType = null;
try {
reforgeType = EnumUtils.ReforgeType.valueOf(Joiner.on("_").join(Arrays.copyOfRange(split, 0, split.length - 1)));
reforgeName = reforgeType.getName();
} catch (IllegalArgumentException e) {
reforgeName = reforgeTag;
if (reforgesWarned.add(reforgeTag))
SkyblockAddons.getInstance().getUtils().sendMessage(ChatFormatting.RED + "A reforja \"" + reforgeTag + "\" ainda não possui uma tradução, por favor, entre em contato com Henry_Fabio (Henry Fábio#1347) para isso ser resolvido. OBS: Registre o nome da reforja junto com sua tradução (Nome do item reforjado).", false);
}
return reforgeType != null ? reforgeName : reforgeTag;
}
}
return null;
}
// This reverses the text while leaving the english parts intact and in order.
// (Maybe its more complicated than it has to be, but it gets the job done.
String reverseText(String originalText) {
StringBuilder newString = new StringBuilder();
String[] parts = originalText.split(" ");
for (int i = parts.length; i > 0; i--) {
String textPart = parts[i - 1];
boolean foundCharacter = false;
for (char letter : textPart.toCharArray()) {
if (letter > 191) { // Found special character
foundCharacter = true;
newString.append(new StringBuilder(textPart).reverse().toString());
break;
}
}
newString.append(" ");
if (!foundCharacter) {
newString.insert(0, textPart);
}
newString.insert(0, " ");
}
return main.getUtils().removeDuplicateSpaces(newString.toString().trim());
}
public boolean cantDropItem(ItemStack item, Rarity rarity, boolean hotbar) {
if (Items.bow.equals(item.getItem()) && rarity == Rarity.COMMON || rarity == null)
return false; // exclude rare bows lol
if (item.hasDisplayName()) {
for (String exclusion : RARE_ITEM_OVERRIDES) {
if (item.getDisplayName().contains(exclusion)) return true;
}
}
if (hotbar) { // Hotbar items also restrict rare rarity.
return item.getItem().isDamageable() || rarity != Rarity.COMMON;
} else {
return item.getItem().isDamageable() || (rarity != Rarity.COMMON && rarity != Rarity.UNCOMMON);
}
}
public void downloadPatch(String version) {
File sbaFolder = getSBAFolder(true);
if (sbaFolder != null) {
main.getUtils().sendMessage(ChatFormatting.YELLOW + Message.MESSAGE_DOWNLOADING_UPDATE.getMessage());
new Thread(() -> {
try {
String fileName = "SkyblockAddons-" + version + "-for-MC-1.8.9.jar";
URL url = new URL("https://github.com/biscuut/SkyblockAddons/releases/download/v" + version + "/" + fileName);
File outputFile = new File(sbaFolder.toString() + File.separator + fileName);
URLConnection connection = url.openConnection();
long totalFileSize = connection.getContentLengthLong();
main.getRenderListener().getDownloadInfo().setTotalBytes(totalFileSize);
main.getRenderListener().getDownloadInfo().setOutputFileName(fileName);
main.getRenderListener().getDownloadInfo().setMessageType(EnumUtils.UpdateMessageType.DOWNLOADING);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
byte[] dataBuffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
main.getRenderListener().getDownloadInfo().setDownloadedBytes(main.getRenderListener().getDownloadInfo().getDownloadedBytes() + bytesRead);
}
main.getRenderListener().getDownloadInfo().setMessageType(EnumUtils.UpdateMessageType.DOWNLOAD_FINISHED);
} catch (IOException e) {
main.getRenderListener().getDownloadInfo().setMessageType(EnumUtils.UpdateMessageType.FAILED);
e.printStackTrace();
}
}).start();
}
}
@SuppressWarnings("unchecked")
public File getSBAFolder(boolean changeMessage) {
try {
Method setupCoreModDir = CoreModManager.class.getDeclaredMethod("setupCoreModDir", File.class);
setupCoreModDir.setAccessible(true);
File coreModFolder = (File) setupCoreModDir.invoke(null, Minecraft.getMinecraft().mcDataDir);
setupCoreModDir.setAccessible(false);
if (coreModFolder.isDirectory()) {
FilenameFilter fileFilter = (dir, name) -> name.endsWith(".jar");
File[] coreModList = coreModFolder.listFiles(fileFilter);
if (coreModList != null) {
Field mccversion = FMLInjectionData.class.getDeclaredField("mccversion");
mccversion.setAccessible(true);
File versionedModDir = new File(coreModFolder, (String) mccversion.get(null));
mccversion.setAccessible(false);
if (versionedModDir.isDirectory()) {
File[] versionedCoreMods = versionedModDir.listFiles(fileFilter);
if (versionedCoreMods != null) {
coreModList = ObjectArrays.concat(coreModList, versionedCoreMods, File.class);
}
}
coreModList = ObjectArrays.concat(coreModList, ModListHelper.additionalMods.values().toArray(new File[0]), File.class);
FileListHelper.sortFileList(coreModList);
for (File coreMod : coreModList) {
JarFile jar = new JarFile(coreMod);
ZipEntry modInfo = jar.getEntry("mcmod.info");
if (modInfo != null) {
MetadataCollection metadata = MetadataCollection.from(jar.getInputStream(modInfo), coreMod.getName());
Field metadatas = metadata.getClass().getDeclaredField("metadatas");
metadatas.setAccessible(true);
for (String modId : ((Map<String, ModMetadata>) metadatas.get(metadata)).keySet()) {
if ("skyblockaddons".equals(modId)) {
return coreMod.getParentFile();
}
}
metadatas.setAccessible(false);
}
}
}
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | NoSuchFieldException | IOException e) {
e.printStackTrace();
if (changeMessage)
main.getRenderListener().getDownloadInfo().setMessageType(EnumUtils.UpdateMessageType.FAILED);
}
return null;
}
public int getNBTInteger(ItemStack item, String... path) {
if (item != null && item.hasTagCompound()) {
NBTTagCompound tag = item.getTagCompound();
for (String tagName : path) {
if (path[path.length - 1] == tagName) continue;
if (tag.hasKey(tagName)) {
tag = tag.getCompoundTag(tagName);
} else {
return -1;
}
}
return tag.getInteger(path[path.length - 1]);
}
return -1;
}
public boolean isHalloween() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.MONTH) == Calendar.OCTOBER && calendar.get(Calendar.DAY_OF_MONTH) == 31;
}
public boolean isPickaxe(Item item) {
return Items.wooden_pickaxe.equals(item) || Items.stone_pickaxe.equals(item) || Items.golden_pickaxe.equals(item) || Items.iron_pickaxe.equals(item) || Items.diamond_pickaxe.equals(item);
}
public void drawTextWithStyle(String text, int x, int y, ChatFormatting color) {
drawTextWithStyle(text, x, y, color.getRGB(), 1);
}
public void drawTextWithStyle(String text, int x, int y, int color) {
drawTextWithStyle(text, x, y, color, 1);
}
public void drawTextWithStyle(String text, int x, int y, int color, float textAlpha) {
if (main.getConfigValues().getTextStyle() == EnumUtils.TextStyle.STYLE_TWO) {
int colorBlack = new Color(0, 0, 0, textAlpha > 0.016 ? textAlpha : 0.016F).getRGB();
String strippedText = main.getUtils().stripColor(text);
MinecraftReflection.FontRenderer.drawString(strippedText, x + 1, y, colorBlack);
MinecraftReflection.FontRenderer.drawString(strippedText, x - 1, y, colorBlack);
MinecraftReflection.FontRenderer.drawString(strippedText, x, y + 1, colorBlack);
MinecraftReflection.FontRenderer.drawString(strippedText, x, y - 1, colorBlack);
MinecraftReflection.FontRenderer.drawString(text, x, y, color);
} else {
MinecraftReflection.FontRenderer.drawString(text, x, y, color, true);
}
}
public int getDefaultBlue(int alpha) {
return new Color(160, 225, 229, alpha).getRGB();
}
public String stripColor(String text) {
return RegexUtil.strip(text, RegexUtil.VANILLA_PATTERN);
}
public void reorderEnchantmentList(List<String> enchantments) {
SortedMap<Integer, String> orderedEnchants = new TreeMap<>();
for (int i = 0; i < enchantments.size(); i++) {
int nameEnd = enchantments.get(i).lastIndexOf(' ');
if (nameEnd < 0) nameEnd = enchantments.get(i).length();
int key = ORDERED_ENCHANTMENTS.indexOf(enchantments.get(i).substring(0, nameEnd).toLowerCase());
if (key < 0) key = 100 + i;
orderedEnchants.put(key, enchantments.get(i));
}
enchantments.clear();
enchantments.addAll(orderedEnchants.values());
}
}
| 47.808955 | 340 | 0.609016 |
ab4e23a12c89699bfbad405eb7db63c885daba3f | 1,990 | /*
* Copyright 2011 The Kuali Foundation.
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.ole.select.businessobject;
import org.kuali.rice.core.api.mo.common.active.MutableInactivatable;
import org.kuali.rice.krad.bo.PersistableBusinessObjectBase;
import java.util.LinkedHashMap;
public class OleRequestSourceType extends PersistableBusinessObjectBase implements MutableInactivatable {
private Integer requestSourceTypeId;
private String requestSourceType;
private boolean active;
public Integer getRequestSourceTypeId() {
return requestSourceTypeId;
}
public void setRequestSourceTypeId(Integer requestSourceTypeId) {
this.requestSourceTypeId = requestSourceTypeId;
}
public String getRequestSourceType() {
return requestSourceType;
}
public void setRequestSourceType(String requestSourceType) {
this.requestSourceType = requestSourceType;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
protected LinkedHashMap toStringMapper_RICE20_REFACTORME() {
// TODO Auto-generated method stub
LinkedHashMap m = new LinkedHashMap();
m.put("requestSourceTypeId", this.requestSourceTypeId);
m.put("requestSourceType", this.requestSourceType);
return m;
}
}
| 31.09375 | 106 | 0.71005 |
484bcf8824c73cd1e2b53fbfcdcd47092d0d3928 | 3,921 | /*
* 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.usergrid.batch.job;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.usergrid.batch.JobExecution;
import org.apache.usergrid.batch.service.JobListener;
/**
* Implementation of the JobListener for tests.
*/
public class TestJobListener implements JobListener {
// public static final long WAIT_MAX_MILLIS = 250;
public static final long WAIT_MAX_MILLIS = 60000L; // max wait 1 minutes
private static final Logger LOG = LoggerFactory.getLogger( TestJobListener.class );
private AtomicInteger submittedCounter = new AtomicInteger();
private AtomicInteger failureCounter = new AtomicInteger();
private AtomicInteger successCounter = new AtomicInteger();
private final Object lock = new Object();
public int getSubmittedCount() {
return submittedCounter.get();
}
public int getFailureCount() {
return failureCounter.get();
}
public int getSuccessCount() {
return successCounter.get();
}
public int getDoneCount() {
return successCounter.get() + failureCounter.get();
}
public void onSubmit( JobExecution execution ) {
LOG.debug( "Job execution {} submitted with count {}.", execution,
submittedCounter.incrementAndGet() );
}
public void onSuccess( JobExecution execution ) {
LOG.debug( "Job execution {} succeeded with count {}.", execution,
successCounter.incrementAndGet() );
}
public void onFailure( JobExecution execution ) {
LOG.debug( "Job execution {} failed with count {}.", execution,
failureCounter.incrementAndGet() );
}
/**
* block until submitted jobs are all accounted for.
*
* @param jobCount total submitted job
* @param idleTime idleTime in millisecond.
* @return true when all jobs are completed (could be succeed or failed) within the given idleTime range, or {@value #WAIT_MAX_MILLIS}, whichever is smaller
* @throws InterruptedException
*/
public boolean blockTilDone( int jobCount, long idleTime ) throws InterruptedException
{
final long waitTime = Math.min( idleTime, WAIT_MAX_MILLIS );
long lastChangeTime = System.currentTimeMillis();
long timeNotChanged = 0;
int currentCount;
int startCount = getDoneCount();
do {
currentCount = getDoneCount();
if ( startCount == currentCount ) {
// if ( timeNotChanged > idleTime ) {
if ( timeNotChanged > waitTime ) {
return false;
}
timeNotChanged = System.currentTimeMillis() - lastChangeTime;
}
else {
timeNotChanged = 0;
startCount = currentCount;
lastChangeTime = System.currentTimeMillis();
}
synchronized ( lock ) {
lock.wait( waitTime );
}
} while ( currentCount < jobCount );
return true;
}
}
| 32.404959 | 160 | 0.65774 |
6fa0499173796bb24a57f39573e0d0ee59c7e2c7 | 3,512 | /**
* 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.kerby.xdr;
import org.apache.kerby.xdr.type.XdrLong;
import org.apache.kerby.xdr.util.HexUtil;
import org.junit.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
public class XdrLongTest {
@Test
public void testEncoding() throws IOException {
testEncodingWith(0L, "0x00 00 00 00 00 00 00 00");
testEncodingWith(1L, "0x00 00 00 00 00 00 00 01");
testEncodingWith(2L, "0x00 00 00 00 00 00 00 02");
testEncodingWith(127L, "0x00 00 00 00 00 00 00 7F");
testEncodingWith(128L, "0x00 00 00 00 00 00 00 80");
testEncodingWith(-1L, "0xFF FF FF FF FF FF FF FF");
testEncodingWith(-127L, "0xFF FF FF FF FF FF FF 81");
testEncodingWith(-255L, "0xFF FF FF FF FF FF FF 01");
testEncodingWith(-32768L, "0xFF FF FF FF FF FF 80 00");
testEncodingWith(1234567890L, "0x00 00 00 00 49 96 02 D2");
testEncodingWith(9223372036854775807L, "0x7F FF FF FF FF FF FF FF");
testEncodingWith(-9223372036854775807L, "0x80 00 00 00 00 00 00 01");
testEncodingWith(-9223372036854775808L, "0x80 00 00 00 00 00 00 00");
}
private void testEncodingWith(long value, String expectedEncoding) throws IOException {
byte[] expected = HexUtil.hex2bytesFriendly(expectedEncoding);
XdrLong aValue = new XdrLong(value);
byte[] encodingBytes = aValue.encode();
assertThat(encodingBytes).isEqualTo(expected);
}
@Test
public void testDecoding() throws IOException {
testDecodingWith(0L, "0x00 00 00 00 00 00 00 00");
testDecodingWith(1L, "0x00 00 00 00 00 00 00 01");
testDecodingWith(2L, "0x00 00 00 00 00 00 00 02");
testDecodingWith(127L, "0x00 00 00 00 00 00 00 7F");
testDecodingWith(128L, "0x00 00 00 00 00 00 00 80");
testDecodingWith(-1L, "0xFF FF FF FF FF FF FF FF");
testDecodingWith(-127L, "0xFF FF FF FF FF FF FF 81");
testDecodingWith(-255L, "0xFF FF FF FF FF FF FF 01");
testDecodingWith(-32768L, "0xFF FF FF FF FF FF 80 00");
testDecodingWith(1234567890L, "0x00 00 00 00 49 96 02 D2");
testDecodingWith(9223372036854775807L, "0x7F FF FF FF FF FF FF FF");
testDecodingWith(-9223372036854775807L, "0x80 00 00 00 00 00 00 01");
testDecodingWith(-9223372036854775808L, "0x80 00 00 00 00 00 00 00");
}
private void testDecodingWith(long expectedValue, String content) throws IOException {
XdrLong decoded = new XdrLong();
decoded.decode(HexUtil.hex2bytesFriendly(content));
assertThat(decoded.getValue().longValue()).isEqualTo(expectedValue);
}
}
| 43.358025 | 91 | 0.684795 |
9008069396128fac2d806aab1dbd40198b9fe663 | 1,688 | package org.jayhenri.store_manager.model.inventory;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.jayhenri.store_manager.model.item.Item;
import org.jayhenri.store_manager.model.store.Store;
import javax.persistence.*;
import java.io.Serializable;
import java.util.UUID;
/**
* The type Store inventory.
*/
@Getter
@Setter
@NoArgsConstructor
@JsonIgnoreProperties({"hibernateLazyInitializer"})
@Entity
@Table(name = "store_inventory")
public class StoreInventory implements Serializable {
private static final long serialVersionUID = -1112477284611964207L;
@Id
@Column(name = "item_id", nullable = false)
private UUID inventoryUUID = UUID.randomUUID();
@Column(name = "item_name", nullable = false, unique = true)
private String itemName;
@Column(name = "quantity", nullable = false, unique = false)
private int quantity;
@Column(name = "price", nullable = false)
private double price;
@MapsId
@OneToOne
@JoinColumn(name = "item_id", unique = true, nullable = false)
private Item item;
@ManyToOne
@JoinColumn(name = "store_id", nullable = false, updatable = false)
private Store store;
/**
* Instantiates a new Store inventory.
*
* @param item the item
* @param itemName the item name
* @param quantity the quantity
* @param price the price
*/
public StoreInventory(Item item, String itemName, int quantity, double price) {
this.item = item;
this.itemName = itemName;
this.quantity = quantity;
this.price = price;
}
}
| 26.375 | 83 | 0.69609 |
445b0c82712b6daf948f2cb54b5b450821c72f7e | 1,810 | /**
* (C) Copyright IBM Corp. 2010, 2015
*
* 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.ibm.bi.dml.runtime.instructions.mr;
import com.ibm.bi.dml.hops.Hop.DataGenMethod;
import com.ibm.bi.dml.runtime.matrix.operators.Operator;
public abstract class DataGenMRInstruction extends MRInstruction
{
protected DataGenMethod method;
protected byte input;
protected long rows;
protected long cols;
protected int rowsInBlock;
protected int colsInBlock;
protected String baseDir;
public DataGenMRInstruction(Operator op, DataGenMethod mthd, byte in, byte out, long r, long c, int rpb, int cpb, String dir)
{
super(op, out);
method = mthd;
input=in;
rows = r;
cols = c;
rowsInBlock = rpb;
colsInBlock = cpb;
baseDir = dir;
}
public DataGenMethod getDataGenMethod() {
return method;
}
public byte getInput() {
return input;
}
public long getRows() {
return rows;
}
public long getCols() {
return cols;
}
public int getRowsInBlock() {
return rowsInBlock;
}
public int getColsInBlock() {
return colsInBlock;
}
public String getBaseDir() {
return baseDir;
}
@Override
public byte[] getInputIndexes() {
return new byte[]{input};
}
@Override
public byte[] getAllIndexes() {
return new byte[]{input, output};
}
}
| 21.547619 | 126 | 0.714917 |
502ed2e2142fe157c2626c4ff68adf49a5825ac3 | 11,619 | /*
* Copyright (c) 2008-2013, Hazelcast, Inc. 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 com.hazelcast.query;
import com.hazelcast.query.impl.DateHelperTest;
import com.hazelcast.query.impl.QueryEntry;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import static com.hazelcast.instance.TestUtil.toData;
import static com.hazelcast.query.SampleObjects.Employee;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class SqlPredicateTest {
@Test
public void testEqualsWhenSqlMatches() throws Exception {
SqlPredicate sql1 = new SqlPredicate("foo='bar'");
SqlPredicate sql2 = new SqlPredicate("foo='bar'");
assertEquals(sql1, sql2);
}
@Test
public void testEqualsWhenSqlDifferent() throws Exception {
SqlPredicate sql1 = new SqlPredicate("foo='bar'");
SqlPredicate sql2 = new SqlPredicate("foo='baz'");
assertNotEquals(sql1, sql2);
}
@Test
public void testEqualsNull() throws Exception {
SqlPredicate sql = new SqlPredicate("foo='bar'");
assertNotEquals(sql, null);
}
@Test
public void testEqualsSameObject() throws Exception {
SqlPredicate sql = new SqlPredicate("foo='bar'");
assertEquals(sql, sql);
}
@Test
public void testHashCode() throws Exception {
SqlPredicate sql = new SqlPredicate("foo='bar'");
assertEquals("foo='bar'".hashCode(), sql.hashCode());
}
@Test
public void testSql_withEnum() {
Employee value = createValue();
value.setState(SampleObjects.State.STATE2);
Employee nullNameValue = createValue(null);
assertSqlTrue("state == TestUtil.State.STATE2", value);
assertSqlTrue("state == " + SampleObjects.State.STATE2, value);
assertSqlFalse("state == TestUtil.State.STATE1", value);
assertSqlFalse("state == TestUtil.State.STATE1", nullNameValue);
assertSqlTrue("state == NULL", nullNameValue);
}
@Test
public void testSql_withDate() {
Employee value = createValue();
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateHelperTest.DATE_FORMAT, Locale.US);
assertSqlTrue("createDate >= '" + simpleDateFormat.format(new Date(0)) + "'", value);
assertSqlTrue("sqlDate >= '" + new java.sql.Date(0) + "'", value);
assertSqlTrue("date >= '" + new Timestamp(0) + "'", value);
}
@Test
public void testSql_withBigDecimal() {
Employee value = createValue();
assertSqlTrue("bigDecimal > '" + new BigDecimal("1.23E2") + "'", value);
assertSqlTrue("bigDecimal >= '" + new BigDecimal("1.23E3") + "'", value);
assertSqlFalse("bigDecimal = '" + new BigDecimal("1.23") + "'", value);
assertSqlTrue("bigDecimal = '1.23E3'", value);
assertSqlTrue("bigDecimal = 1.23E3", value);
assertSqlFalse("bigDecimal = 1.23", value);
}
@Test
public void testSql_withString() {
Employee value = createValue();
Employee nullNameValue = new Employee(null, 34, true, 10D);
assertSqlFalse("name = 'null'", nullNameValue);
assertSqlTrue("name = null", nullNameValue);
assertSqlTrue("name = NULL", nullNameValue);
assertSqlTrue("name != null", value);
assertSqlTrue("name != NULL", value);
assertSqlTrue(" (name LIKE 'abc-%') AND (age <= " + 40 + ")", value);
assertSqlTrue(" (name REGEX 'abc-.*') AND (age <= " + 40 + ")", value);
assertSqlTrue("name='abc-123-xvz'", value);
assertSqlTrue("name='abc 123-xvz'", createValue("abc 123-xvz"));
assertSqlTrue("name='abc 123-xvz+(123)'", createValue("abc 123-xvz+(123)"));
assertSqlFalse("name='abc 123-xvz+(123)'", createValue("abc123-xvz+(123)"));
assertSqlTrue("name LIKE 'abc-%'", createValue("abc-123"));
assertSqlTrue("name REGEX '^\\w{3}-\\d{3}-\\w{3}$'", value);
assertSqlFalse("name REGEX '^[^\\w]{3}-\\d{3}-\\w{3}$'", value);
assertSqlTrue(" (name ILIKE 'ABC-%') AND (age <= " + 40 + ")", value);
}
@Test
public void testSql_withInteger() {
Employee value = new Employee("abc-123-xvz", 34, true, 10D);
assertSqlTrue("(age >= " + 20 + ") AND (age <= " + 40 + ")", value);
assertSqlTrue("(age >= " + 20 + ") AND (age <= " + 34 + ")", value);
assertSqlTrue("(age >= " + 34 + ") AND (age <= " + 35 + ")", value);
assertSqlTrue("age IN (" + 34 + ", " + 35 + ")", value);
assertSqlFalse("age = 33", value);
assertSqlTrue("age = 34", value);
assertSqlTrue("age > 5", value);
assertSqlTrue("age = -33", createValue(-33));
}
@Test
public void testSql_withDouble() {
Employee value = new Employee("abc-123-xvz", 34, true, 10D);
assertSqlTrue("salary > 5", value);
assertSqlTrue("salary > 5 and salary < 11", value);
assertSqlFalse("salary > 15 or salary < 10", value);
assertSqlTrue("salary between 9.99 and 10.01", value);
assertSqlTrue("salary between 5 and 15", value);
}
@Test
public void testSqlPredicate() {
assertEquals("name IN (name0,name2)", sql("name in ('name0', 'name2')"));
assertEquals("(name LIKE 'joe' AND id=5)", sql("name like 'joe' AND id = 5"));
assertEquals("(name REGEX '\\w*' AND id=5)", sql("name regex '\\w*' AND id = 5"));
assertEquals("active=true", sql("active"));
assertEquals("(active=true AND name=abc xyz 123)", sql("active AND name='abc xyz 123'"));
assertEquals("(name LIKE 'abc-xyz+(123)' AND name=abc xyz 123)", sql("name like 'abc-xyz+(123)' AND name='abc xyz 123'"));
assertEquals("(name REGEX '\\w{3}-\\w{3}+\\(\\d{3}\\)' AND name=abc xyz 123)", sql("name regex '\\w{3}-\\w{3}+\\(\\d{3}\\)' AND name='abc xyz 123'"));
assertEquals("(active=true AND age>4)", sql("active and age > 4"));
assertEquals("(active=true AND age>4)", sql("active and age>4"));
assertEquals("(active=false AND age<=4)", sql("active=false AND age<=4"));
assertEquals("(active=false AND age<=4)", sql("active= false and age <= 4"));
assertEquals("(active=false AND age>=4)", sql("active=false AND (age>=4)"));
assertEquals("(active=false OR age>=4)", sql("active =false or (age>= 4)"));
assertEquals("name LIKE 'J%'", sql("name like 'J%'"));
assertEquals("name REGEX 'J.*'", sql("name regex 'J.*'"));
assertEquals("NOT(name LIKE 'J%')", sql("name not like 'J%'"));
assertEquals("NOT(name REGEX 'J.*')", sql("name not regex 'J.*'"));
assertEquals("(active=false OR name LIKE 'J%')", sql("active =false or name like 'J%'"));
assertEquals("(active=false OR name LIKE 'Java World')", sql("active =false or name like 'Java World'"));
assertEquals("(active=false OR name LIKE 'Java W% Again')", sql("active =false or name like 'Java W% Again'"));
assertEquals("(active=false OR name REGEX 'J.*')", sql("active =false or name regex 'J.*'"));
assertEquals("(active=false OR name REGEX 'Java World')", sql("active =false or name regex 'Java World'"));
assertEquals("(active=false OR name REGEX 'Java W.* Again')", sql("active =false or name regex 'Java W.* Again'"));
assertEquals("i<=-1", sql("i<= -1"));
assertEquals("age IN (-1)", sql("age in (-1)"));
assertEquals("age IN (10,15)", sql("age in (10, 15)"));
assertEquals("NOT(age IN (10,15))", sql("age not in ( 10 , 15 )"));
assertEquals("(active=true AND age BETWEEN 10 AND 15)", sql("active and age between 10 and 15"));
assertEquals("(age IN (10,15) AND active=true)", sql("age IN (10, 15) and active"));
assertEquals("(active=true OR age IN (10,15))", sql("active or (age in ( 10,15))"));
assertEquals("(age>10 AND (active=true OR age IN (10,15)))", sql("age>10 AND (active or (age IN (10, 15 )))"));
assertEquals("(age<=10 AND (active=true OR NOT(age IN (10,15))))", sql("age<=10 AND (active or (age not in (10 , 15)))"));
assertEquals("age BETWEEN 10 AND 15", sql("age between 10 and 15"));
assertEquals("NOT(age BETWEEN 10 AND 15)", sql("age not between 10 and 15"));
assertEquals("(active=true AND age BETWEEN 10 AND 15)", sql("active and age between 10 and 15"));
assertEquals("(age BETWEEN 10 AND 15 AND active=true)", sql("age between 10 and 15 and active"));
assertEquals("(active=true OR age BETWEEN 10 AND 15)", sql("active or (age between 10 and 15)"));
assertEquals("(age>10 AND (active=true OR age BETWEEN 10 AND 15))", sql("age>10 AND (active or (age between 10 and 15))"));
assertEquals("(age<=10 AND (active=true OR NOT(age BETWEEN 10 AND 15)))", sql("age<=10 AND (active or (age not between 10 and 15))"));
assertEquals("name ILIKE 'J%'", sql("name ilike 'J%'"));
//issue #594
assertEquals("(name IN (name0,name2) AND age IN (2,5,8))", sql("name in('name0', 'name2') and age IN ( 2, 5 ,8)"));
}
@Test
public void testSqlPredicateEscape() {
assertEquals("(active=true AND name=abc x'yz 1'23)", sql("active AND name='abc x''yz 1''23'"));
assertEquals("(active=true AND name=)", sql("active AND name=''"));
}
@Test(expected = RuntimeException.class)
public void testInvalidSqlPredicate1() {
new SqlPredicate("invalid sql");
}
@Test(expected = RuntimeException.class)
public void testInvalidSqlPredicate2() {
new SqlPredicate("");
}
private String sql(String sql) {
return new SqlPredicate(sql).toString();
}
private static Map.Entry createEntry(final Object key, final Object value) {
return new QueryEntry(null, toData(key), key, value);
}
private void assertSqlTrue(String s, Object value) {
final SqlPredicate predicate = new SqlPredicate(s);
final Map.Entry entry = createEntry("1", value);
assertTrue(predicate.apply(entry));
}
private void assertSqlFalse(String s, Object value) {
final SqlPredicate predicate = new SqlPredicate(s);
final Map.Entry entry = createEntry("1", value);
assertFalse(predicate.apply(entry));
}
private Employee createValue() {
return new Employee("abc-123-xvz", 34, true, 10D);
}
private Employee createValue(String name) {
return new Employee(name, 34, true, 10D);
}
private Employee createValue(int age) {
return new Employee("abc-123-xvz", age, true, 10D);
}
}
| 45.924901 | 158 | 0.624236 |
f6221e658adf761c2473baaefed2fdb204ffdb28 | 956 | package com.silwings.vod.starter.service;
import com.silwings.vod.starter.pojo.vod.dto.VideoMessageDto;
import org.springframework.web.multipart.MultipartFile;
/**
* @author CuiYiXiang
* @Classname VideoService
* @Description TODO
* @Date 2020/7/30
*/
public interface VideoService {
/**
* description: 获取上传码
* version: 1.0
* date: 2020/7/30 10:35
* author: 崔益翔
*
* @param size
* @return java.lang.String
*/
String getUpLoadHashKey(String size);
/**
* description: 视频上传
* version: 1.0
* date: 2020/7/30 10:36
* author: 崔益翔
*
* @param file
* @return VideoMessageDto
*/
VideoMessageDto videoUpload(MultipartFile file, String hashKey);
/**
* description: 获取视频上传状态
* version: 1.0
* date: 2020/7/31 10:16
* author: 崔益翔
* @param hashKey
* @return VideoMessageDto
*/
VideoMessageDto getUpStatus(String hashKey);
}
| 20.782609 | 68 | 0.621339 |
96cebbf1222a8181049f94468edec0157c3b6bb6 | 604 | package com.ruidev.framework.exception;
/**
* 系统异常封装类
*/
public class SysException extends BaseException {
private static final long serialVersionUID = 1L;
/**
* 构造函数:出错信息码
*
* @param errorId
* 出错信息码
*/
public SysException(int errorId) {
super(errorId);
}
/**
* 构造函数:出错信息码
*
* @param errorId
* 出错信息码
* @param arguments
* 替换信息
*/
public SysException(int errorId, Object... arguments) {
super(errorId, arguments);
}
/**
* 默认构造函数
*/
public SysException(String msg) {
super(msg);
}
}
| 15.487179 | 57 | 0.561258 |
85720ec2937c1cb32285255fb8a87cd4bd2939e0 | 5,357 | package com.ios.backend.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ios.backend.dto.NewTaskDTO;
import com.ios.backend.dto.WorkDTO;
import com.ios.backend.entities.Task;
import com.ios.backend.resources.CalendarListResource;
import com.ios.backend.resources.CalendarResource;
import com.ios.backend.resources.TaskListResource;
import com.ios.backend.resources.TaskRecordListResource;
import com.ios.backend.services.TaskService;
import com.ios.backend.utils.Client;
@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@RestController
public class TaskController {
final String clientUrl = Client.clientUrl;
@Autowired
private TaskService service;
@PostMapping("/createTask")
//@CrossOrigin(origins = clientUrl)
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<Boolean> createTask(@RequestBody NewTaskDTO newTaskDto) {
Task task = new Task();
BeanUtils.copyProperties(newTaskDto.getTask(), task);
service.createTask(task, newTaskDto.getUser());
return new ResponseEntity<Boolean>(true,HttpStatus.OK);
}
@GetMapping("/getAllTaskRecordByUser/{pid}/{uid}")
//@CrossOrigin(origins = clientUrl)
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<TaskRecordListResource> getAllTaskRecordByUser(@PathVariable("pid") Long pid, @PathVariable("uid") Long uid) {
// service call
TaskRecordListResource trlr = service.getAllTaskRecordOfUserAndProgram(uid, pid);
return new ResponseEntity<TaskRecordListResource>(trlr, HttpStatus.OK);
}
@GetMapping("/getAllTaskByUser/{pid}/{uid}")
// @CrossOrigin(origins = clientUrl)
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<TaskListResource> getAllTaskByUser(@PathVariable("pid") Long pid, @PathVariable("uid") Long uid) {
// service call
TaskListResource tlr = service.getAllTaskOfUserAndProgram(uid, pid);
return new ResponseEntity<TaskListResource>(tlr, HttpStatus.OK);
}
@GetMapping("/getAllTaskRecord")
// @CrossOrigin(origins = clientUrl)
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<TaskRecordListResource> getAllTaskRecord() {
// service call
TaskRecordListResource trlr = service.getAllTaskRecord();
return new ResponseEntity<TaskRecordListResource>(trlr, HttpStatus.OK);
}
@GetMapping("/getAllTaskByProgram/{pid}")
//@CrossOrigin(origins = clientUrl)
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<TaskListResource> getAllTaskByProgram(@PathVariable("pid") Long pid) {
// service call
TaskListResource tlr = service.getAllTaskByProgram(pid);
return new ResponseEntity<TaskListResource>(tlr, HttpStatus.OK);
}
@PostMapping("/updateTaskStatus/{status}")
// @CrossOrigin(origins = clientUrl)
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<?> updateTaskStatus(@PathVariable("status") String status) {
return new ResponseEntity<>(HttpStatus.OK);
}
@GetMapping("/getTaskCalendar/{pid}/{uid}")
//@CrossOrigin(origins = clientUrl)
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<CalendarListResource> getTaskCalendar(@PathVariable("pid") Long pid, @PathVariable("uid") Long uid) {
// service call
TaskListResource tlr = service.getAllTaskOfUserAndProgram(uid, pid);
List<CalendarResource> cl = new ArrayList<CalendarResource>();
List<Task> tl = tlr.getTaskList();
for(Task t: tl) {
CalendarResource cr = new CalendarResource();
cr.setTitle(t.getName());
cr.setStart(t.getStartTime());
cr.setEnd(t.getDeadline());
cl.add(cr);
}
CalendarListResource clr = new CalendarListResource();
clr.setEvents(cl);
return new ResponseEntity<CalendarListResource>(clr, HttpStatus.OK);
}
@PostMapping("/addTaskWork/{pid}/{uid}/{tid}")
@CrossOrigin(origins = clientUrl)
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<?> addWork(@PathVariable("pid") Long pid, @PathVariable("uid") Long uid, @PathVariable("tid") Long tid, @RequestBody WorkDTO work) {
// service call
service.addWork(uid, pid, tid, work.getWork());
return new ResponseEntity<Boolean>(true, HttpStatus.OK);
}
@GetMapping("/getTaskWork/{pid}/{uid}/{tid}")
@CrossOrigin(origins = clientUrl)
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<WorkDTO> getWork(@PathVariable("pid") Long pid, @PathVariable("uid") Long uid, @PathVariable("tid") Long tid) {
// service call
WorkDTO response = service.getWork(uid, pid, tid);
return new ResponseEntity<WorkDTO>(response, HttpStatus.OK);
}
}
| 41.527132 | 156 | 0.746127 |
c36c9f8629fac4415608db0569116d33545d408c | 716 | /**
* 描述:源数据程序入口
* 包名:com.lvmoney.pay.gateway.application
* 版本信息: 版本1.0
* 日期:2018年9月30日 上午8:51:33
* Copyright XXXXXX科技有限公司
*/
package com.lvmoney.frame.sync.canal.common.application;
import com.lvmoney.frame.sync.canal.common.annotation.EnableCanalClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @describe:统一网关,springboot主方法
* @author: lvmoney /XXXXXX科技有限公司
* @version:v1.0 2018年9月30日 上午8:51:33
*/
@SpringBootApplication(scanBasePackages = {"com.lvmoney.**"})
@EnableCanalClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| 25.571429 | 72 | 0.755587 |
c3c82ce4c6cf4970d4763d6319b5079d579bbf96 | 974 | package stack_and_queue;
import java.util.ArrayList;
import java.util.List;
public class FirstNonRepeatingCharacter {
public String firstNonRepeating(String s) {
final int[] arr = new int[26];
StringBuilder result = new StringBuilder();
List<Character> nrc = new ArrayList<>();
for (char c : s.toCharArray()) {
arr[Character.getNumericValue(c) - 10]++;
if (arr[Character.getNumericValue(c) - 10] == 1) {
nrc.add(c);
} else {
if (nrc.contains(c)) nrc.remove((Character) c);
}
if (!nrc.isEmpty()) {
result.append(nrc.get(0));
} else {
result.append('#');
}
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(new FirstNonRepeatingCharacter().firstNonRepeating("hrqcvsvszpsjammdrw")); // hhhhhhhhhhhhhhhhhh
}
}
| 27.828571 | 124 | 0.554415 |
cb8e275241477a288000dc398468b8f0b81bc077 | 3,290 | /**
* Project Name:kafa-wheat-core
* File Name:UserDO.java
* Package Name:com.kind.perm.core.domain
* Date:2016年6月6日下午5:37:27
* Copyright (c) 2016, weiguo21@126.com All Rights Reserved.
*
*/
package com.kind.perm.core.domain;
import java.io.Serializable;
import java.util.Date;
/**
* Function: 用户. <br/>
* Date: 2016年6月6日 下午5:37:27 <br/>
*
* @author weiguo.liu
* @version
* @since JDK 1.7
* @see
*/
public class UserDO implements Serializable {
private static final long serialVersionUID = 6699967885317239481L;
/**
* 主键
*/
private Long id;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 姓名
*/
private String name;
/**
* 生日
*/
private Date birthday;
/**
* 性别
*/
private Integer gender;
/**
* 邮箱
*/
private String email;
/**
* 手机
*/
private String mobile;
/**
* 描述
*/
private String description;
/**
* 状态
*/
private Integer status;
/**
* 登录次数
*/
private Integer visitCount;
/**
* 最后一次登录时间
*/
private Date lastVisitTime;
/**
* 创建人
*/
private String createUser;
/**
* 最后修改人
*/
private String modifyUser;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date modifyTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getVisitCount() {
return visitCount;
}
public void setVisitCount(Integer visitCount) {
this.visitCount = visitCount;
}
public Date getLastVisitTime() {
return lastVisitTime;
}
public void setLastVisitTime(Date lastVisitTime) {
this.lastVisitTime = lastVisitTime;
}
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public String getModifyUser() {
return modifyUser;
}
public void setModifyUser(String modifyUser) {
this.modifyUser = modifyUser;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getModifyTime() {
return modifyTime;
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
}
| 15.022831 | 67 | 0.669909 |
5ebddcd0f74b28e43731e344949377801abc98b4 | 424 | package com.aminebag.larjson.configuration;
import java.lang.reflect.Method;
/**
* @author Amine Bagdouri
*
* A factory of {@link PropertyConfiguration}
*/
public interface PropertyConfigurationFactory {
/**
* @param getter getter method
* @return a property configuration corresponding to the given getter method if found, {@code null} otherwise
*/
PropertyConfiguration get(Method getter);
}
| 23.555556 | 113 | 0.726415 |
109b0944b5cd244fbf1d07540947ff658601092a | 1,211 | package com.litiengine.gurknukem.entities;
import de.gurkenlabs.litiengine.Direction;
import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.entities.Creature;
import de.gurkenlabs.litiengine.entities.IEntity;
import de.gurkenlabs.litiengine.entities.behavior.IBehaviorController;
public class EnemyController implements IBehaviorController {
private final Creature enemy;
private long directionChanged;
private long nextDirectionChage;
private Direction direction;
public EnemyController(Creature enemy) {
this.enemy = enemy;
}
@Override
public IEntity getEntity() {
return this.enemy;
}
@Override
public void update() {
if (this.enemy.isDead()) {
return;
}
final long timeSinceDirectionChange = Game.time().since(this.directionChanged);
if (timeSinceDirectionChange > this.nextDirectionChage) {
direction = this.direction == Direction.LEFT ? Direction.RIGHT : Direction.LEFT;
this.directionChanged = Game.time().now();
this.nextDirectionChage = Game.random().nextLong(1000, 2000);
}
this.getEntity().setAngle(this.direction.toAngle());
Game.physics().move(this.enemy, this.enemy.getTickVelocity());
}
}
| 29.536585 | 86 | 0.744013 |
87278073228a6423b07af3e28352478e87ba280b | 2,758 | package com.commercetools.payment.domain;
import com.commercetools.payment.model.CreatePaymentData;
import com.commercetools.payment.model.HttpRequestInfo;
import io.sphere.sdk.carts.Cart;
import io.sphere.sdk.client.SphereClient;
import io.sphere.sdk.customers.Customer;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Created by mgatz on 7/20/16.
*/
public class CreatePaymentDataTest {
private static final String CLIENT_TO_STRING = "foo";
private static final String CART_TO_STRING = "bar";
private static final String CUSTOMER_TO_STRING = "hoe";
private static final String REQUEST_TO_STRING = "woo";
private static final String METHOD_ID = "mid";
private static final String INTERFACE_ID = "iid";
private static final String REFERENCE = "ref";
@Mock
private SphereClient mockClient;
@Mock
private Cart mockCart;
@Mock
private Customer mockCustomer;
@Mock
private HttpRequestInfo mockRequestInfo;
@Before
public void setup() {
mockClient = mock(SphereClient.class);
mockCart = mock(Cart.class);
mockCustomer = mock(Customer.class);
mockRequestInfo = mock(HttpRequestInfo.class);
when(mockClient.toString()).thenReturn(CLIENT_TO_STRING);
when(mockCart.toString()).thenReturn(CART_TO_STRING);
when(mockCustomer.toString()).thenReturn(CUSTOMER_TO_STRING);
when(mockRequestInfo.toString()).thenReturn(REQUEST_TO_STRING);
}
@Test
public void of() {
CreatePaymentData cpd = CreatePaymentDataBuilder.of(mockClient, INTERFACE_ID, METHOD_ID, mockCart, REFERENCE).build();
assertThat(cpd.getSphereClient().toString()).isEqualTo(CLIENT_TO_STRING);
assertThat(cpd.getCart().toString()).isEqualTo(CART_TO_STRING);
assertThat(cpd.getReference()).isEqualTo(REFERENCE);
}
@Test
public void addCustomer() {
CreatePaymentData cpd = CreatePaymentDataBuilder.of(mockClient, INTERFACE_ID, METHOD_ID, mockCart, REFERENCE).withCustomer(mockCustomer).build();
assertThat(cpd.getCustomer().isPresent()).isTrue();
assertThat(cpd.getCustomer().get().toString()).isEqualTo(CUSTOMER_TO_STRING);
}
@Test
public void addHttpRequestInformation() {
CreatePaymentData cpd = CreatePaymentDataBuilder.of(mockClient, INTERFACE_ID, METHOD_ID, mockCart, REFERENCE).withHttpRequestInfo(mockRequestInfo).build();
assertThat(cpd.getHttpRequestInfo().isPresent()).isTrue();
assertThat(cpd.getHttpRequestInfo().get().toString()).isEqualTo(REQUEST_TO_STRING);
}
} | 37.27027 | 163 | 0.729877 |
70d0853cc6d96be0e387aec09ffaf965386268b9 | 2,905 | package de.lieferdienst.controllers.productManagment;
import de.lieferdienst.model.errors.NotFounfException;
import de.lieferdienst.model.productManagment.Category;
import de.lieferdienst.model.productManagment.Restaurant;
import de.lieferdienst.repository.storage.CategoryRepository;
import de.lieferdienst.repository.storage.RestaurantRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@Transactional
@RestController
@RequestMapping("/api/category")
public class CategoryController {
private final CategoryRepository categoryRepository;
private final RestaurantRepository restaurantRepository;
@Autowired
public CategoryController(CategoryRepository categoryRepository, RestaurantRepository restaurantRepository) {
this.categoryRepository = categoryRepository;
this.restaurantRepository = restaurantRepository;
}
@GetMapping("/default")
ResponseEntity<List<Category>> getAllCategories()
{
return ResponseEntity.ok(this.categoryRepository.findAll());
}
@GetMapping(path = "/{id}")
ResponseEntity<Category> findCategoryByID(@PathVariable(value = "id") Long id) throws NotFounfException
{
return ResponseEntity.ok(this.categoryRepository
.findById(id)
.orElseThrow(() -> new NotFounfException("No Category found for id " + id)));
}
@PostMapping(path = "/add", produces = "application/json")
ResponseEntity<Category> addNewCategory(@RequestParam String sortTitle,@RequestParam Long restaurantId) {
Optional<Restaurant> restaurantOptional = restaurantRepository.findById(restaurantId);
Restaurant restaurant = restaurantOptional.get();
Category category = new Category(sortTitle,restaurant);
return ResponseEntity.ok(this.categoryRepository.save(category));
}
@PutMapping(path = "/update/{id}", produces = "application/json")
ResponseEntity<Category> updateCategory(@PathVariable Long id, @RequestBody Category newCategory) {
return categoryRepository.findById(id)
.map( category -> {
category.setSortTitle(newCategory.getSortTitle());
category.setRestaurant(newCategory.getRestaurant());
return ResponseEntity.ok(this.categoryRepository.save(category));
})
.orElseGet(() -> {
newCategory.setId(id);
return ResponseEntity.ok(this.categoryRepository.save(newCategory));
});
}
@DeleteMapping("/delete/{id}")
void deleteCategory(@PathVariable Long id) {
this.categoryRepository.deleteById(id);
}
}
| 39.794521 | 113 | 0.71704 |
ad1f541d9d3887279d27a0989ec65fab85a293c8 | 7,219 | package org.consenlabs.tokencore.foundation.crypto;
import junit.framework.Assert;
import static org.junit.Assert.*;
import org.consenlabs.tokencore.wallet.model.Messages;
import org.consenlabs.tokencore.wallet.model.TokenException;
import org.consenlabs.tokencore.foundation.utils.NumericUtil;
import org.consenlabs.tokencore.wallet.SampleKey;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* Created by xyz on 2018/2/3.
*/
public class CryptoTest {
byte[] prvKeyBytes = NumericUtil.hexToBytes(SampleKey.PRIVATE_KEY_STRING);
@Rule
public ExpectedException thrown= ExpectedException.none();
@Test
public void testCreatePBKDF2Crypto() {
Crypto crypto = Crypto.createPBKDF2Crypto(SampleKey.PASSWORD, prvKeyBytes);
assertTrue(crypto instanceof PBKDF2Crypto);
assertEquals(Crypto.CTR, crypto.getCipher());
assertNotNull(crypto.getCipherparams());
assertNotNull(crypto.getCipherparams().getIv());
assertEquals(32, crypto.getCipherparams().getIv().length());
assertEquals(PBKDF2Crypto.PBKDF2, crypto.getKdf());
assertTrue(crypto.getKdfparams() instanceof PBKDF2Params);
PBKDF2Params params = (PBKDF2Params)crypto.getKdfparams();
assertEquals(PBKDF2Params.C_LIGHT, params.getC());
assertEquals(PBKDF2Params.PRF, params.getPrf());
assertEquals(KDFParams.DK_LEN, params.getDklen());
assertNotNull(params.getSalt());
assertEquals(64, params.getSalt().length());
assertNotNull(crypto.getCiphertext());
assertArrayEquals(prvKeyBytes, crypto.decrypt(SampleKey.PASSWORD));
}
@Test
public void testDerivedKey() {
Crypto crypto = Crypto.createPBKDF2Crypto(SampleKey.PASSWORD, prvKeyBytes);
assertFalse(crypto.verifyPassword(SampleKey.WRONG_PASSWORD));
assertTrue(crypto.verifyPassword(SampleKey.PASSWORD));
byte[] derivedKey = crypto.generateDerivedKey(SampleKey.PASSWORD.getBytes());
assertNotNull(derivedKey);
assertEquals(32, derivedKey.length);
}
@Test
public void testValidate() {
thrown.expect(TokenException.class);
thrown.expectMessage(Messages.WALLET_INVALID);
Crypto crypto = Crypto.createPBKDF2Crypto(SampleKey.PASSWORD, prvKeyBytes);
crypto.validate();
assertTrue("Should not throw any exception", true);
crypto.cipher = "not-valid-ctr";
crypto.validate();
assertTrue("Shoud return in early statements", false);
}
@Test
public void testDecrypt() {
thrown.expect(TokenException.class);
thrown.expectMessage(Messages.WALLET_INVALID_PASSWORD);
Crypto crypto = Crypto.createPBKDF2Crypto(SampleKey.PASSWORD, prvKeyBytes);
byte[] result = crypto.decrypt(SampleKey.PASSWORD);
assertArrayEquals(prvKeyBytes, result);
crypto.decrypt(SampleKey.WRONG_PASSWORD);
assertTrue("Should return in early statements", false);
}
@Test
public void testDeriveAndDecryptEncPair() {
Crypto crypto = Crypto.createPBKDF2Crypto(SampleKey.PASSWORD, prvKeyBytes);
EncPair pair = crypto.deriveEncPair(SampleKey.PASSWORD, SampleKey.MNEMONIC.getBytes());
assertNotNull(pair);
assertArrayEquals(SampleKey.MNEMONIC.getBytes(), crypto.decryptEncPair(SampleKey.PASSWORD, pair));
thrown.expect(TokenException.class);
thrown.expectMessage(Messages.WALLET_INVALID_PASSWORD);
crypto.decryptEncPair(SampleKey.WRONG_PASSWORD, pair);
assertTrue("Should return in early statements", false);
}
@Test
public void testDecryptSCryptCrypto() {
Crypto crypto = Crypto.createSCryptCrypto(SampleKey.PASSWORD, prvKeyBytes);
assertTrue(crypto instanceof SCryptCrypto);
assertEquals(Crypto.CTR, crypto.getCipher());
assertNotNull(crypto.getCipherparams());
assertNotNull(crypto.getCipherparams().getIv());
assertEquals(32, crypto.getCipherparams().getIv().length());
assertEquals(SCryptCrypto.SCRYPT, crypto.getKdf());
assertTrue(crypto.getKdfparams() instanceof SCryptParams);
SCryptParams params = (SCryptParams)crypto.getKdfparams();
assertEquals(SCryptParams.COST_FACTOR, params.getN());
assertEquals(SCryptParams.BLOCK_SIZE_FACTOR, params.getR());
assertEquals(SCryptParams.PARALLELIZATION_FACTOR, params.getP());
assertEquals(KDFParams.DK_LEN, params.getDklen());
assertNotNull(params.getSalt());
assertEquals(64, params.getSalt().length());
assertNotNull(crypto.getCiphertext());
assertArrayEquals(prvKeyBytes, crypto.decrypt(SampleKey.PASSWORD));
}
@Test
public void testCreateAndDestroyCacheDerivedKey() {
Crypto crypto = Crypto.createPBKDF2Crypto(SampleKey.PASSWORD, prvKeyBytes);
Assert.assertNull(crypto.getCachedDerivedKey());
crypto = Crypto.createPBKDF2CryptoWithKDFCached(SampleKey.PASSWORD, prvKeyBytes);
Assert.assertNotNull(crypto.getCachedDerivedKey());
crypto.clearCachedDerivedKey();
Assert.assertNull(crypto.getCachedDerivedKey());
crypto.cacheDerivedKey(SampleKey.PASSWORD);
// This function can reenter
crypto.cacheDerivedKey(SampleKey.PASSWORD);
Assert.assertNotNull(crypto.getCachedDerivedKey());
crypto.clearCachedDerivedKey();
// This function can reenter
crypto.clearCachedDerivedKey();
Assert.assertNull(crypto.getCachedDerivedKey());
}
@Test
public void testVerifyPasswordCachedDerivedKey() {
Crypto crypto = Crypto.createPBKDF2Crypto(SampleKey.PASSWORD, prvKeyBytes);
try {
crypto.cacheDerivedKey(SampleKey.WRONG_PASSWORD);
Assert.fail("Should throw invalid password");
} catch (Exception ex) {
Assert.assertTrue(ex.getMessage().contains(Messages.WALLET_INVALID_PASSWORD));
}
try {
crypto.cacheDerivedKey(SampleKey.PASSWORD);
crypto.cacheDerivedKey(SampleKey.WRONG_PASSWORD);
Assert.fail("Although it caches the derivedKey, it should throw 'wrong password' when enter the wrong password");
} catch (Exception ex) {
Assert.assertTrue(ex.getMessage().contains(Messages.WALLET_INVALID_PASSWORD));
}
}
@Test(timeout = 1000)
public void testCacheIsInUsedWhenCreateWithCache() {
Crypto crypto = Crypto.createPBKDF2CryptoWithKDFCached(SampleKey.PASSWORD, prvKeyBytes);
long begin = System.currentTimeMillis();
for (int i=0; i< 1000; i++) {
crypto.verifyPassword(SampleKey.PASSWORD);
crypto.decrypt(SampleKey.PASSWORD);
EncPair encPair = crypto.deriveEncPair(SampleKey.PASSWORD, "imToken".getBytes());
crypto.decryptEncPair(SampleKey.PASSWORD, encPair);
}
System.out.println(String.format("It takes %d ms to test 1000 times", System.currentTimeMillis() - begin));
}
@Test(timeout = 1000)
public void testCacheIsInUsed() {
Crypto crypto = Crypto.createPBKDF2Crypto(SampleKey.PASSWORD, prvKeyBytes);
crypto.cacheDerivedKey(SampleKey.PASSWORD);
long begin = System.currentTimeMillis();
for (int i=0; i< 1000; i++) {
crypto.verifyPassword(SampleKey.PASSWORD);
crypto.decrypt(SampleKey.PASSWORD);
EncPair encPair = crypto.deriveEncPair(SampleKey.PASSWORD, "imToken".getBytes());
crypto.decryptEncPair(SampleKey.PASSWORD, encPair);
}
System.out.println(String.format("It takes %d ms to test 1000 times", System.currentTimeMillis() - begin));
}
}
| 37.598958 | 119 | 0.748165 |
f8ff14255df3d1c28159ceaeb51330c066b639b6 | 793 | package com.xjldtc;
import java.util.Arrays;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
//@MapperScan({"com.xjldtc.user.mapper.*"})
public class CEPApplication {
public static void main(String[] args) {
//System.setProperty("spring.devtools.restart.enabled","false");
ApplicationContext ctx = SpringApplication.run(CEPApplication.class, args);
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}
| 30.5 | 77 | 0.778058 |
21694f3da90aa03d28f1156c357450a8e5304708 | 2,167 | package org.enricogiurin.codingchallenges.pramp;
/*
Shifted Array Search
A sorted array of distinct integers shiftArr is shifted to the left by an unknown offset and you don’t have a
pre-shifted copy of it. For instance, the sequence 1, 2, 3, 4, 5 becomes 3, 4, 5, 1, 2, after shifting it twice to the
left.
Given shiftArr and an integer num, implement a function shiftedArrSearch that finds and returns the index of num in
shiftArr. If num isn’t in shiftArr, return -1. Assume that the offset can be any value between 0 and arr.length - 1.
Explain your solution and analyze its time and space complexities.
Example:
input: shiftArr = [9, 12, 17, 2, 4, 5], num = 2 # shiftArr is the
# outcome of shifting
# [2, 4, 5, 9, 12, 17]
# three times to the left
output: 3 # since it’s the index of 2 in arr
*/
public class ShiftedArray {
static int shiftedArrSearch(int[] shiftArr, int num) {
// your code goes here
return helper(0, shiftArr.length - 1, num, shiftArr);
}
private static int helper(int start, int end, int num, int[] shiftArr) {
if (end < start) {
return -1;
}
int pivot = (start + end) / 2;
if (shiftArr[pivot] == num) {
return pivot;
}
if (shiftArr[start] < shiftArr[pivot]) {
//first half is ordered
if (num >= shiftArr[start] && num <= shiftArr[end]) {
return helper(start, pivot - 1, num, shiftArr);
} else {
return helper(pivot + 1, end, num, shiftArr);
}
} else {
//second half ordered
if (num >= shiftArr[pivot] && num <= shiftArr[end]) {
return helper(pivot + 1, end, num, shiftArr);
} else {
return helper(start, pivot - 1, num, shiftArr);
}
}
}
public static void main(String[] args) {
int search = shiftedArrSearch(new int[]{4, 5, 6, 7, 0, 1, 2}, 3);
//System.out.println(search);
}
}
| 36.116667 | 118 | 0.550069 |
9d0eae7c85221e9239bb57d6baa3c1b8ff135f3f | 7,173 | /*
* Copyright 2019 OPS4J.
*
* 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.ops4j.pax.web.samples.tests;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ServiceLoader;
import java.util.Set;
import javax.servlet.ServletContainerInitializer;
import org.apache.xbean.osgi.bundle.util.BundleResourceHelper;
import org.ops4j.pax.web.utils.ClassPathUtil;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.wiring.BundleWiring;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SneakIntoPaxWebSpi {
public static final Logger LOG = LoggerFactory.getLogger(SneakIntoPaxWebSpi.class);
private SneakIntoPaxWebSpi() {
}
public static Bundle whatsYourBundle() {
return FrameworkUtil.getBundle(SneakIntoPaxWebSpi.class);
}
public static void useXBeanFinder() throws IOException {
Bundle bundle = FrameworkUtil.getBundle(SneakIntoPaxWebSpi.class);
Set<Bundle> wiredBundles = ClassPathUtil.getBundlesInClassSpace(bundle, new LinkedHashSet<>());
// should be:
// wiredBundles: java.util.Set = {java.util.LinkedHashSet@4061} size = 8
// 0 = {org.apache.felix.framework.BundleImpl@4064} "javax.servlet-api [17]"
// 1 = {org.apache.felix.framework.BundleImpl@4065} "org.ops4j.pax.web.pax-web-api [18]"
// 2 = {org.apache.felix.framework.BundleImpl@4066} "org.apache.xbean.bundleutils [21]"
// 3 = {org.apache.felix.framework.BundleImpl@4067} "org.ops4j.pax.logging.pax-logging-api [15]"
// 4 = {org.apache.felix.framework.BundleImpl@4068} "org.apache.xbean.finder [20]"
// 5 = {org.apache.felix.framework.BundleImpl@4069} "org.objectweb.asm [22]"
// 6 = {org.apache.felix.framework.BundleImpl@4070} "org.objectweb.asm.commons [23]"
// 7 = {org.apache.felix.framework.BundleImpl@4071} "org.objectweb.asm.tree [24]"
BundleResourceHelper finder1 = new BundleResourceHelper(bundle, false, true);
BundleResourceHelper finder2 = new BundleResourceHelper(bundle, false, false);
Enumeration<URL> resources1 = finder1.getResources("/*");
Enumeration<URL> resources2 = finder2.getResources("/*");
}
/**
* Check whether we can correctly search for {@link ServletContainerInitializer initializers} using {@link ServiceLoader}
* when the bundle has attached fragments
* @param b
* @return
*/
public static List<Class<? extends ServletContainerInitializer>> findInitializersUsingServiceLoader(Bundle b) {
List<Class<? extends ServletContainerInitializer>> initializers = new LinkedList<>();
ServiceLoader<ServletContainerInitializer> loader = ServiceLoader.load(ServletContainerInitializer.class, b.adapt(BundleWiring.class).getClassLoader());
for (ServletContainerInitializer initializer : loader) {
LOG.info("ServiceLoader service: {}", initializer);
initializers.add(initializer.getClass());
}
return initializers;
}
/**
* Check whether we can correctly search for {@link ServletContainerInitializer initializers} using
* {@link BundleWiring#findEntries}
* @param b
* @return
*/
public static List<Class<? extends ServletContainerInitializer>> findInitializersUsingBundleWiring(Bundle b) throws Exception {
List<Class<? extends ServletContainerInitializer>> initializers = new LinkedList<>();
BundleWiring wiring = b.adapt(BundleWiring.class);
List<URL> urls = wiring.findEntries("/META-INF/services", "javax.servlet.ServletContainerInitializer", 0);
for (URL url : urls) {
LOG.info("Wiring entry: {}", url);
String className = readService(url);
initializers.add(wiring.getClassLoader().loadClass(className).asSubclass(ServletContainerInitializer.class));
}
return initializers;
}
/**
* Check whether we can correctly search for {@link ServletContainerInitializer initializers} using
* {@link Bundle#findEntries}
* @param b
* @return
*/
public static List<Class<? extends ServletContainerInitializer>> findInitializersUsingBundle(Bundle b) throws Exception {
List<Class<? extends ServletContainerInitializer>> initializers = new LinkedList<>();
Enumeration<URL> urls = b.findEntries("/META-INF/services", "javax.servlet.ServletContainerInitializer", false);
if (urls != null) {
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
LOG.info("Bundle entry: {}", url);
String className = readService(url);
initializers.add(b.loadClass(className).asSubclass(ServletContainerInitializer.class));
}
}
return initializers;
}
/**
* Having only bundle, try to find:<ul>
* <li>{@code /WEB-INF/faces-config.xml}</li>
* <li>{@code /WEB-INF/lib/primefaces-VERSION.jar!/META-INF/faces-config.xml}</li>
* <li>{@code /WEB-INF/lib/primefaces-VERSION.jar!/META-INF/primefaces-p.taglib.xml}</li>
* </ul>
* @param b
*/
public static void findFacesConfigs(Bundle b) {
List<URL> result = new LinkedList<>();
Enumeration<URL> urls = b.findEntries("/WEB-INF/", "*faces-config.xml", false);
if (urls != null) {
while (urls.hasMoreElements()) {
result.add(urls.nextElement());
}
}
urls = b.findEntries("/META-INF/", "*faces-config.xml", false);
if (urls != null) {
while (urls.hasMoreElements()) {
result.add(urls.nextElement());
}
}
urls = b.findEntries("/META-INF/", "*.taglib.xml", false);
if (urls != null) {
while (urls.hasMoreElements()) {
result.add(urls.nextElement());
}
}
for (URL url : result) {
LOG.info("Bundle entry: {}", url);
}
Set<Bundle> bundles = new HashSet<>();
bundles = ClassPathUtil.getBundlesInClassSpace(b, bundles);
for (Bundle bundle : bundles) {
LOG.info("Bundle in class space: {}", bundle);
}
URL[] jars = ClassPathUtil.getClassPathJars(b, false);
for (URL jar : jars) {
LOG.info("Jar in class path: {}", jar);
}
List<URL> manifests = b.adapt(BundleWiring.class).findEntries("/META-INF/", "MANIFEST.MF", BundleWiring.FINDENTRIES_RECURSE);
for (URL m : manifests) {
LOG.info("Wiring entry: {}", m);
}
}
private static String readService(URL url) throws IOException {
String className = null;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) {
String line = null;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.isEmpty() && !line.startsWith("#")) {
className = line;
break;
}
}
}
return className;
}
}
| 37.359375 | 154 | 0.720758 |
f3b936e4390424d34e4883bdc65e1fafef87b380 | 813 | package laicode.dfsII;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AllSubsetsII {
public List<String> subSets(String set) {
List<String> res = new ArrayList<>();
if (set == null) return res;
char[] array = set.toCharArray();
Arrays.sort(array);
StringBuilder sb = new StringBuilder();
helper(array, sb, res, 0);
return res;
}
private void helper(char[] array, StringBuilder sb, List<String> res, int index) {
if (index == array.length) {
res.add(sb.toString());
return;
}
helper(array, sb.append(array[index]), res, index + 1);
sb.deleteCharAt(sb.length() - 1);
while (index < array.length - 1 && array[index] == array[index + 1]) {
index++;
}
helper(array, sb, res, index + 1);
}
}
| 26.225806 | 84 | 0.622386 |
55f50fc57e7ebaf7e72ce7cd40a9ee8ac085b03a | 185 | package syncer.replica.rdb.datatype;
import java.io.Serializable;
/**
* @author zhanenqiang
* @Description 描述
* @Date 2020/8/7
*/
public interface Module extends Serializable {
}
| 15.416667 | 46 | 0.72973 |
a16a0b4520565c23b0e8c90432089a32d09ebca1 | 2,513 | package com.knowledge_network.user.dao.impl;
import com.knowledge_network.knowledge_network.entity.Course;
import com.knowledge_network.support.base.BaseHibernateDAO;
import com.knowledge_network.user.dao.StudentDAO;
import com.knowledge_network.user.entity.Clazz;
import com.knowledge_network.user.entity.Student;
import org.hibernate.criterion.Order;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
/**
* Created by limingcheng on 17-12-7
* <p>
* 提供访问用户表student的DAO
*/
@Repository
public class StudentDAOImpl extends BaseHibernateDAO<Student> implements StudentDAO {
/**
* 通过id查找学生
*
* @param userId
* @return
*/
@Override
public Student findStudentById(int userId) {
return findById(userId);
}
/**
* 通过学号查找学生
*
* @param studentIdNum
* @return
*/
@Override
public Student findStudentByIdNum(String studentIdNum) {
return (Student) findByUnique("studentIdNum", studentIdNum);
}
/**
* 查找某班学生
*
* @param clazz
* @return
*/
@Override
public List<Student> findStudentByClass(Clazz clazz) {
return findBy("clazz", clazz);
}
/**
* 通过姓名查找学生
*
* @param username
* @return
*/
@Override
public Student findStudentByUsername(String username) {
return findByUnique("username", username);
}
/**
* 查找某课程学生
*
* @param course
* @return
*/
@Override
public List<Student> findStudentByCourse(Course course) {
return null;
}
@Override
public void createStudent(Student student) {
save(student);
}
@Override
public List<Student> findStudentByConditionsOrderPage(int start, int rows, Order order, List<Condition> conditions) {
return findByOrderConditionsPage(start, rows, order, conditions);
}
@Override
public List<Student> findStudentByOrderPage(int start, int rows, Order order) {
return findStudentByConditionsOrderPage(start, rows, order, null);
}
@Override
public long getStudentCountByConditions(List<Condition> conditions) {
return findCountByConditions(conditions);
}
@Override
public void updateStudent(Student student) {
save(student);
}
/**
* 更新学生表信息
*
* @param map
* @return
*/
@Override
public boolean saveStudent(Map<String, Object> map) {
return false;
}
}
| 22.238938 | 121 | 0.649821 |
a95a75fc54898365f7152a450ac7955f9efedc67 | 6,080 | /*
* Copyright 2000-2001,2004 The Apache Software Foundation.
*
* 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.apache.jetspeed.services.security.nosecurity;
// Java imports
import javax.servlet.ServletConfig;
// Jetspeed import
import org.apache.jetspeed.om.profile.Entry;
import org.apache.jetspeed.om.security.JetspeedUser;
import org.apache.jetspeed.portal.Portlet;
import org.apache.jetspeed.services.security.PortalAccessController;
import org.apache.jetspeed.services.security.PortalResource;
// Turbine imports
import org.apache.turbine.services.TurbineBaseService;
import org.apache.turbine.services.InitializationException;
/**
* NoSecurityAccessController
*
* Use this service if you want to disable all authorization checks
*
* @author <a href="taylor@apache.org">David Sean Taylor</a>
* @version $Id: NoSecurityAccessController.java,v 1.5 2004/02/23 03:53:24 jford Exp $
*/
public class NoSecurityAccessController extends TurbineBaseService
implements PortalAccessController
{
/**
* Given a <code>JetspeedUser</code>, authorize that user to perform the secured action on
* the given <code>Portlet</code> resource. If the user does not have
* sufficient privilege to perform the action on the resource, the check returns false,
* otherwise when sufficient privilege is present, checkPermission returns true.
*
* @param user the user to be checked.
* @param portlet the portlet resource.
* @param action the secured action to be performed on the resource by the user.
* @return boolean true if the user has sufficient privilege.
*/
final public boolean checkPermission(JetspeedUser user, Portlet portlet, String action)
{
return checkPermission(user, portlet, action, null);
}
/**
* Given a <code>JetspeedUser</code>, authorize that user to perform the secured action on
* the given <code>Portlet</code> resource. If the user does not have
* sufficient privilege to perform the action on the resource, the check returns false,
* otherwise when sufficient privilege is present, checkPermission returns true.
*
* @param user the user to be checked.
* @param portlet the portlet resource.
* @param action the secured action to be performed on the resource by the user.
* @param owner of the entry, i.e. the username
* @return boolean true if the user has sufficient privilege.
*/
final public boolean checkPermission(JetspeedUser user, Portlet portlet, String action, String owner)
{
return true;
}
/**
* Given a <code>JetspeedUser</code>, authorize that user to perform the secured action on
* the given Portlet Instance (<code>Entry</code>) resource. If the user does not have
* sufficient privilege to perform the action on the resource, the check returns false,
* otherwise when sufficient privilege is present, checkPermission returns true.
*
* @param user the user to be checked.
* @param entry the portlet instance resource.
* @param action the secured action to be performed on the resource by the user.
* @return boolean true if the user has sufficient privilege.
*/
final public boolean checkPermission(JetspeedUser user, Entry entry, String action)
{
return checkPermission(user, entry, action, null);
}
/**
* Given a <code>JetspeedUser</code>, authorize that user to perform the secured action on
* the given Portlet Instance (<code>Entry</code>) resource. If the user does not have
* sufficient privilege to perform the action on the resource, the check returns false,
* otherwise when sufficient privilege is present, checkPermission returns true.
*
* @param user the user to be checked.
* @param entry the portlet instance resource.
* @param action the secured action to be performed on the resource by the user.
* @param owner of the entry, i.e. the username
* @return boolean true if the user has sufficient privilege.
*/
final public boolean checkPermission(JetspeedUser user, Entry entry, String action, String owner)
{
return true;
}
/**
* Given a <code>JetspeedUser</code>, authorize that user to perform the secured action on
* the given resource. If the user does not have
* sufficient privilege to perform the action on the resource, the check returns false,
* otherwise when sufficient privilege is present, checkPermission returns true.
*
* @param user the user to be checked.
* @param resource requesting an action
* @param action the secured action to be performed on the resource by the user.
* @return boolean true if the user has sufficient privilege.
*/
final public boolean checkPermission(JetspeedUser user, PortalResource resource, String action)
{
return true;
}
/*
* Turbine Services Interface
*/
/**
* This is the early initialization method called by the
* Turbine <code>Service</code> framework
* @param conf The <code>ServletConfig</code>
* @exception throws a <code>InitializationException</code> if the service
* fails to initialize
*/
public synchronized void init(ServletConfig conf)
throws InitializationException
{
if (getInit())
{
return;
}
super.init(conf);
setInit(true);
}
}
| 38.726115 | 105 | 0.697533 |
d884b869348f2d3cbfd41766e4249fea4b066258 | 2,702 | /*-
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. 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.
* ============LICENSE_END=========================================================
*/
package org.onap.policy.common.endpoints.http.server;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AuthorizationFilter implements Filter {
private static Logger logger = LoggerFactory.getLogger(AuthorizationFilter.class);
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
if (!(servletRequest instanceof HttpServletRequest)) {
throw new ServletException("Not an HttpServletRequest instance");
}
if (!(servletResponse instanceof HttpServletResponse)) {
throw new ServletException("Not an HttpServletResponse instance");
}
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String role = getRole(request);
boolean authorized = request.isUserInRole(role);
logger.info("user {} in role {} is {}authorized to {}",
request.getUserPrincipal(), role, ((authorized) ? "" : "NOT "), request.getMethod());
if (!authorized) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
protected abstract String getRole(HttpServletRequest request);
}
| 39.735294 | 113 | 0.647668 |
90703f6021319b2bca29e010232c76fb75803480 | 18,451 | package org.jivesoftware.openfire.admin;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.ParamUtils;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
public final class server_002dlocale_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static java.util.List _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_fmt_message_key_nobody;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_jspx_tagPool_fmt_message_key_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
}
public void _jspDestroy() {
_jspx_tagPool_fmt_message_key_nobody.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
JspFactory _jspxFactory = null;
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\n\n\n\n\n\n\n\n\n\n\n");
org.jivesoftware.util.WebManager webManager = null;
synchronized (_jspx_page_context) {
webManager = (org.jivesoftware.util.WebManager) _jspx_page_context.getAttribute("webManager", PageContext.PAGE_SCOPE);
if (webManager == null){
webManager = new org.jivesoftware.util.WebManager();
_jspx_page_context.setAttribute("webManager", webManager, PageContext.PAGE_SCOPE);
}
}
out.write('\n');
webManager.init(request, response, session, application, out );
out.write('\n');
out.write('\n');
// Get parameters //
String localeCode = ParamUtils.getParameter(request,"localeCode");
String timeZoneID = ParamUtils.getParameter(request,"timeZoneID");
boolean save = request.getParameter("save") != null;
// TODO: We're not displaying this error ever.
Map<String,String> errors = new HashMap<String,String>();
if (save) {
// Set the timezeone
try {
TimeZone tz = TimeZone.getTimeZone(timeZoneID);
JiveGlobals.setTimeZone(tz);
// Log the event
webManager.logEvent("updated time zone to "+tz.getID(), tz.toString());
}
catch (Exception e) {
Log.error(e);
}
if (localeCode != null) {
Locale newLocale = LocaleUtils.localeCodeToLocale(localeCode.trim());
if (newLocale == null) {
errors.put("localeCode","");
}
else {
JiveGlobals.setLocale(newLocale);
// Log the event
webManager.logEvent("updated locale to "+newLocale.getDisplayName(), null);
response.sendRedirect("server-locale.jsp?success=true");
return;
}
}
}
Locale locale = JiveGlobals.getLocale();
// Get the time zone list.
String[][] timeZones = LocaleUtils.getTimeZoneList();
// Get the current time zone.
TimeZone timeZone = JiveGlobals.getTimeZone();
out.write("\n\n<html>\n <head>\n <title>");
if (_jspx_meth_fmt_message_0(_jspx_page_context))
return;
out.write("</title>\n <meta name=\"pageID\" content=\"server-locale\"/>\n <meta name=\"helpPage\" content=\"edit_server_properties.html\"/>\n </head>\n <body>\n\n<p>\n");
if (_jspx_meth_fmt_message_1(_jspx_page_context))
return;
out.write("\n</p>\n\n\n<!-- BEGIN locale settings -->\n<form action=\"server-locale.jsp\" method=\"post\" name=\"sform\">\n\t<div class=\"jive-contentBoxHeader\">\n\t\t");
if (_jspx_meth_fmt_message_2(_jspx_page_context))
return;
out.write("\n\t</div>\n\t<div class=\"jive-contentBox\">\n\t\t<p>\n <b>");
if (_jspx_meth_fmt_message_3(_jspx_page_context))
return;
out.write(":</b> ");
out.print( locale.getDisplayName(locale) );
out.write(" /\n ");
out.print( LocaleUtils.getTimeZoneName(JiveGlobals.getTimeZone().getID(), locale) );
out.write("\n </p>\n\n ");
boolean usingPreset = false;
Locale[] locales = Locale.getAvailableLocales();
for (Locale locale1 : locales) {
usingPreset = locale1.equals(locale);
if (usingPreset) {
break;
}
}
out.write("\n\n <p><b>");
if (_jspx_meth_fmt_message_4(_jspx_page_context))
return;
out.write(":</b></p>\n\n <table cellspacing=\"0\" cellpadding=\"3\" border=\"0\">\n <tbody>\n <tr>\n <td>\n <input type=\"radio\" name=\"localeCode\" value=\"cs_CZ\" ");
out.print( ("cs_CZ".equals(locale.toString()) ? "checked" : "") );
out.write("\n id=\"loc01\" />\n </td>\n <td colspan=\"2\">\n <label for=\"loc01\">Czech (cs_CZ)</label>\n </td>\n </tr>\n <tr>\n <td>\n <input type=\"radio\" name=\"localeCode\" value=\"de\" ");
out.print( ("de".equals(locale.toString()) ? "checked" : "") );
out.write("\n id=\"loc02\" />\n </td>\n <td colspan=\"2\">\n <label for=\"loc02\">Deutsch (de)</label>\n </td>\n </tr>\n <tr>\n <td>\n <input type=\"radio\" name=\"localeCode\" value=\"en\" ");
out.print( ("en".equals(locale.toString()) ? "checked" : "") );
out.write("\n id=\"loc03\" />\n </td>\n <td colspan=\"2\">\n <label for=\"loc03\">English (en)</label>\n </td>\n </tr>\n <tr>\n <td>\n <input type=\"radio\" name=\"localeCode\" value=\"es\" ");
out.print( ("es".equals(locale.toString()) ? "checked" : "") );
out.write("\n id=\"loc04\" />\n </td>\n <td colspan=\"2\">\n <label for=\"loc04\">Español (es)</label>\n </td>\n </tr>\n <tr>\n <td>\n <input type=\"radio\" name=\"localeCode\" value=\"fr\" ");
out.print( ("fr".equals(locale.toString()) ? "checked" : "") );
out.write("\n id=\"loc05\" />\n </td>\n <td colspan=\"2\">\n <label for=\"loc05\">Français (fr)</label>\n </td>\n </tr>\n <tr>\n <td>\n <input type=\"radio\" name=\"localeCode\" value=\"nl\" ");
out.print( ("nl".equals(locale.toString()) ? "checked" : "") );
out.write("\n id=\"loc06\" />\n </td>\n <td colspan=\"2\">\n <label for=\"loc06\">Nederlands (nl)</label>\n </td>\n </tr>\n <tr>\n <td>\n <input type=\"radio\" name=\"localeCode\" value=\"pl_PL\" ");
out.print( ("pl_PL".equals(locale.toString()) ? "checked" : "") );
out.write("\n id=\"loc07\" />\n </td>\n <td colspan=\"2\">\n <label for=\"loc07\">Polski (pl_PL)</label>\n </td>\n </tr>\n <tr>\n <td>\n <input type=\"radio\" name=\"localeCode\" value=\"pt_BR\" ");
out.print( ("pt_BR".equals(locale.toString()) ? "checked" : "") );
out.write("\n id=\"loc08\" />\n </td>\n <td colspan=\"2\">\n <label for=\"loc08\">Português Brasileiro (pt_BR)</label>\n </td>\n </tr>\n <tr>\n <td>\n <input type=\"radio\" name=\"localeCode\" value=\"ru_RU\" ");
out.print( ("ru_RU".equals(locale.toString()) ? "checked" : "") );
out.write("\n id=\"loc09\" />\n </td>\n <td colspan=\"2\">\n <label for=\"loc09\">Русский (ru_RU)</label>\n </td>\n </tr>\n <tr>\n <td>\n <input type=\"radio\" name=\"localeCode\" value=\"sk\" ");
out.print( ("sk".equals(locale.toString()) ? "checked" : "") );
out.write("\n id=\"loc10\" />\n </td>\n <td colspan=\"2\">\n <label for=\"loc10\">Slovenčina (sk)</label>\n </td>\n </tr>\n <tr>\n <td>\n <input type=\"radio\" name=\"localeCode\" value=\"zh_CN\" ");
out.print( ("zh_CN".equals(locale.toString()) ? "checked" : "") );
out.write("\n id=\"loc11\" />\n </td>\n <td>\n <a href=\"#\" onclick=\"document.sform.localeCode[1].checked=true; return false;\"><img src=\"images/language_zh_CN.gif\" border=\"0\" alt=\"\" /></a>\n </td>\n <td>\n <label for=\"loc11\">Simplified Chinese (zh_CN)</label>\n </td>\n </tr>\n </tbody>\n </table>\n\n <br>\n\n <p><b>");
if (_jspx_meth_fmt_message_5(_jspx_page_context))
return;
out.write(":</b></p>\n\n <select size=\"1\" name=\"timeZoneID\">\n ");
for (String[] timeZone1 : timeZones) {
String selected = "";
if (timeZone.getID().equals(timeZone1[0].trim())) {
selected = " selected";
}
out.write("\n <option value=\"");
out.print( timeZone1[0] );
out.write('"');
out.print( selected );
out.write('>');
out.print( timeZone1[1] );
out.write("\n ");
}
out.write("\n </select>\n\t</div>\n<input type=\"submit\" name=\"save\" value=\"");
if (_jspx_meth_fmt_message_6(_jspx_page_context))
return;
out.write("\">\n</form>\n<!-- END locale settings -->\n\n\n</body>\n</html>");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_fmt_message_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// fmt:message
org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_0 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
_jspx_th_fmt_message_0.setPageContext(_jspx_page_context);
_jspx_th_fmt_message_0.setParent(null);
_jspx_th_fmt_message_0.setKey("locale.title");
int _jspx_eval_fmt_message_0 = _jspx_th_fmt_message_0.doStartTag();
if (_jspx_th_fmt_message_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_0);
return true;
}
_jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_0);
return false;
}
private boolean _jspx_meth_fmt_message_1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// fmt:message
org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_1 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
_jspx_th_fmt_message_1.setPageContext(_jspx_page_context);
_jspx_th_fmt_message_1.setParent(null);
_jspx_th_fmt_message_1.setKey("locale.title.info");
int _jspx_eval_fmt_message_1 = _jspx_th_fmt_message_1.doStartTag();
if (_jspx_th_fmt_message_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_1);
return true;
}
_jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_1);
return false;
}
private boolean _jspx_meth_fmt_message_2(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// fmt:message
org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_2 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
_jspx_th_fmt_message_2.setPageContext(_jspx_page_context);
_jspx_th_fmt_message_2.setParent(null);
_jspx_th_fmt_message_2.setKey("locale.system.set");
int _jspx_eval_fmt_message_2 = _jspx_th_fmt_message_2.doStartTag();
if (_jspx_th_fmt_message_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_2);
return true;
}
_jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_2);
return false;
}
private boolean _jspx_meth_fmt_message_3(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// fmt:message
org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_3 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
_jspx_th_fmt_message_3.setPageContext(_jspx_page_context);
_jspx_th_fmt_message_3.setParent(null);
_jspx_th_fmt_message_3.setKey("locale.current");
int _jspx_eval_fmt_message_3 = _jspx_th_fmt_message_3.doStartTag();
if (_jspx_th_fmt_message_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_3);
return true;
}
_jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_3);
return false;
}
private boolean _jspx_meth_fmt_message_4(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// fmt:message
org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_4 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
_jspx_th_fmt_message_4.setPageContext(_jspx_page_context);
_jspx_th_fmt_message_4.setParent(null);
_jspx_th_fmt_message_4.setKey("language.choose");
int _jspx_eval_fmt_message_4 = _jspx_th_fmt_message_4.doStartTag();
if (_jspx_th_fmt_message_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_4);
return true;
}
_jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_4);
return false;
}
private boolean _jspx_meth_fmt_message_5(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// fmt:message
org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_5 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
_jspx_th_fmt_message_5.setPageContext(_jspx_page_context);
_jspx_th_fmt_message_5.setParent(null);
_jspx_th_fmt_message_5.setKey("timezone.choose");
int _jspx_eval_fmt_message_5 = _jspx_th_fmt_message_5.doStartTag();
if (_jspx_th_fmt_message_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_5);
return true;
}
_jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_5);
return false;
}
private boolean _jspx_meth_fmt_message_6(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// fmt:message
org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_6 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
_jspx_th_fmt_message_6.setPageContext(_jspx_page_context);
_jspx_th_fmt_message_6.setParent(null);
_jspx_th_fmt_message_6.setKey("global.save_settings");
int _jspx_eval_fmt_message_6 = _jspx_th_fmt_message_6.doStartTag();
if (_jspx_th_fmt_message_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_6);
return true;
}
_jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_6);
return false;
}
}
| 56.772308 | 509 | 0.612325 |
1416778c4b865cac657803d9511d49ef49a6e3e7 | 906 | /* Generated SBE (Simple Binary Encoding) message codec */
package mktdata;
public enum SecurityUpdateAction
{
/**
* Add
*/
Add((byte)65),
/**
* Delete
*/
Delete((byte)68),
/**
* Modify
*/
Modify((byte)77),
/**
* To be used to represent not present or null.
*/
NULL_VAL((byte)0);
private final byte value;
SecurityUpdateAction(final byte value)
{
this.value = value;
}
public byte value()
{
return value;
}
public static SecurityUpdateAction get(final byte value)
{
switch (value)
{
case 65: return Add;
case 68: return Delete;
case 77: return Modify;
}
if ((byte)0 == value)
{
return NULL_VAL;
}
throw new IllegalArgumentException("Unknown value: " + value);
}
}
| 16.472727 | 70 | 0.513245 |
29bd230c517fe6fbc0474b1f7c9d1e0ad3224ced | 809 | package org.dddjava.jig.infrastructure.logger;
import org.dddjava.jig.domain.model.jigmodel.analyzed.Warning;
import org.dddjava.jig.infrastructure.resourcebundle.Utf8ResourceBundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ResourceBundle;
public class MessageLogger {
private final Class<?> clz;
private final Logger logger;
public MessageLogger(Class<?> clz) {
this.clz = clz;
this.logger = LoggerFactory.getLogger(clz);
}
public static MessageLogger of(Class<?> clz) {
return new MessageLogger(clz);
}
public void warn(Warning warning) {
ResourceBundle resource = Utf8ResourceBundle.messageBundle();
String message = resource.getString(warning.resourceKey());
logger.warn(message);
}
}
| 26.966667 | 72 | 0.715698 |
8b1d477c7f3ccb3dc2677bbed48f7ce5cc556ded | 671 | package org.reboot.server.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import org.reboot.server.route.*;
import org.reboot.server.client.*;
import org.reboot.server.util.*;
class Main {
public static void main(String []args) {
Logger log = LoggerFactory.getLogger(Main.class);
log.info("Booting up....");
List<Route> routes = new ArrayList<Route>();
routes.add(new Route("/v1/<term_id>/v2?a=b&c=d&m=z", Method.GET, TestController.class));
log.info(Serializer.getString(routes));
Server server = new Server(9899, 5, 2000, 2000, routes);
server.startServer();
}
}
| 25.807692 | 96 | 0.660209 |
76a8578d486c3ab0f51f66f561b5cdf606fb4490 | 1,703 | package jim.android.mainFrame;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import jim.android.Splash.R;
/**
* Created by huangjim on 8/14/2015.
*/
public class FragmentMore extends Fragment implements View.OnClickListener {
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_fragment_more, container, false);
return view;
}
@Override
public void onActivityCreated( Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
CustomViewForMore customViewForMore1 = (CustomViewForMore) view.findViewById(R.id.myitem01);
customViewForMore1.setOnClickListener(this);
}
private void showToast(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.myitem01:
showToast("myitem01");
break;
case R.id.myitem02:
showToast("myitem02");
break;
case R.id.myitem03:
showToast("myitem03");
break;
case R.id.myitem04:
showToast("myitem0");
break;
case R.id.myitem05:
showToast("myitem05");
break;
case R.id.myitem06:
showToast("myitem06");
break;
}
}
}
| 25.80303 | 103 | 0.608925 |
539a0399a9b4b61a02cbc4d1a8508a1256cdbeef | 1,701 | package net.ssehub.kernel_haven.test_utils;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import net.ssehub.kernel_haven.analysis.PipelineAnalysis;
import net.ssehub.kernel_haven.util.io.ITableCollection;
import net.ssehub.kernel_haven.util.io.ITableReader;
import net.ssehub.kernel_haven.util.io.ITableWriter;
import net.ssehub.kernel_haven.util.null_checks.NonNull;
/**
* An {@link ITableCollection} that creates {@link MemoryTableWriter}s. Useful to access the result of a test execution
* in a programmatic way (via {@link MemoryTableWriter#getTable(String)}.
*
* @author Adam
*/
public class MemoryTableCollection implements ITableCollection {
/**
* For manual use.
*/
public MemoryTableCollection() {
// Nothing to do
}
/**
* Required by {@link PipelineAnalysis} (create Result).
* @param ignored Will be ignored.
*/
public MemoryTableCollection(File ignored) {
// Nothing to do
}
@Override
public void close() {
// nothing to do
}
@Override
public @NonNull ITableReader getReader(@NonNull String name) throws IOException {
throw new IOException("The MemoryTableCollection can not read");
}
@Override
public @NonNull Set<@NonNull String> getTableNames() throws IOException {
return MemoryTableWriter.getTableNames();
}
@Override
public @NonNull ITableWriter getWriter(@NonNull String name) throws IOException {
return new MemoryTableWriter(name);
}
@Override
public @NonNull Set<@NonNull File> getFiles() throws IOException {
return new HashSet<>();
}
}
| 27 | 119 | 0.697237 |
e3420011d262db2246eaae241b5a3c06d7dc7c44 | 4,715 | /*
* BSD 2-Clause License
*
* Copyright (c) 2021, Vladimír Ulman
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package cz.it4i.ulman.transfers.graphexport;
public interface GraphExportable
{
int get_xColumnWidth();
int get_yLineStep();
int get_defaultBendingPointAbsoluteOffsetY();
int get_defaultNodeWidth();
int get_defaultNodeHeight();
int get_defaultNodeColour();
void set_xColumnWidth(int val);
void set_yLineStep(int val);
void set_defaultBendingPointAbsoluteOffsetY(int val);
void set_defaultNodeWidth(int val);
void set_defaultNodeHeight(int val);
void set_defaultNodeColour(int val);
/** adds node whose color should have a meaning
when read in hexadecimal 0xRRGGBB format; default
width and height of the node graphics shall be used */
void addNode(final String id,
final String label, final int colorRGB,
final int x, final int y);
/** adds node whose color should have a meaning
when read in hexadecimal 0xRRGGBB format */
void addNode(final String id,
final String label, final int colorRGB,
final int x, final int y,
final int width, final int height);
void addStraightLine(final String fromId, final String toId);
/** adds a new node and connects the given parent with this node;
default size of the node is expected */
void addStraightLineConnectedVertex(final String parentNodeID,
final String newNodeID,
final String label, final int colorRGB,
final int x, final int y);
/** adds bended line where the bending shall happen at
[toX + defaultNodeWidth/2 , toY + defaultBendingPointAbsoluteOffsetY ] */
void addBendedLine(final String fromId, final String toId,
final int toX, final int toY);
/** adds bended line where the bending shall happen at
[toX + defaultNodeWidth/2 , toY + bendingOffsetY ] */
void addBendedLine(final String fromId, final String toId,
final int toX, final int toY, final int bendingOffsetY);
/** adds a new node and connects the given parent with this node;
default size of the node is expected as well as default bending point */
void addBendedLineConnectedVertex(final String parentNodeID,
final String newNodeID,
final String label, final int colorRGB,
final int x, final int y);
/** optional, whether to leave empty or implement depends on the underlying export mechanism */
void close();
/*
static void runExample()
{
System.out.println("graph export example started");
//the main root of the tree
addNode("A", "A",defaultNodeColour, 200,0);
//left subtree: straight lines
addStraightLineConnectedVertex("A" , "AL" , "AL" ,defaultNodeColour, 100,200,0);
addStraightLineConnectedVertex("AL", "ALL", "ALL",defaultNodeColour, 50,400,0);
addStraightLineConnectedVertex("AL", "ALR", "ALR",defaultNodeColour, 150,400,0);
//right subtree: bended lines
addBendedLineConnectedVertex( "A" , "AR" , "AR" ,defaultNodeColour, 300,200,0);
addBendedLineConnectedVertex( "AR", "ARL", "ARL",defaultNodeColour, 250,400,0);
addBendedLineConnectedVertex( "AR", "ARR", "ARR",defaultNodeColour, 350,400,0);
System.out.println("graph export example stopped");
}
*/
}
| 41.725664 | 96 | 0.703075 |
5542902183306bbdf0977222cfc62f6c8cb54dbe | 2,396 | package org.ihtsdo.buildcloud.rest.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.ihtsdo.buildcloud.rest.controller.helper.HypermediaGenerator;
import org.ihtsdo.buildcloud.rest.security.IsAuthenticatedAsGlobalAdmin;
import org.ihtsdo.buildcloud.core.service.PermissionService;
import org.ihtsdo.buildcloud.core.service.PermissionServiceCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/permissions")
@Api(value = "Permissions")
public class PermissionController {
@Autowired
private HypermediaGenerator hypermediaGenerator;
@Autowired
private PermissionService permissionService;
@Autowired
private PermissionServiceCache permissionServiceCache;
@GetMapping(value = "/roles")
@ApiOperation(value = "Returns a list all roles for a logged in user",
notes = "Returns a list of all roles visible to the currently logged in user.")
@ResponseBody
public ResponseEntity getCurrentRoles(HttpServletRequest request) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication() ;
if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
throw new AccessDeniedException("Access is denied");
}
return new ResponseEntity(permissionService.getRolesForLoggedInUser(), HttpStatus.OK);
}
@PostMapping(value = "/clearCache")
@IsAuthenticatedAsGlobalAdmin
public ResponseEntity clearCache(HttpServletRequest request) {
permissionServiceCache.clearCache();
return new ResponseEntity(HttpStatus.OK);
}
}
| 41.310345 | 96 | 0.801336 |
bfeb5ee23ec50f2ac2738402f51252bb3b43cbe8 | 1,321 | package fi.aalto.cs.apluscourses.model;
import fi.aalto.cs.apluscourses.utils.Event;
import org.jetbrains.annotations.NotNull;
public class Progress {
private int value = 0;
private int maxValue;
private String label;
private final boolean indeterminate;
public final Event updated = new Event();
/**
* Constructor for Progress.
*/
public Progress(int maxValue, @NotNull String label, boolean indeterminate) {
this.maxValue = maxValue;
this.label = label;
this.indeterminate = indeterminate;
}
public int getValue() {
return this.value;
}
public int getMaxValue() {
return this.maxValue;
}
public String getLabel() {
return this.label;
}
public boolean getIndeterminate() {
return this.indeterminate;
}
public boolean isFinished() {
return this.value >= this.maxValue;
}
public void increment() {
this.value++;
updated.trigger();
}
public void incrementMaxValue(int amount) {
this.maxValue = this.maxValue + amount;
updated.trigger();
}
public void finish() {
this.value = this.maxValue;
updated.trigger();
}
public void setLabel(@NotNull String label) {
this.label = label;
updated.trigger();
}
public void setValue(int value) {
this.value = value;
updated.trigger();
}
}
| 19.426471 | 79 | 0.671461 |
64ba8093d7442687f7544f457eb154a1f536411f | 1,243 | package algorithm.quickselect.quickselect;
import java.util.Random;
import algorithm.quickselect.quicksort.QuickSort;
/**
* QuickSelect
*
* Ensure the selection of n-th member at cost of O(n)
*
* @author Administrator
*
* @param <Key>
*/
public class QuickSelect<Key extends Comparable> extends QuickSort {
public QuickSelect(int length, Key[] data) {
super(length, data);
}
public Key select(int rank) {
return quickSelect(0, this.length - 1, rank);
}
private Key quickSelect(int start, int end, int rank) {
// call partition with random pivot
// randomize is critical to get over the worst condition
Random rand = new Random();
int nextInt = rand.nextInt(end - start + 1) + start;
Key swapValue = (Key) data[nextInt];
data[nextInt] = data[end];
data[end] = swapValue;
int pivotPosition = partition(start, end);
int sizeOfLess = pivotPosition - start;
// selection only follow one recursive call
if (sizeOfLess == rank - 1)
return (Key) data[pivotPosition];
else if (sizeOfLess > rank - 1)
return quickSelect(start, pivotPosition - 1, rank);
else
return quickSelect(pivotPosition + 1, end, rank - sizeOfLess - 1);
}
}
| 23.018519 | 70 | 0.663717 |
0f994e66fd7a6b4c80df28b58e434fe24e7940f4 | 3,571 | /*
* Copyright 2017 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.core.validation;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.b2international.commons.exceptions.NotFoundException;
import com.b2international.index.Index;
import com.b2international.index.Indexes;
import com.b2international.index.mapping.Mappings;
import com.b2international.snowowl.core.IDisposableService;
import com.b2international.snowowl.core.ServiceProvider;
import com.b2international.snowowl.core.internal.validation.ValidationRepository;
import com.b2international.snowowl.core.repository.JsonSupport;
import com.b2international.snowowl.core.validation.rule.ValidationRule;
import com.b2international.snowowl.core.validation.rule.ValidationRule.Severity;
import com.b2international.snowowl.core.validation.rule.ValidationRules;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @since 6.0
*/
public class ValidationRuleApiTest {
private ServiceProvider context;
@Before
public void setup() {
final ObjectMapper mapper = JsonSupport.getDefaultObjectMapper();
final Index index = Indexes.createIndex(UUID.randomUUID().toString(), mapper, new Mappings(ValidationRule.class));
index.admin().create();
final ValidationRepository repository = new ValidationRepository(index);
context = ServiceProvider.EMPTY.inject()
.bind(ValidationRepository.class, repository)
.build();
}
@After
public void after() {
context.service(ValidationRepository.class).admin().delete();
if (context instanceof IDisposableService) {
((IDisposableService) context).dispose();
}
}
@Test
public void getAllValidationRules() throws Exception {
final ValidationRules rules = ValidationRequests.rules().prepareSearch()
.all()
.buildAsync().getRequest()
.execute(context);
assertThat(rules).isEmpty();
}
@Test(expected = NotFoundException.class)
public void throwNotFoundIfRuleDoesNotExist() throws Exception {
ValidationRequests.rules().prepareGet("invalid")
.buildAsync().getRequest()
.execute(context);
}
@Test
public void createRule() throws Exception {
final String ruleId = ValidationRequests.rules().prepareCreate()
.setId(UUID.randomUUID().toString())
.setToolingId("TerminologyToolingId")
.setMessageTemplate("Error message")
.setSeverity(Severity.ERROR)
.setType("snomed-query")
.setImplementation("*")
.buildAsync().getRequest()
.execute(context);
final ValidationRule rule = ValidationRequests.rules().prepareGet(ruleId).buildAsync().getRequest().execute(context);
assertThat(rule.getToolingId()).isEqualTo("TerminologyToolingId");
assertThat(rule.getMessageTemplate()).isEqualTo("Error message");
assertThat(rule.getSeverity()).isEqualTo(Severity.ERROR);
assertThat(rule.getType()).isEqualTo("snomed-query");
assertThat(rule.getImplementation()).isEqualTo("*");
}
}
| 35.009804 | 119 | 0.768692 |
19f6ef4354ff665e666a85e68478ab5baf25b047 | 256 | package mods.defeatedcrow.api.appliance;
import net.minecraft.item.ItemStack;
/**
* Jawplateを作成する場合に実装するインターフェイス
*/
public interface IJawPlate {
// 一回使用される度に呼ばれるメソッド
ItemStack returnItem(ItemStack item);
// Tier設定
int getTier(ItemStack item);
}
| 15.058824 | 40 | 0.765625 |
df9a6ae075eb5de3f2b183992491de077e314f68 | 2,619 | package it.at7.gemini.boot;
import it.at7.gemini.api.Api;
import it.at7.gemini.auth.api.AuthModuleAPI;
import it.at7.gemini.auth.core.AuthModule;
import it.at7.gemini.core.Gemini;
import it.at7.gemini.gui.Gui;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.Banner;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.Set;
public class GeminiPostgresql {
private static final Logger logger = LoggerFactory.getLogger(GeminiPostgresql.class);
public static void start(String[] args) {
start(args, Set.of(), Set.of());
}
public static void start(String[] args, Set<Class> coreBean, Set<Class> apiBean) {
logger.info("***** STARTING GEMINI POSTRESQL MAIN *****");
logger.info("STARTING - GEMINI-ROOT APP CONTEXT ");
SpringApplicationBuilder appBuilder = new SpringApplicationBuilder()
.parent(AutoConfiguration.class, Gemini.class, AuthModule.class);
if (coreBean.size() != 0) {
appBuilder.sources(coreBean.toArray(new Class[0]));
}
ConfigurableApplicationContext root = appBuilder
.web(WebApplicationType.NONE)
.bannerMode(Banner.Mode.OFF)
.run(args);
root.setId("GEMINI-ROOT");
Gemini gemini = root.getBean(Gemini.class);
gemini.init();
logger.info("STARTED - GEMINI-ROOT APP CONTEXT");
logger.info("STARTING - GEMINI-GUI APP CONTEXT ");
SpringApplicationBuilder webAppBuilder = new SpringApplicationBuilder()
.parent(root).sources(Api.class).sources(Gui.class, AuthModuleAPI.class, AutoConfiguration.class).web(WebApplicationType.SERVLET);
if (apiBean.size() != 0) {
webAppBuilder.sources(apiBean.toArray(new Class[0]));
}
ConfigurableApplicationContext gui = webAppBuilder.bannerMode(Banner.Mode.OFF)
.run(args);
gui.setId("GEMINI-GUI");
logger.info("STARTED - GEMINI-GUI APP CONTEXT");
}
@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class})
public static class AutoConfiguration {
}
}
| 40.921875 | 146 | 0.712486 |
64072725f58b15ae21a387c10f0ce1ef6a86b223 | 1,033 | package ru.job4j.sbulygin.condition;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Class DummyBotTest.
* @author sbulygin.
* @since 02.08.2018.
* @version 1.0.
*/
public class DummyBotTest {
/**
* Test greet answer.
*/
@Test
public void whenGreetBot() {
DummyBot bot = new DummyBot();
assertThat(
bot.answer("Привет, Бот."),
is("Привет, умник.")
);
}
/**
* Test byu answer.
*/
@Test
public void whenByuBot() {
DummyBot bot = new DummyBot();
assertThat(
bot.answer("Пока."),
is("До скорой встречи.")
);
}
/**
* Test unknown answer.
*/
@Test
public void whenUnknownBot() {
DummyBot bot = new DummyBot();
assertThat(
bot.answer("Сколько будет 2 + 2?"),
is("Это ставит меня в тупик. Спросите другой вопрос.")
);
}
}
| 20.254902 | 70 | 0.518877 |
c83724f91d7fd587aaf7874d79b3716b39cc9634 | 567 | package org.camunda.bpm.example.bpmntransaction.bpmntransaction;
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
public class CancelBookingDelegate implements JavaDelegate {
@Override
public void execute(DelegateExecution exec) throws Exception {
HotelBookingForm thisBooking = (HotelBookingForm) exec.getVariable("thisBooking");
exec.removeVariable("thisBooking");
exec.setVariable("cancelledBooking", thisBooking);
//
}
}
| 24.652174 | 84 | 0.791887 |
d388519e44d43447f8ae2b95db9665a7d430fb3f | 5,663 | package duy.phuong.handnote.Fragment;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import duy.phuong.handnote.DTO.Character;
import duy.phuong.handnote.DTO.Line;
import duy.phuong.handnote.Listener.BackPressListener;
import duy.phuong.handnote.MyView.DrawingView.FingerDrawerView;
import duy.phuong.handnote.R;
import duy.phuong.handnote.Recognizer.BitmapProcessor;
import duy.phuong.handnote.Recognizer.ImageToText;
import duy.phuong.handnote.Recognizer.MachineLearning.Input;
import duy.phuong.handnote.Support.SupportUtils;
/**
* Created by Phuong on 24/05/2016.
*/
public class WebFragment extends BaseFragment implements BitmapProcessor.DetectCharactersCallback, BackPressListener {
private WebView mWebView;
private FingerDrawerView mDrawer;
private LinearLayout mLayoutProcessing;
private ArrayList<String> mListDomainNames;
public WebFragment() {
mLayoutRes = R.layout.fragment_web;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mDrawer = (FingerDrawerView) mFragmentView.findViewById(R.id.FingerDrawer);
mDrawer.setListener(this);
mDrawer.setDisplayListener(this);
mDrawer.setDefault();
mWebView = (WebView) mFragmentView.findViewById(R.id.webSearch);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
mWebView.getSettings().setLoadsImagesAutomatically(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
mLayoutProcessing.setVisibility(View.VISIBLE);
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mLayoutProcessing.setVisibility(View.GONE);
}
});
mWebView.loadUrl("about:blank");
mLayoutProcessing = (LinearLayout) mFragmentView.findViewById(R.id.layoutProcessing);
initDomainNames();
}
@Override
public void onStart() {
super.onStart();
}
@Override
public String fragmentIdentify() {
return BaseFragment.WEB_FRAGMENT;
}
@Override
public void onBeginDetect(Bundle bundle) {
mLayoutProcessing.setVisibility(View.VISIBLE);
}
@Override
public void onDetectSuccess(final ArrayList<Character> listCharacters) {
if (listCharacters.size() > 0) {
for (Character character : listCharacters) {
character.isSorted = false;
}
final ArrayList<Line> currentLines = mDrawer.getLines();
ImageToText imageToText = new ImageToText(mListener.getGlobalSOM(), mListener.getMapNames());
imageToText.imageToText(currentLines, listCharacters, new ImageToText.ConvertingCompleteCallback() {
@Override
public void convertingComplete(String result, HashMap<Input, Point> map) {
String url = result.replace(" ", "").toLowerCase();
for (String domain : mListDomainNames) {
if (url.contains(domain)) {
mWebView.loadUrl("https://" + url);
return;
}
}
mWebView.loadUrl("https://www.google.com.vn/search?q=" + result);
}
});
} else {
mLayoutProcessing.setVisibility(View.VISIBLE);
}
}
@Override
public boolean doBack() {
if (!mDrawer.isEmpty()) {
mDrawer.emptyDrawer();
mWebView.loadUrl("about:blank");
return true;
}
return false;
}
public void initDomainNames() {
if (mListDomainNames == null) {
mListDomainNames = new ArrayList<>();
} else {
mListDomainNames.clear();
}
try {
String data = SupportUtils.getStringResource(mActivity, R.raw.domain);
String[] domainData = data.split("\r\n");
if (domainData.length > 0) {
for (String s : domainData) {
if (s.length() > 0) {
StringTokenizer tokenizer = new StringTokenizer(s, ".");
if (tokenizer.countTokens() > 0) {
while (tokenizer.hasMoreTokens()) {
String domain = tokenizer.nextToken();
if (domain.length() > 0) {
mListDomainNames.add("." + domain);
}
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 35.616352 | 118 | 0.597033 |
92057a66d1ea491651d99990f9c5061857e57e65 | 686 | /*
* Copyright (C) 2016 Andrea Binello ("andbin")
*
* This file is part of the "Java Examples" project and is licensed under the
* MIT License. See one of the license files included in the root of the project
* for the full text of the license.
*/
package javaexample;
public class StandardFontsDemoPdfMain {
public static void main(String[] args) {
String filename = "standard-fonts-demo.pdf";
try {
StandardFontsDemoPdf standardFontsDemoPdf = new StandardFontsDemoPdf(filename);
System.out.format("Generating %s ... ", filename);
standardFontsDemoPdf.generateDocument();
System.out.println("Ok");
} catch (Exception e) {
System.err.println(e);
}
}
} | 27.44 | 82 | 0.715743 |
8b32db2837d2cb67868f8664021ba32771fdcd11 | 2,201 | /*
* 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.
*/
/*
* SchemaParserTest.java
* NetBeans JUnit based test
*
* Created on July 24, 2002, 11:44 PM
*/
package org.netbeans.modules.xml.wizard;
import org.netbeans.modules.xml.wizard.SchemaParser;
import java.net.URL;
import junit.framework.*;
import org.netbeans.junit.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
/**
*
* @author Petr Kuzel <petr.kuzel@sun.com>
*/
public class SchemaParserTest extends NbTestCase {
public SchemaParserTest(java.lang.String testName) {
super(testName);
}
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new NbTestSuite(SchemaParserTest.class);
return suite;
}
/** Test of parse method, of class org.netbeans.modules.xml.wizard.SchemaParser. */
public void testParse() {
System.out.println("testParse");
URL ns = getClass().getResource("data/schemaWithNS.xsd");
SchemaParser parser = new SchemaParser();
SchemaParser.SchemaInfo info = parser.parse(ns.toExternalForm());
assertTrue("root expected",info.roots.contains("root"));
assertTrue("ns expected", "test:schemaWithNS".equals(info.namespace));
assertTrue("unexpected root", info.roots.contains("seq1") == false);
}
}
| 31.898551 | 87 | 0.686506 |
ba099d776aa2abf7623ec112d97fc2345b63d55f | 3,798 | package com.kika.simplifycontacts.ui.fragment;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import butterknife.Bind;
import com.kika.simplifycontacts.R;
import com.kika.simplifycontacts.bean.Contact;
import com.kika.simplifycontacts.presenter.IMainPresenter;
import com.kika.simplifycontacts.presenter.impl.MainPresenter;
import com.kika.simplifycontacts.support.Constants;
import com.kika.simplifycontacts.ui.activity.ContactDetailActivity;
import com.kika.simplifycontacts.ui.adapter.BaseRecyclerAdapter;
import com.kika.simplifycontacts.ui.adapter.ContactAdapter;
import com.kika.simplifycontacts.view.IMainView;
import java.util.List;
/**
* Created by skylineTan on 2016/6/30.
*/
public class MainFragment
extends BaseListFragment<List<Contact>, IMainView, IMainPresenter>
implements IMainView,SwipeRefreshLayout.OnRefreshListener{
@Bind(R.id.loadingView) ProgressBar loadingView;
@Bind(R.id.errorView) TextView errorView;
@Bind(R.id.main_recycler_view) RecyclerView mainRecyclerView;
@Bind(R.id.main_swipe_refresh_layout) SwipeRefreshLayout
mainSwipeRefreshLayout;
private List<Contact> mContactList;
private ContactAdapter mContactAdapter;
@Override protected IMainPresenter createPresenter() {
return new MainPresenter(getActivity());
}
@Override protected void initViewsAndEvents() {
loadData(false);
}
@Override protected int getLayoutId() {
return R.layout.fragment_main;
}
@Override public void showLoading(boolean pullToRefresh) {
errorView.setVisibility(View.GONE);
loadingView.setVisibility(View.VISIBLE);
mainRecyclerView.setVisibility(View.GONE);
}
@Override public void hideLoading() {
errorView.setVisibility(View.GONE);
loadingView.setVisibility(View.GONE);
mainRecyclerView.setVisibility(View.VISIBLE);
}
@Override public void showError(String msg, boolean pullToRefresh) {
errorView.setVisibility(View.VISIBLE);
loadingView.setVisibility(View.GONE);
mainRecyclerView.setVisibility(View.GONE);
}
@Override public void setData(List<Contact> data) {
mContactList = data;
mContactAdapter = new ContactAdapter(getActivity(),R.layout
.item_contact,mContactList);
mainRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mContactAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
@Override public void onItemClick(View view, int position) {
ContactDetailActivity.startActivityWithContact(getActivity(),
mContactList.get(position));
}
});
mainRecyclerView.setAdapter(mContactAdapter);
}
@Override public void loadData(boolean pullToRefresh) {
mPresenter.loadContacts(pullToRefresh);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK){
mContactAdapter.add((Contact) data.getParcelableExtra(Constants.Extras
.ADD_CONTACT));
}
}
@Override public void onRefresh() {
loadData(true);
}
}
| 33.610619 | 95 | 0.707214 |
75bded793881d536cde72fb575892cf94bbfe10a | 348 | package buffer;
public class BCB {
public BCB(int page_id2, int frame_id2, boolean b, int i, boolean c) {
page_id = page_id2;
frame_id = frame_id2;
latch = b;
count = i;
dirty = c;
// TODO Auto-generated constructor stub
}
public int page_id;
public int frame_id;
public boolean latch;
public int count;
public boolean dirty;
}
| 19.333333 | 71 | 0.701149 |
4cb1ee55d69b5097a8816d3c3366bc975b25cf8b | 5,905 | /*******************************************************************************
* Copyright 2012-present Pixate, 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.pixate.freestyle.styling.adapters;
import java.util.ArrayList;
import java.util.List;
import android.app.ActionBar;
import android.widget.ImageButton;
import com.pixate.freestyle.annotations.PXDocElement;
import com.pixate.freestyle.styling.virtualStyleables.PXVirtualActionBarOverflowImage;
/**
* A style adapter for {@link ActionBar} 'overflow' menu button. This adapter is
* very similar to the {@link PXImageButtonStyleAdapter}, as the Android's
* internal implementation for the menu button extends {@link ImageButton}.
*
* <pre>
* - scale-type: center | center-crop | center-inside | fit-center | fit-end | fit-start | fit-xy | matrix
* - max-height: px
* - max-width: px
* - view-bounds: adjust | none
* - tint: color
* - transform: matrix (inherited from the view styles, but used here when the scale-type is set to 'matrix')
* </pre>
*
* For example:
*
* <pre>
* action-bar-overflow {
* tint: #450022FF;
* transform: matrix(0.8660254037844387, 0.49999999999999994, -0.49999999999999994, 0.8660254037844387, 0, 0);
* scale-type: matrix;
* background-image: url(default-bg.svg);
* }
*
* </pre>
*
* And to set the image properties (virtual child of 'image'):
*
* <pre>
* action-bar-overflow image {
* background-image: url(mic-on.svg);
* background-size: 300px;
* }
*
* action-bar-overflow image:pressed {
* background-image: url(mic-off.svg);
* background-size: 300px;
* }
* </pre>
*
* @author Shalom Gibly
*/
@PXDocElement
public class PXActionBarOverflowStyleAdapter extends PXImageViewStyleAdapter {
private static String ELEMENT_NAME = "action-bar-overflow";
private static PXActionBarOverflowStyleAdapter instance;
/**
* Returns an instance of this {@link PXActionBarOverflowStyleAdapter}
*/
public static PXActionBarOverflowStyleAdapter getInstance() {
synchronized (PXActionBarOverflowStyleAdapter.class) {
if (instance == null) {
instance = new PXActionBarOverflowStyleAdapter();
}
}
return instance;
}
protected PXActionBarOverflowStyleAdapter() {
}
/*
* (non-Javadoc)
* @see
* com.pixate.freestyle.styling.adapters.PXImageViewStyleAdapter#getElementName
* (java.lang.Object)
*/
@Override
public String getElementName(Object object) {
return ELEMENT_NAME;
}
/*
* (non-Javadoc)
* @see
* com.pixate.freestyle.styling.adapters.PXStyleAdapter#getVirtualChildren
* (java.lang.Object)
*/
@Override
protected List<Object> getVirtualChildren(Object styleable) {
// Intentionally don't add the super to avoid conflict.
List<Object> result = new ArrayList<Object>(1);
result.add(new PXVirtualActionBarOverflowImage(styleable));
return result;
}
/*
* (non-Javadoc)
* @see com.pixate.freestyle.styling.adapters.PXCompoundButtonStyleAdapter#
* createAdditionalDrawableStates(int)
*/
@Override
public int[][] createAdditionalDrawableStates(int initialValue) {
// These are the states that are set for the default implementation of
// that menu button. Note that the 'pressed' state are actually taking
// TransitionDrawables, which we don't support yet.
// @formatter:off
// { android.R.attr.state_focused, -android.R.attr.state_enabled, android.R.attr.state_pressed }
// { android.R.attr.state_focused, -android.R.attr.state_enabled }
// { android.R.attr.state_focused, android.R.attr.state_pressed }
// { -android.R.attr.state_focused, android.R.attr.state_pressed }
// { android.R.attr.state_focused }
// { } - default 'android.R.attr.drawable'
// @formatter:on
List<int[]> states = new ArrayList<int[]>(4);
// check for some special cases for the image button.
// @formatter:off
switch (initialValue) {
case android.R.attr.state_focused:
states.add(new int[] { android.R.attr.state_focused, -android.R.attr.state_enabled });
break;
case android.R.attr.state_pressed:
states.add(new int[] { android.R.attr.state_focused, -android.R.attr.state_enabled, android.R.attr.state_pressed});
states.add(new int[] { android.R.attr.state_focused, android.R.attr.state_pressed});
states.add(new int[] { -android.R.attr.state_focused, android.R.attr.state_pressed});
break;
case android.R.attr.drawable:
states.add(new int[] { android.R.attr.state_focused, -android.R.attr.state_enabled });
states.add(new int[] { android.R.attr.state_focused, android.R.attr.state_enabled });
states.add(new int[] { android.R.attr.state_enabled });
states.add(new int[] {});
break;
default:
break;
}
// @formatter:on
states.add(new int[] { initialValue });
return states.toArray(new int[states.size()][]);
}
}
| 36.90625 | 131 | 0.636749 |
fe31463f297d55baca883183023bf09af5bc4484 | 377 | package com.gxitsky.structural.bridge.message;
/**
* @author gxing
* @desc 告警类型
* @date 2021/6/18
*/
public class WarnMessage extends AbstractMessage {
public WarnMessage(IMessage iMessage) {
super(iMessage);
}
@Override
void sendMessage(String content) {
System.out.println("----->告警消息类型");
super.iMessage.send(content);
}
}
| 18.85 | 50 | 0.64191 |
451c94dcaf324a0668fbd1422b2a3741d9b85496 | 3,142 | /*
Title : Find the transpose of the matrix .
User needs to provide the number of rows and columns .
And the user needs to provide the elements of the matrix .
User will get the transpose of the matrix .
i.e Row elements become the column elements and vice- versa .
**** Maximum 10 number of rows and columns can be only entered .
*/
import java.util.Scanner;
import java.lang.*;
class transpose
{
final static int MAXLIMIT=10 ;
private int row;
private int col;
int i ,j ;
private double a[][];
transpose(int rows , int cols) //Constructor
{
row=rows ;
col=cols ;
a=new double[row][col] ;
}
Scanner in=new Scanner(System.in);
public void get ()
{
System.out.println("\n Enter the elements : \n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
a[i][j]=in.nextDouble();
}
}
}
public void display ()
{
System.out.println( "\n Matrix A " + row + " * " + col + " : \n") ;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
System.out.print(a[i][j]+ "\t") ;
}
System.out.println("\n") ;
}
}
public void trans()
{
System.out.println( "\n\n The transpose of the given matrix : \n");
System.out.println( "\n Matrix AT " + col + " * " + row+ " : \n") ;
for(i=0;i<col;i++)
{
for(j=0;j<row;j++)
{
System.out.print(a[j][i]+ "\t") ;
}
System.out.println("\n") ;
}
}
public static void main (String [] args )
{
int rows , cols ;
int opt;
Scanner in=new Scanner(System.in);
do
{ opt=0;
System.out.println("\n Enter the total number of rows and columns respectively : \n");
rows=in.nextInt();
cols=in.nextInt();
if(rows>MAXLIMIT|| cols>MAXLIMIT|| rows<1||cols<1)
{
System.out.println("\n Invalid enteries ! \n Remember , Maximum limit of rows and columns is 10 .\n");
System.out.println(" Do you wish to continue ? \n Press 1 if yes otherwise any to stop . \n");
opt=in.nextInt();
}
else
{
transpose A = new transpose(rows , cols);
A.get();
A.display();
A.trans();
}
} while(opt==1);
}
}
/*
Enter the total number of rows and columns respectively :
13
1
Invalid enteries !
Remember , Maximum limit of rows and columns is 10 .
Do you wish to continue ?
Press 1 if yes otherwise any to stop .
1
Enter the total number of rows and columns respectively :
3
2
Enter the elements :
1
2
3
5
5
5
Matrix A 3 * 2 :
1.0 2.0
3.0 5.0
5.0 5.0
The transpose of the given matrix : \n");
Matrix AT 2 * 3 :
1.0 3.0 5.0
2.0 5.0 5.0
*/
| 20.807947 | 117 | 0.480586 |
2668bec0117ceec74226ac286a2f212e3ea6ea6d | 201 | public interface ISortAlgorithm {
/**
* 排序算法的名字
*
* @return
*/
String getName();
/**
* 排序算法的实现
*
* @param arr 待排序数组
*/
void sort(int[] arr);
}
| 11.823529 | 33 | 0.442786 |
4ad87609ff7ca37961d41a6aaae30865f60d6096 | 1,546 | package io.github.picodotdev.blogbitix.javaexception;
import io.vavr.control.Either;
import io.vavr.control.Try;
import java.util.Optional;
import java.util.concurrent.TransferQueue;
public class Main {
private static int errorCode(boolean error) {
return (error) ? 1 : 0;
}
private static Optional<Integer> optional(boolean error) {
return (error) ? Optional.empty() : Optional.of(0);
}
private static Integer exception(boolean error) throws Exception {
if (error) {
throw new Exception();
} else {
return 0;
}
}
private static Either<Exception, Integer> either(boolean error) {
return (error) ? Either.left(new Exception()) : Either.right(1);
}
public static void main(String[] args) {
int errorCode = errorCode(true);
if (errorCode != 0) {
System.out.printf("Error code: %d%n", errorCode);
}
Optional<Integer> value = optional(true);
if (!value.isPresent()) {
System.out.println("Optional empty");
}
try {
exception(true);
} catch (Exception e) {
e.printStackTrace();
}
Either<Exception, Integer> either = either(true);
if (either.isLeft()) {
System.out.printf("Either exception: %s%n", either.getLeft().getClass().getName());
}
Try.<Integer>of(() -> exception(true)).onFailure(e -> System.out.printf("Try exception: %s%n", e.getClass().getName()));
}
}
| 27.122807 | 128 | 0.587322 |
c092449a6fb01c33bf3b526d9ef8d423d3debe10 | 2,029 | package com.nbs.iais.ms.meta.referential.db.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nbs.iais.ms.common.db.domains.translators.Translator;
import com.nbs.iais.ms.meta.referential.common.messageing.queries.process.document.GetProcessDocumentQuery;
import com.nbs.iais.ms.meta.referential.common.messageing.queries.process.document.GetProcessDocumentsQuery;
import com.nbs.iais.ms.meta.referential.db.domains.gsim.ProcessDocumentationEntity;
import com.nbs.iais.ms.meta.referential.db.repositories.ProcessDocumentRepository;
@Service
public class ProcessDocumentQueryService {
@Autowired
private ProcessDocumentRepository processDocumentRepository;
/**
* Method to get all process documents or many process documents filtered by
* processDocumentation
*
* @param query to request
* @return GetProcessDocumentsQuery with the DTOList of requested process
* documents
*/
public GetProcessDocumentsQuery getProcessDocuments(final GetProcessDocumentsQuery query) {
if (query.getProcessDocumentation() != null) {
Translator
.translateProcessDocuments(
processDocumentRepository.findByProcessDocumentation(
new ProcessDocumentationEntity(query.getProcessDocumentation())),
query.getLanguage())
.ifPresent(query.getRead()::setData);
return query;
}
Translator.translateProcessDocuments(processDocumentRepository.findAll(), query.getLanguage())
.ifPresent(query.getRead()::setData);
return query;
}
/**
* Method to get a single process documents by id
*
* @param query to request
* @return GetProcessDocumentQuery including requested process documents dto in
* the read
*/
public GetProcessDocumentQuery getProcessDocument(final GetProcessDocumentQuery query) {
processDocumentRepository.findById(query.getId()).flatMap(ss -> Translator.translate(ss, query.getLanguage()))
.ifPresent(query.getRead()::setData);
return query;
}
}
| 33.816667 | 112 | 0.782159 |
55fcf1dd6edd2798d3b3bea9ba317249eef5a6e4 | 6,780 | /*
* Copyright 2010 Outerthought bvba
*
* 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.lilyproject.util.repo;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.lilyproject.repository.api.FieldType;
import org.lilyproject.repository.api.FieldTypeNotFoundException;
import org.lilyproject.repository.api.IdRecord;
import org.lilyproject.repository.api.LRepository;
import org.lilyproject.repository.api.LTable;
import org.lilyproject.repository.api.QName;
import org.lilyproject.repository.api.Record;
import org.lilyproject.repository.api.RecordId;
import org.lilyproject.repository.api.RepositoryException;
import org.lilyproject.repository.api.SchemaId;
import org.lilyproject.repository.api.Scope;
import org.lilyproject.repository.api.TypeManager;
/**
* Version tag related utilities.
*/
public class VersionTag {
/**
* Namespace for field types that serve as version tags.
*/
public static final String NAMESPACE = "org.lilyproject.vtag";
/**
* Name for the field type that serves as last version tag.
*/
public static final QName LAST = new QName(NAMESPACE, "last");
private VersionTag() {
}
public static QName qname(String vtag) {
return new QName(NAMESPACE, vtag);
}
/**
* Returns true if the given FieldType is a version tag.
*/
public static boolean isVersionTag(FieldType fieldType) {
String namespace = fieldType.getName().getNamespace();
return (fieldType.getScope() == Scope.NON_VERSIONED
&& fieldType.getValueType().getBaseName().equals("LONG")
&& namespace != null && namespace.equals(NAMESPACE) /* namespace is typically the longest string,
therefore compare it last */
&& !fieldType.getName().getName().equals("last")); /* filter out 'last' vtag, it should not be
custom assigned */
}
/**
* Filters the given set of fields to only those that are vtag fields.
*/
public static Set<SchemaId> filterVTagFields(Set<SchemaId> fieldIds, TypeManager typeManager)
throws RepositoryException, InterruptedException {
Set<SchemaId> result = new HashSet<SchemaId>();
for (SchemaId field : fieldIds) {
try {
if (isVersionTag(typeManager.getFieldTypeById(field))) {
result.add(field);
}
} catch (FieldTypeNotFoundException e) {
// ignore, if it does not exist, it can't be a version tag
}
}
return result;
}
/**
* Get an IdRecord of the given vtag version, based on a recordId.
*/
public static IdRecord getIdRecord(RecordId recordId, SchemaId vtagId, LTable table, LRepository repository)
throws RepositoryException, InterruptedException {
VTaggedRecord vtRecord = new VTaggedRecord(recordId, null, table, repository);
return vtRecord.getIdRecord(vtagId);
}
/**
* Get an IdRecord of the given vtag version, based on a existing IdRecord. The existing IdRecord should be the
* last (when it was read) and should have been read with all fields!
*/
public static IdRecord getIdRecord(IdRecord idRecord, SchemaId vtagId, LTable table, LRepository repository)
throws RepositoryException, InterruptedException {
VTaggedRecord vtRecord = new VTaggedRecord(idRecord, null, table, repository);
return vtRecord.getIdRecord(vtagId);
}
/**
* Returns null if the vtag does not exist or is not defined for the record.
*/
public static Record getRecord(RecordId recordId, String vtag, List<QName> fields,
LTable table, LRepository repository) throws RepositoryException, InterruptedException {
QName vtagName = new QName(NAMESPACE, vtag);
Record record = table.read(recordId);
long version;
if (vtag.equals("last")) {
// we loaded the last version
if (fields != null) {
filterFields(record, new HashSet<QName>(fields));
}
return record;
} else if (!record.hasField(vtagName)) {
return null;
} else {
version = (Long) record.getField(vtagName);
if (version == 0) {
reduceToNonVersioned(record, fields != null ? new HashSet<QName>(fields) : null,
repository.getTypeManager());
} else {
record = table.read(recordId, version, fields);
}
return record;
}
}
/**
* Removes any versioned information from the supplied record object.
*/
public static void reduceToNonVersioned(Record record, Set<QName> fields, TypeManager typeManager)
throws RepositoryException, InterruptedException {
if (record.getVersion() == null) {
// The record has no versions so there should be no versioned fields in it
return;
}
Iterator<Map.Entry<QName, Object>> fieldsIt = record.getFields().entrySet().iterator();
while (fieldsIt.hasNext()) {
Map.Entry<QName, Object> entry = fieldsIt.next();
if (fields != null && !fields.contains(entry.getKey())) {
fieldsIt.remove();
} else if (typeManager.getFieldTypeByName(entry.getKey()).getScope() != Scope.NON_VERSIONED) {
fieldsIt.remove();
}
}
// Remove versioned record type info
record.setRecordType(Scope.VERSIONED, (QName) null, null);
record.setRecordType(Scope.VERSIONED_MUTABLE, (QName) null, null);
}
private static void filterFields(Record record, Set<QName> fields) {
Iterator<Map.Entry<QName, Object>> fieldsIt = record.getFields().entrySet().iterator();
while (fieldsIt.hasNext()) {
Map.Entry<QName, Object> entry = fieldsIt.next();
if (!fields.contains(entry.getKey())) {
fieldsIt.remove();
}
}
}
}
| 37.877095 | 115 | 0.634956 |
6450d2534c23c98eaec1ec89580fe74c87b00f3c | 2,656 | package frc.robot.subsystems;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.RobotBase;
import edu.wpi.first.wpilibj.RobotController;
import edu.wpi.first.wpilibj.motorcontrol.Victor;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.wpilibj.simulation.ElevatorSim;
import edu.wpi.first.wpilibj.simulation.EncoderSim;
import edu.wpi.first.math.system.plant.DCMotor;
import edu.wpi.first.math.util.Units;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.PIDSubsystem;
public class Elevator extends PIDSubsystem {
private static final double kP = 4;
private static final double kI = 0.0;
private static final double kD = 0.0;
private static final double kElevatorGearing = 10.0;
private static final double kElevatorDrumRadius = Units.inchesToMeters(2);
private static final double kCarriageMass = 4.0;
private static final DCMotor kElevatorGearbox = DCMotor.getVex775Pro(4);
private static final double kMinElevatorHeight = Units.inchesToMeters(0);
private static final double kMaxElevatorHeight = Units.inchesToMeters(50);
private static final double kArmEncoderDistPerPulse =
2.0 * 3.14 * kElevatorDrumRadius / 4096.0;
private final Victor m_motor;
private final Encoder m_encoder;
// Sim
private EncoderSim m_encoderSim;
private ElevatorSim m_elevatorSim;
/** Create a new elevator subsystem. */
public Elevator() {
super(new PIDController(kP, kI, kD));
m_motor = new Victor(PortMap.kElevatorMotorPort);
m_encoder = new Encoder(PortMap.kElevatorEncoderPortA, PortMap.kElevatorEncoderPortB);
m_encoder.setDistancePerPulse(kArmEncoderDistPerPulse);
getController().setTolerance(0.005);
if (RobotBase.isSimulation()) {
m_encoderSim = new EncoderSim(m_encoder);
m_elevatorSim = new ElevatorSim(kElevatorGearbox, kElevatorGearing, kCarriageMass,
kElevatorDrumRadius, kMinElevatorHeight,
kMaxElevatorHeight);
}
}
public void log() {
SmartDashboard.putNumber("Elevator Height", m_encoder.getDistance());
}
@Override
public double getMeasurement() {
return m_encoder.getDistance();
}
@Override
public void useOutput(double output, double setpoint) {
m_motor.set(output);
}
@Override
public void periodic() {
log();
}
@Override
public void simulationPeriodic() {
m_elevatorSim.setInput(m_motor.get() * RobotController.getInputVoltage());
m_elevatorSim.update(0.02);
m_encoderSim.setDistance(m_elevatorSim.getPositionMeters());
}
public void stop() {
m_motor.set(0);
}
}
| 30.528736 | 90 | 0.747364 |
fa4d8055c2c280e74c4b2417a9cbf03d4769b927 | 2,300 | package me.simple.domain;
import me.simple.validator.group.Remove;
import org.hibernate.validator.constraints.Length;
import java.util.List;
public class SysMenu implements java.io.Serializable {
private int id;
private int pid;
private String viewname;
private String url;
private int srt;
private boolean deleted;
private boolean disabled;
private String cruser;
private java.sql.Timestamp crtime;
private String mduser;
private java.sql.Timestamp mdtime;
// ============================================================
@Length(min = 1,max = 200,groups = {Remove.class})
private String ids;
private List<SysMenu> children;
// ============================================================
public SysMenu() {
}
public SysMenu(int id) {
this.id = id;
}
// ============================================================
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public int getPid(){
return pid;
}
public void setPid(int pid){
this.pid = pid;
}
public String getViewname(){
return viewname;
}
public void setViewname(String viewname){
this.viewname = viewname;
}
public String getUrl(){
return url;
}
public void setUrl(String url){
this.url = url;
}
public boolean getDeleted(){
return deleted;
}
public void setDeleted(boolean deleted){
this.deleted = deleted;
}
public boolean getDisabled(){
return disabled;
}
public void setDisabled(boolean disabled){
this.disabled = disabled;
}
public String getCruser(){
return cruser;
}
public void setCruser(String cruser){
this.cruser = cruser;
}
public java.sql.Timestamp getCrtime(){
return crtime;
}
public void setCrtime(java.sql.Timestamp crtime){
this.crtime = crtime;
}
public String getMduser(){
return mduser;
}
public void setMduser(String mduser){
this.mduser = mduser;
}
public java.sql.Timestamp getMdtime(){
return mdtime;
}
public void setMdtime(java.sql.Timestamp mdtime){
this.mdtime = mdtime;
}
public int getSrt() {
return srt;
}
public void setSrt(int srt) {
this.srt = srt;
}
public String getIds() {
return ids;
}
public void setIds(String ids) {
this.ids = ids;
}
public List<SysMenu> getChildren() {
return children;
}
public void setChildren(List<SysMenu> children) {
this.children = children;
}
} | 18.852459 | 63 | 0.657826 |
b617a86a6798d2fa5ec05738f1d18d84c31b928c | 3,484 | package instrumentTest.model.dao;
import android.location.Location;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import shike.app.helper.json.JsonDateDeserializer;
import shike.app.helper.json.JsonDateSerializer;
import shike.app.model.dao.performance.PerformanceDao;
import shike.app.model.dao.performance.PerformanceDaoImpl;
import shike.app.model.session.performance.Performance;
import shike.app.model.session.track.RecordedTrack;
/**
* Test per la classe PerformanceDaoImpl
*/
public class PerformanceDaoImplTest extends DaoBaseTest {
private PerformanceDao performanceDao;
@Override
protected void setUp() throws Exception {
super.setUp();
performanceDao = new PerformanceDaoImpl(context);
}
public void testMultipleItems() {
Map<Integer, Performance> perfMap = new HashMap<>();
int performanceCount = randomGenerator.nextInt(100);
for (int i = 0; i < performanceCount; i++) {
Performance rndPerformance = randomPerformance();
perfMap.put(rndPerformance.get_id(), rndPerformance);
}
performanceCount = perfMap.size();
Collection<Performance> perfCol = perfMap.values();
assertEquals(performanceCount, performanceDao.add(new ArrayList<>(perfCol), true));
List<Performance> dbPerfs = performanceDao.getAll();
assertEquals(perfCol.size(), dbPerfs.size());
assertTrue(perfCol.containsAll(dbPerfs) && dbPerfs.containsAll(perfCol));
assertEquals(performanceCount, performanceDao.removeAll());
}
public Performance randomPerformance() {
int _id = Math.abs(randomGenerator.nextInt()) + 1;
Performance performance = new Performance(_id, randomTrack(true));
performance.setDistance(randomGenerator.nextDouble() * 100000);
performance.setSteps(randomGenerator.nextInt(100000));
performance.setDate(new Date(Math.abs(randomGenerator.nextLong() % 1893456000000l)));
performance.setTotalTime(Math.abs(randomGenerator.nextLong()) % 36000000);
performance.setMaxSpeed(randomGenerator.nextDouble() * 20);
return performance;
}
private RecordedTrack randomTrack(boolean null_id) {
Integer _id = null;
if (!null_id) {
_id = Math.abs(randomGenerator.nextInt(10000)) + 1;
}
List<Location> points = new ArrayList<>();
int pointCount = randomGenerator.nextInt(100);
for (int i = 0; i < pointCount; i++) {
points.add(randomLocation());
}
Date creationDate = new Date(Math.abs(randomGenerator.nextLong() % 1893456000000l));
return new RecordedTrack(_id, null, creationDate, points);
}
public void testSingleItem() {
Performance performance = randomPerformance();
int _id = performance.get_id();
performanceDao.removeAll();
assertEquals(_id, performanceDao.add(performance));
Performance dbPerformance = performanceDao.getAll().get(0);
assertEquals(performance, dbPerformance);
assertEquals(1, performanceDao.removeAll());
}
public void testJsonConversion() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDateSerializer());
gsonBuilder.registerTypeAdapter(Date.class, new JsonDateDeserializer());
Gson gson = gsonBuilder.create();
Performance performance = randomPerformance();
String json = gson.toJson(performance);
Performance performance1 = gson.fromJson(json, Performance.class);
assertEquals(performance, performance1);
}
}
| 29.525424 | 87 | 0.762916 |
32aa1a0412859d67f4877911bfef742d9ce6124a | 5,163 | package org.pipservices3.commons.reflect;
import java.time.*;
import java.util.*;
import org.pipservices3.commons.convert.TypeCode;
import org.pipservices3.commons.convert.TypeConverter;
/**
* Helper class matches value types for equality.
* <p>
* This class has symmetric implementation across all languages supported
* by Pip.Services toolkit and used to support dynamic data processing.
*
* @see TypeCode
*/
public class TypeMatcher {
/**
* Matches expected type to a type of a value. The expected type can be
* specified by a type, type name or TypeCode.
*
* @param expectedType an expected type to match.
* @param actualValue a value to match its type to the expected one.
* @return true if types are matching and false if they don't.
*
* @see #matchType(Object, Class)
* @see #matchValueByName(String, Object) (for matching by types' string names)
*/
public static boolean matchValue(Object expectedType, Object actualValue) {
if (expectedType == null)
return true;
if (actualValue == null)
throw new NullPointerException("Actual value cannot be null");
return matchType(expectedType, actualValue.getClass());
}
/**
* Matches expected type to an actual type. The types can be specified as types,
* type names or TypeCode.
*
* @param expectedType an expected type to match.
* @param actualType an actual type to match.
* @return true if types are matching and false if they don't.
*
* @see #matchTypeByName(String, Class)
*/
public static boolean matchType(Object expectedType, Class<?> actualType) {
if (expectedType == null)
return true;
if (actualType == null)
throw new NullPointerException("Actual type cannot be null");
if (expectedType instanceof Class<?>)
return ((Class<?>) expectedType).isAssignableFrom(actualType);
if (expectedType instanceof String)
return matchTypeByName((String) expectedType, actualType);
if (expectedType instanceof TypeCode)
return TypeConverter.toTypeCode(actualType).equals(expectedType);
return false;
}
/**
* Matches expected type to a type of a value.
*
* @param expectedType an expected type name to match.
* @param actualValue a value to match its type to the expected one.
* @return true if types are matching and false if they don't.
*/
public static boolean matchValueByName(String expectedType, Object actualValue) {
if (expectedType == null)
return true;
if (actualValue == null)
throw new NullPointerException("Actual value cannot be null");
return matchTypeByName(expectedType, actualValue.getClass());
}
/**
* Matches expected type to an actual type.
*
* @param expectedType an expected type name to match.
* @param actualType an actual type to match defined by type code.
* @return true if types are matching and false if they don't.
*/
public static boolean matchTypeByName(String expectedType, Class<?> actualType) {
if (expectedType == null)
return true;
if (actualType == null)
throw new NullPointerException("Actual type cannot be null");
expectedType = expectedType.toLowerCase();
if (actualType.getName().equalsIgnoreCase(expectedType))
return true;
else if (actualType.getSimpleName().equalsIgnoreCase(expectedType))
return true;
else if (expectedType.equals("object"))
return true;
else if (expectedType.equals("int") || expectedType.equals("integer")) {
return Integer.class.isAssignableFrom(actualType) || Long.class.isAssignableFrom(actualType);
} else if (expectedType.equals("long")) {
return Long.class.isAssignableFrom(actualType);
} else if (expectedType.equals("float")) {
return Float.class.isAssignableFrom(actualType) || Double.class.isAssignableFrom(actualType);
} else if (expectedType.equals("double")) {
return Double.class.isAssignableFrom(actualType);
} else if (expectedType.equals("string")) {
return String.class.isAssignableFrom(actualType);
} else if (expectedType.equals("bool") || expectedType.equals("boolean")) {
return Boolean.class.isAssignableFrom(actualType);
} else if (expectedType.equals("date") || expectedType.equals("datetime")) {
return Date.class.isAssignableFrom(actualType) || Calendar.class.isAssignableFrom(actualType)
|| ZonedDateTime.class.isAssignableFrom(actualType);
} else if (expectedType.equals("timespan") || expectedType.equals("duration")) {
return Integer.class.isAssignableFrom(actualType) || Long.class.isAssignableFrom(actualType)
|| Float.class.isAssignableFrom(actualType) || Double.class.isAssignableFrom(actualType);
} else if (expectedType.equals("enum")) {
return Enum.class.isAssignableFrom(actualType);
} else if (expectedType.equals("map") || expectedType.equals("dict") || expectedType.equals("dictionary")) {
return Map.class.isAssignableFrom(actualType);
} else if (expectedType.equals("array") || expectedType.equals("list")) {
return actualType.isArray() || List.class.isAssignableFrom(actualType);
} else if (expectedType.endsWith("[]")) {
// Todo: Check subtype
return actualType.isArray() || List.class.isAssignableFrom(actualType);
} else
return false;
}
}
| 38.244444 | 110 | 0.730777 |
f429a965cb1e4dcf6da1aa2fe97e6ff44ddf496d | 349 | package org.elsys.postfix.operations;
import org.elsys.postfix.Calculator;
public class BinaryPlus extends BinaryOperation {
public BinaryPlus(Calculator calculator, String token) {
super(calculator, token);
}
@Override
public double binaryCalculate(double firstOperand, double secondOperand) {
return firstOperand + secondOperand;
}
}
| 21.8125 | 75 | 0.790831 |
ab50a7468e858aa3b4a8cf5701824c03a1665428 | 733 | package com.yhy.doc.excel.annotation;
import org.apache.poi.ss.usermodel.IndexedColors;
import java.lang.annotation.*;
/**
* 文档信息
* <p>
* Created on 2019-05-02 16:51
*
* @author 颜洪毅
* @version 1.0.0
* @since 1.0.0
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Document {
/**
* 标题样式
*
* @return 标题样式
*/
Style titleStyle() default @Style(
align = @Align,
border = @Border,
font = @Font(
size = 14,
bold = true
),
ground = @Ground(
back = IndexedColors.GREY_25_PERCENT,
fore = IndexedColors.GREY_25_PERCENT
),
size = @Size
);
}
| 17.878049 | 49 | 0.563438 |
57e54943cc44a49547219f1206a5d404c010561f | 1,755 | package synyx.coffee;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.TimeoutException;
/**
* Created by jayasinghe on 22/02/16.
*/
public class ReceiverApp {
private static final String QUEUE_NAME = "DEMO";
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
Optional<Connection > conn = Optional.empty();
Optional<Channel> channel = Optional.empty();
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.99.100");
conn = Optional.of(factory.newConnection());
channel = Optional.of(conn.get().createChannel());
channel.get().queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println("waiting for messages.");
Consumer firstConsumer = new DefaultConsumer(channel.get()) {
public void handleDelivery(String s, Envelope envelope,
AMQP.BasicProperties basicProperties, byte[] bytes) throws IOException {
String receivedMsg = new String(bytes, "UTF-8");
System.out.println("received message " + receivedMsg);
try {
doWork(receivedMsg);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
System.out.println("done! :)");
}
}
};
channel.get().basicConsume(QUEUE_NAME, true, firstConsumer);
}
private static void doWork(String task) throws InterruptedException {
for (char ch: task.toCharArray()) {
if (ch == '.') Thread.sleep(1000);
}
}
} | 35.816327 | 103 | 0.611396 |
0ed6ac102d2a1f6917eaaa5b7b03e1d0dbf35760 | 978 | package com.huiketong.cofpasgers.entity;
import lombok.Data;
import javax.persistence.*;
/**
* @Author:  ̄左飞 ̄
* @Date: 2018/12/25 21:24
* @Version 1.0
*/
@Entity
@Data
public class Bank {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(columnDefinition = "int(10) default 0")
Integer id;
@Column(columnDefinition = "int(10) default 0 COMMENT '用户ID'")
Integer userId;
@Column(columnDefinition = "varchar(255) default '' COMMENT '持卡人姓名'")
String name;
@Column(columnDefinition = "varchar(255) default '' COMMENT '所在城市'")
String city;
@Column(columnDefinition = "varchar(255) default '' COMMENT '支行'")
String branch;
@Column(columnDefinition = "varchar(255) default '' COMMENT '银行卡号'")
String bankNum;
@Column(columnDefinition = "int(10) default 0 COMMENT '公司ID'")
Integer companyId;
@Column(columnDefinition = "int(10) default 0 COMMENT '哪家银行1中国银行2中国工商银行3中国建设银行4中国农业银行'")
Integer bankId;
}
| 28.764706 | 92 | 0.682004 |
5bd9152546f1ae9826db86ddb6ff18cc81cfbcd0 | 819 | package com.twokeys.moinho.entities;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="tb_operational_payment")
public class OperationalPayment extends Payment {
private static final long serialVersionUID = 1L;
@ManyToOne
@JoinColumn(name="apportionment_type_id")
private OperationalCostType operationalCostType;
public OperationalPayment() {
}
public OperationalPayment(OperationalCostType operationalCostType) {
this.operationalCostType = operationalCostType;
}
public OperationalCostType getOperationalCostType() {
return operationalCostType;
}
public void setOperationalCostType(OperationalCostType operationalCostType) {
this.operationalCostType = operationalCostType;
}
}
| 24.818182 | 78 | 0.818071 |
475cbd71609b39740de469f64dcd14fbf441bc9d | 135 | /**
* Package for calculate test task.
*
* @author sbulygin
* @since 25.07.2018
* @version 1.0
*/
package ru.job4j.sbulygin.calculate;
| 15 | 36 | 0.696296 |
70008a16e80e903a74b9c60865b311653ea287db | 20,684 | package de.tum.in.www1.artemis.service;
import static de.tum.in.www1.artemis.security.AuthoritiesConstants.*;
import java.security.Principal;
import java.time.ZonedDateTime;
import java.util.Optional;
import javax.validation.constraints.NotNull;
import org.springframework.stereotype.Service;
import de.tum.in.www1.artemis.domain.*;
import de.tum.in.www1.artemis.domain.exam.Exam;
import de.tum.in.www1.artemis.domain.lecture.LectureUnit;
import de.tum.in.www1.artemis.domain.participation.StudentParticipation;
import de.tum.in.www1.artemis.repository.UserRepository;
import de.tum.in.www1.artemis.security.AuthoritiesConstants;
import de.tum.in.www1.artemis.security.SecurityUtils;
/**
* Service used to check whether user is authorized to perform actions on the entity.
*/
@Service
public class AuthorizationCheckService {
private final UserRepository userRepository;
public AuthorizationCheckService(UserRepository userRepository) {
this.userRepository = userRepository;
}
/**
* Given any type of exercise, the method returns if the current user is at least TA for the course the exercise belongs to. If exercise is not present, it will return false,
* because the optional will be empty, and therefore `isPresent()` will return false This is due how `filter` works: If a value is present, apply the provided mapping function
* to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
* https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#filter-java.util.function.Predicate
*
* @param exercise the exercise that needs to be checked
* @param <T> The type of the concrete exercise, because Exercise is an abstract class
* @return true if the user is at least a teaching assistant (also if the user is instructor or admin) in the course of the given exercise
*/
public <T extends Exercise> boolean isAtLeastTeachingAssistantForExercise(Optional<T> exercise) {
return exercise.filter(this::isAtLeastTeachingAssistantForExercise).isPresent();
}
/**
* Checks if the currently logged in user is at least a teaching assistant in the course of the given exercise.
* The course is identified from either {@link Exercise#course(Course)} or {@link Exam#getCourse()}
*
* @param exercise belongs to a course that will be checked for permission rights
* @return true if the currently logged in user is at least a teaching assistant (also if the user is instructor or admin), false otherwise
*/
public boolean isAtLeastTeachingAssistantForExercise(Exercise exercise) {
return isAtLeastTeachingAssistantInCourse(exercise.getCourseViaExerciseGroupOrCourseMember(), null);
}
/**
* checks if the passed user is at least a teaching assistant in the course of the given exercise
* The course is identified from {@link Exercise#getCourseViaExerciseGroupOrCourseMember()}
*
* @param exercise the exercise that needs to be checked
* @param user the user whose permissions should be checked
* @return true if the passed user is at least a teaching assistant (also if the user is instructor or admin), false otherwise
*/
public boolean isAtLeastTeachingAssistantForExercise(Exercise exercise, User user) {
if (user == null || user.getGroups() == null) {
// only retrieve the user and the groups if the user is null or the groups are missing (to save performance)
user = userRepository.getUserWithGroupsAndAuthorities();
}
return isAtLeastTeachingAssistantInCourse(exercise.getCourseViaExerciseGroupOrCourseMember(), user);
}
/**
* checks if the currently logged in user is at least a student in the course of the given exercise.
*
* @param exercise belongs to a course that will be checked for permission rights
* @return true if the currently logged in user is at least a student (also if the user is teaching assistant, instructor or admin), false otherwise
*/
public boolean isAtLeastStudentForExercise(Exercise exercise) {
return isAtLeastStudentForExercise(exercise, null);
}
/**
* checks if the currently logged in user is at least a student in the course of the given exercise.
*
* @param exercise belongs to a course that will be checked for permission rights
@param user the user whose permissions should be checked
* @return true if the currently logged in user is at least a student (also if the user is teaching assistant, instructor or admin), false otherwise
*/
public boolean isAtLeastStudentForExercise(Exercise exercise, User user) {
if (user == null || user.getGroups() == null) {
// only retrieve the user and the groups if the user is null or the groups are missing (to save performance)
user = userRepository.getUserWithGroupsAndAuthorities();
}
return isStudentInCourse(exercise.getCourseViaExerciseGroupOrCourseMember(), user) || isAtLeastTeachingAssistantForExercise(exercise, user);
}
/**
* checks if the passed user is at least a teaching assistant in the given course
*
* @param course the course that needs to be checked
* @param user the user whose permissions should be checked
* @return true if the passed user is at least a teaching assistant in the course (also if the user is instructor or admin), false otherwise
*/
public boolean isAtLeastTeachingAssistantInCourse(Course course, User user) {
if (user == null || user.getGroups() == null) {
// only retrieve the user and the groups if the user is null or the groups are missing (to save performance)
user = userRepository.getUserWithGroupsAndAuthorities();
}
return user.getGroups().contains(course.getInstructorGroupName()) || user.getGroups().contains(course.getTeachingAssistantGroupName()) || isAdmin(user);
}
/**
* checks if the passed user is at least a teaching assistant in the given course
*
* @param course the course that needs to be checked
* @param user the user whose permissions should be checked
* @return true if the passed user is at least a teaching assistant in the course (also if the user is instructor or admin), false otherwise
*/
public boolean isAtLeastStudentInCourse(Course course, User user) {
if (user == null || user.getGroups() == null) {
// only retrieve the user and the groups if the user is null or the groups are missing (to save performance)
user = userRepository.getUserWithGroupsAndAuthorities();
}
return user.getGroups().contains(course.getInstructorGroupName()) || user.getGroups().contains(course.getTeachingAssistantGroupName())
|| user.getGroups().contains(course.getStudentGroupName()) || isAdmin(user);
}
/**
* Checks if the currently logged in user is at least an instructor in the course of the given exercise.
* The course is identified from either exercise.course or exercise.exerciseGroup.exam.course
*
* @param exercise belongs to a course that will be checked for permission rights
* @param user the user whose permissions should be checked
* @return true if the currently logged in user is at least an instructor (or admin), false otherwise
*/
public boolean isAtLeastInstructorForExercise(Exercise exercise, User user) {
return isAtLeastInstructorInCourse(exercise.getCourseViaExerciseGroupOrCourseMember(), user);
}
/**
* checks if the currently logged in user is at least an instructor in the course of the given exercise.
*
* @param exercise belongs to a course that will be checked for permission rights
* @return true if the currently logged in user is at least an instructor (or admin), false otherwise
*/
public boolean isAtLeastInstructorForExercise(Exercise exercise) {
return isAtLeastInstructorForExercise(exercise, null);
}
/**
* checks if the passed user is at least instructor in the given course
*
* @param course the course that needs to be checked
* @param user the user whose permissions should be checked
* @return true if the passed user is at least instructor in the course (also if the user is admin), false otherwise
*/
public boolean isAtLeastInstructorInCourse(Course course, User user) {
if (user == null || user.getGroups() == null) {
// only retrieve the user and the groups if the user is null or the groups are missing (to save performance)
user = userRepository.getUserWithGroupsAndAuthorities();
}
return user.getGroups().contains(course.getInstructorGroupName()) || isAdmin(user);
}
/**
* checks if the passed user is instructor in the given course
*
* @param course the course that needs to be checked
* @param user the user whose permissions should be checked
* @return true, if user is instructor of this course, otherwise false
*/
public boolean isInstructorInCourse(Course course, User user) {
if (user == null || user.getGroups() == null) {
// only retrieve the user and the groups if the user is null or the groups are missing (to save performance)
user = userRepository.getUserWithGroupsAndAuthorities();
}
return user.getGroups().contains(course.getInstructorGroupName());
}
/**
* checks if the currently logged in user is teaching assistant of this course
*
* @param course the course that needs to be checked
* @param user the user whose permissions should be checked
* @return true, if user is teaching assistant of this course, otherwise false
*/
public boolean isTeachingAssistantInCourse(Course course, User user) {
if (user == null || user.getGroups() == null) {
// only retrieve the user and the groups if the user is null or the groups are missing (to save performance)
user = userRepository.getUserWithGroupsAndAuthorities();
}
return user.getGroups().contains(course.getTeachingAssistantGroupName());
}
/**
* checks if the currently logged in user is only a student of this course. This means the user is NOT a tutor, NOT an instructor and NOT an ADMIN
*
* @param course the course that needs to be checked
* @param user the user whose permissions should be checked
* @return true, if user is only student of this course, otherwise false
*/
public boolean isOnlyStudentInCourse(Course course, User user) {
if (user == null || user.getGroups() == null) {
// only retrieve the user and the groups if the user is null or the groups are missing (to save performance)
user = userRepository.getUserWithGroupsAndAuthorities();
}
return user.getGroups().contains(course.getStudentGroupName()) && !isAtLeastTeachingAssistantInCourse(course, user);
}
/**
* checks if the currently logged in user is student in the given course
*
* @param course the course that needs to be checked
* @param user the user whose permissions should be checked
* @return true, if user is student of this course, otherwise false
*/
public boolean isStudentInCourse(Course course, User user) {
if (user == null || user.getGroups() == null) {
// only retrieve the user and the groups if the user is null or the groups are missing (to save performance)
user = userRepository.getUserWithGroupsAndAuthorities();
}
return user.getGroups().contains(course.getStudentGroupName());
}
/**
* checks if the currently logged in user is owner of the given participation
*
* @param participation the participation that needs to be checked
* @return true, if user is student is owner of this participation, otherwise false
*/
public boolean isOwnerOfParticipation(StudentParticipation participation) {
if (participation.getParticipant() == null) {
return false;
}
else {
return participation.isOwnedBy(SecurityUtils.getCurrentUserLogin().get());
}
}
/**
* checks if the currently logged in user is owner of the given participation
*
* @param participation the participation that needs to be checked
* @param user the user whose permissions should be checked
* @return true, if user is student is owner of this participation, otherwise false
*/
public boolean isOwnerOfParticipation(StudentParticipation participation, User user) {
if (user == null || user.getGroups() == null) {
// only retrieve the user and the groups if the user is null or the groups are missing (to save performance)
user = userRepository.getUserWithGroupsAndAuthorities();
}
if (participation.getParticipant() == null) {
return false;
}
else {
return participation.isOwnedBy(user);
}
}
/**
* checks if the currently logged in user is owner of the given team
*
* @param team the team that needs to be checked
* @param user the user whose permissions should be checked
* @return true if user is owner of this team, otherwise false
*/
public boolean isOwnerOfTeam(Team team, User user) {
return user.equals(team.getOwner());
}
/**
* checks if the currently logged in user is student of the given team
*
* @param course the course to which the team belongs to (acts as scope for team short name)
* @param teamShortName the short name of the team that needs to be checked
* @param user the user whose permissions should be checked
* @return true, if user is student is owner of this team, otherwise false
*/
public boolean isStudentInTeam(Course course, String teamShortName, User user) {
return userRepository.findAllInTeam(course.getId(), teamShortName).contains(user);
}
/**
* Method used to check whether the user of the websocket message is owner of this participation
*
* @param participation participation to check the rights for
* @param principal a representation of the currently logged in user
* @return true, if user is student is owner of this participation, otherwise false
*/
public boolean isOwnerOfParticipation(StudentParticipation participation, Principal principal) {
return participation.getParticipant() != null && participation.isOwnedBy(principal.getName());
}
/**
* checks if the passed user is allowed to see the given exercise, i.e. if the passed user is at least a student in the course
*
* @param exercise the exercise that needs to be checked
* @param user the user whose permissions should be checked
* @return true, if user is allowed to see this exercise, otherwise false
*/
public boolean isAllowedToSeeExercise(Exercise exercise, User user) {
if (user == null || user.getGroups() == null) {
user = userRepository.getUserWithGroupsAndAuthorities();
}
if (isAdmin(user)) {
return true;
}
Course course = exercise.getCourseViaExerciseGroupOrCourseMember();
return isInstructorInCourse(course, user) || isTeachingAssistantInCourse(course, user) || (isStudentInCourse(course, user) && exercise.isVisibleToStudents());
}
/**
* Determines if a user is allowed to see a lecture unit
*
* @param lectureUnit the lectureUnit for which to check permission
* @param user the user for which to check permission
* @return true if the user is allowed, false otherwise
*/
public boolean isAllowedToSeeLectureUnit(LectureUnit lectureUnit, User user) {
if (user == null || user.getGroups() == null) {
user = userRepository.getUserWithGroupsAndAuthorities();
}
if (isAdmin(user)) {
return true;
}
Course course = lectureUnit.getLecture().getCourse();
return isInstructorInCourse(course, user) || isTeachingAssistantInCourse(course, user) || (isStudentInCourse(course, user) && lectureUnit.isVisibleToStudents());
}
/**
* NOTE: this method should only be used in a REST Call context, when the SecurityContext is correctly setup.
* Preferably use the method isAdmin(user) below
*
* Checks if the currently logged in user is an admin user
*
* @return true, if user is admin, otherwise false
*/
public boolean isAdmin() {
return SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN);
}
/**
* checks if the currently logged in user is an admin user
* @param user the user with authorities. Both cannot be null
*
* @return true, if user is admin, otherwise false
*/
public boolean isAdmin(@NotNull User user) {
return user.getAuthorities().contains(Authority.ADMIN_AUTHORITY);
}
/**
* Checks if the currently logged in user is allowed to retrieve the given result.
* The user is allowed to retrieve the result if (s)he is an instructor of the course, or (s)he is at least a student in the corresponding course, the
* submission is his/her submission, the assessment due date of the corresponding exercise is in the past (or not set) and the result is finished.
*
* @param exercise the corresponding exercise
* @param participation the participation the result belongs to
* @param result the result that should be sent to the client
* @return true if the user is allowed to retrieve the given result, false otherwise
*/
public boolean isUserAllowedToGetResult(Exercise exercise, StudentParticipation participation, Result result) {
return isAtLeastStudentForExercise(exercise) && (isOwnerOfParticipation(participation) || isAtLeastInstructorForExercise(exercise))
&& (exercise.getAssessmentDueDate() == null || exercise.getAssessmentDueDate().isBefore(ZonedDateTime.now())) && result.getAssessor() != null
&& result.getCompletionDate() != null;
}
/**
* Checks if the user is allowed to see the exam result. Returns true if
*
* - the current user is at least teaching assistant in the course
* - OR if the exercise is not part of an exam
* - OR if the exam has not ended
* - OR if the exam has already ended and the results were published
*
* @param exercise - Exercise that the result is requested for
* @param user - User that requests the result
* @return true if user is allowed to see the result, false otherwise
*/
public boolean isAllowedToGetExamResult(Exercise exercise, User user) {
return this.isAtLeastTeachingAssistantInCourse(exercise.getCourseViaExerciseGroupOrCourseMember(), user)
|| (exercise.isCourseExercise() || (exercise.isExamExercise() && exercise.getExerciseGroup().getExam().getEndDate().isAfter(ZonedDateTime.now()))
|| exercise.getExerciseGroup().getExam().resultsPublished());
}
/**
* Check if a participation can be accessed with the current user.
*
* @param participation to access
* @return can user access participation
*/
public boolean canAccessParticipation(StudentParticipation participation) {
return Optional.ofNullable(participation).isPresent() && userHasPermissionsToAccessParticipation(participation);
}
/**
* Check if a user has permissions to access a certain participation. This includes not only the owner of the participation but also the TAs and instructors of the course.
*
* @param participation to access
* @return does user has permissions to access participation
*/
private boolean userHasPermissionsToAccessParticipation(StudentParticipation participation) {
if (isOwnerOfParticipation(participation)) {
return true;
}
// if the user is not the owner of the participation, the user can only see it in case he is
// a teaching assistant or an instructor of the course, or in case he is admin
User user = userRepository.getUserWithGroupsAndAuthorities();
Course course = participation.getExercise().getCourseViaExerciseGroupOrCourseMember();
return isAtLeastTeachingAssistantInCourse(course, user);
}
}
| 49.840964 | 179 | 0.696867 |
a8c3d3fe52caf4498db8d2d75699be4c12665726 | 153 | package io.vertx.starter.database;
/**
* Created by wujun on 2017/7/19.
*/
public enum ErrorCodes {
NO_ACTION_SPECIFIED,
BAD_ACTION,
DB_ERROR
}
| 13.909091 | 34 | 0.712418 |
c994e3f4c6d8b6506bc60b2123e4182a40626b70 | 4,494 | package com.montefiore.gaulthiergain.adhoclibrary.datalink.service;
import android.annotation.SuppressLint;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import com.montefiore.gaulthiergain.adhoclibrary.datalink.util.MessageAdHoc;
/**
* <p>This class defines the constants for connection states and message handling and aims to serve
* as a common interface for service {@link ServiceClient} and {@link ServiceServer} classes. </p>
*
* @author Gaulthier Gain
* @version 1.0
*/
public abstract class Service {
protected final String TAG = "[AdHoc][Service]";
// Constant for type
public static final byte WIFI = 0;
public static final byte BLUETOOTH = 1;
// Constants that indicate the current connection state
public static final byte STATE_NONE = 0; // no connection
public static final byte STATE_LISTENING = 1; // listening for incoming connections
public static final byte STATE_CONNECTING = 2; // initiating an outgoing connection
public static final byte STATE_CONNECTED = 3; // connected to a remote device
// Constants for message handling
public static final byte MESSAGE_READ = 5; // message received
// Constants for connection
public static final byte CONNECTION_ABORTED = 6; // connection aborted
public static final byte CONNECTION_PERFORMED = 7; // connection performed
public static final byte CONNECTION_FAILED = 8; // connection failed
public static final byte LOG_EXCEPTION = 9; // log exception
public static final byte MESSAGE_EXCEPTION = 10; // catch message exception
public static final int NETWORK_UNREACHABLE = 11;
protected int state;
protected final boolean v;
protected final boolean json;
private final ServiceMessageListener serviceMessageListener;
/**
* Constructor
*
* @param verbose a boolean value to set the debug/verbose mode.
* @param json a boolean value to use json or bytes in network transfer.
* @param serviceMessageListener a serviceMessageListener object which serves as callback functions.
*/
Service(boolean verbose, boolean json, ServiceMessageListener serviceMessageListener) {
this.state = 0;
this.v = verbose;
this.json = json;
this.serviceMessageListener = serviceMessageListener;
}
/**
* Method allowing to defines the state of a connection.
*
* @param state an integer values which defines the state of a connection.
*/
protected void setState(int state) {
if (v) Log.d(TAG, "setState() " + this.state + " -> " + state);
this.state = state;
}
/**
* Method allowing to get the state of a connection.
*
* @return an integer values which defines the state of a connection.
*/
public int getState() {
return state;
}
@SuppressLint("HandlerLeak")
protected final android.os.Handler handler = new android.os.Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
if (v) Log.d(TAG, "MESSAGE_READ");
serviceMessageListener.onMessageReceived((MessageAdHoc) msg.obj);
break;
case CONNECTION_ABORTED:
if (v) Log.d(TAG, "CONNECTION_ABORTED");
serviceMessageListener.onConnectionClosed((String) msg.obj);
break;
case CONNECTION_PERFORMED:
if (v) Log.d(TAG, "CONNECTION_PERFORMED");
serviceMessageListener.onConnection((String) msg.obj);
break;
case CONNECTION_FAILED:
if (v) Log.d(TAG, "CONNECTION_FAILED");
serviceMessageListener.onConnectionFailed((Exception) msg.obj);
break;
case MESSAGE_EXCEPTION:
if (v) Log.e(TAG, "MESSAGE_EXCEPTION");
serviceMessageListener.onMsgException((Exception) msg.obj);
break;
case LOG_EXCEPTION:
if (v) Log.w(TAG, "LOG_EXCEPTION: " + ((Exception) msg.obj).getMessage());
break;
}
}
};
}
| 39.078261 | 104 | 0.6166 |
bf4d222c393474bea381e30dbdb620d12e4b01fd | 12,334 |
import java.util.*;
import java.nio.*;
import java.nio.channels.*;
/**
* Description of the Class
*
*@author Paul Nguyen
*@created April 24, 2003
*/
public class Volume {
/**
* Description of the Field
*
*@since
*/
public final static int VOL_ID_SIZE = 4;// 4 bytes
/**
* Description of the Field
*
*@since
*/
public final static int PAGE_ID_SIZE = 2;// 2 bytes
/**
* Description of the Field
*
*@since
*/
public final static int BLOCK_ID_SIZE = 2;// 2 bytes
/**
* Description of the Field
*
*@since
*/
public final static int RECORD_ID_SIZE = 8;// 8 bytes. (volid+pageid+blocknum)
/**
* Description of the Field
*
*@since
*/
public final static int RECORD_GUID_SIZE = 32;// 32 bytes guid (logical record ids)
/**
* Description of the Field
*
*@since
*/
public final static int TRANSLATION_TABLE_ENTRIES = 100000;// 100K Entries @ 40 bytes each
/**
* Description of the Field
*
*@since
*/
public final static int MAX_TRANSLATION_TABLE_SIZE_PER_PAGE = TRANSLATION_TABLE_ENTRIES * 40;// 4 bytes - free page #
private final static int DEFAULT_EXTENT_SIZE = 10;// reserve 10 pages
private final static int DEFAULT_MAX_EXTENTS = 20;// max volume size
private final static boolean DEBUG = true;// 100K Entries @ 40 bytes each
private int vol_hdr_size;// 4 bytes - # of bytes for header
private int vol_id;// 4 bytes - physical id of volume
private int vol_page_size;// 4 bytes - # of bytes in a page
private int vol_block_size;// 4 bytes - # of bytes in a block
private int vol_num_pages;// 4 bytes - # of pages allocated in volume
private int vol_extent_size;// 4 bytes - # of pages reserved in volume
private int vol_max_extents;// 4 bytes - max # of pages in volume
private int vol_free_page; // 4 bytes - current free page counter
public int getVolumeId() { return this.vol_id ; }
/**
*@since
*@supplierCardinality 1
*/
private Device vol_device;
/**
*@since
*@link dependency
*/
/*
* #Page lnkPage;
*/
private HashMap vol_pages;
/**
* Constructor for the Volume object
*
*@param filename Description of Parameter
*@param id Description of Parameter
*@since
*/
public Volume(int id, String filename) {
this(id, filename, DEFAULT_EXTENT_SIZE, DEFAULT_MAX_EXTENTS);
}
/**
* Constructor for the Volume object
*
*@param id Description of Parameter
*@param filename Description of Parameter
*@param reserve Description of Parameter
*@param max Description of Parameter
*@since
*/
public Volume(int id, String filename, int reserve, int max) {
vol_device = new Device(filename);
try {
if (vol_device.mount()) {
// New Volume. Create Header Block.
if (DEBUG) {
System.out.println("Creating Header Block...");
}
vol_hdr_size = Device.BLOCK_SIZE;// one block
vol_id = id;
vol_page_size = Device.PAGE_SIZE;// 512 blocks per page
vol_block_size = Device.BLOCK_SIZE;// 8K blocks
vol_num_pages = 0;// start with no pages
vol_extent_size = reserve;// reserve pages in volume
vol_max_extents = max;// max growth limit
vol_free_page = 0;// page 0 free to start
reservePages(vol_extent_size);
allocateNewPage();// allocate first page (page allocation includes implicit vol hdr flush)
if (DEBUG) {
printVolumeHeader();
}
} else {
// Read In Header Block
ByteBuffer buffer = vol_device.getBlock(0);
this.vol_hdr_size = buffer.getInt();
this.vol_id = buffer.getInt();
this.vol_page_size = buffer.getInt();
this.vol_block_size = buffer.getInt();
this.vol_num_pages = buffer.getInt();
this.vol_extent_size = buffer.getInt();
this.vol_max_extents = buffer.getInt();
this.vol_free_page = buffer.getInt() ;
if (DEBUG) {
printVolumeHeader();
Page page0 = getPage(0);
page0.dumpHeader();
}
}
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
/**
* Description of the Method
*
*@param args Description of Parameter
*@since
*/
public static void main(String args[]) {
Volume m_volume = new Volume(0, "master.db", 2, 10);
Page m_page = m_volume.getPage(0);
ByteBuffer rec_id = ByteBuffer.allocate(8);
rec_id.putInt(0);
rec_id.putShort((short) 0);
rec_id.putShort((short) 1);
byte[] rec_id_bytes = rec_id.array();
ByteBuffer trans_table = m_page.getRecordByteBuffer(rec_id_bytes);
if (trans_table == null) {
System.out.println("Creating Translation Table...");
byte[] trans_table_array = new byte[MAX_TRANSLATION_TABLE_SIZE_PER_PAGE];
try {
m_page.addRecord(trans_table_array);
} catch (Exception e) {}
}
/*
* ITERATOR TESTING
* Volume master_volume = new Volume(0,"master.db",2,10);
* Page m_page = master_volume.getPage(0) ;
* m_page.addRecord( "THIS IS A TEST #1".getBytes() ) ;
* m_page.addRecord( "THIS IS A TEST #2".getBytes() ) ;
* m_page.addRecord( "THIS IS A TEST #3".getBytes() ) ;
* m_page.addRecord( "THIS IS A TEST #4".getBytes() ) ;
* m_page.addRecord( "THIS IS A TEST #5".getBytes() ) ;
* RecordSetIterator m_records = m_page.getRecordSetIterator() ;
* m_records.reset() ;
* while( m_records.hasMoreRecords()) {
* byte[] data = m_records.getNextRecord() ;
* System.out.println( "ITERATOR GOT RECORD: " + Util.toHexString( data ) ) ;
* }
*/
/*
* BASIC OPERATIONS TESTING
* Page freepage = master_volume.getFreePage() ;
* byte[] recid = freepage.addRecord( "THIS IS A TEST".getBytes() ) ;
* / recid format: volid(4 bytes)-pageid(2 bytes)-blockid(2 bytes)
* ByteBuffer recid_buf = ByteBuffer.wrap(recid);
* int rec_vol_id = recid_buf.getInt() ;
* int rec_page_id = (int)recid_buf.getShort();
* Page datapage = master_volume.getPage( rec_page_id ) ;
* byte[] data = datapage.getRecord( recid ) ;
* byte[] recid2 = datapage.updateRecord( recid, "THIS IS A TEST #2".getBytes() ) ;
* byte[] data2 = datapage.getRecord( recid2 ) ;
* datapage.deleteRecord( recid2 ) ;
*/
}
/**
* Gets the page attribute of the Volume object
*
*@param page_number Description of Parameter
*@return The page value
*@since
*/
public ByteBuffer getPageBuffer(int page_number) {
return vol_device.getPage(page_number);
// todo, make this read-only
}
public ByteBuffer getPageBuffer(int page_number, int page_count ) {
return vol_device.getLargePages( page_number, page_count ) ;
}
/**
* Gets the blockBuffer attribute of the Volume object
*
*@param block_number Description of Parameter
*@return The blockBuffer value
*@since
*/
public ByteBuffer getBlockBuffer(int block_number) {
return vol_device.getBlock(block_number);
// todo, make this read-only
}
/**
* Gets the page attribute of the Volume object
*
*@param page_number Description of Parameter
*@return The page value
*@since
*/
public Page getPage(int page_number) {
return new Page(vol_device.getPage(page_number), this);
}
/**
* Gets the freePage attribute of the Volume object
*
*@return The freePage value
*@since
*/
public Page getFreePage() {
return new Page(vol_device.getPage(vol_free_page), this);
}
/**
* Gets the freePage attribute of the Volume object
*
*@param record_length Description of Parameter
*@return The freePage value
*@since
*/
public Page getFreePage(long record_length) {
return new Page(vol_device.getPage(vol_free_page), this);
// todo, using record_length, may have to use large record strategy
// note: large record is where record size > page size
}
/**
* Description of the Method
*
*@return Description of the Returned Value
*@since
*/
public Page newFreePage() throws NoFreePageException {
Page freepg = null ;
try {
if (DEBUG)
printVolumeHeader() ;
// out of space
if (vol_num_pages == vol_max_extents)
throw new NoFreePageException() ;
// check for extent size
if ( vol_num_pages == vol_extent_size )
extendVolume() ;
// Allocate Page
vol_num_pages++;
// Advance Free Page Counter.
vol_free_page++;
// Vol Header
flushVolumeHeader();
// Page Header
ByteBuffer pagebuffer = vol_device.getPage(vol_num_pages - 1);
int page_hdrsize = Device.BLOCK_SIZE;
// one block
int page_number = vol_num_pages - 1;
// page num
int page_num_blocks = Device.PAGE_SIZE;
// 512 blocks
pagebuffer.clear();
pagebuffer.putInt(page_hdrsize);
pagebuffer.putInt(page_number);
pagebuffer.putInt(page_num_blocks);
pagebuffer.putInt(-1);// reserved
pagebuffer.putInt(-1);// reserved
// newly allocated page
freepg = new Page(vol_device.getPage(vol_free_page), this);
if (DEBUG)
printVolumeHeader() ;
} catch (Exception e) {
System.out.println(e);
}
finally {
return freepg ;
}
}
public void close() {
if (DEBUG)
printVolumeHeader() ;
vol_device.umount() ;
}
/**
*@since
*@link dependency
*/
/*
* #Page lnkPage;
*/
private void printVolumeHeader() {
System.out.println("===== START VOLUME HEADER =====");
System.out.println("Header Size: " + vol_hdr_size + " bytes ");
System.out.println("Volume ID: " + vol_id);
System.out.println("Page Size: " + vol_page_size + " bytes ");
System.out.println("Block Size: " + vol_block_size + " bytes ");
System.out.println("Num Pages: " + vol_num_pages + " pages allocated ");
System.out.println("Extent Size: " + vol_extent_size + " pages reserved ");
System.out.println("Max Extents: " + vol_max_extents + " max pages ");
System.out.println("Free Page: " + vol_free_page);
System.out.println("===== END VOLUME HEADER =====");
}
/**
* Description of the Method
*
*@since
*/
private void flushVolumeHeader() {
try {
// Vol Header
ByteBuffer buffer = vol_device.getBlock(0);
buffer.clear();
buffer.putInt(vol_hdr_size);
buffer.putInt(vol_id);
buffer.putInt(vol_page_size);
buffer.putInt(vol_block_size);
buffer.putInt(vol_num_pages);
buffer.putInt(vol_extent_size);
buffer.putInt(vol_max_extents);
buffer.putInt(vol_free_page);
} catch (Exception e) {
System.out.println(e);
}
}
/**
* Description of the Method
*
*@since
*/
private void allocateNewPage() {
try {
// Allocate Page
vol_num_pages++;
// Vol Header
flushVolumeHeader();
// Page Header
ByteBuffer pagebuffer = vol_device.getPage(vol_num_pages - 1);
int page_hdrsize = Device.BLOCK_SIZE;
// one block
int page_number = vol_num_pages - 1;
// page num
int page_num_blocks = Device.PAGE_SIZE;
// 512 blocks
pagebuffer.clear();
pagebuffer.putInt(page_hdrsize);
pagebuffer.putInt(page_number);
pagebuffer.putInt(page_num_blocks);
pagebuffer.putInt(-1);// reserved
pagebuffer.putInt(-1);// reserved
} catch (Exception e) {
System.out.println(e);
}
}
/**
* Description of the Method
*
*@param num_pages Description of Parameter
*@since
*/
private void reservePages(int num_pages) {
try {
vol_device.getPage(num_pages - 1);// expands device if needed
} catch (Exception e) {
System.out.println(e);
}
}
/**
* Description of the Method
*
*@since
*/
private void extendVolume() {
try {
vol_device.getPage(vol_max_extents - 1);
this.vol_extent_size = this.vol_max_extents ;
} catch (Exception e) {
System.out.println(e);
}
}
}
| 26.754881 | 119 | 0.62048 |
aefe6aa82ba9ca45ac5137085a37beed95e6b273 | 2,804 | package com.meandmyphone.chupacabraremote.ui.listeners;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import com.meandmyphone.chupacabraremote.network.ServerConnectionInfo;
import com.meandmyphone.chupacabraremote.providers.impl.ClientContext;
import com.meandmyphone.chupacabraremote.service.api.VolumeService;
import com.meandmyphone.chupacabraremote.ui.views.ConfirmDialog;
import com.meandmyphone.chupacabraremote.ui.views.VolumeControlDialog;
import com.meandmyphone.shared.action.ActionType;
import java.util.Optional;
public class VolumeChangeListener implements OnSeekBarChangeListener {
private final VolumeService volumeService;
private final VolumeControlDialog volumeControlDialog;
public VolumeChangeListener(VolumeService volumeService, VolumeControlDialog volumeControlDialog) {
this.volumeService = volumeService;
this.volumeControlDialog = volumeControlDialog;
}
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean fromUser) {
volumeService.changeVolume(i);
if (fromUser) {
volumeControlDialog.updateCurrentVolumeState(i);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Optional<ServerConnectionInfo> connectedServerInfo = ClientContext.getInstance().getLocatedServerDetails().stream()
.filter(serverConnectionInfo -> serverConnectionInfo.getHostAddress().equals(
ClientContext.getInstance().getConnection().getValue().getDetails().getHostAddress()))
.findFirst();
if (connectedServerInfo.isPresent() && connectedServerInfo.get().getInterpolationData() != null) {
ConfirmDialog.showConfirmDialog(
seekBar.getContext(),
"Confirmation",
"Volume is currently interpolating, setting volume now will stop interpolation, are you sure?",
(dialog, which) -> {
ClientContext.getInstance().getActionSenderService().sendAction(
ActionType.INTERPOLATE_VOLUME,
ClientContext.getInstance().getPayloadFactory().createCancelInterpolationPayload());
connectedServerInfo.get().setInterpolationData(null);
volumeService.startVolumeChange(seekBar.getProgress());
},
(dialog, which) -> {
// unused
});
} else {
volumeService.startVolumeChange(seekBar.getProgress());
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
volumeService.finishVolumeChange(seekBar.getProgress());
}
}
| 41.850746 | 123 | 0.676534 |
b95dd142209c28423790c2a06e89fb8f3c8544d2 | 720 | package com.outbrain.selenium.extjs.core.locators;
import com.thoughtworks.selenium.Selenium;
/**
* @author Asaf Levy
* @version $Revision: 1.0
*/
public class ComponentIdLocator extends ComponentLocator {
/**
* Field componentId.
*/
private String componentId = null;
/**
* Constructor for ComponentIdLocator.
* @param selenium Selenium
* @param componentId String
*/
public ComponentIdLocator(final Selenium selenium, final String componentId) {
super(selenium);
this.componentId = componentId;
}
/**
* Method getComponentId.
* @return String */
@Override
public final String getComponentId() {
return componentId;
}
}
| 20.571429 | 81 | 0.661111 |
14477ef1f6d93a2470a5d2ca81071d41b4be2bcb | 5,439 | /*
Copyright (C) 2013-2021 Expedia 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.hotels.styx.client.netty.connectionpool;
import com.hotels.styx.api.extension.Origin;
import com.hotels.styx.api.extension.service.ConnectionPoolSettings;
import com.hotels.styx.client.Connection;
import com.hotels.styx.client.connectionpool.ConnectionPool;
import com.hotels.styx.client.connectionpool.stubs.StubConnectionFactory;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import java.util.Objects;
import static com.hotels.styx.api.extension.service.ConnectionPoolSettings.defaultConnectionPoolSettings;
import static java.util.Objects.hash;
public class StubConnectionPool implements ConnectionPool, Comparable<ConnectionPool> {
private Connection connection;
private final Origin origin;
private int busyConnectionCount = 0;
private int maxConnectionsPerHost = 1;
private int availableConnections = 0;
private final ConnectionPoolSettings settings;
private int pendingConnectionCount;
public StubConnectionPool(Origin origin) {
this(new StubConnectionFactory.StubConnection(origin));
}
public StubConnectionPool(Connection connection) {
this.connection = connection;
this.origin = connection.getOrigin();
this.settings = defaultConnectionPoolSettings();
}
@Override
public int compareTo(ConnectionPool other) {
return this.connection.getOrigin().hostAndPortString().compareTo(other.getOrigin().hostAndPortString());
}
@Override
public Origin getOrigin() {
return this.origin;
}
@Override
public Publisher<Connection> borrowConnection() {
return Flux.just(connection);
}
@Override
public boolean returnConnection(Connection connection) {
return false;
}
@Override
public boolean closeConnection(Connection connection) {
return false;
}
@Override
public boolean isExhausted() {
return false;
}
@Override
public Stats stats() {
return new Stats() {
@Override
public int pendingConnectionCount() {
return pendingConnectionCount;
}
@Override
public int availableConnectionCount() {
return availableConnections;
}
@Override
public int busyConnectionCount() {
return busyConnectionCount;
}
@Override
public int connectionAttempts() {
return 0;
}
@Override
public int connectionFailures() {
return 0;
}
@Override
public int closedConnections() {
return 0;
}
@Override
public int terminatedConnections() {
return 0;
}
@Override
public int connectionsInEstablishment() {
return 0;
}
};
}
@Override
public ConnectionPoolSettings settings() {
return settings;
}
public StubConnectionPool withBusyConnections(int busyConnectionCount) {
this.busyConnectionCount = busyConnectionCount;
return this;
}
public ConnectionPool withPendingConnections(int pendingConnectionCount) {
this.pendingConnectionCount = pendingConnectionCount;
return this;
}
public StubConnectionPool withMaxConnectionsPerHost(int maxConnectionsPerHost) {
this.maxConnectionsPerHost = maxConnectionsPerHost;
return this;
}
public StubConnectionPool withAvailableConnections(int availableConnections) {
this.availableConnections = availableConnections;
return this;
}
@Override
public int hashCode() {
return hash(origin, busyConnectionCount, pendingConnectionCount);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
StubConnectionPool other = (StubConnectionPool) obj;
return Objects.equals(this.origin, other.origin) &&
Objects.equals(this.busyConnectionCount, other.busyConnectionCount) &&
Objects.equals(this.pendingConnectionCount, other.pendingConnectionCount);
}
@Override
public String toString() {
return new StringBuilder(96)
.append(this.getClass().getSimpleName())
.append("{origin=")
.append(origin)
.append(", busyConnections=")
.append(busyConnectionCount)
.append(", pendingConnections=")
.append(pendingConnectionCount)
.append('}')
.toString();
}
}
| 29.559783 | 112 | 0.64442 |
6da832c54fc759dee185b1f9c080f7de8628c0cd | 496 | package com.bruno.caetano.dev.shoppingcart.entity.response.in;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.math.BigInteger;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class GetItemResponse {
private String id;
private String name;
private String description;
private String market;
private BigDecimal price;
private BigInteger stock;
private String status;
}
| 19.076923 | 62 | 0.816532 |
9836a2d6a96bf7971d2fdc79fbc581229dc04a4f | 8,646 | /*
* Copyright 2017 - 2018 SoftAvail 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.softavail.commsrouter.api.dto.model.skill;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.InvalidTypeIdException;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.hamcrest.collection.IsIterableContainingInOrder;
import static org.junit.Assert.assertThat;
import org.junit.Test;
/**
*
* @author ikrustev
*/
public class AttributeDomainDtoSerializationTest {
private ObjectMapper objectMapper = new ObjectMapper();
private static class TestBean {
public AttributeDomainDto domain;
public TestBean(AttributeDomainDto domain) {
this.domain = domain;
}
public TestBean() {
}
}
@Test(expected = JsonMappingException.class)
public void testInvalidDomainValue() throws IOException, Throwable {
String content = "{"
+ "\"domain\":false"
+ "}";
objectMapper.readValue(content, TestBean.class);
}
@Test
public void testMissingType() throws IOException, Throwable {
String content = "{"
+ "\"domain\":{}"
+ "}";
try {
objectMapper.readValue(content, TestBean.class);
} catch (JsonMappingException ex) {
assertThat(ex.getMessage(), containsString("missing property 'type'"));
}
}
@Test(expected = UnrecognizedPropertyException.class)
public void testUnknownProperty() throws IOException, Throwable {
String content = "{"
+ "\"domain\":{"
+ "\"type\":\"enumeration\","
+ "\"some-unknown-field\":\"a value\""
+ "}"
+ "}";
objectMapper.readValue(content, TestBean.class);
}
@Test(expected = InvalidTypeIdException.class)
public void testBadType() throws IOException, Throwable {
String content = "{"
+ "\"domain\":{"
+ "\"type\":\"bad-type\""
+ "}"
+ "}";
objectMapper.readValue(content, TestBean.class);
}
@Test
public void testEnumeration() throws IOException, Throwable {
String content = "{"
+ "\"domain\":{"
+ "\"type\":\"enumeration\","
+ "\"values\":[\"en\",\"es\"]"
+ "}"
+ "}";
TestBean testBean = objectMapper.readValue(content, TestBean.class);
assertEquals(AttributeType.enumeration, testBean.domain.getType());
assertEquals(
new HashSet<>(Arrays.asList("en", "es")),
((EnumerationAttributeDomainDto)testBean.domain).getValues()
);
}
@Test
public void testEnumerationSerializeDeserialize() throws IOException, Throwable {
EnumerationAttributeDomainDto expected = new EnumerationAttributeDomainDto();
expected.setValues(new HashSet<>(Arrays.asList("some", "enum", "value")));
String asString = objectMapper.writeValueAsString(new TestBean(expected));
TestBean actualTestBean = objectMapper.readValue(asString, TestBean.class);
assertThat(actualTestBean.domain, instanceOf(EnumerationAttributeDomainDto.class));
EnumerationAttributeDomainDto actual = (EnumerationAttributeDomainDto)actualTestBean.domain;
assertEquals(expected.getType(), actual.getType());
assertEquals(expected.getValues(), actual.getValues());
}
@Test
public void testNumber() throws IOException, Throwable {
String content = "{"
+ "\"domain\":{"
+ "\"type\":\"number\","
+ "\"intervals\":[{\"low\":{\"boundary\":13.4},\"high\":{\"boundary\":\"Infinity\"}}]"
+ "}"
+ "}";
TestBean testBean = objectMapper.readValue(content, TestBean.class);
assertEquals(AttributeType.number, testBean.domain.getType());
List<NumberInterval> actual = ((NumberAttributeDomainDto)testBean.domain).getIntervals();
NumberInterval interval = new NumberInterval();
interval.setLow(new NumberIntervalBoundary(13.4));
interval.setHigh(NumberIntervalBoundary.POSITIVE_INFINITY);
List<NumberInterval> expected = Arrays.asList(interval);
assertThat(actual, IsIterableContainingInOrder.contains(expected.toArray()));
}
@Test
public void testNumberSerializeDeserialize() throws IOException, Throwable {
NumberInterval interval1 = new NumberInterval();
interval1.setLow(NumberIntervalBoundary.NEGATIVE_INFINITY);
interval1.setHigh(new NumberIntervalBoundary(10.0, true));
NumberInterval interval2 = new NumberInterval();
interval2.setLow(new NumberIntervalBoundary(13.4, false));
interval2.setHigh(NumberIntervalBoundary.POSITIVE_INFINITY);
NumberAttributeDomainDto expected = new NumberAttributeDomainDto();
expected.setIntervals(Arrays.asList(interval1, interval2));
String asString = objectMapper.writeValueAsString(new TestBean(expected));
TestBean actualTestBean = objectMapper.readValue(asString, TestBean.class);
assertThat(actualTestBean.domain, instanceOf(NumberAttributeDomainDto.class));
NumberAttributeDomainDto actual = (NumberAttributeDomainDto)actualTestBean.domain;
assertEquals(expected.getType(), actual.getType());
assertThat(actual.getIntervals(),
IsIterableContainingInOrder.contains(expected.getIntervals().toArray()));
}
@Test
public void testStringNoRegex() throws IOException, Throwable {
String content = "{"
+ "\"domain\":{"
+ "\"type\":\"string\""
+ "}"
+ "}";
TestBean testBean = objectMapper.readValue(content, TestBean.class);
assertEquals(AttributeType.string, testBean.domain.getType());
assertNull(((StringAttributeDomainDto)testBean.domain).getRegex());
}
@Test
public void testString() throws IOException, Throwable {
String content = "{"
+ "\"domain\":{"
+ "\"type\":\"string\","
+ "\"regex\":\"prefix-.*\""
+ "}"
+ "}";
TestBean testBean = objectMapper.readValue(content, TestBean.class);
assertEquals(AttributeType.string, testBean.domain.getType());
assertEquals("prefix-.*", ((StringAttributeDomainDto)testBean.domain).getRegex());
}
@Test
public void testStringSerializeDeserialize() throws IOException, Throwable {
StringAttributeDomainDto expected = new StringAttributeDomainDto();
expected.setRegex("prefix-.*");
String asString = objectMapper.writeValueAsString(new TestBean(expected));
TestBean actualTestBean = objectMapper.readValue(asString, TestBean.class);
assertThat(actualTestBean.domain, instanceOf(StringAttributeDomainDto.class));
StringAttributeDomainDto actual = (StringAttributeDomainDto)actualTestBean.domain;
assertEquals(expected.getType(), actual.getType());
assertEquals(expected.getRegex(), actual.getRegex());
}
@Test
public void testBool() throws IOException, Throwable {
String content = "{"
+ "\"domain\":{"
+ "\"type\":\"bool\""
+ "}"
+ "}";
TestBean testBean = objectMapper.readValue(content, TestBean.class);
assertEquals(AttributeType.bool, testBean.domain.getType());
}
@Test
public void testBoolSerializeDeserialize() throws IOException, Throwable {
BoolAttributeDomainDto expected = new BoolAttributeDomainDto();
String asString = objectMapper.writeValueAsString(new TestBean(expected));
TestBean actualTestBean = objectMapper.readValue(asString, TestBean.class);
assertThat(actualTestBean.domain, instanceOf(BoolAttributeDomainDto.class));
BoolAttributeDomainDto actual = (BoolAttributeDomainDto)actualTestBean.domain;
assertEquals(expected.getType(), actual.getType());
}
}
| 35.434426 | 102 | 0.685288 |
66e3b4bb83c68fc811d64ed8e5f44aab46ecf730 | 1,078 | package jetbrains.mps.kotlin.behavior;
/*Generated by MPS */
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.scope.Scope;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.internal.collections.runtime.Sequence;
import org.jetbrains.mps.openapi.language.SInterfaceConcept;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
public class ResolvingUtil {
public static boolean isResolvableByScope(String name, SAbstractConcept scopeConcept, SNode context) {
Scope varScope = Scope.getScope(SNodeOperations.getParent(context), context, CONCEPTS.IVariableIdentifier$v2);
return Sequence.fromIterable(varScope.getAvailableElements(name)).isNotEmpty();
}
private static final class CONCEPTS {
/*package*/ static final SInterfaceConcept IVariableIdentifier$v2 = MetaAdapterFactory.getInterfaceConcept(0x6b3888c1980244d8L, 0x8baff8e6c33ed689L, 0x2043bc83114d2ab6L, "jetbrains.mps.kotlin.structure.IVariableIdentifier");
}
}
| 46.869565 | 228 | 0.828386 |
50e7ba7c4b9e1283bd622328b7876e46dd48cc92 | 2,903 | package com.smartmarket.activity.account;
import android.content.Context;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.ViewTarget;
import com.common.app.view.BaseActivity;
import com.smartmarket.R;
import com.smartmarket.activity.LaunchActivity;
import com.smartmarket.fragment.account.LoginFragment;
import com.smartmarket.fragment.account.RegisterFragment;
import butterknife.BindView;
/**
* @author wulinpeng
* @datetime: 18/1/31 下午4:43
* @description: 用户界面,负责登陆注册
*/
public class AccountActivity extends BaseActivity {
private Fragment mCurrentFragment;
private LoginFragment mLoginFragment;
private RegisterFragment mRegisterFragment;
@BindView(R.id.im_bg)
public ImageView mBg;
public static void show(Context context) {
context.startActivity(new Intent(context, AccountActivity.class));
}
@Override
protected int getLayoutId() {
return R.layout.activity_account;
}
@Override
protected void initView() {
// super.initView();
mBg = (ImageView) findViewById(R.id.im_bg);
mCurrentFragment = mLoginFragment = new LoginFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.container, mCurrentFragment)
.commit();
// 初始化背景
Glide.with(this).load(R.drawable.bg_src_tianjin)
.centerCrop()
.into(new ViewTarget<ImageView, GlideDrawable>(mBg) {
@Override
public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
Drawable drawable = resource.getCurrent();
drawable = DrawableCompat.wrap(drawable);
drawable.setColorFilter(getResources().getColor(R.color.colorAccent),
PorterDuff.Mode.SCREEN);
this.view.setImageDrawable(drawable);
}
});
}
/**
* 登陆/注册布局切换
*/
public void triggerView() {
if (mCurrentFragment == mLoginFragment) {
if (mRegisterFragment == null) {
mRegisterFragment = new RegisterFragment();
}
mCurrentFragment = mRegisterFragment;
} else {
mCurrentFragment = mLoginFragment;
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, mCurrentFragment)
.commit();
}
}
| 32.255556 | 127 | 0.65484 |
bdcb777f2379addaae1efb7ac78ddc04550376ac | 1,449 | package quickutils.core.services;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import quickutils.core.QuickUtils;
import quickutils.core.interfaces.OnEventListener;
/**
* Created by cesarferreira on 16/06/14.
*/
public class DownloadImageTask<T> extends AsyncTask<Void, Void, T> {
protected final OnEventListener callback;
private final String mImageURL;
protected Exception e;
protected Bitmap mBitmap;
public DownloadImageTask(String imageURL, OnEventListener callback) {
this.callback = callback;
this.mImageURL = imageURL;
this.e = null;
}
@Override
protected T doInBackground(Void... params) {
QuickUtils.log.i("BACKGROUND");
URL url;
try {
url = new URL(mImageURL);
mBitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e1) {
e = e1;
} catch (IOException e1) {
e = e1;
}
return (T) mBitmap;
}
@Override
protected void onPostExecute(T bitmap) {
if (callback != null) {
if (e == null && bitmap != null) {
callback.onSuccess(bitmap);
} else {
callback.onFailure(e);
}
}
}
} | 23.754098 | 88 | 0.621118 |
8a343a657d37531cf61dd1bf3fb1a2f7f8e965a1 | 4,271 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.jbpm.workbench.forms.display.backend.provider;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import org.jbpm.workbench.forms.service.providing.ProcessRenderingSettings;
import org.kie.workbench.common.forms.dynamic.service.context.generation.dynamic.BackendFormRenderingContext;
import org.kie.workbench.common.forms.dynamic.service.context.generation.dynamic.BackendFormRenderingContextManager;
import org.kie.workbench.common.forms.jbpm.model.authoring.JBPMVariable;
import org.kie.workbench.common.forms.jbpm.model.authoring.process.BusinessProcessFormModel;
import org.kie.workbench.common.forms.jbpm.service.bpmn.DynamicBPMNFormGenerator;
import org.kie.workbench.common.forms.model.FormDefinition;
import org.kie.workbench.common.forms.serialization.FormDefinitionSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Dependent
public class ProcessFormsValuesProcessor extends KieWorkbenchFormsValuesProcessor<ProcessRenderingSettings> {
private static final Logger logger = LoggerFactory.getLogger( ProcessFormsValuesProcessor.class );
@Inject
public ProcessFormsValuesProcessor( FormDefinitionSerializer formSerializer,
BackendFormRenderingContextManager contextManager,
DynamicBPMNFormGenerator dynamicBPMNFormGenerator ) {
super( formSerializer, contextManager, dynamicBPMNFormGenerator );
}
@Override
protected String getFormName( ProcessRenderingSettings settings ) {
return settings.getProcess().getId();
}
@Override
protected Map<String, Object> getOutputValues( Map<String, Object> values,
FormDefinition form,
ProcessRenderingSettings context ) {
if ( isValid( form ) ) {
BusinessProcessFormModel model = (BusinessProcessFormModel) form.getModel();
values.entrySet().stream().allMatch( entry -> model.getVariables().stream().filter( variable -> variable.getName().equals(
entry.getKey() ) ).findFirst().isPresent() );
return values;
}
throw new IllegalArgumentException( "Form not valid to start process" );
}
@Override
protected void prepareContext( ProcessRenderingSettings settings, BackendFormRenderingContext context ) {
// Nothing to do for processes
}
@Override
protected boolean isValid( FormDefinition rootForm ) {
return rootForm != null && rootForm.getModel() instanceof BusinessProcessFormModel;
}
@Override
protected Collection<FormDefinition> generateDefaultFormsForContext( ProcessRenderingSettings settings ) {
List<JBPMVariable> variables = new ArrayList<>();
settings.getProcessData().forEach( ( name, type ) -> {
variables.add( new JBPMVariable( name, type ) );
} );
BusinessProcessFormModel formModel = new BusinessProcessFormModel( settings.getProcess().getId(),
settings.getProcess().getName(),
variables );
return dynamicBPMNFormGenerator.generateProcessForms( formModel,
settings.getMarshallerContext().getClassloader() );
}
@Override
protected Logger getLogger() {
return logger;
}
}
| 43.581633 | 134 | 0.683681 |
2268f96428755d028204a8ed5c2a092699337745 | 12,908 | /*
* Copyright 2008-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.webflow.validation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.binding.expression.ExpressionParser;
import org.springframework.binding.mapping.MappingResults;
import org.springframework.binding.message.MessageContext;
import org.springframework.binding.message.MessageContextErrors;
import org.springframework.binding.validation.ValidationContext;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.SmartValidator;
import org.springframework.validation.Validator;
import org.springframework.webflow.execution.RequestContext;
/**
* A helper class the encapsulates conventions to invoke validation logic.
*
* @author Scott Andrews
* @author Canny Duck
* @author Jeremy Grelle
*/
public class ValidationHelper {
private static final Log logger = LogFactory.getLog(ValidationHelper.class);
private final Object model;
private final RequestContext requestContext;
private final String eventId;
private final String modelName;
private final ExpressionParser expressionParser;
private final MessageCodesResolver messageCodesResolver;
private final MappingResults mappingResults;
private Validator validator;
private Object[] validationHints;
/**
* Create a throwaway validation helper object. Validation is invoked by the {@link #validate()} method.
* <p>
* Validation methods invoked include a validation method on the model object or a validator bean. The method name
* on either object is in the form of validate[viewStateId]. A ValidationContext is passed in the method signature
* along with the model object for validator beans. A MessageContext can be substituted for the ValidationContext.
* <p>
* For example: <code>model.validateEnterBookingDetails(VaticationContext)</code> or
* <code>context.getBean("modelValidator").validateEnterBookingDetails(model, VaticationContext)</code>
*
* @param model the object to validate
* @param requestContext the context for the request
* @param eventId the event triggering validation
* @param modelName the name of the model object
* @param expressionParser the expression parser
* @param mappingResults object mapping results
*/
public ValidationHelper(Object model, RequestContext requestContext, String eventId, String modelName,
ExpressionParser expressionParser, MessageCodesResolver messageCodesResolver, MappingResults mappingResults) {
Assert.notNull(model, "The model to validate is required");
Assert.notNull(requestContext, "The request context for the validator is required");
this.model = model;
this.requestContext = requestContext;
this.eventId = eventId;
this.modelName = modelName;
this.expressionParser = expressionParser;
this.messageCodesResolver = messageCodesResolver;
this.mappingResults = mappingResults;
}
/**
* Configure a {@link Validator} to apply to the model.
*/
public void setValidator(Validator validator) {
this.validator = validator;
}
/**
* Provide validation hints such as validation groups to use against a JSR-303 provider.
*/
public void setValidationHints(Object[] validationHints) {
this.validationHints = validationHints;
}
/**
* Invoke the validators available by convention.
*/
public void validate() {
if (this.validator != null) {
invokeValidatorDefaultValidateMethod(this.validator);
}
invokeModelValidationMethod(model);
Object modelValidator = getModelValidator();
if (modelValidator != null) {
invokeModelValidator(modelValidator);
}
}
private void invokeModelValidationMethod(Object model) {
invokeValidateMethodForCurrentState(model);
invokeDefaultValidateMethod(model);
}
private boolean invokeValidateMethodForCurrentState(Object model) {
String methodName = "validate" + StringUtils.capitalize(requestContext.getCurrentState().getId());
// preferred
Method validateMethod = ReflectionUtils.findMethod(model.getClass(), methodName,
new Class[] { ValidationContext.class });
if (validateMethod != null) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking current state model validation method '" + methodName + "(ValidationContext)'");
}
ReflectionUtils.invokeMethod(validateMethod, model, new Object[] { new DefaultValidationContext(
requestContext, eventId, mappingResults) });
return true;
}
// web flow 2.0.3 or < compatibility only
validateMethod = ReflectionUtils.findMethod(model.getClass(), methodName, new Class[] { MessageContext.class });
if (validateMethod != null) {
ReflectionUtils.invokeMethod(validateMethod, model, new Object[] { requestContext.getMessageContext() });
return true;
}
// mvc 2 compatibility only
validateMethod = ReflectionUtils.findMethod(model.getClass(), methodName, new Class[] { Errors.class });
if (validateMethod != null) {
MessageContextErrors errors = new MessageContextErrors(requestContext.getMessageContext(), modelName,
model, expressionParser, messageCodesResolver, mappingResults);
if (logger.isDebugEnabled()) {
logger.debug("Invoking current state model validation method '" + methodName + "(Errors)'");
}
ReflectionUtils.invokeMethod(validateMethod, model, new Object[] { errors });
return true;
}
return false;
}
private boolean invokeDefaultValidateMethod(Object model) {
// preferred
Method validateMethod = ReflectionUtils.findMethod(model.getClass(), "validate",
new Class[] { ValidationContext.class });
if (validateMethod != null) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking default model validation method 'validate(ValidationContext)'");
}
ReflectionUtils.invokeMethod(validateMethod, model, new Object[] { new DefaultValidationContext(
requestContext, eventId, mappingResults) });
return true;
}
// mvc 2 compatibility only
validateMethod = ReflectionUtils.findMethod(model.getClass(), "validate", new Class[] { Errors.class });
if (validateMethod != null) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking default model validation method 'validate(Errors)'");
}
MessageContextErrors errors = new MessageContextErrors(requestContext.getMessageContext(), modelName,
model, expressionParser, messageCodesResolver, mappingResults);
ReflectionUtils.invokeMethod(validateMethod, model, new Object[] { errors });
return true;
}
return false;
}
private Object getModelValidator() {
BeanFactory beanFactory = requestContext.getActiveFlow().getApplicationContext();
if (beanFactory != null && StringUtils.hasText(modelName)) {
String validatorName = modelName + "Validator";
if (beanFactory.containsBean(validatorName)) {
return beanFactory.getBean(validatorName);
}
}
return null;
}
private void invokeModelValidator(Object validator) {
invokeValidatorValidateMethodForCurrentState(validator);
invokeValidatorDefaultValidateMethod(validator);
}
private boolean invokeValidatorValidateMethodForCurrentState(Object validator) {
String methodName = "validate" + StringUtils.capitalize(requestContext.getCurrentState().getId());
// preferred
Method validateMethod = findValidationMethod(model, validator, methodName, ValidationContext.class);
if (validateMethod != null) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking current state validator method '"
+ ClassUtils.getShortName(validator.getClass()) + "." + methodName + "("
+ ClassUtils.getShortName(model.getClass()) + ", ValidationContext)'");
}
ReflectionUtils.invokeMethod(validateMethod, validator, new Object[] { model,
new DefaultValidationContext(requestContext, eventId, mappingResults) });
return true;
}
// mvc 2 compatibility only
validateMethod = findValidationMethod(model, validator, methodName, Errors.class);
if (validateMethod != null) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking current state validator method '"
+ ClassUtils.getShortName(validator.getClass()) + "." + methodName + "("
+ ClassUtils.getShortName(model.getClass()) + ", Errors)'");
}
MessageContextErrors errors = new MessageContextErrors(requestContext.getMessageContext(), modelName,
model, expressionParser, messageCodesResolver, mappingResults);
ReflectionUtils.invokeMethod(validateMethod, validator, new Object[] { model, errors });
return true;
}
// web flow 2.0.0 to 2.0.3 compatibility only [to remove in web flow 3]
validateMethod = findValidationMethod(model, validator, methodName, MessageContext.class);
if (validateMethod != null) {
ReflectionUtils.invokeMethod(validateMethod, validator,
new Object[] { model, requestContext.getMessageContext() });
return true;
}
return false;
}
private boolean invokeValidatorDefaultValidateMethod(Object validator) {
if (validator instanceof Validator) {
// Spring Framework Validator type
Validator springValidator = (Validator) validator;
if (logger.isDebugEnabled()) {
logger.debug("Invoking Spring Validator '" + ClassUtils.getShortName(validator.getClass()) + "'");
}
if (springValidator.supports(model.getClass())) {
MessageContextErrors errors = new MessageContextErrors(requestContext.getMessageContext(), modelName,
model, expressionParser, messageCodesResolver, mappingResults);
if (this.validationHints != null) {
if (springValidator instanceof SmartValidator) {
((SmartValidator) springValidator).validate(model, errors, this.validationHints);
}
else {
logger.warn("Validation hints provided but validator not an instance of SmartValidator: ["
+ springValidator.getClass().getName() + "]");
}
}
else {
springValidator.validate(model, errors);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Spring Validator '" + ClassUtils.getShortName(validator.getClass())
+ "' doesn't support model class " + model.getClass());
}
}
return true;
}
// preferred
Method validateMethod = findValidationMethod(model, validator, "validate", ValidationContext.class);
if (validateMethod != null) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking default validator method '" + ClassUtils.getShortName(validator.getClass())
+ ".validate(" + ClassUtils.getShortName(model.getClass()) + ", ValidationContext)'");
}
ReflectionUtils.invokeMethod(validateMethod, validator, new Object[] { model,
new DefaultValidationContext(requestContext, eventId, mappingResults) });
return true;
}
// mvc 2 compatibility only
validateMethod = findValidationMethod(model, validator, "validate", Errors.class);
if (validateMethod != null) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking default validator method '" + ClassUtils.getShortName(validator.getClass())
+ ".validate(" + ClassUtils.getShortName(model.getClass()) + ", Errors)'");
}
MessageContextErrors errors = new MessageContextErrors(requestContext.getMessageContext(), modelName,
model, expressionParser, messageCodesResolver, mappingResults);
ReflectionUtils.invokeMethod(validateMethod, validator, new Object[] { model, errors });
return true;
}
return false;
}
private Method findValidationMethod(Object model, Object validator, String methodName, Class<?> context) {
Class<?> modelClass = AopUtils.getTargetClass(model);
List<Class<?>> modelSearchClasses = new ArrayList<Class<?>>();
while (modelClass != null) {
modelSearchClasses.add(modelClass);
modelClass = modelClass.getSuperclass();
}
for (Class<?> searchClass : modelSearchClasses) {
Method method = ReflectionUtils.findMethod(validator.getClass(), methodName, new Class[] { searchClass,
context });
if (method != null) {
return method;
}
}
return null;
}
}
| 39.962848 | 115 | 0.750387 |
3538576cdcf8e9c14268f36e6ac670862688d804 | 3,637 | package me.ANONIMUS.mcprotocol.network.protocol.packet.impl.server.status;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import me.ANONIMUS.mcprotocol.network.protocol.data.PlayerInfo;
import me.ANONIMUS.mcprotocol.network.protocol.data.ServerStatusInfo;
import me.ANONIMUS.mcprotocol.network.protocol.data.VersionInfo;
import me.ANONIMUS.mcprotocol.network.protocol.packet.Packet;
import me.ANONIMUS.mcprotocol.network.protocol.packet.PacketBuffer;
import me.ANONIMUS.mcprotocol.objects.GameProfile;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.chat.ComponentSerializer;
@NoArgsConstructor
@AllArgsConstructor
@Getter
public class ServerStatusResponsePacket extends Packet {
private ServerStatusInfo info;
@Override
public void write(PacketBuffer out, int protocol) {
JsonObject obj = new JsonObject();
JsonObject ver = new JsonObject();
ver.addProperty("name", this.info.getVersionInfo().getVersionName());
ver.addProperty("protocol", this.info.getVersionInfo().getProtocolVersion());
JsonObject plrs = new JsonObject();
plrs.addProperty("max", this.info.getPlayerInfo().getMaxPlayers());
plrs.addProperty("online", this.info.getPlayerInfo().getOnlinePlayers());
if (this.info.getPlayerInfo().getPlayers().length > 0) {
JsonArray array = new JsonArray();
for (GameProfile profile : this.info.getPlayerInfo().getPlayers()) {
JsonObject o = new JsonObject();
o.addProperty("name", profile.getName());
o.addProperty("id", profile.getIdAsString());
array.add(o);
}
plrs.add("sample", array);
}
obj.add("version", ver);
obj.add("players", plrs);
obj.add("description", new Gson().fromJson(ComponentSerializer.toString(this.info.getDescription()), JsonElement.class));
if (this.info.getIcon() != null) {
obj.addProperty("favicon", this.info.getIcon());
}
out.writeString(obj.toString());
}
@Override
public void read(PacketBuffer in, int protocol) {
JsonObject obj = new Gson().fromJson(in.readString(), JsonObject.class);
JsonObject ver = obj.get("version").getAsJsonObject();
VersionInfo version = new VersionInfo(ver.get("name").getAsString(), ver.get("protocol").getAsInt());
JsonObject plrs = obj.get("players").getAsJsonObject();
GameProfile[] profiles = new GameProfile[0];
if (plrs.has("sample")) {
JsonArray prof = plrs.get("sample").getAsJsonArray();
if (prof.size() > 0) {
profiles = new GameProfile[prof.size()];
for (int index = 0; index < prof.size(); index++) {
JsonObject o = prof.get(index).getAsJsonObject();
profiles[index] = new GameProfile(o.get("id").getAsString(), o.get("name").getAsString());
}
}
}
PlayerInfo players = new PlayerInfo(plrs.get("online").getAsInt(), plrs.get("max").getAsInt(), profiles);
JsonElement desc = obj.get("description");
BaseComponent[] description = ComponentSerializer.parse(desc.toString());
String icon = null;
if (obj.has("favicon")) {
icon = obj.get("favicon").getAsString();
}
this.info = new ServerStatusInfo(version, players, description, icon);
}
} | 43.297619 | 129 | 0.654385 |
898a2acd2480d414846b9a99f05f42ddd425290c | 3,959 | package net.teamio.taam.content.piping;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.teamio.taam.piping.IPipe;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Created by oliver on 2017-07-04.
*/
public class GenericPipeTests {
/**
* Used in other test classes to test a pipe end / pipe implementation with a generic test set.
*
* @param pipe
* @param capacity
*/
public static void testPipeEnd(IPipe pipe, int capacity, boolean singularCapacity) {
int amount;
// Insert LAVA
FluidStack stack = new FluidStack(FluidRegistry.LAVA, 5);
amount = pipe.addFluid(stack);
assertEquals(5, pipe.getFluidAmount(new FluidStack(FluidRegistry.LAVA, 0)));
assertEquals(5, amount);
/*
Test: Inserting fluidstack does not modify original fluid stack
+ modifying stack does not change amount in pipe
*/
assertEquals(5, stack.amount);
stack.amount = 0;
amount = pipe.getFluidAmount(stack);
assertEquals(5, amount);
stack.amount = 5;
amount = pipe.addFluid(stack);
assertEquals(5, stack.amount);
assertEquals(10, pipe.getFluidAmount(new FluidStack(FluidRegistry.LAVA, 0)));
assertEquals(5, amount);
amount = pipe.removeFluid(stack);
assertEquals(5, stack.amount);
assertEquals(5, pipe.getFluidAmount(new FluidStack(FluidRegistry.LAVA, 0)));
assertEquals(5, amount);
// Insert WATER
amount = pipe.addFluid(new FluidStack(FluidRegistry.WATER, 5));
if(singularCapacity) {
assertEquals(0, amount);
assertEquals(5, pipe.getFluidAmount(new FluidStack(FluidRegistry.LAVA, 0)));
assertEquals(0, pipe.getFluidAmount(new FluidStack(FluidRegistry.WATER, 0)));
} else {
assertEquals(5, amount);
assertEquals(5, pipe.getFluidAmount(new FluidStack(FluidRegistry.LAVA, 0)));
assertEquals(5, pipe.getFluidAmount(new FluidStack(FluidRegistry.WATER, 0)));
}
// Drain WATER
amount = pipe.removeFluid(new FluidStack(FluidRegistry.WATER, 5));
if(singularCapacity) {
assertEquals(0, amount);
} else {
assertEquals(5, amount);
}
assertEquals(5, pipe.getFluidAmount(new FluidStack(FluidRegistry.LAVA, 0)));
assertEquals(0, pipe.getFluidAmount(new FluidStack(FluidRegistry.WATER, 0)));
// Drain LAVA
amount = pipe.removeFluid(new FluidStack(FluidRegistry.LAVA, 5));
assertEquals(5, amount);
assertEquals(0, pipe.getFluidAmount(new FluidStack(FluidRegistry.LAVA, 0)));
assertEquals(0, pipe.getFluidAmount(new FluidStack(FluidRegistry.WATER, 0)));
assertNotNull(pipe.getFluids());
assertEquals(0, pipe.getFluids().size());
// Drain LAVA more
amount = pipe.removeFluid(new FluidStack(FluidRegistry.LAVA, 5));
assertEquals(0, amount);
assertEquals(0, pipe.getFluidAmount(new FluidStack(FluidRegistry.LAVA, 0)));
assertEquals(0, pipe.getFluidAmount(new FluidStack(FluidRegistry.WATER, 0)));
assertNotNull(pipe.getFluids());
assertEquals(0, pipe.getFluids().size());
// Insert WATER
amount = pipe.addFluid(new FluidStack(FluidRegistry.WATER, 5));
assertEquals(5, amount);
assertEquals(0, pipe.getFluidAmount(new FluidStack(FluidRegistry.LAVA, 0)));
assertEquals(5, pipe.getFluidAmount(new FluidStack(FluidRegistry.WATER, 0)));
// Insert WATER above capacity
amount = pipe.addFluid(new FluidStack(FluidRegistry.WATER, capacity + 50));
assertEquals(capacity - 5, amount);
assertEquals(0, pipe.getFluidAmount(new FluidStack(FluidRegistry.LAVA, 0)));
assertEquals(capacity, pipe.getFluidAmount(new FluidStack(FluidRegistry.WATER, 0)));
// Drain WATER more than inside
amount = pipe.removeFluid(new FluidStack(FluidRegistry.WATER, capacity + 50));
assertEquals(capacity, amount);
assertEquals(0, pipe.getFluidAmount(new FluidStack(FluidRegistry.LAVA, 0)));
assertEquals(0, pipe.getFluidAmount(new FluidStack(FluidRegistry.WATER, 0)));
assertNotNull(pipe.getFluids());
assertEquals(0, pipe.getFluids().size());
}
}
| 34.426087 | 96 | 0.742864 |
b2a3b5649cfa33ec33495637c8802c4dd3ccad1b | 1,670 | /*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ratpack.dropwizard.metrics.internal;
import com.codahale.metrics.MetricRegistry;
import ratpack.dropwizard.metrics.BlockingExecTimingInterceptor;
import ratpack.dropwizard.metrics.DropwizardMetricsConfig;
import javax.inject.Inject;
import javax.inject.Provider;
/**
* Provide a timer for blocking executions.
*
* @since 1.2
*/
public class BlockingExecTimingInterceptorProvider implements Provider<BlockingExecTimingInterceptor> {
private final MetricRegistry metricRegistry;
private final DropwizardMetricsConfig config;
private static final BlockingExecTimingInterceptor NOOP = (execution, execType, executionSegment) -> executionSegment.execute();
@Inject
public BlockingExecTimingInterceptorProvider(MetricRegistry metricRegistry, DropwizardMetricsConfig config) {
this.metricRegistry = metricRegistry;
this.config = config;
}
@Override
public BlockingExecTimingInterceptor get() {
return config.isBlockingTimingMetrics() ? new DefaultBlockingExecTimingInterceptor(metricRegistry, config) : NOOP;
}
}
| 34.081633 | 130 | 0.786826 |
326724b41f46cb283bdc6d5b17d258c0a79c3fc9 | 4,035 | package com.bloomberg.fx.web.rest;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.bloomberg.fx.entity.FileStatus;
import com.bloomberg.fx.entity.FxFile;
import com.bloomberg.fx.entity.FxInvalidFileData;
import com.bloomberg.fx.repository.FxFileRepository;
import com.bloomberg.fx.repository.FxInvalidFileDataRepository;
import com.bloomberg.fx.service.SaveFileService;
@RestController
@RequestMapping("/api/file")
public class FileResource {
private static final Logger logger = LoggerFactory.getLogger(FileResource.class);
@Autowired
SaveFileService saveFileService;
@Autowired
FxFileRepository fxFileRepository;
@Autowired
FxInvalidFileDataRepository fxInvalidFileDataRepository;
/**
* POST /upload : post the file data into the controller.
*
* @param file to get the MultipartFile data from the client
* @return the FileStatus with status 200 (OK)
*/
@PostMapping("/upload")
private @ResponseBody FileStatus uploadFile(@RequestParam(value = "files[]", required = true) MultipartFile file) {
String name = "";
String fileString = null;
StopWatch stopWatch = new StopWatch("My Stop Watch");
stopWatch.start();
if (!file.isEmpty()) {
try {
if(!file.getOriginalFilename().endsWith(".csv")){
stopWatch.stop();
return new FileStatus(stopWatch.getTotalTimeSeconds(), file.getOriginalFilename(),
" File not imported.Please select a csv file");
}
name = FilenameUtils.removeExtension(file.getOriginalFilename());
if (fxFileRepository.existsbyfileName(name)) {
stopWatch.stop();
return new FileStatus(stopWatch.getTotalTimeSeconds(), name,
" Unsuccessfull Import .File already exists");
}
else {
byte[] bytes = file.getBytes();
fileString = new String(bytes, StandardCharsets.UTF_8);
List<String> fileDetailsList = Stream.of(fileString.split("\\r?\\n")).map(elem -> new String(elem))
.collect(Collectors.toList());
saveFileService.saveFileList(fileDetailsList, name);
}
stopWatch.stop();
} catch (Exception e) {
logger.error(e.getMessage());
}
return new FileStatus(stopWatch.getTotalTimeSeconds(), name, "File imported succesfully.");
} else {
return new FileStatus(stopWatch.getTotalTimeSeconds(), name, "File is Empty");
}
}
/**
* GET /search/valid-file-details : get a page of valid file details
*
* @param fileName Name of the file
* @return the FxFile with status 200 (OK) and the list of FxFile in body
*/
@GetMapping("search/valid-file-details/{fileName}")
private @ResponseBody List<FxFile> getValidFileDetails(@PathVariable String fileName) {
return fxFileRepository.findByfileName(fileName);
}
/**
* GET /search/invalid-file-details : get a page of invalid file details
*
* @param fileName Name of the file
* @return the FxInvalidFileData with status 200 (OK) and the list of FxInvalidFileData in body
*/
@GetMapping("search/invalid-file-details/{fileName}")
private @ResponseBody List<FxInvalidFileData> getInValidFileDetails(@PathVariable String fileName) {
return fxInvalidFileDataRepository.findByfileName(fileName);
}
}
| 33.907563 | 116 | 0.748203 |
f1fe3561d1701f1468c5b92a842a3a8b97429a6b | 423 | package com.dynamicallyblunttech.cve.pojo.v1_0;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BaseMetricV3 {
@JsonProperty
private CvssV3 cvssV3 ;
@JsonProperty
private double exploitabilityScore ;
@JsonProperty
private double impactScore ;
}
| 21.15 | 53 | 0.794326 |
b3e2a662fcd3dd6706d59554ad45db5abab8bb49 | 466 | /*
* 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 mage.deck;
import mage.cards.decks.Constructed;
/**
*
* @author LevelX2
*/
public class StarWarsBlock extends Constructed {
public StarWarsBlock() {
super("Constructed Custom - Star Wars Block");
setCodes.add("SWS");
}
}
| 21.181818 | 80 | 0.656652 |
f58bc657049185421a23b0b2baf297a7d4e14c38 | 7,847 | /**
* Autogenerated by Thrift Compiler (0.12.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package io.github.avpinchuk.zipkin.thriftjava;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public class zipkincoreConstants {
/**
* The client sent ("cs") a request to a server. There is only one send per
* span. For example, if there's a transport error, each attempt can be logged
* as a WIRE_SEND annotation.
*
* If chunking is involved, each chunk could be logged as a separate
* CLIENT_SEND_FRAGMENT in the same span.
*
* Annotation.host is not the server. It is the host which logged the send
* event, almost always the client. When logging CLIENT_SEND, instrumentation
* should also log the SERVER_ADDR.
*/
public static final java.lang.String CLIENT_SEND = "cs";
/**
* The client received ("cr") a response from a server. There is only one
* receive per span. For example, if duplicate responses were received, each
* can be logged as a WIRE_RECV annotation.
*
* If chunking is involved, each chunk could be logged as a separate
* CLIENT_RECV_FRAGMENT in the same span.
*
* Annotation.host is not the server. It is the host which logged the receive
* event, almost always the client. The actual endpoint of the server is
* recorded separately as SERVER_ADDR when CLIENT_SEND is logged.
*/
public static final java.lang.String CLIENT_RECV = "cr";
/**
* The server sent ("ss") a response to a client. There is only one response
* per span. If there's a transport error, each attempt can be logged as a
* WIRE_SEND annotation.
*
* Typically, a trace ends with a server send, so the last timestamp of a trace
* is often the timestamp of the root span's server send.
*
* If chunking is involved, each chunk could be logged as a separate
* SERVER_SEND_FRAGMENT in the same span.
*
* Annotation.host is not the client. It is the host which logged the send
* event, almost always the server. The actual endpoint of the client is
* recorded separately as CLIENT_ADDR when SERVER_RECV is logged.
*/
public static final java.lang.String SERVER_SEND = "ss";
/**
* The server received ("sr") a request from a client. There is only one
* request per span. For example, if duplicate responses were received, each
* can be logged as a WIRE_RECV annotation.
*
* Typically, a trace starts with a server receive, so the first timestamp of a
* trace is often the timestamp of the root span's server receive.
*
* If chunking is involved, each chunk could be logged as a separate
* SERVER_RECV_FRAGMENT in the same span.
*
* Annotation.host is not the client. It is the host which logged the receive
* event, almost always the server. When logging SERVER_RECV, instrumentation
* should also log the CLIENT_ADDR.
*/
public static final java.lang.String SERVER_RECV = "sr";
/**
* Message send ("ms") is a request to send a message to a destination, usually
* a broker. This may be the only annotation in a messaging span. If WIRE_SEND
* exists in the same span, it follows this moment and clarifies delays sending
* the message, such as batching.
*
* Unlike RPC annotations like CLIENT_SEND, messaging spans never share a span
* ID. For example, "ms" should always be the parent of "mr".
*
* Annotation.host is not the destination, it is the host which logged the send
* event: the producer. When annotating MESSAGE_SEND, instrumentation should
* also tag the MESSAGE_ADDR.
*/
public static final java.lang.String MESSAGE_SEND = "ms";
/**
* A consumer received ("mr") a message from a broker. This may be the only
* annotation in a messaging span. If WIRE_RECV exists in the same span, it
* precedes this moment and clarifies any local queuing delay.
*
* Unlike RPC annotations like SERVER_RECV, messaging spans never share a span
* ID. For example, "mr" should always be a child of "ms" unless it is a root
* span.
*
* Annotation.host is not the broker, it is the host which logged the receive
* event: the consumer. When annotating MESSAGE_RECV, instrumentation should
* also tag the MESSAGE_ADDR.
*/
public static final java.lang.String MESSAGE_RECV = "mr";
/**
* Optionally logs an attempt to send a message on the wire. Multiple wire send
* events could indicate network retries. A lag between client or server send
* and wire send might indicate queuing or processing delay.
*/
public static final java.lang.String WIRE_SEND = "ws";
/**
* Optionally logs an attempt to receive a message from the wire. Multiple wire
* receive events could indicate network retries. A lag between wire receive
* and client or server receive might indicate queuing or processing delay.
*/
public static final java.lang.String WIRE_RECV = "wr";
/**
* Optionally logs progress of a (CLIENT_SEND, WIRE_SEND). For example, this
* could be one chunk in a chunked request.
*/
public static final java.lang.String CLIENT_SEND_FRAGMENT = "csf";
/**
* Optionally logs progress of a (CLIENT_RECV, WIRE_RECV). For example, this
* could be one chunk in a chunked response.
*/
public static final java.lang.String CLIENT_RECV_FRAGMENT = "crf";
/**
* Optionally logs progress of a (SERVER_SEND, WIRE_SEND). For example, this
* could be one chunk in a chunked response.
*/
public static final java.lang.String SERVER_SEND_FRAGMENT = "ssf";
/**
* Optionally logs progress of a (SERVER_RECV, WIRE_RECV). For example, this
* could be one chunk in a chunked request.
*/
public static final java.lang.String SERVER_RECV_FRAGMENT = "srf";
/**
* The value of "lc" is the component or namespace of a local span.
*
* BinaryAnnotation.host adds service context needed to support queries.
*
* Local Component("lc") supports three key features: flagging, query by
* service and filtering Span.name by namespace.
*
* While structurally the same, local spans are fundamentally different than
* RPC spans in how they should be interpreted. For example, zipkin v1 tools
* center on RPC latency and service graphs. Root local-spans are neither
* indicative of critical path RPC latency, nor have impact on the shape of a
* service graph. By flagging with "lc", tools can special-case local spans.
*
* Zipkin v1 Spans are unqueryable unless they can be indexed by service name.
* The only path to a service name is by (Binary)?Annotation.host.serviceName.
* By logging "lc", a local span can be queried even if no other annotations
* are logged.
*
* The value of "lc" is the namespace of Span.name. For example, it might be
* "finatra2", for a span named "bootstrap". "lc" allows you to resolves
* conflicts for the same Span.name, for example "finatra/bootstrap" vs
* "finch/bootstrap". Using local component, you'd search for spans named
* "bootstrap" where "lc=finch"
*/
public static final java.lang.String LOCAL_COMPONENT = "lc";
/**
* Indicates a client address ("ca") in a span. Most likely, there's only one.
* Multiple addresses are possible when a client changes its ip or port within
* a span.
*/
public static final java.lang.String CLIENT_ADDR = "ca";
/**
* Indicates a server address ("sa") in a span. Most likely, there's only one.
* Multiple addresses are possible when a client is redirected, or fails to a
* different server ip or port.
*/
public static final java.lang.String SERVER_ADDR = "sa";
/**
* Indicates the remote address of a messaging span, usually the broker.
*/
public static final java.lang.String MESSAGE_ADDR = "ma";
}
| 41.518519 | 81 | 0.708424 |
2a5bfb8b12c5de07e946882afbd0e8faad6a5e39 | 1,545 | /**
* Copyright 2016 Toni Kocjan
*
* 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 compiler.ast.tree.expr;
import java.util.*;
import compiler.*;
import compiler.ast.*;
public class AstFunctionCallExpression extends AstExpression {
public final String name;
public final List<AstLabeledExpr> arguments;
public AstFunctionCallExpression(Position pos, String name, List<AstLabeledExpr> args) {
super(pos);
this.name = name;
this.arguments = args;
}
public AstExpression getArgumentAtIndex(int index) {
return arguments.get(index);
}
public int getArgumentCount() {
return arguments.size();
}
public void addArgument(AstLabeledExpr arg) {
arguments.add(0, arg);
}
public String getStringRepresentation() {
StringBuilder sb = new StringBuilder(name);
sb.append('(');
for (AstLabeledExpr arg: arguments) {
sb.append(arg.label);
sb.append(':');
}
sb.append(')');
return sb.toString();
}
@Override public void accept(ASTVisitor aSTVisitor) { aSTVisitor.visit(this); }
} | 24.919355 | 89 | 0.724919 |
2e08a45e1750d9c58e9d0db6d8cdb0b8db34c8d4 | 2,343 | /*
* * Copyright 2020 github.com/ReflxctionDev
*
* 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 io.github.spleefx.arena.bow;
import io.github.spleefx.arena.ArenaPlayer;
import io.github.spleefx.arena.api.BaseArenaEngine;
import io.github.spleefx.extension.ability.GameAbility;
import io.github.spleefx.team.GameTeam;
import org.bukkit.entity.Player;
import java.util.Map;
import java.util.function.Supplier;
import static io.github.spleefx.extension.standard.bowspleef.BowSpleefExtension.EXTENSION;
/**
* A customized engine for bow spleef to add custom abilities
*/
public class BowSpleefEngine extends BaseArenaEngine<BowSpleefArena> {
public static final String ARROW_METADATA = "spleefx.bowspleef.projectile";
/**
* Creates an engine for the specified arena
*
* @param arena Arena to create for
*/
public BowSpleefEngine(BowSpleefArena arena) {
super(arena);
}
/**
* Joins the player to the arena
*
* @param p Player to join
*/
@Override
public boolean join(ArenaPlayer p, GameTeam team) {
if (super.join(p, team)) {
abilityCount.get(p.getPlayer().getUniqueId()).put(GameAbility.TRIPLE_ARROWS, EXTENSION.getTripleArrows().getDefaultAmount());
return true;
}
return false;
}
/**
* Returns the scoreboard placeholders map
*
* @param player Player to retrieve necessary information from
* @return The placeholders map
*/
@Override public Map<String, Supplier<String>> getScoreboardMap(Player player) {
Map<String, Supplier<String>> map = super.getScoreboardMap(player);
map.put("{triple_arrows}", () -> Integer.toString(abilityCount.get(player.getUniqueId()).getOrDefault(GameAbility.TRIPLE_ARROWS, 0)));
return map;
}
}
| 33 | 142 | 0.705506 |
54456fb6f43e12e3e1a207aa9b5b2365b53f25ff | 445 | package com.napier.sem;
/**
* Representation of a City
*/
public class City {
/**
* City ID Number
*/
public int city_no;
/**
* Name of City
*/
public String name;
/**
* 3 Character Identification Code from country
*/
public String country;
/**
* City's district
*/
public String district;
/**
* Population of the City
*/
public int population;
}
| 13.484848 | 51 | 0.534831 |
313ae6049640ce8628f3bf58254d7ca94233be5f | 237 | package c99;
public interface ISourceRange
{
public String getFileName ();
public int getLine1 ();
public int getCol1 ();
public String getFileName2 ();
/** Inclusive */
public int getLine2 ();
/** Exclusive */
public int getCol2 ();
}
| 16.928571 | 30 | 0.708861 |
868f2c292f4c2b9fc30b0378627c3303a939f73a | 553 | package org.bakasoft.framboyan.expect;
import org.bakasoft.framboyan.test.TestCase;
public class Expect_toEndWith extends TestCase {{
pass("String should end with prefix", () -> {
expect("image.jpg").toEndWith(".jpg");
});
pass("String should not end with prefix", () -> {
expect("image.jpg").not.toEndWith(".png");
});
fail("Unexpected match", ExpectError.class, () -> {
expect("image.gif").not.toEndWith(".gif");
});
fail("Unexpected mismatch", ExpectError.class, () -> {
expect("image.gif").toEndWith(".jpg");
});
}} | 30.722222 | 56 | 0.64557 |
7b8f7b9ae5d6110a8fff93a5e3cfa8ce359f9449 | 4,477 | package jp.ac.titech.cs.se.reqchecker.analyzer;
import java.util.ArrayList;
import java.util.List;
import jp.ac.titech.cs.se.reqchecker.cabocha.Phrase;
import jp.ac.titech.cs.se.reqchecker.cabocha.Sentence;
import jp.ac.titech.cs.se.reqchecker.cabocha.Word;
import jp.ac.titech.cs.se.reqchecker.model.Definition;
import jp.ac.titech.cs.se.reqchecker.util.Utils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DefinitionExtractor {
protected List<Definition> definitions = new ArrayList<>();
protected final Sentence sentence;
public DefinitionExtractor(final Sentence sentence) {
this.sentence = sentence;
}
public List<Definition> extractDefinitions() {
search_TOHA_DEARU();
search_TOHA_WOSASU();
search_HA_TOSURU();
search_GA_DEARU();
return definitions;
}
private void search_GA_DEARU() {
Phrase definingInstance = null;
for (final Phrase phrase : sentence.getPhrases()) {
if (definingInstance != null) {
if (phrase.contains(Word.DE_AUXILIARY) && phrase.contains(Word.ARU)) {
final Definition d = new Definition(sentence, definingInstance, phrase);
log.trace("Definition found: {}", d);
definitions.add(d);
definingInstance = null;
}
} else if (phrase.contains(Word.GA) || phrase.contains(Word.HA) && !phrase.contains(Word.TO_CASE)) {
definingInstance = phrase;
}
}
}
private void search_TOHA_WOSASU() {
Phrase definingInstance = null;
for (final Phrase phrase : sentence.getPhrases()) {
if (definingInstance != null) {
if (phrase.contains(Word.WO) && phrase.getForwardPhrase().contains(Word.SASU)) {
final Definition d = new Definition(sentence, definingInstance, phrase);
log.trace("Definition found: {}", d);
definitions.add(d);
definingInstance = null;
}
} else if (phrase.contains(Word.TO_CASE) && phrase.contains(Word.HA)) {
definingInstance = phrase;
}
}
}
private void search_TOHA_DEARU() {
Phrase definingInstance = null;
for (final Phrase phrase : sentence.getPhrases()) {
if (definingInstance != null) {
if (phrase.contains(Word.DE_AUXILIARY) && phrase.contains(Word.ARU)) {
final Definition d = new Definition(sentence, definingInstance, phrase);
log.trace("Definition found: {}", d);
definitions.add(d);
definingInstance = null;
}
} else if (phrase.contains(Word.TO_CASE) && phrase.contains(Word.HA)) {
definingInstance = phrase;
}
}
}
private void search_HA_TOSURU() {
// A は B とする
// A は B と呼ぶ
Phrase description = null;
for (final Phrase phrase : sentence.getPhrases()) {
if (description != null) {
final Phrase forward = phrase.getForwardPhrase();
if (forward == null) {
break;
}
if (isTO_kaku(phrase.getLast())) {
final String verb = forward.getCriticalWord();
log.trace(verb);
if (verb.equals("する") || verb.equals("呼ぶ")) {
final Definition d = new Definition(sentence, phrase, description);
log.trace("Definition found: {}", d);
definitions.add(d);
description = null;
}
}
} else if (phrase.contains(Word.HA)) {
description = phrase;
}
}
}
private Phrase findModifier(final Phrase subject) {
final List<Phrase> backwards = subject.getBackwardPhrases();
if (!backwards.isEmpty()) {
final Phrase m = Utils.last(backwards);
if (m.getLast().isPosOf("助動詞")) {
return m;
}
}
return null;
}
/**
* Checks whether the given word is Binding particle "と".
*/
private boolean isTO_kaku(final Word w) {
return w.getOriginal().equals("と") && w.isPosOf("助詞") && w.isDetailedPosOf("格助詞");
}
}
| 36.104839 | 112 | 0.547018 |
e3d29d007d4decd11431fe28a75041ec10302d34 | 4,087 | /**
*/
package ca.mcgill.cs.sel.ram;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Instantiation</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link ca.mcgill.cs.sel.ram.Instantiation#getMappings <em>Mappings</em>}</li>
* <li>{@link ca.mcgill.cs.sel.ram.Instantiation#getExternalAspect <em>External Aspect</em>}</li>
* <li>{@link ca.mcgill.cs.sel.ram.Instantiation#getType <em>Type</em>}</li>
* </ul>
* </p>
*
* @see ca.mcgill.cs.sel.ram.RamPackage#getInstantiation()
* @model annotation="http://www.eclipse.org/emf/2002/Ecore constraints='aspectCannotMapSelf mandatoryAspectParametersMapped'"
* annotation="http://www.eclipse.org/emf/2002/Ecore/OCL/Pivot aspectCannotMapSelf='not (self.externalAspect = self.Aspect)' aspectCannotMapSelf$message='\'Aspect may not depend on itself\'' mandatoryAspectParametersMapped='if self.type = InstantiationType::Depends then self.externalAspect.mandatoryAspectParameters->forAll(element : MappableElement | self.mappings->exists(fromElement = element)) else true endif' mandatoryAspectParametersMapped$message='\'Partial elements from lower-level aspects have to be mapped\''"
* @generated
*/
public interface Instantiation extends EObject {
/**
* Returns the value of the '<em><b>Mappings</b></em>' containment reference list.
* The list contents are of type {@link ca.mcgill.cs.sel.ram.ClassifierMapping}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Mappings</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Mappings</em>' containment reference list.
* @see ca.mcgill.cs.sel.ram.RamPackage#getInstantiation_Mappings()
* @model containment="true"
* @generated
*/
EList<ClassifierMapping> getMappings();
/**
* Returns the value of the '<em><b>External Aspect</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>External Aspect</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>External Aspect</em>' reference.
* @see #setExternalAspect(Aspect)
* @see ca.mcgill.cs.sel.ram.RamPackage#getInstantiation_ExternalAspect()
* @model required="true"
* @generated
*/
Aspect getExternalAspect();
/**
* Sets the value of the '{@link ca.mcgill.cs.sel.ram.Instantiation#getExternalAspect <em>External Aspect</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>External Aspect</em>' reference.
* @see #getExternalAspect()
* @generated
*/
void setExternalAspect(Aspect value);
/**
* Returns the value of the '<em><b>Type</b></em>' attribute.
* The default value is <code>"Depends"</code>.
* The literals are from the enumeration {@link ca.mcgill.cs.sel.ram.InstantiationType}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Type</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Type</em>' attribute.
* @see ca.mcgill.cs.sel.ram.InstantiationType
* @see #setType(InstantiationType)
* @see ca.mcgill.cs.sel.ram.RamPackage#getInstantiation_Type()
* @model default="Depends" required="true"
* @generated
*/
InstantiationType getType();
/**
* Sets the value of the '{@link ca.mcgill.cs.sel.ram.Instantiation#getType <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Type</em>' attribute.
* @see ca.mcgill.cs.sel.ram.InstantiationType
* @see #getType()
* @generated
*/
void setType(InstantiationType value);
} // Instantiation
| 40.068627 | 529 | 0.661855 |
c2870c24a481b85a4c432c9ff0d472700cc50ed4 | 1,945 | /*-
* <<
* DBus
* ==
* Copyright (C) 2016 - 2017 Bridata
* ==
* 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.creditease.dbus.heartbeat.util;
public class Constants {
private Constants() {
}
public static final String SYS_PROPS_LOG_TYPE = "log.type";
public static final String SYS_PROPS_LOG4J_CONFIG = "log4j.configuration";
public static final String SYS_PROPS_LOG_BASE_PATH = "logs.base.path";
public static final String SYS_PROPS_LOG_HOME = "logs.home";
public static final String CONFIG_DB_KEY = "dbus.conf";
public static final String CONFIG_DB_TYPE_ORA = "oracle";
public static final String CONFIG_DB_TYPE_MYSQL = "mysql";
public static final String CONFIG_KAFKA_CONTROL_PAYLOAD_SCHEMA_KEY = "schema";
public static final String CONFIG_KAFKA_CONTROL_PAYLOAD_DB_KEY = "DB";
public static final String DB_DRIVER_CLASS_ORA = "oracle.jdbc.driver.OracleDriver";
public static final String DB_DRIVER_CLASS_MYSQL = "com.mysql.jdbc.Driver";
public static final String GLOBAL_CTRL_TOPIC = "global_ctrl_topic";
/** 心跳邮件报警内容 */
public static final String MAIL_HEART_BEAT = "尊敬的先生/女士您好,Dbus心跳监控发现数据线路:{0}发生异常,报警次数:{1},超时次数:{2},请及时处理.";
/** 全量邮件报警内容 */
public static final String MAIL_FULL_PULLER = "尊敬的先生/女士您好,Dbus全量拉取监控发现拉取表:{0}数据时发生异常,报警次数:{1},超时次数:{2},请及时处理.";
}
| 33.534483 | 116 | 0.706941 |
0e703302ce91db7bcf94d70dbaf89ed907d98295 | 2,051 | package matrices.dosk48;
import java.util.Random;
public class Juego2048 {
private int[][] tablero;
public Juego2048() {
tablero = new int[4][4];
inicializar();
System.out.println(this);
moverDerecha();
}
public void inicializar() {
Random r = new Random();
int coordenadax = Math.abs(r.nextInt() % tablero.length);
int coordenaday = Math.abs(r.nextInt() % tablero[0].length);
int coordenadax2;
int coordenaday2;
tablero[coordenadax][coordenaday] = 2;
do {
coordenadax2 = Math.abs(r.nextInt() % tablero.length);
coordenaday2 = Math.abs(r.nextInt() % tablero[0].length);
tablero[coordenadax2][coordenaday2] = 2;
} while (coordenadax == coordenadax2 && coordenaday == coordenaday2);
}
public void moverDerecha() {
System.out.println("Empiezan los movimientos");
boolean haSidoModificado = true;
while (haSidoModificado) {
for (int i = 0; i < tablero.length; i++) {
for (int j = tablero[0].length - 1/* 2 */; j > 0; j--) {
if (tablero[i][j] == 0) { // POSICION=0
tablero[i][j] = tablero[i][j - 1] + tablero[i][j];
System.out.println("Se ha encontrado un cero, i y j valen " + i + " " + j);
} // POSICIONES IGUALES (SUMAR)
else if (tablero[i][j] == tablero[i][j - 1]) {
tablero[i][j] = tablero[i][j] + tablero[i][j - 1];
System.out.println("Se han encontrado dos posiciones iguales, i y j valen " + i + " " + j);
} else if (tablero[i][j] != 0 && tablero[i][j] != tablero[i][j - 1]) { // POSICION!=0
System.out.println("CONDICION NUEVA (i,j) " + i + " " + j);
} else if (tablero[i][j - 1] != 0 && tablero[i][j] != tablero[i][j - 1])
haSidoModificado = false;
tablero[i][j - 1] = 0;
}
}
System.out.println(this);
}
}
@Override
public String toString() {
String resultado = "";
for (int[] element : tablero) {
for (int j = 0; j < element.length; j++) {
resultado += element[j] + " ";
}
resultado += "\n";
}
return resultado;
}
} | 30.61194 | 98 | 0.575817 |
e4a286ebbbdba2b7846af3d71d6625d23d2ab119 | 246 | package com.academic.academeet.domain.repository;
import com.academic.academeet.domain.model.Schedule;
import org.springframework.data.jpa.repository.JpaRepository;
public interface IScheduleRepository extends JpaRepository<Schedule, Long> {
}
| 30.75 | 76 | 0.845528 |
106cd4c81dbd8c40aa4a9b2532fc4624c5bbc700 | 276 | package com.itlijunjie.openci.dao;
import com.itlijunjie.openci.vo.User;
public interface IUserDao extends IPageBaseDAO {
/**
* 根据用户名获取用户对象
*
* @param username 用户名
* @return 返回用户对象
*/
User loadByUsername(String username);
}
| 17.25 | 49 | 0.626812 |
f088905341971e39d9a3e8f035536a3b9b1c734b | 1,646 | package msk.node.pre.spec.mzLimit;
import org.knime.core.node.defaultnodesettings.DefaultNodeSettingsPane;
import org.knime.core.node.defaultnodesettings.DialogComponent;
import org.knime.core.node.defaultnodesettings.DialogComponentNumberEdit;
import msk.util.SettingsModelCreate;
/**
* <code>NodeDialog</code> for the "LimitMColumnMZ" Node. This node is used for
* limitting the m/z values, it takes in imzML datasets and then outputs the
* same tables but strictly within the range of the m/z specified by the user.
*
* This node dialog derives from {@link DefaultNodeSettingsPane} which allows
* creation of a simple dialog with standard components. If you need a more
* complex dialog please derive directly from
* {@link org.knime.core.node.NodeDialogPane}.
*
* @author Andrew P Talbot
*/
public class LimitMZNodeDialog extends DefaultNodeSettingsPane {
// Groups for the display on the dialog
private final String GROUP_1 = "Limits on m/z";
// Displays on the Dialog
private final String D_MZ_MIN = "Minimum:";
private final String D_MZ_MAX = "Maximum:";
private DialogComponent minMZDouble = new DialogComponentNumberEdit(
SettingsModelCreate.createSettingsModelDouble(LimitMZNodeModel.DOUBLE_MIN_ID, -1), D_MZ_MIN);
private DialogComponent maxMZDouble = new DialogComponentNumberEdit(
SettingsModelCreate.createSettingsModelDouble(LimitMZNodeModel.DOUBLE_MAX_ID, -1), D_MZ_MAX);
/**
* New pane for configuring the LimitMColumnMZ node.
*/
protected LimitMZNodeDialog() {
createNewGroup(GROUP_1);
addDialogComponent(minMZDouble);
addDialogComponent(maxMZDouble);
closeCurrentGroup();
}
}
| 35.782609 | 96 | 0.786148 |
11b390da335a0ecc5d180bc2fba6cb812e6ade37 | 4,737 | /*
* Copyright 2015 The Energy Detective. All Rights Reserved.
*/
package com.ted.commander.client.view.billing;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.CalendarUtil;
import com.petecode.common.client.model.DateRange;
import com.ted.commander.client.callback.DefaultMethodCallback;
import com.ted.commander.client.clientFactory.ClientFactory;
import com.ted.commander.client.events.PlaceRequestEvent;
import com.ted.commander.client.places.BillingPlace;
import com.ted.commander.client.restInterface.RESTFactory;
import com.ted.commander.common.enums.DataExportFileType;
import com.ted.commander.common.enums.HistoryType;
import com.ted.commander.common.model.AccountLocation;
import com.ted.commander.common.model.CalendarKey;
import com.ted.commander.common.model.export.BillingRequest;
import com.ted.commander.common.model.export.ExportResponse;
import org.fusesource.restygwt.client.Method;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
public class BillingPresenter implements BillingView.Presenter, IsWidget {
static final Logger LOGGER = Logger.getLogger(BillingPresenter.class.getName());
final ClientFactory clientFactory;
BillingView view;
final BillingPlace place;
public BillingPresenter(final ClientFactory clientFactory, BillingPlace place) {
LOGGER.fine("CREATING NEW DashboardPresenter ");
this.clientFactory = clientFactory;
this.place = place;
view = clientFactory.getBillingView();
view.setPresenter(this);
view.setLogo(clientFactory.getInstance().getLogo().getHeaderLogo());
view.getDataExportFileType().setValue(DataExportFileType.CSV);
view.getHistoryType().setValue(HistoryType.BILLING_CYCLE);
Date endDate = new Date();
CalendarUtil.addDaysToDate(endDate, 1);
CalendarUtil.resetTime(endDate);
Date startDate = new Date(endDate.getTime());
CalendarUtil.addDaysToDate(startDate, -7);
CalendarUtil.resetTime(startDate);
DateRange dateRange = new DateRange(startDate, endDate);
view.getDateRangeField().setValue(dateRange);
RESTFactory.getVirtualECCService(clientFactory).getForAllAccounts(new DefaultMethodCallback<List<AccountLocation>>() {
@Override
public void onSuccess(Method method, List<AccountLocation> accountLocationList) {
view.setLocationList(accountLocationList);
}
});
}
@Override
public boolean isValid() {
boolean valid = true;
LOGGER.fine("EXPORT: " + valid);
return valid;
}
@Override
public Widget asWidget() {
return view.asWidget();
}
@Override
public void goTo(Place destinationPage) {
clientFactory.getEventBus().fireEvent(new PlaceRequestEvent(destinationPage, place, null));
}
@Override
public void onResize() {
}
@Override
public void doExport() {
if (isValid()) {
//Set up the base parameters
BillingRequest dataExportRequest = new BillingRequest();
dataExportRequest.setStartDate(new CalendarKey(view.getDateRangeField().getValue().getStartDate()));
if (view.getDateRangeField().getValue().getEndDate() != null) {
dataExportRequest.setEndDate(new CalendarKey(view.getDateRangeField().getValue().getEndDate()));
} else {
dataExportRequest.setEndDate(new CalendarKey(view.getDateRangeField().getValue().getStartDate()));
}
dataExportRequest.setHistoryType(view.getHistoryType().getValue());
dataExportRequest.setDataExportFileType(view.getDataExportFileType().getValue());
List<AccountLocation> accountLocationsForExport = view.getLocationsForExport();
for (int i=0; i < accountLocationsForExport.size(); i++){
dataExportRequest.getVirtualECCIdList().add(accountLocationsForExport.get(i).getVirtualECC().getId());
}
view.setLoadingVisible(true);
LOGGER.fine("Performing Export " + dataExportRequest);
RESTFactory.getExportClient(clientFactory).getBllingStatus(dataExportRequest, dataExportRequest.getDataExportFileType(), new DefaultMethodCallback<ExportResponse>() {
@Override
public void onSuccess(Method method, ExportResponse exportResponse) {
view.setLoadingVisible(false);
view.setDownloadUrl(exportResponse.getUrl());
}
});
}
}
}
| 37.595238 | 178 | 0.698754 |
85f8865c103bd46eb56f8828eec6ba686a6e08f5 | 248 | package ie.gmit.sw;
/**
* @author Tomas Omalley
* @version 1.0
* @since 1.8
*
* public class Gama takes in a byte B and returns state as an integer
*/
public class Gamma {
public byte gamma(byte b) {
return (byte) (Integer.reverse(b));
}
} | 15.5 | 70 | 0.66129 |
584713da3ccc30d166f503a25cfc89af22afbe6d | 6,001 | package it.unibz.inf.ontop.model.term.functionsymbol.db.impl;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import it.unibz.inf.ontop.exception.MinorOntopInternalBugException;
import it.unibz.inf.ontop.iq.node.VariableNullability;
import it.unibz.inf.ontop.model.term.*;
import it.unibz.inf.ontop.model.term.functionsymbol.db.DBFunctionSymbolSerializer;
import it.unibz.inf.ontop.model.type.DBTermType;
import it.unibz.inf.ontop.utils.ImmutableCollectors;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class NullIfDBFunctionSymbolImpl extends AbstractArgDependentTypedDBFunctionSymbol {
protected static final String NULLIF_STR = "NULLIF";
private final DBFunctionSymbolSerializer serializer;
protected NullIfDBFunctionSymbolImpl(String name, DBTermType rootDBTermType, DBFunctionSymbolSerializer serializer) {
super(name, ImmutableList.of(rootDBTermType, rootDBTermType));
this.serializer = serializer;
}
protected NullIfDBFunctionSymbolImpl(DBTermType rootDBTermType) {
this(NULLIF_STR, rootDBTermType, Serializers.getRegularSerializer(NULLIF_STR));
}
@Override
protected Stream<? extends ImmutableTerm> extractPossibleValues(ImmutableList<? extends ImmutableTerm> terms) {
return Stream.of(terms.get(0));
}
@Override
public boolean isPreferringToBePostProcessedOverBeingBlocked() {
return false;
}
@Override
public String getNativeDBString(
ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter,
TermFactory termFactory) {
return serializer.getNativeDBString(terms, termConverter, termFactory);
}
@Override
protected boolean tolerateNulls() {
return true;
}
@Override
protected boolean mayReturnNullWithoutNullArguments() {
return true;
}
@Override
public boolean isAlwaysInjectiveInTheAbsenceOfNonInjectiveFunctionalTerms() {
return false;
}
/**
* Currently cannot be post-processed as we are not sure which kind of equality is considered by the DB engine
* TODO: experiment
*/
@Override
public boolean canBePostProcessed(ImmutableList<? extends ImmutableTerm> arguments) {
return false;
}
@Override
protected ImmutableTerm buildTermAfterEvaluation(ImmutableList<ImmutableTerm> newTerms, TermFactory termFactory,
VariableNullability variableNullability) {
ImmutableTerm term1 = newTerms.get(0);
ImmutableTerm term2 = newTerms.get(1);
if (term1.isNull() || term2.isNull())
return term1;
// As the equality is probably non-strict (TODO: CHECK for most DBs), we only optimize the case of obvious equality
if (term1.equals(term2))
return termFactory.getNullConstant();
return termFactory.getImmutableFunctionalTerm(this, newTerms);
}
@Override
public IncrementalEvaluation evaluateIsNotNull(ImmutableList<? extends ImmutableTerm> terms, TermFactory termFactory,
VariableNullability variableNullability) {
Map.Entry<ImmutableTerm, Stream<ImmutableTerm>> decomposition = decomposeNullIfHierarchy(terms);
ImmutableTerm firstTerm = decomposition.getKey();
Stream<ImmutableTerm> secondTerms = decomposition.getValue();
ImmutableExpression conjunction = termFactory.getConjunction(
Stream.concat(
Stream.of(termFactory.getDBIsNotNull(firstTerm)),
secondTerms
.map(term2 -> termFactory.getDisjunction(
termFactory.getDBIsNull(term2),
termFactory.getDBNot(termFactory.getDBNonStrictDefaultEquality(firstTerm, term2))))))
.orElseThrow(() -> new MinorOntopInternalBugException("Was expecting to have at least one second term"));
return conjunction.evaluate(variableNullability, true);
}
/**
* Decomposes hierarchies like NULLIF(NULLIF(x,1),0) into pairs like (x, [0,1])
*/
protected Map.Entry<ImmutableTerm, Stream<ImmutableTerm>> decomposeNullIfHierarchy(
ImmutableList<? extends ImmutableTerm> terms) {
ImmutableTerm term1 = terms.get(0);
ImmutableTerm term2 = terms.get(1);
if ((term1 instanceof ImmutableFunctionalTerm) &&
((ImmutableFunctionalTerm) term1).getFunctionSymbol() instanceof NullIfDBFunctionSymbolImpl) {
// Recursive
Map.Entry<ImmutableTerm, Stream<ImmutableTerm>> subDecomposition =
decomposeNullIfHierarchy(((ImmutableFunctionalTerm) term1).getTerms());
return Maps.immutableEntry(subDecomposition.getKey(), Stream.concat(Stream.of(term2), subDecomposition.getValue()));
}
else
return Maps.immutableEntry(term1, Stream.of(term2));
}
/**
* If guaranteed to be non-null, only considers the first term.
*/
@Override
public FunctionalTermSimplification simplifyAsGuaranteedToBeNonNull(ImmutableList<? extends ImmutableTerm> terms,
TermFactory termFactory) {
ImmutableTerm firstTerm = terms.get(0);
if (firstTerm instanceof Variable)
return FunctionalTermSimplification.create(firstTerm, ImmutableSet.of((Variable)firstTerm));
else if (firstTerm instanceof ImmutableFunctionalTerm)
return ((ImmutableFunctionalTerm) firstTerm).simplifyAsGuaranteedToBeNonNull();
else
return FunctionalTermSimplification.create(firstTerm, ImmutableSet.of());
}
}
| 41.673611 | 128 | 0.686886 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.